Skip to content

Commit 2f6de00

Browse files
committed
优化多个示例文件中的中文翻译和格式,添加模型设置
1 parent b9e9f14 commit 2f6de00

16 files changed

+532
-386
lines changed

examples/agent_patterns/README.md

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,54 @@
1-
# Common agentic patterns
1+
# 常见的 agent 模式
22

3-
This folder contains examples of different common patterns for agents.
3+
本文件夹包含了不同常见 agent 模式的示例。
44

5-
## Deterministic flows
5+
## 确定性流程
66

7-
A common tactic is to break down a task into a series of smaller steps. Each task can be performed by an agent, and the output of one agent is used as input to the next. For example, if your task was to generate a story, you could break it down into the following steps:
7+
一个常见的策略是将任务分解成一系列小步骤。每个步骤可以由一个 agent 执行,一个 agent 的输出会作为下一个 agent 的输入。例如,如果你的任务是生成一个故事,你可以将其分解为以下步骤:
88

9-
1. Generate an outline
10-
2. Generate the story
11-
3. Generate the ending
9+
1. 生成大纲
10+
2. 生成故事内容
11+
3. 生成结尾
1212

13-
Each of these steps can be performed by an agent. The output of one agent is used as input to the next.
13+
这些步骤每一个都可以由一个 agent 来执行。一个 agent 的输出会作为下一个 agent 的输入。
1414

15-
See the [`deterministic.py`](./deterministic.py) file for an example of this.
15+
查看 [`deterministic.py`](./deterministic.py) 文件获取这种模式的示例。
1616

17-
## Handoffs and routing
17+
## 任务交接和路由
1818

19-
In many situations, you have specialized sub-agents that handle specific tasks. You can use handoffs to route the task to the right agent.
19+
在很多情况下,你会有专门处理特定任务的子 agent。你可以使用任务交接来将任务路由到合适的 agent
2020

21-
For example, you might have a frontline agent that receives a request, and then hands off to a specialized agent based on the language of the request.
22-
See the [`routing.py`](./routing.py) file for an example of this.
21+
例如,你可能有一个前线 agent 接收请求,然后根据请求的语言将任务交给专门的 agent
22+
查看 [`routing.py`](./routing.py) 文件获取这种模式的示例。
2323

24-
## Agents as tools
24+
## 将 agent 作为工具
2525

26-
The mental model for handoffs is that the new agent "takes over". It sees the previous conversation history, and owns the conversation from that point onwards. However, this is not the only way to use agents. You can also use agents as a tool - the tool agent goes off and runs on its own, and then returns the result to the original agent.
26+
任务交接的思维模型是新 agent "接管"任务。它可以看到之前的对话历史,并从那一刻起掌控对话。但这并不是使用 agent 的唯一方式。你也可以将 agent 作为工具使用 - 作为工具的 agent 独立运行,然后将结果返回给原始 agent
2727

28-
For example, you could model the translation task above as tool calls instead: rather than handing over to the language-specific agent, you could call the agent as a tool, and then use the result in the next step. This enables things like translating multiple languages at once.
28+
例如,你可以将上面的翻译任务建模为工具调用:不是将任务交给特定语言的 agent,而是将其作为工具调用,然后在下一步使用结果。这样可以实现同时翻译多种语言等功能。
2929

30-
See the [`agents_as_tools.py`](./agents_as_tools.py) file for an example of this.
30+
查看 [`agents_as_tools.py`](./agents_as_tools.py) 文件获取这种模式的示例。
3131

32-
## LLM-as-a-judge
32+
## LLM 作为评判者
3333

34-
LLMs can often improve the quality of their output if given feedback. A common pattern is to generate a response using a model, and then use a second model to provide feedback. You can even use a small model for the initial generation and a larger model for the feedback, to optimize cost.
34+
如果给出反馈,LLM 通常可以提高其输出质量。一个常见的模式是使用一个模型生成响应,然后使用第二个模型提供反馈。你甚至可以使用较小的模型进行初始生成,使用较大的模型进行反馈,以优化成本。
3535

36-
For example, you could use an LLM to generate an outline for a story, and then use a second LLM to evaluate the outline and provide feedback. You can then use the feedback to improve the outline, and repeat until the LLM is satisfied with the outline.
36+
例如,你可以使用 LLM 生成故事的大纲,然后使用第二个 LLM 评估大纲并提供反馈。然后你可以使用这些反馈来改进大纲,重复这个过程直到 LLM 对大纲满意为止。
3737

38-
See the [`llm_as_a_judge.py`](./llm_as_a_judge.py) file for an example of this.
38+
查看 [`llm_as_a_judge.py`](./llm_as_a_judge.py) 文件获取这种模式的示例。
3939

40-
## Parallelization
40+
## 并行化
4141

42-
Running multiple agents in parallel is a common pattern. This can be useful for both latency (e.g. if you have multiple steps that don't depend on each other) and also for other reasons e.g. generating multiple responses and picking the best one.
42+
并行运行多个 agent 是一种常见模式。这对于延迟很有用(例如,如果你有多个相互之间没有依赖关系的步骤),还有其他原因,例如生成多个响应并选择最佳响应。
4343

44-
See the [`parallelization.py`](./parallelization.py) file for an example of this. It runs a translation agent multiple times in parallel, and then picks the best translation.
44+
查看 [`parallelization.py`](./parallelization.py) 文件获取这种模式的示例。它多次并行运行翻译 agent,然后选择最佳翻译。
4545

46-
## Guardrails
46+
## 保护措施
4747

48-
Related to parallelization, you often want to run input guardrails to make sure the inputs to your agents are valid. For example, if you have a customer support agent, you might want to make sure that the user isn't trying to ask for help with a math problem.
48+
与并行化相关,你通常希望运行输入保护措施以确保输入有效。例如,如果你有一个客户支持 agent,你可能希望确保用户不是在寻求数学问题的帮助。
4949

50-
You can definitely do this without any special Agents SDK features by using parallelization, but we support a special guardrail primitive. Guardrails can have a "tripwire" - if the tripwire is triggered, the agent execution will immediately stop and a `GuardrailTripwireTriggered` exception will be raised.
50+
你可以通过并行化来做到这一点,而无需任何特殊的 Agents SDK 功能,但我们支持一种特殊的保护措施原语。保护措施可以有一个 "触发器" - 如果触发器被触发,agent 执行将立即停止,并引发 `GuardrailTripwireTriggered` 异常。
5151

52-
This is really useful for latency: for example, you might have a very fast model that runs the guardrail and a slow model that runs the actual agent. You wouldn't want to wait for the slow model to finish, so guardrails let you quickly reject invalid inputs.
52+
这对于延迟非常有用:例如,你可能有一个非常快速的模型来运行保护措施,一个较慢的模型来运行实际的 agent。你不希望等待慢模型完成,因此保护措施可以让你快速拒绝无效输入。
5353

54-
See the [`input_guardrails.py`](./input_guardrails.py) and [`output_guardrails.py`](./output_guardrails.py) files for examples.
54+
查看 [`input_guardrails.py`](./input_guardrails.py) [`output_guardrails.py`](./output_guardrails.py) 文件获取这种模式的示例。

examples/agent_patterns/agents_as_tools.py

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,89 @@
11
import asyncio
22

33
from agents import Agent, ItemHelpers, MessageOutputItem, Runner, trace
4+
from agents.extensions.visualization import draw_graph
5+
6+
from examples.models import get_agent_chat_model
47

58
"""
6-
This example shows the agents-as-tools pattern. The frontline agent receives a user message and
7-
then picks which agents to call, as tools. In this case, it picks from a set of translation
8-
agents.
9+
此示例展示了代理作为工具的模式。前线代理接收用户消息,然后选择调用哪些代理作为工具。
10+
在这种情况下,它从一组翻译代理中进行选择。
911
"""
1012

13+
deepseek = get_agent_chat_model('deepseek-v3')
14+
1115
spanish_agent = Agent(
1216
name="spanish_agent",
13-
instructions="You translate the user's message to Spanish",
14-
handoff_description="An english to spanish translator",
17+
instructions="您将用户的消息翻译成西班牙语",
18+
handoff_description="英语到西班牙语的翻译器",
19+
model=deepseek,
1520
)
1621

1722
french_agent = Agent(
1823
name="french_agent",
19-
instructions="You translate the user's message to French",
20-
handoff_description="An english to french translator",
24+
instructions="您将用户的消息翻译成法语",
25+
handoff_description="英语到法语的翻译器",
26+
model=deepseek,
2127
)
2228

2329
italian_agent = Agent(
2430
name="italian_agent",
25-
instructions="You translate the user's message to Italian",
26-
handoff_description="An english to italian translator",
31+
instructions="您将用户的消息翻译成意大利语",
32+
handoff_description="英语到意大利语的翻译器",
33+
model=deepseek,
2734
)
2835

2936
orchestrator_agent = Agent(
3037
name="orchestrator_agent",
3138
instructions=(
32-
"You are a translation agent. You use the tools given to you to translate."
33-
"If asked for multiple translations, you call the relevant tools in order."
34-
"You never translate on your own, you always use the provided tools."
39+
"您是一个翻译代理。您使用提供给您的工具进行翻译。"
40+
"如果被要求进行多重翻译,您按顺序调用相关工具。"
41+
"您从不自己翻译,总是使用提供的工具。"
3542
),
3643
tools=[
3744
spanish_agent.as_tool(
3845
tool_name="translate_to_spanish",
39-
tool_description="Translate the user's message to Spanish",
46+
tool_description="将用户的消息翻译成西班牙语",
4047
),
4148
french_agent.as_tool(
4249
tool_name="translate_to_french",
43-
tool_description="Translate the user's message to French",
50+
tool_description="将用户的消息翻译成法语",
4451
),
4552
italian_agent.as_tool(
4653
tool_name="translate_to_italian",
47-
tool_description="Translate the user's message to Italian",
54+
tool_description="将用户的消息翻译成意大利语",
4855
),
4956
],
57+
model=deepseek,
5058
)
5159

60+
draw_graph(orchestrator_agent).view()
61+
5262
synthesizer_agent = Agent(
5363
name="synthesizer_agent",
54-
instructions="You inspect translations, correct them if needed, and produce a final concatenated response.",
64+
instructions="您检查翻译,必要时进行更正,并生成最终的合并响应。",
65+
model=deepseek,
5566
)
5667

5768

5869
async def main():
59-
msg = input("Hi! What would you like translated, and to which languages? ")
70+
msg = input("你好!你想翻译什么内容,以及翻译成哪些语言?")
6071

61-
# Run the entire orchestration in a single trace
62-
with trace("Orchestrator evaluator"):
72+
# 在单个追踪中运行整个编排流程
73+
with trace("编排器评估器"):
6374
orchestrator_result = await Runner.run(orchestrator_agent, msg)
6475

6576
for item in orchestrator_result.new_items:
6677
if isinstance(item, MessageOutputItem):
6778
text = ItemHelpers.text_message_output(item)
6879
if text:
69-
print(f" - Translation step: {text}")
80+
print(f" - 翻译步骤: {text}")
7081

7182
synthesizer_result = await Runner.run(
7283
synthesizer_agent, orchestrator_result.to_input_list()
7384
)
7485

75-
print(f"\n\nFinal response:\n{synthesizer_result.final_output}")
86+
print(f"\n\n最终回复:\n{synthesizer_result.final_output}")
7687

7788

7889
if __name__ == "__main__":

examples/agent_patterns/deterministic.py

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,25 @@
44

55
from agents import Agent, Runner, trace
66

7+
from examples.models import get_agent_chat_model
8+
79
"""
8-
This example demonstrates a deterministic flow, where each step is performed by an agent.
9-
1. The first agent generates a story outline
10-
2. We feed the outline into the second agent
11-
3. The second agent checks if the outline is good quality and if it is a scifi story
12-
4. If the outline is not good quality or not a scifi story, we stop here
13-
5. If the outline is good quality and a scifi story, we feed the outline into the third agent
14-
6. The third agent writes the story
10+
本示例演示了一个确定性流程,每一步都由一个 agent 执行。
11+
1. 第一个 agent 生成故事大纲
12+
2. 我们将大纲传递给第二个 agent
13+
3. 第二个 agent 检查大纲的质量,并判断其是否为科幻故事
14+
4. 如果大纲质量不好或不是科幻故事,则流程在此结束
15+
5. 如果大纲质量好且是科幻故事,则将大纲传递给第三个 agent
16+
6. 第三个 agent 根据大纲写出故事
1517
"""
1618

19+
gpt = get_agent_chat_model('gpt')
20+
deepseek = get_agent_chat_model('deepseek-v3')
21+
1722
story_outline_agent = Agent(
1823
name="story_outline_agent",
19-
instructions="Generate a very short story outline based on the user's input.",
24+
instructions="根据用户输入生成一个非常简短的故事大纲。",
25+
model=deepseek,
2026
)
2127

2228

@@ -27,53 +33,55 @@ class OutlineCheckerOutput(BaseModel):
2733

2834
outline_checker_agent = Agent(
2935
name="outline_checker_agent",
30-
instructions="Read the given story outline, and judge the quality. Also, determine if it is a scifi story.",
36+
instructions="阅读给定的故事大纲,并判断其质量。同时判断这是否是一个科幻故事。",
3137
output_type=OutlineCheckerOutput,
38+
model=gpt,
3239
)
3340

3441
story_agent = Agent(
3542
name="story_agent",
36-
instructions="Write a short story based on the given outline.",
43+
instructions="根据给定的大纲写一个简短的故事。",
3744
output_type=str,
45+
model=deepseek,
3846
)
3947

4048

4149
async def main():
42-
input_prompt = input("What kind of story do you want? ")
50+
input_prompt = input("你想要什么样的故事?")
4351

44-
# Ensure the entire workflow is a single trace
45-
with trace("Deterministic story flow"):
46-
# 1. Generate an outline
52+
# 确保整个流程在一个 trace
53+
with trace("确定性故事流程"):
54+
# 1. 生成大纲
4755
outline_result = await Runner.run(
4856
story_outline_agent,
4957
input_prompt,
5058
)
51-
print("Outline generated")
59+
print("大纲已生成")
5260

53-
# 2. Check the outline
61+
# 2. 检查大纲
5462
outline_checker_result = await Runner.run(
5563
outline_checker_agent,
5664
outline_result.final_output,
5765
)
5866

59-
# 3. Add a gate to stop if the outline is not good quality or not a scifi story
67+
# 3. 如果大纲质量不好或不是科幻故事,则流程在此结束
6068
assert isinstance(outline_checker_result.final_output, OutlineCheckerOutput)
6169
if not outline_checker_result.final_output.good_quality:
62-
print("Outline is not good quality, so we stop here.")
70+
print("大纲质量不好,因此流程在此结束。")
6371
exit(0)
6472

6573
if not outline_checker_result.final_output.is_scifi:
66-
print("Outline is not a scifi story, so we stop here.")
74+
print("大纲不是科幻故事,因此流程在此结束。")
6775
exit(0)
6876

69-
print("Outline is good quality and a scifi story, so we continue to write the story.")
77+
print("大纲质量良好且是科幻故事,因此我们继续写故事。")
7078

71-
# 4. Write the story
79+
# 4. 写故事
7280
story_result = await Runner.run(
7381
story_agent,
7482
outline_result.final_output,
7583
)
76-
print(f"Story: {story_result.final_output}")
84+
print(f"故事: {story_result.final_output}")
7785

7886

7987
if __name__ == "__main__":

examples/agent_patterns/forcing_tool_use.py

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from __future__ import annotations
22

33
import asyncio
4+
import os
5+
import sys
46
from typing import Any, Literal
57

68
from pydantic import BaseModel
@@ -16,26 +18,24 @@
1618
function_tool,
1719
)
1820

21+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../')))
22+
23+
from examples.models import get_agent_chat_model
24+
1925
"""
20-
This example shows how to force the agent to use a tool. It uses `ModelSettings(tool_choice="required")`
21-
to force the agent to use any tool.
22-
23-
You can run it with 3 options:
24-
1. `default`: The default behavior, which is to send the tool output to the LLM. In this case,
25-
`tool_choice` is not set, because otherwise it would result in an infinite loop - the LLM would
26-
call the tool, the tool would run and send the results to the LLM, and that would repeat
27-
(because the model is forced to use a tool every time.)
28-
2. `first_tool_result`: The first tool result is used as the final output.
29-
3. `custom`: A custom tool use behavior function is used. The custom function receives all the tool
30-
results, and chooses to use the first tool result to generate the final output.
31-
32-
Usage:
26+
本示例展示了如何强制 agent 使用工具。它通过 `ModelSettings(tool_choice="required")` 强制 agent 必须使用某个工具。
27+
28+
你可以用三种方式运行它:
29+
1. `default`:默认行为,即将工具输出发送给 LLM。在这种情况下,`tool_choice` 没有设置,否则会导致无限循环——LLM 会一直调用工具,工具运行后又把结果发给 LLM,如此反复。
30+
2. `first_tool_result`:第一个工具结果会被用作最终输出。
31+
3. `custom`:使用自定义的工具使用行为函数。该自定义函数接收所有工具结果,并选择第一个工具结果作为最终输出。
32+
33+
用法:
3334
python examples/agent_patterns/forcing_tool_use.py -t default
3435
python examples/agent_patterns/forcing_tool_use.py -t first_tool
3536
python examples/agent_patterns/forcing_tool_use.py -t custom
3637
"""
3738

38-
3939
class Weather(BaseModel):
4040
city: str
4141
temperature_range: str
@@ -53,7 +53,7 @@ async def custom_tool_use_behavior(
5353
) -> ToolsToFinalOutputResult:
5454
weather: Weather = results[0].output
5555
return ToolsToFinalOutputResult(
56-
is_final_output=True, final_output=f"{weather.city} is {weather.conditions}."
56+
is_final_output=True, final_output=f"{weather.city} 的天气是 {weather.conditions}"
5757
)
5858

5959

@@ -67,17 +67,20 @@ async def main(tool_use_behavior: Literal["default", "first_tool", "custom"] = "
6767
elif tool_use_behavior == "custom":
6868
behavior = custom_tool_use_behavior
6969

70+
deepseek = get_agent_chat_model('deepseek-v3')
71+
7072
agent = Agent(
71-
name="Weather agent",
72-
instructions="You are a helpful agent.",
73+
name="天气 agent",
74+
instructions="你是一个乐于助人的 agent",
7375
tools=[get_weather],
7476
tool_use_behavior=behavior,
7577
model_settings=ModelSettings(
7678
tool_choice="required" if tool_use_behavior != "default" else None
7779
),
80+
model=deepseek,
7881
)
7982

80-
result = await Runner.run(agent, input="What's the weather in Tokyo?")
83+
result = await Runner.run(agent, input="东京的天气怎么样?")
8184
print(result.final_output)
8285

8386

@@ -91,9 +94,7 @@ async def main(tool_use_behavior: Literal["default", "first_tool", "custom"] = "
9194
type=str,
9295
required=True,
9396
choices=["default", "first_tool", "custom"],
94-
help="The behavior to use for tool use. Default will cause tool outputs to be sent to the model. "
95-
"first_tool_result will cause the first tool result to be used as the final output. "
96-
"custom will use a custom tool use behavior function.",
97+
help="工具使用行为。default 表示工具输出会被发送给模型。first_tool_result 表示第一个工具结果会被用作最终输出。custom 表示使用自定义的工具使用行为函数。",
9798
)
9899
args = parser.parse_args()
99100
asyncio.run(main(args.tool_use_behavior))

0 commit comments

Comments
 (0)