3.LangGraph实现翻译工作流
LangGraph手册:https://langchain-ai.github.io/langgraph/ (opens new window)
# 3.1 环境准备
pip install openai langgraph Agently==3.3.4.5 mermaid-python nest_asyncio
pip install langchain
pip install langchain-openai
pip install langchain-community
1
2
3
4
2
3
4
# 3.2 完整实现代码
import json
import openai
from langgraph.graph import StateGraph, START, END
from openai import OpenAI
import os
# 模型请求准备
client = OpenAI()
def get_completion(
prompt: str,
system_message: str = "You are a helpful assistant.",
model: str = "gpt-4o",
temperature: float = 0.3,
json_mode: bool = False,
):
response = client.chat.completions.create(
model=model,
temperature=temperature,
top_p=1,
messages=[
{"role": "system", "content": system_message},
{"role": "user", "content": prompt},
],
)
return response.choices[0].message.content
# 定义传递的信息结构
from typing import TypedDict, Optional
class State(TypedDict):
source_lang: str
target_lang: str
source_text: str
country: Optional[str] = None
translation_1: Optional[str] = None
reflection: Optional[str] = None
translation_2: Optional[str] = None
# 创建一个工作流对象
workflow = StateGraph(State)
# 定义三个工作块
"""
获取state中的信息:state.get("key_name")
更新state中的信息:return { "key_name": new_value }
"""
def initial_translation(state):
source_lang = state.get("source_lang")
target_lang = state.get("target_lang")
source_text = state.get("source_text")
system_message = f"You are an expert linguist, specializing in translation from {source_lang} to {target_lang}."
prompt = f"""This is an {source_lang} to {target_lang} translation, please provide the {target_lang} translation for this text. \
Do not provide any explanations or text apart from the translation.
{source_lang}: {source_text}
{target_lang}:"""
translation = get_completion(prompt, system_message=system_message)
print("[初次翻译结果]: \n", translation)
return {"translation_1": translation}
def reflect_on_translation(state):
source_lang = state.get("source_lang")
target_lang = state.get("target_lang")
source_text = state.get("source_text")
country = state.get("country") or ""
translation_1 = state.get("translation_1")
system_message = f"You are an expert linguist specializing in translation from {source_lang} to {target_lang}. \
You will be provided with a source text and its translation and your goal is to improve the translation."
additional_rule = (
f"The final style and tone of the translation should match the style of {target_lang} colloquially spoken in {country}."
if country != ""
else ""
)
prompt = f"""Your task is to carefully read a source text and a translation from {source_lang} to {target_lang}, and then give constructive criticism and helpful suggestions to improve the translation. \
{additional_rule}
The source text and initial translation, delimited by XML tags <SOURCE_TEXT></SOURCE_TEXT> and <TRANSLATION></TRANSLATION>, are as follows:
<SOURCE_TEXT>
{source_text}
</SOURCE_TEXT>
<TRANSLATION>
{translation_1}
</TRANSLATION>
When writing suggestions, pay attention to whether there are ways to improve the translation's \n\
(i) accuracy (by correcting errors of addition, mistranslation, omission, or untranslated text),\n\
(ii) fluency (by applying {target_lang} grammar, spelling and punctuation rules, and ensuring there are no unnecessary repetitions),\n\
(iii) style (by ensuring the translations reflect the style of the source text and takes into account any cultural context),\n\
(iv) terminology (by ensuring terminology use is consistent and reflects the source text domain; and by only ensuring you use equivalent idioms {target_lang}).\n\
Write a list of specific, helpful and constructive suggestions for improving the translation.
Each suggestion should address one specific part of the translation.
Output only the suggestions and nothing else."""
reflection = get_completion(prompt, system_message=system_message)
print("[反思结果]: \n", reflection)
return {"reflection": reflection}
def improve_translation(state):
source_lang = state.get("source_lang")
target_lang = state.get("target_lang")
source_text = state.get("source_text")
translation_1 = state.get("translation_1")
reflection = state.get("reflection")
system_message = f"You are an expert linguist, specializing in translation editing from {source_lang} to {target_lang}."
prompt = f"""Your task is to carefully read, then edit, a translation from {source_lang} to {target_lang}, taking into
account a list of expert suggestions and constructive criticisms.
The source text, the initial translation, and the expert linguist suggestions are delimited by XML tags <SOURCE_TEXT></SOURCE_TEXT>, <TRANSLATION></TRANSLATION> and <EXPERT_SUGGESTIONS></EXPERT_SUGGESTIONS> \
as follows:
<SOURCE_TEXT>
{source_text}
</SOURCE_TEXT>
<TRANSLATION>
{translation_1}
</TRANSLATION>
<EXPERT_SUGGESTIONS>
{reflection}
</EXPERT_SUGGESTIONS>
Please take into account the expert suggestions when editing the translation. Edit the translation by ensuring:
(i) accuracy (by correcting errors of addition, mistranslation, omission, or untranslated text),
(ii) fluency (by applying {target_lang} grammar, spelling and punctuation rules and ensuring there are no unnecessary repetitions), \
(iii) style (by ensuring the translations reflect the style of the source text)
(iv) terminology (inappropriate for context, inconsistent use), or
(v) other errors.
Output only the new translation and nothing else."""
translation_2 = get_completion(prompt, system_message)
print("[改进结果]: \n", translation_2)
return {"translation_2": translation_2}
# 规划执行任务
## 节点(node)注册
workflow.add_node("initial_translation", initial_translation)
workflow.add_node("reflect_on_translation", reflect_on_translation)
workflow.add_node("improve_translation", improve_translation)
## 连接节点
workflow.set_entry_point("initial_translation")
workflow.add_edge("initial_translation", "reflect_on_translation")
workflow.add_edge("reflect_on_translation", "improve_translation")
workflow.add_edge("improve_translation", END)
# 开始执行
app = workflow.compile()
result = app.invoke({
"source_lang": "English",
"target_lang": "中文",
"source_text": """I went to the woods because I wished to live deliberately, to front only the essential facts of life, and see if I could not learn what it had to teach, and not, when I came to die, discover that I had not lived. I wanted to live deep and suck out all the marrow of life, to live so sturdily and Spartan-like as to put to rout all that was not life, to cut a broad swath and shave close, to drive life into a corner, and reduce it to its lowest terms."""
})
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
编辑 (opens new window)
上次更新: 2025/12/19, 15:17:48