diff --git a/docs/docs.json b/docs/docs.json index 8be332c094..260e0ae515 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -280,6 +280,7 @@ "en/observability/langdb", "en/observability/langfuse", "en/observability/langtrace", + "en/observability/langwatch", "en/observability/maxim", "en/observability/mlflow", "en/observability/neatlogs", @@ -705,6 +706,7 @@ "pt-BR/observability/langdb", "pt-BR/observability/langfuse", "pt-BR/observability/langtrace", + "pt-BR/observability/langwatch", "pt-BR/observability/maxim", "pt-BR/observability/mlflow", "pt-BR/observability/openlit", @@ -1138,6 +1140,7 @@ "ko/observability/langdb", "ko/observability/langfuse", "ko/observability/langtrace", + "ko/observability/langwatch", "ko/observability/maxim", "ko/observability/mlflow", "ko/observability/neatlogs", diff --git a/docs/en/observability/langwatch.mdx b/docs/en/observability/langwatch.mdx new file mode 100644 index 0000000000..ad5f441447 --- /dev/null +++ b/docs/en/observability/langwatch.mdx @@ -0,0 +1,203 @@ +--- +title: LangWatch Integration +description: Learn how to instrument the CrewAI Python SDK with LangWatch using OpenLLMetry. +keywords: crewai, python, sdk, instrumentation, opentelemetry, langwatch, tracing, openllmetry +icon: magnifying-glass-chart +--- + +LangWatch does not have a built-in auto-tracking integration for CrewAI. However, you can use OpenLLMetry to integrate CrewAI with LangWatch for comprehensive observability. + +## OpenLLMetry Integration + +**OpenLLMetry** is the recommended choice for CrewAI instrumentation with LangWatch. It provides: + +- **Comprehensive Coverage**: Full instrumentation of CrewAI agents, tasks, and tools +- **Active Development**: Well-maintained with regular updates +- **Proven Integration**: Successfully used with multiple observability platforms +- **OpenTelemetry Native**: Built on OpenTelemetry standards for maximum compatibility + +## Installation + +Install the OpenLLMetry CrewAI instrumentor: + +```bash +pip install opentelemetry-instrumentation-crewai +``` + +## Integration Methods + +There are two main ways to integrate OpenLLMetry with LangWatch: + +### 1. Via `langwatch.setup()` (Recommended) + +This method lets LangWatch manage the lifecycle of the instrumentor, ensuring proper setup and teardown. + +```python openllmetry_setup.py +import langwatch +from crewai import Agent, Task, Crew +import os +from opentelemetry_instrumentation_crewai import CrewAIInstrumentor + +# Ensure LANGWATCH_API_KEY is set in your environment, or set it in `setup` +langwatch.setup( + instrumentors=[CrewAIInstrumentor()] +) + +# Define your CrewAI agents and tasks +researcher = Agent( + role='Senior Researcher', + goal='Discover new insights on AI', + backstory='A seasoned researcher with a knack for uncovering hidden gems.' +) +writer = Agent( + role='Expert Writer', + goal='Craft compelling content on AI discoveries', + backstory='A wordsmith who can make complex AI topics accessible and engaging.' +) + +task1 = Task(description='Investigate the latest advancements in LLM prompting techniques.', agent=researcher) +task2 = Task(description='Write a blog post summarizing the findings.', agent=writer) + +# Create and run the crew +crew = Crew( + agents=[researcher, writer], + tasks=[task1, task2], + verbose=2 +) + +@langwatch.trace(name="CrewAI Execution with OpenLLMetry") +def run_crewai_process_ollm(): + result = crew.kickoff() + return result + +if __name__ == "__main__": + print("Running CrewAI process with OpenLLMetry...") + output = run_crewai_process_ollm() + print("\n\nCrewAI Process Output:") + print(output) +``` + +### 2. Direct Instrumentation + +If you prefer to manage the instrumentor lifecycle yourself or have an existing OpenTelemetry setup, you can use direct instrumentation. + +```python openllmetry_direct.py +import langwatch +from crewai import Agent, Task, Crew +from opentelemetry_instrumentation_crewai import CrewAIInstrumentor + +# Initialize LangWatch +langwatch.setup() + +# Instrument CrewAI directly using OpenLLMetry +CrewAIInstrumentor().instrument() + +# Define your agents and tasks +planner = Agent( + role='Event Planner', + goal='Plan an engaging tech conference', + backstory='An experienced planner with a passion for technology events.' +) +task_planner = Task(description='Outline the agenda for a 3-day AI conference.', agent=planner) +conference_crew = Crew(agents=[planner], tasks=[task_planner]) + +@langwatch.trace(name="CrewAI Direct Instrumentation with OpenLLMetry") +def plan_conference(): + agenda = conference_crew.kickoff() + return agenda + +if __name__ == "__main__": + print("Planning conference with OpenLLMetry (direct)...") + conference_agenda = plan_conference() + print("\n\nConference Agenda:") + print(conference_agenda) +``` + +Now you can see the traces in LangWatch. + +![OpenLLMetry Integration](/images/langwatch_crewai.png) + +## Key Benefits + +### Automatic Instrumentation + +- **Agent Operations**: All agent interactions and decision-making processes +- **Task Execution**: Complete task lifecycle from creation to completion +- **Tool Usage**: Integration with external tools and APIs +- **LLM Calls**: Detailed tracking of model interactions and responses + +### Seamless Integration + +- **LangWatch Management**: Automatic lifecycle management when using `langwatch.setup()` +- **OpenTelemetry Compatible**: Works with existing OpenTelemetry infrastructure +- **Global Coverage**: Once instrumented, captures all CrewAI operations automatically + +## Best Practices + +### 1. **Choose the Right Method** + +- **Use `langwatch.setup()`** for new projects or when you want LangWatch to manage everything +- **Use Direct Instrumentation** when you have existing OpenTelemetry setup or need custom control + +### 2. **Environment Configuration** + +```bash +# Set your LangWatch API key +export LANGWATCH_API_KEY="your-api-key-here" + +# Optional: Configure OpenTelemetry endpoint +export OTEL_EXPORTER_OTLP_ENDPOINT="https://api.langwatch.ai:4317" +``` + +### 3. **Error Handling** + +```python +try: + # Your CrewAI operations + result = crew.kickoff() +except Exception as e: + # Errors will be automatically captured in traces + print(f"Error: {e}") +``` + +### 4. **Performance Monitoring** + +- Monitor execution times for agents and tasks +- Track token usage and API costs +- Identify bottlenecks in your workflow + +## Troubleshooting + +### Common Issues + +1. **Instrumentation Not Working** + + - Ensure the instrumentor is properly imported and initialized + - Check that LangWatch is configured with the correct API key + - Verify OpenTelemetry endpoints are accessible + +2. **Missing Traces** + + - Confirm the instrumentor is called before CrewAI operations + - Check LangWatch dashboard for data ingestion + - Verify network connectivity to LangWatch + +3. **Performance Impact** + + - Instrumentation adds minimal overhead + - Consider sampling for high-volume production environments + - Monitor resource usage during development + +### Getting Help + +- **OpenLLMetry**: [Documentation](https://opentelemetry.io/docs/) +- **LangWatch**: [Documentation](https://docs.langwatch.ai) + +## Next Steps + +1. **Set Up LangWatch**: Configure your API key and project settings +2. **Install OpenLLMetry**: Run the installation command above +3. **Instrument Your Code**: Use one of the integration methods above +4. **Monitor and Optimize**: Use the collected data to improve your CrewAI workflows + +For more advanced configurations and use cases, refer to the [OpenLLMetry documentation](https://opentelemetry.io/docs/) and the [LangWatch documentation](https://docs.langwatch.ai). diff --git a/docs/images/langwatch_crewaI.png b/docs/images/langwatch_crewaI.png new file mode 100644 index 0000000000..67f1f5f526 Binary files /dev/null and b/docs/images/langwatch_crewaI.png differ diff --git a/docs/ko/observability/langwatch.mdx b/docs/ko/observability/langwatch.mdx new file mode 100644 index 0000000000..1135b7c1d7 --- /dev/null +++ b/docs/ko/observability/langwatch.mdx @@ -0,0 +1,203 @@ +--- +title: LangWatch 통합 +description: OpenLLMetry를 사용하여 CrewAI Python SDK를 LangWatch와 함께 계측하는 방법을 알아보세요. +keywords: crewai, python, sdk, instrumentation, opentelemetry, langwatch, tracing, openllmetry +icon: magnifying-glass-chart +--- + +LangWatch는 CrewAI를 위한 내장 자동 추적 통합 기능이 없습니다. 하지만 OpenLLMetry를 사용하여 CrewAI를 LangWatch와 통합하여 포괄적인 관찰 가능성을 얻을 수 있습니다. + +## OpenLLMetry 통합 + +**OpenLLMetry**는 CrewAI 계측을 위한 LangWatch와의 권장 선택입니다. 다음과 같은 기능을 제공합니다: + +- **포괄적인 커버리지**: CrewAI 에이전트, 작업 및 도구의 완전한 계측 +- **적극적인 개발**: 정기적인 업데이트로 잘 유지됨 +- **검증된 통합**: 여러 관찰 가능성 플랫폼에서 성공적으로 사용됨 +- **OpenTelemetry 네이티브**: 최대 호환성을 위한 OpenTelemetry 표준 기반 + +## 설치 + +OpenLLMetry CrewAI 계측기를 설치하세요: + +```bash +pip install opentelemetry-instrumentation-crewai +``` + +## 통합 방법 + +LangWatch와 OpenLLMetry를 통합하는 두 가지 주요 방법이 있습니다: + +### 1. `langwatch.setup()`을 통한 방법 (권장) + +이 방법은 LangWatch가 계측기의 생명주기를 관리하여 적절한 설정과 정리를 보장합니다. + +```python openllmetry_setup.py +import langwatch +from crewai import Agent, Task, Crew +import os +from opentelemetry_instrumentation_crewai import CrewAIInstrumentor + +# 환경에서 LANGWATCH_API_KEY가 설정되어 있는지 확인하거나, `setup`에서 설정 +langwatch.setup( + instrumentors=[CrewAIInstrumentor()] +) + +# CrewAI 에이전트와 작업 정의 +researcher = Agent( + role='시니어 연구원', + goal='AI에 대한 새로운 인사이트 발견', + backstory='숨겨진 보석을 찾아내는 재능을 가진 경험 많은 연구원' +) +writer = Agent( + role='전문 작가', + goal='AI 발견에 대한 매력적인 콘텐츠 작성', + backstory='복잡한 AI 주제를 접근 가능하고 흥미롭게 만들 수 있는 문장의 달인' +) + +task1 = Task(description='LLM 프롬프팅 기법의 최신 발전 동향 조사', agent=researcher) +task2 = Task(description='발견 사항을 요약한 블로그 포스트 작성', agent=writer) + +# 크루 생성 및 실행 +crew = Crew( + agents=[researcher, writer], + tasks=[task1, task2], + verbose=2 +) + +@langwatch.trace(name="OpenLLMetry를 사용한 CrewAI 실행") +def run_crewai_process_ollm(): + result = crew.kickoff() + return result + +if __name__ == "__main__": + print("OpenLLMetry로 CrewAI 프로세스 실행 중...") + output = run_crewai_process_ollm() + print("\n\nCrewAI 프로세스 출력:") + print(output) +``` + +### 2. 직접 계측 + +계측기 생명주기를 직접 관리하거나 기존 OpenTelemetry 설정이 있는 경우 직접 계측을 사용할 수 있습니다. + +```python openllmetry_direct.py +import langwatch +from crewai import Agent, Task, Crew +from opentelemetry_instrumentation_crewai import CrewAIInstrumentor + +# LangWatch 초기화 +langwatch.setup() + +# OpenLLMetry를 사용하여 CrewAI 직접 계측 +CrewAIInstrumentor().instrument() + +# 에이전트와 작업 정의 +planner = Agent( + role='이벤트 기획자', + goal='흥미진진한 기술 컨퍼런스 기획', + backstory='기술 이벤트에 대한 열정을 가진 경험 많은 기획자' +) +task_planner = Task(description='3일간의 AI 컨퍼런스 일정 개요 작성', agent=planner) +conference_crew = Crew(agents=[planner], tasks=[task_planner]) + +@langwatch.trace(name="OpenLLMetry를 사용한 CrewAI 직접 계측") +def plan_conference(): + agenda = conference_crew.kickoff() + return agenda + +if __name__ == "__main__": + print("OpenLLMetry로 컨퍼런스 기획 중 (직접)...") + conference_agenda = plan_conference() + print("\n\n컨퍼런스 일정:") + print(conference_agenda) +``` + +이제 LangWatch에서 추적을 볼 수 있습니다. + +![OpenLLMetry 통합](/images/langwatch_crewai.png) + +## 주요 이점 + +### 자동 계측 + +- **에이전트 작업**: 모든 에이전트 상호작용 및 의사결정 프로세스 +- **작업 실행**: 생성부터 완료까지의 완전한 작업 생명주기 +- **도구 사용**: 외부 도구 및 API와의 통합 +- **LLM 호출**: 모델 상호작용 및 응답의 상세한 추적 + +### 원활한 통합 + +- **LangWatch 관리**: `langwatch.setup()` 사용 시 자동 생명주기 관리 +- **OpenTelemetry 호환**: 기존 OpenTelemetry 인프라와 작동 +- **전역 커버리지**: 한 번 계측되면 모든 CrewAI 작업을 자동으로 캡처 + +## 모범 사례 + +### 1. **올바른 방법 선택** + +- **새 프로젝트**나 LangWatch가 모든 것을 관리하기를 원할 때는 **`langwatch.setup()` 사용** +- **기존 OpenTelemetry 설정**이 있거나 **사용자 정의 제어**가 필요할 때는 **직접 계측 사용** + +### 2. **환경 구성** + +```bash +# LangWatch API 키 설정 +export LANGWATCH_API_KEY="your-api-key-here" + +# 선택사항: OpenTelemetry 엔드포인트 구성 +export OTEL_EXPORTER_OTLP_ENDPOINT="https://api.langwatch.ai:4317" +``` + +### 3. **오류 처리** + +```python +try: + # CrewAI 작업 + result = crew.kickoff() +except Exception as e: + # 오류는 추적에서 자동으로 캡처됨 + print(f"오류: {e}") +``` + +### 4. **성능 모니터링** + +- 에이전트 및 작업의 실행 시간 모니터링 +- 토큰 사용량 및 API 비용 추적 +- 워크플로우의 병목 지점 식별 + +## 문제 해결 + +### 일반적인 문제 + +1. **계측이 작동하지 않음** + + - 계측기가 올바르게 가져와지고 초기화되었는지 확인 + - LangWatch가 올바른 API 키로 구성되었는지 확인 + - OpenTelemetry 엔드포인트에 접근 가능한지 확인 + +2. **추적 누락** + + - CrewAI 작업 전에 계측기가 호출되었는지 확인 + - 데이터 수집을 위해 LangWatch 대시보드 확인 + - LangWatch에 대한 네트워크 연결 확인 + +3. **성능 영향** + + - 계측은 최소한의 오버헤드만 추가 + - 고용량 프로덕션 환경을 위한 샘플링 고려 + - 개발 중 리소스 사용량 모니터링 + +### 도움 받기 + +- **OpenLLMetry**: [문서](https://opentelemetry.io/docs/) +- **LangWatch**: [문서](https://docs.langwatch.ai) + +## 다음 단계 + +1. **LangWatch 설정**: API 키 및 프로젝트 설정 구성 +2. **OpenLLMetry 설치**: 위의 설치 명령 실행 +3. **코드 계측**: 위의 통합 방법 중 하나 사용 +4. **모니터링 및 최적화**: 수집된 데이터를 사용하여 CrewAI 워크플로우 개선 + +더 고급 구성 및 사용 사례는 [OpenLLMetry 문서](https://opentelemetry.io/docs/)와 [LangWatch 문서](https://docs.langwatch.ai)를 참조하세요. diff --git a/docs/pt-BR/observability/langwatch.mdx b/docs/pt-BR/observability/langwatch.mdx new file mode 100644 index 0000000000..93fcf075c3 --- /dev/null +++ b/docs/pt-BR/observability/langwatch.mdx @@ -0,0 +1,203 @@ +--- +title: Integração com LangWatch +description: Aprenda como instrumentar o SDK Python do CrewAI com LangWatch usando OpenLLMetry. +keywords: crewai, python, sdk, instrumentação, opentelemetry, langwatch, rastreamento, openllmetry +icon: magnifying-glass-chart +--- + +O LangWatch não possui uma integração de rastreamento automático integrada para o CrewAI. No entanto, você pode usar o OpenLLMetry para integrar o CrewAI com o LangWatch para observabilidade abrangente. + +## Integração com OpenLLMetry + +**OpenLLMetry** é a escolha recomendada para instrumentação do CrewAI com LangWatch. Ele fornece: + +- **Cobertura Abrangente**: Instrumentação completa de agentes, tarefas e ferramentas do CrewAI +- **Desenvolvimento Ativo**: Bem mantido com atualizações regulares +- **Integração Comprovada**: Usado com sucesso com múltiplas plataformas de observabilidade +- **Nativo OpenTelemetry**: Construído sobre padrões OpenTelemetry para máxima compatibilidade + +## Instalação + +Instale o instrumentador OpenLLMetry para CrewAI: + +```bash +pip install opentelemetry-instrumentation-crewai +``` + +## Métodos de Integração + +Existem duas maneiras principais de integrar o OpenLLMetry com o LangWatch: + +### 1. Via `langwatch.setup()` (Recomendado) + +Este método permite que o LangWatch gerencie o ciclo de vida do instrumentador, garantindo configuração e finalização adequadas. + +```python openllmetry_setup.py +import langwatch +from crewai import Agent, Task, Crew +import os +from opentelemetry_instrumentation_crewai import CrewAIInstrumentor + +# Certifique-se de que LANGWATCH_API_KEY está definido em seu ambiente, ou defina-o em `setup` +langwatch.setup( + instrumentors=[CrewAIInstrumentor()] +) + +# Defina seus agentes e tarefas do CrewAI +pesquisador = Agent( + role='Pesquisador Sênior', + goal='Descobrir novos insights sobre IA', + backstory='Um pesquisador experiente com talento para descobrir joias escondidas.' +) +escritor = Agent( + role='Escritor Especialista', + goal='Criar conteúdo convincente sobre descobertas de IA', + backstory='Um artesão das palavras que pode tornar tópicos complexos de IA acessíveis e envolventes.' +) + +tarefa1 = Task(description='Investigar os últimos avanços em técnicas de prompt de LLM.', agent=pesquisador) +tarefa2 = Task(description='Escrever um post de blog resumindo as descobertas.', agent=escritor) + +# Crie e execute a equipe +crew = Crew( + agents=[pesquisador, escritor], + tasks=[tarefa1, tarefa2], + verbose=2 +) + +@langwatch.trace(name="Execução CrewAI com OpenLLMetry") +def executar_processo_crewai_ollm(): + result = crew.kickoff() + return result + +if __name__ == "__main__": + print("Executando processo CrewAI com OpenLLMetry...") + output = executar_processo_crewai_ollm() + print("\n\nSaída do Processo CrewAI:") + print(output) +``` + +### 2. Instrumentação Direta + +Se você preferir gerenciar o ciclo de vida do instrumentador por conta própria ou tiver uma configuração OpenTelemetry existente, pode usar instrumentação direta. + +```python openllmetry_direct.py +import langwatch +from crewai import Agent, Task, Crew +from opentelemetry_instrumentation_crewai import CrewAIInstrumentor + +# Inicialize o LangWatch +langwatch.setup() + +# Instrumente o CrewAI diretamente usando OpenLLMetry +CrewAIInstrumentor().instrument() + +# Defina seus agentes e tarefas +planejador = Agent( + role='Planejador de Eventos', + goal='Planejar uma conferência de tecnologia envolvente', + backstory='Um planejador experiente com paixão por eventos de tecnologia.' +) +tarefa_planejador = Task(description='Esboçar a agenda para uma conferência de IA de 3 dias.', agent=planejador) +crew_conferencia = Crew(agents=[planejador], tasks=[tarefa_planejador]) + +@langwatch.trace(name="Instrumentação Direta CrewAI com OpenLLMetry") +def planejar_conferencia(): + agenda = crew_conferencia.kickoff() + return agenda + +if __name__ == "__main__": + print("Planejando conferência com OpenLLMetry (direto)...") + agenda_conferencia = planejar_conferencia() + print("\n\nAgenda da Conferência:") + print(agenda_conferencia) +``` + +Agora você pode ver os rastreamentos no LangWatch. + +![Integração OpenLLMetry](/images/langwatch_crewai.png) + +## Benefícios Principais + +### Instrumentação Automática + +- **Operações de Agentes**: Todas as interações de agentes e processos de tomada de decisão +- **Execução de Tarefas**: Ciclo de vida completo da tarefa desde a criação até a conclusão +- **Uso de Ferramentas**: Integração com ferramentas externas e APIs +- **Chamadas LLM**: Rastreamento detalhado de interações e respostas do modelo + +### Integração Perfeita + +- **Gerenciamento LangWatch**: Gerenciamento automático do ciclo de vida ao usar `langwatch.setup()` +- **Compatível OpenTelemetry**: Funciona com infraestrutura OpenTelemetry existente +- **Cobertura Global**: Uma vez instrumentado, captura todas as operações CrewAI automaticamente + +## Melhores Práticas + +### 1. **Escolha o Método Correto** + +- **Use `langwatch.setup()`** para novos projetos ou quando quiser que o LangWatch gerencie tudo +- **Use Instrumentação Direta** quando tiver configuração OpenTelemetry existente ou precisar de controle personalizado + +### 2. **Configuração do Ambiente** + +```bash +# Defina sua chave de API do LangWatch +export LANGWATCH_API_KEY="sua-chave-api-aqui" + +# Opcional: Configure o endpoint OpenTelemetry +export OTEL_EXPORTER_OTLP_ENDPOINT="https://api.langwatch.ai:4317" +``` + +### 3. **Tratamento de Erros** + +```python +try: + # Suas operações CrewAI + result = crew.kickoff() +except Exception as e: + # Erros serão automaticamente capturados nos rastreamentos + print(f"Erro: {e}") +``` + +### 4. **Monitoramento de Performance** + +- Monitore tempos de execução para agentes e tarefas +- Acompanhe uso de tokens e custos de API +- Identifique gargalos em seu fluxo de trabalho + +## Solução de Problemas + +### Problemas Comuns + +1. **Instrumentação Não Funcionando** + + - Certifique-se de que o instrumentador está sendo importado e inicializado corretamente + - Verifique se o LangWatch está configurado com a chave de API correta + - Confirme se os endpoints OpenTelemetry estão acessíveis + +2. **Rastreamentos Ausentes** + + - Confirme se o instrumentador é chamado antes das operações CrewAI + - Verifique o painel do LangWatch para ingestão de dados + - Confirme conectividade de rede com o LangWatch + +3. **Impacto na Performance** + + - A instrumentação adiciona sobrecarga mínima + - Considere amostragem para ambientes de produção de alto volume + - Monitore uso de recursos durante o desenvolvimento + +### Obtendo Ajuda + +- **OpenLLMetry**: [Documentação](https://opentelemetry.io/docs/) +- **LangWatch**: [Documentação](https://docs.langwatch.ai) + +## Próximos Passos + +1. **Configure o LangWatch**: Configure sua chave de API e configurações do projeto +2. **Instale o OpenLLMetry**: Execute o comando de instalação acima +3. **Instrumente Seu Código**: Use um dos métodos de integração acima +4. **Monitore e Otimize**: Use os dados coletados para melhorar seus fluxos de trabalho CrewAI + +Para configurações mais avançadas e casos de uso, consulte a [documentação do OpenLLMetry](https://opentelemetry.io/docs/) e a [documentação do LangWatch](https://docs.langwatch.ai).