快速入门
创建项目和虚拟环境
你只需执行一次此操作。
激活虚拟环境
每次启动新的终端会话时都要执行此操作。
安装Agents SDK
设置OpenAI API密钥
如果你还没有,请按照这些说明创建OpenAI API密钥。
创建你的第一个智能体
智能体通过指令、名称和可选配置(如model_config
)进行定义。
from agents import Agent
agent = Agent(
name="数学辅导老师",
instructions="你帮助解决数学问题。在每一步都解释你的推理过程,并包含示例",
)
添加更多智能体
可以用相同的方式定义其他智能体。handoff_descriptions
为确定交接路由提供了更多上下文。
from agents import Agent
history_tutor_agent = Agent(
name="历史辅导老师",
handoff_description="历史问题专家智能体",
instructions="你协助解答历史相关查询。清晰地解释重要事件和背景。",
)
math_tutor_agent = Agent(
name="数学辅导老师",
handoff_description="数学问题专家智能体",
instructions="你帮助解决数学问题。在每一步都解释你的推理过程,并包含示例",
)
定义交接
在每个智能体上,你可以定义一个传出交接选项清单,智能体可以从中选择,以决定如何推进其任务。
triage_agent = Agent(
name="分类智能体",
instructions="你根据用户的家庭作业问题确定使用哪个智能体",
handoffs=[history_tutor_agent, math_tutor_agent]
)
运行智能体编排
我们来检查工作流程是否运行,以及分类智能体是否在两个专家智能体之间正确路由。
from agents import Runner
async def main():
result = await Runner.run(triage_agent, "What is the capital of France?")
print(result.final_output)
添加安全护栏
你可以定义自定义安全护栏,以在输入或输出上运行。
from agents import GuardrailFunctionOutput, Agent, Runner
from pydantic import BaseModel
class HomeworkOutput(BaseModel):
is_homework: bool
reasoning: str
guardrail_agent = Agent(
name="Guardrail check",
instructions="Check if the user is asking about homework.",
output_type=HomeworkOutput,
)
async def homework_guardrail(ctx, agent, input_data):
result = await Runner.run(guardrail_agent, input_data, context=ctx.context)
final_output = result.final_output_as(HomeworkOutput)
return GuardrailFunctionOutput(
output_info=final_output,
tripwire_triggered=not final_output.is_homework,
)
整合所有内容
让我们整合所有内容并运行整个工作流程,使用交接/切换和输入安全护栏。
from agents import Agent, InputGuardrail, GuardrailFunctionOutput, Runner
from pydantic import BaseModel
import asyncio
class HomeworkOutput(BaseModel):
is_homework: bool
reasoning: str
guardrail_agent = Agent(
name="安全护栏检查",
instructions="检查用户是否在询问家庭作业相关内容。",
output_type=HomeworkOutput,
)
math_tutor_agent = Agent(
name="数学辅导",
handoff_description="数学问题的专家代理",
instructions="你为数学问题提供帮助。在每一步都解释你的推理过程,并包含示例",
)
history_tutor_agent = Agent(
name="历史辅导",
handoff_description="历史问题的专家代理",
instructions="你为历史查询提供帮助。清晰地解释重要事件和背景。",
)
async def homework_guardrail(ctx, agent, input_data):
result = await Runner.run(guardrail_agent, input_data, context=ctx.context)
final_output = result.final_output_as(HomeworkOutput)
return GuardrailFunctionOutput(
output_info=final_output,
tripwire_triggered=not final_output.is_homework,
)
triage_agent = Agent(
name="分诊代理",
instructions="你根据用户的家庭作业问题确定使用哪个代理",
handoffs=[history_tutor_agent, math_tutor_agent],
input_guardrails=[
InputGuardrail(guardrail_function=homework_guardrail),
],
)
async def main():
result = await Runner.run(triage_agent, "美国第一任总统是谁?")
print(result.final_output)
result = await Runner.run(triage_agent, "什么是生命")
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
查看追踪记录
若要回顾代理运行期间发生的情况,请前往 OpenAI 仪表盘的追踪查看器,查看代理运行的追踪记录。