OpenAI 助手与代理人

Microsoft代理框架支持创建使用 OpenAI 助手 服务的代理。

警告

OpenAI 助手 API 已弃用,将关闭。 有关详细信息,请参阅 OpenAI 文档

入门

将所需的 NuGet 包添加到项目。

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

创建 OpenAI 助手代理

首先需要创建客户端以连接到 OpenAI 服务。

using System;
using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");

OpenAI 支持多个服务,这些服务都提供模型调用功能。 我们将使用 Assistants 客户端创建基于助手的代理。

#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
var assistantClient = client.GetAssistantClient();
#pragma warning restore OPENAI001

若要使用 OpenAI 助手服务,需要在服务中创建助手资源。 可以使用 OpenAI SDK 或使用 Microsoft Agent Framework 帮助程序来完成此作。

使用 OpenAI SDK

使用客户端创建助手并检索它作为 AIAgent

// Create a server-side assistant
var createResult = await assistantClient.CreateAssistantAsync(
    "gpt-4o-mini",
    new() { Name = "Joker", Instructions = "You are good at telling jokes." });

// Retrieve the assistant as an AIAgent
AIAgent agent1 = await assistantClient.GetAIAgentAsync(createResult.Value.Id);

// Invoke the agent and output the text result.
Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate."));

使用 Agent Framework 辅助工具

你还可以一步创建并返回AIAgent

AIAgent agent2 = await assistantClient.CreateAIAgentAsync(
    model: "gpt-4o-mini",
    name: "Joker",
    instructions: "You are good at telling jokes.");

重用 OpenAI 助手

可以通过使用其 ID 检索现有 OpenAI 助手来重复使用它们。

AIAgent agent3 = await assistantClient.GetAIAgentAsync("<agent-id>");

使用代理

代理是标准 AIAgent 代理,支持所有标准代理操作。

有关如何运行和与代理交互的详细信息,请参阅 代理入门教程

先决条件

安装 Microsoft Agent Framework 包。

pip install agent-framework --pre

配置

环境变量

设置 OpenAI 身份验证所需的环境变量:

# Required for OpenAI API access
OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini"  # or your preferred model

或者,可以在项目根目录中使用 .env 文件:

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

入门

从代理框架导入所需的类:

import asyncio
from agent_framework import ChatAgent
from agent_framework.openai import OpenAIAssistantsClient

创建 OpenAI 助手代理

基本代理创建

创建代理的最简单方法是使用 OpenAIAssistantsClient 自动创建和管理助手:

async def basic_example():
    # Create an agent with automatic assistant creation and cleanup
    async with OpenAIAssistantsClient().create_agent(
        instructions="You are a helpful assistant.",
        name="MyAssistant"
    ) as agent:
        result = await agent.run("Hello, how are you?")
        print(result.text)

使用显式配置

可以提供显式配置,而不是依赖于环境变量:

async def explicit_config_example():
    async with OpenAIAssistantsClient(
        ai_model_id="gpt-4o-mini",
        api_key="your-api-key-here",
    ).create_agent(
        instructions="You are a helpful assistant.",
    ) as agent:
        result = await agent.run("What's the weather like?")
        print(result.text)

使用现有助手

可以通过提供现有 OpenAI 助手的 ID 来重复使用:

from openai import AsyncOpenAI

async def existing_assistant_example():
    # Create OpenAI client directly
    client = AsyncOpenAI()

    # Create or get an existing assistant
    assistant = await client.beta.assistants.create(
        model="gpt-4o-mini",
        name="WeatherAssistant",
        instructions="You are a weather forecasting assistant."
    )

    try:
        # Use the existing assistant with Agent Framework
        async with ChatAgent(
            chat_client=OpenAIAssistantsClient(
                async_client=client,
                assistant_id=assistant.id
            ),
            instructions="You are a helpful weather agent.",
        ) as agent:
            result = await agent.run("What's the weather like in Seattle?")
            print(result.text)
    finally:
        # Clean up the assistant
        await client.beta.assistants.delete(assistant.id)

代理功能

函数工具

你可以为助手提供自定义功能:

from typing import Annotated
from pydantic import Field

def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")]
) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny with 25°C."

async def tools_example():
    async with ChatAgent(
        chat_client=OpenAIAssistantsClient(),
        instructions="You are a helpful weather assistant.",
        tools=get_weather,  # Provide tools to the agent
    ) as agent:
        result = await agent.run("What's the weather like in Tokyo?")
        print(result.text)

代码解释器

使助手能够执行 Python 代码:

from agent_framework import HostedCodeInterpreterTool

async def code_interpreter_example():
    async with ChatAgent(
        chat_client=OpenAIAssistantsClient(),
        instructions="You are a helpful assistant that can write and execute Python code.",
        tools=HostedCodeInterpreterTool(),
    ) as agent:
        result = await agent.run("Calculate the factorial of 100 using Python code.")
        print(result.text)

流式处理响应

对即时生成的响应进行获取,以提升用户体验。

async def streaming_example():
    async with OpenAIAssistantsClient().create_agent(
        instructions="You are a helpful assistant.",
    ) as agent:
        print("Assistant: ", end="", flush=True)
        async for chunk in agent.run_stream("Tell me a story about AI."):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()  # New line after streaming is complete

使用代理

代理是标准 BaseAgent 代理,支持所有标准代理操作。

有关如何运行和与代理交互的详细信息,请参阅 代理入门教程

后续步骤