Skip to content

快速開始

建立專案與虛擬環境

這個步驟只需要執行一次。

mkdir my_project
cd my_project
python -m venv .venv

啟用虛擬環境

每次啟動新的終端機工作階段時,請執行此步驟。

source .venv/bin/activate

安裝 Agents SDK

pip install openai-agents # or `uv add openai-agents`, etc

設定 OpenAI API 金鑰

如果你還沒有 API 金鑰,請依照這些指引建立一組 OpenAI API 金鑰。

export OPENAI_API_KEY=sk-...

建立你的第一個代理 (Agent)

代理 (Agent) 是由指令、名稱,以及可選的設定(例如 model_config)所定義。

from agents import Agent

agent = Agent(
    name="Math Tutor",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

新增更多代理 (Agents)

可以用相同的方式定義其他代理 (Agents)。handoff_descriptions 提供額外的情境,用於判斷交接 (Handoffs) 路由。

from agents import Agent

history_tutor_agent = Agent(
    name="History Tutor",
    handoff_description="Specialist agent for historical questions",
    instructions="You provide assistance with historical queries. Explain important events and context clearly.",
)

math_tutor_agent = Agent(
    name="Math Tutor",
    handoff_description="Specialist agent for math questions",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

定義你的交接 (Handoffs)

在每個 Agent 上,你可以定義一份可用的交接 (Handoffs) 選項清單,讓該 Agent 能從中選擇,決定如何推進他們的任務。

triage_agent = Agent(
    name="Triage Agent",
    instructions="You determine which agent to use based on the user's homework question",
    handoffs=[history_tutor_agent, math_tutor_agent]
)

執行代理協作流程

讓我們來檢查 workflow 是否能順利運行,以及 triage agent 是否能正確地在兩個專家代理(specialist agents)之間進行路由。

from agents import Runner

async def main():
    result = await Runner.run(triage_agent, "What is the capital of France?")
    print(result.final_output)

新增 guardrail

你可以定義自訂的 guardrail,以在輸入或輸出時執行。

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,
    )

整合全部流程

讓我們將所有步驟整合起來,並運行完整的工作流程,結合交接(Handoffs)以及輸入防護機制(input guardrail)。

from agents import Agent, InputGuardrail, GuardrailFunctionOutput, Runner
from agents.exceptions import InputGuardrailTripwireTriggered
from pydantic import BaseModel
import asyncio

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,
)

math_tutor_agent = Agent(
    name="Math Tutor",
    handoff_description="Specialist agent for math questions",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

history_tutor_agent = Agent(
    name="History Tutor",
    handoff_description="Specialist agent for historical questions",
    instructions="You provide assistance with historical queries. Explain important events and context clearly.",
)


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="Triage Agent",
    instructions="You determine which agent to use based on the user's homework question",
    handoffs=[history_tutor_agent, math_tutor_agent],
    input_guardrails=[
        InputGuardrail(guardrail_function=homework_guardrail),
    ],
)

async def main():
    # Example 1: History question
    try:
        result = await Runner.run(triage_agent, "who was the first president of the united states?")
        print(result.final_output)
    except InputGuardrailTripwireTriggered as e:
        print("Guardrail blocked this input:", e)

    # Example 2: General/philosophical question
    try:
        result = await Runner.run(triage_agent, "What is the meaning of life?")
        print(result.final_output)
    except InputGuardrailTripwireTriggered as e:
        print("Guardrail blocked this input:", e)

if __name__ == "__main__":
    asyncio.run(main())

檢視您的追蹤紀錄

若要檢視代理(Agent)執行過程中發生的情況,請前往 OpenAI Dashboard 的 Trace viewer,以查看您的代理(Agent)執行追蹤紀錄。

下一步

學習如何建立更複雜的代理流程(agentic flows):