OpenAI Agents SDK 是一個輕量且強大的框架,用於構建多代理(multi-agent)工作流程。它不依賴特定供應商,支援 OpenAI Responses 與 Chat Completions API,以及超過 100 種其他大型語言模型(LLM)。
Note
尋找 JavaScript/TypeScript 版本嗎?請參考 Agents SDK JS/TS。
- Agents:配置了指令、工具、安全防護(guardrails)與交接(handoffs)的 LLM
- Handoffs:Agents SDK 用於在代理之間轉移控制權的專用工具呼叫
- Guardrails:可配置的安全檢查,用於輸入與輸出驗證
- Sessions:自動管理代理執行過程中的對話歷史
- Tracing:內建的代理執行追蹤功能,讓你能夠檢視、除錯並優化你的工作流程
瀏覽 examples 目錄以了解 SDK 的實際應用,並閱讀我們的文件以獲得更多細節。
要開始使用,請先設定你的 Python 環境(需 Python 3.9 或更新版本),然後安裝 OpenAI Agents SDK 套件。
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install openai-agents
若需語音支援,請使用可選的 voice
群組安裝:pip install 'openai-agents[voice]'
。
如果你熟悉 uv,使用這個工具會非常類似:
uv init
uv add openai-agents
若需語音支援,請使用可選的 voice
群組安裝:uv add 'openai-agents[voice]'
。
from agents import Agent, Runner
agent = Agent(name="Assistant", instructions="You are a helpful assistant")
result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)
# Code within the code,
# Functions calling themselves,
# Infinite loop's dance.
(如果要執行此操作,請確保已設定 OPENAI_API_KEY
環境變數)
(Jupyter notebook 使用者請參考 hello_world_jupyter.ipynb)
from agents import Agent, Runner
import asyncio
spanish_agent = Agent(
name="Spanish agent",
instructions="You only speak Spanish.",
)
english_agent = Agent(
name="English agent",
instructions="You only speak English",
)
triage_agent = Agent(
name="Triage agent",
instructions="Handoff to the appropriate agent based on the language of the request.",
handoffs=[spanish_agent, english_agent],
)
async def main():
result = await Runner.run(triage_agent, input="Hola, ¿cómo estás?")
print(result.final_output)
# ¡Hola! Estoy bien, gracias por preguntar. ¿Y tú, cómo estás?
if __name__ == "__main__":
asyncio.run(main())
import asyncio
from agents import Agent, Runner, function_tool
@function_tool
def get_weather(city: str) -> str:
return f"The weather in {city} is sunny."
agent = Agent(
name="Hello world",
instructions="You are a helpful agent.",
tools=[get_weather],
)
async def main():
result = await Runner.run(agent, input="What's the weather in Tokyo?")
print(result.final_output)
# The weather in Tokyo is sunny.
if __name__ == "__main__":
asyncio.run(main())
當你呼叫 Runner.run()
時,我們會執行一個迴圈直到取得最終輸出為止。
- 我們會根據 agent 上設定的模型與參數,以及訊息歷史,呼叫大型語言模型 (LLM)。
- LLM 會回傳一個回應,這個回應可能包含工具呼叫 (tool calls)。
- 如果回應中有最終輸出(詳見下方說明),我們就會回傳該輸出並結束迴圈。
- 如果回應中有交接 (handoff),我們會將 agent 切換為新的 agent,然後回到步驟 1。
- 我們會處理所有工具呼叫(如果有的話),並將工具回應訊息加入訊息歷史。接著回到步驟 1。
你可以使用 max_turns
參數來限制此迴圈執行的次數。
最終輸出是 agent 在此迴圈中產生的最後一個結果。
- 如果你在 agent 上設定了
output_type
,當 LLM 回傳該類型的內容時即為最終輸出。我們會使用 結構化輸出 來實現這點。 - 如果沒有設定
output_type
(即為純文字回應),那麼第一個沒有任何工具呼叫或交接的 LLM 回應會被視為最終輸出。
因此,agent 迴圈的心智模型如下:
- 如果目前的 agent 有
output_type
,則迴圈會持續執行,直到 agent 產生符合該類型的結構化輸出為止。 - 如果目前的 agent 沒有
output_type
,則迴圈會持續執行,直到目前的 agent 產生一個沒有任何工具呼叫或交接的訊息。
Agents SDK 設計上極具彈性,讓你可以建構各種大型語言模型 (LLM) 工作流程,包括確定性流程、反覆迴圈等。你可以在 examples/agent_patterns
中查看範例。
Agents SDK 會自動追蹤你的 agent 執行流程,讓你能輕鬆追蹤與除錯 agent 的行為。追蹤功能設計上可擴充,支援自訂 span 以及多種外部目的地,包括 Logfire、AgentOps、Braintrust、Scorecard 和 Keywords AI。如需更多自訂或停用追蹤的細節,請參考 Tracing,其中也包含更完整的 外部追蹤處理器清單。
你可以利用 Agents SDK 的 Temporal 整合,來執行可持久化、長時間運作的工作流程,包括人類協作 (human-in-the-loop) 任務。你可以觀看 Temporal 與 Agents SDK 協作完成長時間任務的展示影片 in this video,並可於 view docs here 參閱相關文件。
Agents SDK 提供內建的 session 記憶,可自動維護多次 agent 執行間的對話歷史,無需手動處理每回合間的 .to_input_list()
。
from agents import Agent, Runner, SQLiteSession
# Create agent
agent = Agent(
name="Assistant",
instructions="Reply very concisely.",
)
# Create a session instance
session = SQLiteSession("conversation_123")
# First turn
result = await Runner.run(
agent,
"What city is the Golden Gate Bridge in?",
session=session
)
print(result.final_output) # "San Francisco"
# Second turn - agent automatically remembers previous context
result = await Runner.run(
agent,
"What state is it in?",
session=session
)
print(result.final_output) # "California"
# Also works with synchronous runner
result = Runner.run_sync(
agent,
"What's the population?",
session=session
)
print(result.final_output) # "Approximately 39 million"
- 無記憶(預設):當未指定 session 參數時,不會有 session 記憶
session: Session = DatabaseSession(...)
:使用 Session 實例來管理對話歷史
from agents import Agent, Runner, SQLiteSession
# Custom SQLite database file
session = SQLiteSession("user_123", "conversations.db")
agent = Agent(name="Assistant")
# Different session IDs maintain separate conversation histories
result1 = await Runner.run(
agent,
"Hello",
session=session
)
result2 = await Runner.run(
agent,
"Hello",
session=SQLiteSession("user_456", "conversations.db")
)
你可以透過建立一個遵循 Session
協定的類別,來實作自己的 Session 記憶:
from agents.memory import Session
from typing import List
class MyCustomSession:
"""Custom session implementation following the Session protocol."""
def __init__(self, session_id: str):
self.session_id = session_id
# Your initialization here
async def get_items(self, limit: int | None = None) -> List[dict]:
# Retrieve conversation history for the session
pass
async def add_items(self, items: List[dict]) -> None:
# Store new items for the session
pass
async def pop_item(self) -> dict | None:
# Remove and return the most recent item from the session
pass
async def clear_session(self) -> None:
# Clear all items for the session
pass
# Use your custom session
agent = Agent(name="Assistant")
result = await Runner.run(
agent,
"Hello",
session=MyCustomSession("my_session")
)
- 請確保你已安裝
uv
。
uv --version
- 安裝相依套件
make sync
- (進行變更後)執行 lint/test
make check # run tests linter and typechecker
或者單獨執行它們:
make tests # run tests
make mypy # run typechecker
make lint # run linter
make format-check # run style checker
我們要感謝開源社群的卓越貢獻,特別是:
我們承諾將持續以開源框架的方式推動 Agents SDK 的發展,讓社群中的其他成員能夠在我們的方法基礎上進一步擴展。