模型#
在许多情况下,代理需要访问LLM模型服务,如OpenAI、Azure OpenAI或本地模型。由于有许多不同的提供商提供不同的API,autogen-core
实现了一个模型客户端协议,而autogen-ext
则实现了一组用于流行模型服务的模型客户端。AgentChat可以使用这些模型客户端与模型服务进行交互。
本节快速概述了可用的模型客户端。 有关如何直接使用它们的更多详细信息,请参阅核心API文档中的模型客户端。
注意
请参阅 ChatCompletionCache
了解与以下客户端一起使用的缓存包装器。
OpenAI#
要访问OpenAI模型,请安装openai
扩展,该扩展允许您使用OpenAIChatCompletionClient
。
pip install "autogen-ext[openai]"
您还需要从OpenAI获取一个API key。
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)
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进行身份验证。 所使用的身份必须被分配Cognitive Services OpenAI User角色。
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
# Create the token provider
token_provider = get_bearer_token_provider(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.
)
请参见此处了解如何直接使用Azure客户端或获取更多信息。
Azure AI 铸造厂#
Azure AI Foundry(以前称为Azure AI Studio)提供了托管在Azure上的模型。
要使用这些模型,您可以使用AzureAIChatCompletionClient
。
您需要安装azure
额外包以使用此客户端。
pip install "autogen-ext[azure]"
以下是使用该客户端与Phi-4模型的示例,来自GitHub Marketplace。
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://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",
},
)
result = await client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)
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)
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)
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)
finish_reason='stop' content='Paris\n' usage=RequestUsage(prompt_tokens=7, completion_tokens=2) cached=False logprobs=None thought=None
语义内核适配器#
SKChatCompletionAdapter
允许你将语义内核模型客户端适配为所需的接口,从而作为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)
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适配器的内容。