OpenAI ChatCompletion 代理

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

入门

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

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

创建 OpenAI ChatCompletion 代理

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

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

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

OpenAI 支持多个服务,这些服务都提供模型调用功能。 我们需要选择 ChatCompletion 服务来创建基于 ChatCompletion 的代理。

var chatCompletionClient = client.GetChatClient("gpt-4o-mini");

最后,使用 CreateAIAgent 扩展方法在 ChatCompletionClient 上创建代理。

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

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

使用代理

代理是标准的AIAgent,支持所有标准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 OpenAIChatClient

创建 OpenAI ChatCompletion 代理

基本代理创建

创建聊天完成代理的最简单方法:

async def basic_example():
    # Create an agent using OpenAI ChatCompletion
    agent = OpenAIChatClient().create_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("Hello, how can you help me?")
    print(result.text)

使用显式配置

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

async def explicit_config_example():
    agent = OpenAIChatClient(
        ai_model_id="gpt-4o-mini",
        api_key="your-api-key-here",
    ).create_agent(
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("What can you do?")
    print(result.text)

代理功能

函数工具

为代理配备自定义功能:

from typing import Annotated
from pydantic import Field

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

async def tools_example():
    agent = ChatAgent(
        chat_client=OpenAIChatClient(),
        instructions="You are a helpful weather assistant.",
        tools=get_weather,  # Add tools to the agent
    )

    result = await agent.run("What's the weather like in Tokyo?")
    print(result.text)

流式处理响应

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

async def streaming_example():
    agent = OpenAIChatClient().create_agent(
        name="StoryTeller",
        instructions="You are a creative storyteller.",
    )

    print("Assistant: ", end="", flush=True)
    async for chunk in agent.run_stream("Tell me a short story about AI."):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()  # New line after streaming

使用代理

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

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

后续步骤