重要
本文中標示為預覽的項目目前仍在預覽中。 此預覽版未簽訂服務等級協議,Microsoft 不建議用於生產工作負載。 某些功能可能不被支援或功能受限。 欲了解更多資訊,請參閱Microsoft Azure預覽補充使用條款。
註
追蹤通常適用於提示和裝載的 Agent。 工作流程和外部代理目前為預覽版。
當 AI 代理在生產環境中行為異常時,追蹤能讓你快速辨識根本原因。 追蹤能捕捉詳細的遙測資料——包括大型語言模型呼叫、工具調用及代理決策流程——讓您能除錯問題、監控延遲,並理解代理在不同請求間的行為。
Microsoft Foundry 提供針對熱門代理框架的追蹤整合,只需極少的程式碼變更。 在本文中,您將學習如何:
- 為 Microsoft Agent Framework 與語意核心設定自動追蹤功能
- 設定適用於 LangChain 和 LangGraph 的 Microsoft OpenTelemetry 發佈項目
- 使用 OpenTelemetry 為 OpenAI Agents SDK 加入檢測
- 確認痕跡是否出現在鑄造廠入口中
- 針對常見的追蹤問題進行疑難排解
Microsoft Foundry Skill可協助設定架構檢測,並驗證 Foundry 中的追蹤資料。
先決條件
- 一個鑄造廠的專案。 欲了解更多資訊,請參閱 「建立鑄造廠專案」。
- 追蹤連接到 Azure 監視器 Application Insights 資源。 要設定它,請參考 Microsoft Foundry 中的「設定追蹤」。
- Application Insights 資源上需具備參與者或更高角色,才能進行追蹤擷取。
- 存取連接的 Application Insights 資源以檢視追蹤。 對於基於日誌的查詢,你可能還需要存取相關的 Log Analytics 工作區。
- Python 3.10 或更新版本(本文所有程式碼範例皆需)。
-
microsoft-opentelemetry套件(LangChain 和 LangGraph 範例所需)。 - 如果你使用 LangChain 或 LangGraph,那是安裝了 pip 的 Python 環境。
確認你能看到遙測數據
要查看追蹤資料,請確保您的帳號能存取連接的 Application Insights 資源。
在 Azure 入口網站中,開啟與你的 Foundry 專案連結的 Application Insights 資源。
選擇存取控制(IAM)。
為你的使用者或群組指派適當的角色。
如果你使用基於日誌的查詢,請先賦予 Log Analytics Reader 角色。 如果底層的 Log Analytics 資料表受到保護,也要授與特殊權限監控資料讀取者角色。
安全與隱私
追蹤可以捕捉敏感資訊(例如使用者輸入、模型輸出,以及工具的參數與結果)。
- 在開發與除錯期間啟用內容錄製,以查看完整的請求與回應資料。 在生產環境中關閉內容錄製以保護敏感資料。 在本文中的範例中,內容錄製由環境變數
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT、OTEL_SEMCONV_STABILITY_OPT_IN、AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING及 控制。 - 不要在提示詞或工具參數中儲存秘密、憑證或令牌。
更多指引請參閱 安全與隱私。
註
Application Insights 中儲存的追蹤資料會依照你工作空間的資料保留設定及 Azure 監視器 價格而定。 在成本管理方面,可考慮調整抽樣率或生產期間。 請參見 Azure 監視器 價格 及 配置資料保留與歸檔。
為 Microsoft Agent Framework 與 語意核心 設定追蹤
Microsoft Foundry 原生整合了 Microsoft Agent Framework 與 語意核心。 使用任一框架建置的代理程式在啟用 Foundry 專案的追蹤時會自動產生追蹤記錄,無需額外程式碼或套件。
為了確認追蹤是否有效:
- 至少要執行一次你的代理程式。
- 在 Foundry 入口網站中,移至可觀察性>追蹤。
- 確認會出現新的追蹤,且包含您 Agent 作業的跨度。
痕跡通常在藥劑執行後2至5分鐘內出現。 欲了解進階設定,請參閱框架專用文件:
使用 OpenInference 儀器函式庫配置追蹤
Microsoft Foundry 支援用於追蹤 AI 代理的 OpenInference 儀器函式庫。 這些 openinference-* 套件會為各種架構提供自動檢測,並可用於追蹤裝載的 Agent (部署至 Foundry 的 Agent) 和非 Foundry Agent (裝載於 Foundry 外部的 Agent)。
在 PyPI 上瀏覽可用的儀器套件。 如需了解 LangChain,請參閱 Microsoft OpenTelemetry 發行版的 LangChain 範例,其中示範如何使用 use_microsoft_opentelemetry 啟用 Azure 監視器 匯出和 LangChain 自動檢測。
關鍵要求是將 OpenInference 的追蹤與特定代理人相關聯。 如何達成此目標取決於你的代理在哪裡:
託管代理(部署至 Foundry)
當你使用其中一個託管代理伺服器套件部署代理到 Foundry 時,追蹤相關性會自動處理。 伺服器套件:
- 設定 Azure 監視器 的 OpenTelemetry 追蹤範圍匯出功能。
- 透過專案、代理名稱、代理版本及代理 ID 屬性豐富所有跨度,使 Foundry 介面能查詢並顯示這些屬性。
不需要進行其他組態設定。 安裝適用於您所用框架的 openinference-* 插裝套件後,追蹤資料就會自動顯示在 Foundry 入口網站中。
裝載於 Foundry 外部的 Microsoft Agent Framework 代理程式
如果你的 Microsoft Agent Framework 代理程式沒有隨 Foundry 託管代理伺服器套件部署,請使用 Microsoft OpenTelemetry 發行版設定 Azure 監視器 匯出與代理框架工具。 發行版可以啟用 Azure 監視器 匯出器,並為 spans 新增代理身份屬性:
from microsoft.opentelemetry import use_microsoft_opentelemetry
use_microsoft_opentelemetry(
enable_azure_monitor=True,
azure_monitor_connection_string="...",
sampling_ratio=1.0,
enable_sensitive_data=True,
instrumentation_options={
"agent-framework": {
"enabled": True,
"agent_id": "ms-imagination-agent",
"agent_name": "ms-imagination-agent",
},
},
)
設定 azure_monitor_connection_string 為與你的 Foundry 專案相關的 Application Insights 資源。 若要在開發過程中擷取提示與完成內容,請設定 enable_sensitive_data=True。
託管於 Foundry 外部的 LangChain 代理程式
如果您的 Agent 不是以 Foundry 裝載的 Agent 伺服器套件部署,請使用 Microsoft OpenTelemetry 發佈項目設定 Azure 監視器匯出和 LangChain 檢測。 發行版可以啟用 Azure 監視器 匯出器,並為 LangChain 範圍新增代理身份屬性:
from microsoft.opentelemetry import use_microsoft_opentelemetry
use_microsoft_opentelemetry(
enable_azure_monitor=True,
sampling_ratio=1.0,
instrumentation_options={
"langchain": {
"enabled": True,
"agent_id": "weather_info_agent_771929",
"agent_name": "Weather information agent",
},
},
)
設定 APPLICATIONINSIGHTS_CONNECTION_STRING 為與你的 Foundry 專案相關的 Application Insights 資源。 在開發過程中擷取提示與完成內容,請設定 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_AND_EVENT、 OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental、 AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING=true。
為 LangChain 與 LangGraph 配置追蹤
註
LangChain 與 LangGraph 的追蹤整合目前僅支援 Python。
使用 Microsoft OpenTelemetry 發行版 來產生符合 OpenTelemetry 規範的 span,用於 LangChain 和 LangGraph 的作業。 這些追蹤會顯示在 Foundry 入口網站中的可檢視性>追蹤檢視中。
範例:使用 Azure AI 追蹤的 LangChain v1 代理程式
使用此端對端範例,透過 Microsoft OpenTelemetry 發佈項目檢測 LangChain v1 (預覽版) Agent。 此發佈項目會使用最新 OpenTelemetry (OTel) 語意慣例啟用 LangChain 自動檢測,因此您可以在 Foundry 可觀測性檢視中檢視豐富追蹤。
LangChain v1:安裝套件
pip install \
microsoft-opentelemetry \
langchain \
langgraph \
langchain-openai \
azure-identity \
python-dotenv \
rich
LangChain v1:設定環境
-
APPLICATIONINSIGHTS_CONNECTION_STRING:Azure 監視器 Application Insights 連接字串 用於追蹤。 -
AZURE_OPENAI_ENDPOINT:你Azure OpenAI 端點網址。 -
AZURE_OPENAI_CHAT_DEPLOYMENT: 聊天模式部署名稱。 -
AZURE_OPENAI_VERSION: API 版本,例如2024-08-01-preview。 - SDK 使用
DefaultAzureCredential解析Azure憑證,支援環境變數、管理身份及 VS Code 登入。
將這些數值儲存在 .env 檔案中,方便本地開發。
LangChain v1:追蹤器設定
from dotenv import load_dotenv
from microsoft.opentelemetry import use_microsoft_opentelemetry
load_dotenv(override=True)
use_microsoft_opentelemetry(
enable_azure_monitor=True,
sampling_ratio=1.0,
instrumentation_options={
"langchain": {
"enabled": True,
"agent_id": "weather_info_agent_771929",
"agent_name": "Weather information agent",
},
},
)
LangChain v1: Model setup (Azure OpenAI)
import os
import azure.identity
from langchain_openai import AzureChatOpenAI
token_provider = azure.identity.get_bearer_token_provider(
azure.identity.DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default",
)
model = AzureChatOpenAI(
azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
azure_deployment=os.environ.get("AZURE_OPENAI_CHAT_DEPLOYMENT"),
openai_api_version=os.environ.get("AZURE_OPENAI_VERSION"),
azure_ad_token_provider=token_provider,
)
LangChain v1:定義工具與提示詞
from dataclasses import dataclass
from langchain_core.tools import tool
system_prompt = """You are an expert weather forecaster, who speaks in puns.
You have access to two tools:
- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location
If a user asks you for the weather, make sure you know the location.
If you can tell from the question that they mean wherever they are,
use the get_user_location tool to find their location."""
# Mock user locations keyed by user id (string)
USER_LOCATION = {
"1": "Florida",
"2": "SF",
}
@dataclass
class UserContext:
user_id: str
@tool
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
LangChain v1:使用執行時上下文並定義使用者資訊工具
from langgraph.runtime import get_runtime
from langchain_core.runnables import RunnableConfig
@tool
def get_user_info(config: RunnableConfig) -> str:
"""Retrieve user information based on user ID."""
runtime = get_runtime(UserContext)
user_id = runtime.context.user_id
return USER_LOCATION[user_id]
LangChain v1:建立代理
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
from dataclasses import dataclass
@dataclass
class WeatherResponse:
conditions: str
punny_response: str
checkpointer = InMemorySaver()
agent = create_agent(
model=model,
prompt=system_prompt,
tools=[get_user_info, get_weather],
response_format=WeatherResponse,
checkpointer=checkpointer,
)
LangChain v1:執行代理程式並進行追蹤
from rich import print
def main():
config = {"configurable": {"thread_id": "1"}}
context = UserContext(user_id="1")
r1 = agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather outside?"}]},
config=config,
context=context,
)
print(r1.get("structured_response"))
r2 = agent.invoke(
{"messages": [{"role": "user", "content": "Thanks"}]},
config=config,
context=context,
)
print(r2.get("structured_response"))
if __name__ == "__main__":
main()
啟用 Microsoft OpenTelemetry 發行版後,所有 LangChain v1 操作(LLM 呼叫、工具呼叫、代理步驟)皆依最新語意慣例發布 OpenTelemetry 區間。 這些痕跡會出現在 Foundry 入口網站的 可觀察性>痕跡 檢視中,並連結到你的應用洞察資源。
提示
執行 Agent 後,請等候幾分鐘讓追蹤顯示。 如果您沒有看到追蹤資料,請確認您的 Application Insights 連接字串正確,並檢查疑難排解常見問題一節。
驗證你 LangChain v1 的追蹤記錄
執行代理後:
- 等待2到5分鐘,讓痕跡傳播。
- 在 Foundry 入口網站中,移至可觀察性>追蹤。
- 尋找帶有你指定的名稱的追蹤檔案(例如「天氣資訊代理」)。
- 展開追蹤以查看 LLM 呼叫、工具調用與 Agent 步驟的跨度。
如果找不到痕跡,請查看 常見問題故障排除 區塊。
範例:LangGraph代理程式搭配Azure AI追蹤
此範例顯示一個使用 Microsoft OpenTelemetry 發佈項目檢測的簡單 LangGraph Agent,以針對圖形步驟、工具呼叫和模型調用發出符合 OpenTelemetry 的追蹤。
LangGraph:安裝套件
pip install \
microsoft-opentelemetry \
"langgraph>=1.0.0" \
"langchain>=1.0.0" \
langchain-openai \
azure-identity \
python-dotenv
LangGraph:配置環境
-
APPLICATIONINSIGHTS_CONNECTION_STRING:Azure 監視器 Application Insights 連接字串 用於追蹤。 -
AZURE_OPENAI_ENDPOINT:你Azure OpenAI 端點網址。 -
AZURE_OPENAI_CHAT_DEPLOYMENT: 聊天模式部署名稱。 -
AZURE_OPENAI_VERSION: API 版本,例如2024-08-01-preview。
將這些數值儲存在 .env 檔案中,方便本地開發。
LangGraph 追蹤器設定
from dotenv import load_dotenv
from microsoft.opentelemetry import use_microsoft_opentelemetry
load_dotenv(override=True)
use_microsoft_opentelemetry(
enable_azure_monitor=True,
sampling_ratio=1.0,
instrumentation_options={
"langchain": {
"enabled": True,
"agent_name": "Music Player Agent",
},
},
)
LangGraph:工具
from langchain_core.tools import tool
@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!"
tools = [play_song_on_apple, play_song_on_spotify]
LangGraph: Model setup (Azure OpenAI)
import os
import azure.identity
from langchain_openai import AzureChatOpenAI
token_provider = azure.identity.get_bearer_token_provider(
azure.identity.DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default",
)
model = AzureChatOpenAI(
azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
azure_deployment=os.environ.get("AZURE_OPENAI_CHAT_DEPLOYMENT"),
openai_api_version=os.environ.get("AZURE_OPENAI_VERSION"),
azure_ad_token_provider=token_provider,
).bind_tools(tools, parallel_tool_calls=False)
建立 LangGraph 工作流程
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode
from langgraph.checkpoint.memory import MemorySaver
tool_node = ToolNode(tools)
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.invoke(messages)
return {"messages": [response]}
workflow = StateGraph(MessagesState)
workflow.add_node("agent", call_model)
workflow.add_node("action", tool_node)
workflow.add_edge(START, "agent")
workflow.add_conditional_edges(
"agent",
should_continue,
{
"continue": "action",
"end": END,
},
)
workflow.add_edge("action", "agent")
memory = MemorySaver()
app = workflow.compile(checkpointer=memory)
LangGraph:使用追蹤執行
from langchain_core.messages import HumanMessage
config = {"configurable": {"thread_id": "1"}}
input_message = HumanMessage(content="Can you play Taylor Swift's most popular song?")
for event in app.stream({"messages": [input_message]}, config, stream_mode="values"):
event["messages"][-1].pretty_print()
啟用 Microsoft OpenTelemetry 發行版後,你的 LangGraph 執行會發出符合 OpenTelemetry 標準的範圍,用於模型呼叫、工具調用及圖轉換。 這些追蹤會流向應用洞察,並出現在 Foundry 入口網站的 可觀察性>追蹤 檢視中。
提示
每個圖節點與邊的轉移會建立獨立的區間,方便視覺化代理人的決策流程。
驗證您的 LangGraph 追蹤資料
執行代理後:
- 等待2到5分鐘,讓痕跡傳播。
- 在 Foundry 入口網站中,移至可觀察性>追蹤。
- 尋找具有您指定名稱的痕跡(例如「Music Player Agent」)。
- 展開追蹤圖以查看圖節點、工具調用及模型呼叫的跨度。
如果找不到痕跡,請查看 常見問題故障排除 區塊。
範例:LangChain 0.3 設定搭配 Azure AI 追蹤
這個最小設定示範如何在 LangChain 0.3 應用程式中,使用 Microsoft OpenTelemetry 發行版和 AzureChatOpenAI 啟用 Azure AI 追蹤。
LangChain 0.3:安裝套件
pip install \
"langchain>=0.3,<0.4" \
langchain-openai \
microsoft-opentelemetry \
python-dotenv
LangChain 0.3:配置環境
-
APPLICATIONINSIGHTS_CONNECTION_STRING:用於追蹤的應用洞察連接字串。 要找到此值,請在Azure入口網站開啟你的應用洞察資源,選擇 Overview,並複製 Connection String。 -
AZURE_OPENAI_ENDPOINT:Azure OpenAI 端點網址。 -
AZURE_OPENAI_CHAT_DEPLOYMENT: 聊天模式部署名稱。 -
AZURE_OPENAI_VERSION: API 版本,例如2024-08-01-preview。 -
AZURE_OPENAI_API_KEY:Azure OpenAI API 金鑰。
註
此範例使用 API 金鑰驗證以簡化流程。 對於生產工作負載,請如 LangChain v1 與 LangGraph 範例所示使用 DefaultAzureCredential 和 get_bearer_token_provider。
LangChain 0.3:追蹤器與模型設定
import os
from dotenv import load_dotenv
from microsoft.opentelemetry import use_microsoft_opentelemetry
from langchain_openai import AzureChatOpenAI
load_dotenv(override=True)
# Enable Azure Monitor export and LangChain auto-instrumentation
use_microsoft_opentelemetry(
enable_azure_monitor=True,
sampling_ratio=1.0,
instrumentation_options={
"langchain": {
"enabled": True,
"agent_id": "trip_planner_orchestrator_v3",
"agent_name": "Trip Planner Orchestrator",
},
},
)
# Model: Azure OpenAI
llm = AzureChatOpenAI(
azure_deployment=os.environ.get("AZURE_OPENAI_CHAT_DEPLOYMENT"),
api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
api_version=os.environ.get("AZURE_OPENAI_VERSION"),
temperature=0.2,
)
初始化發佈項目後,會全域自動檢測 LangChain 0.3 作業。 在您執行鏈結或 Agent 之後,追蹤會在 2-5 分鐘內顯示於 Foundry 入口網站中的可觀察性>追蹤檢視。
配置 OpenAI Agents SDK 的追蹤設定
OpenAI 代理程式 SDK 支援 OpenTelemetry 檢測。 請使用以下摘要設定追蹤並將跨度匯出至 Azure 監視器。 如果 APPLICATION_INSIGHTS_CONNECTION_STRING 沒有設定,匯出器會退回到主控台進行本地除錯。
在執行樣本前,先安裝所需的套件:
pip install opentelemetry-sdk opentelemetry-instrumentation-openai-agents azure-monitor-opentelemetry-exporter
import os
from opentelemetry import trace
from opentelemetry.instrumentation.openai_agents import OpenAIAgentsInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
# Configure tracer provider + exporter
resource = Resource.create({
"service.name": os.getenv("OTEL_SERVICE_NAME", "openai-agents-app"),
})
provider = TracerProvider(resource=resource)
conn = os.getenv("APPLICATION_INSIGHTS_CONNECTION_STRING")
if conn:
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
provider.add_span_processor(
BatchSpanProcessor(AzureMonitorTraceExporter.from_connection_string(conn))
)
else:
provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
# Instrument the OpenAI Agents SDK
OpenAIAgentsInstrumentor().instrument(tracer_provider=trace.get_tracer_provider())
# Example: create a session span around your agent run
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("agent_session[openai.agents]"):
# ... run your agent here
pass
在 Foundry 門戶網站中驗證追蹤記錄
- 登入 Microsoft Foundry。 確定 新鑄造廠 的開關是開啟的。 這些步驟參考 Foundry (新)。
- 確認追蹤功能是否已連接至您的項目。 如有需要,請依照 在 Microsoft Foundry 上設定追蹤功能。
- 至少要執行一次你的代理程式。
- 在 Foundry 入口網站中,移至可觀察性>追蹤。
- 確認會出現新的追蹤,且包含您 Agent 作業的跨度。
痕跡通常在藥劑執行後2至5分鐘內出現。 如果這段時間後仍沒有痕跡出現,請參考「 常見問題故障排除」。
排除常見問題
| 問題 | 成因 | 解決方法 |
|---|---|---|
| 您無法在 Foundry 中找到任何痕跡 | 追蹤尚未連線、目前沒有最近的流量,或資料匯入可能有所延遲 | 確認 Application Insights 連線,產生新流量,並在 2 至 5 分鐘後重新整理。 |
| 您看不到 LangChain 或 LangGraph 的跨度 | Microsoft OpenTelemetry 發行版尚未初始化,或 LangChain 儀器尚未啟用 | 確認您在執行 Agent 前,已使用 use_microsoft_opentelemetry(...) 呼叫 "langchain": {"enabled": True}。 |
| LangChain 跨度出現,但缺少工具呼叫 | 工具沒有綁定在模型上,工具節點也沒有設定 | 確認工具已傳遞至模型的 bind_tools(),且工具節點已加入您的圖表。 |
| 追蹤已出現,但不完整或缺少跨度 | 內容記錄已停用、未設定 GenAI 語意慣例選擇加入,或部分作業未檢測 | 在開發期間,為 LangChain 和 LangGraph 設定 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_AND_EVENT、OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental 和 AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING=true。 針對自訂作業,請使用 OpenTelemetry SDK 新增手動跨度。 |
| 查詢遙測資料時會看到授權錯誤 | Application Insights 或 Log Analytics 缺少 RBAC 權限 | 在 存取控制(IAM) 中確認連接資源的存取權限。 對於日誌查詢,請指派 Log Analytics 讀取器角色。 如果資料表受到 保護,也要指定特 權監控資料讀取器。 |
| 追蹤記錄中出現敏感內容 | 內容錄製已啟用,提示詞、工具參數或輸出包含敏感資料 | 在生產環境中關閉內容錄製,並在敏感資料進入遙測系統前將其遮蔽。 |