模型#
在许多情况下,智能体需要访问LLM模型服务,例如OpenAI、Azure OpenAI或本地模型。由于存在众多不同API的供应商,autogen-core
实现了模型客户端协议,而autogen-ext
则为流行模型服务实现了一系列模型客户端。AgentChat可以使用这些模型客户端与模型服务交互。
本节快速概述可用的模型客户端。 有关直接使用它们的更多细节,请参阅核心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-...", # 可选,如果您已设置OPENAI_API_KEY环境变量
)
要测试模型客户端,可以使用以下代码:
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#
同样地,安装 azure
和 openai
扩展以使用 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
# 创建令牌提供程序
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, # 如果选择基于密钥的认证,此项为可选。
# api_key="sk-...", # 用于基于密钥的认证
)
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",
# 要与模型进行身份验证, 您需要在 GitHub 设置中生成个人访问令牌(PAT)。 请按照此处的说明创建您的 PAT 令牌:
# https://docs.github.com/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
# 假设您的 Ollama 服务器在本地 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()
Llama API (实验性功能)#
Llama API 是 Meta 官方提供的 API 服务。它目前提供了 OpenAI 兼容的端点。
因此您可以使用 OpenAIChatCompletionClient
来连接 Llama API。
该端点完全支持以下 OpenAI 客户端库功能:
聊天补全
模型选择
温度/采样控制
流式传输
图像理解
结构化输出 (JSON 模式)
函数调用 (工具)
from pathlib import Path
from autogen_core import Image
from autogen_core.models import UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient
# 文本
model_client = OpenAIChatCompletionClient(
model="Llama-4-Scout-17B-16E-Instruct-FP8",
# api_key="LLAMA_API_KEY"
)
response = await model_client.create([UserMessage(content="Write me a poem", source="user")])
print(response)
await model_client.close()
# 图片
model_client = OpenAIChatCompletionClient(
model="Llama-4-Maverick-17B-128E-Instruct-FP8",
# api_key="LLAMA_API_KEY"
)
image = Image.from_file(Path("test.png"))
response = await model_client.create([UserMessage(content=["What is in this image", image], source="user")])
print(response)
await model_client.close()
Semantic Kernel 适配器#
SKChatCompletionAdapter
允许你将 Semantic Kernel 模型客户端适配为
ChatCompletionClient
接口使用。
使用此适配器需要安装相关的 provider extras。
可安装的 extras 列表:
semantic-kernel-anthropic
: 安装此 extra 以使用 Anthropic 模型semantic-kernel-google
: 安装此 extra 以使用 Google Gemini 模型semantic-kernel-ollama
: 安装此 extra 以使用 Ollama 模型semantic-kernel-mistralai
: 安装此 extra 以使用 MistralAI 模型semantic-kernel-aws
: 安装此 extra 以使用 AWS 模型semantic-kernel-hugging-face
: 安装此 extra 以使用 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", # 可选;用于定位Semantic Kernel中的特定服务
)
settings = AnthropicChatPromptExecutionSettings(
temperature=0.2,
)
anthropic_model_client = SKChatCompletionAdapter(
sk_client, kernel=Kernel(memory=NullMemory()), prompt_settings=settings
)
# 直接调用模型。
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
了解更多关于Semantic Kernel适配器的信息。