Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

一個輕量且強大的多代理工作流程框架

License

NotificationsYou must be signed in to change notification settings

doggy8088/openai-agents-python

 
 

Repository files navigation

OpenAI Agents SDK 是一個輕量且強大的框架,用於構建多代理(multi-agent)工作流程。它不依賴特定供應商,支援 OpenAI Responses 與 Chat Completions API,以及超過 100 種其他大型語言模型(LLM)。

Image of the Agents Tracing UI

Note

尋找 JavaScript/TypeScript 版本嗎?請參考Agents SDK JS/TS

核心概念:

  1. Agents:配置了指令、工具、安全防護(guardrails)與交接(handoffs)的 LLM
  2. Handoffs:Agents SDK 用於在代理之間轉移控制權的專用工具呼叫
  3. Guardrails:可配置的安全檢查,用於輸入與輸出驗證
  4. Sessions:自動管理代理執行過程中的對話歷史
  5. Tracing:內建的代理執行追蹤功能,讓你能夠檢視、除錯並優化你的工作流程

瀏覽examples 目錄以了解 SDK 的實際應用,並閱讀我們的文件以獲得更多細節。

開始使用

要開始使用,請先設定你的 Python 環境(需 Python 3.9 或更新版本),然後安裝 OpenAI Agents SDK 套件。

venv

python -m venv .venvsource .venv/bin/activate# On Windows: .venv\Scripts\activatepip install openai-agents

若需語音支援,請使用可選的voice 群組安裝:pip install 'openai-agents[voice]'

uv

如果你熟悉uv,使用這個工具會非常類似:

uv inituv add openai-agents

若需語音支援,請使用可選的voice 群組安裝:uv add 'openai-agents[voice]'

Hello world 範例

fromagentsimportAgent,Runneragent=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

Handoffs 範例

fromagentsimportAgent,Runnerimportasynciospanish_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],)asyncdefmain():result=awaitRunner.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())

Functions 範例

importasynciofromagentsimportAgent,Runner,function_tool@function_tooldefget_weather(city:str)->str:returnf"The weather in{city} is sunny."agent=Agent(name="Hello world",instructions="You are a helpful agent.",tools=[get_weather],)asyncdefmain():result=awaitRunner.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())

Agent 迴圈

當你呼叫Runner.run() 時,我們會執行一個迴圈直到取得最終輸出為止。

  1. 我們會根據 agent 上設定的模型與參數,以及訊息歷史,呼叫大型語言模型 (LLM)。
  2. LLM 會回傳一個回應,這個回應可能包含工具呼叫 (tool calls)。
  3. 如果回應中有最終輸出(詳見下方說明),我們就會回傳該輸出並結束迴圈。
  4. 如果回應中有交接 (handoff),我們會將 agent 切換為新的 agent,然後回到步驟 1。
  5. 我們會處理所有工具呼叫(如果有的話),並將工具回應訊息加入訊息歷史。接著回到步驟 1。

你可以使用max_turns 參數來限制此迴圈執行的次數。

最終輸出

最終輸出是 agent 在此迴圈中產生的最後一個結果。

  1. 如果你在 agent 上設定了output_type,當 LLM 回傳該類型的內容時即為最終輸出。我們會使用結構化輸出 來實現這點。
  2. 如果沒有設定output_type(即為純文字回應),那麼第一個沒有任何工具呼叫或交接的 LLM 回應會被視為最終輸出。

因此,agent 迴圈的心智模型如下:

  1. 如果目前的 agent 有output_type,則迴圈會持續執行,直到 agent 產生符合該類型的結構化輸出為止。
  2. 如果目前的 agent 沒有output_type,則迴圈會持續執行,直到目前的 agent 產生一個沒有任何工具呼叫或交接的訊息。

常見 agent 模式

Agents SDK 設計上極具彈性,讓你可以建構各種大型語言模型 (LLM) 工作流程,包括確定性流程、反覆迴圈等。你可以在examples/agent_patterns 中查看範例。

追蹤 (Tracing)

Agents SDK 會自動追蹤你的 agent 執行流程,讓你能輕鬆追蹤與除錯 agent 的行為。追蹤功能設計上可擴充,支援自訂 span 以及多種外部目的地,包括LogfireAgentOpsBraintrustScorecardKeywords AI。如需更多自訂或停用追蹤的細節,請參考Tracing,其中也包含更完整的外部追蹤處理器清單

長時間執行 agent 與人類協作 (human-in-the-loop)

你可以利用 Agents SDK 的Temporal 整合,來執行可持久化、長時間運作的工作流程,包括人類協作 (human-in-the-loop) 任務。你可以觀看 Temporal 與 Agents SDK 協作完成長時間任務的展示影片in this video,並可於view docs here 參閱相關文件。

工作階段 (Sessions)

Agents SDK 提供內建的 session 記憶,可自動維護多次 agent 執行間的對話歷史,無需手動處理每回合間的.to_input_list()

快速開始

fromagentsimportAgent,Runner,SQLiteSession# Create agentagent=Agent(name="Assistant",instructions="Reply very concisely.",)# Create a session instancesession=SQLiteSession("conversation_123")# First turnresult=awaitRunner.run(agent,"What city is the Golden Gate Bridge in?",session=session)print(result.final_output)# "San Francisco"# Second turn - agent automatically remembers previous contextresult=awaitRunner.run(agent,"What state is it in?",session=session)print(result.final_output)# "California"# Also works with synchronous runnerresult=Runner.run_sync(agent,"What's the population?",session=session)print(result.final_output)# "Approximately 39 million"

Session 選項

  • 無記憶(預設):當未指定 session 參數時,不會有 session 記憶
  • session: Session = DatabaseSession(...):使用 Session 實例來管理對話歷史
fromagentsimportAgent,Runner,SQLiteSession# Custom SQLite database filesession=SQLiteSession("user_123","conversations.db")agent=Agent(name="Assistant")# Different session IDs maintain separate conversation historiesresult1=awaitRunner.run(agent,"Hello",session=session)result2=awaitRunner.run(agent,"Hello",session=SQLiteSession("user_456","conversations.db"))

自訂 Session 實作

你可以透過建立一個遵循Session 協定的類別,來實作自己的 Session 記憶:

fromagents.memoryimportSessionfromtypingimportListclassMyCustomSession:"""Custom session implementation following the Session protocol."""def__init__(self,session_id:str):self.session_id=session_id# Your initialization hereasyncdefget_items(self,limit:int|None=None)->List[dict]:# Retrieve conversation history for the sessionpassasyncdefadd_items(self,items:List[dict])->None:# Store new items for the sessionpassasyncdefpop_item(self)->dict|None:# Remove and return the most recent item from the sessionpassasyncdefclear_session(self)->None:# Clear all items for the sessionpass# Use your custom sessionagent=Agent(name="Assistant")result=awaitRunner.run(agent,"Hello",session=MyCustomSession("my_session"))

開發(僅當你需要編輯 SDK/範例時才需要)

  1. 請確保你已安裝uv
uv --version
  1. 安裝相依套件
make sync
  1. (進行變更後)執行 lint/test
make check # run tests linter and typechecker

或者單獨執行它們:

make tests  # run testsmake mypy   # run typecheckermake lint   # run lintermake format-check # run style checker

致謝

我們要感謝開源社群的卓越貢獻,特別是:

我們承諾將持續以開源框架的方式推動 Agents SDK 的發展,讓社群中的其他成員能夠在我們的方法基礎上進一步擴展。

About

一個輕量且強大的多代理工作流程框架

Resources

License

Stars

Watchers

Forks

Languages

  • Python99.9%
  • Makefile0.1%

[8]ページ先頭

©2009-2025 Movatter.jp