observability 模块
枚举
| OtelAttr |
用于捕获 OpenTelemetry for Generative AI 中使用的属性的枚举。 基于: https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/ 和 https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-agent-spans/ |
函数
configure_otel_providers
使用 OpenTelemetry 为应用程序配置 query 提供程序并启用检测。
此方法基于提供的值和环境变量为应用程序创建导出者和提供程序,并启用检测。
在应用程序启动期间调用此方法一次,然后捕获任何遥测数据。 请勿多次调用此方法,因为它可能会导致意外行为。
该函数自动读取标准 OpenTelemetry 环境变量:
- OTEL_EXPORTER_OTLP_ENDPOINT:所有信号的基本 OTLP 终结点
- OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:跟踪的 OTLP 终结点
- OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:指标的 OTLP 终结点
- OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:日志的 OTLP 终结点
- OTEL_EXPORTER_OTLP_PROTOCOL:协议(grpc/http)
- OTEL_EXPORTER_OTLP_HEADERS:所有信号的标头
- ENABLE_CONSOLE_EXPORTERS:为遥测启用控制台输出
注释
由于每个信号类型只能设置一个提供程序(日志、跟踪、指标),
可以选择使用此方法,并获取我们创建的导出者和提供程序。
或者,你可以自行设置提供程序,也可以通过另一个库设置提供程序
(例如 Azure Monitor),只需调用 enable_instrumentation() 即可启用检测。
注释
默认情况下,代理框架会发出带有前缀的指标agent_framework
和gen_ai (OpenTelemetry GenAI 语义约定)。 可以使用视图
用于筛选要收集和导出的指标的参数。 还可以使用
用于获取默认视图的 create_metric_views() 帮助程序函数。
-[ 引用 ]-
https://opentelemetry.io/docs/languages/sdk-configuration/general/
https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/
configure_otel_providers(*, enable_sensitive_data: bool | None = None, exporters: list['LogRecordExporter | SpanExporter | MetricExporter'] | None = None, views: list['View'] | None = None, vs_code_extension_port: int | None = None, env_file_path: str | None = None, env_file_encoding: str | None = None) -> None
参数
| 名称 | 说明 |
|---|---|
|
enable_sensitive_data
必需
|
|
|
exporters
必需
|
|
|
views
必需
|
|
|
vs_code_extension_port
必需
|
|
|
env_file_path
必需
|
|
|
env_file_encoding
必需
|
|
仅限关键字的参数
| 名称 | 说明 |
|---|---|
|
enable_sensitive_data
|
启用 OpenTelemetry 敏感事件。 如果已设置,则替代环境变量ENABLE_SENSITIVE_DATA。 默认值为 None。 默认值: None
|
|
exporters
|
日志、指标或范围或任何组合的自定义导出程序列表。 除了通过环境变量配置的导出程序外,还将添加这些导出程序。 默认值为 None。 默认值: None
|
|
views
|
指标配置的 OpenTelemetry 视图的可选列表。 视图允许筛选和自定义收集哪些指标。 默认值为 None(空列表)。 默认值: None
|
|
vs_code_extension_port
|
AI 工具包或 Azure AI Foundry VS Code 扩展正在侦听的端口。 设置后,将使用终结点 http://localhost:{vs_code_extension_port}创建其他 一些导出程序。 如果已设置,则替代环境变量VS_CODE_EXTENSION_PORT。 默认值为 None。 默认值: None
|
|
env_file_path
|
要从中加载环境变量的 .env 文件的可选路径。 默认值为 None。 默认值: None
|
|
env_file_encoding
|
加载 .env 文件时要使用的编码。 默认值为 None,使用系统默认编码。 默认值: None
|
返回
| 类型 | 说明 |
|---|---|
示例
from agent_framework.observability import configure_otel_providers
# Using environment variables (recommended)
# Set ENABLE_INSTRUMENTATION=true
# Set OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
configure_otel_providers()
# Enable console output for debugging
# Set ENABLE_CONSOLE_EXPORTERS=true
configure_otel_providers()
# With custom exporters
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter
configure_otel_providers(
exporters=[
OTLPSpanExporter(endpoint="http://custom:4317"),
OTLPLogExporter(endpoint="http://custom:4317"),
],
)
# VS Code extension integration
configure_otel_providers(
vs_code_extension_port=4317, # Connects to AI Toolkit
)
# Enable sensitive data logging (development only)
configure_otel_providers(
enable_sensitive_data=True,
)
# With custom metrics views
from opentelemetry.sdk.metrics.view import View
configure_otel_providers(
views=[
View(instrument_name="agent_framework*"),
View(instrument_name="gen_ai*"),
],
)
此示例演示如何首先设置提供程序,然后确保代理框架发出跟踪、日志和指标
# when azure monitor is installed
from agent_framework.observability import enable_instrumentation
from azure.monitor.opentelemetry import configure_azure_monitor
connection_string = "InstrumentationKey=your_instrumentation_key_here;..."
configure_azure_monitor(connection_string=connection_string)
enable_instrumentation()
create_metric_views
为 Agent Framework 创建默认的 OpenTelemetry 指标视图。
create_metric_views() -> list['View']
返回
| 类型 | 说明 |
|---|---|
|
list[‘<xref:View>’]
|
create_resource
从环境变量和参数创建 OpenTelemetry 资源。
此函数读取标准 OpenTelemetry 环境变量来配置资源,该资源标识遥测后端中的服务。
读取以下环境变量:
- OTEL_SERVICE_NAME:服务的名称(默认为“agent_framework”)
- OTEL_SERVICE_VERSION:服务版本(默认为包版本)
- OTEL_RESOURCE_ATTRIBUTES:作为键=值对的其他资源属性
create_resource(service_name: str | None = None, service_version: str | None = None, env_file_path: str | None = None, env_file_encoding: str | None = None, **attributes: Any) -> Resource
参数
| 名称 | 说明 |
|---|---|
|
service_name
|
重写服务名称。 如果未提供,则从OTEL_SERVICE_NAME环境变量读取或默认为“agent_framework”。 默认值: None
|
|
service_version
|
重写服务版本。 如果未提供,则从OTEL_SERVICE_VERSION环境变量读取或默认为包版本。 默认值: None
|
|
env_file_path
|
要从中加载环境变量的 .env 文件的路径。 默认值为 None,如果存在,则从“.env”加载。 默认值: None
|
|
env_file_encoding
|
读取 .env 文件时要使用的编码。 默认值为 None,它使用系统默认编码。 默认值: None
|
|
**attributes
必需
|
要包含的其他资源属性。 这些属性将与OTEL_RESOURCE_ATTRIBUTES环境变量中的属性合并。 |
返回
| 类型 | 说明 |
|---|---|
|
<xref:opentelemetry.sdk.resources.Resource>
|
配置的 OpenTelemetry 资源实例。 |
示例
from agent_framework.observability import create_resource
# Use defaults from environment variables
resource = create_resource()
# Override service name
resource = create_resource(service_name="my_service")
# Add custom attributes
resource = create_resource(
service_name="my_service", service_version="1.0.0", deployment_environment="production"
)
# Load from custom .env file
resource = create_resource(env_file_path="config/.env")
enable_instrumentation
为应用程序启用检测。
调用此方法意味着要在应用程序中启用可观测性。
此方法不配置导出程序或提供程序。 它仅更新触发检测代码的全局变量。 如果已设置环境变量 ENABLE_INSTRUMENTATION=true,则调用此方法不起作用,除非你想要启用或禁用敏感数据事件。
enable_instrumentation(*, enable_sensitive_data: bool | None = None) -> None
参数
| 名称 | 说明 |
|---|---|
|
enable_sensitive_data
必需
|
|
仅限关键字的参数
| 名称 | 说明 |
|---|---|
|
enable_sensitive_data
|
启用 OpenTelemetry 敏感事件。 如果已设置,则替代环境变量ENABLE_SENSITIVE_DATA。 默认值为 None。 默认值: None
|
返回
| 类型 | 说明 |
|---|---|
get_meter
返回代理框架的计量。
这是复制opentelemetry.metrics.get_meter行为metrics.get_meter()的便利包装器。
get_meter(name: str = 'agent_framework', version: str = version_info, schema_url: str | None = None, attributes: dict[str, Any] | None = None) -> Meter
参数
| 名称 | 说明 |
|---|---|
|
name
|
检测库的名称。 默认值为“agent_framework”。 默认值: "agent_framework"
|
|
version
|
agent_framework的版本。 默认值为包的当前版本。 默认值: version_info
|
|
schema_url
|
发出的遥测的可选架构 URL。 默认值: None
|
|
attributes
|
与发出的遥测关联的可选属性。 默认值: None
|
返回
| 类型 | 说明 |
|---|---|
|
<xref:opentelemetry.metrics.Meter>
|
用于记录指标的计量实例。 |
示例
from agent_framework import get_meter
# Get default meter
meter = get_meter()
# Create a counter metric
request_counter = meter.create_counter(
name="requests",
description="Number of requests",
unit="1",
)
request_counter.add(1, {"endpoint": "/api/chat"})
# Create a histogram metric
duration_histogram = meter.create_histogram(
name="request_duration",
description="Request duration in seconds",
unit="s",
)
duration_histogram.record(0.125, {"status": "success"})
get_tracer
返回一个跟踪器供给定的检测库使用。
此函数是用于复制opentelemetry.trace.TracerProvider.get_tracer行为的trace.get_tracer()的便利包装器。 如果省略tracer_provider,则使用当前配置的一个。
get_tracer(instrumenting_module_name: str = 'agent_framework', instrumenting_library_version: str = version_info, schema_url: str | None = None, attributes: dict[str, Any] | None = None) -> Tracer
参数
| 名称 | 说明 |
|---|---|
|
instrumenting_module_name
|
检测库的名称。 默认值为“agent_framework”。 默认值: "agent_framework"
|
|
instrumenting_library_version
|
检测库的版本。 默认值为当前agent_framework版本。 默认值: version_info
|
|
schema_url
|
发出的遥测的可选架构 URL。 默认值: None
|
|
attributes
|
与发出的遥测关联的可选属性。 默认值: None
|
返回
| 类型 | 说明 |
|---|---|
|
<xref:opentelemetry.trace.Tracer>
|
用于创建范围的跟踪实例。 |
示例
from agent_framework import get_tracer
# Get default tracer
tracer = get_tracer()
# Use tracer to create spans
with tracer.start_as_current_span("my_operation") as span:
span.set_attribute("custom.attribute", "value")
# Your operation here
pass
# Get tracer with custom module name
custom_tracer = get_tracer(
instrumenting_module_name="my_custom_module",
instrumenting_library_version="1.0.0",
)
use_agent_instrumentation
为代理启用 OpenTelemetry 可观测性的类修饰器。
此修饰器会自动跟踪代理运行请求、捕获事件和记录修饰代理类的交互。
注释
此修饰器必须应用于代理类本身,而不是实例。
代理类应具有AGENT_PROVIDER_NAME类变量来设置
用于遥测的正确系统名称。
use_agent_instrumentation(agent: type[TAgent] | None = None, *, capture_usage: bool = True) -> type[TAgent] | Callable[[type[TAgent]], type[TAgent]]
参数
| 名称 | 说明 |
|---|---|
|
agent
|
要为其启用可观测性的代理类。 默认值: None
|
|
capture_usage
必需
|
|
仅限关键字的参数
| 名称 | 说明 |
|---|---|
|
capture_usage
|
是否将令牌使用情况捕获为 span 属性。 默认为 True,当代理具有已捕获令牌用法的基础跟踪以避免双重计数时,设置为 False。 默认值: True
|
返回
| 类型 | 说明 |
|---|---|
|
启用了可观测性的修饰代理类。 |
例外
| 类型 | 说明 |
|---|---|
|
如果代理没有所需的方法(运行,run_stream)。 |
示例
from agent_framework import use_agent_instrumentation, configure_otel_providers
from agent_framework._agents import AgentProtocol
# Decorate a custom agent class
@use_agent_instrumentation
class MyCustomAgent:
AGENT_PROVIDER_NAME = "my_agent_system"
async def run(self, messages=None, *, thread=None, **kwargs):
# Your implementation
pass
async def run_stream(self, messages=None, *, thread=None, **kwargs):
# Your implementation
pass
# Setup observability
configure_otel_providers(otlp_endpoint="http://localhost:4317")
# Now all agent runs will be traced
agent = MyCustomAgent()
response = await agent.run("Perform a task")
use_instrumentation
为聊天客户端启用 OpenTelemetry 可观测性的类修饰器。
此修饰器会自动跟踪聊天完成请求、捕获指标和记录已修饰聊天客户端类的事件。
注释
此修饰器必须应用于类本身,而不是实例。
聊天客户端类应具有类变量OTEL_PROVIDER_NAME
为遥测设置正确的提供程序名称。
use_instrumentation(chat_client: type[TChatClient]) -> type[TChatClient]
参数
| 名称 | 说明 |
|---|---|
|
chat_client
必需
|
type[<xref:TChatClient>]
用于启用可观测性的聊天客户端类。 |
返回
| 类型 | 说明 |
|---|---|
|
type[~<xref:TChatClient>]
|
已启用可观测性的修饰聊天客户端类。 |
例外
| 类型 | 说明 |
|---|---|
|
如果聊天客户端没有所需的方法(get_response,get_streaming_response)。 |
示例
from agent_framework import use_instrumentation, configure_otel_providers
from agent_framework import ChatClientProtocol
# Decorate a custom chat client class
@use_instrumentation
class MyCustomChatClient:
OTEL_PROVIDER_NAME = "my_provider"
async def get_response(self, messages, **kwargs):
# Your implementation
pass
async def get_streaming_response(self, messages, **kwargs):
# Your implementation
pass
# Setup observability
configure_otel_providers(otlp_endpoint="http://localhost:4317")
# Now all calls will be traced
client = MyCustomChatClient()
response = await client.get_response("Hello")