安装
使用您首选的包管理器安装所需包复制
向 AI 提问
pip install langsmith crewai openinference-instrumentation-crewai openinference-instrumentation-openai
设置
1. 配置环境变量
设置您的 API 密钥和项目名称复制
向 AI 提问
export LANGSMITH_API_KEY=<your_langsmith_api_key>
export LANGSMITH_PROJECT=<your_project_name>
export OPENAI_API_KEY=<your_openai_api_key>
2. 配置 OpenTelemetry 集成
在您的 CrewAI 应用程序中,导入并配置 LangSmith OpenTelemetry 集成以及 CrewAI 和 OpenAI 检测器复制
向 AI 提问
from langsmith.integrations.otel import OtelSpanProcessor
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from openinference.instrumentation.crewai import CrewAIInstrumentor
from openinference.instrumentation.openai import OpenAIInstrumentor
# Get or create tracer provider
tracer_provider = trace.get_tracer_provider()
if not isinstance(tracer_provider, TracerProvider):
tracer_provider = TracerProvider()
trace.set_tracer_provider(tracer_provider)
# Add OtelSpanProcessor to the tracer provider
tracer_provider.add_span_processor(OtelSpanProcessor())
# Instrument CrewAI and OpenAI
CrewAIInstrumentor().instrument()
OpenAIInstrumentor().instrument()
3. 创建并运行您的 CrewAI 应用程序
配置完成后,您的 CrewAI 应用程序将自动向 LangSmith 发送追踪: 此示例包含一个最小应用程序,它定义了代理和任务,创建了一个团队,并运行它以生成被追踪的活动。复制
向 AI 提问
from crewai import Agent, Task, Crew
from langsmith.integrations.otel import OtelSpanProcessor
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from openinference.instrumentation.crewai import CrewAIInstrumentor
from openinference.instrumentation.openai import OpenAIInstrumentor
import dotenv
# Load environment variables
dotenv.load_dotenv(".env.local")
# Configure OpenTelemetry
tracer_provider = trace.get_tracer_provider()
if not isinstance(tracer_provider, TracerProvider):
tracer_provider = TracerProvider()
trace.set_tracer_provider(tracer_provider)
# Add OtelSpanProcessor to the tracer provider
tracer_provider.add_span_processor(OtelSpanProcessor())
# Instrument CrewAI and OpenAI
CrewAIInstrumentor().instrument()
OpenAIInstrumentor().instrument()
# Define your agents
market_researcher = Agent(
role="Senior Market Researcher",
goal="Analyze market trends and consumer behavior in the tech industry",
backstory="""You are an experienced market researcher with 10+ years of experience
analyzing technology markets. You excel at identifying emerging trends and
understanding consumer needs.""",
verbose=True,
allow_delegation=False,
)
content_strategist = Agent(
role="Content Marketing Strategist",
goal="Create compelling marketing content based on research insights",
backstory="""You are a creative content strategist who transforms complex market
research into engaging marketing materials. You understand how to communicate
technical concepts to different audiences.""",
verbose=True,
allow_delegation=False,
)
data_analyst = Agent(
role="Data Analyst",
goal="Provide statistical analysis and data-driven insights",
backstory="""You are a skilled data analyst who can interpret complex datasets
and provide actionable insights. You excel at finding patterns and trends
in data that others might miss.""",
verbose=True,
allow_delegation=False,
)
# Define your tasks
research_task = Task(
description="""Conduct comprehensive research on the current state of AI adoption
in small to medium businesses. Focus on:
1. Current adoption rates and trends
2. Main barriers to adoption
3. Most popular AI tools and use cases
4. ROI and business impact metrics
Provide a detailed analysis with supporting data and statistics.""",
agent=market_researcher,
expected_output="A comprehensive market research report on AI adoption in SMBs with data, trends, and insights.",
)
analysis_task = Task(
description="""Analyze the research findings and identify key statistical patterns.
Create data visualizations and provide quantitative insights on:
1. Adoption rate trends over time
2. Industry-specific adoption patterns
3. ROI correlation analysis
4. Barrier impact assessment
Present findings in a clear, data-driven format.""",
agent=data_analyst,
expected_output="Statistical analysis report with key metrics, trends, and data-driven insights.",
context=[research_task],
)
content_task = Task(
description="""Based on the research and analysis, create a compelling marketing
strategy document that includes:
1. Executive summary of key findings
2. Target audience personas based on adoption patterns
3. Key messaging framework addressing main barriers
4. Content recommendations for different business segments
5. Campaign strategy to drive AI adoption
Make the content actionable and business-focused.""",
agent=content_strategist,
expected_output="Complete marketing strategy document with personas, messaging, and campaign recommendations.",
context=[research_task, analysis_task],
)
# Create and run the crew
crew = Crew(
agents=[market_researcher, data_analyst, content_strategist],
tasks=[research_task, analysis_task, content_task],
verbose=True,
process="sequential" # Tasks will be executed in order
)
def run_market_research_crew():
"""Run the market research crew and return results."""
result = crew.kickoff()
return result
if __name__ == "__main__":
print("Running CrewAI market research process...")
output = run_market_research_crew()
print("\n" + "="*50)
print("CrewAI Process Output:")
print("="*50)
print(output)
高级用法
自定义元数据和标签
您可以通过在 CrewAI 应用程序中设置跨度属性来向您的追踪添加自定义元数据复制
向 AI 提问
from opentelemetry import trace
# Get the current tracer
tracer = trace.get_tracer(__name__)
def run_market_research_crew():
with tracer.start_as_current_span("crewai_market_research") as span:
# Add custom metadata
span.set_attribute("langsmith.metadata.crew_type", "market_research")
span.set_attribute("langsmith.metadata.agent_count", "3")
span.set_attribute("langsmith.metadata.task_complexity", "high")
span.set_attribute("langsmith.span.tags", "crewai,market-research,multi-agent")
# Run your crew
result = crew.kickoff()
return result
与其他工具结合使用
您可以通过将其他检测器添加到您的设置中来将 CrewAI 检测与其他检测器结合使用复制
向 AI 提问
from openinference.instrumentation.crewai import CrewAIInstrumentor
from openinference.instrumentation.openai import OpenAIInstrumentor
from openinference.instrumentation.dspy import DSPyInstrumentor
# Initialize multiple instrumentors
CrewAIInstrumentor().instrument()
OpenAIInstrumentor().instrument()
DSPyInstrumentor().instrument()
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。