模型#

在许多情况下,代理需要访问 LLM 模型服务,例如 OpenAI、Azure OpenAI 或本地模型。由于有许多不同的提供商使用不同的 API,autogen-core 实现了一个模型客户端协议,而 autogen-ext 实现了一组用于流行模型服务的模型客户端。 AgentChat 可以使用这些模型客户端与模型服务进行交互。

本节提供可用模型客户端的快速概述。有关如何直接使用它们的更多详细信息,请参阅 Core API 文档中的模型客户端

注意

请参阅ChatCompletionCache以获取一个用于以下客户端的缓存包装器。

记录模型调用#

AutoGen 使用标准的 Python 日志模块来记录诸如模型调用和响应之类的事件。记录器名称是autogen_core.EVENT_LOGGER_NAME,事件类型是 LLMCall

import logging

from autogen_core import EVENT_LOGGER_NAME

logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(EVENT_LOGGER_NAME)
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)

OpenAI#

要访问 OpenAI 模型,请安装 openai 扩展,这使您可以使用OpenAIChatCompletionClient

pip install "autogen-ext[openai]"

您还需要从 OpenAI 获取一个 API 密钥

from autogen_ext.models.openai import OpenAIChatCompletionClient

openai_model_client = OpenAIChatCompletionClient(
    model="gpt-4o-2024-08-06",
    # api_key="sk-...", # Optional if you have an OPENAI_API_KEY environment variable set.
)

要测试模型客户端,您可以使用以下代码

from autogen_core.models import UserMessage

result = await openai_model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)
await openai_model_client.close()
CreateResult(finish_reason='stop', content='The capital of France is Paris.', usage=RequestUsage(prompt_tokens=15, completion_tokens=7), cached=False, logprobs=None)

注意

您可以将此客户端与托管在与 OpenAI 兼容的端点上的模型一起使用,但是,我们尚未测试此功能。 有关更多信息,请参见OpenAIChatCompletionClient

Azure OpenAI#

同样,安装 azureopenai 扩展以使用AzureOpenAIChatCompletionClient

pip install "autogen-ext[openai,azure]"

要使用客户端,您需要提供您的部署 ID、Azure 认知服务终结点、API 版本和模型功能。 对于身份验证,您可以提供 API 密钥或 Azure Active Directory (AAD) 令牌凭据。

以下代码段显示了如何使用 AAD 身份验证。 使用的身份必须被分配 认知服务 OpenAI 用户角色。

from autogen_ext.auth.azure import AzureTokenProvider
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
from azure.identity import DefaultAzureCredential

# Create the token provider
token_provider = AzureTokenProvider(
    DefaultAzureCredential(),
    "https://cognitiveservices.azure.com/.default",
)

az_model_client = AzureOpenAIChatCompletionClient(
    azure_deployment="{your-azure-deployment}",
    model="{model-name, such as gpt-4o}",
    api_version="2024-06-01",
    azure_endpoint="https://{your-custom-endpoint}.openai.azure.com/",
    azure_ad_token_provider=token_provider,  # Optional if you choose key-based authentication.
    # api_key="sk-...", # For key-based authentication.
)

result = await az_model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)
await az_model_client.close()

有关如何直接使用 Azure 客户端或获取更多信息,请参见此处

Azure AI Foundry#

Azure AI Foundry(以前称为 Azure AI Studio)提供托管在 Azure 上的模型。要使用这些模型,您可以使用AzureAIChatCompletionClient

您需要安装 azure 额外功能才能使用此客户端。

pip install "autogen-ext[azure]"

以下是使用此客户端和来自 GitHub Marketplace 的 Phi-4 模型的一个示例。

import os

from autogen_core.models import UserMessage
from autogen_ext.models.azure import AzureAIChatCompletionClient
from azure.core.credentials import AzureKeyCredential

client = AzureAIChatCompletionClient(
    model="Phi-4",
    endpoint="https://models.inference.ai.azure.com",
    # To authenticate with the model you will need to generate a personal access token (PAT) in your GitHub settings.
    # Create your PAT token by following instructions here: https://githubdocs.cn/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens
    credential=AzureKeyCredential(os.environ["GITHUB_TOKEN"]),
    model_info={
        "json_output": False,
        "function_calling": False,
        "vision": False,
        "family": "unknown",
        "structured_output": False,
    },
)

result = await client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)
await client.close()
finish_reason='stop' content='The capital of France is Paris.' usage=RequestUsage(prompt_tokens=14, completion_tokens=8) cached=False logprobs=None

Anthropic (实验性)#

要使用AnthropicChatCompletionClient,您需要安装 anthropic 额外功能。 在底层,它使用 anthropic python sdk 来访问模型。 您还需要从 Anthropic 获取一个 API 密钥

# !pip install -U "autogen-ext[anthropic]"
from autogen_core.models import UserMessage
from autogen_ext.models.anthropic import AnthropicChatCompletionClient

anthropic_client = AnthropicChatCompletionClient(model="claude-3-7-sonnet-20250219")
result = await anthropic_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)
await anthropic_client.close()
finish_reason='stop' content="The capital of France is Paris. It's not only the political and administrative capital but also a major global center for art, fashion, gastronomy, and culture. Paris is known for landmarks such as the Eiffel Tower, the Louvre Museum, Notre-Dame Cathedral, and the Champs-Élysées." usage=RequestUsage(prompt_tokens=14, completion_tokens=73) cached=False logprobs=None thought=None

Ollama (实验性)#

Ollama 是一个本地模型服务器,可以在您的机器上本地运行模型。

注意

小型本地模型通常不如云上的大型模型那么强大。 对于某些任务,它们可能表现不佳,并且输出可能令人惊讶。

要使用 Ollama,请安装 ollama 扩展并使用OllamaChatCompletionClient

pip install -U "autogen-ext[ollama]"
from autogen_core.models import UserMessage
from autogen_ext.models.ollama import OllamaChatCompletionClient

# Assuming your Ollama server is running locally on port 11434.
ollama_model_client = OllamaChatCompletionClient(model="llama3.2")

response = await ollama_model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(response)
await ollama_model_client.close()
finish_reason='unknown' content='The capital of France is Paris.' usage=RequestUsage(prompt_tokens=32, completion_tokens=8) cached=False logprobs=None thought=None

Gemini (实验性)#

Gemini 目前提供 与 OpenAI 兼容的 API(测试版)。 因此,您可以将 OpenAIChatCompletionClient 与 Gemini API 一起使用。

注意

虽然某些模型提供商可能提供与 OpenAI 兼容的 API,但它们仍然可能存在细微差异。 例如,finish_reason 字段在响应中可能有所不同。

from autogen_core.models import UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient

model_client = OpenAIChatCompletionClient(
    model="gemini-1.5-flash-8b",
    # api_key="GEMINI_API_KEY",
)

response = await model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(response)
await model_client.close()
finish_reason='stop' content='Paris\n' usage=RequestUsage(prompt_tokens=7, completion_tokens=2) cached=False logprobs=None thought=None

此外,随着 Gemini 添加新模型,您可能需要通过 model_info 字段定义模型功能。 例如,要使用 gemini-2.0-flash-lite 或类似的新模型,您可以使用以下代码

from autogen_core.models import UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core.models import ModelInfo

model_client = OpenAIChatCompletionClient(
    model="gemini-2.0-flash-lite",
    model_info=ModelInfo(vision=True, function_calling=True, json_output=True, family="unknown", structured_output=True)
    # api_key="GEMINI_API_KEY",
)

response = await model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(response)
await model_client.close()

语义内核适配器#

SKChatCompletionAdapter 允许您通过将 Semantic kernel 模型客户端调整到所需的接口,来将其用作ChatCompletionClient

您需要安装相关的提供商额外功能才能使用此适配器。

可以安装的额外功能列表

  • semantic-kernel-anthropic:安装此额外功能以使用 Anthropic 模型。

  • semantic-kernel-google:安装此额外功能以使用 Google Gemini 模型。

  • semantic-kernel-ollama:安装此额外功能以使用 Ollama 模型。

  • semantic-kernel-mistralai:安装此额外功能以使用 MistralAI 模型。

  • semantic-kernel-aws:安装此额外功能以使用 AWS 模型。

  • semantic-kernel-hugging-face:安装此额外功能以使用 Hugging Face 模型。

例如,要使用 Anthropic 模型,您需要安装 semantic-kernel-anthropic

# pip install "autogen-ext[semantic-kernel-anthropic]"

要使用此适配器,您需要创建一个 Semantic Kernel 模型客户端并将其传递给适配器。

例如,要使用 Anthropic 模型

import os

from autogen_core.models import UserMessage
from autogen_ext.models.semantic_kernel import SKChatCompletionAdapter
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.anthropic import AnthropicChatCompletion, AnthropicChatPromptExecutionSettings
from semantic_kernel.memory.null_memory import NullMemory

sk_client = AnthropicChatCompletion(
    ai_model_id="claude-3-5-sonnet-20241022",
    api_key=os.environ["ANTHROPIC_API_KEY"],
    service_id="my-service-id",  # Optional; for targeting specific services within Semantic Kernel
)
settings = AnthropicChatPromptExecutionSettings(
    temperature=0.2,
)

anthropic_model_client = SKChatCompletionAdapter(
    sk_client, kernel=Kernel(memory=NullMemory()), prompt_settings=settings
)

# Call the model directly.
model_result = await anthropic_model_client.create(
    messages=[UserMessage(content="What is the capital of France?", source="User")]
)
print(model_result)
await anthropic_model_client.close()
finish_reason='stop' content='The capital of France is Paris. It is also the largest city in France and one of the most populous metropolitan areas in Europe.' usage=RequestUsage(prompt_tokens=0, completion_tokens=0) cached=False logprobs=None

阅读有关语义内核适配器的更多信息。