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

使用 Microsoft Foundry 和 Azure Monitor 跟踪 LangChain 和 LangGraph 应用

使用 langchain-azure-ai 集成包从 LangChain 和 LangGraph 应用程序发送 OpenTelemetry 跟踪,并将其存储在 Azure 应用程序 Insights 中。 在本文中,你将配置 AzureAIOpenTelemetryTracer,将其附加到你的可运行项目,并检查 Azure Monitor 中的跟踪。

跟踪器为智能体执行、模型调用、工具执行和检索操作发出跨度。 可以将它用于运行完全本地的混合流、调用 Foundry 代理服务或多代理 LangGraph 解决方案的应用。

先决条件

  • 一个 Azure 订阅。 免费创建一个。
  • Foundry 项目。
  • 已部署的 Azure OpenAI 聊天模型(例如,gpt-4.1)。
  • Python 3.11 或更高版本。
  • Azure CLI登录(az login),以便DefaultAzureCredential进行身份验证。

请配置您的环境

安装所需的包:

pip install -U "langchain-azure-ai[opentelemetry]" azure-identity

设置本文中使用的环境变量:

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>"
os.environ["APPLICATION_INSIGHTS_CONNECTION_STRING"] = "InstrumentationKey=0ab1c2d3..."

若要控制是否在跟踪中记录消息和工具调用的内容,请将 enable_content_recording 作为参数传递给 AzureAIOpenTelemetryTracer 构造函数。 默认情况下启用内容录制。

提示

在 enable_content_recording=False 构造函数中设置 AzureAIOpenTelemetryTracer,以编辑跟踪中的消息内容和工具调用参数。

创建跟踪器

创建一个跟踪实例,并在工作流中重复使用它。

import os

from azure.identity import DefaultAzureCredential
from langchain_azure_ai.callbacks.tracers import AzureAIOpenTelemetryTracer

tracer = AzureAIOpenTelemetryTracer(
	project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
	credential=DefaultAzureCredential(),
	name="langchain-tracing-sample",
	agent_id="support-bot",
	trace_all_langgraph_nodes=True,
)

此代码片段的作用:配置一个跟踪程序,用于从 Foundry 项目终结点解析关联的 Application Insights 连接字符串,并为 LangGraph 节点启用跟踪。 agent_id使用参数在调用代理时设置属性gen_ai.agent.id。 该 name 参数设置 OpenTelemetry 跟踪器名称。

跟踪器支持生产工作流的常见控件:

  • 传入 connection_string 以指定特定的 Application Insights 资源,或配置环境变量 APPLICATION_INSIGHTS_CONNECTION_STRING。
  • 将 trace_all_langgraph_nodes=True 设置为默认跟踪所有节点。
  • 使用节点元数据(例如 otel_trace: True 或 otel_trace: False 包括或跳过特定节点)。
  • 当你的消息嵌套在自定义状态形状下时使用 message_keys 和 message_paths,例如 chat_history。

参考:

跟踪智能体

从一个最小化的 LangChain 代理开始,以便快速验证追踪。 对于 LangGraph,在编译的图形上附加跟踪器 with_config 。

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.", 
).with_config(
    {"callbacks": [tracer]}
)

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

I’m ChatGPT, your AI assistant.

此代码片段的作用: 创建简单的 LangGraph 代理,附加跟踪程序,并使用消息调用代理。

参考:

跟踪 LangChain 可运行项目

从最小的 LangChain 流开始,以便快速验证跟踪。

import os

from azure.identity import DefaultAzureCredential
from langchain_core.prompts import ChatPromptTemplate
from langchain_azure_ai.chat_models import AzureAIChatCompletionsModel

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

prompt = ChatPromptTemplate.from_template(
	"You are concise. Answer in one sentence: {question}"
)
chain = prompt | model

response = chain.invoke(
	{"question": "What does OpenTelemetry help me do?"},
	config={"callbacks": [tracer]},
)

print(response.content)
OpenTelemetry helps you observe requests, latency, dependencies, and failures across your AI workflow.

此代码片段的作用: 运行标准的 LangChain 管道,并通过 AzureAIOpenTelemetryTracer 将聊天 span 发送到 OpenTelemetry。

参考:

跟踪 LangGraph 图形

对于 LangGraph,请使用 with_config 将跟踪器附加到已编译的图形。 此代码片段重复使用 model 和 tracer 前面的示例。

from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode
from langgraph.checkpoint.memory import MemorySaver
from langchain_core.tools import tool
from langchain_azure_ai.utils.agents import pretty_print

@tool
def play_song_on_spotify(song: str):
    """Play a song on Spotify"""
    # Integrate with Spotify API here.
    return f"Successfully played {song} on Spotify!"

@tool
def play_song_on_apple(song: str):
    """Play a song on Apple Music"""
    # Integrate with Apple Music API here.
    return f"Successfully played {song} on Apple Music!"

tool_node = ToolNode([play_song_on_apple, play_song_on_spotify])
model_with_tools = model.bind_tools([play_song_on_apple, play_song_on_spotify])

def should_continue(state: MessagesState):
    messages = state["messages"]
    last_message = messages[-1]
    return "continue" if getattr(last_message, "tool_calls", None) else "end"

def call_model(state: MessagesState):
    messages = state["messages"]
    response = model_with_tools.invoke(messages)
    return {"messages": [response]}

memory = MemorySaver()
workflow = (
    StateGraph(MessagesState)
    .add_node("agent", call_model)
    .add_node("action", tool_node)
    .add_edge(START, "agent")
    .add_conditional_edges(
        "agent",
        should_continue,
        {
            "continue": "action",
            "end": END,
        },
    )
    .add_edge("action", "agent")
    .compile(checkpointer=memory)
)

然后,可以像往常一样运行图形:

from langchain_core.messages import HumanMessage

config = {"configurable": {"thread_id": "1"}, "callbacks": [tracer]}
message = HumanMessage(content="Can you play Taylor Swift's most popular song?")

result = workflow.invoke({"messages": [message]}, config)
pretty_print(result)
================================ Human Message =================================

Can you play Taylor Swift's most popular song?
================================== Ai Message ==================================
Tool Calls:
  play_song_on_spotify (call_xxx)
 Call ID: call_xxx
  Args:
    song: Anti-Hero
================================= Tool Message =================================
Name: play_song_on_spotify

Successfully played Anti-Hero on Spotify!
================================== Ai Message ==================================

I played Taylor Swift's popular song "Anti-Hero" on Spotify.

此代码片段的作用: 创建一个简单的 LangGraph 应用,标记用于跟踪的节点,并发出 invoke_agent 和模型/工具跨度到同一跟踪中。

参考:

了解跟踪结构

跟踪器发出遵循 OpenTelemetry GenAI 语义约定的范围。 每个跨度类型都使用特定 gen_ai.operation.name 值:

范围类型 gen_ai.operation.name 描述
代理或链调用 invoke_agent 每个 LangGraph 节点或链步骤。 范围名称为 invoke_agent {gen_ai.agent.name}.
聊天模型调用 chat LLM 推理请求。 范围名称为 chat {gen_ai.request.model}.
文本完成 text_completion 非聊天 LLM 呼叫。
工具执行 execute_tool 模型触发的工具调用。 范围名称为 execute_tool {gen_ai.tool.name}.
猎犬 execute_tool 矢量存储或搜索中的检索操作。

跨度还具有以下关键属性:

  • gen_ai.agent.name — 代理或节点名称。
  • gen_ai.agent.id — 从 agent_id 构造函数参数设置。
  • gen_ai.agent.description — 代理的说明。
  • gen_ai.provider.name — 模型提供程序(例如 openai)。
  • gen_ai.request.model — 用于推理的模型名称。
  • gen_ai.conversation.id — 线程或会话标识符(如果可用)。
  • gen_ai.usage.input_tokens / gen_ai.usage.output_tokens — 模型响应中的令牌计数。
  • gen_ai.input.messages / gen_ai.output.messages — 消息内容(启用内容录制时)。

跟踪器的解析方式gen_ai.agent.name

跟踪程序按以下顺序从第一个非空值解析代理名称:

  1. agent_name 在节点元数据中。
  2. 节点元数据中的 langgraph_node(由 LangGraph 自动设置)。
  3. agent_type 在节点元数据中。
  4. name LangChain 回调中的关键字参数。
  5. 如果前面的值是通用占位符,则使用langgraph_path(最后一个元素)。
  6. 序列化链 ID 或类名。
  7. 构造函数 name 中的参数 AzureAIOpenTelemetryTracer(后备默认值)。

跟踪器的解析方式gen_ai.agent.id

追踪器通过以下方法解析代理 ID:

  1. agent_id 中的节点元数据(每个节点覆盖)。
  2. agent_id 构造函数参数(所有区间的默认值)。

使用节点元数据自定义属性

使用 LangGraph 元数据为每个节点设置 agent_name、agent_id 和 agent_description。 以gen_ai.开头的任何元数据键也会作为范围属性进行转发。

config = {
    "configurable": {"thread_id": "session-abc-123"},
    "callbacks": [tracer],
    "metadata": {
        "agent_name": "support-bot",
        "agent_id": "support-bot-v2",
        "agent_description": "Handles customer support requests",
    },
}
result = workflow.invoke({"messages": [message]}, config)

使用 LangGraph 时,还可以为图定义中的每个节点设置元数据:

workflow = StateGraph(MessagesState)
workflow.add_node(
    "planner",
    planner_fn,
    metadata={
        "agent_name": "PlannerAgent",
        "agent_id": "planner-v1",
        "otel_agent_span": True,
    },
)

参考:

在 Azure Monitor 中查看跟踪

Azure 应用程序 Insights 接收跟踪,可以使用Azure Monitor对其进行查询:

  1. 转到 Azure 门户。

  2. 导航到您配置的 Azure 应用程序洞察。

  3. 在左侧导航栏中,选择调查>智能体(预览版)。

  4. 你会看到一个仪表板,其中显示了代理、模型和工具执行。 使用此视图可了解代理的整体活动。

  5. 选择“ 查看代理运行的记录”。 侧面板显示代理运行生成的所有轨迹。

    显示 Azure Monitor 中“代理(预览)”部分的多个运行的屏幕截图。

  6. 选择其中一个轨迹。 你将看到详细信息。

    显示所选运行的跟踪详细信息的屏幕截图。

在 Foundry 控制平面中查看跟踪

注册在 Foundry 外部运行的 LangGraph 或 LangChain 代理,将其遥测数据链接到 Foundry。 注册不会移动或托管代理的运行时。 有关遥测设置和访问要求,请参阅 注册外部代理以实现可观测性和评估。

Important

无法再添加新的控制平面自定义代理。 对于现有的自定义代理,请按照 将自定义代理迁移到外部代理。 保留其 OpenTelemetry 代理 ID、网关和调用路由。 请勿在迁移过程中注销或删除原始自定义代理或其 API 管理 API。

若要在门户中注册外部代理,请执行以下操作:

  1. 在 Foundry 门户中 打开项目,然后选择 “生成>代理”。

  2. 选择 “新建代理”>“链接外部代理”。

    “新建代理”菜单的屏幕截图,其中显示了“链接外部代理”选项。

  3. 输入 代理名称 和(可选)说明。

  4. 输入与您的插桩发出的 相匹配的 gen_ai.agent.id。

    此字段为可选项,如果留空,则将默认使用代理名称。 该值必须与您的遥测中的 ID 匹配,才能将跟踪与已注册代理关联起来。

  5. 选择注册。

    “注册外部智能体”表单的屏幕截图,其中包含“智能体名称”“描述”“OTel 智能体 ID”和“注册”控件。

在代理发出遥测数据后,选择“管理>Fleet>代理”,然后选择该代理并打开“追踪”。 有关详细信息,请参阅 查看代理跟踪信息。

疑难解答

  • 如果未显示任何跟踪,请验证是否已配置 connection_string 或者项目终结点已公开遥测数据。
  • 如果消息内容似乎被编辑过,请在 enable_content_recording=True 构造函数中设置 AzureAIOpenTelemetryTracer。
  • 如果缺少某些 LangGraph 节点,请设置 trace_all_langgraph_nodes=True 或添加节点元数据 otel_trace: True。