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

在 Microsoft Foundry 中使用模型和 LangChain 开发应用程序(经典版)

注意

本文介绍 Microsoft Foundry (经典) 门户。 如果使用的是新门户,请改用本文的 新版本 。

LangChain 是一个开发人员生态系统,可用于更轻松地构建推理应用程序。 它包括多个组件,其中大多数组件都可以独立使用,因此你可以选取并选择所需的部分。

可以通过两种方式使用在 Microsoft Foundry 中部署的模型与 LangChain 一起使用:

本教程演示如何使用 Azure AI 模型推理 API 将 langchain-azure-ai[v1] 包与 LangChain 配合使用。 某些模型(如 OpenAI、Cohere 或 Mistral)提供自己的 API 和 LangChain 扩展。 这些扩展可能包括特定于模型的功能,如果需要使用这些扩展,则适用。 安装所选模型的扩展,例如 langchain-openai 或 langchain-cohere。

谨慎

模型推理 langchain-azure-ai[v1] 已弃用,将于 2026 年 5 月 30 日停用。 使用 langchain-azure-ai 或 langchain-openai 中引入的稳定 OpenAI SDK,切换到正式发布的 OpenAI/v1 API。 了解详细信息。

先决条件

若要运行本教程,需要:

  • 所需角色:
    • 用于部署模型的 Foundry 资源或 AI 中心的所有者或参与者

    • Foundry 用户可在 Foundry 项目中使用该模型

      Important

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

    • Azure AI 开发人员将使用模型于一个以中心为基础的项目中

  • 支持 模型推理 API 的模型部署。 本文使用 Mistral-Large-3。

  • Python 3.9 或更高版本安装,包括 pip。

  • 已安装 LangChain。 可以使用以下命令安装它:

    pip install langchain
    
  • 安装 Foundry 集成:

    pip install -U langchain-azure-ai[v1]
    

配置环境

若要使用 Microsoft Foundry 门户中部署的 LLM,你需要端点和凭据才能连接到它。 按照以下步骤从要使用的模型获取所需的信息:

  1. 登录到 Microsoft Foundry。 确保New Foundry开关处于打开状态。 这些步骤适用于 Foundry(新版)。

  2. 打开部署模型的项目(如果尚未打开)。

  3. 复制终结点 URL 和密钥。

在此方案中,将终结点 URL 和密钥设置为环境变量。 (如果您复制的终结点在 /models 之后包含其他文本,请将其删除,以使 URL 以 /models 结束,如下所示。)

export AZURE_INFERENCE_ENDPOINT="https://<resource>.services.ai.azure.com/models"
export AZURE_INFERENCE_CREDENTIAL="<your-key-goes-here>"

使用 AzureAIChatCompletionsModel 类创建客户端以连接到聊天模型。

import os
from langchain_azure_ai.chat_models import AzureAIChatCompletionsModel

model = AzureAIChatCompletionsModel(
    endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
    credential=os.environ["AZURE_INFERENCE_CREDENTIAL"],
    model="Mistral-Large-3",
)

此片段的作用:实例化配置为使用 API 密钥进行身份验证来连接到已部署模型的 AzureAIChatCompletionsModel 客户端。 此客户端充当模型推理 API 的接口。

引用:

如果终结点支持Microsoft Entra ID,请使用以下代码创建客户端:

import os
from azure.identity import DefaultAzureCredential
from langchain_azure_ai.chat_models.inference import AzureAIChatCompletionsModel

model = AzureAIChatCompletionsModel(
    endpoint=os.environ["AZURE_AI_INFERENCE_ENDPOINT"],
    credential=DefaultAzureCredential(),
    model="Mistral-Large-3",
)

注意

使用Microsoft Entra ID时,请确保终结点是使用该身份验证方法部署的,并且你具有调用它所需的权限。

如果计划使用异步调用,请使用凭据的异步版本:

from azure.identity.aio import (
    DefaultAzureCredential as DefaultAzureCredentialAsync,
)
from langchain_azure_ai.chat_models.inference import AzureAIChatCompletionsModel

model = AzureAIChatCompletionsModel(
    endpoint=os.environ["AZURE_AI_INFERENCE_ENDPOINT"],
    credential=DefaultAzureCredentialAsync(),
    model="Mistral-Large-3",
)

如果终结点提供单个模型(例如无服务器 API 部署),则不包括参数 model :

import os
from langchain_azure_ai.chat_models.inference import AzureAIChatCompletionsModel

model = AzureAIChatCompletionsModel(
    endpoint=os.environ["AZURE_AI_INFERENCE_ENDPOINT"],
    credential=os.environ["AZURE_AI_CREDENTIAL"],
)

验证设置

使用简单的调用测试客户端连接:

response = model.invoke("Say hello")
print(response.content)

其用途: 使用简单的提示调用模型以验证身份验证和连接。 预期输出:来自模型的问候消息(例如,“Hello!我今天怎么能帮你?

引用:

使用聊天补全模型

直接使用模型。 ChatModels 是 LangChain Runnable 接口的实例,它提供与它们交互的标准方法。 若要调用模型,请将消息列表传递给 invoke 方法。

from langchain_core.messages import HumanMessage, SystemMessage

messages = [
    SystemMessage(content="Translate the following from English into Italian"),
    HumanMessage(content="hi!"),
]

model.invoke(messages)

此代码片段的作用: 演示如何将列表 HumanMessage 和 SystemMessage 对象传递给模型 invoke() 的方法以生成响应。

引用:

根据需要将操作以链的形式组合。 使用提示模板翻译句子:

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

system_template = "Translate the following into {language}:"
prompt_template = ChatPromptTemplate.from_messages(
    [("system", system_template), ("user", "{text}")]
)

该链采用 language 和 text 作为输入。 现在,创建输出分析器:

from langchain_core.output_parsers import StrOutputParser

parser = StrOutputParser()

此代码片段的作用: 创建一个 StrOutputParser,将模型的输出转换为字符串格式,并去除任何额外的元数据。

引用:

使用管道 (|) 运算符组合模板、模型和输出解析器:

chain = prompt_template | model | parser

使用 language 方法提供 text 和 invoke 值来调用链:

chain.invoke({"language": "italian", "text": "hi"})

将多个 LLM 链接在一起

由于 Foundry 中的模型公开了一个常见的模型推理 API,因此你可以链接多个 LLM 操作,并选择最适合每个步骤的模型。

在以下示例中,将创建两个模型客户端:一个生成者和一个验证程序。 若要明确区分,请使用多模型终结点(例如 模型推理 API ),并将 model 参数传递给大型模型进行生成,使用小型模型进行验证。 生成内容通常需要更大的模型,而验证可以使用较小的模型。

from langchain_azure_ai.chat_models import AzureAIChatCompletionsModel

producer = AzureAIChatCompletionsModel(
    endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
    credential=os.environ["AZURE_INFERENCE_CREDENTIAL"],
    model="Mistral-Large-3",
)

verifier = AzureAIChatCompletionsModel(
    endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
    credential=os.environ["AZURE_INFERENCE_CREDENTIAL"],
    model="mistral-small",
)

此代码片段的作用: 实例化两个单独的 AzureAIChatCompletionsModel 客户端:一个用于 Mistral-Large-3 内容生成,另一个用于 Mistral-Small 验证,演示如何为不同的任务选择不同的模型。

引用:

提示

查看每个模型的模型卡,以了解最佳用例。

以下示例生成由城市诗人撰写的诗:

from langchain_core.prompts import PromptTemplate

producer_template = PromptTemplate(
    template="You are an urban poet, your job is to come up \
             verses based on a given topic.\n\
             Here is the topic you have been asked to generate a verse on:\n\
             {topic}",
    input_variables=["topic"],
)

verifier_template = PromptTemplate(
    template="You are a verifier of poems, you are tasked\
              to inspect the verses of poem. If they consist of violence and abusive language\
              report it. Your response should be only one word either True or False.\n \
              Here is the lyrics submitted to you:\n\
              {input}",
    input_variables=["input"],
)

此代码片段的作用: 创建提示模板并将其与 producer 模型客户端链接,以生成创意内容(在本例中为诗)。

将这些部分串联起来:

chain = producer_template | producer | parser | verifier_template | verifier | parser

此代码片段的作用: 通过 verifier 模型链接生成的诗歌,以验证或查看生成的内容,演示生成者-验证程序工作流。

上一个链条仅返回步骤verifier的输出。 若要访问由 producer生成的中间结果,请使用 RunnablePassthrough 来输出该中间步骤。

from langchain_core.runnables import RunnablePassthrough, RunnableParallel

generate_poem = producer_template | producer | parser
verify_poem = verifier_template | verifier | parser

chain = generate_poem | RunnableParallel(poem=RunnablePassthrough(), verification=RunnablePassthrough() | verify_poem)

使用 invoke 方法调用链:

chain.invoke({"topic": "living in a foreign country"})

此代码片段的作用: 使用主题输入调用完整的生成者验证程序链,同时返回生成的内容和验证结果。 预期输出:一个 JSON 对象,包含键 poem(生成的诗歌)和键 verification(验证响应)。

引用:

使用嵌入模型

以类似的方式创建嵌入客户端。 将环境变量设置为指向嵌入模型:

export AZURE_INFERENCE_ENDPOINT="<your-model-endpoint-goes-here>"
export AZURE_INFERENCE_CREDENTIAL="<your-key-goes-here>"

创建客户端:

import os
from langchain_azure_ai.embeddings import AzureAIEmbeddingsModel

embed_model = AzureAIEmbeddingsModel(
    endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
    credential=os.environ["AZURE_INFERENCE_CREDENTIAL"],
    model="text-embedding-3-large",
)

此代码片段的作用: 实例化嵌入客户端,用于 AzureAIEmbeddingsModel 将文本转换为矢量嵌入,可用于语义搜索和相似性比较。

引用:

使用内存中向量存储:

from langchain_core.vectorstores import InMemoryVectorStore

vector_store = InMemoryVectorStore(embed_model)

此代码片段的作用: 创建一个内存中矢量存储(InMemoryVectorStore),用于存储嵌入以执行快速相似性搜索操作。

引用:

添加文档:

from langchain_core.documents import Document

document_1 = Document(id="1", page_content="foo", metadata={"baz": "bar"})
document_2 = Document(id="2", page_content="thud", metadata={"bar": "baz"})

documents = [document_1, document_2]
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}]")

此代码片段的作用: 针对矢量存储执行语义搜索,根据嵌入相似性返回与查询最相似的文档。 预期输出:按相似性分数排名的相关文档列表。

使用 Azure OpenAI 模型

将 Azure OpenAI 模型与 langchain-azure-ai 包配合使用时,请使用以下终结点格式:

import os
from langchain_azure_ai.chat_models.inference import AzureAIChatCompletionsModel

llm = AzureAIChatCompletionsModel(
    endpoint="https://<resource>.openai.azure.com/openai/v1",
    credential=os.environ["AZURE_INFERENCE_CREDENTIAL"],
    model="gpt-4o"
)

此代码片段的作用:使用 Azure OpenAI 终结点格式实例化专门为 Azure OpenAI 模型配置的客户端。 endpoint 参数指向 Azure OpenAI 资源,credential使用存储在环境变量中的 API 密钥。

引用:

调试和故障排除

如果需要调试应用程序并了解发送到 Foundry 中的模型的请求,请使用集成调试功能:

首先,将日志记录配置为所需的级别:

import sys
import logging

# Acquire the logger for this client library. Use 'azure' to affect both
# 'azure.core` and `azure.ai.inference' libraries.
logger = logging.getLogger("azure")

# Set the desired logging level. logging.INFO or logging.DEBUG are good options.
logger.setLevel(logging.DEBUG)

# Direct logging output to stdout:
handler = logging.StreamHandler(stream=sys.stdout)
# Or direct logging output to a file:
# handler = logging.FileHandler(filename="sample.log")
logger.addHandler(handler)

# Optional: change the default logging format. Here we add a timestamp.
formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message)s")
handler.setFormatter(formatter)

此代码片段的作用:在 DEBUG 级别设置Python日志记录,以捕获有关 LangChain 与模型推理 API 之间的 HTTP 请求和响应的详细信息。

引用:

若要查看请求有效负载,请在实例化客户端时,在logging_enable=True中传入client_kwargs。

import os
from langchain_azure_ai.chat_models import AzureAIChatCompletionsModel

model = AzureAIChatCompletionsModel(
    endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
    credential=os.environ["AZURE_INFERENCE_CREDENTIAL"],
    model="Mistral-Large-3",
    client_kwargs={"logging_enable": True},
)

此代码片段的作用: 创建启用了日志记录的客户端,以捕获和显示详细的请求/响应有效负载,有助于调试 API 交互。

像往常一样在代码中使用客户端。

跟踪

在 Foundry 中,通过创建追踪器来使用跟踪。 日志存储在 Azure 应用程序 Insights 中,随时可以使用 Azure Monitor 或 Foundry 门户查询日志。 每个 AI 中心都有一个关联的 Azure 应用程序 Insights 实例。

获取检测连接字符串

提示

由于可以在 Microsoft Foundry 门户中自定义左窗格,因此你可能会看到与这些步骤中显示的项不同。 如果未看到要查找的内容,请选择 ... 左窗格底部的更多内容。

可以使用以下任一方法将应用程序配置为将遥测数据发送到 Azure 应用程序 Insights:

  1. 使用连接字符串直接连接到 Azure 应用程序 Insights:

    1. 转到 Foundry 门户 并选择“ 追踪”。

    2. 选择“ 管理数据源”。 在此屏幕中,可以看到与项目关联的实例。

    3. 复制 连接字符串 处的值并将其设置为以下变量:

      import os
      
      application_insights_connection_string = "instrumentation...."
      
  2. 使用 Microsoft Foundry SDK 和 Foundry Project 接口:

    1. 确保已在环境中安装包 azure-ai-projects 。

    2. 转到 Foundry 门户。

    3. 复制 Foundry 项目终结点 URL,并在以下代码中设置它:

      from azure.ai.projects import AIProjectClient
      from azure.identity import DefaultAzureCredential
      
      project_client = AIProjectClient(
          credential=DefaultAzureCredential(),
          endpoint="<your-foundry-project-endpoint-url>",
      )
      
      application_insights_connection_string = project_client.telemetry.get_application_insights_connection_string()
      

详细了解 如何可视化和管理跟踪。

后续步骤