导读
环境:OpenEuler、Windows 11、WSL 2、Python 3.12.3 langchain 0.3
背景:前期忙碌的开发阶段结束,需要沉淀自己的应用知识,过一遍LangChain
时间:20250221
说明:技术梳理,使用LangChain基本功能实现翻译功能,由简入繁,并讲解相关的LangChain
1、极简实现
使用LangChain实现基本的翻译功能,复杂翻译肯定存在bug
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 调用一个大模型,qwen的开源,可以自己获取
translate_llm = ChatOpenAI(
base_url="https:/xxxxxxxxxxx",
api_key="skawxxxxxxxxW",
model_name="xxxxxx"
)
# 创建一个提示词模板,变量即为用户输入的英文
translate_prompt = PromptTemplate.from_template("请将英文翻译为中文, 问题:{cc}")
print("translate_prompt:", translate_prompt.invoke("hello").to_string())
# 构造链,最终以字符串格式输出
model = translate_prompt | translate_llm | StrOutputParser()
# 调用链
response = model.invoke({"cc":"hello"})
print("response:", response)
输出如下
translate_prompt: 请将英文翻译为中文, 问题:hello
response: 翻译:你好
分析
使用了基础的PromptTemplate作为提示词模板,输出解析器为StrOutputParser,其功能为将最终的返回值变为字符串。此处有两个输出,第一个是PromptValue,第二个是模型输出。
PromptValue使用了to_string方式生成,还有其他的三种to_messages、to_json、to_json_not_implemented来生成,大家可以自己尝试,实践出真知,从PromptValue生成可知,PromptTemplate将用户的输入与提示词合成了PromptValue。
在模型分析中可知,这个输出多了两个字 -- 翻译:,这样并不好,我们需要进行优化。
优化思路
从代码层面来看,能优化的也只有提示词,以下几个思路可以尝试
1、翻译也是一种对话机制,因此选择ChatPromptTemplate
2、详细描述任务,使大模型更能清楚任务的细节
2、优化提示词
通过精细化提示词,明确任务细节,提示词模板改为ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 调用一个大模型,qwen的开源,可以自己获取
translate_llm = ChatOpenAI(
base_url="https:/xxxxxxxxxxx",
api_key="skawxxxxxxxxW",
model_name="xxxxxx"
)
# 创建一个提示词模板,变量即为用户输入的英文
system_template = """
你是一个高级的翻译专家,精通中、英文,
你将收到一段文本。你的任务是:
- 将给定的英文文本翻译成简体中文,保留原格式。
- 如果你的输入包含富文本格式,请保留该格式并仅翻译文本部分。
- 仅输出格式与文本,不要输出解释、说明性的文本
请严格遵守上述要求,不要输出其他信息。
"""
translate_prompt = ChatPromptTemplate.from_messages(
[("system", system_template), ("user", "{text}")]
)
print("translate_prompt:", translate_prompt.invoke({"text":"hello"}).to_messages())
# 构造链,最终以字符串格式输出
model = translate_prompt | translate_llm | StrOutputParser()
# 调用链
response = model.invoke({"text":"hello"})
print("response:", response)
输出结果
translate_prompt: [SystemMessage(content='\n 你是一个高级的翻译专家,精通中、英文,\n 你将收到一段文本。你的任务是:\n - 将给定的英文文本翻译成简体中文,保留原格式。\n - 如果你的输入包含富文本格式,请保留该格式并仅翻译文本部分。\n - 仅输出格式与文本,不要输出解释、说明性的文本\n 请严格遵守上述要求,不要输出其他信息。\n', additional_kwargs={}, response_metadata={}), HumanMessage(content='hello', additional_kwargs={}, response_metadata={})]
response: 你好
分析
此处输出PromptValue改为to_messages,输出格式发生了变化,不再是字符串,而是一个列表,其内有两个对象,分别是SystemMessage和HumanMessage。
此处返回值也是按照我们的需求进行了返回,并没有返回多余的文字,接下来测试一篇文章,看看效果
长文本测试
Airbus crisis over
Airbus says it has turned the corner after a crisis connected to production problems and turmoil in the boardroom at its A380 super-jumbo project that has gone on for the past year. Speaking at the Paris air show, Louis Gallois, CEO of the European planemaker, said, "Airbus is back."
Airbus, which announced a raft of orders on the first day of the show, is competing with Boeing, its American rival, for the title of the largest planemaker in the world.
Boeing is expected to reveal the numbers of orders for its 787 Dreamliner soon. Airbus orders unveiled on Monday included Qatar Airways confirming a $16bn order for 80 A350 Airbus planes and ordering three A380 super-jumbos for about $750m.
Boeing and Airbus are also competing for orders from aircraft leasing firms. Orders from these companies - who rank highly among the biggest global buyers of aircraft - are often regarded as an indication of how successful a model will be in the long term.
Airbus also secured orders from US Airways that are worth $10bn for 22 of its A350 jets, 60 A320s and ten of its A330-200 wide-body planes.
A few months ago, Airbus unveiled a major cost-cutting programme aiming to reduce the workforce in Europe by 10,000, as well as announcing a group restructuring. "I can tell you with full confidence that Airbus is back and fully back, as you have started noting yesterday as demonstrated by our first day announcements," said Mr Gallois on the second day of the air show.
However, Boeing also announced a deal with General Electric (GE) on the show's first day. GE's commercial aviation services placed an order for six 777 Boeing freighters valued at around $1.4bn, to be delivered in the last quarter of 2008.
A Wall Street Journal website report, quoting the Delta operating chief yesterday said that Delta Air Lines were on the verge of ordering as many as 125 Boeing 787 jetliners by the end of this year. However, a spokesman for Delta later said that it had been having conversations "with several aircraft makers" and that "no final decision" had been made on future fleet purchases.
长文本结果
空中客车危机结束
空中客车表示,公司已经度过了长达一年的生产问题和A380超大飞机项目董事会动荡所引发的危机。欧洲飞机制造商的首席执行官路易·加洛伊斯在巴黎航空展上发言称,“空中客车回来了。”
空中客车在展览首日宣布了一系列订单,正与它的美国竞争对手波音争夺全球最大飞机制造商的称号。
波音预计很快会公布其787梦幻客机的订单数量。周一公布的空中客车订单包括卡塔尔航空确认订购价值160亿美元的80架A350空中客车飞机,以及订购三架A380超大飞机,价值约7.5亿美元。
波音和空中客车也在争夺飞机租赁公司的订单。这些公司在全球飞机采购中排名靠前,它们的订单通常被视为长期成功的一个标志。
空中客车还从美国航空公司获得了价值100亿美元的22架A350喷气机、60架A320和10架A330-200宽体客机的订单。
几周前,空中客车公布了大规模的削减成本计划,旨在将欧洲的员工人数减少10000人,并宣布了集团重组。加洛伊斯在航空展第二天发言时表示,“我可以满怀信心地告诉你,空中客车已经全面回归。正如你们从昨天第一天的公告中开始注意到的那样。”
然而,波音也在展览首日宣布了一项与通用电气(GE)的协议。GE的商用航空公司订购了六架价值约14亿美元的波音777货机,计划于2008年第四季度交付。
华尔街日报网站引用三角洲航空运营主管昨日的说法称,三角洲航空公司即将在今年底之前订购多达125架波音787客机。然而,三角洲的发言人随后表示,他们正在与多家飞机制造商进行洽谈,对于未来的机队采购“尚未作出最终决定”。
说明此种方法已经解决问题,为了进一步确保成功率,添加FewShotPromptTemplate
3、添加示例
通过FewShotPromptTemplate添加少量示例
from langchain_openai import ChatOpenAI
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 调用一个大模型,qwen的开源,可以自己获取
translate_llm = ChatOpenAI(
base_url="https://llm.ams.lenovo.com/v1/",
api_key="sk-Vie3w5wRtkawW",
model_name="qwen2.5-instruct"
)
examples = [
{
"question": "hello",
"answer": "你好"
},
{
"question": "<p>I want to change the world</p>",
"answer": "<p>我想改变世界</p>"
}
]
example_prompt = PromptTemplate(template="Question: {question}\nAnswer: {answer}")
# 创建一个提示词模板,变量即为用户输入的英文
system_template = """
你是一个高级的翻译专家,精通中、英文,
你将收到一段文本。你的任务是:
- 将给定的英文文本翻译成简体中文,保留原格式。
- 如果你的输入包含富文本格式,请保留该格式并仅翻译文本部分。
- 仅输出格式与文本,不要输出解释、说明性的文本
请严格遵守上述要求,不要输出其他信息。
"""
translate_llm = ChatOpenAI(
base_url="https:/xxxxxxxxxxx",
api_key="skawxxxxxxxxW",
model_name="xxxxxx"
)
print("translate_prompt:", translate_prompt.invoke({"text":"hello"}).to_string())
# 构造链,最终以字符串格式输出
model = translate_prompt | translate_llm | StrOutputParser()
text = """
Airbus crisis over
Airbus says it has turned the corner after a crisis connected to production problems and turmoil in the boardroom at its A380 super-jumbo project that has gone on for the past year. Speaking at the Paris air show, Louis Gallois, CEO of the European planemaker, said, "Airbus is back."
Airbus, which announced a raft of orders on the first day of the show, is competing with Boeing, its American rival, for the title of the largest planemaker in the world.
Boeing is expected to reveal the numbers of orders for its 787 Dreamliner soon. Airbus orders unveiled on Monday included Qatar Airways confirming a $16bn order for 80 A350 Airbus planes and ordering three A380 super-jumbos for about $750m.
Boeing and Airbus are also competing for orders from aircraft leasing firms. Orders from these companies - who rank highly among the biggest global buyers of aircraft - are often regarded as an indication of how successful a model will be in the long term.
Airbus also secured orders from US Airways that are worth $10bn for 22 of its A350 jets, 60 A320s and ten of its A330-200 wide-body planes.
A few months ago, Airbus unveiled a major cost-cutting programme aiming to reduce the workforce in Europe by 10,000, as well as announcing a group restructuring. "I can tell you with full confidence that Airbus is back and fully back, as you have started noting yesterday as demonstrated by our first day announcements," said Mr Gallois on the second day of the air show.
However, Boeing also announced a deal with General Electric (GE) on the show's first day. GE's commercial aviation services placed an order for six 777 Boeing freighters valued at around $1.4bn, to be delivered in the last quarter of 2008.
A Wall Street Journal website report, quoting the Delta operating chief yesterday said that Delta Air Lines were on the verge of ordering as many as 125 Boeing 787 jetliners by the end of this year. However, a spokesman for Delta later said that it had been having conversations "with several aircraft makers" and that "no final decision" had been made on future fleet purchases.
"""
# # 调用链
response = model.invoke({"text":text})
print("\n", response)
输出结果
translate_prompt:
你是一个高级的翻译专家,精通中、英文,
你将收到一段文本。你的任务是:
- 将给定的英文文本翻译成简体中文,保留原格式。
- 如果你的输入包含富文本格式,请保留该格式并仅翻译文本部分。
- 仅输出格式与文本,不要输出解释、说明性的文本
请严格遵守上述要求,不要输出其他信息。
Question: hello
Answer: 你好Question: <p>I want to change the world</p>
Answer: <p>我想改变世界</p>Question: hello
空客危机结束
空客表示,在过去一年中,由于A380超级客机项目生产问题和董事会动荡导致的危机已经过去。欧洲飞机制造商的首席执行官路易·加洛伊斯在巴黎航展上表示,“空客回来了。”
空客在展会的第一天宣布了一系列订单,正与美国竞争对手波音争夺全球最大的飞机制造商的称号。
预计波音将很快公布其787梦想飞机的订单数量。周一公布的空客订单包括卡塔尔航空确认购买80架A350空客飞机,价值160亿美元,并订购三架A380超级客机,价值约7.5亿美元。
波音和空客也在争夺飞机租赁公司的订单。这些公司在全球最大的飞机买家中排名靠前,他们的订单通常被视为某种机型是否长期成功的一个标志。
空客还从美国航空公司获得了价值100亿美元的22架A350喷气机、60架A320和10架A330-200宽体飞机的订单。
此前几个月,空客宣布了一项大规模的成本削减计划,旨在减少欧洲的员工数量10,000人,并宣布了公司的重组计划。“我可以非常自信地告诉你,空客回来了,并且完全恢复正常,正如您昨天开始注意到的那样,通过我们第一天的公告可以看出这一点,”加洛伊斯在航展第二天上说。
然而,波音也在展会第一天与通用电气(GE)达成了协议。GE的商业航空服务公司订购了六架波音777货机,价值约14亿美元,预计将于2008年最后一季度交付。
《华尔街日报》网站昨日引用达美航空公司运营主管的话说,达美航空即将在今年年底前订购多达125架波音787喷气机。然而,达美航空的一位发言人后来表示,他们一直“与几家飞机制造商”进行对话,并且“尚未对未来机队采购做出最终决定”。
分析
此处添加示例可以使输出结果更为精确,需要大量测试才能确认,此处只能展示使用方法
优化思路
正常输出都是一个字或是词输出,称之为流式输出,我们也是用该种方法
4、流式输出
大型语言模型生成完整响应可能需要几秒钟。这远远慢于应用程序对最终用户感觉响应的~200-300毫秒阈值。使应用程序感觉更具响应性的关键策略是显示中间进度;即,从模型逐个Token流式输出。
所有Runnable
对象都实现了一个名为stream
的同步方法和一个名为astream
的异步变体。
对于上述程序而言,仅需将调用invoke进行修改为stream即可,由于返回是迭代器,故需要使用for来输出
# # 调用链
response = model.invoke({"text":text})
print("\n", response)
# 将上述代码替换为下面代码
for i in model.stream({"text":text}):
print(i, end="/")
输出结果
///空/中客/车危/机结束/
/空/中/客/车/表示/,/在/经/历了/与A/3/8/0超/级巨/无/霸项目/相关/联/的生/产/问/题和/董/事/会动/荡的/危/机/后,/现在/已/度/过/了难/关。/在巴/黎航空/展/上,/这家/欧/洲/飞/机/制/造/商/的首/席执/行官/路易/斯·/加洛/伊斯/表/示/,“/空/中客/车已/经/回到/正轨。/”/
空/中客车在/展会/的/第/一/天宣/布了/一系列订/单/,/正与/它的/美国/竞争/对手波/音/争夺/全球/最/大/飞机/制造/商的/称/号/。/
/波音/公/司/即/将公/布其/7/87/梦幻客/机的/订单/数量/。周/一/公/布/的空中客/车订/单/包括/卡/塔/尔/航/空/公/司/确认/的订/购8/0/架/A/350/空/中客/车价/值1/6/0/亿/美/元/的/订单/以/及/采/购三/架/A3/8/0/超/级/巨无霸/飞机/,/价/值/约7/.5/亿美/元。/
波/音和/空中客/车还/在/争夺/飞机/租/赁公/司的订/单。/这些/公司/是/全球/最/大的/飞机/买家之/一,/它们/的订/单通/常被/视/为未/来某/个机/型成/功/程/度的/指标。
/空中客/车还/从/美/国/航空公/司/获得/了/价值10/0/亿/美/元/的/订/单/,/其/中/包/括/2/2/架/A/3/5/0/客/机/、/6/0/架/A/3/2/0/和/十/架A/330/-/2/00/宽体/机。/
几/个/月前/,空/中客/车宣/布/了一/项重/大成/本削减/计划/,旨/在/减少/欧洲/地区/的员/工人/数1/万人/,并宣/布进/行集/团/重组。/“/我可/以满/怀信/心地/告诉你,/空/中客/车已/经完/全/恢复/正/常/,正/如你们/昨/天所/看到/的,/我们/第/一/天的/公/告就/是证明/。”/加洛/伊斯/在/展/会/第二/天说/道。
/然而/,/波/音也/在展/会/第一/天/宣布了/与通/用/电气/(/GE/)的/一项/交/易。/G/E/的/商/业/航/空/服/务/部/订/购了/六/架/波/音77/7/货机/,/价/值/约/1/4亿/美元/,将/于2/0/0/8年第/四季/度/交付/。
/据《/华/尔街/日报》网站/昨日/报道/,引/用D/e/l/ta航空运/营主管的/话说/,/De/lt/a航/空/公/司/即/将/在/年/内/订/购/多/达/12/5/架波音78/7客/机/。不过/,D/el/t/a的一/位发言/人/后/来表/示,/该公司/一/直在/与“/几家/飞/机/制造/商”/进行/谈判/,/并且/“尚未/作/出/最终/决/定”关于未来的机队采购。//
分析
从代码层面考虑,流式输出修改量不大,凡是返回值为迭代器,所以需要遍历输出
5、多语言支持
想要支持多语言,首先修改提示词,并将代码进行遍历。此处添加计时装饰器,方便测试性能。
from langchain_openai import ChatOpenAI
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_core.output_parsers import StrOutputParser
import time
# 装饰器计算时间
def takes_time(a_func):
def wrapper(*args, **kwargs):
start_time = time.time()
a_func(*args, **kwargs)
print(f"花费{time.time() - start_time}秒")
return wrapper
def create_translation_model(target, examples):
system_template = f"""
你是一个高级的翻译专家,精通中、日、韩、英文,
你将收到一段文本。你的任务是:
- 将给定的英文文本翻译成{target},保留原格式。
- 如果你的输入包含富文本格式,请保留该格式并仅翻译文本部分。
- 仅输出格式与文本,不要输出解释、说明性的文本
请严格遵守上述要求,不要输出其他信息。
"""
example_prompt = PromptTemplate(template="Target:{target}\n{question}\n{answer}")
translate_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix=system_template,
suffix="Question: {text}"
)
translate_llm = ChatOpenAI(
base_url="https:/xxxxxxxxxxx",
api_key="skawxxxxxxxxW",
model_name="xxxxxx"
)
return translate_prompt | translate_llm | StrOutputParser()
@takes_time
def translate_languages():
targets = ["zh", "ko", "ja"]
text = "I want to change the world"
examples = [
{
"target": "zh",
"question": "hello",
"answer": "你好"
}
]
for target in targets:
model = create_translation_model(target, examples)
# 调用模型进行翻译
for i in model.stream({"text": text, "target": target}):
print(i, end="/")
print()
# 调用函数
translate_languages()
输出结果
我想改变世界//
///저는 세상을改变世界//
///世界を変えるたいです//
花费3.4068121910095215秒
分析
为了让代码具备整体性,此处分为多个函数,便于理解
6、异步输出
Runnable实现输出基本均有同步方法invoke、stream、batch,对应的异步方法是ainvoke、astream、abatch,下面使用异步流的方式来展示,由于示例简单,并不能实现效率提升,此处仅为展示异步实现方法
python中的异步需要使用asyncio构造一个事件循环,同时还需要构造一个函数,修改如下:
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, FewShotPromptTemplate, PromptTemplate
from langchain_core.output_parsers import StrOutputParser
import asyncio, time
# 装饰器计算时间
def takes_time(a_func):
async def wrapper(*args, **kwargs):
start_time = time.time()
await a_func(*args, **kwargs) # 传递参数
print(f"花费{time.time() - start_time}秒")
return wrapper
async def create_translation_model(target, text, examples):
system_template = f"""
你是一个高级的翻译专家,精通中、日、韩、英文,
你将收到一段文本。你的任务是:
- 将给定的英文文本翻译成{target},保留原格式。
- 如果你的输入包含富文本格式,请保留该格式并仅翻译文本部分。
- 仅输出格式与文本,不要输出解释、说明性的文本
请严格遵守上述要求,不要输出其他信息。
"""
example_prompt = PromptTemplate(template="Target:{target}\n{question}\n{answer}")
translate_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix=system_template,
suffix="Question: {text}"
)
translate_llm = ChatOpenAI(
base_url="https:/xxxxxxxxxxx",
api_key="skawxxxxxxxxW",
model_name="xxxxxx"
)
return translate_prompt | translate_llm | StrOutputParser()
async def to_language(per_lang, model, text):
try:
async for i in model.astream({"text": text, "target": per_lang}):
print(i, end="/")
print("\n")
except Exception as e:
print(f"Error translating to {per_lang}: {e}")
@takes_time
async def translate_languages():
targets = ["zh", "ko", "ja"]
text = "I want to change the world"
examples = [
{
"target": "zh",
"question": "hello",
"answer": "你好"
}
]
tasks = []
for target in targets:
model = await create_translation_model(target, text, examples)
tasks.append(to_language(target, model, text))
await asyncio.gather(*tasks)
asyncio.run(translate_languages())
输出结果
我想改变世界//
///私は世界を変えるたいです
/질/문:/ 세계를 바꾸고 싶어요//
花费1.6649830341339111秒
分析
显然,异步提升很多,如果翻译的种类越多,提升的也就更明显
7、异步多线程实现
异步多线程已经无法提升性能,此处仅作为用法示例,便于以后在复杂的场景下使用
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, FewShotPromptTemplate, PromptTemplate
from langchain_core.output_parsers import StrOutputParser
import asyncio, time
from concurrent.futures import ThreadPoolExecutor
# 装饰器计算时间
def takes_time(a_func):
async def wrapper(*args, **kwargs):
start_time = time.time()
await a_func(*args, **kwargs) # 传递参数
print(f"花费{time.time() - start_time}秒")
return wrapper
async def create_translation_model(target, text, examples):
system_template = f"""
你是一个高级的翻译专家,精通中、日、韩、英文,
你将收到一段文本。你的任务是:
- 将给定的英文文本翻译成{target},保留原格式。
- 如果你的输入包含富文本格式,请保留该格式并仅翻译文本部分。
- 仅输出格式与文本,不要输出解释、说明性的文本
请严格遵守上述要求,不要输出其他信息。
"""
example_prompt = PromptTemplate(template="Target:{target}\n{question}\n{answer}")
translate_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix=system_template,
suffix="Question: {text}"
)
translate_llm = ChatOpenAI(
base_url="https://llm.ams.lenovo.com/v1/",
api_key="sk-Vie3w5wRtkawW",
model_name="qwen2.5-instruct"
)
return translate_prompt | translate_llm | StrOutputParser()
async def to_language(per_lang, model, text):
try:
async for i in model.astream({"text": text, "target": per_lang}):
print(i, end="/")
print("\n")
except Exception as e:
print(f"Error translating to {per_lang}: {e}")
async def process_with_threadpool(executor, target, text, examples):
loop = asyncio.get_running_loop()
model = await create_translation_model(target, text, examples)
await loop.run_in_executor(executor, lambda: asyncio.run(to_language(target, model, text)))
@takes_time
async def translate_languages():
targets = ["zh", "ko", "ja"]
text = "I want to change the world"
examples = [
{
"target": "zh",
"question": "hello",
"answer": "你好"
}
]
with ThreadPoolExecutor() as executor:
tasks = [process_with_threadpool(executor, target, text, examples) for target in targets]
await asyncio.gather(*tasks)
asyncio.run(translate_languages())
输出结果
//我想改变世界//
///世界を変えるたいです
변경하고 싶은 세계//
花费1.4943761825561523秒
分析
性能并未提升
8、同步多线程
实现同步多线程,与异步进行对比
from langchain_openai import ChatOpenAI
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_core.output_parsers import StrOutputParser
import time
from concurrent.futures import ThreadPoolExecutor
# 装饰器计算时间
def takes_time(a_func):
def wrapper(*args, **kwargs):
start_time = time.time()
a_func(*args, **kwargs)
print(f"花费{time.time() - start_time}秒")
return wrapper
def create_translation_model(target, examples):
system_template = f"""
你是一个高级的翻译专家,精通中、日、韩、英文,
你将收到一段文本。你的任务是:
- 将给定的英文文本翻译成{target},保留原格式。
- 如果你的输入包含富文本格式,请保留该格式并仅翻译文本部分。
- 仅输出格式与文本,不要输出解释、说明性的文本
请严格遵守上述要求,不要输出其他信息。
"""
example_prompt = PromptTemplate(template="Target:{target}\n{question}\n{answer}")
translate_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix=system_template,
suffix="Question: {text}"
)
translate_llm = ChatOpenAI(
base_url="https://llm.ams.lenovo.com/v1/",
api_key="sk-Vie3w5wRtkawW",
model_name="qwen2.5-instruct"
)
return translate_prompt | translate_llm | StrOutputParser()
def translate_to_language(target, text, examples):
try:
model = create_translation_model(target, examples)
for i in model.stream({"text": text, "target": target}):
print(i, end="/")
print("\n")
except Exception as e:
print(f"Error translating to {target}: {e}")
@takes_time
def translate_languages():
targets = ["zh", "ko", "ja"]
text = "I want to change the world"
examples = [
{
"target": "zh",
"question": "hello",
"answer": "你好"
}
]
with ThreadPoolExecutor() as executor:
futures = [executor.submit(translate_to_language, target, text, examples) for target in targets]
for future in futures:
future.result() # 确保所有任务完成后再继续
# 调用函数
translate_languages()
输出结果
///我想改变世界
//世界を変えたいです//
///저는 /세상을 바꾸고 싶습니다//
花费1.5249838829040527秒
分析
此处可以得知,异步、异步多线程、多线程三种方式性能是相似的,一般而言,选择一种即可
综述
上述示例涵盖多个功能搭配,均使用最为基础的功能进行示例