智能体,也就是Agent,一个快被炒烂了的概念,大模型套壳被叫做Agent,搞个对话窗口,设置好角色,任务提示词也可以叫Agent,反正就是只要和大模型应用沾一点点边儿,都会被叫做Agent,那到底什么是Agent??
Agent的不同含义
Agent不就是智能体?还有什么不同含义?当然,因为Agent并不是一个新概念
机器学习中的Agent
Agent并不是大模型出现以后才有的概念,在机器学习领域中Agent是一个存在了很长时间的概念,它是指,能够感知环境,做出决策,并实现特定目标的实体,这些实体具备自主性,能够通过传感器获取信息,经过内部处理以后,再通过某些设备对外部施加影响,并且能够在设定好的范围内有自主进化,AlphaGo就是一个机器学习领域下的Agent。
大模型下的agent
2023年OpenAI研究员Lilian Weng发表了篇技术博客,探讨了大模型驱动的智能体是什么(原文地址:lilianweng.github.io/posts/2023-…),这篇文章让大模型驱动的智能体有了共识性的基础定义
按文章中的描述,大模型驱动的Agent应该有以下特征
- 核心驱动:LLM(提供基础智力、通识、逻辑、上下文内学习等基础能力)关键组件:
- 规划(Planning):将复杂任务分解为可管理的子目标(Task Decomposition),并通过自我反思(Self-Reflection)来提高结果质量记忆(Memory):包括短期记忆(对话记录)和长期记忆(通过外部向量存储和快速检索来保留和回忆信息)(这部分突破项目不多,去年有一个叫Mem0的项目刷过一次屏)工具使用(Tool Use):学习调用外部工具,补充额外信息或完成环境交互
像之前比较火的AutoGPT,GPT-Engineer,BabyAGI 包括ReAct都是基于上面的定义进行的各种探索。
再回顾我们在上篇文章中提到的Function Calling 其实已经初步具备了agent的基础能力,可以说是一个agent的最最简化版本,不过还是有一定的缺陷,因为我们需要用Agent解决的问题是可大可小的,Function Calling只是在限定范围内完成了识别目标,选择工具,执行动作,整合上下文的回路,对于复杂问题可能就力不从心了,所以在其基础上又有了更加扩展的Agent系统。
在有了大模型驱动的智能体驱动后,业界有了很多的尝试,致力于去解决更复杂的问题
Agent的花样落地姿势
Langchain
LangChain前面的文章我们也提到过,他更注重于模型交互的封装,其实这是因为LangChain更关注对于模型能力的应用,也就是他不在乎我做出来的是不是一个符合范式的智能体,而是如何使用好模型能力去解决问题。
多智能体协同
代表项目有:
- Camel.aiMetaGPTMicrosoft AutoGenOpenAI Swarm(现在的Agent SDK)
但上面的项目通常用的都是一个简化结构的智能体,比如只用了Role的设定,或者ReAct提示词,所以他们的关注点也不在如何构建一个更完整的Agent,也不在于如何应用好模型能力,而是去构建一个协作网络,将用户制作的或厂商提供的智能体放入网络,通过这样的方式来解决问题
GPTs和Assistant API
Assistant搭建界面
Gpts使用界面
上面两个是OpenAI提供的应用,也可以说是对Agent产品化的尝试,这些工具提供了一定的能力比如:切换驱动模型(可在OpenAI系列模型中切换),角色设置,工具调用等等,让普罗大众对agent有了具象化的认知,不过这个东西也成了国内自媒体炒作的素材,于是各种各样的错误认知开始出现,比如模型应用是Agent,GPTs是Agent,等等只要和大模型应用稍微沾一点点边儿,就被叫Agent。
Responses
Responses是OpenAI,提供的一个新一代的模型的表达格式或协议,说白了就是一种和模型沟通的新的接口标准(和mcp不同,mcp针对的是工具的调用),所以在使用Responses的时候需要确认,你现在用的大模型的厂商是不是兼容了这个标准。
Responses可以说是Assistant API的简化版本,Assistant API 用过的都知道,不好用。。。所以Response做了一定的优化,提供了一些新的能力:
- 动态调整角色设定
- 涉及参数:
instructions
- 涉及参数:
tools
、parallel_tool_calls
、tool_choice
、include
- 涉及参数:
reasoning
- 涉及参数:
previous_response_id
- 涉及参数:
store
简单使用:
import osfrom openai import OpenAIimport dotenvdotenv.load_dotenv('.env')client = OpenAI( api_key=os.environ.get("OPENAI_API_KEY"), base_url=os.environ.get("OPENAI_API_BASE"),)first_response = client.responses.create( model="gpt-4o-mini", tools=[{ "type": "web_search_preview" }], input="搜索并回答Agently AI应用开发框架是什么?", include=["file_search_call.results"], instructions="你是一个系统架构师",)print(first_response)print("工具调用记录: ", first_response.output[:-1])print("============")print("回复:", first_response.output[-1].content[0].text)
输出:
Response(id='resp_685a638b56f88199b740432256997ce308010fad144b5473', created_at=1750754187.0, error=None, incomplete_details=None, instructions='你是一个系统架构师', metadata=[], model='gpt-4o-mini-2024-07-18', object='response', output=[ResponseFunctionWebSearch(id='ws_685a638c1fbc8199b637ece347b6617d08010fad144b5473', status='completed', type='web_search_call'), ResponseOutputMessage(id='msg_685a638dc56881998305196f688aa5b108010fad144b5473', content=[ResponseOutputText(annotations=[AnnotationURLCitation(end_index=275, start_index=186, title='Agently AnyModel介绍 - Agently AI应用开发框架', type='url_citation', url='https://agently.tech/guides/model_settings/index.html?utm_source=openai'), AnnotationURLCitation(end_index=453, start_index=363, title='手把手入门教程 - Agently AI应用开发框架', type='url_citation', url='https://agently.tech/guides/agentic_request/guide.html?utm_source=openai'), AnnotationURLCitation(end_index=609, start_index=526, title='Agently Workflow介绍 - Agently AI应用开发框架', type='url_citation', url='https://agently.tech/guides/workflow/index.html?utm_source=openai'), AnnotationURLCitation(end_index=745, start_index=692, title='Agently AI应用开发框架', type='url_citation', url='https://agently.cn/?utm_source=openai'), AnnotationURLCitation(end_index=851, start_index=798, title='Agently AI应用开发框架', type='url_citation', url='https://agently.cn/?utm_source=openai')], text='Agently AI应用开发框架是一个开源的AI代理应用开发框架,旨在帮助开发者快速构建AI智能体原生应用。该框架提供了简洁直观的API,使开发者能够专注于业务逻辑,而无需深入处理底层的AI模型交互细节。\n\nAgently的主要特点包括:\n\n- **AnyModel模型切换**:支持无缝切换多种主流商用模型API和本地私有化部署模型,允许在业务逻辑中协同处理复杂问题。 ([agently.tech](https://agently.tech/guides/model_settings/index.html?utm_source=openai))\n\n- **AgenticRequest增强模型输出控制**:提供强大的模型输出控制能力,支持意图识别、思维链、角色控制、知识插入等应用场景,结构化数据输出成功率超过90%。 ([agently.tech](https://agently.tech/guides/agentic_request/guide.html?utm_source=openai))\n\n- **Workflow工作流编程方案**:支持环状结构、并行分支、条件分发等复杂工作流结构,允许对多轮模型请求和复杂业务逻辑进行编排管理。 ([agently.tech](https://agently.tech/guides/workflow/index.html?utm_source=openai))\n\n- **Agently-YAML配置化管理**:通过YAML语法将业务代码逻辑与模型请求方案进一步解耦,提升协作顺畅度,支持配置化、模块化,具备极高的可扩展性。 ([agently.cn](https://agently.cn/?utm_source=openai))\n\n此外,Agently还提供了丰富的文档和示例,帮助开发者快速上手并深入理解框架的设计理念和应用场景。 ([agently.cn](https://agently.cn/?utm_source=openai))\n\n通过这些功能,Agently旨在为开发者提供一个易用、灵活、高效的AI应用开发体验,简化AI代理应用的构建过程。 ', type='output_text', logprobs=None)], role='assistant', status='completed', type='message')], parallel_tool_calls=True, temperature=1.0, tool_choice='auto', tools=[WebSearchTool(type='web_search_preview', search_context_size='medium', user_location=UserLocation(type='approximate', city=None, country='US', region=None, timezone=None))], top_p=1.0, background=False, max_output_tokens=None, previous_response_id=None, prompt=None, reasoning=Reasoning(effort=None, generate_summary=None, summary=None), service_tier='default', status='completed', text=ResponseTextConfig(format=ResponseFormatText(type='text')), truncation='disabled', usage=ResponseUsage(input_tokens=324, input_tokens_details=InputTokensDetails(cached_tokens=0), output_tokens=462, output_tokens_details=OutputTokensDetails(reasoning_tokens=0), total_tokens=786), user=None, store=True)工具调用记录: [ResponseFunctionWebSearch(id='ws_685a638c1fbc8199b637ece347b6617d08010fad144b5473', status='completed', type='web_search_call')]============回复: Agently AI应用开发框架是一个开源的AI代理应用开发框架,旨在帮助开发者快速构建AI智能体原生应用。该框架提供了简洁直观的API,使开发者能够专注于业务逻辑,而无需深入处理底层的AI模型交互细节。Agently的主要特点包括:- **AnyModel模型切换**:支持无缝切换多种主流商用模型API和本地私有化部署模型,允许在业务逻辑中协同处理复杂问题。 ([agently.tech](https://agently.tech/guides/model_settings/index.html?utm_source=openai))- **AgenticRequest增强模型输出控制**:提供强大的模型输出控制能力,支持意图识别、思维链、角色控制、知识插入等应用场景,结构化数据输出成功率超过90%。 ([agently.tech](https://agently.tech/guides/agentic_request/guide.html?utm_source=openai))- **Workflow工作流编程方案**:支持环状结构、并行分支、条件分发等复杂工作流结构,允许对多轮模型请求和复杂业务逻辑进行编排管理。 ([agently.tech](https://agently.tech/guides/workflow/index.html?utm_source=openai))- **Agently-YAML配置化管理**:通过YAML语法将业务代码逻辑与模型请求方案进一步解耦,提升协作顺畅度,支持配置化、模块化,具备极高的可扩展性。 ([agently.cn](https://agently.cn/?utm_source=openai))此外,Agently还提供了丰富的文档和示例,帮助开发者快速上手并深入理解框架的设计理念和应用场景。 ([agently.cn](https://agently.cn/?utm_source=openai))通过这些功能,Agently旨在为开发者提供一个易用、灵活、高效的AI应用开发体验,简化AI代理应用的构建过程。
然后我们带上response_id
再次请求:
second_response = client.responses.create( model="gpt-4o-mini", tools=[{ "type": "web_search_preview" }], input="所以Agently AI应用开发框架可以用来做什么?是怎么做到的?用了哪些特性?", include=["file_search_call.results"], instructions="你是一个为8岁孩子👦👧讲解概念的教师👨🏫,你喜欢使用emoji辅助表达🙂", previous_response_id=first_response.id)print(second_response)print("回复:", second_response.output[-1].content[0].text)
输出:
可以看到,是有去获取上一次请求的信息的,至于这样是不是省token? 不知道,这个是openAI来判断的。
总之,业界对于Agent的落地进行了各种各样的尝试,但是却好像还存在什么问题。没错,就是不可控,不管是Responses还是其他什么Agent应用,模型做什么操作,以什么顺序去操作,对于我们来说完全是一个黑盒子,就像这样
中间那个大方块我们决定不了,也就是我们只能提供边缘信息,核心逻辑完全不可控。。。
如何让Agent变得可控
ReAct思考模式
我们会看一下ReAct思考模式,也就是:规划-> 行动 -> 反思,那我们是不是可以把这个过程拆分开呢?
以FunctionCalling为例
这里我们使用Agently框架,
pip install Agently
Agently简单使用
构建基础请求
import osimport Agentlyagent = ( Agently.create_agent(is_debug=True) # 开启debug模式可以观察调用过程 .set_settings("current_model", "OpenAI") .set_settings("model.OpenAI.url", os.environ.get("OPENAI_BASE_URL")) .set_settings("model.OpenAI.auth", { "api_key": os.environ.get("OPENAI_API_KEY") }) .set_settings("model.OpenAI.options", { "model": "gpt-4o-mini" }))agent.input("你是谁").start()
输出:
[Request Data] { "stream": true, "messages": [ { "role": "user", "content": "你是谁" } ], "model": "gpt-4o-mini"}[Realtime Response]我是一个人工智能助手,旨在回答你的问题和提供信息。如果你有什么具体问题或需要帮助的地方,请告诉我!--------------------------[Final Reply] 我是一个人工智能助手,旨在回答你的问题和提供信息。如果你有什么具体问题或需要帮助的地方,请告诉我! --------------------------'我是一个人工智能助手,旨在回答你的问题和提供信息。如果你有什么具体问题或需要帮助的地方,请告诉我!'
工作流编排
test_workflow = Agently.Workflow()@test_workflow.chunk()def echo(inputs, storage): print(inputs["default"]) storage.set("saved_data", f"ECHO: { inputs['default'] }")@test_workflow.chunk()def return_value(inputs, storage): return storage.get("saved_data")( test_workflow .connect_to("echo") .connect_to("return_value") .connect_to("END"))test_workflow.draw(type='img')result = test_workflow.start("This is a workflow")print(result["default"])
输出:
This is a workflowECHO: This is a workflow
上面是Agently的简单使用下面我们还是以天气查询为例,完成一个完整的FunctionCalling
Function Calling
import osimport Agentlyagent = ( Agently.create_agent() .set_settings("current_model", "OpenAI") .set_settings("model.OpenAI.url", os.environ.get("OPENAI_API_BASE")) .set_settings("model.OpenAI.auth", { "api_key": os.environ.get("OPENAI_API_KEY") }) .set_settings("model.OpenAI.options", { "model": "gpt-4o" }))workflow = Agently.Workflow()@workflow.chunk()def save_data(inputs, storage): if "debug" in inputs["default"] and inputs["default"]["debug"]: agent.set_settings("is_debug", True) storage.set("prompt", inputs["default"]["prompt"]) storage.set("tools_info", inputs["default"]["tools_info"]) storage.set("tools_mapping", inputs["default"]["tools_mapping"]) return@workflow.chunk()def plan_and_judge_tool_call(inputs, storage): return ( agent # 用户问题输入 .input(storage.get("prompt")) # 提供工具列表信息 .info({ "可用工具列表": storage.get("tools_info") }) # 问题处理方向说明 .instruct("根据{input}的用户要求以及{可用工具列表}提供的工具信息,决定你的行动方案") # 提供结构化输出能力,按结构化要求顺序输出结果,顺序输出是COT的基础 # tuple第一个元素标记类型,可以使用自然语言描述,第二个元素是对字段的进一步补充说明 .output({ # 理解用户问题 "clarify": ("str", "用户在{input}中提出的具体要求是什么?"), # 思考工具调用 "tool_using_thinking": { # 确定是否用工具 "use_tool": ("bool", "是否需要使用工具解决{input}及{clarify}提出的要求或问题?"), # 如果用工具则输出具体的规划 "tool_using": ({ "tool_name": ("str from {可用工具列表.name}", ), # 使用哪个工具 "purpose": ("str", "描述希望使用此工具解决的问题"), # 解决什么问题 "kwargs": ("dict", "根据{可用工具列表.kwargs}的要求给出所需参数"), # 参数是什么 }, "如果use_tool==true, 需要输出调用工具的具体规划,否则输出null") }, # 如果不用,则直接给出回复 "direct_reply": ("str", "如果{tool_using_thinking.use_tool}==false,则在此输出你的直接回复,否则输出''") }) .start() )@workflow.chunk()def call_tool(inputs, storage): tools_mapping = storage.get("tools_mapping") tool_using = inputs["default"]["tool_using_thinking"]["tool_using"] return { # <需要解决的问题>:对应工具映射中的<tool_name>(**kwargs)的最终结果 tool_using["purpose"]: tools_mapping[tool_using["tool_name"]](**tool_using["kwargs"]) }@workflow.chunk()def generate_reply(inputs, storage): tool_using_result = inputs["default"] return ( agent .input(storage.get("prompt")) .info({ "工具调用结果": tool_using_result, }) .instruct("根据{工具调用结果}回答{input}") .start() )@workflow.chunk()def direct_reply(inputs, storage): return inputs["default"]["direct_reply"]( workflow .connect_to("save_data") .connect_to("plan_and_judge_tool_call") .if_condition(lambda return_value, storage: return_value["tool_using_thinking"]["use_tool"]) .connect_to("call_tool") .connect_to("generate_reply") .connect_to("END") .else_condition() .connect_to("direct_reply") .connect_to("END"))workflow.draw(type="img")
输出:
在上面的代码中我们通过工作流编排和限定COT的步骤,来实现核心逻辑的可控。。
实际调用
def get_weather(*, latitude:float, longitude:float): return { "temperature": 23, "weather": "Sunny", "wind_direction": "South", "windy": 2, }tools_info = [{ "name": "get_weather", "desc": "Get current temperature for provided coordinates in celsius.", "kwargs": { "latitude": ("number", ), "longitude": ("number", ), },}]tools_mapping = { "get_weather": get_weather}result = workflow.start({ "prompt": "今天北京的天气怎么样?", "tools_info": tools_info, "tools_mapping": tools_mapping, "debug": True})print(result["default"])
输出:
[Request Data] { "stream": true, "messages": [ { "role": "user", "content": "# [INPUT]:\n今天北京的天气怎么样?\n\n# [HELPFUL INFORMATION]:\n{'可用工具列表': [{'name': 'get_weather', 'desc': 'Get current temperature for provided coordinates in celsius.', 'kwargs': {'latitude': ('number',), 'longitude': ('number',)}}]}\n\n# [INSTRUCTION]:\n根据{input}的用户要求以及{可用工具列表}提供的工具信息,决定你的行动方案\n\n# [OUTPUT REQUIREMENT]:\n## TYPE:\nJSON can be parsed in Python\n## FORMAT:\n{\n\t"clarify": <str>,//用户在{input}中提出的具体要求是什么?\n\t"tool_using_thinking": \n\t{\n\t\t"use_tool": <bool>,//是否需要使用工具解决{input}及{clarify}提出的要求或问题?\n\t\t"tool_using": \n\n\t\t\t{\n\t\t\t\t"tool_name": <str from {可用工具列表.name}>,\n\t\t\t\t"purpose": <str>,//描述希望使用此工具解决的问题\n\t\t\t\t"kwargs": <dict>,//根据{可用工具列表.kwargs}的要求给出所需参数\n\t\t\t\t},,//如果use_tool==true, 需要输出调用工具的具体规划,否则输出null\n\t\t},\n\t"direct_reply": <str>,//如果{tool_using_thinking.use_tool}==false,则在此输出你的直接回复,否则输出''\n}\n\n\n[OUTPUT]:\n" } ], "model": "gpt-4o"}[Realtime Response]```json{"clarify": "查询今天北京的天气情况","tool_using_thinking": {"use_tool": true,"tool_using": {"tool_name": "get_weather","purpose": "获取北京当前的温度信息","kwargs": {"latitude": 39.9042, "longitude": 116.4074}}},"direct_reply": ""}```--------------------------[Final Reply] ```json{"clarify": "查询今天北京的天气情况","tool_using_thinking": {"use_tool": true,"tool_using": {"tool_name": "get_weather","purpose": "获取北京当前的温度信息","kwargs": {"latitude": 39.9042, "longitude": 116.4074}}},"direct_reply": ""}``` --------------------------[Cleaned JSON String]: {"clarify": "查询今天北京的天气情况","tool_using_thinking": {"use_tool": true,"tool_using": {"tool_name": "get_weather","purpose": "获取北京当前的温度信息","kwargs": {"latitude": 39.9042, "longitude": 116.4074}}},"direct_reply": ""}--------------------------[Request Data] { "stream": true, "messages": [ { "role": "user", "content": "# [INPUT]:\n今天北京的天气怎么样?\n\n# [HELPFUL INFORMATION]:\n{'工具调用结果': {'获取北京当前的温度信息': {'temperature': 23, 'weather': 'Sunny', 'wind_direction': 'South', 'windy': 2}}}\n\n# [INSTRUCTION]:\n根据{工具调用结果}回答{input}\n\n[OUTPUT]:\n" } ], "model": "gpt-4o"}[Realtime Response]北京今天的天气是晴朗,当前气温是23摄氏度,风向来自南方,风力为2级。--------------------------[Final Reply] 北京今天的天气是晴朗,当前气温是23摄氏度,风向来自南方,风力为2级。 --------------------------北京今天的天气是晴朗,当前气温是23摄氏度,风向来自南方,风力为2级。
可以看到模型是在根据我们的编排和设定完成了任务。但是好像少了什么,上面的代码有规划,有行动,但是没有反思。
Reflection能够获得更好的输出?
关于反思其实有一个猜想,反思是否可以带来更好的输出。关于这个问题,吴恩达有一个翻译项目是用来演示反思所带来的效果的:github.com/andrewyng/t…
项目整体流程并不复杂,给到agent一个稿件进行翻译,然后交给审查agent提出修改意见,最后把翻译初稿和修改意见交给最后一个agent进行修改输出终稿,代码如下:
import jsonimport Agentlyimport os # 将模型请求配置设置到agent工厂,后续工厂创建的agent对象都可以继承这个配置agent_factory = ( Agently.AgentFactory() .set_settings("current_model", "OpenAI") .set_settings("model.OpenAI.url", os.environ.get("OPENAI_API_BASE")) .set_settings("model.OpenAI.auth", { "api_key": os.environ.get("OPENAI_API_KEY") }) .set_settings("model.OpenAI.options", { "model": "gpt-4o-mini" }))# 创建工作流workflow = Agently.Workflow()# 定义关键处理节点## 首次翻译@workflow.chunk()def initial_translation(inputs, storage): source_lang = storage.get("source_lang") target_lang = storage.get("target_lang") source_text = storage.get("source_text") # 创建一个翻译agent来执行任务 translate_agent = agent_factory.create_agent() # 给翻译agent设置system信息 translate_agent.set_agent_prompt( "role", f"You are an expert linguist, specializing in translation from {source_lang} to {target_lang}." ) # 向翻译agent发起翻译任务请求 translation_1 = ( translate_agent .input(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}:""" ) .start() ) # 保存翻译结果 storage.set("translation_1", translation_1) # 保存翻译agent备用 storage.set("translate_agent", translate_agent) return { "stage": "initial translation", "result": translation_1 }## 反思优化@workflow.chunk()def reflect_on_translation(inputs, storage): source_lang = storage.get("source_lang") target_lang = storage.get("target_lang") source_text = storage.get("source_text") country = storage.get("country", "") translation_1 = storage.get("translation_1") # 创建一个反思agent来执行任务 reflection_agent = agent_factory.create_agent() # 给反思agent设置system信息 reflection_agent.set_agent_prompt( "role", 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 = ( "The final style and tone of the translation should match the style of {target_lang} colloquially spoken in {country}." if country != "" else "" ) # 向反思agent发起反思任务 reflection = ( reflection_agent .input(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.""" ) .start() ) # 保存反思结果 storage.set("reflection", reflection) return { "stage": "reflection", "result": reflection }## 二次翻译@workflow.chunk()def improve_translation(inputs, storage): source_lang = storage.get("source_lang") target_lang = storage.get("target_lang") source_text = storage.get("source_text") translation_1 = storage.get("translation_1") reflection = storage.get("reflection") # 使用保存下来的翻译agent translate_agent = storage.get("translate_agent") # 直接发起二次翻译任务 translation_2 = ( translate_agent .input(f"""Your task is to carefully read, then edit, a translation from {source_lang} to {target_lang}, taking intoaccount 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.""" ) .start() ) # 保存二次翻译结果 storage.set("translation_2", translation_2) return { "stage": "improve translation", "result": translation_2 }# 连接工作块( workflow .connect_to("initial_translation") .connect_to("reflect_on_translation") .connect_to("improve_translation") .connect_to("end"))workflow.draw(type='img')
调优
我们对整个输出过程做一下优化:
# 添加过程输出优化@workflow.chunk_class()def output_stage_result(inputs, storage): print(f"[{ inputs['default']['stage'] }]:\n", inputs["default"]["result"]) return( workflow.chunks["initial_translation"] .connect_to("@output_stage_result") .connect_to("reflect_on_translation.wait"))( workflow.chunks["reflect_on_translation"] .connect_to("@output_stage_result") .connect_to("improve_translation.wait"))( workflow.chunks["improve_translation"] .connect_to("@output_stage_result"))workflow.draw(type="img")
@output_stage_result
用于做输出补充,@
表示每次出现都是新的独立代码块
具体的优化逻辑是将:
- 原文->初翻agent->翻译初稿->审批agent->翻译初稿和修改意见->修改agent调整为原文->初翻agent->原文+翻译初稿->审批agent->原文信息+翻译初稿+修改意见->修改agent
目的是为了增加模型看到的信息的丰富程度从而提高输出效果
调用
# 启动工作流result = workflow.start(storage = { "source_lang": "English", "target_lang": "中文", "source_text": """Translation Agent: Agentic translation using reflection workflowThis is a Python demonstration of a reflection agentic workflow for machine translation. The main steps are:Prompt an LLM to translate a text from source_language to target_language;Have the LLM reflect on the translation to come up with constructive suggestions for improving it;Use the suggestions to improve the translation.CustomizabilityBy using an LLM as the heart of the translation engine, this system is highly steerable. For example, by changing the prompts, it is easier using this workflow than a traditional machine translation (MT) system to:Modify the output's style, such as formal/informal.Specify how to handle idioms and special terms like names, technical terms, and acronyms. For example, including a glossary in the prompt lets you make sure particular terms (such as open source, H100 or GPU) are translated consistently.Specify specific regional use of the language, or specific dialects, to serve a target audience. For example, Spanish spoken in Latin America is different from Spanish spoken in Spain; French spoken in Canada is different from how it is spoken in France.This is not mature software, and is the result of Andrew playing around with translations on weekends the past few months, plus collaborators (Joaquin Dominguez, Nedelina Teneva, John Santerre) helping refactor the code.According to our evaluations using BLEU score on traditional translation datasets, this workflow is sometimes competitive with, but also sometimes worse than, leading commercial offerings. However, we’ve also occasionally gotten fantastic results (superior to commercial offerings) with this approach. We think this is just a starting point for agentic translations, and that this is a promising direction for translation, with significant headroom for further improvement, which is why we’re releasing this demonstration to encourage more discussion, experimentation, research and open-source contributions.If agentic translations can generate better results than traditional architectures (such as an end-to-end transformer that inputs a text and directly outputs a translation) -- which are often faster/cheaper to run than our approach here -- this also provides a mechanism to automatically generate training data (parallel text corpora) that can be used to further train and improve traditional algorithms. (See also this article in The Batch on using LLMs to generate training data.)Comments and suggestions for how to improve this are very welcome!"""})# 打印执行结果print(json.dumps(result["default"], indent=4, ensure_ascii=False))
输出:
[initial translation]: 翻译代理:使用反思工作流程的代理翻译这是一个用于机器翻译的反思代理工作流程的 Python 演示。主要步骤包括:提示大型语言模型(LLM)将文本从源语言翻译成目标语言;让 LLM 反思翻译结果,以提出改进的建设性建议;利用这些建议改进翻译。可定制性通过将 LLM 作为翻译引擎的核心,该系统具有高度的可操控性。例如,通过更改提示,使用此工作流程比传统的机器翻译(MT)系统更容易:修改输出的风格,例如正式/非正式;指定如何处理习语和特定术语,比如名字、技术术语和缩略语。例如,在提示中包含词汇表可以确保特定术语(如开源、H100 或 GPU)的翻译一致性;指定语言的特定地区用法或特定方言,以服务于目标受众。例如,拉丁美洲说的西班牙语与西班牙说的西班牙语不同;加拿大说的法语与法国说的法语不同。这并不是成熟的软件,是 Andrew 在过去几个月的周末玩弄翻译的结果,此外还有合作者(Joaquin Dominguez、Nedelina Teneva、John Santerre)帮助重构代码。根据我们使用传统翻译数据集的 BLEU 分数评估,这种工作流程有时与领先的商业产品具有竞争力,但有时也不如它们。然而,我们也有时能通过这种方法获得出色的结果(优于商业产品)。我们认为这只是代理翻译的起点,这是翻译的一个有前途的方向,具有显著的提升空间,这就是为什么我们发布这个演示以鼓励更多的讨论、实验、研究和开源贡献。如果代理翻译能够生成比传统架构(如输入文本并直接输出翻译的端到端变压器)更好的结果——而且通常比我们这里的方法更快/更便宜——这也提供了一种自动生成训练数据(平行文本语料库)的机制,可以用来进一步训练和改善传统算法。(参见 The Batch 上关于使用 LLM 生成训练数据的文章。)关于如何改进这一点的评论和建议非常欢迎![reflection]: 1. In the title "翻译代理:使用反思工作流程的代理翻译", consider rephrasing it to "翻译代理:基于反思工作流程的代理翻译" to emphasize that the translation is based on a reflection workflow.2. In the sentence "这是一个用于机器翻译的反思代理工作流程的 Python 演示", you could improve clarity by rearranging it to "这是一个演示机器翻译反思代理工作流程的 Python 程序".3. In "提示大型语言模型(LLM)将文本从源语言翻译成目标语言;", change "将文本从源语言翻译成目标语言" to "将文本从源语言翻译为目标语言" for better precision.4. The phrase "利用这些建议改进翻译" can be enhanced to "利用这些建议来改进翻译" for improved fluency.5. In "通过将 LLM 作为翻译引擎的核心,该系统具有高度的可操控性", consider rephrasing this to "通过将 LLM 作为翻译引擎的核心,系统具有高度的可定制性", which better captures the meaning of customizability presented in the source text.6. In the explanation of modifying output styles, change "正式/非正式" to "正式和非正式风格" to provide clearer structure.7. The phrase "这并不是成熟的软件" could be rephrased to "这并不是一个成熟的软件系统" to add clarity.8. The sentence "是 Andrew 在过去几个月的周末玩弄翻译的结果" can be improved to "是 Andrew 在过去几个月周末进行翻译实验的结果" for better fluency and to avoid colloquial language.9. Instead of "我们也有时能通过这种方法获得出色的结果(优于商业产品)", consider rephrasing it to "我们也时常能通过这种方法获得优于商业产品的出色结果" to enhance clarity and flow.10. In "这也提供了一种自动生成训练数据(平行文本语料库)的机制", consider replacing "这也提供了" with "这为我们提供了" to clarify the subject.11. The phrase "而且通常比我们这里的方法更快/更便宜" can be improved to "且通常比我们的这一方法更快且更经济" for better fluency.12. In "对于如何改进这一点的评论和建议非常欢迎!", changing "非常欢迎" to "热切欢迎" would create a more positive and engaging tone.[improve translation]: 翻译代理:基于反思工作流程的代理翻译 这是一个演示机器翻译反思代理工作流程的 Python 程序。主要步骤包括:提示大型语言模型(LLM)将文本从源语言翻译为目标语言; 让 LLM 反思翻译结果,以提出改进的建设性建议; 利用这些建议来改进翻译。 可定制性 通过将 LLM 作为翻译引擎的核心,系统具有高度的可定制性。例如,通过更改提示,使用此工作流程比传统的机器翻译(MT)系统更容易:修改输出的风格,例如正式和非正式风格; 指定如何处理习语和特定术语,比如名字、技术术语和缩略语。例如,在提示中包含词汇表可以确保特定术语(如开源、H100 或 GPU)的翻译一致性; 指定语言的特定地区用法或特定方言,以服务于目标受众。例如,拉丁美洲说的西班牙语与西班牙说的西班牙语不同;加拿大说的法语与法国说的法语不同。 这并不是一个成熟的软件系统,是 Andrew 在过去几个月周末进行翻译实验的结果,此外还有合作者(Joaquin Dominguez、Nedelina Teneva、John Santerre)帮助重构代码。 根据我们使用传统翻译数据集的 BLEU 分数评估,这种工作流程有时与领先的商业产品具有竞争力,但有时也不如它们。然而,我们也时常能通过这种方法获得优于商业产品的出色结果。我们认为这只是代理翻译的起点,这是翻译的一个有前途的方向,具有显著的提升空间,这就是为什么我们发布这个演示以鼓励更多的讨论、实验、研究和开源贡献。 如果代理翻译能够生成比传统架构(如输入文本并直接输出翻译的端到端变压器)更好的结果——且通常比我们的这一方法更快且更经济——这为我们提供了一种自动生成训练数据(平行文本语料库)的机制,可以用来进一步训练和改善传统算法。(参见 The Batch 上关于使用 LLM 生成训练数据的文章。) 关于如何改进这一点的评论和建议热切欢迎!{ "stage": "improve translation", "result": "翻译代理:基于反思工作流程的代理翻译 \n这是一个演示机器翻译反思代理工作流程的 Python 程序。主要步骤包括:\n\n提示大型语言模型(LLM)将文本从源语言翻译为目标语言; \n让 LLM 反思翻译结果,以提出改进的建设性建议; \n利用这些建议来改进翻译。 \n可定制性 \n通过将 LLM 作为翻译引擎的核心,系统具有高度的可定制性。例如,通过更改提示,使用此工作流程比传统的机器翻译(MT)系统更容易:\n\n修改输出的风格,例如正式和非正式风格; \n指定如何处理习语和特定术语,比如名字、技术术语和缩略语。例如,在提示中包含词汇表可以确保特定术语(如开源、H100 或 GPU)的翻译一致性; \n指定语言的特定地区用法或特定方言,以服务于目标受众。例如,拉丁美洲说的西班牙语与西班牙说的西班牙语不同;加拿大说的法语与法国说的法语不同。 \n这并不是一个成熟的软件系统,是 Andrew 在过去几个月周末进行翻译实验的结果,此外还有合作者(Joaquin Dominguez、Nedelina Teneva、John Santerre)帮助重构代码。 \n\n根据我们使用传统翻译数据集的 BLEU 分数评估,这种工作流程有时与领先的商业产品具有竞争力,但有时也不如它们。然而,我们也时常能通过这种方法获得优于商业产品的出色结果。我们认为这只是代理翻译的起点,这是翻译的一个有前途的方向,具有显著的提升空间,这就是为什么我们发布这个演示以鼓励更多的讨论、实验、研究和开源贡献。 \n\n如果代理翻译能够生成比传统架构(如输入文本并直接输出翻译的端到端变压器)更好的结果——且通常比我们的这一方法更快且更经济——这为我们提供了一种自动生成训练数据(平行文本语料库)的机制,可以用来进一步训练和改善传统算法。(参见 The Batch 上关于使用 LLM 生成训练数据的文章。) \n\n关于如何改进这一点的评论和建议热切欢迎!"}
也许有人会说只是一个翻译,审核,修改的流程要写这么多代码,太麻烦了,有没有更简单的方式?有,那就是COT
另一种实现方式:COT
import jsonimport Agentlyimport os # 将模型请求配置设置到agent工厂,后续工厂创建的agent对象都可以继承这个配置agent_factory = ( Agently.AgentFactory(is_debug=True) .set_settings("current_model", "OpenAI") .set_settings("model.OpenAI.url", os.environ.get("OPENAI_API_BASE")) .set_settings("model.OpenAI.auth", { "api_key": os.environ.get("OPENAI_API_KEY") }) .set_settings("model.OpenAI.options", { "model": "gpt-4o-mini" }))agent = agent_factory.create_agent()result = ( agent.input({ "source_lang": "English", "target_lang": "中文", "source_text": """Translation Agent: Agentic translation using reflection workflow This is a Python demonstration of a reflection agentic workflow for machine translation. The main steps are: Prompt an LLM to translate a text from source_language to target_language; Have the LLM reflect on the translation to come up with constructive suggestions for improving it; Use the suggestions to improve the translation. Customizability By using an LLM as the heart of the translation engine, this system is highly steerable. For example, by changing the prompts, it is easier using this workflow than a traditional machine translation (MT) system to: Modify the output's style, such as formal/informal. Specify how to handle idioms and special terms like names, technical terms, and acronyms. For example, including a glossary in the prompt lets you make sure particular terms (such as open source, H100 or GPU) are translated consistently. Specify specific regional use of the language, or specific dialects, to serve a target audience. For example, Spanish spoken in Latin America is different from Spanish spoken in Spain; French spoken in Canada is different from how it is spoken in France. This is not mature software, and is the result of Andrew playing around with translations on weekends the past few months, plus collaborators (Joaquin Dominguez, Nedelina Teneva, John Santerre) helping refactor the code. According to our evaluations using BLEU score on traditional translation datasets, this workflow is sometimes competitive with, but also sometimes worse than, leading commercial offerings. However, we’ve also occasionally gotten fantastic results (superior to commercial offerings) with this approach. We think this is just a starting point for agentic translations, and that this is a promising direction for translation, with significant headroom for further improvement, which is why we’re releasing this demonstration to encourage more discussion, experimentation, research and open-source contributions. If agentic translations can generate better results than traditional architectures (such as an end-to-end transformer that inputs a text and directly outputs a translation) -- which are often faster/cheaper to run than our approach here -- this also provides a mechanism to automatically generate training data (parallel text corpora) that can be used to further train and improve traditional algorithms. (See also this article in The Batch on using LLMs to generate training data.) Comments and suggestions for how to improve this are very welcome!""" }) .output({ "first_translation":('str',"将{input.source_text}从{input.source_lang}翻译成{input.target_lang}"), "reflection":('str',"""你现在需要将翻译角色变更为翻译校验角色,根据以下原则给出翻译修订意见: 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 {input.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. """), "final_translation":( 'str','基于{input.source_text},{first_translation}和{reflection}的修改建议,给出最终的翻译结果' ) }).start())
输出:
[Request Data] { "stream": true, "messages": [ { "role": "user", "content": "# [INPUT]:\nsource_lang: English\ntarget_lang: 中文\nsource_text: "Translation Agent: Agentic translation using reflection workflow\n \\n \ This is a Python demonstration of a reflection agentic workflow for machine\\n \ translation. The main steps are:\n\n Prompt an LLM to translate a text\\n \ from source_language to target_language;\n Have the LLM reflect on the\\n \ translation to come up with constructive suggestions for improving it;\n \\n \ Use the suggestions to improve the translation.\n Customizability\n \\n \ By using an LLM as the heart of the translation engine, this system is highly\\n \ steerable. For example, by changing the prompts, it is easier using this workflow\\n \ than a traditional machine translation (MT) system to:\n\n Modify the output's\\n \ style, such as formal/informal.\n Specify how to handle idioms and special\\n \ terms like names, technical terms, and acronyms. For example, including a glossary\\n \ in the prompt lets you make sure particular terms (such as open source, H100 or\\n \ GPU) are translated consistently.\n Specify specific regional use of the\\n \ language, or specific dialects, to serve a target audience. For example, Spanish\\n \ spoken in Latin America is different from Spanish spoken in Spain; French spoken\\n \ in Canada is different from how it is spoken in France.\n This is not mature\\n \ software, and is the result of Andrew playing around with translations on weekends\\n \ the past few months, plus collaborators (Joaquin Dominguez, Nedelina Teneva, John\\n \ Santerre) helping refactor the code.\n\n According to our evaluations using\\n \ BLEU score on traditional translation datasets, this workflow is sometimes competitive\\n \ with, but also sometimes worse than, leading commercial offerings. However, we’ve\\n \ also occasionally gotten fantastic results (superior to commercial offerings)\\n \ with this approach. We think this is just a starting point for agentic translations,\\n \ and that this is a promising direction for translation, with significant headroom\\n \ for further improvement, which is why we’re releasing this demonstration to encourage\\n \ more discussion, experimentation, research and open-source contributions.\n\n\\n \ If agentic translations can generate better results than traditional architectures\\n \ (such as an end-to-end transformer that inputs a text and directly outputs a translation)\\n \ -- which are often faster/cheaper to run than our approach here -- this also provides\\n \ a mechanism to automatically generate training data (parallel text corpora) that\\n \ can be used to further train and improve traditional algorithms. (See also this\\n \ article in The Batch on using LLMs to generate training data.)\n\n Comments\\n \ and suggestions for how to improve this are very welcome!"\n\n\n# [OUTPUT REQUIREMENT]:\n## TYPE:\nJSON can be parsed in Python\n## FORMAT:\n{\n\t"first_translation": <str>,//将{input.source_text}从{input.source_lang}翻译成{input.target_lang}\n\t"reflection": <str>,//你现在需要将翻译角色变更为翻译校验角色,根据以下原则给出翻译修订意见:\n 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 {input.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\n Write a list of specific, helpful and constructive suggestions for improving the translation.\n Each suggestion should address one specific part of the translation.\n Output only the suggestions and nothing else.\n \n\t"final_translation": <str>,//基于{input.source_text},{first_translation}和{reflection}的修改建议,给出最终的翻译结果\n}\n\n\n[OUTPUT]:\n" } ], "model": "gpt-4o-mini"}[Realtime Response]{"first_translation": "翻译代理:基于反思的代理翻译工作流\n这是一个使用反思代理工作流进行机器翻译的Python示例。主要步骤包括:\n\n提示大型语言模型(LLM)将文本从源语言翻译为目标语言;\n让LLM对翻译进行反思,提出改进建议;\n使用这些建议来改善翻译。\n\n可定制性\n通过将LLM作为翻译引擎的核心,系统具有高度可引导性。例如,通过更改提示,这种工作流比传统的机器翻译(MT)系统更容易:\n\n修改输出的风格,如正式/非正式。\n指定如何处理习语和特殊术语,如名称、技术术语和缩略语。例如,包含术语表在提示中可以确保特定术语的翻译(如开源、H100或GPU)的一致性。\n指定语言的特定地区使用或特定方言,以服务目标受众。例如,拉丁美洲使用的西班牙语与西班牙使用的西班牙语不同;加拿大的法语与法国的法语也不同。\n\n这不是成熟的软件,而是安德鲁在过去几个月的周末玩翻译的结果,加上一些合作者(华金·多明戈斯、内德利娜·特内娃、约翰·桑特尔)帮助重构代码。\n\n根据我们使用BLEU评分对传统翻译数据集的评估,这种工作流有时在竞争上与领先的商业产品相当,但有时也更差。不过,我们偶尔也得到了很棒的结果(优于商业产品)。我们认为这只是代理翻译的开始,这是一种有前景的翻译方向,还有很大的改进空间,这也是我们发布这个示范的原因,以鼓励更多的讨论、实验、研究和开源贡献。\n\n如果代理翻译能够产生比传统架构(例如输入文本并直接输出翻译的端到端变换器)更好的结果——这些结果通常比我们这里的方法运行得更快/更便宜——这还提供了一个机制,可以自动生成训练数据(平行文本语料库),以进一步训练和改善传统算法。(另请参见这篇关于使用LLM生成训练数据的The Batch文章。)\n\n欢迎提出改善建议和意见!","reflection": ["在翻译开始部分的'Translation Agent'翻译为'翻译代理'时,'代理'可能更好地翻译为'翻译代理商',以更符合中文的通用表达。","将'agentic translation'翻译为'代理翻译',可以考虑使用更符合中文习惯的表达,比如'智能代理翻译'。","'This is a Python demonstration of a reflection agentic workflow for machine translation.' 此句的翻译可以更流畅,建议翻译为'这是一个基于反思的智能代理工作流用于机器翻译的Python示例。'","'This is not mature software, and is the result of Andrew playing around with translations on weekends.'可以明确为'这并不是成熟软件,而是安德鲁在周末进行翻译实验的结果。'以确保流畅性。","在提到合作者时,保持一致性最好,建议增加'与华金·多明戈斯、内德利娜·特内娃和约翰·桑特尔等人合作',以便形成清晰的表述。","在描述BLEU得分的部分,添加'在'字样将其变为'根据我们在传统翻译数据集上使用BLEU评分的评估,'以增强语句的完整性。"],"final_translation": "翻译代理商:基于反思的智能代理翻译工作流\n这是一个基于反思的智能代理工作流用于机器翻译的Python示例。主要步骤包括:\n\n提示大型语言模型(LLM)将文本从源语言翻译为目标语言;\n让LLM对翻译进行反思,提出改进建议;\n使用这些建议来改善翻译。\n\n可定制性\n通过将LLM作为翻译引擎的核心,系统具有高度可引导性。例如,通过更改提示,这种工作流比传统的机器翻译系统更容易:\n\n修改输出的风格,如正式/非正式。\n指定如何处理习语和特殊术语,如名称、技术术语和缩略语。例如,包含术语表在提示中可以确保特定术语的翻译(如开源、H100或GPU)的一致性。\n指定语言的特定地区使用或特定方言,以服务目标受众。例如,拉丁美洲使用的西班牙语与西班牙使用的西班牙语不同;加拿大的法语与法国的法语也不同。\n\n这并不是成熟软件,而是安德鲁在周末进行翻译实验的结果,加上一些合作者与华金·多明戈斯、内德利娜·特内娃和约翰·桑特尔等人合作帮助重构代码。\n\n根据我们在传统翻译数据集上使用BLEU评分的评估,这种工作流有时在竞争上与领先的商业产品相当,但有时也更差。不过,我们偶尔也得到了很棒的结果(优于商业产品)。我们认为这只是代理翻译的开始,这是一种有前景的翻译方向,还有很大的改进空间,这也是我们发布这个示范的原因,以鼓励更多的讨论、实验、研究和开源贡献。\n\n如果代理翻译能够产生比传统架构(例如输入文本并直接输出翻译的端到端变换器)更好的结果——这些结果通常比我们这里的方法运行得更快/更便宜——这还提供了一个机制,可以自动生成训练数据(平行文本语料库),以进一步训练和改善传统算法。(另请参见这篇关于使用LLM生成训练数据的The Batch文章。)\n\n欢迎提出改善建议和意见!"}--------------------------[Final Reply] {"first_translation": "翻译代理:基于反思的代理翻译工作流\n这是一个使用反思代理工作流进行机器翻译的Python示例。主要步骤包括:\n\n提示大型语言模型(LLM)将文本从源语言翻译为目标语言;\n让LLM对翻译进行反思,提出改进建议;\n使用这些建议来改善翻译。\n\n可定制性\n通过将LLM作为翻译引擎的核心,系统具有高度可引导性。例如,通过更改提示,这种工作流比传统的机器翻译(MT)系统更容易:\n\n修改输出的风格,如正式/非正式。\n指定如何处理习语和特殊术语,如名称、技术术语和缩略语。例如,包含术语表在提示中可以确保特定术语的翻译(如开源、H100或GPU)的一致性。\n指定语言的特定地区使用或特定方言,以服务目标受众。例如,拉丁美洲使用的西班牙语与西班牙使用的西班牙语不同;加拿大的法语与法国的法语也不同。\n\n这不是成熟的软件,而是安德鲁在过去几个月的周末玩翻译的结果,加上一些合作者(华金·多明戈斯、内德利娜·特内娃、约翰·桑特尔)帮助重构代码。\n\n根据我们使用BLEU评分对传统翻译数据集的评估,这种工作流有时在竞争上与领先的商业产品相当,但有时也更差。不过,我们偶尔也得到了很棒的结果(优于商业产品)。我们认为这只是代理翻译的开始,这是一种有前景的翻译方向,还有很大的改进空间,这也是我们发布这个示范的原因,以鼓励更多的讨论、实验、研究和开源贡献。\n\n如果代理翻译能够产生比传统架构(例如输入文本并直接输出翻译的端到端变换器)更好的结果——这些结果通常比我们这里的方法运行得更快/更便宜——这还提供了一个机制,可以自动生成训练数据(平行文本语料库),以进一步训练和改善传统算法。(另请参见这篇关于使用LLM生成训练数据的The Batch文章。)\n\n欢迎提出改善建议和意见!","reflection": ["在翻译开始部分的'Translation Agent'翻译为'翻译代理'时,'代理'可能更好地翻译为'翻译代理商',以更符合中文的通用表达。","将'agentic translation'翻译为'代理翻译',可以考虑使用更符合中文习惯的表达,比如'智能代理翻译'。","'This is a Python demonstration of a reflection agentic workflow for machine translation.' 此句的翻译可以更流畅,建议翻译为'这是一个基于反思的智能代理工作流用于机器翻译的Python示例。'","'This is not mature software, and is the result of Andrew playing around with translations on weekends.'可以明确为'这并不是成熟软件,而是安德鲁在周末进行翻译实验的结果。'以确保流畅性。","在提到合作者时,保持一致性最好,建议增加'与华金·多明戈斯、内德利娜·特内娃和约翰·桑特尔等人合作',以便形成清晰的表述。","在描述BLEU得分的部分,添加'在'字样将其变为'根据我们在传统翻译数据集上使用BLEU评分的评估,'以增强语句的完整性。"],"final_translation": "翻译代理商:基于反思的智能代理翻译工作流\n这是一个基于反思的智能代理工作流用于机器翻译的Python示例。主要步骤包括:\n\n提示大型语言模型(LLM)将文本从源语言翻译为目标语言;\n让LLM对翻译进行反思,提出改进建议;\n使用这些建议来改善翻译。\n\n可定制性\n通过将LLM作为翻译引擎的核心,系统具有高度可引导性。例如,通过更改提示,这种工作流比传统的机器翻译系统更容易:\n\n修改输出的风格,如正式/非正式。\n指定如何处理习语和特殊术语,如名称、技术术语和缩略语。例如,包含术语表在提示中可以确保特定术语的翻译(如开源、H100或GPU)的一致性。\n指定语言的特定地区使用或特定方言,以服务目标受众。例如,拉丁美洲使用的西班牙语与西班牙使用的西班牙语不同;加拿大的法语与法国的法语也不同。\n\n这并不是成熟软件,而是安德鲁在周末进行翻译实验的结果,加上一些合作者与华金·多明戈斯、内德利娜·特内娃和约翰·桑特尔等人合作帮助重构代码。\n\n根据我们在传统翻译数据集上使用BLEU评分的评估,这种工作流有时在竞争上与领先的商业产品相当,但有时也更差。不过,我们偶尔也得到了很棒的结果(优于商业产品)。我们认为这只是代理翻译的开始,这是一种有前景的翻译方向,还有很大的改进空间,这也是我们发布这个示范的原因,以鼓励更多的讨论、实验、研究和开源贡献。\n\n如果代理翻译能够产生比传统架构(例如输入文本并直接输出翻译的端到端变换器)更好的结果——这些结果通常比我们这里的方法运行得更快/更便宜——这还提供了一个机制,可以自动生成训练数据(平行文本语料库),以进一步训练和改善传统算法。(另请参见这篇关于使用LLM生成训练数据的The Batch文章。)\n\n欢迎提出改善建议和意见!"} --------------------------[Cleaned JSON String]: {"first_translation": "翻译代理:基于反思的代理翻译工作流\n这是一个使用反思代理工作流进行机器翻译的Python示例。主要步骤包括:\n\n提示大型语言模型(LLM)将文本从源语言翻译为目标语言;\n让LLM对翻译进行反思,提出改进建议;\n使用这些建议来改善翻译。\n\n可定制性\n通过将LLM作为翻译引擎的核心,系统具有高度可引导性。例如,通过更改提示,这种工作流比传统的机器翻译(MT)系统更容易:\n\n修改输出的风格,如正式/非正式。\n指定如何处理习语和特殊术语,如名称、技术术语和缩略语。例如,包含术语表在提示中可以确保特定术语的翻译(如开源、H100或GPU)的一致性。\n指定语言的特定地区使用或特定方言,以服务目标受众。例如,拉丁美洲使用的西班牙语与西班牙使用的西班牙语不同;加拿大的法语与法国的法语也不同。\n\n这不是成熟的软件,而是安德鲁在过去几个月的周末玩翻译的结果,加上一些合作者(华金·多明戈斯、内德利娜·特内娃、约翰·桑特尔)帮助重构代码。\n\n根据我们使用BLEU评分对传统翻译数据集的评估,这种工作流有时在竞争上与领先的商业产品相当,但有时也更差。不过,我们偶尔也得到了很棒的结果(优于商业产品)。我们认为这只是代理翻译的开始,这是一种有前景的翻译方向,还有很大的改进空间,这也是我们发布这个示范的原因,以鼓励更多的讨论、实验、研究和开源贡献。\n\n如果代理翻译能够产生比传统架构(例如输入文本并直接输出翻译的端到端变换器)更好的结果——这些结果通常比我们这里的方法运行得更快/更便宜——这还提供了一个机制,可以自动生成训练数据(平行文本语料库),以进一步训练和改善传统算法。(另请参见这篇关于使用LLM生成训练数据的The Batch文章。)\n\n欢迎提出改善建议和意见!","reflection": ["在翻译开始部分的'Translation Agent'翻译为'翻译代理'时,'代理'可能更好地翻译为'翻译代理商',以更符合中文的通用表达。","将'agentic translation'翻译为'代理翻译',可以考虑使用更符合中文习惯的表达,比如'智能代理翻译'。","'This is a Python demonstration of a reflection agentic workflow for machine translation.' 此句的翻译可以更流畅,建议翻译为'这是一个基于反思的智能代理工作流用于机器翻译的Python示例。'","'This is not mature software, and is the result of Andrew playing around with translations on weekends.'可以明确为'这并不是成熟软件,而是安德鲁在周末进行翻译实验的结果。'以确保流畅性。","在提到合作者时,保持一致性最好,建议增加'与华金·多明戈斯、内德利娜·特内娃和约翰·桑特尔等人合作',以便形成清晰的表述。","在描述BLEU得分的部分,添加'在'字样将其变为'根据我们在传统翻译数据集上使用BLEU评分的评估,'以增强语句的完整性。"],"final_translation": "翻译代理商:基于反思的智能代理翻译工作流\n这是一个基于反思的智能代理工作流用于机器翻译的Python示例。主要步骤包括:\n\n提示大型语言模型(LLM)将文本从源语言翻译为目标语言;\n让LLM对翻译进行反思,提出改进建议;\n使用这些建议来改善翻译。\n\n可定制性\n通过将LLM作为翻译引擎的核心,系统具有高度可引导性。例如,通过更改提示,这种工作流比传统的机器翻译系统更容易:\n\n修改输出的风格,如正式/非正式。\n指定如何处理习语和特殊术语,如名称、技术术语和缩略语。例如,包含术语表在提示中可以确保特定术语的翻译(如开源、H100或GPU)的一致性。\n指定语言的特定地区使用或特定方言,以服务目标受众。例如,拉丁美洲使用的西班牙语与西班牙使用的西班牙语不同;加拿大的法语与法国的法语也不同。\n\n这并不是成熟软件,而是安德鲁在周末进行翻译实验的结果,加上一些合作者与华金·多明戈斯、内德利娜·特内娃和约翰·桑特尔等人合作帮助重构代码。\n\n根据我们在传统翻译数据集上使用BLEU评分的评估,这种工作流有时在竞争上与领先的商业产品相当,但有时也更差。不过,我们偶尔也得到了很棒的结果(优于商业产品)。我们认为这只是代理翻译的开始,这是一种有前景的翻译方向,还有很大的改进空间,这也是我们发布这个示范的原因,以鼓励更多的讨论、实验、研究和开源贡献。\n\n如果代理翻译能够产生比传统架构(例如输入文本并直接输出翻译的端到端变换器)更好的结果——这些结果通常比我们这里的方法运行得更快/更便宜——这还提供了一个机制,可以自动生成训练数据(平行文本语料库),以进一步训练和改善传统算法。(另请参见这篇关于使用LLM生成训练数据的The Batch文章。)\n\n欢迎提出改善建议和意见!"}
可以看到,也可以有同样的效果
总结
文章看到这里你会发现一个问题,就是关于Agent的应用形式非常多,基于协作的,基于模型能力的等等,并没有一个确定的范式出现,其实总结下来目前至少有下面这些:
应用思路举例
- CoT/简单工作流附加Function Calling的单次请求基于SOP的复杂工作流自规划
应用场景举例:
- 文案生成Auto CoderNL2DB智能家居智能座舱
项目举例:
也许就像吴恩达所说:“与其争论哪些工作才算是真正的 Agent,不如承认系统可以具有不同程度的 Agentic 特性。”
我们更应该关注的不是如何搞一个符合范式的Agent出来,而是应该把注意力放在如何应用好模型能力解决实际问题以及通过工程化的方式让模型变的更可控,毕竟现阶段通过一两次模型调用就解决复杂问题还是不现实。