如何使用OpenAI的Responses API和Agent SDK?

如何使用OpenAI的Responses API和Agent SDK?

OpenAI 一直是 GenAI 領域領先的解決方案提供商。從傳奇的 ChatGPT 到 Sora,OpenAI 是所有職場人士的首選平臺。隨著 Qwen 和 Claude 在開發人員中越來越受歡迎,OpenAI 再次推出最新更新,幫助開發人員建立更可靠、更強大的人工智慧代理。其中的主要亮點包括 Responses API 和 Agents SDK。在本部落格中,我們將探討 Responses API 和 Agents SDK,瞭解如何訪問它們,並學習如何使用它們構建真實世界的應用程式!

什麼是Responses API?

Responses API 是 OpenAI 最新的 API,旨在簡化構建基於 AI 的應用程式的過程。它結合了聊天完成 API 的簡易性和助手 API 的強大工具使用功能。這意味著開發人員現在可以建立利用多種工具的代理,並更高效地處理複雜的多步驟任務。該 API 減少了對複雜的提示工程和外部整合的依賴。

  • 內建網路搜尋、檔案搜尋和計算機使用等工具,允許代理與真實世界的資料進行互動。
  • 統一的設計簡化了多型性並提高了可用性。
  • 更好的可觀察性,幫助開發人員跟蹤代理行為並優化工作流程。
  • 無需支付額外費用,因為它是按照 OpenAI 的標準定價,根據令牌使用情況收費的。

有了這些工具,Responses API 將改變構建人工智慧代理的遊戲規則。事實上,在未來,Responses API 將支援 OpenAI 的所有新模型和即將推出的模型。讓我們看看如何使用它來構建應用程式。

如何使用Responses API?

嘗試使用 Responses API:

  1. 安裝 openai(如果尚未安裝)並使用 OpenAI。
  2. 確保擁有最新的 OpenAI 庫(pip install openai – -upgrade)。
  3. 匯入 OpenAI 並設定客戶端。

設定完成後,您就可以請求響應 API。雖然基本的 API 呼叫很常見,但它的內建功能卻非常強大。讓我們來了解一下它的三個主要功能:

  • 檔案搜尋:從檔案中檢索見解。
  • 網路搜尋:獲取實時引用資訊。
  • 計算機使用:自動進行系統互動。

現在,讓我們來看看它們的實際應用!

1. 檔案搜尋

它能讓模型通過語義和關鍵字搜尋檢索知識庫中先前上傳檔案的資訊。目前它不支援 csv 檔案,您可以在這裡檢視支援的檔案型別列表。

注意:在使用檔案搜尋之前,請確保將檔案儲存在向量資料庫中。

任務:Names of people with domain as Data Science。(我使用了以下檔案)

程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
response = client.responses.create(
model="gpt-4o-mini",
input="Names of people with domain as Data Science",
tools=[{
"type": "file_search",
"vector_store_ids": [vector_store_id],
"filters": {
"type": "eq",
"key": "Domain",
"value": "Data Science"
}
}]
)
print(response.output_text)
response = client.responses.create( model="gpt-4o-mini", input="Names of people with domain as Data Science", tools=[{ "type": "file_search", "vector_store_ids": [vector_store_id], "filters": { "type": "eq", "key": "Domain", "value": "Data Science" } }] ) print(response.output_text)
response = client.responses.create(
    model="gpt-4o-mini",
    input="Names of people with domain as Data Science",
    tools=[{
        "type": "file_search",
        "vector_store_ids": [vector_store_id],
        "filters": {
            "type": "eq",
            "key": "Domain",
            "value": "Data Science"
        }
    }]
)
print(response.output_text)

輸出:

The person with the domain of Data Science is Alice Johnson [0].[0] names_and_domains.pdf

2. 網路搜尋

此功能允許模型在生成響應之前在網上搜尋最新資訊,確保資料保持最新。模型可以根據輸入提示的內容選擇是否搜尋網路。

任務:What are the best cafes in Vijay nagar?

程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
response = client.responses.create(
model="gpt-4o",
tools=[{
"type": "web_search_preview",
"user_location": {
"type": "approximate",
"country": "IN",
"city": "Indore",
"region": "Madhya Pradesh",
}
}],
input="What are the best cafe in Vijay nagar?",
)
print(response.output_text)
response = client.responses.create( model="gpt-4o", tools=[{ "type": "web_search_preview", "user_location": { "type": "approximate", "country": "IN", "city": "Indore", "region": "Madhya Pradesh", } }], input="What are the best cafe in Vijay nagar?", ) print(response.output_text)
response = client.responses.create(
    model="gpt-4o",
    tools=[{
        "type": "web_search_preview",
        "user_location": {
            "type": "approximate",
            "country": "IN",
            "city": "Indore",
            "region": "Madhya Pradesh",
        }
    }],
    input="What are the best cafe in Vijay nagar?",
)
print(response.output_text)

輸出:

網路搜尋任務響應

3. 計算機使用

這是計算機使用代理(CUA)模型的實際應用,它將 GPT-4o 的視覺功能與高階推理相結合,模擬控制計算機介面並執行任務。

任務:Check the latest blog on Analytics Vidhya website.

程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
response = client.responses.create(
model="computer-use-preview",
tools=[{
"type": "computer_use_preview",
"display_width": 1024,
"display_height": 768,
"environment": "browser" # other possible values: "mac", "windows", "ubuntu"
}],
input=[
{
"role": "user",
"content": "Check the latest blog on Analytics Vidhya website."
}
],
truncation="auto"
)
print(response.output)
response = client.responses.create( model="computer-use-preview", tools=[{ "type": "computer_use_preview", "display_width": 1024, "display_height": 768, "environment": "browser" # other possible values: "mac", "windows", "ubuntu" }], input=[ { "role": "user", "content": "Check the latest blog on Analytics Vidhya website." } ], truncation="auto" ) print(response.output)
response = client.responses.create(
    model="computer-use-preview",
    tools=[{
        "type": "computer_use_preview",
        "display_width": 1024,
        "display_height": 768,
        "environment": "browser" # other possible values: "mac", "windows", "ubuntu"
    }],
    input=[
        {
            "role": "user",
            "content": "Check the latest blog on Analytics Vidhya website."
        }
    ],
    truncation="auto"
)
print(response.output)

輸出:

ResponseComputerToolCall(id='cu_67d147af346c8192b78719dd0e22856964fbb87c6a42e96', action=ActionScreenshot(type='screenshot'), call_id='call_a0w16G1BNEk09aYIV25vdkxY', pending_safety_checks=[], status='completed', type='computer_call')

Responses API與Completions API有何不同?

既然我們已經瞭解了 Responses API 的工作原理,那麼讓我們來看看它與之前存在的 Completions API 有何不同。

Responses API與Completions API:執行

API Responses API Completions API
程式碼
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-4o",
inputs=[
{
"role": "user",
"content": "Write a one-sentence bedtime story about a unicorn."
}
]
)
print(response.output_text)
from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": "Write a one-sentence bedtime story about a unicorn."
}
]
)
print(completion.choices[0].message.content)
輸出 Responses API執行輸出 Completions API執行輸出

Responses API與Completions API:功能

以下是 Chat Complerions APi 和 Responses API 各項功能的簡化細分:

功能 Responses API Chat Completions API
文字生成
音訊 即將推出
視覺
網頁搜尋
檔案搜尋
計算機使用
程式碼解釋 即將推出
響應處理 返回單一結構化輸出 返回選擇陣列
會話狀態 用於保持連續性的 previous_response_id 必須人工管理
儲存行為 預設儲存(儲存:false 表示禁用) 預設儲存

路線圖:哪些將繼續使用,哪些將被淘汰?

隨著回覆 API 的上線,現在最迫切的問題是,它會影響現有的聊天完成和助手 API 嗎?會的。讓我們來看看是如何影響的:

  • Chat Completions API:OpenAI 將繼續用新模型更新它,但前提是這些功能不需要內建工具。
  • 網路搜尋和檔案搜尋工具:在 Responses API 中,這些工具將變得更加完善和強大。
  • Assistants API: Responses API 融合了其最佳功能,同時提高了效能。OpenAI 已經宣佈,全面的功能對等即將到來,Assistants API 將在 2026 年中期被淘汰。

介紹Agents SDK

構建人工智慧代理不僅需要功能強大的 API,還需要高效的協調。這正是 OpenAI 的 Agents SDK 發揮作用的地方。Agents SDK 是一個開源工具包,可簡化代理工作流程(您可以將其理解為智慧體開發套件)。該代理構建框架可與響應 API 和聊天完成 API 無縫整合。此外,它還與各種提供商的模型相容,只要它們提供風格類似於 Chat Completions 的 API 端點。

Agents SDK 的一些主要功能包括

  • 它允許開發人員使用內建工具配置人工智慧代理。
  • 它支援多代理協調,允許根據需要無縫協調不同的代理。
  • 它允許我們跟蹤代理之間的對話和資訊流。
  • 它能讓我們更輕鬆地應用安全和合規性防護措施。
  • 它能確保開發人員利用內建的可觀察性工具監控和優化代理效能。

Agent SDK 並不是 OpenAI 的“新成員”。它是 OpenAI 去年釋出的實驗 SDK“Swarm”的改進版。雖然 “Swarm ”只是出於教育目的而釋出,但它在開發者中很受歡迎,也被一些企業所採用。為了滿足更多企業的需求,幫助他們無縫構建生產級代理,Agents SDK 已經發布。既然我們已經瞭解了 Agents SDK 的功能,那就讓我們看看如何使用這個框架來構建我們的代理系統。

使用Agent SDK構建多代理系統

我們將利用 LLM 驅動的代理和網路搜尋工具,構建一個多代理系統,幫助使用者進行汽車推薦和轉售價格估算,從而提供準確的最新見解。

Step 1:建立一個簡單的人工智慧代理

我們首先建立一個汽車顧問代理,幫助使用者根據自己的需求選擇合適的汽車型別。

程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
car_advisor = Agent(
name="Car advisor",
instructions= "You are an expert in advising suitable car type like sedan, hatchback etc to people based on their requirements.",
model="gpt-4o",
)
prompt = "I am looking for a car that I enjoy driving and comforatbly take 4 people. I plane to travel to hills. What type of car should I buy?"
async def main():
result = await Runner.run(car_advisor, prompt)
print(result.final_output)
# Run the function in Jupyter
await main()
car_advisor = Agent( name="Car advisor", instructions= "You are an expert in advising suitable car type like sedan, hatchback etc to people based on their requirements.", model="gpt-4o", ) prompt = "I am looking for a car that I enjoy driving and comforatbly take 4 people. I plane to travel to hills. What type of car should I buy?" async def main(): result = await Runner.run(car_advisor, prompt) print(result.final_output) # Run the function in Jupyter await main()
car_advisor = Agent(
    name="Car advisor",
    instructions= "You are an expert in advising suitable car type like sedan, hatchback etc to people based on their requirements.",
    model="gpt-4o",
    )
prompt = "I am looking for a car that I enjoy driving and comforatbly take 4 people. I plane to travel to hills. What type of car should I buy?"
async def main():
    result = await Runner.run(car_advisor, prompt)
    print(result.final_output)
# Run the function in Jupyter
await main()

輸出:

建立一個簡單的人工智慧代理

Step 2:構建多代理系統

有了基本代理後,我們現在要建立一個多代理系統,將不同的人工智慧代理整合到各自擅長的領域中。具體操作如下:

多代理系統中的代理

  1. 汽車銷售估價代理:它根據汽車的詳細資訊提供轉售價格估算。
  2. 車型顧問代理:它根據預算和地點推薦合適的車型。
  3. 分流代理:它將查詢轉給合適的代理。

我們將向代理提供兩種不同的提示,並觀察它們的輸出結果。

提示詞 1:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
car_sell_estimate = Agent(
name="Car sell estimate",
instructions= "You are an expert in suggesting a suitable price of reselling a car based on its make, model, year of purchase, and condition.",
handoff_description= "Car reselling price estimate expert",
model="gpt-4o",
tools=[WebSearchTool()]
)
car_model_advisor = Agent(
name="Car model advisor",
instructions= "You are an expert in advising suitable car model to people based on their budget and location.",
handoff_description= "Car model recommendation expert",
model="gpt-4o",
tools=[WebSearchTool()]
)
triage_agent = Agent(
name = "Triage Agent",
instructions="You determine the appropriate agent for the task.",
model = "gpt-4o",
handoffs=[car_sell_estimate, car_model_advisor]
)
Prompt 1:
prompt = "I want to sell my Ecosport car in New Delhi. It is 3 years old and in good condition. 50000Km. What price should I expect?"
async def main():
result = await Runner.run(triage_agent, prompt)
print(result.final_output)
# Run the function in Jupyter
await main()
car_sell_estimate = Agent( name="Car sell estimate", instructions= "You are an expert in suggesting a suitable price of reselling a car based on its make, model, year of purchase, and condition.", handoff_description= "Car reselling price estimate expert", model="gpt-4o", tools=[WebSearchTool()] ) car_model_advisor = Agent( name="Car model advisor", instructions= "You are an expert in advising suitable car model to people based on their budget and location.", handoff_description= "Car model recommendation expert", model="gpt-4o", tools=[WebSearchTool()] ) triage_agent = Agent( name = "Triage Agent", instructions="You determine the appropriate agent for the task.", model = "gpt-4o", handoffs=[car_sell_estimate, car_model_advisor] ) Prompt 1: prompt = "I want to sell my Ecosport car in New Delhi. It is 3 years old and in good condition. 50000Km. What price should I expect?" async def main(): result = await Runner.run(triage_agent, prompt) print(result.final_output) # Run the function in Jupyter await main()
car_sell_estimate = Agent(
    name="Car sell estimate",
    instructions= "You are an expert in suggesting a suitable price of reselling a car based on its make, model, year of purchase, and condition.",
    handoff_description= "Car reselling price estimate expert",
    model="gpt-4o",
    tools=[WebSearchTool()]
    )
car_model_advisor = Agent(
    name="Car model advisor",
    instructions= "You are an expert in advising suitable car model to people based on their budget and location.",
    handoff_description= "Car model recommendation expert",
    model="gpt-4o",
    tools=[WebSearchTool()]
    )
triage_agent = Agent(
    name = "Triage Agent",
    instructions="You determine the appropriate agent for the task.",
    model = "gpt-4o",
    handoffs=[car_sell_estimate, car_model_advisor]
)
Prompt 1: 
prompt = "I want to sell my Ecosport car in New Delhi. It is 3 years old and in good condition. 50000Km. What price should I expect?"
async def main():
    result = await Runner.run(triage_agent, prompt)
    print(result.final_output)
# Run the function in Jupyter
await main()

輸出 1:

構建多代理系統輸出

提示詞 2:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
prompt = "I want to buy a high acceleration car, comfortable for 4 people for 20 lakhs in New Delhi. Which car should I buy?"
async def main():
result = await Runner.run(triage_agent, prompt)
print(result.final_output)
# Run the function in Jupyter
await main()
prompt = "I want to buy a high acceleration car, comfortable for 4 people for 20 lakhs in New Delhi. Which car should I buy?" async def main(): result = await Runner.run(triage_agent, prompt) print(result.final_output) # Run the function in Jupyter await main()
prompt = "I want to buy a high acceleration car, comfortable for 4 people for 20 lakhs in New Delhi. Which car should I buy?"
async def main():
    result = await Runner.run(triage_agent, prompt)
    print(result.final_output)
# Run the function in Jupyter
await main()

輸出 2:

構建多代理系統輸出

我們得到了符合要求的汽車選項!實施簡單快捷。您可以使用這個代理框架來建立旅行支援、財務規劃、醫療援助、個性化購物、自動研究等方面的代理。

Agent SDK:新的代理框架?

OpenAI 的 Agents SDK 代表著其為人工智慧代理開發提供專用框架的戰略推進。該框架通過其分流代理,模仿 Crew AI 的功能,加入了類似船員的功能。同樣,它的交接機制也與 AutoGen 非常相似,可以在多個代理之間高效地分配任務。

此外,LangChain 在模組化代理協調方面的優勢還體現在 Agents SDK 提供結構化工作流程的方式上,從而確保了執行的流暢性和適應性。雖然 Agents SDK 所提供的功能與現有框架已做的功能相差無幾,但它很快就會與這些框架展開激烈的競爭。

開發人員為什麼需要Responses API和Agents SDK?

Responses API 和 Agents SDK 為開發人員提供了構建人工智慧驅動型應用的工具和平臺。通過減少對手動提示工程和大量自定義邏輯的依賴,這些工具使開發人員能夠專注於建立智慧工作流,並將摩擦降至最低。

  • 易於整合:開發人員不再需要為不同的工具同時使用多個應用程式介面;Responses API 將網路搜尋、檔案搜尋和計算機使用整合到一個介面中。
  • 更好的可觀察性:藉助內建的監控和除錯工具,開發人員可以更輕鬆地優化代理效能。
  • 可擴充套件性:Agents SDK 提供了一種結構化的方法來處理多代理工作流,從而實現更強大的自動化。
  • 改進開發週期:由於無需進行大量的提示迭代和外部工具整合,開發人員可以更快地開發和部署基於代理的應用原型。

小結

OpenAI 的 Responses API 和 Agents SDK 的推出改變了人工智慧驅動自動化的遊戲規則。通過利用這些工具,我們僅用幾行程式碼就成功地快速構建了一個多代理系統。這一實施方案還可以進一步擴充套件,納入更多工具、整合和代理功能,為各行各業更智慧、更自主的人工智慧應用鋪平道路。

這些工具必將幫助開發人員和企業降低開發複雜性,建立更智慧、更可擴充套件的自動化解決方案。無論是客戶支援、研究、業務自動化,還是特定行業的人工智慧應用,Responses API 和 Agents SDK 都能提供一個強大的框架,輕鬆構建下一代人工智慧驅動的系統。

評論留言