使用 Litefuse Trace Microsoft Agent Framework
本 notebook 演示如何将 Litefuse 集成 到你的 Microsoft Agent Framework 工作流中,以监控、调试并评估你的 AI Agent。
什么是 Microsoft Agent Framework?:Microsoft Agent Framework 是一个用于构建智能 Agent 的开源框架。它提供了一整套工具,用于创建可与各种服务交互、执行任务并处理复杂工作流的 Agent。该框架支持多个 LLM 提供方,包括 Azure OpenAI 和 OpenAI,并通过 OpenTelemetry 提供内置可观测性。
什么是 Litefuse?:Litefuse 是一个面向 AI Agent 的开源可观测性平台。它帮助你可视化并监控 LLM 调用、工具使用、成本、延迟等信息。
1. 安装依赖
下面我们安装 agent-framework 库(Microsoft Agent Framework)和用于可观测性的 langfuse。
%pip install agent-framework langfuse --pre2. 配置环境与 Litefuse 凭证
接下来设置你的 Litefuse API Key。可通过注册免费的 Litefuse Cloud 账号或 自托管 Litefuse 获取这些 Key。这些环境变量是 Langfuse 客户端鉴权并向 Litefuse 项目发送数据所必需的。
import os
# Get keys for your project from the project settings page: https://litefuse.cloud
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..."
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..."
os.environ["LANGFUSE_BASE_URL"] = "https://litefuse.cloud"
# Your Azure OpenAI credentials
os.environ["AZURE_OPENAI_API_KEY"] = "your-azure-openai-key"
os.environ["AZURE_OPENAI_ENDPOINT"] = "https://your-resource.openai.azure.com/"
os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"] = "gpt-5-mini"
os.environ["OPENAI_CHAT_MODEL_ID"] = "gpt-5-mini"3. 初始化 Langfuse 客户端
初始化 Langfuse 客户端以验证连接。get_client() 会使用环境变量中提供的凭证来初始化 Langfuse 客户端。
from langfuse import get_client
langfuse = get_client()
# Verify connection
if langfuse.auth_check():
print("Langfuse client is authenticated and ready!")
else:
print("Authentication failed. Please check your credentials and host.")4. 启用可观测性
Microsoft Agent Framework 通过 OpenTelemetry 提供内置的可观测性支持。通过调用 configure_otel_providers() 启用,它会自动将 trace 导出到 Litefuse。
注意: 设置 enable_sensitive_data=True 可捕获完整的请求/响应数据,包括函数参数和结果。
from agent_framework.observability import configure_otel_providers
configure_otel_providers(enable_sensitive_data=True)5. 带工具的 Hello World 示例
下面我们使用 Microsoft Agent Framework 与 Azure OpenAI 创建一个天气 Agent。该 Agent 可以调用 get_weather 函数工具来获取天气信息。
import asyncio
from random import randint
from typing import Annotated
from agent_framework.azure import AzureOpenAIChatClient
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
async def main():
# Create an agent with Azure OpenAI
async with AzureOpenAIChatClient().create_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
query = "What's the weather like in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
# Run the agent
await main()6. 直接使用 OpenAI
Microsoft Agent Framework 也支持直接使用 OpenAI(不通过 Azure)。只需用 OpenAIResponsesClient 替代 AzureOpenAIChatClient。
# Required for OpenAI API access
os.environ["OPENAI_API_KEY"]="sk-proj-..."
os.environ["OPENAI_RESPONSES_MODEL_ID"]="gpt-5-mini" from agent_framework.openai import OpenAIResponsesClient
from typing import Annotated
from pydantic import Field
from random import randint
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
async def main():
async with OpenAIResponsesClient().create_agent(
instructions="You are a helpful assistant.",
tools=get_weather,
) as agent:
query = "What's the weather in Tokyo?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
await main()7. 在 Litefuse 中查看 Trace

Interoperability with the Python SDK
You can use this integration together with the Litefuse SDKs to add additional attributes to the observation.
The @observe() decorator provides a convenient way to automatically wrap your instrumented code and add additional attributes to the observation.
from langfuse import observe, propagate_attributes, get_client
langfuse = get_client()
@observe()
def my_llm_pipeline(input):
# Add additional attributes (user_id, session_id, metadata, version, tags) to all spans created within this execution scope
with propagate_attributes(
user_id="user_123",
session_id="session_abc",
tags=["agent", "my-observation"],
metadata={"email": "user@litefuse.ai"},
version="1.0.0"
):
# YOUR APPLICATION CODE HERE
result = call_llm(input)
return result
# Run the function
my_llm_pipeline("Hi")Learn more about using the Decorator in the Langfuse SDK instrumentation docs.
Troubleshooting
No observations appearing
First, enable debug mode in the Python SDK:
export LANGFUSE_DEBUG="True"Then run your application and check the debug logs:
- OTel observations appear in the logs: Your application is instrumented correctly but observations are not reaching Litefuse. To resolve this:
- Call
langfuse.flush()at the end of your application to ensure all observations are exported. - Verify that you are using the correct API keys and base URL.
- Call
- No OTel spans in the logs: Your application is not instrumented correctly. Make sure the instrumentation runs before your application code.
Unwanted observations in Litefuse
The Langfuse SDK is based on OpenTelemetry. Other libraries in your application may emit OTel spans that are not relevant to you. These still count toward your billable units, so you should filter them out. See Unwanted spans in Litefuse for details.
Missing attributes
Some attributes may be stored in the metadata object of the observation rather than being mapped to the Litefuse data model. If a mapping or integration does not work as expected, please raise an issue on GitHub.
Next Steps
Once you have instrumented your code, you can manage, evaluate and debug your application: