OpenAI

Microsoft Agent Framework 支援 C#、Python 和 Go 中的 OpenAI 代理程式。 C# 和 Python 支援兩種 OpenAI 用戶端類型——回應(Responses)和聊天完成(Chat Completions),而 Go 目前使用聊天完成服務提供者。 Responses 是推薦的主要用戶端(若有):它針對較新的 OpenAI 回應 API,並支援完整的託管工具組合(程式碼解譯器、檔案搜尋、網頁搜尋、託管 MCP、影像生成)。 當你需要廣泛的模型相容性、Go 支援,或想保留現有的 Chat Completions 整合時,請使用 Chat Completion。

客戶類型 API 最適合
回應(建議) 回應 API 具備完整功能代理,並附有託管工具(程式碼解譯器、檔案搜尋、網頁搜尋、託管 MCP)
聊天完成 聊天完成 API 簡單的代理,廣泛的模型支援

Note

OpenAI 助理 API 已被 OpenAI 取代。 新程式碼應該使用回應客戶端。 如果你是從現有的 Assistants 應用程式遷移過來,請參考 語意核心 遷移指南

使用者入門

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

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

回應客戶端

Responses 用戶端是推薦的主要用戶端,提供最豐富的工具支援,包括程式碼直譯器、檔案搜尋、網頁搜尋及託管 MCP。

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
var responsesClient = client.GetResponsesClient();

AIAgent agent = responsesClient.AsAIAgent(
    model: "gpt-4o-mini",
    instructions: "You are a helpful coding assistant.",
    name: "CodeHelper");

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

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

聊天完成客戶端

聊天完成客戶端提供了一種直接使用聊天完成 API 來建立代理的方式。 當你需要廣泛的模型相容性或已有 Chat Completions 整合時,可以使用它。

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 工具。

助理用戶端

Note

OpenAI 助理的 API 已被 OpenAI 取代。 Agent Framework 不再提供 Assistants 用戶端的說明文件;新程式碼請改用上述的 Responses 用戶端。 關於遷移現有應用程式,請參閱 語意核心 遷移指南

使用代理程式

兩種用戶端類型都會產生一個標準的 AIAgent,支援相同的代理程式操作(串流、執行緒、中介軟體)。

更多資訊請參閱 入門教學

工具

OpenAI .NET 用戶端會根據目標 API 暴露不同的工具表面。 同樣的對照表也適用於 Azure OpenAI 提供者頁面 上相對應的 Azure OpenAI 用戶端。

Tool 回應 聊天完成
函式工具
工具核准
程式碼解譯器
檔案搜尋
網路搜尋
託管 MCP 工具
本地 MCP 工具

Note

工具核准 由框架的函式調用聊天客戶端提供,因此無論底層 API 為何,都能對任何函式工具呼叫有效。

Note

OpenAI 已棄用 OpenAI 助理 API,且 Python 不再提供助理相容客戶端/服務提供者。 回應請使用 OpenAIChatClient,聊天完成請使用 OpenAIChatCompletionClient。 如果你是從先前的代理框架Python版本遷移過來,請參閱 Python重大變更指南。 如果你是從 語意核心 遷移,請參考 語意核心 遷移指南

Tip

在 Python 中,Azure OpenAI 現在使用與此處所示相同的 agent_framework.openai 用戶端。 明確傳遞 Azure 路由輸入,例如credentialazure_endpoint當你需要 Azure 路由時,在此情況下,然後設定api_version為你想使用的 Azure API 介面。 如果 OPENAI_API_KEY 已設定,通用客戶端即使在 AZURE_OPENAI_* 變數存在時也會留在 OpenAI。 如果你已經有完整 .../openai/v1 網址,請用 base_url 代替 azure_endpoint。 關於 Microsoft Foundry 專案端點及 Foundry 代理服務,請參見 Microsoft Foundry 提供者頁面。 關於本地執行環境,請參見 Foundry Local

安裝

pip install agent-framework-openai

agent-framework-openai 是可選的 Python 提供者套件,適用於直接使用 OpenAI 和 Azure OpenAI。

Configuration

Python OpenAI 聊天客戶端使用以下環境變數模式:

OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL="gpt-4o-mini"
# Optional shared fallback:
# OPENAI_MODEL="gpt-4o-mini"

共同特徵

這些客戶端類型支援以下標準客服專員功能:

功能工具

from agent_framework import Agent, 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 = Agent(
        client=OpenAIChatClient(),
        instructions="You are a weather assistant.",
        tools=get_weather,
    )
    result = await agent.run("What's the weather in Tokyo?")
    print(result)

多回合對話

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

async def thread_example():
    agent = Agent(
        client=OpenAIChatClient(),
        instructions="You are a helpful assistant.",
    )
    session = 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"

Streaming

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

async def streaming_example():
    agent = Agent(
        client=OpenAIChatClient(),
        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()

提示快取

在支援明確提示快取斷點的模型中,可以使用 OpenAIChatClientprompt_cache_keyprompt_cache_options以及 Content.additional_properties["prompt_cache_breakpoint"] 來控制可重用前綴。 支援的型號可分別計費快取寫入。

OpenAI 快取使用量通常化為 response.usage_details

  • cache_creation_input_token_count - 寫入提供者管理快取的輸入標記。
  • cache_read_input_token_count - 從快取中提供的輸入標記。

啟用 OpenTelemetry 時,這些值會對應到 gen_ai.usage.cache_creation.input_tokensgen_ai.usage.cache_read.input_tokens

import asyncio
import time

from agent_framework import Content, Message
from agent_framework.openai import OpenAIChatClient, OpenAIChatOptions
from dotenv import load_dotenv

load_dotenv()
# A stable block of context that is reused across requests, for example a product
# catalog, a policy document, or long system guidance. Repeated here to clear the
# 1024-token minimum a cache breakpoint requires.
STABLE_CONTEXT = (
    "You are a support assistant for the Contoso appliance store. "
    "Always answer briefly, quote the relevant catalog section, and never invent "
    "model numbers. If a question is out of scope, say so and point the customer "
    "to support@contoso.example. "
) * 40


def build_messages(question: str) -> list[Message]:
    """Build a request with a cache breakpoint at the end of the stable prefix."""
    return [
        Message(
            role="user",
            contents=[
                Content.from_text(
                    STABLE_CONTEXT,
                    additional_properties={"prompt_cache_breakpoint": {"mode": "explicit"}},
                )
            ],
        ),
        Message(role="user", contents=[Content.from_text(question)]),
    ]


async def main() -> None:
    print("\033[92m=== OpenAI Chat Client Prompt Caching Example ===\033[0m\n")

    client = OpenAIChatClient[OpenAIChatOptions](model="gpt-5.6-luna")
    options: OpenAIChatOptions = {
        "prompt_cache_options": {"mode": "explicit"},
        "prompt_cache_key": f"contoso_appliance_store-{time.time()}",
    }

    questions = ["Do you sell refrigerators?", "What is the return policy contact?"]
    for turn, question in enumerate(questions, start=1):
        response = await client.get_response(build_messages(question), options=options)
        usage = response.usage_details or {}
        cached = usage.get("cache_read_input_token_count", 0)
        cached_write = usage.get("cache_creation_input_token_count", 0)
        print(f"Turn {turn}: {question}")
        print(f"  Answer: {response.text}")
        print(f"  Cached input tokens (read): {cached}\n")
        print(f"  Cached input tokens (created): {cached_write}\n")
        if turn < len(questions):
            # A freshly written cache entry becomes readable shortly after the request
            # completes; the brief pause keeps the next turn from racing this one.
            await asyncio.sleep(2)

    print("The first turn writes the prefix to the cache; later turns read it back.")

使用代理程式

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

更多資訊請參閱 入門教學

工具

Python OpenAI 用戶端會根據底層 API 暴露不同的工具表面。 OpenAIChatClient(回應)透過 client.get_*_tool(...) 提供託管工具工廠——get_code_interpreter_toolget_file_search_toolget_web_search_toolget_image_generation_toolget_shell_toolget_mcp_toolOpenAIChatCompletionClient 只暴露 get_web_search_tool。 兩者都能搭配函式工具和本地 MCP 伺服器運作。

當你將這些客戶端指向 OpenAI Azure,也同樣適用這個矩陣——參見 Azure OpenAI

Tool OpenAIChatClient (回應) OpenAIChatCompletionClient (聊天結束)
函式工具
工具核准
程式碼解譯器
檔案搜尋
網路搜尋
影像生成 ✅ (get_image_generation_tool
託管 Shell ✅ (get_shell_tool
託管 MCP 工具
本地 MCP 工具

Note

工具審核 由框架的函式呼叫聊天客戶端處理,因此無論底層 API 為何,都能對任何函式工具呼叫有效。

OpenAI 對話完成

openaiprovider 套件使用 OpenAI 聊天完成 API 來建立代理。

安裝

go get github.com/microsoft/agent-framework-go

直接使用 OpenAI

import (
    "github.com/microsoft/agent-framework-go/agent"
    "github.com/microsoft/agent-framework-go/provider/openaiprovider"

    "github.com/openai/openai-go/v3"
)

a := openaiprovider.NewChatCompletionsAgent(
    openai.NewClient(), // uses OPENAI_API_KEY env var
    openaiprovider.AgentConfig{
        Model: "gpt-4o-mini",
        Instructions: "You are a helpful assistant.",
        Config: agent.Config{
            Name:         "MyAgent",
        },
    },
)

resp, err := a.RunText(ctx, "Tell me a joke.").Collect()

Azure OpenAI

使用相同的 openaiprovider 套件,搭配 Azure 憑證:

import (
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    openai "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/azure"
)

token, _ := azidentity.NewDefaultAzureCredential(nil)

a := openaiprovider.NewChatCompletionsAgent(
    openai.NewClient(
        azure.WithEndpoint(endpoint, apiVersion),
        azure.WithTokenCredential(token),
    ),
    openaiprovider.AgentConfig{
        Model: deployment,
        Instructions: "You are a helpful assistant.",
        Config: agent.Config{
        },
    },
)

Warning

azidentity.NewDefaultAzureCredential 開發方便,但在生產過程中需謹慎考量。 在生產環境中,建議使用特定的憑證,例如 azidentity.NewManagedIdentityCredential,以避免延遲問題、意外的憑證探測,以及備用機制帶來的安全風險。

自訂選項

使用 openaiprovider.ChatCompletionNewParams 傳遞提供者專屬選項:

resp, err := a.RunText(ctx, "Hello!",
    openaiprovider.ChatCompletionNewParams(openai.ChatCompletionNewParams{
        Temperature: openai.Float(0.7),
    }),
).Collect()

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

Tip

完整範例請參閱 OpenAI 提供者範例Azure OpenAI 範例

下一步