Skip to content
CrewAI 文档版本 跟随上游 源快照 28fa663b 更新于 2026-10-18

LangDB 集成

使用 LangDB AI Gateway 治理、保护并优化你的 CrewAI 工作流:访问 350+ 模型、自动路由、成本优化以及完整的可观测性。

概述

LangDB AI Gateway 提供兼容 OpenAI 的 API,可连接多个大语言模型,并充当可观测性平台,让你可以轻松端到端追踪 CrewAI 工作流,同时提供对 350+ 语言模型的访问。只需一次 init() 调用,所有智能体交互、任务执行和 LLM 调用都会被捕获,为你的应用提供全面的可观测性和可用于生产环境的 AI 基础设施。

LangDB CrewAI trace example
LangDB CrewAI Trace Example

查看: 查看实时追踪示例

特性

AI Gateway 功能

  • 访问 350+ LLM:通过单一集成连接所有主流语言模型
  • 虚拟模型:使用特定参数和路由规则创建自定义模型配置
  • 虚拟 MCP:实现与 MCP(Model Context Protocol)系统的兼容和集成,以增强智能体通信
  • 护栏:为智能体行为实施安全措施和合规控制

可观测性与追踪

  • 自动追踪:单次 init() 调用即可捕获所有 CrewAI 交互
  • 端到端可见性:从头到尾监控智能体工作流
  • 工具使用追踪:追踪智能体使用了哪些工具及其结果
  • 模型调用监控:深入洞察 LLM 交互
  • 性能分析:监控延迟、token 用量和成本
  • 调试支持:逐步执行以排查问题
  • 实时监控:实时追踪和指标仪表板

设置说明

Install LangDB

安装带 CrewAI 功能标志的 LangDB 客户端:

bash
pip install 'pylangdb[crewai]'

Set Environment Variables

配置你的 LangDB 凭据:

bash
export LANGDB_API_KEY="<your_langdb_api_key>"
export LANGDB_PROJECT_ID="<your_langdb_project_id>"
export LANGDB_API_BASE_URL='https://api.us-east-1.langdb.ai'

Initialize Tracing

在配置 CrewAI 代码之前导入并初始化 LangDB:

python
from pylangdb.crewai import init
# Initialize LangDB
init()

Configure CrewAI with LangDB

使用 LangDB 请求头设置你的 LLM:

python
from crewai import Agent, Task, Crew, LLM
import os

# Configure LLM with LangDB headers
llm = LLM(
    model="openai/gpt-4o", # Replace with the model you want to use
    api_key=os.getenv("LANGDB_API_KEY"),
    base_url=os.getenv("LANGDB_API_BASE_URL"),
    extra_headers={"x-project-id": os.getenv("LANGDB_PROJECT_ID")}
)

快速开始示例

下面是一个简单的示例,帮助你开始使用 LangDB 和 CrewAI:

python
import os
from pylangdb.crewai import init
from crewai import Agent, Task, Crew, LLM

# Initialize LangDB before any CrewAI imports
init()

def create_llm(model):
    return LLM(
        model=model,
        api_key=os.environ.get("LANGDB_API_KEY"),
        base_url=os.environ.get("LANGDB_API_BASE_URL"),
        extra_headers={"x-project-id": os.environ.get("LANGDB_PROJECT_ID")}
    )

# Define your agent
researcher = Agent(
    role="Research Specialist",
    goal="Research topics thoroughly",
    backstory="Expert researcher with skills in finding information",
    llm=create_llm("openai/gpt-4o"), # Replace with the model you want to use
    verbose=True
)

# Create a task
task = Task(
    description="Research the given topic and provide a comprehensive summary",
    agent=researcher,
    expected_output="Detailed research summary with key findings"
)

# Create and run the crew
crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()
print(result)

完整示例:研究与规划智能体

这个完整的示例演示了一个具备研究与规划能力的多智能体工作流。

前提条件

bash
pip install crewai 'pylangdb[crewai]' crewai_tools setuptools python-dotenv

环境设置

bash
# LangDB credentials
export LANGDB_API_KEY="<your_langdb_api_key>"
export LANGDB_PROJECT_ID="<your_langdb_project_id>"
export LANGDB_API_BASE_URL='https://api.us-east-1.langdb.ai'

# Additional API keys (optional)
export SERPER_API_KEY="<your_serper_api_key>"  # For web search capabilities

完整实现

python
#!/usr/bin/env python3

import os
import sys
from pylangdb.crewai import init
init()  # Initialize LangDB before any CrewAI imports
from dotenv import load_dotenv
from crewai import Agent, Task, Crew, Process, LLM
from crewai_tools import SerperDevTool

load_dotenv()

def create_llm(model):
    return LLM(
        model=model,
        api_key=os.environ.get("LANGDB_API_KEY"),
        base_url=os.environ.get("LANGDB_API_BASE_URL"),
        extra_headers={"x-project-id": os.environ.get("LANGDB_PROJECT_ID")}
    )

class ResearchPlanningCrew:
    def researcher(self) -> Agent:
        return Agent(
            role="Research Specialist",
            goal="Research topics thoroughly and compile comprehensive information",
            backstory="Expert researcher with skills in finding and analyzing information from various sources",
            tools=[SerperDevTool()],
            llm=create_llm("openai/gpt-4o"),
            verbose=True
        )
    
    def planner(self) -> Agent:
        return Agent(
            role="Strategic Planner",
            goal="Create actionable plans based on research findings",
            backstory="Strategic planner who breaks down complex challenges into executable plans",
            reasoning=True,
            max_reasoning_attempts=3,
            llm=create_llm("openai/anthropic/claude-3.7-sonnet"),
            verbose=True
        )
    
    def research_task(self) -> Task:
        return Task(
            description="Research the topic thoroughly and compile comprehensive information",
            agent=self.researcher(),
            expected_output="Comprehensive research report with key findings and insights"
        )
    
    def planning_task(self) -> Task:
        return Task(
            description="Create a strategic plan based on the research findings",
            agent=self.planner(),
            expected_output="Strategic execution plan with phases, goals, and actionable steps",
            context=[self.research_task()]
        )
    
    def crew(self) -> Crew:
        return Crew(
            agents=[self.researcher(), self.planner()],
            tasks=[self.research_task(), self.planning_task()],
            verbose=True,
            process=Process.sequential
        )

def main():
        topic = sys.argv[1] if len(sys.argv) > 1 else "Artificial Intelligence in Healthcare"
        
        crew_instance = ResearchPlanningCrew()
        
        # Update task descriptions with the specific topic
        crew_instance.research_task().description = f"Research {topic} thoroughly and compile comprehensive information"
    crew_instance.planning_task().description = f"Create a strategic plan for {topic} based on the research findings"
    
    result = crew_instance.crew().kickoff()
    print(result)

if __name__ == "__main__":
    main()

运行示例

bash
python main.py "Sustainable Energy Solutions"

在 LangDB 中查看追踪

运行 CrewAI 应用后,你可以在 LangDB 仪表板中查看详细的追踪:

LangDB trace dashboard showing CrewAI workflow
LangDB Trace Dashboard

你将看到什么

  • 智能体交互:智能体对话和任务交接的完整流程
  • 工具使用:调用了哪些工具、它们的输入和输出
  • 模型调用:包含提示词 image.png和响应的详细 LLM 交互
  • 性能指标:延迟、token 用量和成本追踪
  • 执行时间线:整个工作流的逐步视图

故障排查

常见问题

  • 没有出现追踪:确保在任何 CrewAI 导入之前调用 init()
  • 身份认证错误:验证你的 LangDB API 密钥和项目 ID

资源

下一步

本指南介绍了将 LangDB AI Gateway 与 CrewAI 集成的基础知识。要进一步增强你的 AI 工作流,可以探索:

  • 虚拟模型:使用路由策略创建自定义模型配置
  • 护栏与安全:实施内容过滤和合规控制
  • 生产部署:配置回退、重试和负载均衡

有关更多高级功能和用例,请访问 LangDB 文档 或浏览 模型目录 以发现所有可用模型。

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。