Microsoft Agent Framework 支持三种不同的 OpenAI 客户端类型,每个类型面向具有不同工具功能的不同 API 图面:
| 客户端类型 | API | 最适用于 |
|---|---|---|
| 聊天完成 | 聊天完成 API | 简单代理,广泛的模型支持 |
| 反应 | 响应 API | 具有托管工具的全功能代理(代码解释器、文件搜索、Web 搜索、托管 MCP) |
| 助手 | 助手 API | 具有代码解释器和文件搜索的服务器托管代理 |
小窍门
有关 Azure OpenAI 的等效项(AzureOpenAIChatClient、AzureOpenAIResponsesClient、AzureOpenAIAssistantsClient),可以查看 Azure OpenAI 提供程序页以获取更多信息。 工具支持是相同的。
入门
将所需的 NuGet 包添加到项目。
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
聊天完成客户端
聊天完成客户端提供了使用 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."));
支持的工具: 函数工具、Web 搜索、本地 MCP 工具。
响应客户端
响应客户端提供最丰富的工具支持,包括代码解释器、文件搜索、Web 搜索和托管 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."));
支持的工具: 函数工具、工具审批、代码解释器、文件搜索、Web 搜索、托管 MCP、本地 MCP 工具。
助手客户端
Assistants 客户端使用内置代码解释器和文件搜索创建服务器管理的代理。
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 。
有关详细信息,请参阅 入门教程。
安装
pip install agent-framework --pre
配置
每个客户端类型使用不同的环境变量:
聊天补全
OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini"
Responses
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 使用聊天完成 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())
支持的工具: 函数工具、Web 搜索、本地 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 使用响应 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())
支持的工具: 函数工具、工具审批、代码解释器、文件搜索、Web 搜索、托管 MCP、本地 MCP 工具。
包含响应客户端的托管工具
响应客户端为每个托管工具类型提供 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 使用助手 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。
有关详细信息,请参阅 入门教程。