你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

在 Microsoft Foundry 中将 LangChain 与模型配合使用

使用 langchain-azure-ai 生成调用 Microsoft Foundry 中部署的模型的 LangChain 应用。 可以直接使用与 OpenAI 兼容的 API 的模型。 在本文中,你将创建聊天和嵌入客户端、运行提示链,并将生成与验证工作流相结合。

先决条件

  • 一个 Azure 订阅。 免费创建一个。

  • Foundry 项目。

  • Foundry 项目中的 用户 角色。

    重要

    Foundry RBAC 角色最近已更名。 Foundry 用户、Foundry 所有者、Foundry 帐户所有者和 Foundry 项目经理之前的名称分别为“Azure AI 用户”、“Azure AI 所有者”、“Azure AI 帐户所有者”和“Azure AI 项目经理”。 在重命名推出时,你仍可能会在某些位置看到以前的名称。重命名后,角色 ID 和核心权限保持不变。

  • 支持 OpenAI 兼容的 API(例如 gpt-4.1 或 Mistral-Large-3)的已部署聊天模型。

  • 已部署的嵌入模型,例如 text-embedding-3-large。

  • Python 3.11 或更高版本。

安装所需的包:

pip install -U langchain langchain-azure-ai azure-identity

重要

langchain-azure-ai使用新的 Microsoft Foundry SDK (v2)。 如果你使用的是 Foundry classic,请使用 langchain-azure-ai[v1],其使用的是 Azure AI 推理 SDK(已停用)。 了解详细信息。

配置环境

设置以下连接模式之一:

  • 使用 Microsoft Entra ID 项目的终结点(推荐)。
  • 使用 API 密钥的直接端点。
import os

# Option 1: Project endpoint (recommended)
os.environ["FOUNDRY_PROJECT_ENDPOINT"] = (
	"https://<resource>.services.ai.azure.com/api/projects/<project>"
)

# Option 2: Direct OpenAI-compatible endpoint + API key
os.environ["OPENAI_BASE_URL"] = (
	"https://<resource>.services.ai.azure.com/openai/v1"
)
os.environ["OPENAI_API_KEY"] = "<your-api-key>"

此代码片段的作用: 定义供模型类使用的环境变量,以用于项目基础或直接终结点的访问。

使用聊天模型

可以使用以下方法 init_chat_model轻松实例化模型:

from langchain.chat_models import init_chat_model

model = init_chat_model("azure_ai:gpt-4.1")

重要

使用 init_chat_model 需要 langchain>=1.2.13。 如果无法更新版本, 请直接配置客户端。

支持 OpenAI 兼容 API 的所有 Foundry 模型都可以与客户端一起使用,但首先需要将它们部署到 Foundry 资源。 使用 project_endpoint(环境变量 FOUNDRY_PROJECT_ENDPOINT)需要使用 Microsoft Entra ID 进行身份验证,并具有 Foundry User 角色。

此代码片段的作用: 使用 init_chat_model 便捷方法创建聊天模型客户端。 客户端通过在环境中配置的 Foundry 项目终结点或直接终结点路由到指定的模型。

引用:

验证设置

运行简单的模型调用:

response = model.invoke("Say hello")
response.pretty_print()
================================== Ai Message ==================================
Hello! 👋 How can I help you today?

此代码片段的作用: 发送基本提示以验证终结点、身份验证和模型路由。

引用:

可配置模型

还可以通过指定 configurable_fields来创建运行时可配置的模型。 省略 model 参数时,它默认变为可配置字段。

from langchain.chat_models import init_chat_model
from azure.identity import DefaultAzureCredential

configurable_model = init_chat_model(
    model_provider="azure_ai", 
    temperature=0,
	credential=DefaultAzureCredential()
)


configurable_model.invoke(
    "what's your name",
    config={"configurable": {"model": "gpt-5-nano"}},  # Run with GPT-5-nano
).pretty_print()

configurable_model.invoke(
    "what's your name",
    config={"configurable": {"model": "Mistral-Large-3"}}, # Run with Mistral Large
).pretty_print()
================================== Ai Message ==================================

Hi! I'm ChatGPT, an AI assistant built by OpenAI. You can call me ChatGPT or just Assistant. How can I help you today?
================================== Ai Message ==================================

I don't have a name, but you can call me **Assistant** or anything you like! 😊 What can I help you with today?

此代码片段的作用: 创建一个可配置的模型实例,用于在调用时轻松切换模型。 model由于init_chat_model中缺少参数,因此默认情况下它是可配置的字段,可以通过invoke()传递。 可以通过配置 configurable_fields 来添加其他可配置字段。

直接配置客户端

还可以使用 AzureAIOpenAIApiChatModel 类创建聊天模型客户端。

import os

from azure.identity import DefaultAzureCredential
from langchain_azure_ai.chat_models import AzureAIOpenAIApiChatModel

model = AzureAIOpenAIApiChatModel(
	project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
	credential=DefaultAzureCredential(),
	model="Mistral-Large-3",
)

默认情况下, AzureAIOpenAIApiChatModel 使用 OpenAI 响应 API。 可以通过传递 use_responses_api=False以下方法更改此行为:

import os

from azure.identity import DefaultAzureCredential
from langchain_azure_ai.chat_models import AzureAIOpenAIApiChatModel

model = AzureAIOpenAIApiChatModel(
    endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential(),
    model="Mistral-Large-3",
    use_responses_api=False
)

运行异步调用

如果您的应用使用ainvoke调用模型,请使用异步凭据。 使用 Microsoft Entra ID 进行身份验证时,对凭据使用相应的异步实现:

import os

from azure.identity.aio import DefaultAzureCredential as DefaultAzureCredentialAsync
from langchain_azure_ai.chat_models import AzureAIOpenAIApiChatModel

model = AzureAIOpenAIApiChatModel(
	project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
	credential=DefaultAzureCredentialAsync(),
	model="gpt-4.1",
)


async def main():
	response = await model.ainvoke("Say hello asynchronously")
	response.pretty_print()


import asyncio
asyncio.run(main())

提示

如果在 Jupyter 笔记本中运行此代码,可以直接使用 await main() ,而不是 asyncio.run(main())。

================================== Ai Message ==================================
Hello! 👋 How can I help you today?

此代码片段的作用: 创建异步客户端,并运行非阻塞请求 ainvoke。

引用:

推理

许多模型可以执行多步骤推理来得出结论。 这涉及到将复杂问题分解为更小、更易于管理的步骤。

from langchain.chat_models import init_chat_model

model = init_chat_model("azure_ai:DeepSeek-R1-0528")

for chunk in model.stream("Why do parrots have colorful feathers?"):
    reasoning_steps = [r for r in chunk.content_blocks if r["type"] == "reasoning"]
    print(reasoning_steps if reasoning_steps else chunk.text, end="")

print("\n")
Parrots have colorful feathers primarily due to a combination of evolutionary ...

引用:

服务器端工具

在 Foundry 中部署的 OpenAI 模型支持服务器端工具调用循环:模型可以与 Web 搜索、代码解释器和其他工具交互,然后在单个对话轮次中分析结果。 如果模型调用工具服务器端,响应消息的内容将包含表示调用和工具结果的内容。

重要

命名空间中的 langchain_azure_ai.tools.builtin 工具仅在 OpenAI 模型中受支持。

这些工具由 OpenAI 提供,用于扩展模型的功能。 若要查看受支持工具的完整列表,请参阅 内置工具。

以下示例演示如何使用 Web 搜索:

from langchain.chat_models import init_chat_model
from langchain_azure_ai.tools.builtin import WebSearchTool
from azure.identity import DefaultAzureCredential

model = init_chat_model("azure_ai:gpt-4.1", credential=DefaultAzureCredential())
model_with_web_search = model.bind_tools([WebSearchTool()])

result = model_with_web_search.invoke("What is the current price of gold? Give me the answer in one sentence.")
result.content[-1]["text"]
As of today, March 24, 2026, the spot price of gold is approximately $4,397.80 per ounce. ([tradingeconomics.com](https://tradingeconomics.com/commodity/gold))

某些工具可能需要配置项目中的其他资源。 使用 azure-ai-projects 来配置这些资源,然后从 LangChain/LangGraph 调用它们。

以下示例演示如何在工具中使用文件存储之前对其进行配置:

import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential

# Create clients to call Foundry API
project = AIProjectClient(
    endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()

# Create vector store and upload file
vector_store = openai.vector_stores.create(name="ProductInfoStore")
vector_store_id = vector_store.id

with open("product_info.md", "rb") as file_handle:
    vector_store_file = openai.vector_stores.files.upload_and_poll(
        vector_store_id=vector_store.id,
        file=file_handle,
    )

此代码片段的作用是:在 Microsoft Foundry 中设置一个带有文件的向量存储库,以便模型可以稍后搜索该文件的内容(在下一个代码块中与 FileSearchTool 一起使用)。

from langchain_azure_ai.tools.builtin import FileSearchTool

model_with_tools = model.bind_tools([FileSearchTool(vector_store_ids=[vector_store.id])])

results = model_with_tools.invoke("Tell me about Contoso products")
print("Answer:", results.content[-1]["text"])
print("Annotations:", results.content[-1]["annotations"])
Answer: Contoso offers the following products:

1. **The widget**
   - Description: A high-quality widget that is perfect for all your widget needs.
   - Price: $19.99

2. **The gadget**
   - Description: An advanced gadget that offers exceptional performance and reliability.
   - Price: $49.99

These products are part of Contoso's main offerings as detailed in their product information documentation.
Annotations: [{'file_id': 'assistant-MvU5SEqUcUBumoLUV5BXxn', 'filename': 'product_info.md', 'type': 'file_citation', 'file_index': 395}]

在代理中使用 Foundry 模型

与 create_agent 连接到 Foundry 的模型一起使用,以创建 ReAct 风格的智能体循环:

from langchain.agents import create_agent

agent = create_agent(
    model="azure_ai:gpt-5.2", 
    system_prompt="You're an informational agent. Answer questions cheerfully.", 
)

response = agent.invoke({"messages": "what's your name?"})
response["messages"][-1].pretty_print()
================================== Ai Message ==================================

I’m ChatGPT, your AI assistant.

还可以使用服务器端工具,但它们需要调用 bind_tools。

from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
from langchain_azure_ai.tools.builtin import ImageGenerationTool

model = init_chat_model("azure_ai:gpt-5.2")
tools = [ImageGenerationTool(model="gpt-image-1.5", size="1024x1024")]
model_with_tools = model.bind_tools(tools)

agent = create_agent(
    model=model_with_tools,
    tools=tools,
    system_prompt="You're an informational agent. Answer questions with graphics.", 
)

提示

Foundry 中的映像生成工具需要将映像生成的模型部署名称作为标头 x-ms-oai-image-generation-deployment的一部分传递。 使用 langchain-azure-ai时,会自动处理此问题。 但是,如果打算将此工具与 langchain-openai 一起使用,则必须手动传递标头信息。

使用嵌入模型

可以使用以下方法 init_embeddings轻松实例化模型:

from langchain.embeddings import init_embeddings
from azure.identity import DefaultAzureCredential

embed_model = init_embeddings(
    "azure_ai:text-embedding-3-small",
    credential=DefaultAzureCredential(),
)

此代码片段的作用: 使用 init_embeddings 便捷方法创建嵌入模型客户端。 与 init_chat_model 不同,init_embeddings 不会自动回退到 DefaultAzureCredential,因此请显式传递凭据。

支持 OpenAI 兼容 API 的所有 Foundry 模型都可以与客户端一起使用,但首先需要将它们部署到 Foundry 资源。 使用 project_endpoint(环境变量 FOUNDRY_PROJECT_ENDPOINT)需要使用 Microsoft Entra ID 进行身份验证,并具有 Foundry User 角色。

或者使用 AzureAIOpenAIApiEmbeddingsModel.. 创建嵌入客户端。

import os

from azure.identity import DefaultAzureCredential
from langchain_azure_ai.embeddings import AzureAIOpenAIApiEmbeddingsModel

embed_model = AzureAIOpenAIApiEmbeddingsModel(
	project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
	credential=DefaultAzureCredential(),
	model="text-embedding-3-large",
)

对于直接终结点和 API 密钥身份验证:

import os

from langchain_azure_ai.embeddings import AzureAIOpenAIApiEmbeddingsModel

embed_model = AzureAIOpenAIApiEmbeddingsModel(
	endpoint=os.environ["OPENAI_BASE_URL"],
	credential=os.environ["OPENAI_API_KEY"],
	model="text-embedding-3-large",
)

此代码片段的作用: 设置矢量搜索、检索和排序工作流的嵌入生成配置。

引用:

示例:使用矢量存储运行相似性搜索

使用内存中矢量存储进行本地试验。

from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore

vector_store = InMemoryVectorStore(embed_model)

documents = [
	Document(id="1", page_content="foo", metadata={"baz": "bar"}),
	Document(id="2", page_content="thud", metadata={"bar": "baz"}),
]

vector_store.add_documents(documents=documents)

results = vector_store.similarity_search(query="thud", k=1)
for doc in results:
	print(f"* {doc.page_content} [{doc.metadata}]")
* thud [{'bar': 'baz'}]

此代码片段的作用: 将示例文档添加到矢量存储,并返回查询最相似的文档。

引用:

使用日志记录调试请求

启用 langchain_azure_ai 调试日志记录以检查请求流。

import logging
import sys

logger = logging.getLogger("langchain_azure_ai")
logger.setLevel(logging.DEBUG)

handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter(
	"%(asctime)s:%(levelname)s:%(name)s:%(message)s"
)
handler.setFormatter(formatter)
logger.addHandler(handler)

此代码片段的作用:设置Python日志记录,以生成详细的SDK日志,帮助排查端点或有效负载问题。

引用:

环境变量参考

可以配置以下环境变量。 构造对象时还可以配置这些值:

变量 作用 例子 构造函数中的参数
FOUNDRY_PROJECT_ENDPOINT Foundry 项目终结点。 使用项目终结点需要Microsoft Entra ID身份验证(建议)。 https://contoso.services.ai.azure.com/api/projects/my-project project_endpoint
AZURE_OPENAI_ENDPOINT OpenAI 资源的根目录。 https://contoso.openai.azure.com 没有。
OPENAI_BASE_URL 用于模型调用的直接 OpenAI 兼容终结点。 https://contoso.services.ai.azure.com/openai/v1 endpoint
OPENAI_API_KEY 或 AZURE_OPENAI_API_KEY 用于 OPENAI_BASE_URL 或 AZURE_OPENAI_ENDPOINT 的基于密钥的身份验证的 API 密钥。 <your-api-key> credential
AZURE_OPENAI_DEPLOYMENT_NAME Foundry 或 OpenAI 资源中的模型部署名称。 检查 Foundry 门户中的名称,因为部署名称可能不同于使用的基础模型。 可以使用支持 OpenAI 兼容 API 的任何模型,但并非所有参数都受支持。 Mistral-Large-3 model
AZURE_OPENAI_API_VERSION 要使用的 API 版本。 当 api_version 可用时,我们构造 OpenAI 客户端,并通过 api-version 注入 default_query 查询参数。 v1 或 preview api_version

重要

不再使用用于 AZURE_AI_INFERENCE_ENDPOINT 或 AZURE_AI_CREDENTIALS (旧版)的环境变量 AzureAIChatCompletionsModel 和 AzureAIEmbeddingsModel。

下一步