mirror of
https://github.com/crewAIInc/crewAI.git
synced 2025-12-16 04:18:35 +00:00
fix: correct code example language inconsistency in pt-BR docs (#3088)
* fix: correct code example language inconsistency in pt-BR docs * fix: fix: fully standardize code example language and naming in pt-BR docs * fix: fix: fully standardize code example language and naming in pt-BR docs fixed variables * fix: fix: fully standardize code example language and naming in pt-BR docs fixed params --------- Co-authored-by: Lucas Gomide <lucaslg200@gmail.com>
This commit is contained in:
@@ -149,34 +149,33 @@ from crewai_tools import SerperDevTool
|
|||||||
|
|
||||||
# Crie um agente com todos os parâmetros disponíveis
|
# Crie um agente com todos os parâmetros disponíveis
|
||||||
agent = Agent(
|
agent = Agent(
|
||||||
role="Senior Data Scientist",
|
role="Cientista de Dados Sênior",
|
||||||
goal="Analyze and interpret complex datasets to provide actionable insights",
|
goal="Analisar e interpretar conjuntos de dados complexos para fornecer insights acionáveis",
|
||||||
backstory="With over 10 years of experience in data science and machine learning, "
|
backstory="Com mais de 10 anos de experiência em ciência de dados e aprendizado de máquina, você é especialista em encontrar padrões em grandes volumes de dados.",
|
||||||
"you excel at finding patterns in complex datasets.",
|
llm="gpt-4", # Padrão: OPENAI_MODEL_NAME ou "gpt-4"
|
||||||
llm="gpt-4", # Default: OPENAI_MODEL_NAME or "gpt-4"
|
function_calling_llm=None, # Opcional: LLM separado para chamadas de ferramentas
|
||||||
function_calling_llm=None, # Optional: Separate LLM for tool calling
|
verbose=False, # Padrão: False
|
||||||
verbose=False, # Default: False
|
allow_delegation=False, # Padrão: False
|
||||||
allow_delegation=False, # Default: False
|
max_iter=20, # Padrão: 20 iterações
|
||||||
max_iter=20, # Default: 20 iterations
|
max_rpm=None, # Opcional: Limite de requisições por minuto
|
||||||
max_rpm=None, # Optional: Rate limit for API calls
|
max_execution_time=None, # Opcional: Tempo máximo de execução em segundos
|
||||||
max_execution_time=None, # Optional: Maximum execution time in seconds
|
max_retry_limit=2, # Padrão: 2 tentativas em caso de erro
|
||||||
max_retry_limit=2, # Default: 2 retries on error
|
allow_code_execution=False, # Padrão: False
|
||||||
allow_code_execution=False, # Default: False
|
code_execution_mode="safe", # Padrão: "safe" (opções: "safe", "unsafe")
|
||||||
code_execution_mode="safe", # Default: "safe" (options: "safe", "unsafe")
|
respect_context_window=True, # Padrão: True
|
||||||
respect_context_window=True, # Default: True
|
use_system_prompt=True, # Padrão: True
|
||||||
use_system_prompt=True, # Default: True
|
multimodal=False, # Padrão: False
|
||||||
multimodal=False, # Default: False
|
inject_date=False, # Padrão: False
|
||||||
inject_date=False, # Default: False
|
date_format="%Y-%m-%d", # Padrão: formato ISO
|
||||||
date_format="%Y-%m-%d", # Default: ISO format
|
reasoning=False, # Padrão: False
|
||||||
reasoning=False, # Default: False
|
max_reasoning_attempts=None, # Padrão: None
|
||||||
max_reasoning_attempts=None, # Default: None
|
tools=[SerperDevTool()], # Opcional: Lista de ferramentas
|
||||||
tools=[SerperDevTool()], # Optional: List of tools
|
knowledge_sources=None, # Opcional: Lista de fontes de conhecimento
|
||||||
knowledge_sources=None, # Optional: List of knowledge sources
|
embedder=None, # Opcional: Configuração de embedder customizado
|
||||||
embedder=None, # Optional: Custom embedder configuration
|
system_template=None, # Opcional: Template de prompt de sistema
|
||||||
system_template=None, # Optional: Custom system prompt template
|
prompt_template=None, # Opcional: Template de prompt customizado
|
||||||
prompt_template=None, # Optional: Custom prompt template
|
response_template=None, # Opcional: Template de resposta customizado
|
||||||
response_template=None, # Optional: Custom response template
|
step_callback=None, # Opcional: Função de callback para monitoramento
|
||||||
step_callback=None, # Optional: Callback function for monitoring
|
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -185,65 +184,62 @@ Vamos detalhar algumas combinações de parâmetros-chave para casos de uso comu
|
|||||||
#### Agente de Pesquisa Básico
|
#### Agente de Pesquisa Básico
|
||||||
```python Code
|
```python Code
|
||||||
research_agent = Agent(
|
research_agent = Agent(
|
||||||
role="Research Analyst",
|
role="Analista de Pesquisa",
|
||||||
goal="Find and summarize information about specific topics",
|
goal="Encontrar e resumir informações sobre tópicos específicos",
|
||||||
backstory="You are an experienced researcher with attention to detail",
|
backstory="Você é um pesquisador experiente com atenção aos detalhes",
|
||||||
tools=[SerperDevTool()],
|
tools=[SerperDevTool()],
|
||||||
verbose=True # Enable logging for debugging
|
verbose=True # Ativa logs para depuração
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Agente de Desenvolvimento de Código
|
#### Agente de Desenvolvimento de Código
|
||||||
```python Code
|
```python Code
|
||||||
dev_agent = Agent(
|
dev_agent = Agent(
|
||||||
role="Senior Python Developer",
|
role="Desenvolvedor Python Sênior",
|
||||||
goal="Write and debug Python code",
|
goal="Escrever e depurar códigos Python",
|
||||||
backstory="Expert Python developer with 10 years of experience",
|
backstory="Desenvolvedor Python especialista com 10 anos de experiência",
|
||||||
allow_code_execution=True,
|
allow_code_execution=True,
|
||||||
code_execution_mode="safe", # Uses Docker for safety
|
code_execution_mode="safe", # Usa Docker para segurança
|
||||||
max_execution_time=300, # 5-minute timeout
|
max_execution_time=300, # Limite de 5 minutos
|
||||||
max_retry_limit=3 # More retries for complex code tasks
|
max_retry_limit=3 # Mais tentativas para tarefas complexas
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Agente de Análise de Longa Duração
|
#### Agente de Análise de Longa Duração
|
||||||
```python Code
|
```python Code
|
||||||
analysis_agent = Agent(
|
analysis_agent = Agent(
|
||||||
role="Data Analyst",
|
role="Analista de Dados",
|
||||||
goal="Perform deep analysis of large datasets",
|
goal="Realizar análise aprofundada de grandes conjuntos de dados",
|
||||||
backstory="Specialized in big data analysis and pattern recognition",
|
backstory="Especialista em análise de big data e reconhecimento de padrões",
|
||||||
memory=True,
|
memory=True,
|
||||||
respect_context_window=True,
|
respect_context_window=True,
|
||||||
max_rpm=10, # Limit API calls
|
max_rpm=10, # Limite de requisições por minuto
|
||||||
function_calling_llm="gpt-4o-mini" # Cheaper model for tool calls
|
function_calling_llm="gpt-4o-mini" # Modelo mais econômico para chamadas de ferramentas
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Agente com Template Personalizado
|
#### Agente com Template Personalizado
|
||||||
```python Code
|
```python Code
|
||||||
custom_agent = Agent(
|
custom_agent = Agent(
|
||||||
role="Customer Service Representative",
|
role="Atendente de Suporte ao Cliente",
|
||||||
goal="Assist customers with their inquiries",
|
goal="Auxiliar clientes com suas dúvidas e solicitações",
|
||||||
backstory="Experienced in customer support with a focus on satisfaction",
|
backstory="Experiente em atendimento ao cliente com foco em satisfação",
|
||||||
system_template="""<|start_header_id|>system<|end_header_id|>
|
system_template="""<|start_header_id|>system<|end_header_id|>\n {{ .System }}<|eot_id|>""",
|
||||||
{{ .System }}<|eot_id|>""",
|
prompt_template="""<|start_header_id|>user<|end_header_id|>\n {{ .Prompt }}<|eot_id|>""",
|
||||||
prompt_template="""<|start_header_id|>user<|end_header_id|>
|
response_template="""<|start_header_id|>assistant<|end_header_id|>\n {{ .Response }}<|eot_id|>""",
|
||||||
{{ .Prompt }}<|eot_id|>""",
|
|
||||||
response_template="""<|start_header_id|>assistant<|end_header_id|>
|
|
||||||
{{ .Response }}<|eot_id|>""",
|
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Agente Ciente de Data, com Raciocínio
|
#### Agente Ciente de Data, com Raciocínio
|
||||||
```python Code
|
```python Code
|
||||||
strategic_agent = Agent(
|
strategic_agent = Agent(
|
||||||
role="Market Analyst",
|
role="Analista de Mercado",
|
||||||
goal="Track market movements with precise date references and strategic planning",
|
goal="Acompanhar movimentos do mercado com referências de datas precisas e planejamento estratégico",
|
||||||
backstory="Expert in time-sensitive financial analysis and strategic reporting",
|
backstory="Especialista em análise financeira sensível ao tempo e relatórios estratégicos",
|
||||||
inject_date=True, # Automatically inject current date into tasks
|
inject_date=True, # Injeta automaticamente a data atual nas tarefas
|
||||||
date_format="%B %d, %Y", # Format as "May 21, 2025"
|
date_format="%d de %B de %Y", # Exemplo: "21 de maio de 2025"
|
||||||
reasoning=True, # Enable strategic planning
|
reasoning=True, # Ativa planejamento estratégico
|
||||||
max_reasoning_attempts=2, # Limit planning iterations
|
max_reasoning_attempts=2, # Limite de iterações de planejamento
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
@@ -251,12 +247,12 @@ strategic_agent = Agent(
|
|||||||
#### Agente de Raciocínio
|
#### Agente de Raciocínio
|
||||||
```python Code
|
```python Code
|
||||||
reasoning_agent = Agent(
|
reasoning_agent = Agent(
|
||||||
role="Strategic Planner",
|
role="Planejador Estratégico",
|
||||||
goal="Analyze complex problems and create detailed execution plans",
|
goal="Analisar problemas complexos e criar planos de execução detalhados",
|
||||||
backstory="Expert strategic planner who methodically breaks down complex challenges",
|
backstory="Especialista em planejamento estratégico que desmembra desafios complexos metodicamente",
|
||||||
reasoning=True, # Enable reasoning and planning
|
reasoning=True, # Ativa raciocínio e planejamento
|
||||||
max_reasoning_attempts=3, # Limit reasoning attempts
|
max_reasoning_attempts=3, # Limite de tentativas de raciocínio
|
||||||
max_iter=30, # Allow more iterations for complex planning
|
max_iter=30, # Permite mais iterações para planejamento complexo
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
@@ -264,10 +260,10 @@ reasoning_agent = Agent(
|
|||||||
#### Agente Multimodal
|
#### Agente Multimodal
|
||||||
```python Code
|
```python Code
|
||||||
multimodal_agent = Agent(
|
multimodal_agent = Agent(
|
||||||
role="Visual Content Analyst",
|
role="Analista de Conteúdo Visual",
|
||||||
goal="Analyze and process both text and visual content",
|
goal="Analisar e processar tanto conteúdo textual quanto visual",
|
||||||
backstory="Specialized in multimodal analysis combining text and image understanding",
|
backstory="Especialista em análise multimodal combinando compreensão de texto e imagem",
|
||||||
multimodal=True, # Enable multimodal capabilities
|
multimodal=True, # Ativa capacidades multimodais
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
@@ -336,8 +332,8 @@ wiki_tool = WikipediaTools()
|
|||||||
|
|
||||||
# Adicionar ferramentas ao agente
|
# Adicionar ferramentas ao agente
|
||||||
researcher = Agent(
|
researcher = Agent(
|
||||||
role="AI Technology Researcher",
|
role="Pesquisador de Tecnologia em IA",
|
||||||
goal="Research the latest AI developments",
|
goal="Pesquisar os últimos avanços em IA",
|
||||||
tools=[search_tool, wiki_tool],
|
tools=[search_tool, wiki_tool],
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
@@ -351,9 +347,9 @@ Agentes podem manter a memória de suas interações e usar contexto de tarefas
|
|||||||
from crewai import Agent
|
from crewai import Agent
|
||||||
|
|
||||||
analyst = Agent(
|
analyst = Agent(
|
||||||
role="Data Analyst",
|
role="Analista de Dados",
|
||||||
goal="Analyze and remember complex data patterns",
|
goal="Analisar e memorizar padrões complexos de dados",
|
||||||
memory=True, # Enable memory
|
memory=True, # Ativa memória
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
@@ -380,10 +376,10 @@ Esta é a **configuração padrão e recomendada** para a maioria dos casos. Qua
|
|||||||
```python Code
|
```python Code
|
||||||
# Agente com gerenciamento automático de contexto (padrão)
|
# Agente com gerenciamento automático de contexto (padrão)
|
||||||
smart_agent = Agent(
|
smart_agent = Agent(
|
||||||
role="Research Analyst",
|
role="Analista de Pesquisa",
|
||||||
goal="Analyze large documents and datasets",
|
goal="Analisar grandes documentos e conjuntos de dados",
|
||||||
backstory="Expert at processing extensive information",
|
backstory="Especialista em processar informações extensas",
|
||||||
respect_context_window=True, # 🔑 Default: auto-handle context limits
|
respect_context_window=True, # 🔑 Padrão: gerencia limites de contexto automaticamente
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -75,6 +75,20 @@ Exemplo:
|
|||||||
crewai train -n 10 -f my_training_data.pkl
|
crewai train -n 10 -f my_training_data.pkl
|
||||||
```
|
```
|
||||||
|
|
||||||
|
# Exemplo de uso programático do comando train
|
||||||
|
n_iterations = 2
|
||||||
|
inputs = {"topic": "Treinamento CrewAI"}
|
||||||
|
filename = "seu_modelo.pkl"
|
||||||
|
|
||||||
|
try:
|
||||||
|
SuaCrew().crew().train(
|
||||||
|
n_iterations=n_iterations,
|
||||||
|
inputs=inputs,
|
||||||
|
filename=filename
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Ocorreu um erro ao treinar a crew: {e}")
|
||||||
|
|
||||||
### 4. Replay
|
### 4. Replay
|
||||||
|
|
||||||
Reexecute a execução do crew a partir de uma tarefa específica.
|
Reexecute a execução do crew a partir de uma tarefa específica.
|
||||||
|
|||||||
@@ -15,18 +15,18 @@ from crewai import Agent, Crew, Task
|
|||||||
|
|
||||||
# Enable collaboration for agents
|
# Enable collaboration for agents
|
||||||
researcher = Agent(
|
researcher = Agent(
|
||||||
role="Research Specialist",
|
role="Especialista em Pesquisa",
|
||||||
goal="Conduct thorough research on any topic",
|
goal="Realizar pesquisas aprofundadas sobre qualquer tema",
|
||||||
backstory="Expert researcher with access to various sources",
|
backstory="Pesquisador especialista com acesso a diversas fontes",
|
||||||
allow_delegation=True, # 🔑 Key setting for collaboration
|
allow_delegation=True, # 🔑 Configuração chave para colaboração
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
writer = Agent(
|
writer = Agent(
|
||||||
role="Content Writer",
|
role="Redator de Conteúdo",
|
||||||
goal="Create engaging content based on research",
|
goal="Criar conteúdo envolvente com base em pesquisas",
|
||||||
backstory="Skilled writer who transforms research into compelling content",
|
backstory="Redator habilidoso que transforma pesquisas em conteúdo atraente",
|
||||||
allow_delegation=True, # 🔑 Enables asking questions to other agents
|
allow_delegation=True, # 🔑 Permite fazer perguntas a outros agentes
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -67,19 +67,17 @@ from crewai import Agent, Crew, Task, Process
|
|||||||
|
|
||||||
# Create collaborative agents
|
# Create collaborative agents
|
||||||
researcher = Agent(
|
researcher = Agent(
|
||||||
role="Research Specialist",
|
role="Especialista em Pesquisa",
|
||||||
goal="Find accurate, up-to-date information on any topic",
|
goal="Realizar pesquisas aprofundadas sobre qualquer tema",
|
||||||
backstory="""You're a meticulous researcher with expertise in finding
|
backstory="Pesquisador especialista com acesso a diversas fontes",
|
||||||
reliable sources and fact-checking information across various domains.""",
|
|
||||||
allow_delegation=True,
|
allow_delegation=True,
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
writer = Agent(
|
writer = Agent(
|
||||||
role="Content Writer",
|
role="Redator de Conteúdo",
|
||||||
goal="Create engaging, well-structured content",
|
goal="Criar conteúdo envolvente com base em pesquisas",
|
||||||
backstory="""You're a skilled content writer who excels at transforming
|
backstory="Redator habilidoso que transforma pesquisas em conteúdo atraente",
|
||||||
research into compelling, readable content for different audiences.""",
|
|
||||||
allow_delegation=True,
|
allow_delegation=True,
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
@@ -95,17 +93,17 @@ editor = Agent(
|
|||||||
|
|
||||||
# Create a task that encourages collaboration
|
# Create a task that encourages collaboration
|
||||||
article_task = Task(
|
article_task = Task(
|
||||||
description="""Write a comprehensive 1000-word article about 'The Future of AI in Healthcare'.
|
description="""Escreva um artigo abrangente de 1000 palavras sobre 'O Futuro da IA na Saúde'.
|
||||||
|
|
||||||
The article should include:
|
O artigo deve incluir:
|
||||||
- Current AI applications in healthcare
|
- Aplicações atuais de IA na saúde
|
||||||
- Emerging trends and technologies
|
- Tendências e tecnologias emergentes
|
||||||
- Potential challenges and ethical considerations
|
- Desafios potenciais e considerações éticas
|
||||||
- Expert predictions for the next 5 years
|
- Previsões de especialistas para os próximos 5 anos
|
||||||
|
|
||||||
Collaborate with your teammates to ensure accuracy and quality.""",
|
Colabore com seus colegas para garantir precisão e qualidade.""",
|
||||||
expected_output="A well-researched, engaging 1000-word article with proper structure and citations",
|
expected_output="Um artigo bem pesquisado, envolvente, com 1000 palavras, estrutura adequada e citações",
|
||||||
agent=writer # Writer leads, but can delegate research to researcher
|
agent=writer # O redator lidera, mas pode delegar pesquisa ao pesquisador
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create collaborative crew
|
# Create collaborative crew
|
||||||
@@ -124,37 +122,37 @@ result = crew.kickoff()
|
|||||||
### Padrão 1: Pesquisa → Redação → Edição
|
### Padrão 1: Pesquisa → Redação → Edição
|
||||||
```python
|
```python
|
||||||
research_task = Task(
|
research_task = Task(
|
||||||
description="Research the latest developments in quantum computing",
|
description="Pesquise os últimos avanços em computação quântica",
|
||||||
expected_output="Comprehensive research summary with key findings and sources",
|
expected_output="Resumo abrangente da pesquisa com principais descobertas e fontes",
|
||||||
agent=researcher
|
agent=researcher
|
||||||
)
|
)
|
||||||
|
|
||||||
writing_task = Task(
|
writing_task = Task(
|
||||||
description="Write an article based on the research findings",
|
description="Escreva um artigo com base nos achados da pesquisa",
|
||||||
expected_output="Engaging 800-word article about quantum computing",
|
expected_output="Artigo envolvente de 800 palavras sobre computação quântica",
|
||||||
agent=writer,
|
agent=writer,
|
||||||
context=[research_task] # Gets research output as context
|
context=[research_task] # Recebe a saída da pesquisa como contexto
|
||||||
)
|
)
|
||||||
|
|
||||||
editing_task = Task(
|
editing_task = Task(
|
||||||
description="Edit and polish the article for publication",
|
description="Edite e revise o artigo para publicação",
|
||||||
expected_output="Publication-ready article with improved clarity and flow",
|
expected_output="Artigo pronto para publicação, com clareza e fluidez aprimoradas",
|
||||||
agent=editor,
|
agent=editor,
|
||||||
context=[writing_task] # Gets article draft as context
|
context=[writing_task] # Recebe o rascunho do artigo como contexto
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Padrão 2: Tarefa Única Colaborativa
|
### Padrão 2: Tarefa Única Colaborativa
|
||||||
```python
|
```python
|
||||||
collaborative_task = Task(
|
collaborative_task = Task(
|
||||||
description="""Create a marketing strategy for a new AI product.
|
description="""Crie uma estratégia de marketing para um novo produto de IA.
|
||||||
|
|
||||||
Writer: Focus on messaging and content strategy
|
Redator: Foque em mensagens e estratégia de conteúdo
|
||||||
Researcher: Provide market analysis and competitor insights
|
Pesquisador: Forneça análise de mercado e insights de concorrentes
|
||||||
|
|
||||||
Work together to create a comprehensive strategy.""",
|
Trabalhem juntos para criar uma estratégia abrangente.""",
|
||||||
expected_output="Complete marketing strategy with research backing",
|
expected_output="Estratégia de marketing completa com embasamento em pesquisa",
|
||||||
agent=writer # Lead agent, but can delegate to researcher
|
agent=writer # Agente líder, mas pode delegar ao pesquisador
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -167,35 +165,35 @@ from crewai import Agent, Crew, Task, Process
|
|||||||
|
|
||||||
# Manager agent coordinates the team
|
# Manager agent coordinates the team
|
||||||
manager = Agent(
|
manager = Agent(
|
||||||
role="Project Manager",
|
role="Gerente de Projetos",
|
||||||
goal="Coordinate team efforts and ensure project success",
|
goal="Coordenar esforços da equipe e garantir o sucesso do projeto",
|
||||||
backstory="Experienced project manager skilled at delegation and quality control",
|
backstory="Gerente de projetos experiente, habilidoso em delegação e controle de qualidade",
|
||||||
allow_delegation=True,
|
allow_delegation=True,
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
# Specialist agents
|
# Specialist agents
|
||||||
researcher = Agent(
|
researcher = Agent(
|
||||||
role="Researcher",
|
role="Pesquisador",
|
||||||
goal="Provide accurate research and analysis",
|
goal="Fornecer pesquisa e análise precisas",
|
||||||
backstory="Expert researcher with deep analytical skills",
|
backstory="Pesquisador especialista com habilidades analíticas profundas",
|
||||||
allow_delegation=False, # Specialists focus on their expertise
|
allow_delegation=False, # Especialistas focam em sua expertise
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
writer = Agent(
|
writer = Agent(
|
||||||
role="Writer",
|
role="Redator",
|
||||||
goal="Create compelling content",
|
goal="Criar conteúdo envolvente",
|
||||||
backstory="Skilled writer who creates engaging content",
|
backstory="Redator habilidoso que cria conteúdo atraente",
|
||||||
allow_delegation=False,
|
allow_delegation=False,
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
# Manager-led task
|
# Manager-led task
|
||||||
project_task = Task(
|
project_task = Task(
|
||||||
description="Create a comprehensive market analysis report with recommendations",
|
description="Crie um relatório de análise de mercado completo com recomendações",
|
||||||
expected_output="Executive summary, detailed analysis, and strategic recommendations",
|
expected_output="Resumo executivo, análise detalhada e recomendações estratégicas",
|
||||||
agent=manager # Manager will delegate to specialists
|
agent=manager # O gerente delega para especialistas
|
||||||
)
|
)
|
||||||
|
|
||||||
# Hierarchical crew
|
# Hierarchical crew
|
||||||
|
|||||||
@@ -153,32 +153,32 @@ from crewai_tools import YourCustomTool
|
|||||||
class YourCrewName:
|
class YourCrewName:
|
||||||
def agent_one(self) -> Agent:
|
def agent_one(self) -> Agent:
|
||||||
return Agent(
|
return Agent(
|
||||||
role="Data Analyst",
|
role="Analista de Dados",
|
||||||
goal="Analyze data trends in the market",
|
goal="Analisar tendências de dados no mercado brasileiro",
|
||||||
backstory="An experienced data analyst with a background in economics",
|
backstory="Analista experiente com formação em economia",
|
||||||
verbose=True,
|
verbose=True,
|
||||||
tools=[YourCustomTool()]
|
tools=[YourCustomTool()]
|
||||||
)
|
)
|
||||||
|
|
||||||
def agent_two(self) -> Agent:
|
def agent_two(self) -> Agent:
|
||||||
return Agent(
|
return Agent(
|
||||||
role="Market Researcher",
|
role="Pesquisador de Mercado",
|
||||||
goal="Gather information on market dynamics",
|
goal="Coletar informações sobre a dinâmica do mercado nacional",
|
||||||
backstory="A diligent researcher with a keen eye for detail",
|
backstory="Pesquisador dedicado com olhar atento aos detalhes",
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
def task_one(self) -> Task:
|
def task_one(self) -> Task:
|
||||||
return Task(
|
return Task(
|
||||||
description="Collect recent market data and identify trends.",
|
description="Coletar dados recentes do mercado brasileiro e identificar tendências.",
|
||||||
expected_output="A report summarizing key trends in the market.",
|
expected_output="Um relatório resumido com as principais tendências do mercado.",
|
||||||
agent=self.agent_one()
|
agent=self.agent_one()
|
||||||
)
|
)
|
||||||
|
|
||||||
def task_two(self) -> Task:
|
def task_two(self) -> Task:
|
||||||
return Task(
|
return Task(
|
||||||
description="Research factors affecting market dynamics.",
|
description="Pesquisar fatores que afetam a dinâmica do mercado nacional.",
|
||||||
expected_output="An analysis of factors influencing the market.",
|
expected_output="Uma análise dos fatores que influenciam o mercado.",
|
||||||
agent=self.agent_two()
|
agent=self.agent_two()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -51,24 +51,24 @@ from crewai.utilities.events import (
|
|||||||
)
|
)
|
||||||
from crewai.utilities.events.base_event_listener import BaseEventListener
|
from crewai.utilities.events.base_event_listener import BaseEventListener
|
||||||
|
|
||||||
class MyCustomListener(BaseEventListener):
|
class MeuListenerPersonalizado(BaseEventListener):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
def setup_listeners(self, crewai_event_bus):
|
def setup_listeners(self, crewai_event_bus):
|
||||||
@crewai_event_bus.on(CrewKickoffStartedEvent)
|
@crewai_event_bus.on(CrewKickoffStartedEvent)
|
||||||
def on_crew_started(source, event):
|
def ao_iniciar_crew(source, event):
|
||||||
print(f"Crew '{event.crew_name}' has started execution!")
|
print(f"Crew '{event.crew_name}' iniciou a execução!")
|
||||||
|
|
||||||
@crewai_event_bus.on(CrewKickoffCompletedEvent)
|
@crewai_event_bus.on(CrewKickoffCompletedEvent)
|
||||||
def on_crew_completed(source, event):
|
def ao_finalizar_crew(source, event):
|
||||||
print(f"Crew '{event.crew_name}' has completed execution!")
|
print(f"Crew '{event.crew_name}' finalizou a execução!")
|
||||||
print(f"Output: {event.output}")
|
print(f"Saída: {event.output}")
|
||||||
|
|
||||||
@crewai_event_bus.on(AgentExecutionCompletedEvent)
|
@crewai_event_bus.on(AgentExecutionCompletedEvent)
|
||||||
def on_agent_execution_completed(source, event):
|
def ao_finalizar_execucao_agente(source, event):
|
||||||
print(f"Agent '{event.agent.role}' completed task")
|
print(f"Agente '{event.agent.role}' concluiu a tarefa")
|
||||||
print(f"Output: {event.output}")
|
print(f"Saída: {event.output}")
|
||||||
```
|
```
|
||||||
|
|
||||||
## Registrando Corretamente Seu Listener
|
## Registrando Corretamente Seu Listener
|
||||||
|
|||||||
@@ -486,8 +486,9 @@ Existem duas formas de executar um flow:
|
|||||||
Você pode executar um flow programaticamente criando uma instância da sua classe de flow e chamando o método `kickoff()`:
|
Você pode executar um flow programaticamente criando uma instância da sua classe de flow e chamando o método `kickoff()`:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
flow = ExampleFlow()
|
# Exemplo de execução de flow em português
|
||||||
result = flow.kickoff()
|
flow = ExemploFlow()
|
||||||
|
resultado = flow.kickoff()
|
||||||
```
|
```
|
||||||
|
|
||||||
### Usando a CLI
|
### Usando a CLI
|
||||||
|
|||||||
@@ -39,17 +39,17 @@ llm = LLM(model="gpt-4o-mini", temperature=0)
|
|||||||
|
|
||||||
# Create an agent with the knowledge store
|
# Create an agent with the knowledge store
|
||||||
agent = Agent(
|
agent = Agent(
|
||||||
role="About User",
|
role="Sobre o Usuário",
|
||||||
goal="You know everything about the user.",
|
goal="Você sabe tudo sobre o usuário.",
|
||||||
backstory="You are a master at understanding people and their preferences.",
|
backstory="Você é mestre em entender pessoas e suas preferências.",
|
||||||
verbose=True,
|
verbose=True,
|
||||||
allow_delegation=False,
|
allow_delegation=False,
|
||||||
llm=llm,
|
llm=llm,
|
||||||
)
|
)
|
||||||
|
|
||||||
task = Task(
|
task = Task(
|
||||||
description="Answer the following questions about the user: {question}",
|
description="Responda às seguintes perguntas sobre o usuário: {question}",
|
||||||
expected_output="An answer to the question.",
|
expected_output="Uma resposta para a pergunta.",
|
||||||
agent=agent,
|
agent=agent,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -87,17 +87,17 @@ llm = LLM(model="gpt-4o-mini", temperature=0)
|
|||||||
|
|
||||||
# Create an agent with the knowledge store
|
# Create an agent with the knowledge store
|
||||||
agent = Agent(
|
agent = Agent(
|
||||||
role="About papers",
|
role="Sobre artigos",
|
||||||
goal="You know everything about the papers.",
|
goal="Você sabe tudo sobre os artigos.",
|
||||||
backstory="You are a master at understanding papers and their content.",
|
backstory="Você é mestre em entender artigos e seus conteúdos.",
|
||||||
verbose=True,
|
verbose=True,
|
||||||
allow_delegation=False,
|
allow_delegation=False,
|
||||||
llm=llm,
|
llm=llm,
|
||||||
)
|
)
|
||||||
|
|
||||||
task = Task(
|
task = Task(
|
||||||
description="Answer the following questions about the papers: {question}",
|
description="Responda às seguintes perguntas sobre os artigos: {question}",
|
||||||
expected_output="An answer to the question.",
|
expected_output="Uma resposta para a pergunta.",
|
||||||
agent=agent,
|
agent=agent,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -201,16 +201,16 @@ specialist_knowledge = StringKnowledgeSource(
|
|||||||
)
|
)
|
||||||
|
|
||||||
specialist_agent = Agent(
|
specialist_agent = Agent(
|
||||||
role="Technical Specialist",
|
role="Especialista Técnico",
|
||||||
goal="Provide technical expertise",
|
goal="Fornecer expertise técnica",
|
||||||
backstory="Expert in specialized technical domains",
|
backstory="Especialista em domínios técnicos especializados",
|
||||||
knowledge_sources=[specialist_knowledge] # Agent-specific knowledge
|
knowledge_sources=[specialist_knowledge] # Conhecimento específico do agente
|
||||||
)
|
)
|
||||||
|
|
||||||
task = Task(
|
task = Task(
|
||||||
description="Answer technical questions",
|
description="Responda perguntas técnicas",
|
||||||
agent=specialist_agent,
|
agent=specialist_agent,
|
||||||
expected_output="Technical answer"
|
expected_output="Resposta técnica"
|
||||||
)
|
)
|
||||||
|
|
||||||
# No crew-level knowledge required
|
# No crew-level knowledge required
|
||||||
@@ -240,7 +240,7 @@ Cada nível de knowledge usa coleções de armazenamento independentes:
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
# Agent knowledge storage
|
# Agent knowledge storage
|
||||||
agent_collection_name = agent.role # e.g., "Technical Specialist"
|
agent_collection_name = agent.role # e.g., "Especialista Técnico"
|
||||||
|
|
||||||
# Crew knowledge storage
|
# Crew knowledge storage
|
||||||
crew_collection_name = "crew"
|
crew_collection_name = "crew"
|
||||||
@@ -248,7 +248,7 @@ crew_collection_name = "crew"
|
|||||||
# Both stored in same ChromaDB instance but different collections
|
# Both stored in same ChromaDB instance but different collections
|
||||||
# Path: ~/.local/share/CrewAI/{project}/knowledge/
|
# Path: ~/.local/share/CrewAI/{project}/knowledge/
|
||||||
# ├── crew/ # Crew knowledge collection
|
# ├── crew/ # Crew knowledge collection
|
||||||
# ├── Technical Specialist/ # Agent knowledge collection
|
# ├── Especialista Técnico/ # Agent knowledge collection
|
||||||
# └── Another Agent Role/ # Another agent's collection
|
# └── Another Agent Role/ # Another agent's collection
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -265,7 +265,7 @@ agent_knowledge = StringKnowledgeSource(
|
|||||||
)
|
)
|
||||||
|
|
||||||
agent = Agent(
|
agent = Agent(
|
||||||
role="Specialist",
|
role="Especialista",
|
||||||
goal="Use specialized knowledge",
|
goal="Use specialized knowledge",
|
||||||
backstory="Expert with specific knowledge",
|
backstory="Expert with specific knowledge",
|
||||||
knowledge_sources=[agent_knowledge],
|
knowledge_sources=[agent_knowledge],
|
||||||
@@ -299,10 +299,10 @@ specialist_knowledge = StringKnowledgeSource(
|
|||||||
)
|
)
|
||||||
|
|
||||||
specialist = Agent(
|
specialist = Agent(
|
||||||
role="Technical Specialist",
|
role="Especialista Técnico",
|
||||||
goal="Provide technical expertise",
|
goal="Fornecer expertise técnica",
|
||||||
backstory="Technical expert",
|
backstory="Especialista em domínios técnicos especializados",
|
||||||
knowledge_sources=[specialist_knowledge] # Agent-specific
|
knowledge_sources=[specialist_knowledge] # Conhecimento específico do agente
|
||||||
)
|
)
|
||||||
|
|
||||||
generalist = Agent(
|
generalist = Agent(
|
||||||
|
|||||||
@@ -78,15 +78,15 @@ Existem diferentes locais no código do CrewAI onde você pode especificar o mod
|
|||||||
|
|
||||||
# Configuração avançada com parâmetros detalhados
|
# Configuração avançada com parâmetros detalhados
|
||||||
llm = LLM(
|
llm = LLM(
|
||||||
model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
model="openai/gpt-4",
|
||||||
temperature=0.7, # Mais alto para saídas criativas
|
temperature=0.8,
|
||||||
timeout=120, # Segundos para aguardar resposta
|
max_tokens=150,
|
||||||
max_tokens=4000, # Comprimento máximo da resposta
|
top_p=0.9,
|
||||||
top_p=0.9, # Parâmetro de amostragem nucleus
|
frequency_penalty=0.1,
|
||||||
frequency_penalty=0.1 , # Reduz repetição
|
presence_penalty=0.1,
|
||||||
presence_penalty=0.1, # Incentiva diversidade de tópicos
|
response_format={"type":"json"},
|
||||||
response_format={"type": "json"}, # Para respostas estruturadas
|
stop=["FIM"],
|
||||||
seed=42 # Para resultados reproduzíveis
|
seed=42
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -127,13 +127,13 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
|||||||
from crewai import LLM
|
from crewai import LLM
|
||||||
|
|
||||||
llm = LLM(
|
llm = LLM(
|
||||||
model="openai/gpt-4", # chamar modelo por provider/model_name
|
model="openai/gpt-4",
|
||||||
temperature=0.8,
|
temperature=0.8,
|
||||||
max_tokens=150,
|
max_tokens=150,
|
||||||
top_p=0.9,
|
top_p=0.9,
|
||||||
frequency_penalty=0.1,
|
frequency_penalty=0.1,
|
||||||
presence_penalty=0.1,
|
presence_penalty=0.1,
|
||||||
stop=["END"],
|
stop=["FIM"],
|
||||||
seed=42
|
seed=42
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
@@ -169,7 +169,7 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
|||||||
llm = LLM(
|
llm = LLM(
|
||||||
model="meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8",
|
model="meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8",
|
||||||
temperature=0.8,
|
temperature=0.8,
|
||||||
stop=["END"],
|
stop=["FIM"],
|
||||||
seed=42
|
seed=42
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ Começar a usar o recurso de planejamento é muito simples, o único passo neces
|
|||||||
from crewai import Crew, Agent, Task, Process
|
from crewai import Crew, Agent, Task, Process
|
||||||
|
|
||||||
# Monte sua crew com capacidades de planejamento
|
# Monte sua crew com capacidades de planejamento
|
||||||
my_crew = Crew(
|
minha_crew = Crew(
|
||||||
agents=self.agents,
|
agents=self.agents,
|
||||||
tasks=self.tasks,
|
tasks=self.tasks,
|
||||||
process=Process.sequential,
|
process=Process.sequential,
|
||||||
|
|||||||
@@ -28,23 +28,23 @@ from crewai import Crew, Process
|
|||||||
|
|
||||||
# Exemplo: Criando uma crew com processo sequencial
|
# Exemplo: Criando uma crew com processo sequencial
|
||||||
crew = Crew(
|
crew = Crew(
|
||||||
agents=my_agents,
|
agents=meus_agentes,
|
||||||
tasks=my_tasks,
|
tasks=minhas_tarefas,
|
||||||
process=Process.sequential
|
process=Process.sequential
|
||||||
)
|
)
|
||||||
|
|
||||||
# Exemplo: Criando uma crew com processo hierárquico
|
# Exemplo: Criando uma crew com processo hierárquico
|
||||||
# Certifique-se de fornecer um manager_llm ou manager_agent
|
# Certifique-se de fornecer um manager_llm ou manager_agent
|
||||||
crew = Crew(
|
crew = Crew(
|
||||||
agents=my_agents,
|
agents=meus_agentes,
|
||||||
tasks=my_tasks,
|
tasks=minhas_tarefas,
|
||||||
process=Process.hierarchical,
|
process=Process.hierarchical,
|
||||||
manager_llm="gpt-4o"
|
manager_llm="gpt-4o"
|
||||||
# ou
|
# ou
|
||||||
# manager_agent=my_manager_agent
|
# manager_agent=meu_agente_gerente
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
**Nota:** Certifique-se de que `my_agents` e `my_tasks` estejam definidos antes de criar o objeto `Crew`, e para o processo hierárquico, é necessário também fornecer o `manager_llm` ou `manager_agent`.
|
**Nota:** Certifique-se de que `meus_agentes` e `minhas_tarefas` estejam definidos antes de criar o objeto `Crew`, e para o processo hierárquico, é necessário também fornecer o `manager_llm` ou `manager_agent`.
|
||||||
|
|
||||||
## Processo Sequencial
|
## Processo Sequencial
|
||||||
|
|
||||||
|
|||||||
@@ -15,12 +15,12 @@ Para habilitar o reasoning para um agente, basta definir `reasoning=True` ao cri
|
|||||||
```python
|
```python
|
||||||
from crewai import Agent
|
from crewai import Agent
|
||||||
|
|
||||||
agent = Agent(
|
analista = Agent(
|
||||||
role="Data Analyst",
|
role="Analista de Dados",
|
||||||
goal="Analyze complex datasets and provide insights",
|
goal="Analisar dados e fornecer insights",
|
||||||
backstory="You are an experienced data analyst with expertise in finding patterns in complex data.",
|
backstory="Você é um analista de dados especialista.",
|
||||||
reasoning=True, # Enable reasoning
|
reasoning=True,
|
||||||
max_reasoning_attempts=3 # Optional: Set a maximum number of reasoning attempts
|
max_reasoning_attempts=3 # Opcional: Defina um limite de tentativas de reasoning
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -53,23 +53,23 @@ Aqui está um exemplo completo:
|
|||||||
from crewai import Agent, Task, Crew
|
from crewai import Agent, Task, Crew
|
||||||
|
|
||||||
# Create an agent with reasoning enabled
|
# Create an agent with reasoning enabled
|
||||||
analyst = Agent(
|
analista = Agent(
|
||||||
role="Data Analyst",
|
role="Analista de Dados",
|
||||||
goal="Analyze data and provide insights",
|
goal="Analisar dados e fornecer insights",
|
||||||
backstory="You are an expert data analyst.",
|
backstory="Você é um analista de dados especialista.",
|
||||||
reasoning=True,
|
reasoning=True,
|
||||||
max_reasoning_attempts=3 # Optional: Set a limit on reasoning attempts
|
max_reasoning_attempts=3 # Opcional: Defina um limite de tentativas de reasoning
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create a task
|
# Create a task
|
||||||
analysis_task = Task(
|
analysis_task = Task(
|
||||||
description="Analyze the provided sales data and identify key trends.",
|
description="Analise os dados de vendas fornecidos e identifique as principais tendências.",
|
||||||
expected_output="A report highlighting the top 3 sales trends.",
|
expected_output="Um relatório destacando as 3 principais tendências de vendas.",
|
||||||
agent=analyst
|
agent=analista
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create a crew and run the task
|
# Create a crew and run the task
|
||||||
crew = Crew(agents=[analyst], tasks=[analysis_task])
|
crew = Crew(agents=[analista], tasks=[analysis_task])
|
||||||
result = crew.kickoff()
|
result = crew.kickoff()
|
||||||
|
|
||||||
print(result)
|
print(result)
|
||||||
@@ -90,16 +90,16 @@ logging.basicConfig(level=logging.INFO)
|
|||||||
|
|
||||||
# Create an agent with reasoning enabled
|
# Create an agent with reasoning enabled
|
||||||
agent = Agent(
|
agent = Agent(
|
||||||
role="Data Analyst",
|
role="Analista de Dados",
|
||||||
goal="Analyze data and provide insights",
|
goal="Analisar dados e fornecer insights",
|
||||||
reasoning=True,
|
reasoning=True,
|
||||||
max_reasoning_attempts=3
|
max_reasoning_attempts=3
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create a task
|
# Create a task
|
||||||
task = Task(
|
task = Task(
|
||||||
description="Analyze the provided sales data and identify key trends.",
|
description="Analise os dados de vendas fornecidos e identifique as principais tendências.",
|
||||||
expected_output="A report highlighting the top 3 sales trends.",
|
expected_output="Um relatório destacando as 3 principais tendências de vendas.",
|
||||||
agent=agent
|
agent=agent
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -113,7 +113,7 @@ result = agent.execute_task(task)
|
|||||||
Veja um exemplo de como pode ser um plano de reasoning para uma tarefa de análise de dados:
|
Veja um exemplo de como pode ser um plano de reasoning para uma tarefa de análise de dados:
|
||||||
|
|
||||||
```
|
```
|
||||||
Task: Analyze the provided sales data and identify key trends.
|
Task: Analise os dados de vendas fornecidos e identifique as principais tendências.
|
||||||
|
|
||||||
Reasoning Plan:
|
Reasoning Plan:
|
||||||
I'll analyze the sales data to identify the top 3 trends.
|
I'll analyze the sales data to identify the top 3 trends.
|
||||||
|
|||||||
@@ -386,7 +386,7 @@ def validate_with_context(result: TaskOutput) -> Tuple[bool, Any]:
|
|||||||
validated_data = perform_validation(result)
|
validated_data = perform_validation(result)
|
||||||
return (True, validated_data)
|
return (True, validated_data)
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
return (False, f"VALIDATION_ERROR: {str(e)}")
|
return (False, f"ERRO_DE_VALIDACAO: {str(e)}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return (False, str(e))
|
return (False, str(e))
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -67,17 +67,17 @@ web_rag_tool = WebsiteSearchTool()
|
|||||||
|
|
||||||
# Criar agentes
|
# Criar agentes
|
||||||
researcher = Agent(
|
researcher = Agent(
|
||||||
role='Market Research Analyst',
|
role='Analista de Mercado',
|
||||||
goal='Provide up-to-date market analysis of the AI industry',
|
goal='Fornecer análise de mercado atualizada da indústria de IA',
|
||||||
backstory='An expert analyst with a keen eye for market trends.',
|
backstory='Analista especialista com olhar atento para tendências de mercado.',
|
||||||
tools=[search_tool, web_rag_tool],
|
tools=[search_tool, web_rag_tool],
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
writer = Agent(
|
writer = Agent(
|
||||||
role='Content Writer',
|
role='Redator de Conteúdo',
|
||||||
goal='Craft engaging blog posts about the AI industry',
|
goal='Criar posts de blog envolventes sobre a indústria de IA',
|
||||||
backstory='A skilled writer with a passion for technology.',
|
backstory='Redator habilidoso com paixão por tecnologia.',
|
||||||
tools=[docs_tool, file_tool],
|
tools=[docs_tool, file_tool],
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -36,19 +36,18 @@ Para treinar sua crew de forma programática, siga estes passos:
|
|||||||
3. Execute o comando de treinamento dentro de um bloco try-except para tratar possíveis erros.
|
3. Execute o comando de treinamento dentro de um bloco try-except para tratar possíveis erros.
|
||||||
|
|
||||||
```python Code
|
```python Code
|
||||||
n_iterations = 2
|
n_iteracoes = 2
|
||||||
inputs = {"topic": "CrewAI Training"}
|
entradas = {"topic": "Treinamento CrewAI"}
|
||||||
filename = "your_model.pkl"
|
nome_arquivo = "seu_modelo.pkl"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
YourCrewName_Crew().crew().train(
|
SuaCrew().crew().train(
|
||||||
n_iterations=n_iterations,
|
n_iterations=n_iteracoes,
|
||||||
inputs=inputs,
|
inputs=entradas,
|
||||||
filename=filename
|
filename=nome_arquivo
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise Exception(f"An error occurred while training the crew: {e}")
|
raise Exception(f"Ocorreu um erro ao treinar a crew: {e}")
|
||||||
```
|
```
|
||||||
|
|
||||||
### Pontos Importantes
|
### Pontos Importantes
|
||||||
|
|||||||
@@ -26,13 +26,13 @@ from crewai.tasks.hallucination_guardrail import HallucinationGuardrail
|
|||||||
from crewai import LLM
|
from crewai import LLM
|
||||||
|
|
||||||
# Uso básico - utiliza o expected_output da tarefa como contexto
|
# Uso básico - utiliza o expected_output da tarefa como contexto
|
||||||
guardrail = HallucinationGuardrail(
|
protecao = HallucinationGuardrail(
|
||||||
llm=LLM(model="gpt-4o-mini")
|
llm=LLM(model="gpt-4o-mini")
|
||||||
)
|
)
|
||||||
|
|
||||||
# Com contexto de referência explícito
|
# Com contexto de referência explícito
|
||||||
context_guardrail = HallucinationGuardrail(
|
protecao_com_contexto = HallucinationGuardrail(
|
||||||
context="AI helps with various tasks including analysis and generation.",
|
context="IA ajuda em várias tarefas, incluindo análise e geração.",
|
||||||
llm=LLM(model="gpt-4o-mini")
|
llm=LLM(model="gpt-4o-mini")
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
@@ -43,11 +43,11 @@ context_guardrail = HallucinationGuardrail(
|
|||||||
from crewai import Task
|
from crewai import Task
|
||||||
|
|
||||||
# Crie sua tarefa com a proteção
|
# Crie sua tarefa com a proteção
|
||||||
task = Task(
|
minha_tarefa = Task(
|
||||||
description="Write a summary about AI capabilities",
|
description="Escreva um resumo sobre as capacidades da IA",
|
||||||
expected_output="A factual summary based on the provided context",
|
expected_output="Um resumo factual baseado no contexto fornecido",
|
||||||
agent=my_agent,
|
agent=meu_agente,
|
||||||
guardrail=guardrail # Adiciona a proteção para validar a saída
|
guardrail=protecao # Adiciona a proteção para validar a saída
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -59,8 +59,8 @@ Para validação mais rigorosa, é possível definir um limiar de fidelidade per
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
# Proteção rigorosa exigindo alta pontuação de fidelidade
|
# Proteção rigorosa exigindo alta pontuação de fidelidade
|
||||||
strict_guardrail = HallucinationGuardrail(
|
protecao_rigorosa = HallucinationGuardrail(
|
||||||
context="Quantum computing uses qubits that exist in superposition states.",
|
context="Computação quântica utiliza qubits que existem em estados de superposição.",
|
||||||
llm=LLM(model="gpt-4o-mini"),
|
llm=LLM(model="gpt-4o-mini"),
|
||||||
threshold=8.0 # Requer pontuação >= 8 para validar
|
threshold=8.0 # Requer pontuação >= 8 para validar
|
||||||
)
|
)
|
||||||
@@ -72,10 +72,10 @@ Se sua tarefa utiliza ferramentas, você pode incluir as respostas das ferrament
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
# Proteção com contexto de resposta da ferramenta
|
# Proteção com contexto de resposta da ferramenta
|
||||||
weather_guardrail = HallucinationGuardrail(
|
protecao_clima = HallucinationGuardrail(
|
||||||
context="Current weather information for the requested location",
|
context="Informações meteorológicas atuais para o local solicitado",
|
||||||
llm=LLM(model="gpt-4o-mini"),
|
llm=LLM(model="gpt-4o-mini"),
|
||||||
tool_response="Weather API returned: Temperature 22°C, Humidity 65%, Clear skies"
|
tool_response="API do Clima retornou: Temperatura 22°C, Umidade 65%, Céu limpo"
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -123,15 +123,15 @@ Quando uma proteção é adicionada à tarefa, ela valida automaticamente a saí
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
# Fluxo de validação de saída da tarefa
|
# Fluxo de validação de saída da tarefa
|
||||||
task_output = agent.execute_task(task)
|
task_output = meu_agente.execute_task(minha_tarefa)
|
||||||
validation_result = guardrail(task_output)
|
resultado_validacao = protecao(task_output)
|
||||||
|
|
||||||
if validation_result.valid:
|
if resultado_validacao.valid:
|
||||||
# Tarefa concluída com sucesso
|
# Tarefa concluída com sucesso
|
||||||
return task_output
|
return task_output
|
||||||
else:
|
else:
|
||||||
# Tarefa falha com feedback de validação
|
# Tarefa falha com feedback de validação
|
||||||
raise ValidationError(validation_result.feedback)
|
raise ValidationError(resultado_validacao.feedback)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Rastreamento de Eventos
|
### Rastreamento de Eventos
|
||||||
@@ -151,10 +151,10 @@ A proteção se integra ao sistema de eventos do CrewAI para fornecer observabil
|
|||||||
Inclua todas as informações factuais relevantes nas quais a IA deve basear sua saída:
|
Inclua todas as informações factuais relevantes nas quais a IA deve basear sua saída:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
context = """
|
contexto = """
|
||||||
Company XYZ was founded in 2020 and specializes in renewable energy solutions.
|
Empresa XYZ foi fundada em 2020 e é especializada em soluções de energia renovável.
|
||||||
They have 150 employees and generated $50M revenue in 2023.
|
Possui 150 funcionários e faturou R$ 50 milhões em 2023.
|
||||||
Their main products include solar panels and wind turbines.
|
Seus principais produtos incluem painéis solares e turbinas eólicas.
|
||||||
"""
|
"""
|
||||||
```
|
```
|
||||||
</Step>
|
</Step>
|
||||||
@@ -164,10 +164,10 @@ A proteção se integra ao sistema de eventos do CrewAI para fornecer observabil
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
# Bom: Contexto focado
|
# Bom: Contexto focado
|
||||||
context = "The current weather in New York is 18°C with light rain."
|
contexto = "O clima atual em Nova York é 18°C com chuva leve."
|
||||||
|
|
||||||
# Evite: Informações irrelevantes
|
# Evite: Informações irrelevantes
|
||||||
context = "The weather is 18°C. The city has 8 million people. Traffic is heavy."
|
contexto = "The weather is 18°C. The city has 8 million people. Traffic is heavy."
|
||||||
```
|
```
|
||||||
</Step>
|
</Step>
|
||||||
|
|
||||||
|
|||||||
@@ -84,31 +84,31 @@ from crewai import Agent, Task, Crew
|
|||||||
from crewai_tools import CrewaiEnterpriseTools
|
from crewai_tools import CrewaiEnterpriseTools
|
||||||
|
|
||||||
# Obtenha ferramentas enterprise (a ferramenta Gmail será incluída)
|
# Obtenha ferramentas enterprise (a ferramenta Gmail será incluída)
|
||||||
enterprise_tools = CrewaiEnterpriseTools(
|
ferramentas_enterprise = CrewaiEnterpriseTools(
|
||||||
enterprise_token="your_enterprise_token"
|
enterprise_token="seu_token_enterprise"
|
||||||
)
|
)
|
||||||
# imprima as ferramentas
|
# imprima as ferramentas
|
||||||
print(enterprise_tools)
|
printf(ferramentas_enterprise)
|
||||||
|
|
||||||
# Crie um agente com capacidades do Gmail
|
# Crie um agente com capacidades do Gmail
|
||||||
email_agent = Agent(
|
agente_email = Agent(
|
||||||
role="Email Manager",
|
role="Gerente de E-mails",
|
||||||
goal="Manage and organize email communications",
|
goal="Gerenciar e organizar comunicações por e-mail",
|
||||||
backstory="An AI assistant specialized in email management and communication.",
|
backstory="Um assistente de IA especializado em gestão de e-mails e comunicação.",
|
||||||
tools=enterprise_tools
|
tools=ferramentas_enterprise
|
||||||
)
|
)
|
||||||
|
|
||||||
# Tarefa para enviar um e-mail
|
# Tarefa para enviar um e-mail
|
||||||
email_task = Task(
|
tarefa_email = Task(
|
||||||
description="Draft and send a follow-up email to john@example.com about the project update",
|
description="Redigir e enviar um e-mail de acompanhamento para john@example.com sobre a atualização do projeto",
|
||||||
agent=email_agent,
|
agent=agente_email,
|
||||||
expected_output="Confirmation that email was sent successfully"
|
expected_output="Confirmação de que o e-mail foi enviado com sucesso"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Execute a tarefa
|
# Execute a tarefa
|
||||||
crew = Crew(
|
crew = Crew(
|
||||||
agents=[email_agent],
|
agents=[agente_email],
|
||||||
tasks=[email_task]
|
tasks=[tarefa_email]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Execute o crew
|
# Execute o crew
|
||||||
@@ -125,23 +125,23 @@ enterprise_tools = CrewaiEnterpriseTools(
|
|||||||
)
|
)
|
||||||
gmail_tool = enterprise_tools["gmail_find_email"]
|
gmail_tool = enterprise_tools["gmail_find_email"]
|
||||||
|
|
||||||
gmail_agent = Agent(
|
agente_gmail = Agent(
|
||||||
role="Gmail Manager",
|
role="Gerente do Gmail",
|
||||||
goal="Manage gmail communications and notifications",
|
goal="Gerenciar comunicações e notificações do gmail",
|
||||||
backstory="An AI assistant that helps coordinate gmail communications.",
|
backstory="Um assistente de IA que ajuda a coordenar comunicações no gmail.",
|
||||||
tools=[gmail_tool]
|
tools=[gmail_tool]
|
||||||
)
|
)
|
||||||
|
|
||||||
notification_task = Task(
|
tarefa_notificacao = Task(
|
||||||
description="Find the email from john@example.com",
|
description="Encontrar o e-mail de john@example.com",
|
||||||
agent=gmail_agent,
|
agent=agente_gmail,
|
||||||
expected_output="Email found from john@example.com"
|
expected_output="E-mail encontrado de john@example.com"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Execute a tarefa
|
# Execute a tarefa
|
||||||
crew = Crew(
|
crew = Crew(
|
||||||
agents=[slack_agent],
|
agents=[agente_gmail],
|
||||||
tasks=[notification_task]
|
tasks=[tarefa_notificacao]
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ Antes de usar o Repositório de Ferramentas, certifique-se de que você possui:
|
|||||||
Para instalar uma ferramenta:
|
Para instalar uma ferramenta:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
crewai tool install <tool-name>
|
crewai tool install <nome-da-ferramenta>
|
||||||
```
|
```
|
||||||
|
|
||||||
Isso instala a ferramenta e a adiciona ao `pyproject.toml`.
|
Isso instala a ferramenta e a adiciona ao `pyproject.toml`.
|
||||||
@@ -40,7 +40,7 @@ Isso instala a ferramenta e a adiciona ao `pyproject.toml`.
|
|||||||
Para criar um novo projeto de ferramenta:
|
Para criar um novo projeto de ferramenta:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
crewai tool create <tool-name>
|
crewai tool create <nome-da-ferramenta>
|
||||||
```
|
```
|
||||||
|
|
||||||
Isso gera um projeto de ferramenta estruturado localmente.
|
Isso gera um projeto de ferramenta estruturado localmente.
|
||||||
@@ -76,7 +76,7 @@ Para atualizar uma ferramenta publicada:
|
|||||||
3. Faça o commit das alterações e publique
|
3. Faça o commit das alterações e publique
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git commit -m "Update version to 0.1.1"
|
git commit -m "Atualizar versão para 0.1.1"
|
||||||
crewai tool publish
|
crewai tool publish
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -12,16 +12,17 @@ O Enterprise Event Streaming permite que você receba atualizações em tempo re
|
|||||||
|
|
||||||
Ao utilizar a API Kickoff, inclua um objeto `webhooks` em sua requisição, por exemplo:
|
Ao utilizar a API Kickoff, inclua um objeto `webhooks` em sua requisição, por exemplo:
|
||||||
|
|
||||||
|
# Exemplo de uso da API Kickoff com webhooks
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"inputs": {"foo": "bar"},
|
"inputs": {"foo": "bar"},
|
||||||
"webhooks": {
|
"webhooks": {
|
||||||
"events": ["crew_kickoff_started", "llm_call_started"],
|
"events": ["crew_kickoff_started", "llm_call_started"],
|
||||||
"url": "https://your.endpoint/webhook",
|
"url": "https://seu.endpoint/webhook",
|
||||||
"realtime": false,
|
"realtime": false,
|
||||||
"authentication": {
|
"authentication": {
|
||||||
"strategy": "bearer",
|
"strategy": "bearer",
|
||||||
"token": "my-secret-token"
|
"token": "meu-token-secreto"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -33,19 +34,20 @@ Se `realtime` estiver definido como `true`, cada evento será entregue individua
|
|||||||
|
|
||||||
Cada webhook envia uma lista de eventos:
|
Cada webhook envia uma lista de eventos:
|
||||||
|
|
||||||
|
# Exemplo de evento enviado pelo webhook
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"events": [
|
"events": [
|
||||||
{
|
{
|
||||||
"id": "event-id",
|
"id": "id-do-evento",
|
||||||
"execution_id": "crew-run-id",
|
"execution_id": "id-da-execucao-do-crew",
|
||||||
"timestamp": "2025-02-16T10:58:44.965Z",
|
"timestamp": "2025-02-16T10:58:44.965Z",
|
||||||
"type": "llm_call_started",
|
"type": "llm_call_started",
|
||||||
"data": {
|
"data": {
|
||||||
"model": "gpt-4",
|
"model": "gpt-4",
|
||||||
"messages": [
|
"messages": [
|
||||||
{"role": "system", "content": "You are an assistant."},
|
{"role": "system", "content": "Você é um assistente."},
|
||||||
{"role": "user", "content": "Summarize this article."}
|
{"role": "user", "content": "Resuma este artigo."}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,17 +16,17 @@ from crewai import CrewBase
|
|||||||
from crewai.project import before_kickoff
|
from crewai.project import before_kickoff
|
||||||
|
|
||||||
@CrewBase
|
@CrewBase
|
||||||
class MyCrew:
|
class MinhaEquipe:
|
||||||
@before_kickoff
|
@before_kickoff
|
||||||
def prepare_data(self, inputs):
|
def preparar_dados(self, entradas):
|
||||||
# Preprocess or modify inputs
|
# Pré-processa ou modifica as entradas
|
||||||
inputs['processed'] = True
|
entradas['processado'] = True
|
||||||
return inputs
|
return entradas
|
||||||
|
|
||||||
#...
|
#...
|
||||||
```
|
```
|
||||||
|
|
||||||
Neste exemplo, a função prepare_data modifica as entradas adicionando um novo par chave-valor indicando que as entradas foram processadas.
|
Neste exemplo, a função preparar_dados modifica as entradas adicionando um novo par chave-valor indicando que as entradas foram processadas.
|
||||||
|
|
||||||
## Hook Depois do Kickoff
|
## Hook Depois do Kickoff
|
||||||
|
|
||||||
@@ -39,17 +39,17 @@ from crewai import CrewBase
|
|||||||
from crewai.project import after_kickoff
|
from crewai.project import after_kickoff
|
||||||
|
|
||||||
@CrewBase
|
@CrewBase
|
||||||
class MyCrew:
|
class MinhaEquipe:
|
||||||
@after_kickoff
|
@after_kickoff
|
||||||
def log_results(self, result):
|
def registrar_resultados(self, resultado):
|
||||||
# Log or modify the results
|
# Registra ou modifica os resultados
|
||||||
print("Crew execution completed with result:", result)
|
print("Execução da equipe concluída com resultado:", resultado)
|
||||||
return result
|
return resultado
|
||||||
|
|
||||||
# ...
|
# ...
|
||||||
```
|
```
|
||||||
|
|
||||||
Na função `log_results`, os resultados da execução da crew são simplesmente impressos. Você pode estender isso para realizar operações mais complexas, como enviar notificações ou integrar com outros serviços.
|
Na função `registrar_resultados`, os resultados da execução da crew são simplesmente impressos. Você pode estender isso para realizar operações mais complexas, como enviar notificações ou integrar com outros serviços.
|
||||||
|
|
||||||
## Utilizando Ambos os Hooks
|
## Utilizando Ambos os Hooks
|
||||||
|
|
||||||
|
|||||||
@@ -77,9 +77,9 @@ search_tool = SerperDevTool()
|
|||||||
|
|
||||||
# Inicialize o agente com opções avançadas
|
# Inicialize o agente com opções avançadas
|
||||||
agent = Agent(
|
agent = Agent(
|
||||||
role='Research Analyst',
|
role='Analista de Pesquisa',
|
||||||
goal='Provide up-to-date market analysis',
|
goal='Fornecer análises de mercado atualizadas',
|
||||||
backstory='An expert analyst with a keen eye for market trends.',
|
backstory='Um analista especialista com olhar atento para tendências de mercado.',
|
||||||
tools=[search_tool],
|
tools=[search_tool],
|
||||||
memory=True, # Ativa memória
|
memory=True, # Ativa memória
|
||||||
verbose=True,
|
verbose=True,
|
||||||
@@ -98,14 +98,9 @@ eficiência dentro do ecossistema CrewAI. Se necessário, a delegação pode ser
|
|||||||
|
|
||||||
```python Code
|
```python Code
|
||||||
agent = Agent(
|
agent = Agent(
|
||||||
role='Content Writer',
|
role='Redator de Conteúdo',
|
||||||
goal='Write engaging content on market trends',
|
goal='Escrever conteúdo envolvente sobre tendências de mercado',
|
||||||
backstory='A seasoned writer with expertise in market analysis.',
|
backstory='Um redator experiente com expertise em análise de mercado.',
|
||||||
allow_delegation=True # Habilitando delegação
|
allow_delegation=True # Habilitando delegação
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Conclusão
|
|
||||||
|
|
||||||
Personalizar agentes no CrewAI definindo seus papéis, objetivos, histórias e ferramentas, juntamente com opções avançadas como personalização de modelo de linguagem, memória, ajustes de performance e preferências de delegação,
|
|
||||||
proporciona uma equipe de IA sofisticada e preparada para enfrentar desafios complexos.
|
|
||||||
@@ -45,17 +45,17 @@ from crewai import Crew, Agent, Task
|
|||||||
|
|
||||||
# Create an agent with code execution enabled
|
# Create an agent with code execution enabled
|
||||||
coding_agent = Agent(
|
coding_agent = Agent(
|
||||||
role="Python Data Analyst",
|
role="Analista de Dados Python",
|
||||||
goal="Analyze data and provide insights using Python",
|
goal="Analisar dados e fornecer insights usando Python",
|
||||||
backstory="You are an experienced data analyst with strong Python skills.",
|
backstory="Você é um analista de dados experiente com fortes habilidades em Python.",
|
||||||
allow_code_execution=True
|
allow_code_execution=True
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create a task that requires code execution
|
# Create a task that requires code execution
|
||||||
data_analysis_task = Task(
|
data_analysis_task = Task(
|
||||||
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
|
description="Analise o conjunto de dados fornecido e calcule a idade média dos participantes. Idades: {ages}",
|
||||||
agent=coding_agent,
|
agent=coding_agent,
|
||||||
expected_output="The average age of the participants."
|
expected_output="A idade média dos participantes."
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create a crew and add the task
|
# Create a crew and add the task
|
||||||
@@ -83,23 +83,23 @@ from crewai import Crew, Agent, Task
|
|||||||
|
|
||||||
# Create an agent with code execution enabled
|
# Create an agent with code execution enabled
|
||||||
coding_agent = Agent(
|
coding_agent = Agent(
|
||||||
role="Python Data Analyst",
|
role="Analista de Dados Python",
|
||||||
goal="Analyze data and provide insights using Python",
|
goal="Analisar dados e fornecer insights usando Python",
|
||||||
backstory="You are an experienced data analyst with strong Python skills.",
|
backstory="Você é um analista de dados experiente com fortes habilidades em Python.",
|
||||||
allow_code_execution=True
|
allow_code_execution=True
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create tasks that require code execution
|
# Create tasks that require code execution
|
||||||
task_1 = Task(
|
task_1 = Task(
|
||||||
description="Analyze the first dataset and calculate the average age of participants. Ages: {ages}",
|
description="Analise o primeiro conjunto de dados e calcule a idade média dos participantes. Idades: {ages}",
|
||||||
agent=coding_agent,
|
agent=coding_agent,
|
||||||
expected_output="The average age of the participants."
|
expected_output="A idade média dos participantes."
|
||||||
)
|
)
|
||||||
|
|
||||||
task_2 = Task(
|
task_2 = Task(
|
||||||
description="Analyze the second dataset and calculate the average age of participants. Ages: {ages}",
|
description="Analise o segundo conjunto de dados e calcule a idade média dos participantes. Idades: {ages}",
|
||||||
agent=coding_agent,
|
agent=coding_agent,
|
||||||
expected_output="The average age of the participants."
|
expected_output="A idade média dos participantes."
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create two crews and add tasks
|
# Create two crews and add tasks
|
||||||
|
|||||||
@@ -43,11 +43,11 @@ try:
|
|||||||
with MCPServerAdapter(server_params_list) as aggregated_tools:
|
with MCPServerAdapter(server_params_list) as aggregated_tools:
|
||||||
print(f"Available aggregated tools: {[tool.name for tool in aggregated_tools]}")
|
print(f"Available aggregated tools: {[tool.name for tool in aggregated_tools]}")
|
||||||
|
|
||||||
multi_server_agent = Agent(
|
agente_multiservidor = Agent(
|
||||||
role="Versatile Assistant",
|
role="Assistente Versátil",
|
||||||
goal="Utilize tools from local Stdio, remote SSE, and remote HTTP MCP servers.",
|
goal="Utilizar ferramentas de servidores MCP locais Stdio, remotos SSE e remotos HTTP.",
|
||||||
backstory="An AI agent capable of leveraging a diverse set of tools from multiple sources.",
|
backstory="Um agente de IA capaz de aproveitar um conjunto diversificado de ferramentas de múltiplas fontes.",
|
||||||
tools=aggregated_tools, # All tools are available here
|
tools=aggregated_tools, # Todas as ferramentas estão disponíveis aqui
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -73,10 +73,10 @@ server_params = {
|
|||||||
with MCPServerAdapter(server_params) as mcp_tools:
|
with MCPServerAdapter(server_params) as mcp_tools:
|
||||||
print(f"Available tools: {[tool.name for tool in mcp_tools]}")
|
print(f"Available tools: {[tool.name for tool in mcp_tools]}")
|
||||||
|
|
||||||
my_agent = Agent(
|
meu_agente = Agent(
|
||||||
role="MCP Tool User",
|
role="Usuário de Ferramentas MCP",
|
||||||
goal="Utilize tools from an MCP server.",
|
goal="Utilizar ferramentas de um servidor MCP.",
|
||||||
backstory="I can connect to MCP servers and use their tools.",
|
backstory="Posso conectar a servidores MCP e usar suas ferramentas.",
|
||||||
tools=mcp_tools, # Passe as ferramentas carregadas para o seu agente
|
tools=mcp_tools, # Passe as ferramentas carregadas para o seu agente
|
||||||
reasoning=True,
|
reasoning=True,
|
||||||
verbose=True
|
verbose=True
|
||||||
@@ -91,10 +91,10 @@ Este padrão geral mostra como integrar ferramentas. Para exemplos específicos
|
|||||||
with MCPServerAdapter(server_params) as mcp_tools:
|
with MCPServerAdapter(server_params) as mcp_tools:
|
||||||
print(f"Available tools: {[tool.name for tool in mcp_tools]}")
|
print(f"Available tools: {[tool.name for tool in mcp_tools]}")
|
||||||
|
|
||||||
my_agent = Agent(
|
meu_agente = Agent(
|
||||||
role="MCP Tool User",
|
role="Usuário de Ferramentas MCP",
|
||||||
goal="Utilize tools from an MCP server.",
|
goal="Utilizar ferramentas de um servidor MCP.",
|
||||||
backstory="I can connect to MCP servers and use their tools.",
|
backstory="Posso conectar a servidores MCP e usar suas ferramentas.",
|
||||||
tools=mcp_tools["tool_name"], # Passe as ferramentas filtradas para o seu agente
|
tools=mcp_tools["tool_name"], # Passe as ferramentas filtradas para o seu agente
|
||||||
reasoning=True,
|
reasoning=True,
|
||||||
verbose=True
|
verbose=True
|
||||||
|
|||||||
@@ -37,24 +37,24 @@ try:
|
|||||||
print(f"Available tools from SSE MCP server: {[tool.name for tool in tools]}")
|
print(f"Available tools from SSE MCP server: {[tool.name for tool in tools]}")
|
||||||
|
|
||||||
# Example: Using a tool from the SSE MCP server
|
# Example: Using a tool from the SSE MCP server
|
||||||
sse_agent = Agent(
|
agente_sse = Agent(
|
||||||
role="Remote Service User",
|
role="Usuário de Serviço Remoto",
|
||||||
goal="Utilize a tool provided by a remote SSE MCP server.",
|
goal="Utilizar uma ferramenta fornecida por um servidor MCP remoto via SSE.",
|
||||||
backstory="An AI agent that connects to external services via SSE.",
|
backstory="Um agente de IA que conecta a serviços externos via SSE.",
|
||||||
tools=tools,
|
tools=tools,
|
||||||
reasoning=True,
|
reasoning=True,
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
sse_task = Task(
|
sse_task = Task(
|
||||||
description="Fetch real-time stock updates for 'AAPL' using an SSE tool.",
|
description="Buscar atualizações em tempo real das ações 'AAPL' usando uma ferramenta SSE.",
|
||||||
expected_output="The latest stock price for AAPL.",
|
expected_output="O preço mais recente da ação AAPL.",
|
||||||
agent=sse_agent,
|
agent=agente_sse,
|
||||||
markdown=True
|
markdown=True
|
||||||
)
|
)
|
||||||
|
|
||||||
sse_crew = Crew(
|
sse_crew = Crew(
|
||||||
agents=[sse_agent],
|
agents=[agente_sse],
|
||||||
tasks=[sse_task],
|
tasks=[sse_task],
|
||||||
verbose=True,
|
verbose=True,
|
||||||
process=Process.sequential
|
process=Process.sequential
|
||||||
@@ -101,16 +101,16 @@ try:
|
|||||||
print(f"Available tools (manual SSE): {[tool.name for tool in tools]}")
|
print(f"Available tools (manual SSE): {[tool.name for tool in tools]}")
|
||||||
|
|
||||||
manual_sse_agent = Agent(
|
manual_sse_agent = Agent(
|
||||||
role="Remote Data Analyst",
|
role="Analista Remoto de Dados",
|
||||||
goal="Analyze data fetched from a remote SSE MCP server using manual connection management.",
|
goal="Analisar dados obtidos de um servidor MCP remoto SSE usando gerenciamento manual de conexão.",
|
||||||
backstory="An AI skilled in handling SSE connections explicitly.",
|
backstory="Um agente de IA especializado em gerenciar conexões SSE explicitamente.",
|
||||||
tools=tools,
|
tools=tools,
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
analysis_task = Task(
|
analysis_task = Task(
|
||||||
description="Fetch and analyze the latest user activity trends from the SSE server.",
|
description="Buscar e analisar as tendências mais recentes de atividade de usuários do servidor SSE.",
|
||||||
expected_output="A summary report of user activity trends.",
|
expected_output="Um relatório resumido das tendências de atividade dos usuários.",
|
||||||
agent=manual_sse_agent
|
agent=manual_sse_agent
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -38,24 +38,24 @@ with MCPServerAdapter(server_params) as tools:
|
|||||||
print(f"Available tools from Stdio MCP server: {[tool.name for tool in tools]}")
|
print(f"Available tools from Stdio MCP server: {[tool.name for tool in tools]}")
|
||||||
|
|
||||||
# Exemplo: Usando as ferramentas do servidor MCP Stdio em um Agente CrewAI
|
# Exemplo: Usando as ferramentas do servidor MCP Stdio em um Agente CrewAI
|
||||||
research_agent = Agent(
|
pesquisador_local = Agent(
|
||||||
role="Local Data Processor",
|
role="Processador Local de Dados",
|
||||||
goal="Process data using a local Stdio-based tool.",
|
goal="Processar dados usando uma ferramenta local baseada em Stdio.",
|
||||||
backstory="An AI that leverages local scripts via MCP for specialized tasks.",
|
backstory="Uma IA que utiliza scripts locais via MCP para tarefas especializadas.",
|
||||||
tools=tools,
|
tools=tools,
|
||||||
reasoning=True,
|
reasoning=True,
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
processing_task = Task(
|
processing_task = Task(
|
||||||
description="Process the input data file 'data.txt' and summarize its contents.",
|
description="Processar o arquivo de dados de entrada 'data.txt' e resumir seu conteúdo.",
|
||||||
expected_output="A summary of the processed data.",
|
expected_output="Um resumo dos dados processados.",
|
||||||
agent=research_agent,
|
agent=pesquisador_local,
|
||||||
markdown=True
|
markdown=True
|
||||||
)
|
)
|
||||||
|
|
||||||
data_crew = Crew(
|
data_crew = Crew(
|
||||||
agents=[research_agent],
|
agents=[pesquisador_local],
|
||||||
tasks=[processing_task],
|
tasks=[processing_task],
|
||||||
verbose=True,
|
verbose=True,
|
||||||
process=Process.sequential
|
process=Process.sequential
|
||||||
@@ -95,16 +95,16 @@ try:
|
|||||||
|
|
||||||
# Exemplo: Usando as ferramentas com sua configuração de Agent, Task, Crew
|
# Exemplo: Usando as ferramentas com sua configuração de Agent, Task, Crew
|
||||||
manual_agent = Agent(
|
manual_agent = Agent(
|
||||||
role="Local Task Executor",
|
role="Executor Local de Tarefas",
|
||||||
goal="Execute a specific local task using a manually managed Stdio tool.",
|
goal="Executar uma tarefa local específica usando uma ferramenta Stdio gerenciada manualmente.",
|
||||||
backstory="An AI proficient in controlling local processes via MCP.",
|
backstory="Uma IA proficiente em controlar processos locais via MCP.",
|
||||||
tools=tools,
|
tools=tools,
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
manual_task = Task(
|
manual_task = Task(
|
||||||
description="Execute the 'perform_analysis' command via the Stdio tool.",
|
description="Executar o comando 'perform_analysis' via ferramenta Stdio.",
|
||||||
expected_output="Results of the analysis.",
|
expected_output="Resultados da análise.",
|
||||||
agent=manual_agent
|
agent=manual_agent
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -35,22 +35,22 @@ try:
|
|||||||
with MCPServerAdapter(server_params) as tools:
|
with MCPServerAdapter(server_params) as tools:
|
||||||
print(f"Available tools from Streamable HTTP MCP server: {[tool.name for tool in tools]}")
|
print(f"Available tools from Streamable HTTP MCP server: {[tool.name for tool in tools]}")
|
||||||
|
|
||||||
http_agent = Agent(
|
agente_http = Agent(
|
||||||
role="HTTP Service Integrator",
|
role="Integrador de Serviços HTTP",
|
||||||
goal="Utilize tools from a remote MCP server via Streamable HTTP.",
|
goal="Utilizar ferramentas de um servidor MCP remoto via Streamable HTTP.",
|
||||||
backstory="An AI agent adept at interacting with complex web services.",
|
backstory="Um agente de IA especializado em interagir com serviços web complexos.",
|
||||||
tools=tools,
|
tools=tools,
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
http_task = Task(
|
http_task = Task(
|
||||||
description="Perform a complex data query using a tool from the Streamable HTTP server.",
|
description="Realizar uma consulta de dados complexa usando uma ferramenta do servidor Streamable HTTP.",
|
||||||
expected_output="The result of the complex data query.",
|
expected_output="O resultado da consulta de dados complexa.",
|
||||||
agent=http_agent,
|
agent=agente_http,
|
||||||
)
|
)
|
||||||
|
|
||||||
http_crew = Crew(
|
http_crew = Crew(
|
||||||
agents=[http_agent],
|
agents=[agente_http],
|
||||||
tasks=[http_task],
|
tasks=[http_task],
|
||||||
verbose=True,
|
verbose=True,
|
||||||
process=Process.sequential
|
process=Process.sequential
|
||||||
@@ -91,16 +91,16 @@ try:
|
|||||||
print(f"Available tools (manual Streamable HTTP): {[tool.name for tool in tools]}")
|
print(f"Available tools (manual Streamable HTTP): {[tool.name for tool in tools]}")
|
||||||
|
|
||||||
manual_http_agent = Agent(
|
manual_http_agent = Agent(
|
||||||
role="Advanced Web Service User",
|
role="Usuário Avançado de Serviços Web",
|
||||||
goal="Interact with an MCP server using manually managed Streamable HTTP connections.",
|
goal="Interagir com um servidor MCP usando conexões HTTP Streamable gerenciadas manualmente.",
|
||||||
backstory="An AI specialist in fine-tuning HTTP-based service integrations.",
|
backstory="Um especialista em IA em ajustar integrações baseadas em HTTP.",
|
||||||
tools=tools,
|
tools=tools,
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|
||||||
data_processing_task = Task(
|
data_processing_task = Task(
|
||||||
description="Submit data for processing and retrieve results via Streamable HTTP.",
|
description="Enviar dados para processamento e recuperar resultados via Streamable HTTP.",
|
||||||
expected_output="Processed data or confirmation.",
|
expected_output="Dados processados ou confirmação.",
|
||||||
agent=manual_http_agent
|
agent=manual_http_agent
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -78,47 +78,40 @@ CrewAIInstrumentor().instrument(skip_dep_check=True, tracer_provider=tracer_prov
|
|||||||
search_tool = SerperDevTool()
|
search_tool = SerperDevTool()
|
||||||
|
|
||||||
# Defina seus agentes com papéis e objetivos
|
# Defina seus agentes com papéis e objetivos
|
||||||
researcher = Agent(
|
pesquisador = Agent(
|
||||||
role="Senior Research Analyst",
|
role="Analista Sênior de Pesquisa",
|
||||||
goal="Uncover cutting-edge developments in AI and data science",
|
goal="Descobrir os avanços mais recentes em IA e ciência de dados",
|
||||||
backstory="""You work at a leading tech think tank.
|
backstory="""
|
||||||
Your expertise lies in identifying emerging trends.
|
Você trabalha em um importante think tank de tecnologia. Sua especialidade é identificar tendências emergentes. Você tem habilidade para dissecar dados complexos e apresentar insights acionáveis.
|
||||||
You have a knack for dissecting complex data and presenting actionable insights.""",
|
""",
|
||||||
verbose=True,
|
verbose=True,
|
||||||
allow_delegation=False,
|
allow_delegation=False,
|
||||||
# You can pass an optional llm attribute specifying what model you wanna use.
|
|
||||||
# llm=ChatOpenAI(model_name="gpt-3.5", temperature=0.7),
|
|
||||||
tools=[search_tool],
|
tools=[search_tool],
|
||||||
)
|
)
|
||||||
writer = Agent(
|
writer = Agent(
|
||||||
role="Tech Content Strategist",
|
role="Estrategista de Conteúdo Técnico",
|
||||||
goal="Craft compelling content on tech advancements",
|
goal="Criar conteúdo envolvente sobre avanços tecnológicos",
|
||||||
backstory="""You are a renowned Content Strategist, known for your insightful and engaging articles.
|
backstory="Você é um Estrategista de Conteúdo renomado, conhecido por seus artigos perspicazes e envolventes. Você transforma conceitos complexos em narrativas atraentes.",
|
||||||
You transform complex concepts into compelling narratives.""",
|
|
||||||
verbose=True,
|
verbose=True,
|
||||||
allow_delegation=True,
|
allow_delegation=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Crie tarefas para seus agentes
|
# Crie tarefas para seus agentes
|
||||||
task1 = Task(
|
task1 = Task(
|
||||||
description="""Conduct a comprehensive analysis of the latest advancements in AI in 2024.
|
description="Realize uma análise abrangente dos avanços mais recentes em IA em 2024. Identifique tendências-chave, tecnologias inovadoras e impactos potenciais na indústria.",
|
||||||
Identify key trends, breakthrough technologies, and potential industry impacts.""",
|
expected_output="Relatório analítico completo em tópicos",
|
||||||
expected_output="Full analysis report in bullet points",
|
agent=pesquisador,
|
||||||
agent=researcher,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
task2 = Task(
|
task2 = Task(
|
||||||
description="""Using the insights provided, develop an engaging blog
|
description="Utilizando os insights fornecidos, desenvolva um blog envolvente destacando os avanços mais significativos em IA. O post deve ser informativo e acessível, voltado para um público técnico. Dê um tom interessante, evite palavras complexas para não soar como IA.",
|
||||||
post that highlights the most significant AI advancements.
|
expected_output="Post de blog completo com pelo menos 4 parágrafos",
|
||||||
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,
|
agent=writer,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Instancie seu crew com um processo sequencial
|
# Instancie seu crew com um processo sequencial
|
||||||
crew = Crew(
|
crew = Crew(
|
||||||
agents=[researcher, writer], tasks=[task1, task2], verbose=1, process=Process.sequential
|
agents=[pesquisador, writer], tasks=[task1, task2], verbose=1, process=Process.sequential
|
||||||
)
|
)
|
||||||
|
|
||||||
# Coloque seu crew para trabalhar!
|
# Coloque seu crew para trabalhar!
|
||||||
|
|||||||
@@ -76,20 +76,20 @@ from crewai_tools import (
|
|||||||
|
|
||||||
web_rag_tool = WebsiteSearchTool()
|
web_rag_tool = WebsiteSearchTool()
|
||||||
|
|
||||||
writer = Agent(
|
escritor = Agent(
|
||||||
role="Writer",
|
role="Escritor",
|
||||||
goal="Você torna a matemática envolvente e compreensível para crianças pequenas através de poesias",
|
goal="Você torna a matemática envolvente e compreensível para crianças pequenas através de poesias",
|
||||||
backstory="Você é especialista em escrever haicais mas não sabe nada de matemática.",
|
backstory="Você é especialista em escrever haicais mas não sabe nada de matemática.",
|
||||||
tools=[web_rag_tool],
|
tools=[web_rag_tool],
|
||||||
)
|
)
|
||||||
|
|
||||||
task = Task(description=("O que é {multiplicação}?"),
|
tarefa = Task(description=("O que é {multiplicação}?"),
|
||||||
expected_output=("Componha um haicai que inclua a resposta."),
|
expected_output=("Componha um haicai que inclua a resposta."),
|
||||||
agent=writer)
|
agent=escritor)
|
||||||
|
|
||||||
crew = Crew(
|
equipe = Crew(
|
||||||
agents=[writer],
|
agents=[escritor],
|
||||||
tasks=[task],
|
tasks=[tarefa],
|
||||||
share_crew=False
|
share_crew=False
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ Essa integração permite o registro de hiperparâmetros, o monitoramento de reg
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
from langtrace_python_sdk import langtrace
|
from langtrace_python_sdk import langtrace
|
||||||
langtrace.init(api_key='<LANGTRACE_API_KEY>')
|
langtrace.init(api_key='<SUA_CHAVE_LANGTRACE>')
|
||||||
|
|
||||||
# Agora importe os módulos do CrewAI
|
# Agora importe os módulos do CrewAI
|
||||||
from crewai import Agent, Task, Crew
|
from crewai import Agent, Task, Crew
|
||||||
|
|||||||
@@ -73,26 +73,24 @@ instrument_crewai(logger)
|
|||||||
### 4. Crie e execute sua aplicação CrewAI normalmente
|
### 4. Crie e execute sua aplicação CrewAI normalmente
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
pesquisador = Agent(
|
||||||
# Crie seu agente
|
role='Pesquisador Sênior',
|
||||||
researcher = Agent(
|
goal='Descobrir os avanços mais recentes em IA',
|
||||||
role='Senior Research Analyst',
|
backstory="Você é um pesquisador especialista em um think tank de tecnologia...",
|
||||||
goal='Uncover cutting-edge developments in AI',
|
|
||||||
backstory="You are an expert researcher at a tech think tank...",
|
|
||||||
verbose=True,
|
verbose=True,
|
||||||
llm=llm
|
llm=llm
|
||||||
)
|
)
|
||||||
|
|
||||||
# Defina a tarefa
|
# Defina a tarefa
|
||||||
research_task = Task(
|
research_task = Task(
|
||||||
description="Research the latest AI advancements...",
|
description="Pesquise os avanços mais recentes em IA...",
|
||||||
expected_output="",
|
expected_output="",
|
||||||
agent=researcher
|
agent=pesquisador
|
||||||
)
|
)
|
||||||
|
|
||||||
# Configure e execute a crew
|
# Configure e execute a crew
|
||||||
crew = Crew(
|
crew = Crew(
|
||||||
agents=[researcher],
|
agents=[pesquisador],
|
||||||
tasks=[research_task],
|
tasks=[research_task],
|
||||||
verbose=True
|
verbose=True
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -70,22 +70,19 @@ O tracing fornece uma forma de registrar os inputs, outputs e metadados associad
|
|||||||
|
|
||||||
class TripAgents:
|
class TripAgents:
|
||||||
def city_selection_agent(self):
|
def city_selection_agent(self):
|
||||||
return Agent(
|
especialista_cidades = Agent(
|
||||||
role="City Selection Expert",
|
role="Especialista em Seleção de Cidades",
|
||||||
goal="Select the best city based on weather, season, and prices",
|
goal="Selecionar a melhor cidade com base no clima, estação e preços",
|
||||||
backstory="An expert in analyzing travel data to pick ideal destinations",
|
backstory="Especialista em analisar dados de viagem para escolher destinos ideais",
|
||||||
tools=[
|
tools=[search_tool],
|
||||||
search_tool,
|
|
||||||
],
|
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
def local_expert(self):
|
def local_expert(self):
|
||||||
return Agent(
|
especialista_local = Agent(
|
||||||
role="Local Expert at this city",
|
role="Especialista Local nesta cidade",
|
||||||
goal="Provide the BEST insights about the selected city",
|
goal="Fornecer as MELHORES informações sobre a cidade selecionada",
|
||||||
backstory="""A knowledgeable local guide with extensive information
|
backstory="Um guia local experiente com amplo conhecimento sobre a cidade, suas atrações e costumes",
|
||||||
about the city, it's attractions and customs""",
|
|
||||||
tools=[search_tool],
|
tools=[search_tool],
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
@@ -96,53 +93,36 @@ O tracing fornece uma forma de registrar os inputs, outputs e metadados associad
|
|||||||
return Task(
|
return Task(
|
||||||
description=dedent(
|
description=dedent(
|
||||||
f"""
|
f"""
|
||||||
Analyze and select the best city for the trip based
|
Analise e selecione a melhor cidade para a viagem com base em critérios específicos como padrões climáticos, eventos sazonais e custos de viagem. Esta tarefa envolve comparar várias cidades, considerando fatores como condições climáticas atuais, eventos culturais ou sazonais e despesas gerais de viagem.
|
||||||
on specific criteria such as weather patterns, seasonal
|
Sua resposta final deve ser um relatório detalhado sobre a cidade escolhida e tudo o que você descobriu sobre ela, incluindo custos reais de voo, previsão do tempo e atrações.
|
||||||
events, and travel costs. This task involves comparing
|
|
||||||
multiple cities, considering factors like current weather
|
|
||||||
conditions, upcoming cultural or seasonal events, and
|
|
||||||
overall travel expenses.
|
|
||||||
Your final answer must be a detailed
|
|
||||||
report on the chosen city, and everything you found out
|
|
||||||
about it, including the actual flight costs, weather
|
|
||||||
forecast and attractions.
|
|
||||||
|
|
||||||
Traveling from: {origin}
|
Saindo de: {origin}
|
||||||
City Options: {cities}
|
Opções de cidades: {cities}
|
||||||
Trip Date: {range}
|
Data da viagem: {range}
|
||||||
Traveler Interests: {interests}
|
Interesses do viajante: {interests}
|
||||||
"""
|
"""
|
||||||
),
|
),
|
||||||
agent=agent,
|
agent=agent,
|
||||||
expected_output="Detailed report on the chosen city including flight costs, weather forecast, and attractions",
|
expected_output="Relatório detalhado sobre a cidade escolhida incluindo custos de voo, previsão do tempo e atrações",
|
||||||
)
|
)
|
||||||
|
|
||||||
def gather_task(self, agent, origin, interests, range):
|
def gather_task(self, agent, origin, interests, range):
|
||||||
return Task(
|
return Task(
|
||||||
description=dedent(
|
description=dedent(
|
||||||
f"""
|
f"""
|
||||||
As a local expert on this city you must compile an
|
Como especialista local nesta cidade, você deve compilar um guia aprofundado para alguém que está viajando para lá e quer ter a MELHOR viagem possível!
|
||||||
in-depth guide for someone traveling there and wanting
|
Reúna informações sobre principais atrações, costumes locais, eventos especiais e recomendações de atividades diárias.
|
||||||
to have THE BEST trip ever!
|
Encontre os melhores lugares para ir, aqueles que só um local conhece.
|
||||||
Gather information about key attractions, local customs,
|
Este guia deve fornecer uma visão abrangente do que a cidade tem a oferecer, incluindo joias escondidas, pontos culturais, marcos imperdíveis, previsão do tempo e custos gerais.
|
||||||
special events, and daily activity recommendations.
|
A resposta final deve ser um guia completo da cidade, rico em insights culturais e dicas práticas, adaptado para aprimorar a experiência de viagem.
|
||||||
Find the best spots to go to, the kind of place only a
|
|
||||||
local would know.
|
|
||||||
This guide should provide a thorough overview of what
|
|
||||||
the city has to offer, including hidden gems, cultural
|
|
||||||
hotspots, must-visit landmarks, weather forecasts, and
|
|
||||||
high level costs.
|
|
||||||
The final answer must be a comprehensive city guide,
|
|
||||||
rich in cultural insights and practical tips,
|
|
||||||
tailored to enhance the travel experience.
|
|
||||||
|
|
||||||
Trip Date: {range}
|
Data da viagem: {range}
|
||||||
Traveling from: {origin}
|
Saindo de: {origin}
|
||||||
Traveler Interests: {interests}
|
Interesses do viajante: {interests}
|
||||||
"""
|
"""
|
||||||
),
|
),
|
||||||
agent=agent,
|
agent=agent,
|
||||||
expected_output="Comprehensive city guide including hidden gems, cultural hotspots, and practical travel tips",
|
expected_output="Guia completo da cidade incluindo joias escondidas, pontos culturais e dicas práticas",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -189,7 +169,7 @@ O tracing fornece uma forma de registrar os inputs, outputs e metadados associad
|
|||||||
trip_crew = TripCrew("California", "Tokyo", "Dec 12 - Dec 20", "sports")
|
trip_crew = TripCrew("California", "Tokyo", "Dec 12 - Dec 20", "sports")
|
||||||
result = trip_crew.run()
|
result = trip_crew.run()
|
||||||
|
|
||||||
print(result)
|
print("Resultado da equipe:", result)
|
||||||
```
|
```
|
||||||
Consulte a [Documentação de Tracing do MLflow](https://mlflow.org/docs/latest/llms/tracing/index.html) para mais configurações e casos de uso.
|
Consulte a [Documentação de Tracing do MLflow](https://mlflow.org/docs/latest/llms/tracing/index.html) para mais configurações e casos de uso.
|
||||||
</Step>
|
</Step>
|
||||||
|
|||||||
@@ -69,10 +69,10 @@ Essa configuração permite acompanhar hiperparâmetros e monitorar problemas de
|
|||||||
|
|
||||||
openlit.init(disable_metrics=True)
|
openlit.init(disable_metrics=True)
|
||||||
# Definir seus agentes
|
# Definir seus agentes
|
||||||
researcher = Agent(
|
pesquisador = Agent(
|
||||||
role="Researcher",
|
role="Pesquisador",
|
||||||
goal="Conduct thorough research and analysis on AI and AI agents",
|
goal="Realizar pesquisas e análises aprofundadas sobre IA e agentes de IA",
|
||||||
backstory="You're an expert researcher, specialized in technology, software engineering, AI, and startups. You work as a freelancer and are currently researching for a new client.",
|
backstory="Você é um pesquisador especialista em tecnologia, engenharia de software, IA e startups. Trabalha como freelancer e está atualmente pesquisando para um novo cliente.",
|
||||||
allow_delegation=False,
|
allow_delegation=False,
|
||||||
llm='command-r'
|
llm='command-r'
|
||||||
)
|
)
|
||||||
@@ -80,24 +80,24 @@ Essa configuração permite acompanhar hiperparâmetros e monitorar problemas de
|
|||||||
|
|
||||||
# Definir sua task
|
# Definir sua task
|
||||||
task = Task(
|
task = Task(
|
||||||
description="Generate a list of 5 interesting ideas for an article, then write one captivating paragraph for each idea that showcases the potential of a full article on this topic. Return the list of ideas with their paragraphs and your notes.",
|
description="Gere uma lista com 5 ideias interessantes para um artigo e escreva um parágrafo cativante para cada ideia, mostrando o potencial de um artigo completo sobre o tema. Retorne a lista de ideias com seus parágrafos e suas anotações.",
|
||||||
expected_output="5 bullet points, each with a paragraph and accompanying notes.",
|
expected_output="5 tópicos, cada um com um parágrafo e notas complementares.",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Definir o agente gerente
|
# Definir o agente gerente
|
||||||
manager = Agent(
|
gerente = Agent(
|
||||||
role="Project Manager",
|
role="Gerente de Projeto",
|
||||||
goal="Efficiently manage the crew and ensure high-quality task completion",
|
goal="Gerenciar eficientemente a equipe e garantir a conclusão de tarefas de alta qualidade",
|
||||||
backstory="You're an experienced project manager, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.",
|
backstory="Você é um gerente de projetos experiente, habilidoso em supervisionar projetos complexos e guiar equipes para o sucesso. Sua função é coordenar os esforços dos membros da equipe, garantindo que cada tarefa seja concluída no prazo e com o mais alto padrão.",
|
||||||
allow_delegation=True,
|
allow_delegation=True,
|
||||||
llm='command-r'
|
llm='command-r'
|
||||||
)
|
)
|
||||||
|
|
||||||
# Instanciar sua crew com um manager personalizado
|
# Instanciar sua crew com um manager personalizado
|
||||||
crew = Crew(
|
crew = Crew(
|
||||||
agents=[researcher],
|
agents=[pesquisador],
|
||||||
tasks=[task],
|
tasks=[task],
|
||||||
manager_agent=manager,
|
manager_agent=gerente,
|
||||||
process=Process.hierarchical,
|
process=Process.hierarchical,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -132,18 +132,18 @@ Essa configuração permite acompanhar hiperparâmetros e monitorar problemas de
|
|||||||
|
|
||||||
# Criar um agente com execução de código habilitada
|
# Criar um agente com execução de código habilitada
|
||||||
coding_agent = Agent(
|
coding_agent = Agent(
|
||||||
role="Python Data Analyst",
|
role="Analista de Dados Python",
|
||||||
goal="Analyze data and provide insights using Python",
|
goal="Analisar dados e fornecer insights usando Python",
|
||||||
backstory="You are an experienced data analyst with strong Python skills.",
|
backstory="Você é um analista de dados experiente com fortes habilidades em Python.",
|
||||||
allow_code_execution=True,
|
allow_code_execution=True,
|
||||||
llm="command-r"
|
llm="command-r"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Criar uma task que exige execução de código
|
# Criar uma task que exige execução de código
|
||||||
data_analysis_task = Task(
|
data_analysis_task = Task(
|
||||||
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
|
description="Analise o conjunto de dados fornecido e calcule a idade média dos participantes. Idades: {ages}",
|
||||||
agent=coding_agent,
|
agent=coding_agent,
|
||||||
expected_output="5 bullet points, each with a paragraph and accompanying notes.",
|
expected_output="5 tópicos, cada um com um parágrafo e notas complementares.",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Criar uma crew e adicionar a task
|
# Criar uma crew e adicionar a task
|
||||||
|
|||||||
@@ -58,43 +58,43 @@ Neste guia, utilizaremos o exemplo de início rápido da CrewAI.
|
|||||||
from crewai import Agent, Crew, Task, Process
|
from crewai import Agent, Crew, Task, Process
|
||||||
|
|
||||||
|
|
||||||
class YourCrewName:
|
class NomeDaEquipe:
|
||||||
def agent_one(self) -> Agent:
|
def agente_um(self) -> Agent:
|
||||||
return Agent(
|
return Agent(
|
||||||
role="Data Analyst",
|
role="Analista de Dados",
|
||||||
goal="Analyze data trends in the market",
|
goal="Analisar tendências de dados no mercado",
|
||||||
backstory="An experienced data analyst with a background in economics",
|
backstory="Analista de dados experiente com formação em economia",
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
def agent_two(self) -> Agent:
|
def agente_dois(self) -> Agent:
|
||||||
return Agent(
|
return Agent(
|
||||||
role="Market Researcher",
|
role="Pesquisador de Mercado",
|
||||||
goal="Gather information on market dynamics",
|
goal="Coletar informações sobre a dinâmica do mercado",
|
||||||
backstory="A diligent researcher with a keen eye for detail",
|
backstory="Pesquisador dedicado com olhar atento para detalhes",
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
def task_one(self) -> Task:
|
def tarefa_um(self) -> Task:
|
||||||
return Task(
|
return Task(
|
||||||
name="Collect Data Task",
|
name="Tarefa de Coleta de Dados",
|
||||||
description="Collect recent market data and identify trends.",
|
description="Coletar dados recentes do mercado e identificar tendências.",
|
||||||
expected_output="A report summarizing key trends in the market.",
|
expected_output="Um relatório resumindo as principais tendências do mercado.",
|
||||||
agent=self.agent_one(),
|
agent=self.agente_um(),
|
||||||
)
|
)
|
||||||
|
|
||||||
def task_two(self) -> Task:
|
def tarefa_dois(self) -> Task:
|
||||||
return Task(
|
return Task(
|
||||||
name="Market Research Task",
|
name="Tarefa de Pesquisa de Mercado",
|
||||||
description="Research factors affecting market dynamics.",
|
description="Pesquisar fatores que afetam a dinâmica do mercado.",
|
||||||
expected_output="An analysis of factors influencing the market.",
|
expected_output="Uma análise dos fatores que influenciam o mercado.",
|
||||||
agent=self.agent_two(),
|
agent=self.agente_dois(),
|
||||||
)
|
)
|
||||||
|
|
||||||
def crew(self) -> Crew:
|
def equipe(self) -> Crew:
|
||||||
return Crew(
|
return Crew(
|
||||||
agents=[self.agent_one(), self.agent_two()],
|
agents=[self.agente_um(), self.agente_dois()],
|
||||||
tasks=[self.task_one(), self.task_two()],
|
tasks=[self.tarefa_um(), self.tarefa_dois()],
|
||||||
process=Process.sequential,
|
process=Process.sequential,
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
@@ -108,7 +108,7 @@ Neste guia, utilizaremos o exemplo de início rápido da CrewAI.
|
|||||||
|
|
||||||
track_crewai(project_name="crewai-integration-demo")
|
track_crewai(project_name="crewai-integration-demo")
|
||||||
|
|
||||||
my_crew = YourCrewName().crew()
|
my_crew = NomeDaEquipe().equipe()
|
||||||
result = my_crew.kickoff()
|
result = my_crew.kickoff()
|
||||||
|
|
||||||
print(result)
|
print(result)
|
||||||
|
|||||||
@@ -64,17 +64,17 @@ patronus_eval_tool = PatronusEvalTool()
|
|||||||
|
|
||||||
# Define an agent that uses the tool
|
# Define an agent that uses the tool
|
||||||
coding_agent = Agent(
|
coding_agent = Agent(
|
||||||
role="Coding Agent",
|
role="Agente de Programação",
|
||||||
goal="Generate high quality code and verify that the output is code",
|
goal="Gerar código de alta qualidade e verificar se a saída é código",
|
||||||
backstory="An experienced coder who can generate high quality python code.",
|
backstory="Um programador experiente que pode gerar código Python de alta qualidade.",
|
||||||
tools=[patronus_eval_tool],
|
tools=[patronus_eval_tool],
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Example task to generate and evaluate code
|
# Example task to generate and evaluate code
|
||||||
generate_code_task = Task(
|
generate_code_task = Task(
|
||||||
description="Create a simple program to generate the first N numbers in the Fibonacci sequence. Select the most appropriate evaluator and criteria for evaluating your output.",
|
description="Crie um programa simples para gerar os N primeiros números da sequência de Fibonacci. Selecione o avaliador e os critérios mais apropriados para avaliar sua saída.",
|
||||||
expected_output="Program that generates the first N numbers in the Fibonacci sequence.",
|
expected_output="Programa que gera os N primeiros números da sequência de Fibonacci.",
|
||||||
agent=coding_agent,
|
agent=coding_agent,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -98,17 +98,17 @@ patronus_eval_tool = PatronusPredefinedCriteriaEvalTool(
|
|||||||
|
|
||||||
# Define an agent that uses the tool
|
# Define an agent that uses the tool
|
||||||
coding_agent = Agent(
|
coding_agent = Agent(
|
||||||
role="Coding Agent",
|
role="Agente de Programação",
|
||||||
goal="Generate high quality code",
|
goal="Gerar código de alta qualidade",
|
||||||
backstory="An experienced coder who can generate high quality python code.",
|
backstory="Um programador experiente que pode gerar código Python de alta qualidade.",
|
||||||
tools=[patronus_eval_tool],
|
tools=[patronus_eval_tool],
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Example task to generate code
|
# Example task to generate code
|
||||||
generate_code_task = Task(
|
generate_code_task = Task(
|
||||||
description="Create a simple program to generate the first N numbers in the Fibonacci sequence.",
|
description="Crie um programa simples para gerar os N primeiros números da sequência de Fibonacci.",
|
||||||
expected_output="Program that generates the first N numbers in the Fibonacci sequence.",
|
expected_output="Programa que gera os N primeiros números da sequência de Fibonacci.",
|
||||||
agent=coding_agent,
|
agent=coding_agent,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -149,17 +149,17 @@ patronus_eval_tool = PatronusLocalEvaluatorTool(
|
|||||||
|
|
||||||
# Define an agent that uses the tool
|
# Define an agent that uses the tool
|
||||||
coding_agent = Agent(
|
coding_agent = Agent(
|
||||||
role="Coding Agent",
|
role="Agente de Programação",
|
||||||
goal="Generate high quality code",
|
goal="Gerar código de alta qualidade",
|
||||||
backstory="An experienced coder who can generate high quality python code.",
|
backstory="Um programador experiente que pode gerar código Python de alta qualidade.",
|
||||||
tools=[patronus_eval_tool],
|
tools=[patronus_eval_tool],
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Example task to generate code
|
# Example task to generate code
|
||||||
generate_code_task = Task(
|
generate_code_task = Task(
|
||||||
description="Create a simple program to generate the first N numbers in the Fibonacci sequence.",
|
description="Crie um programa simples para gerar os N primeiros números da sequência de Fibonacci.",
|
||||||
expected_output="Program that generates the first N numbers in the Fibonacci sequence.",
|
expected_output="Programa que gera os N primeiros números da sequência de Fibonacci.",
|
||||||
agent=coding_agent,
|
agent=coding_agent,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -50,48 +50,48 @@ O Weave captura automaticamente rastreamentos (traces) de suas aplicações Crew
|
|||||||
llm = LLM(model="gpt-4o", temperature=0)
|
llm = LLM(model="gpt-4o", temperature=0)
|
||||||
|
|
||||||
# Crie os agentes
|
# Crie os agentes
|
||||||
researcher = Agent(
|
pesquisador = Agent(
|
||||||
role='Research Analyst',
|
role='Analista de Pesquisa',
|
||||||
goal='Find and analyze the best investment opportunities',
|
goal='Encontrar e analisar as melhores oportunidades de investimento',
|
||||||
backstory='Expert in financial analysis and market research',
|
backstory='Especialista em análise financeira e pesquisa de mercado',
|
||||||
llm=llm,
|
llm=llm,
|
||||||
verbose=True,
|
verbose=True,
|
||||||
allow_delegation=False,
|
allow_delegation=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
writer = Agent(
|
redator = Agent(
|
||||||
role='Report Writer',
|
role='Redator de Relatórios',
|
||||||
goal='Write clear and concise investment reports',
|
goal='Escrever relatórios de investimento claros e concisos',
|
||||||
backstory='Experienced in creating detailed financial reports',
|
backstory='Experiente na criação de relatórios financeiros detalhados',
|
||||||
llm=llm,
|
llm=llm,
|
||||||
verbose=True,
|
verbose=True,
|
||||||
allow_delegation=False,
|
allow_delegation=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Crie as tarefas
|
# Crie as tarefas
|
||||||
research_task = Task(
|
pesquisa = Task(
|
||||||
description='Deep research on the {topic}',
|
description='Pesquisa aprofundada sobre o {tema}',
|
||||||
expected_output='Comprehensive market data including key players, market size, and growth trends.',
|
expected_output='Dados de mercado abrangentes incluindo principais players, tamanho de mercado e tendências de crescimento.',
|
||||||
agent=researcher
|
agent=pesquisador
|
||||||
)
|
)
|
||||||
|
|
||||||
writing_task = Task(
|
redacao = Task(
|
||||||
description='Write a detailed report based on the research',
|
description='Escreva um relatório detalhado com base na pesquisa',
|
||||||
expected_output='The report should be easy to read and understand. Use bullet points where applicable.',
|
expected_output='O relatório deve ser fácil de ler e entender. Use tópicos quando aplicável.',
|
||||||
agent=writer
|
agent=redator
|
||||||
)
|
)
|
||||||
|
|
||||||
# Crie o crew
|
# Crie o crew
|
||||||
crew = Crew(
|
equipe = Crew(
|
||||||
agents=[researcher, writer],
|
agents=[pesquisador, redator],
|
||||||
tasks=[research_task, writing_task],
|
tasks=[pesquisa, redacao],
|
||||||
verbose=True,
|
verbose=True,
|
||||||
process=Process.sequential,
|
process=Process.sequential,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Execute o crew
|
# Execute o crew
|
||||||
result = crew.kickoff(inputs={"topic": "AI in material science"})
|
resultado = equipe.kickoff(inputs={"tema": "IA em ciência dos materiais"})
|
||||||
print(result)
|
print(resultado)
|
||||||
```
|
```
|
||||||
</Step>
|
</Step>
|
||||||
<Step title="Visualize rastreamentos no Weave">
|
<Step title="Visualize rastreamentos no Weave">
|
||||||
|
|||||||
@@ -39,23 +39,19 @@ Siga os passos abaixo para começar a tripular! 🚣♂️
|
|||||||
# src/latest_ai_development/config/agents.yaml
|
# src/latest_ai_development/config/agents.yaml
|
||||||
researcher:
|
researcher:
|
||||||
role: >
|
role: >
|
||||||
{topic} Senior Data Researcher
|
Pesquisador Sênior de Dados em {topic}
|
||||||
goal: >
|
goal: >
|
||||||
Uncover cutting-edge developments in {topic}
|
Descobrir os avanços mais recentes em {topic}
|
||||||
backstory: >
|
backstory: >
|
||||||
You're a seasoned researcher with a knack for uncovering the latest
|
Você é um pesquisador experiente com talento para descobrir os últimos avanços em {topic}. Conhecido por sua habilidade em encontrar as informações mais relevantes e apresentá-las de forma clara e concisa.
|
||||||
developments in {topic}. Known for your ability to find the most relevant
|
|
||||||
information and present it in a clear and concise manner.
|
|
||||||
|
|
||||||
reporting_analyst:
|
reporting_analyst:
|
||||||
role: >
|
role: >
|
||||||
{topic} Reporting Analyst
|
Analista de Relatórios em {topic}
|
||||||
goal: >
|
goal: >
|
||||||
Create detailed reports based on {topic} data analysis and research findings
|
Criar relatórios detalhados com base na análise de dados e descobertas de pesquisa em {topic}
|
||||||
backstory: >
|
backstory: >
|
||||||
You're a meticulous analyst with a keen eye for detail. You're known for
|
Você é um analista meticuloso com um olhar atento aos detalhes. É conhecido por sua capacidade de transformar dados complexos em relatórios claros e concisos, facilitando o entendimento e a tomada de decisão por parte dos outros.
|
||||||
your ability to turn complex data into clear and concise reports, making
|
|
||||||
it easy for others to understand and act on the information you provide.
|
|
||||||
```
|
```
|
||||||
</Step>
|
</Step>
|
||||||
<Step title="Modifique seu arquivo `tasks.yaml`">
|
<Step title="Modifique seu arquivo `tasks.yaml`">
|
||||||
@@ -63,20 +59,19 @@ Siga os passos abaixo para começar a tripular! 🚣♂️
|
|||||||
# src/latest_ai_development/config/tasks.yaml
|
# src/latest_ai_development/config/tasks.yaml
|
||||||
research_task:
|
research_task:
|
||||||
description: >
|
description: >
|
||||||
Conduct a thorough research about {topic}
|
Realize uma pesquisa aprofundada sobre {topic}.
|
||||||
Make sure you find any interesting and relevant information given
|
Certifique-se de encontrar informações interessantes e relevantes considerando que o ano atual é 2025.
|
||||||
the current year is 2025.
|
|
||||||
expected_output: >
|
expected_output: >
|
||||||
A list with 10 bullet points of the most relevant information about {topic}
|
Uma lista com 10 tópicos dos dados mais relevantes sobre {topic}
|
||||||
agent: researcher
|
agent: researcher
|
||||||
|
|
||||||
reporting_task:
|
reporting_task:
|
||||||
description: >
|
description: >
|
||||||
Review the context you got and expand each topic into a full section for a report.
|
Revise o contexto obtido e expanda cada tópico em uma seção completa para um relatório.
|
||||||
Make sure the report is detailed and contains any and all relevant information.
|
Certifique-se de que o relatório seja detalhado e contenha todas as informações relevantes.
|
||||||
expected_output: >
|
expected_output: >
|
||||||
A fully fledge reports with the mains topics, each with a full section of information.
|
Um relatório completo com os principais tópicos, cada um com uma seção detalhada de informações.
|
||||||
Formatted as markdown without '```'
|
Formate como markdown sem usar '```'
|
||||||
agent: reporting_analyst
|
agent: reporting_analyst
|
||||||
output_file: report.md
|
output_file: report.md
|
||||||
```
|
```
|
||||||
@@ -122,15 +117,15 @@ Siga os passos abaixo para começar a tripular! 🚣♂️
|
|||||||
def reporting_task(self) -> Task:
|
def reporting_task(self) -> Task:
|
||||||
return Task(
|
return Task(
|
||||||
config=self.tasks_config['reporting_task'], # type: ignore[index]
|
config=self.tasks_config['reporting_task'], # type: ignore[index]
|
||||||
output_file='output/report.md' # This is the file that will be contain the final report.
|
output_file='output/report.md' # Este é o arquivo que conterá o relatório final.
|
||||||
)
|
)
|
||||||
|
|
||||||
@crew
|
@crew
|
||||||
def crew(self) -> Crew:
|
def crew(self) -> Crew:
|
||||||
"""Creates the LatestAiDevelopment crew"""
|
"""Creates the LatestAiDevelopment crew"""
|
||||||
return Crew(
|
return Crew(
|
||||||
agents=self.agents, # Automatically created by the @agent decorator
|
agents=self.agents, # Criado automaticamente pelo decorador @agent
|
||||||
tasks=self.tasks, # Automatically created by the @task decorator
|
tasks=self.tasks, # Criado automaticamente pelo decorador @task
|
||||||
process=Process.sequential,
|
process=Process.sequential,
|
||||||
verbose=True,
|
verbose=True,
|
||||||
)
|
)
|
||||||
@@ -229,7 +224,7 @@ Siga os passos abaixo para começar a tripular! 🚣♂️
|
|||||||
|
|
||||||
<CodeGroup>
|
<CodeGroup>
|
||||||
```markdown output/report.md
|
```markdown output/report.md
|
||||||
# Comprehensive Report on the Rise and Impact of AI Agents in 2025
|
# Relatório Abrangente sobre a Ascensão e o Impacto dos Agentes de IA em 2025
|
||||||
|
|
||||||
## 1. Introduction to AI Agents
|
## 1. Introduction to AI Agents
|
||||||
In 2025, Artificial Intelligence (AI) agents are at the forefront of innovation across various industries. As intelligent systems that can perform tasks typically requiring human cognition, AI agents are paving the way for significant advancements in operational efficiency, decision-making, and overall productivity within sectors like Human Resources (HR) and Finance. This report aims to detail the rise of AI agents, their frameworks, applications, and potential implications on the workforce.
|
In 2025, Artificial Intelligence (AI) agents are at the forefront of innovation across various industries. As intelligent systems that can perform tasks typically requiring human cognition, AI agents are paving the way for significant advancements in operational efficiency, decision-making, and overall productivity within sectors like Human Resources (HR) and Finance. This report aims to detail the rise of AI agents, their frameworks, applications, and potential implications on the workforce.
|
||||||
|
|||||||
@@ -35,78 +35,18 @@ from crewai_tools import LinkupSearchTool
|
|||||||
from crewai import Agent
|
from crewai import Agent
|
||||||
import os
|
import os
|
||||||
|
|
||||||
# Initialize the tool with your API key
|
# Inicialize a ferramenta com sua chave de API
|
||||||
linkup_tool = LinkupSearchTool(api_key=os.getenv("LINKUP_API_KEY"))
|
linkup_ferramenta = LinkupSearchTool(api_key=os.getenv("LINKUP_API_KEY"))
|
||||||
|
|
||||||
# Define an agent that uses the tool
|
# Defina um agente que usa a ferramenta
|
||||||
@agent
|
@agent
|
||||||
def researcher(self) -> Agent:
|
def pesquisador(self) -> Agent:
|
||||||
'''
|
'''
|
||||||
This agent uses the LinkupSearchTool to retrieve contextual information
|
Este agente usa o LinkupSearchTool para recuperar informações contextuais
|
||||||
from the Linkup API.
|
da API do Linkup.
|
||||||
'''
|
'''
|
||||||
return Agent(
|
return Agent(
|
||||||
config=self.agents_config["researcher"],
|
config=self.agentes_config["pesquisador"],
|
||||||
tools=[linkup_tool]
|
tools=[linkup_ferramenta]
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Parâmetros
|
|
||||||
|
|
||||||
O `LinkupSearchTool` aceita os seguintes parâmetros:
|
|
||||||
|
|
||||||
### Parâmetros do Construtor
|
|
||||||
- **api_key**: Obrigatório. Sua chave de API do Linkup.
|
|
||||||
|
|
||||||
### Parâmetros de Execução
|
|
||||||
- **query**: Obrigatório. O termo ou frase de busca.
|
|
||||||
- **depth**: Opcional. A profundidade da busca. O padrão é "standard".
|
|
||||||
- **output_type**: Opcional. O tipo de saída. O padrão é "searchResults".
|
|
||||||
|
|
||||||
## Uso Avançado
|
|
||||||
|
|
||||||
Você pode personalizar os parâmetros de busca para resultados mais específicos:
|
|
||||||
|
|
||||||
```python Code
|
|
||||||
# Perform a search with custom parameters
|
|
||||||
results = linkup_tool.run(
|
|
||||||
query="Women Nobel Prize Physics",
|
|
||||||
depth="deep",
|
|
||||||
output_type="searchResults"
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Formato de Retorno
|
|
||||||
|
|
||||||
A ferramenta retorna resultados no seguinte formato:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"success": true,
|
|
||||||
"results": [
|
|
||||||
{
|
|
||||||
"name": "Result Title",
|
|
||||||
"url": "https://example.com/result",
|
|
||||||
"content": "Content of the result..."
|
|
||||||
},
|
|
||||||
// Additional results...
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Se ocorrer um erro, a resposta será:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"success": false,
|
|
||||||
"error": "Error message"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Tratamento de Erros
|
|
||||||
|
|
||||||
A ferramenta lida com erros de API de forma amigável e fornece feedback estruturado. Se a requisição à API falhar, a ferramenta retornará um dicionário com `success: false` e uma mensagem de erro.
|
|
||||||
|
|
||||||
## Conclusão
|
|
||||||
|
|
||||||
O `LinkupSearchTool` oferece uma forma integrada de incorporar as capacidades de busca de informações contextuais do Linkup aos seus agentes CrewAI. Ao utilizar esta ferramenta, os agentes podem acessar informações relevantes e atualizadas para aprimorar sua tomada de decisão e execução de tarefas.
|
|
||||||
Reference in New Issue
Block a user