Microsoft Agent Framework 支持 C#、Python 和 Go 中的 OpenAI 代理。 C# 和Python支持两种 OpenAI 客户端类型(响应和聊天完成),而 Go 当前使用聊天完成提供程序。 当可用时,建议使用响应的主要客户端:它面向较新的 OpenAI 响应 API,并支持完整的托管工具集(代码解释器、文件搜索、Web 搜索、托管 MCP、图像生成)。 如果需要广泛的模型兼容性、Go 支持或者有现有的 Chat Completions 集成要保留,使用 Chat Completions。
| 客户端类型 | API | 最适用于 |
|---|---|---|
| 响应 (建议) | 响应 API | 具有托管工具的全功能代理(代码解释器、文件搜索、Web 搜索、托管 MCP) |
| 聊天完成 | 聊天完成 API | 简单代理,广泛的模型支持 |
注释
OpenAI 助手 API 已由 OpenAI 弃用。 新代码应使用 Responses 客户端。 如果要从基于助手的现有应用进行迁移,请参阅 语义内核 迁移指南。
入门
将所需的 NuGet 包添加到项目。
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
Responses 客户端
响应客户端是推荐的主要客户端,提供最丰富的工具支持,包括代码解释器、文件搜索、Web 搜索和托管 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."));
支持的工具: 函数工具、工具审批、代码解释器、文件搜索、Web 搜索、托管 MCP、本地 MCP 工具。
Chat Completion 客户端
聊天完成客户端提供了使用聊天完成 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."));
支持的工具: 函数工具、Web 搜索、本地 MCP 工具。
助手客户端
注释
OpenAI 助手 API 已由 OpenAI 弃用。 Agent Framework 不再记录 Assistants 客户端 — 对新代码使用上面的 Responses 客户端。 有关迁移现有应用,请参阅 语义内核 迁移指南。
使用代理
这两种客户端类型都生成支持相同代理操作(流式处理、线程、中间件)的标准 AIAgent 。
有关详细信息,请参阅 入门教程。
工具
OpenAI .NET客户端根据它们所面向的 API 公开不同的工具图面。 相同的对应矩阵也适用于 Azure OpenAI 提供程序页 上对应的 Azure OpenAI 客户端。
| 工具 | Responses | 聊天完成 |
|---|---|---|
| 函数工具 | ✅ | ✅ |
| 工具审批 | ✅ | ✅ |
| 代码解释器 | ✅ | ❌ |
| 文件搜索 | ✅ | ❌ |
| Web 搜索 | ✅ | ✅ |
| 托管 MCP 工具 | ✅ | ❌ |
| 本地 MCP 工具 | ✅ | ✅ |
注释
工具批准由框架中支持函数调用的聊天客户端提供,因此无论底层 API 是什么,它都适用于任何函数工具调用。
注释
OpenAI Assistants API 已被 OpenAI 弃用,且 Python 不再随附 Assistants 兼容客户端/提供程序。 对 Responses 使用 OpenAIChatClient,对 Chat Completions 使用 OpenAIChatCompletionClient。 如果要从以前的 Agent Framework Python 版本迁移,请参阅 Python 重大更改指南。 如果要从语义内核迁移,请参阅 语义内核 迁移指南。
小窍门
在 Python 中,Azure OpenAI 现在使用此处所示的相同 agent_framework.openai 客户端。 传递显式 Azure 路由输入,例如 credential 或 azure_endpoint ,当需要 Azure 路由时,然后为您要使用的 Azure API 接口设置 api_version 。 如果已配置OPENAI_API_KEY,则即使存在AZURE_OPENAI_*变量,通用客户端也会保留在OpenAI上。 如果已有完整的 .../openai/v1 URL,请使用 base_url 而不是 azure_endpoint。 有关 Microsoft Foundry 项目终结点和 Foundry 代理服务,请参阅 Microsoft Foundry 提供程序页。 有关本地运行时,请参阅 Foundry Local。
安装
pip install agent-framework-openai
agent-framework-openai 是用于直接 OpenAI 和 Azure OpenAI 用法的可选 Python 提供程序包。
配置
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 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 = OpenAIChatClient().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 = OpenAIChatClient().as_agent(
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"
流媒体
async def streaming_example():
agent = OpenAIChatClient().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。
有关详细信息,请参阅 入门教程。
工具
Python OpenAI 客户端根据基础 API 公开不同的工具图面。
OpenAIChatClient (Responses) 通过 client.get_*_tool(...) 提供托管工具工厂 — get_code_interpreter_tool、get_file_search_tool、get_web_search_tool、get_image_generation_tool、get_shell_tool 和 get_mcp_tool。
OpenAIChatCompletionClient 只暴露 get_web_search_tool。 两者都可与函数工具和本地 MCP 服务器配合使用。
将这些客户端指向 Azure OpenAI 时,将应用相同的矩阵 — 请参阅 Azure OpenAI。
| 工具 |
OpenAIChatClient (答复) |
OpenAIChatCompletionClient (聊天完成) |
|---|---|---|
| 函数工具 | ✅ | ✅ |
| 工具审批 | ✅ | ✅ |
| 代码解释器 | ✅ | ❌ |
| 文件搜索 | ✅ | ❌ |
| Web 搜索 | ✅ | ✅ |
| 映像生成 |
✅(get_image_generation_tool) |
❌ |
| 托管 Shell |
✅(get_shell_tool) |
❌ |
| 托管 MCP 工具 | ✅ | ❌ |
| 本地 MCP 工具 | ✅ | ✅ |
注释
工具审批由框架中具备函数调用能力的聊天客户端处理,因此它可用于任何函数工具调用,而与底层 API 无关。
OpenAI 聊天补全
该 openaiprovider 包使用 OpenAI 聊天完成 API 创建代理。
安装
go get github.com/microsoft/agent-framework-go
Direct 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()
支持的工具: 函数工具、Web 搜索、本地 MCP 工具。
小窍门
有关完整示例,请参阅 OpenAI 提供程序示例和 Azure OpenAI 示例。