← 文章 / AI技术
signoz 13天前 · 2026-11-11 14:13:15 · 21 阅读

基于OpenTelemetry的CrewAI可观测性与监控

CrewAI 可观测性让你实时掌握 AI 工作流中智能体、模型和工具的性能。本指南将指导你使用 OpenTelemetry 对 CrewAI 进行插桩,并将 trace、日志和指标导出到 SigNoz,从而监控 CrewAI 应用中的延迟、错误率和使用趋势。

借助 SigNoz 中的完整 CrewAI 可观测性,你可以在统一的仪表盘中关联 trace、日志和指标,配置告警,并获取可操作的洞察以提升可靠性和响应速度。覆盖整个 AI 工作流的 CrewAI 监控使调试失败任务、识别缓慢智能体以及理解 LLM 使用模式变得简单直观。

前置条件

  • SigNoz 部署(二选一):
  • 互联网访问权限,用于向 SigNoz Cloud 发送遥测数据
  • 你的应用中已集成 CrewAI
  • 对 AI 智能体和工具调用工作流有基本理解
  • 对于 Python:已安装 pip 用于管理 Python 包,以及(可选但推荐)一个 Python 虚拟环境以隔离依赖

使用 OpenTelemetry 监控 CrewAI

PythonNo Code(Recommended)Code

推荐采用无代码自动插桩以实现快速配置并最小化代码改动。如果你希望在不修改应用代码的情况下启用可观测性,并利用标准插桩库,这是理想选择。

步骤 1: 在你的 Python 环境中安装必要的包。

Copy
pip install \
  opentelemetry-distro \
  opentelemetry-exporter-otlp \
  opentelemetry-instrumentation-httpx \
  opentelemetry-instrumentation-system-metrics \
  openinference-instrumentation-crewai \
  openinference-instrumentation-openai \
  crewai \
  crewai-tools

步骤 2: 添加自动插桩

Copy
opentelemetry-bootstrap --action=install

步骤 3: 配置日志级别

为确保日志被正确捕获和导出,请将根 logger 配置为 INFO 级别或更高:

Copy
import logging
logging.getLogger().setLevel(logging.INFO)

这会将根 logger 的最低日志级别设为 INFO,确保 logger.info() 调用及更高级别的日志(WARNING、ERROR、CRITICAL)都能被 OpenTelemetry 日志自动埋点捕获并发送到 SigNoz。

第 4 步:运行示例

Copy
import os
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool
 
search_tool = SerperDevTool()
 
# 定义带角色和目标的 Agent
researcher = Agent(
  role='Senior Research Analyst',
  goal='Uncover cutting-edge developments in AI and data science',
  backstory="""You work at a leading tech think tank.
  Your expertise lies in identifying emerging trends.
  You have a knack for dissecting complex data and presenting actionable insights.""",
  verbose=True,
  allow_delegation=False,
  # 可以传入可选的 llm 属性,指定要使用的模型。
  # llm=ChatOpenAI(model_name="gpt-3.5", temperature=0.7),
  tools=[search_tool]
)
writer = Agent(
  role='Tech Content Strategist',
  goal='Craft compelling content on tech advancements',
  backstory="""You are a renowned Content Strategist, known for your insightful and engaging articles.
  You transform complex concepts into compelling narratives.""",
  verbose=True,
  allow_delegation=True
)
 
# 为 Agent 创建任务
task1 = Task(
  description="""Conduct a comprehensive analysis of the latest advancements in AI in 2024.
  Identify key trends, breakthrough technologies, and potential industry impacts.""",
  expected_output="Full analysis report in bullet points",
  agent=researcher
)
 
task2 = Task(
  description="""Using the insights provided, develop an engaging blog
  post that highlights the most significant AI advancements.
  Your post should be informative yet accessible, catering to a tech-savvy audience.
  Make it sound cool, avoid complex words so it doesn't sound like AI.""",
  expected_output="Full blog post of at least 4 paragraphs",
  agent=writer
)
 
# 以顺序流程实例化 Crew
crew = Crew(
  agents=[researcher, writer],
  tasks=[task1, task2],
  verbose=True,
  process=Process.sequential
)
 
# 让你的 Crew 开始工作!
result = crew.kickoff()
 
print("######################")
print(result)
Expand 58 lines

📌 注意:在运行此代码前,请确保将你选用的特定 LLM 的 API key 设置为环境变量。本示例使用 OpenAI,因此需将 OPENAI_API_KEY 设置为你有效的 API key。此外,针对此特定示例,你需要创建一个 Serper 账户,生成 API key,并将其设置为环境变量 SERPER_API_KEY。

步骤 5: 使用自动插桩(auto-instrumentation)运行你的应用

Copy
OTEL_RESOURCE_ATTRIBUTES="service.name=<service_name>" \
OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.<region>.signoz.cloud:443" \
OTEL_EXPORTER_OTLP_HEADERS="signoz-ingestion-key=<your-ingestion-key>" \
OTEL_EXPORTER_OTLP_PROTOCOL=grpc \
OTEL_TRACES_EXPORTER=otlp \
OTEL_METRICS_EXPORTER=otlp \
OTEL_LOGS_EXPORTER=otlp \
OTEL_PYTHON_LOG_CORRELATION=true \
OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true \
opentelemetry-instrument <your_run_command>
Info

使用自托管的 SigNoz?大部分步骤相同。要适配本指南,请参照 Cloud → Self-Hosted 部分,更新 endpoint 并移除摄入密钥头部(header)。

基于代码的插桩(code-based instrumentation)能让你精细控制遥测配置。当你需要自定义资源属性、采样策略,或集成到现有的可观测性基础设施时,请使用此方法。

步骤 1: 在你的 Python 环境中安装必要的包。

CrewAI 支持多种 LLM 提供商用于代理工作流,包括 OpenAI、Anthropic、Google(Gemini/Vertex AI)、Azure、AWS Bedrock、Mistral、Groq、Ollama 等。参见 支持的 LLM 提供商完整列表。

根据你在 CrewAI 中使用的 LLM 提供商,需要安装对应的 OpenInference instrumentor 来追踪 LLM 相关的 trace。可用的 instrumentor 请查阅 OpenInference 文档。 本示例使用 OpenAI: Copy
pip install \
  opentelemetry-api \
  opentelemetry-sdk \
  opentelemetry-exporter-otlp \
  opentelemetry-instrumentation-httpx \
  opentelemetry-instrumentation-system-metrics \
  openinference-instrumentation-crewai \
  openinference-instrumentation-openai \
  crewai \
  crewai-tools

📌 注意:如果你使用其他 LLM 提供商(如 Anthropic、Bedrock、Mistral),请将 openinference-instrumentation-openai 替换为对应的 instrumentor 包,例如 openinference-instrumentation-anthropic、openinference-instrumentation-bedrock 等。

第 2 步:在 Python 应用中导入所需的模块

Traces:

Copy
from openinference.instrumentation.crewai import CrewAIInstrumentor
from openinference.instrumentation.openai import OpenAIInstrumentor
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

日志:

Copy
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
from opentelemetry._logs import set_logger_provider
import logging

指标:

Copy
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry import metrics
from opentelemetry.instrumentation.system_metrics import SystemMetricsInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor

第 3 步:配置 OpenTelemetry Tracer Provider,将 trace 直接发送到 SigNoz Cloud

Copy
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry import trace
import os
 
resource = Resource.create({"service.name": "<service_name>"})
provider = TracerProvider(resource=resource)
span_exporter = OTLPSpanExporter(
    endpoint= os.getenv("OTEL_EXPORTER_TRACES_ENDPOINT"),
    headers={"signoz-ingestion-key": os.getenv("SIGNOZ_INGESTION_KEY")},
)
processor = BatchSpanProcessor(span_exporter)
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
  • <service_name> 你的服务名称
  • OTEL_EXPORTER_TRACES_ENDPOINT → SigNoz Cloud 指定区域的 trace 端点:https://ingest.<region>.signoz.cloud:443/v1/traces(参见区域说明)
  • SIGNOZ_INGESTION_KEY → 你的 SigNoz 采集密钥
Info

使用自托管 SigNoz?大部分步骤相同。参照Cloud → Self-Hosted指南,更新端点并移除采集密钥请求头即可。

步骤 4: 使用已配置的 Tracer Provider,通过各自的 instrumentor 对 CrewAI 和 LLM 供应商进行插桩

Copy
from openinference.instrumentation.crewai import CrewAIInstrumentor
from openinference.instrumentation.openai import OpenAIInstrumentor
 
CrewAIInstrumentor().instrument(tracer_provider=provider)
OpenAIInstrumentor().instrument(tracer_provider=provider)

📌 重要:必须对 CrewAI 及所接入的 LLM 供应商分别进行插桩。本示例使用 OpenAI,因此同时插桩 CrewAIInstrumentor 和 OpenAIInstrumentor。若使用其他 LLM 供应商(如 Anthropic、Bedrock、Mistral),请替换为对应供应商的 instrumentor。

📌 I

原始来源: signoz

评论 (0)