magentic可观测性指南:使用OpenTelemetry和Logfire的终极监控策略

张开发
2026/4/17 17:38:27 15 分钟阅读

分享文章

magentic可观测性指南:使用OpenTelemetry和Logfire的终极监控策略
magentic可观测性指南使用OpenTelemetry和Logfire的终极监控策略【免费下载链接】magenticSeamlessly integrate LLMs as Python functions项目地址: https://gitcode.com/gh_mirrors/ma/magenticmagentic是一个能无缝集成LLM作为Python函数的强大工具而有效的可观测性策略是确保其稳定运行的关键。本文将详细介绍如何利用OpenTelemetry和Logfire实现对magentic应用的全面监控帮助开发者快速定位问题、优化性能。为什么magentic可观测性至关重要在构建基于LLM的应用时可观测性是确保系统可靠性和性能的关键因素。magentic通过与Pydantic Logfire集成提供了强大的日志和追踪能力同时支持OpenTelemetry标准使开发者能够深入了解应用内部运作及时发现并解决问题。快速入门使用Logfire实现基础监控安装与配置Logfire要开始使用Logfire监控magentic应用首先需要安装Logfire Python包pip install logfire然后进行基础配置将日志输出到标准输出import logfire logfire.configure(send_to_logfireFalse) logfire.instrument_openai() # 可选用于追踪OpenAI API调用 # logfire.instrument_anthropic() # 可选用于追踪Anthropic API调用配置完成后运行magentic代码时将看到详细的日志输出包括提示链调用、LLM交互和函数执行过程23:02:34.197 Calling prompt-chain describe_weather 23:02:34.221 Chat Completion with gpt-4o [LLM] 23:02:35.364 streaming response from gpt-4o took 0.05s [LLM] 23:02:35.365 Executing function call get_current_weather使用Logfire云平台进行高级监控创建Pydantic Logfire账户并完成认证后可以将日志和追踪数据发送到Logfire云平台进行更深入的分析。只需简单配置import logfire logfire.configure() # 默认send_to_logfireTrue logfire.instrument_openai() # 追踪OpenAI API调用在Logfire UI中你可以直观地查看magentic应用的调用链和性能指标如下所示高级监控使用OpenTelemetry与Jaeger配置OpenTelemetry要启用OpenTelemetry支持使用以下Logfire配置import logfire logfire.configure( send_to_logfireFalse, service_namemagentic-test, # 可选也可通过OTEL_SERVICE_NAME环境变量设置 ) logfire.instrument_openai() # 追踪OpenAI API调用本地追踪可视化与Jaeger要在本地查看追踪数据可以使用Jaeger启动Jaeger容器docker run --rm --name jaeger \ -p 16686:16686 \ -p 4317:4317 \ -p 4318:4318 \ jaegertracing/all-in-one:1.58安装OpenTelemetry exporterpip install opentelemetry-exporter-otlp配置OpenTelemetry发送追踪数据到Jaegerfrom opentelemetry import trace from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))访问Jaeger UIhttp://localhost:16686查看追踪数据调试日志深入了解LLM交互细节除了上述监控方法还可以启用LLM提供商Python包的调试日志查看原始请求和响应。例如对于OpenAIimport logging logging.basicConfig(levellogging.DEBUG)这将输出详细的API请求信息帮助开发者调试复杂的LLM交互问题。总结构建可靠的magentic应用通过Logfire和OpenTelemetry开发者可以全面监控magentic应用的运行状态及时发现并解决问题。无论是基础的日志输出还是高级的分布式追踪这些工具都能为构建可靠的LLM应用提供有力支持。官方文档docs/logging-and-tracing.md【免费下载链接】magenticSeamlessly integrate LLMs as Python functions项目地址: https://gitcode.com/gh_mirrors/ma/magentic创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

更多文章