共用方式為


OpenAI 代理程式

Microsoft Agent Framework 支援三種不同的 OpenAI 用戶端類型,每種針對不同的 API 表面及不同工具功能:

客戶類型 API 適用對象
聊天完成 聊天完成 API 簡單的代理,廣泛的模型支援
回應 回應 API 具備完整功能代理,並附有託管工具(程式碼解譯器、檔案搜尋、網頁搜尋、託管 MCP)
助理 助手 API 由伺服器管理的代理程式、程式碼解釋器與檔案搜尋

小提示

關於Azure OpenAI的AzureOpenAIChatClient對應(, AzureOpenAIResponsesClient, ), AzureOpenAIAssistantsClient請參見 Azure OpenAI提供者頁面。 工具支援完全相同。

使用者入門

將必要的 NuGet 套件新增至您的專案。

dotnet add package Microsoft.Agents.AI.OpenAI --prerelease

聊天完成客戶端

Chat Completion 客戶端提供了一種直接使用 ChatCompletion API 建立代理的方式。

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
var chatClient = client.GetChatClient("gpt-4o-mini");

AIAgent agent = chatClient.AsAIAgent(
    instructions: "You are good at telling jokes.",
    name: "Joker");

Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));

支援工具: 功能工具、網頁搜尋、本地 MCP 工具。

回應客戶端

回應客戶端提供最豐富的工具支援,包括程式碼直譯器、檔案搜尋、網頁搜尋及託管 MCP。

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
var responsesClient = client.GetResponseClient("gpt-4o-mini");

AIAgent agent = responsesClient.AsAIAgent(
    instructions: "You are a helpful coding assistant.",
    name: "CodeHelper");

Console.WriteLine(await agent.RunAsync("Write a Python function to sort a list."));

支援工具: 功能工具、工具審核、程式碼解譯器、檔案搜尋、網頁搜尋、託管 MCP、本地 MCP 工具。

助理客戶

助理客戶端建立內建程式碼直譯器和檔案搜尋的伺服器管理代理。

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
var assistantsClient = client.GetAssistantClient();

// Assistants are managed server-side
AIAgent agent = assistantsClient.AsAIAgent(
    instructions: "You are a data analysis assistant.",
    name: "DataHelper");

Console.WriteLine(await agent.RunAsync("Analyze trends in the uploaded data."));

支援工具: 功能工具、程式碼直譯器、檔案搜尋、本地 MCP 工具。

小提示

完整可執行範例請參閱 .NET 範例

使用代理程式

三種用戶端類型都符合相同的標準 AIAgent,支援相同的代理操作(串流、執行緒、中介軟體)。

更多資訊請參閱 入門教學

Installation

pip install agent-framework --pre

設定

每種用戶端類型使用不同的環境變數:

聊天完成

OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini"

回覆

OPENAI_API_KEY="your-openai-api-key"
OPENAI_RESPONSES_MODEL_ID="gpt-4o-mini"

Assistants

OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini"

聊天完成客戶端

OpenAIChatClient 使用 Chat Completions API——這是最簡單的選項,且支援廣泛的模型。

import asyncio
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = OpenAIChatClient().as_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant.",
    )
    result = await agent.run("Hello, how can you help me?")
    print(result)

asyncio.run(main())

支援工具: 功能工具、網頁搜尋、本地 MCP 工具。

網路搜索搭配聊天完成功能

async def web_search_example():
    client = OpenAIChatClient()
    web_search = client.get_web_search_tool()

    agent = client.as_agent(
        name="SearchBot",
        instructions="You can search the web for current information.",
        tools=web_search,
    )
    result = await agent.run("What are the latest developments in AI?")
    print(result)

回應客戶端

OpenAIResponsesClient 使用 Responses API——這是託管工具中功能最豐富的選項。

import asyncio
from agent_framework.openai import OpenAIResponsesClient

async def main():
    agent = OpenAIResponsesClient().as_agent(
        name="FullFeaturedAgent",
        instructions="You are a helpful assistant with access to many tools.",
    )
    result = await agent.run("Write and run a Python script that calculates fibonacci numbers.")
    print(result)

asyncio.run(main())

支援工具: 功能工具、工具審核、程式碼解譯器、檔案搜尋、網頁搜尋、託管 MCP、本地 MCP 工具。

帶有回應客戶端的託管工具

Responses 用戶端為每種託管工具類型提供 get_*_tool() 方法:

async def hosted_tools_example():
    client = OpenAIResponsesClient()

    # Each tool is created via a client method
    code_interpreter = client.get_code_interpreter_tool()
    web_search = client.get_web_search_tool()
    file_search = client.get_file_search_tool(vector_store_ids=["vs_abc123"])
    mcp_tool = client.get_mcp_tool(
        name="GitHub",
        url="https://api.githubcopilot.com/mcp/",
        approval_mode="never_require",
    )

    agent = client.as_agent(
        name="PowerAgent",
        instructions="You have access to code execution, web search, files, and GitHub.",
        tools=[code_interpreter, web_search, file_search, mcp_tool],
    )
    result = await agent.run("Search the web for Python best practices, then write a summary.")
    print(result)

助理用戶端

OpenAIAssistantProvider 使用 Assistants API——內建程式碼直譯器與檔案搜尋的伺服器管理代理。 提供者會自動管理助理生命週期。

import asyncio
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI

async def main():
    client = AsyncOpenAI()
    provider = OpenAIAssistantProvider(client)

    agent = await provider.create_agent(
        name="DataAnalyst",
        model="gpt-4o-mini",
        instructions="You analyze data using code execution.",
    )

    try:
        result = await agent.run("Calculate the first 20 prime numbers.")
        print(result)
    finally:
        await provider.delete_agent(agent.id)

asyncio.run(main())

支援工具: 功能工具、程式碼直譯器、檔案搜尋、本地 MCP 工具。

共同特徵

三種用戶端類型皆支援以下標準代理功能:

功能工具

from agent_framework import tool

@tool
def get_weather(location: str) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny, 25°C."

async def example():
    agent = OpenAIResponsesClient().as_agent(
        instructions="You are a weather assistant.",
        tools=get_weather,
    )
    result = await agent.run("What's the weather in Tokyo?")
    print(result)

多回合對話

async def thread_example():
    agent = OpenAIResponsesClient().as_agent(
        instructions="You are a helpful assistant.",
    )
    session = await agent.create_session()

    result1 = await agent.run("My name is Alice", session=session)
    print(result1)
    result2 = await agent.run("What's my name?", session=session)
    print(result2)  # Remembers "Alice"

串流

async def streaming_example():
    agent = OpenAIResponsesClient().as_agent(
        instructions="You are a creative storyteller.",
    )
    print("Agent: ", end="", flush=True)
    async for chunk in agent.run("Tell me a short story about AI.", stream=True):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()

使用代理程式

所有客戶端類型都會產生一個標準Agent,支援相同的操作。

更多資訊請參閱 入門教學

後續步驟