你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
使用 langchain-azure-ai 包将 LangGraph 和 LangChain 应用程序连接到 Foundry 代理服务。 本文逐步介绍实际场景,从使用现有智能体和组合多智能体图到启用工具的工作流、人工介入审批和跟踪。
先决条件
- 一个 Azure 订阅。 免费创建一个。
- Foundry 项目。
- 项目中已部署的聊天模型(例如
gpt-4.1)。 - Python 3.11 或更高版本。
- Azure CLI登录(
az login),以便DefaultAzureCredential进行身份验证。
一些示例需要其他资源:
- 代码解释器示例需要 受支持的区域和模型。
- 图像生成示例需要一个
gpt-image-1.5部署。 在项目中部署模型 。 如果需要,申请模型访问权限。 - 文件搜索示例需要包含至少一个索引文件的矢量存储。 有关设置说明,请参阅 “使用文件搜索工具”。
请配置您的环境
安装包 langchain-azure-ai,以在 LangGraph 和 LangChain 中使用 Microsoft Foundry 功能。
pip install langchain-azure-ai[tools,opentelemetry] azure-identity
验证Python版本、包安装和Azure登录:
python --version
python -c "import langchain_azure_ai; print('langchain-azure-ai is installed')"
az account show --output table
提示
安装附加功能[tools],以使用文档智能或Azure 逻辑应用连接器等工具。 安装 [opentelemetry] 以包含对 OpenTelemetry 的支持,以及生成式 AI 解决方案的语义约定。
设置本教程中使用的环境变量:
export AZURE_AI_PROJECT_ENDPOINT="https://<resource>.services.ai.azure.com/api/projects/<project>"
export MODEL_DEPLOYMENT_NAME="gpt-4.1"
使用 Foundry 智能体服务智能体
该类 AgentServiceFactory 是您在 LangGraph 中构建与 Foundry 中代理服务进行交互的代理的起点。
工厂创建与 LangGraph 兼容的节点,这些节点通过代理服务运行,并可用于使用 LangGraph 编写更复杂的解决方案。
通过将类连接到 AgentServiceFactory Foundry 项目来创建代理工厂。 通过此工厂创建或引用的所有智能体都在项目内管理,并在 Foundry 门户(新版)中可见。
注意
从 Foundry 经典迁移: 创建的 langchain_azure_ai.agents.v1.AgentServiceFactory 代理仅在 Foundry 门户(经典)中可见。
import os
from langchain_core.messages import HumanMessage
from azure.identity import DefaultAzureCredential
from langchain_azure_ai.agents import AgentServiceFactory
from langchain_azure_ai.utils.agents import pretty_print
factory = AgentServiceFactory(
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
)
使用现有代理
建议在 Foundry 门户或 Foundry SDK 中创建和配置代理,然后通过名称 get_agent_node 引用它们以构建图表。 建议使用此方法,因为它使代理配置集中在 Foundry 中,并使代码专注于业务流程。 如果需要在代码中完全定义代理,还可以以编程方式 create_prompt_agent 创建代理。
echo_node = factory.get_agent_node(
name="my-echo-agent",
version="latest",
)
此代码片段的作用: 检索对现有 Foundry 代理作为与 LangGraph 兼容的节点的引用。 代理必须已存在于 Foundry 项目中。 使用 version="latest" 来始终定位最新版本,或指定特定版本号以确保稳定性。
测试代理是否可以运行:
response = echo_node.invoke(
{"messages": [HumanMessage(content="Hello, world!")]}
)
pretty_print(response)
================================ Human Message =================================
Hello, world!
================================== Ai Message ==================================
Name: my-echo-agent
Goodbye, world!
对话和状态
附加到代理服务的节点会自动跟踪会话中的响应。 该 azure_ai_agents_conversation_id 属性将添加到状态,以便可以引用或继续对话:
print(
"azure_ai_agents_conversation_id:",
response["azure_ai_agents_conversation_id"],
)
azure_ai_agents_conversation_id: <conversation-id>
使用现有代理构建图表
可以使用代理服务节点和 LangGraph 中的其他任何节点一样生成复杂的图形。 以下示例生成条件路由图,其中本地 router_node 检查用户消息,并确定是否委托给 Foundry 代理。
from typing import Literal
from langchain_core.messages import AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
class RouterState(MessagesState):
jump_to: str | None
def router_node(state: RouterState):
last_message = state["messages"][-1].content.lower()
# Simple logic simulating a model decision
if "negate" in last_message:
return RouterState(
messages=state["messages"], jump_to="delegate"
)
else:
return RouterState(
messages=[AIMessage(content="I can handle this!")],
jump_to=None,
)
def route_decision(state: RouterState) -> Literal["expert_node", END]:
if state.get("jump_to", None) == "delegate":
return "expert_node"
return END
workflow = StateGraph(RouterState)
workflow.add_node("router_node", router_node)
workflow.add_node("expert_node", echo_node)
workflow.add_edge(START, "router_node")
workflow.add_conditional_edges("router_node", route_decision)
workflow.add_edge("expert_node", END)
app = workflow.compile()
此代码片段的作用: 生成包含两个节点的 LangGraph StateGraph 。
router_node 检查最后一条消息 — 如果包含“negate”,它会委托给 expert_node(使用 get_agent_node 检索的 Foundry 智能体)。 否则,路由器在本地处理请求并结束图形。 此模式演示如何将本地逻辑与 Foundry 代理相结合。
该图如下所示:
调用图形:
print("--- Test 1 (Direct) ---")
pretty_print(
app.invoke({"messages": [HumanMessage(content="Hello, world!")]})
)
print("\n--- Test 2 (Delegated) ---")
pretty_print(
app.invoke(
{"messages": [HumanMessage(content="Negate that I'm a genius!")]}
)
)
------------------------------- Test 1 (Direct) --------------------------------
================================ Human Message =================================
Hello, world!
================================== Ai Message ==================================
I can handle this!
------------------------------ Test 2 (Delegated) ------------------------------
================================ Human Message =================================
Negate that I'm a genius!
================================== Ai Message ==================================
Name: my-echo-agent
You're not a genius!
在测试 1 中,路由器在本地处理请求。 在测试 2 中,路由器将任务委托给 Foundry 代理,该代理响应时给出与用户陈述相反的回答。
创建基本提示代理
如果需要在代码中完全定义代理(例如,在原型制作期间或代理配置应与应用程序一起运行)时,请使用 create_prompt_agent。 从一个简约的 ReAct 风格提示代理开始,以验证您的集成。
agent = factory.create_prompt_agent(
name="my-echo-agent",
model=os.environ["MODEL_DEPLOYMENT_NAME"],
instructions=(
"You are a helpful AI assistant that always replies with the "
"opposite of what the user says."
),
)
agent_ids = factory.get_agents_id_from_graph(agent)
print(f"Agent created: {next(iter(agent_ids))}")
Agent created: my-echo-agent:1
调用代理:
messages = [HumanMessage(content="I'm a genius and I love programming!")]
response = agent.invoke({"messages": messages})
pretty_print(response)
================================ Human Message =================================
I'm a genius and I love programming!
================================== Ai Message ==================================
Name: my-echo-agent
You are not a genius and you hate programming!
此代码片段的作用: 在 Foundry 代理服务中创建基于提示的代理,并返回使用该代理的 LangGraph CompiledStateGraph 。 代理会立即显示在 Foundry 门户下的代理栏目中。
该方法 factory.get_agents_id_from_graph 从编译的图形中检索 Foundry 分配的代理名称和版本。
可以通过打印代理的关系图表示形式来可视化代理在 LangGraph 图中创建和使用的方式。 节点 foundryAgent 在 Foundry 代理服务中运行。 请注意代理名称和版本在关系图中如何显示。
from IPython import display
display.Image(agent.get_graph().draw_mermaid_png())
factory.delete_agent(agent)
将工具添加到代理
可以将工具添加到代理以执行操作。
create_prompt_agent该方法为你实现代理循环。
应区分两种类型的工具:
- 本地工具:这些工具是与代理代码在同一位置运行的工具。 它们可以是可调用的函数,也可以是可用于 LangChain/LangGraph 生态系统的任何函数。
- 内置工具:这些工具可在 Foundry 代理服务中独占运行;服务器端。 服务器端工具只能应用于 Foundry 代理。
将 本地工具 添加到代理会将 工具节点 添加到图形,以便这些工具运行。 内置工具 不会添加 工具节点 ,并在发出请求时在服务中执行。
以下部分介绍了如何使用这两种方法:
添加本地工具
可以定义本地Python函数并将其附加为工具。 此模式适用于确定性业务逻辑和实用工具操作。
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
def multiply(a: int, b: int) -> int:
"""Multiply two integers."""
return a * b
def divide(a: int, b: int) -> float:
"""Divide one integer by another."""
return a / b
将工具传递给 create_prompt_agent 函数,并使用多步骤算术问题调用代理:
math_agent = factory.create_prompt_agent(
name="math-agent",
model=os.environ["MODEL_DEPLOYMENT_NAME"],
instructions=(
"You are a helpful assistant tasked with performing arithmetic "
"on a set of inputs."
),
tools=[add, multiply, divide],
)
messages = [
HumanMessage(
content="Add 3 and 4. Multiply the output by 2. Divide the output by 5."
)
]
response = math_agent.invoke({"messages": messages})
pretty_print(response)
================================ Human Message =================================
Add 3 and 4. Multiply the output by 2. Divide the output by 5
================================== Ai Message ==================================
Tool Calls:
add (call_JSmltOCbsTRkbNEBMAVSgVe1)
Call ID: call_JSmltOCbsTRkbNEBMAVSgVe1
Args:
a: 3
b: 4
================================= Tool Message =================================
Name: add
7
================================== Ai Message ==================================
Tool Calls:
multiply (call_ae6M6XyhOIBOkPy3ETd8nDI9)
...
================================== Ai Message ==================================
Name: math-agent
Here's the step-by-step calculation:
1. Add 3 and 4 to get 7.
2. Multiply the result (7) by 2 to get 14.
3. Divide the result (14) by 5 to get 2.8.
The final result is 2.8.
此代码片段的作用: 使用三个算术工具创建一个代理。 当代理确定需要工具调用时,Foundry 代理服务在本地协调工具调用,并将结果馈送回代理以继续推理。
使用来自 LangGraph/LangChain 生态系统的其他工具,例如同一代理流中的 Foundry Tools 中的 Azure 文档智能。 虽然这些工具已连接到 Foundry 资源, 但它们并非代理服务独占,因此充当本地工具。
from langchain_azure_ai.tools import AzureAIDocumentIntelligenceTool
document_parser_agent = factory.create_prompt_agent(
name="document-agent",
model=os.environ["MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant tasked with analyzing documents.",
tools=[AzureAIDocumentIntelligenceTool()],
)
提示
AzureAIDocumentIntelligenceTool可以使用 Foundry 项目连接到服务,它还支持 Microsoft Entra 进行身份验证。 默认情况下,该工具使用AZURE_AI_PROJECT_ENDPOINT与DefaultAzureCredential,因此无需进一步配置。 如果需要,您可以更改设置以使用特定的终结点和密钥。
要求代理从 URL 分析发票:
messages = [
HumanMessage(
content=(
"What's the total amount in the invoice at "
"https://raw.githubusercontent.com/Azure/azure-sdk-for-python/main/"
"sdk/formrecognizer/azure-ai-formrecognizer/tests/sample_forms/"
"forms/Form_1.jpg"
)
)
]
response = document_parser_agent.invoke({"messages": messages})
pretty_print(response)
================================ Human Message =================================
What's the total amount in ...
================================== Ai Message ==================================
Tool Calls:
azure_ai_document_intelligence (call_32V6bqeCcJhhsOXDrYFXggnc)
Call ID: call_32V6bqeCcJhhsOXDrYFXggnc
Args:
source_type: url
source: https://raw.githubusercontent.com/Azure/ ...
================================= Tool Message =================================
Name: azure_ai_document_intelligence
Content: Purchase Order Hero ...
================================== Ai Message ==================================
Name: document-agent
The total amount in the invoice is **$144.00**.
此代码片段的作用: 要求代理从示例发票映像中提取数据。 代理调用 AzureAIDocumentIntelligenceTool 分析文档并返回结果。 预期输出: “发票中的总金额为 144.00 美元。
添加内置工具
Foundry 代理服务中的内置工具运行服务器端,而不是在本地 工具等工具节点 中运行。 命名空间 langchain_azure_ai.agents.prebuilt.tools.* 中的工具都是内置工具,只能使用 create_prompt_agent。
示例:使用代码解释器工具
创建用于数据分析的代码解释器代理,并使用虚构 data.csv 数据文件调用它。
在运行此示例之前,请在当前工作目录中创建本地 data.csv 文件。
region,sales
North,120
South,80
East,100
West,60
import base64
from langchain_azure_ai.agents.prebuilt.tools import CodeInterpreterTool
code_interpreter_agent = factory.create_prompt_agent(
name="code-interpreter-agent",
model=os.environ["MODEL_DEPLOYMENT_NAME"],
instructions=(
"You are a data analyst agent. Analyze CSV data and create "
"visualizations when helpful."
),
tools=[CodeInterpreterTool()],
)
with open("data.csv", "rb") as file_handle:
csv_data = base64.b64encode(file_handle.read()).decode()
response = code_interpreter_agent.invoke(
{
"messages": [
HumanMessage(
content=[
{
"type": "file",
"mime_type": "text/csv",
"base64": csv_data,
},
{
"type": "text",
"text": (
"Create a pie chart showing sales by region and "
"return it as a PNG image."
),
},
]
)
]
}
)
pretty_print(response)
================================ Human Message =================================
[
{'type': 'file', 'mime_type': 'text/csv', 'base64': '77u/bW9udG...xTb3V0aAo='},
{'type': 'text', 'text': 'create a pie chart with the data showing sales by region and show it to me as a png image.'}
]
================================== Ai Message ==================================
Name: code-interpreter-agent
[
{'type': 'text', 'text': 'Here is the pie chart showing sales by region as a PNG image:\n\n[Download the Pie Chart](sandbox:/mnt/data/sales_by_region_pie.png)'},
{'type': 'image', 'mime_type': 'image/png', 'base64': 'iVBORw0...ErkJggg=='}
]
示例:使用图像生成工具
运行此示例之前,请确认您的项目中有一个名为 的部署。 以下示例演示如何使用 ImageGenTool 来进行图像生成:
from langchain_azure_ai.agents.prebuilt.tools import ImageGenTool
image_agent = factory.create_prompt_agent(
name="image-generator-agent",
model=os.environ["MODEL_DEPLOYMENT_NAME"],
instructions=(
"You are an image generation assistant. You receive a text prompt and "
"must generate an image by using the configured tool."
),
tools=[ImageGenTool(model_deployment="gpt-image-1.5", quality="medium")],
)
response = image_agent.invoke(
{"messages": [HumanMessage("Generate an image of a sunset over mountains.")]}
)
pretty_print(response)
================================ Human Message =================================
Generate an image of a sunset over the mountains.
================================== Ai Message ==================================
Name: image-generator-agent
使用其他内置工具
任何 Foundry 代理服务工具都可以与 create_prompt_agent 一起使用。 使用 AgentServiceBaseTool 封装 Azure AI 项目 SDK 的工具,并将其附加到提示代理。
运行此示例之前,请确保项目中存在矢量存储 ID。 将 ID 设置为环境变量:
export VECTOR_STORE_ID="<vector-store-id>"
以下示例演示如何使用FileSearchTool:
from azure.ai.projects.models import FileSearchTool
from langchain_azure_ai.agents.prebuilt.tools import AgentServiceBaseTool
file_search_agent = factory.create_prompt_agent(
name="file-search-agent",
model=os.environ["MODEL_DEPLOYMENT_NAME"],
instructions=(
"You are a helpful agent with access to a file search tool over a "
"vector store."
),
tools=[
AgentServiceBaseTool(
tool=FileSearchTool(
vector_store_ids=[os.environ["VECTOR_STORE_ID"]]
),
)
],
)
print(factory.get_agents_id_from_graph(file_search_agent))
{'file-search-agent:1'}
人工干预
Foundry 中的某些工具具有内置的审批工作流,例如 MCPTool。 您可以要求在服务器中为特定工具执行工具调用之前获得批准。
create_prompt_agent该方法通过引入图形中的审批节点来实现 LangGraph 建议的相同模式:
以下示例演示如何使用 MCPTool 进行审批:
from langchain_azure_ai.agents.prebuilt.tools import MCPTool
from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import Command
mcp_agent = factory.create_prompt_agent(
name="mcp-github-specs-agent",
model=os.environ["MODEL_DEPLOYMENT_NAME"],
instructions=(
"Use the available MCP tool to answer every request. "
"Don't answer from your existing knowledge."
),
tools=[
MCPTool(
server_label="api-specs",
server_url="https://gitmcp.io/Azure/azure-rest-api-specs",
require_approval="always",
)
],
checkpointer=MemorySaver(),
)
config = {"configurable": {"thread_id": "mcp-session-1"}}
response = mcp_agent.invoke(
input={
"messages": [
HumanMessage(
"Use the MCP tool to find the APIs available for Azure Cosmos DB."
)
]
},
config=config,
)
pretty_print(response)
================================ Human Message =================================
Use the MCP tool to find the APIs available for Azure Cosmos DB.
================================== Ai Message ==================================
Tool Calls:
mcp_approval_request (mcpr_74e314080483acce0069a11d2d9f008190a971212ac61d76d8)
Call ID: mcpr_74e314080483acce0069a11d2d9f008190a971212ac61d76d8
Args:
server_label: api-specs
name: search_azure_rest_api_docs
arguments: {"query":"Cosmos DB APIs"}
================================== Interrupt ==================================
Interrupt ID: c3cb23363f91d097298fb3c6f8fbf70a
Interrupt Value:
Tool Call ID: mcpr_74e314080483acce0069a11d2d9f008190a971212ac61d76d8
Server Label: api-specs
Tool Name: search_azure_rest_api_docs
Arguments: {"query":"Cosmos DB APIs"}
使用 LangGraph 中的 Command 发送审批请求:
response = mcp_agent.invoke(Command(resume={"approve": True}), config)
pretty_print(response)
================================ Human Message =================================
Use the MCP tool to find the APIs available for Azure Cosmos DB.
================================== Ai Message ==================================
Tool Calls:
mcp_approval_request (mcpr_74e314080483acce0069a11d2d9f008190a971212ac61d76d8)
Call ID: mcpr_74e314080483acce0069a11d2d9f008190a971212ac61d76d8
Args:
server_label: api-specs
name: search_azure_rest_api_docs
arguments: {"query":"Cosmos DB APIs"}
================================= Tool Message =================================
{"approve": true}
================================== Ai Message ==================================
Name: mcp-github-specs-agent
Azure Cosmos DB supports multiple APIs, ...
可观察性
使用 Foundry 代理服务和 LangGraph 编写解决方案时,某些部分在代理服务中运行,而其他部分则运行代码执行的位置。
该类 AzureAIOpenTelemetryTracer 允许使用代理服务支持的 OpenTelemetry 标准跟踪使用 LangGraph 生成的端到端解决方案。
若要跟踪代码,请使用:
from langchain_azure_ai.callbacks.tracers import AzureAIOpenTelemetryTracer
tracer = AzureAIOpenTelemetryTracer(
agent_id="mcp-github-specs-agent-langgraph"
)
mcp_agent = mcp_agent.with_config({"callbacks": [tracer]})
此代码片段的作用是:创建 AzureAIOpenTelemetryTracer 的实例,以使用 OpenTelemetry 标准将跟踪发送到 Azure 应用程序 Insights。 它设置参数 agent_id 以通过在 gen_ai.agent.id 类型的跨度中设置属性 来标识跟踪。
AzureAIOpenTelemetryTracer需要一个连接字符串来连接到 Azure 应用程序 Insights。 在这种情况下,它不会显示,因为您设置了环境变量 AZURE_AI_PROJECT_ENDPOINT,该类可以用于检测与项目相关的 Azure 应用程序 Insights 的连接字符串。 可以传递您所需的任何连接字符串。
要查看追踪,务必了解此处有 两个代理:
- Foundry 代理是图形中某个节点的后端部分。
- 整个 LangGraph 图,由多个节点组成。
可以使用 Foundry 门户查看 Foundry 代理跟踪,但若要在开发时查看 LangGraph 代理的跟踪,需要在 Azure 门户中使用 Azure Monitor。
提示
可以在 Foundry 控制平面中注册 LangChain 和 LangGraph 应用程序进行治理。 然后,可以使用 Foundry 门户 查看追踪日志。 请参阅在 Foundry 控制平面中查看跟踪。
使用 Azure Monitor 来查看跟踪:
转到 Azure 门户。
导航到您配置的 Azure 应用程序洞察。
使用左侧导航栏,选择调查>。
你会看到一个仪表板,其中显示了代理、模型和工具执行。 使用此视图可以了解代理的整体情况。
选择“ 查看代理运行的记录”。 侧面板显示代理运行生成的所有轨迹。
选择其中一个轨迹。 你应该看到详细信息。
请注意有两个代理参与了会话:代理
foundryAgent和名为mcp-github-specs-agent-langgraph的代理。
清理智能体
删除在示例中创建的代理,以避免留下未使用的资源。
仅删除在会话中创建的代理。
for variable_name in (
"math_agent",
"document_parser_agent",
"image_agent",
"code_interpreter_agent",
"mcp_agent",
"file_search_agent",
):
created_agent = locals().get(variable_name)
if created_agent is not None:
factory.delete_agent(created_agent)
重要
删除后,无法再使用 LangGraph 对象。
故障 排除
使用此清单来诊断将 langchain-azure-ai 与代理服务结合使用时的常见问题。
启用诊断日志记录
首先启用调试日志,以便可以检查身份验证、请求流和工具执行详细信息。
import logging
logging.getLogger("langchain_azure_ai").setLevel(logging.DEBUG)
如果需要更多详细信息,请增加日志记录以包括其他库:
import logging
logging.basicConfig(level=logging.DEBUG)
提前验证配置
- 确认
AZURE_AI_PROJECT_ENDPOINT指向正确的项目终结点,并且你正在使用具有新体验的 Foundry 项目。 - 确认
MODEL_DEPLOYMENT_NAME与现有已部署的模型匹配。 - 请使用
az account show验证身份验证上下文。 - 首先使用最小
create_prompt_agent示例。
验证资源和权限的访问
- 确保你的帐户有权访问 Foundry 项目和模型部署。
- 确保下游依赖项(例如矢量存储或工具资源)存在且可访问。
- 如果某个工具需要特定的资源类型,请验证是否已在正确的订阅和区域中预配资源。
解决工具执行错误
- 如果代码解释器返回
400响应,请重试请求。 如果错误仍然存在,请确认项目区域和聊天模型支持代码解释器。 - 如果映像生成返回
DeploymentNotFound,请在项目中部署gpt-image-1.5或更新model_deployment到现有映像模型部署的名称。 - 如果 MCP 请求没有暂停以等待批准,请在提示词中明确要求使用 MCP 工具。 仅当模型选择该工具时,才会进行审批。