-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtranslation_chain.py
More file actions
44 lines (35 loc) · 1.86 KB
/
Copy pathtranslation_chain.py
File metadata and controls
44 lines (35 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from utils import LOG
from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate
class TranslationChain:
def __init__(self, model_name: str = "gpt-3.5-turbo", verbose: bool = True):
# 翻译任务指令始终由 System 角色承担
template = (
"""You are a translation expert, proficient in various languages. \n
Translates {source_language} to {target_language}.{style_template}"""
)
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
# 待翻译文本由 Human 角色输入
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 使用 System 和 Human 角色的提示模板构造 ChatPromptTemplate
chat_prompt_template = ChatPromptTemplate.from_messages(
[system_message_prompt, human_message_prompt]
)
# 为了翻译结果的稳定性,将 temperature 设置为 0
chat = ChatOpenAI(model_name=model_name, base_url= os.getenv("OPENAI_BASE_URL"),api_key=os.getenv("OPENAI_API_KEY"),temperature=0, verbose=verbose)
self.chain = LLMChain(llm=chat, prompt=chat_prompt_template, verbose=verbose)
def run(self, text: str, source_language: str, target_language: str, style_template: str) -> (str, bool):
result = ""
try:
result = self.chain.run({
"text": text,
"source_language": source_language,
"target_language": target_language,
"style_template": style_template,
})
except Exception as e:
LOG.error(f"An error occurred during translation: {e}")
return result, False
return result, True