这将帮助您开始使用 AzureAIOpenAIApiChatModel 聊天模型.
此 AzureAIOpenAIApiChatModel class uses the OpenAI-compatible API available in Azure AI Foundry. AI Foundry has several chat models, including AzureOpenAI, Cohere, Llama, Phi-3/4, and DeepSeek-R1, among others. You can find information about their latest models and their costs, context windows, and supported input types in the Azure 文档.
概述
集成详情
| 类 | 包 | 可序列化 | JS 支持 | 下载量 | 版本 |
|---|---|---|---|---|---|
ChatOpenAI | langchain-openai | ✅ | ✅ | !PyPI - 下载量 | !PyPI - 版本 |
ChatAnthropic | langchain-anthropic | ✅ | ✅ | !PyPI - 下载量 | !PyPI - 版本 |
AzureAIOpenAIApiChatModel | langchain-azure-ai | ✅ | ✅ | !PyPI - 下载量 | !PyPI - 版本 |
模型特性
| 工具调用 | 结构化输出 | 图像输入 | 音频输入 | 视频输入 | 逐Token流式输出 | 原生异步 | Token使用量 | 对数概率 |
|---|---|---|---|---|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ |
设置
要访问 AzureAIOpenAIApiChatModel 模型,您需要创建一个 Azure 账户,获取API密钥,并安装 langchain-azure-ai 集成包。
凭据
前往 Azure 文档 查看如何创建部署并生成 API 密钥。模型部署后,点击 AI Foundry 中的'获取端点'按钮。这将显示您的端点和 API 密钥。完成此操作后,设置环境变量:
if not os.getenv("AZURE_AI_PROJECT_ENDPOINT"):
os.environ["AZURE_AI_PROJECT_ENDPOINT"] = getpass.getpass(
"Enter your Azure AI project endpoint: "
)
如果您想获取模型调用的自动化追踪,您也可以设置您的 LangSmith API 密钥,方法是将下面的注释取消:
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
安装
LangChain AzureAIOpenAIApiChatModel 集成位于 langchain-azure-ai package:
pip install -qU langchain-azure-ai
实例化
现在我们可以实例化模型对象并生成聊天补全:
from langchain_azure_ai.chat_models import AzureAIOpenAIApiChatModel
from azure.identity import DefaultAzureCredential
llm = AzureAIOpenAIApiChatModel(
model="gpt-4o",
credential=DefaultAzureCredential(),
temperature=0,
max_tokens=None,
max_retries=2,
)
调用
messages = [
(
"system",
"You are a helpful assistant that translates English to French. Translate the user sentence.",
),
("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
ai_msg
AIMessage(content="J'adore programmer.", additional_kwargs={}, response_metadata={'model': 'gpt-4o-2024-05-13', 'token_usage': {'input_tokens': 31, 'output_tokens': 4, 'total_tokens': 35}, 'finish_reason': 'stop'}, id='run-c082dffd-b1de-4b3f-943f-863836663ddb-0', usage_metadata={'input_tokens': 31, 'output_tokens': 4, 'total_tokens': 35})
print(ai_msg.content)
J'adore programmer.