Spaces:
Sleeping
Sleeping
DaniloSBorba commited on
Commit ·
9dc2ddb
1
Parent(s): c34bfae
deploy: agente aula07 no HF Space
Browse files- README_SPACE.md +157 -0
- app.py +187 -0
- config/products.yaml +128 -0
- requirements.txt +13 -0
- src/__init__.py +3 -0
- src/__pycache__/__init__.cpython-311.pyc +0 -0
- src/__pycache__/__init__.cpython-312.pyc +0 -0
- src/__pycache__/cli.cpython-311.pyc +0 -0
- src/__pycache__/cli.cpython-312.pyc +0 -0
- src/__pycache__/config.cpython-311.pyc +0 -0
- src/__pycache__/config.cpython-312.pyc +0 -0
- src/__pycache__/llm.cpython-311.pyc +0 -0
- src/__pycache__/llm.cpython-312.pyc +0 -0
- src/agents/__init__.py +1 -0
- src/agents/__pycache__/__init__.cpython-312.pyc +0 -0
- src/agents/__pycache__/multi_agent.cpython-312.pyc +0 -0
- src/agents/__pycache__/single_agent.cpython-312.pyc +0 -0
- src/agents/multi_agent.py +266 -0
- src/agents/single_agent.py +124 -0
- src/api/__init__.py +1 -0
- src/api/__pycache__/__init__.cpython-312.pyc +0 -0
- src/api/__pycache__/app.cpython-312.pyc +0 -0
- src/api/app.py +166 -0
- src/cli.py +171 -0
- src/config.py +68 -0
- src/llm.py +47 -0
- src/mcp/__init__.py +1 -0
- src/mcp/__pycache__/__init__.cpython-312.pyc +0 -0
- src/mcp/__pycache__/server.cpython-312.pyc +0 -0
- src/mcp/server.py +114 -0
- src/tools/__init__.py +48 -0
- src/tools/__pycache__/__init__.cpython-312.pyc +0 -0
- src/tools/__pycache__/calculator.cpython-312.pyc +0 -0
- src/tools/__pycache__/design_validator.cpython-312.pyc +0 -0
- src/tools/__pycache__/grade_classifier.cpython-312.pyc +0 -0
- src/tools/__pycache__/ideation_generator.cpython-312.pyc +0 -0
- src/tools/__pycache__/knowledge_base.cpython-312.pyc +0 -0
- src/tools/calculator.py +78 -0
- src/tools/design_validator.py +82 -0
- src/tools/grade_classifier.py +77 -0
- src/tools/ideation_generator.py +63 -0
- src/tools/knowledge_base.py +107 -0
README_SPACE.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Deploy para Hugging Face Spaces
|
| 2 |
+
|
| 3 |
+
Guia para publicar seu agente como Space público gratuito.
|
| 4 |
+
|
| 5 |
+
## Pré-requisitos
|
| 6 |
+
|
| 7 |
+
- Conta Hugging Face ativa (gratuita) em <https://huggingface.co/join>.
|
| 8 |
+
- Repositório `aula07-agentes` no GitHub com tag `aula07-final`.
|
| 9 |
+
- Saldo na conta OpenAI (mesma chave que você usou no Codespaces).
|
| 10 |
+
|
| 11 |
+
## Passo 1 · Criar o Space
|
| 12 |
+
|
| 13 |
+
1. Acesse <https://huggingface.co/new-space>.
|
| 14 |
+
2. **Owner**: seu usuário.
|
| 15 |
+
3. **Space name**: `educiacao` ou `designmind` (sem espaços, minúsculo).
|
| 16 |
+
4. **License**: MIT (padrão para projetos didáticos).
|
| 17 |
+
5. **Space SDK**: selecione **Gradio**.
|
| 18 |
+
6. **Gradio template**: deixe como "Blank".
|
| 19 |
+
7. **Hardware**: `CPU basic · Free` (suficiente para o agente, que só chama API).
|
| 20 |
+
8. **Visibility**: `Public` (recomendado para portfólio) ou `Private`.
|
| 21 |
+
9. Clique em **Create Space**.
|
| 22 |
+
|
| 23 |
+
## Passo 2 · Configurar Secrets e Variables
|
| 24 |
+
|
| 25 |
+
Antes de subir código, configure os segredos. No Space recém-criado:
|
| 26 |
+
|
| 27 |
+
1. Clique em **Settings** (canto superior direito do Space).
|
| 28 |
+
2. Role até **Variables and secrets**.
|
| 29 |
+
3. Em **Secrets**, clique em **New secret**:
|
| 30 |
+
- Name: `OPENAI_API_KEY`
|
| 31 |
+
- Value: sua chave (`sk-...`)
|
| 32 |
+
4. Em **Variables**, clique em **New variable**:
|
| 33 |
+
- Name: `PRODUCT`
|
| 34 |
+
- Value: `educiacao` ou `designmind` (mesmo que você usa no `.env`)
|
| 35 |
+
- Name: `OPENAI_MODEL`
|
| 36 |
+
- Value: `gpt-4.1-mini`
|
| 37 |
+
|
| 38 |
+
**Importante**: Secrets ficam ocultos para visitantes. Variables aparecem no log público mas servem para config não-sensível.
|
| 39 |
+
|
| 40 |
+
## Passo 3 · Subir os arquivos
|
| 41 |
+
|
| 42 |
+
Você tem duas opções: upload manual via UI ou git push. Recomendo git.
|
| 43 |
+
|
| 44 |
+
### Opção A · git push (recomendado)
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
# No seu Codespaces, terminal:
|
| 48 |
+
|
| 49 |
+
# 1. Clone o repositório do Space ao lado do projeto
|
| 50 |
+
cd /tmp
|
| 51 |
+
git clone https://huggingface.co/spaces/<SEU_USER>/<NOME_SPACE>
|
| 52 |
+
cd <NOME_SPACE>
|
| 53 |
+
|
| 54 |
+
# 2. Copie os 3 arquivos do deploy + tudo de src/ e config/
|
| 55 |
+
cp -r /workspaces/aula07-agentes/deploy/* .
|
| 56 |
+
cp -r /workspaces/aula07-agentes/src ./src
|
| 57 |
+
cp -r /workspaces/aula07-agentes/config ./config
|
| 58 |
+
|
| 59 |
+
# 3. Commit e push (HF aceita push direto)
|
| 60 |
+
git add .
|
| 61 |
+
git commit -m "deploy: agente aula07 no HF Space"
|
| 62 |
+
git push
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
O Space vai detectar `app.py` na raiz, instalar `requirements.txt`,
|
| 66 |
+
e em ~2 minutos seu agente estará público.
|
| 67 |
+
|
| 68 |
+
### Opção B · upload manual via UI
|
| 69 |
+
|
| 70 |
+
1. No Space, aba **Files**.
|
| 71 |
+
2. Clique em **Add file → Upload files**.
|
| 72 |
+
3. Suba os arquivos nesta estrutura na raiz do Space:
|
| 73 |
+
|
| 74 |
+
```
|
| 75 |
+
<seu-space>/
|
| 76 |
+
├── app.py ← do deploy/app.py
|
| 77 |
+
├── requirements.txt ← do deploy/requirements.txt
|
| 78 |
+
├── README.md ← este arquivo (opcional)
|
| 79 |
+
├── src/ ← pasta inteira
|
| 80 |
+
│ ├── __init__.py
|
| 81 |
+
│ ├── config.py
|
| 82 |
+
│ ├── llm.py
|
| 83 |
+
│ ├── agents/
|
| 84 |
+
│ │ ├── __init__.py
|
| 85 |
+
│ │ ├── single_agent.py
|
| 86 |
+
│ │ └── multi_agent.py
|
| 87 |
+
│ └── tools/
|
| 88 |
+
│ └── ... (todos os 6 arquivos)
|
| 89 |
+
└── config/
|
| 90 |
+
└── products.yaml
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
4. Commit.
|
| 94 |
+
|
| 95 |
+
## Passo 4 · Aguardar build e validar
|
| 96 |
+
|
| 97 |
+
1. Volte à aba **App** do Space.
|
| 98 |
+
2. Verá um log de build:
|
| 99 |
+
|
| 100 |
+
```
|
| 101 |
+
===== Application Startup at 2026-MM-DD HH:MM =====
|
| 102 |
+
Installing requirements...
|
| 103 |
+
Successfully installed gradio openai langgraph ...
|
| 104 |
+
Running on local URL: http://0.0.0.0:7860
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
3. Quando aparecer a UI Gradio, **clique em uma das perguntas-exemplo**.
|
| 108 |
+
4. Confirme que retorna resposta coerente em PT-BR.
|
| 109 |
+
|
| 110 |
+
## Limitações deste Space gratuito
|
| 111 |
+
|
| 112 |
+
| Limitação | Valor | Impacto |
|
| 113 |
+
|---|---|---|
|
| 114 |
+
| Timeout por requisição | 30 segundos | Multi-agente complexo pode estourar. Use single para chat. |
|
| 115 |
+
| Hardware | 2 vCPU, 16GB RAM | Suficiente — agente só faz I/O ao OpenAI. |
|
| 116 |
+
| Persistência | Nenhuma | Histórico de conversa some entre sessões. |
|
| 117 |
+
| Auth | Nenhuma | Qualquer pessoa com a URL usa sua chave OpenAI. |
|
| 118 |
+
| Sleep | 48h sem uso | Volta a rodar em ~30s na primeira requisição depois. |
|
| 119 |
+
| Rate limit OpenAI | sua quota | Se viralizar e sua conta zerar, Space para de responder. |
|
| 120 |
+
|
| 121 |
+
## O que NÃO usar este Space para
|
| 122 |
+
|
| 123 |
+
- Produção comercial real (sem auth, sem SLA, sem monitoramento).
|
| 124 |
+
- Dados sensíveis dos usuários (não há controle de acesso).
|
| 125 |
+
- Workloads pesados (timeout de 30s).
|
| 126 |
+
- Workflows multi-step de longa duração.
|
| 127 |
+
|
| 128 |
+
## Como atualizar depois
|
| 129 |
+
|
| 130 |
+
Sempre que mudar o código local:
|
| 131 |
+
|
| 132 |
+
```bash
|
| 133 |
+
cd /tmp/<NOME_SPACE>
|
| 134 |
+
cp -r /workspaces/aula07-agentes/src/* ./src/
|
| 135 |
+
git add .
|
| 136 |
+
git commit -m "update: ..."
|
| 137 |
+
git push
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
O Space rebuilda automaticamente em ~1-2 minutos.
|
| 141 |
+
|
| 142 |
+
## Próximos passos pós-Space
|
| 143 |
+
|
| 144 |
+
1. **Compartilhar a URL** com colegas, recrutadores, professores.
|
| 145 |
+
2. **Adicionar ao seu CV**: "Construí agente conversacional em LangGraph + OpenAI, publicado em HF Spaces. Acesso público: huggingface.co/spaces/...".
|
| 146 |
+
3. **Iterar com feedback real**: usuários diferentes encontram bugs diferentes. Anote, ajuste persona, faça push.
|
| 147 |
+
4. **Migrar para produção real** quando ficar grande: Render, Railway, Fly.io, AWS App Runner. Mas só quando precisar.
|
| 148 |
+
|
| 149 |
+
## Custos esperados
|
| 150 |
+
|
| 151 |
+
| Cenário | Custo/mês |
|
| 152 |
+
|---|---|
|
| 153 |
+
| Space gratuito + você testando | USD 0 (sem chamadas) |
|
| 154 |
+
| Space público com 10 visitantes/mês | USD 0.50 - 2.00 |
|
| 155 |
+
| Space viralizado com 1000 chamadas/dia | USD 30 - 100 |
|
| 156 |
+
|
| 157 |
+
Se viralizar, **desative o Space** ou adicione rate limit antes de virar Space pago.
|
app.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gradio UI para Hugging Face Spaces.
|
| 2 |
+
|
| 3 |
+
Este é o entry point do Space. O arquivo é detectado automaticamente pelo HF
|
| 4 |
+
quando se chama `app.py` na raiz do Space.
|
| 5 |
+
|
| 6 |
+
Dois modos de execução expostos via abas:
|
| 7 |
+
· Single ReAct → rápido, trace visível
|
| 8 |
+
· Multi LangGraph → mais lento, mostra plan/context/draft/critique
|
| 9 |
+
|
| 10 |
+
A OPENAI_API_KEY vem como Secret do Space (NÃO commitar no código).
|
| 11 |
+
A variável PRODUCT vem como Variable do Space (educiacao ou designmind).
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
# Resolver path para conseguir importar src/ no Space (cwd varia)
|
| 21 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 22 |
+
if str(ROOT) not in sys.path:
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
|
| 25 |
+
import gradio as gr
|
| 26 |
+
|
| 27 |
+
from src.agents.multi_agent import run_multi_agent
|
| 28 |
+
from src.agents.single_agent import SingleAgent
|
| 29 |
+
from src.config import get_product_config
|
| 30 |
+
|
| 31 |
+
# Carrega config do produto ativo uma vez (espaço fica fixado em um produto)
|
| 32 |
+
_PRODUCT_CONFIG = get_product_config()
|
| 33 |
+
_PRODUCT_NAME = _PRODUCT_CONFIG["name"]
|
| 34 |
+
_EXAMPLE_PROMPTS = _PRODUCT_CONFIG["example_prompts"]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# =============================================================================
|
| 38 |
+
# Handlers
|
| 39 |
+
# =============================================================================
|
| 40 |
+
def handle_single(query: str) -> tuple[str, str]:
|
| 41 |
+
"""Roda agente single ReAct. Retorna (resposta_final, trace_markdown)."""
|
| 42 |
+
if not query or len(query.strip()) < 3:
|
| 43 |
+
return "Digite uma pergunta com pelo menos 3 caracteres.", ""
|
| 44 |
+
|
| 45 |
+
agent = SingleAgent()
|
| 46 |
+
result = agent.run(query, verbose=False)
|
| 47 |
+
|
| 48 |
+
# Formata trace em markdown
|
| 49 |
+
trace_lines = ["### Trace do agente\n"]
|
| 50 |
+
for s in result.steps:
|
| 51 |
+
if s.is_final:
|
| 52 |
+
trace_lines.append(f"**Passo {s.step_number} · FINAL**")
|
| 53 |
+
trace_lines.append(f"_resposta direta ao usuário (mostrada acima)_\n")
|
| 54 |
+
else:
|
| 55 |
+
args_str = json.dumps(s.tool_args or {}, ensure_ascii=False, indent=2)
|
| 56 |
+
result_str = (s.tool_result or "")[:500]
|
| 57 |
+
trace_lines.append(f"**Passo {s.step_number} · TOOL**")
|
| 58 |
+
trace_lines.append(f"- ferramenta: `{s.tool_name}`")
|
| 59 |
+
trace_lines.append(f"- argumentos: `{args_str}`")
|
| 60 |
+
trace_lines.append(f"- resultado: {result_str}\n")
|
| 61 |
+
|
| 62 |
+
return result.final_answer, "\n".join(trace_lines)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def handle_multi(query: str) -> tuple[str, str, str, str, str]:
|
| 66 |
+
"""Roda multi-agente. Retorna (final, plan, context, draft, critique)."""
|
| 67 |
+
if not query or len(query.strip()) < 3:
|
| 68 |
+
empty = "Digite uma pergunta com pelo menos 3 caracteres."
|
| 69 |
+
return empty, "", "", "", ""
|
| 70 |
+
|
| 71 |
+
state = run_multi_agent(query, max_iterations=2)
|
| 72 |
+
return (
|
| 73 |
+
state.get("final_answer", state.get("draft_answer", "")),
|
| 74 |
+
state.get("plan", ""),
|
| 75 |
+
state.get("context", "")[:2000],
|
| 76 |
+
state.get("draft_answer", ""),
|
| 77 |
+
state.get("critique", ""),
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# =============================================================================
|
| 82 |
+
# UI
|
| 83 |
+
# =============================================================================
|
| 84 |
+
INTRO = f"""
|
| 85 |
+
# {_PRODUCT_NAME}
|
| 86 |
+
|
| 87 |
+
Agente construído na Aula 07 do curso de Engenharia de IA.
|
| 88 |
+
Função calling nativa OpenAI + LangGraph + avaliação BFCL.
|
| 89 |
+
|
| 90 |
+
**Modelo**: {os.getenv("OPENAI_MODEL", "gpt-4.1-mini")} ·
|
| 91 |
+
**Produto ativo**: `{os.getenv("PRODUCT", "educiacao")}`
|
| 92 |
+
|
| 93 |
+
> Limitações deste Space gratuito: timeout de 30 segundos por requisição,
|
| 94 |
+
> sem persistência entre sessões, latência variável.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
with gr.Blocks(title=f"{_PRODUCT_NAME} · Agente") as demo:
|
| 99 |
+
gr.Markdown(INTRO)
|
| 100 |
+
|
| 101 |
+
with gr.Tabs():
|
| 102 |
+
# ---------------------------------------------------------------------
|
| 103 |
+
# Tab 1: Single ReAct
|
| 104 |
+
# ---------------------------------------------------------------------
|
| 105 |
+
with gr.Tab("Single ReAct · rápido"):
|
| 106 |
+
gr.Markdown(
|
| 107 |
+
"**Loop ReAct**: o LLM raciocina, chama tool, recebe resultado, "
|
| 108 |
+
"itera até resposta final. Limite: 8 iterações."
|
| 109 |
+
)
|
| 110 |
+
with gr.Row():
|
| 111 |
+
with gr.Column(scale=2):
|
| 112 |
+
s_input = gr.Textbox(
|
| 113 |
+
label="Sua pergunta",
|
| 114 |
+
placeholder=_EXAMPLE_PROMPTS[0],
|
| 115 |
+
lines=3,
|
| 116 |
+
)
|
| 117 |
+
gr.Examples(
|
| 118 |
+
examples=[[p] for p in _EXAMPLE_PROMPTS],
|
| 119 |
+
inputs=s_input,
|
| 120 |
+
label="Exemplos · clique para preencher",
|
| 121 |
+
)
|
| 122 |
+
s_button = gr.Button("Perguntar", variant="primary")
|
| 123 |
+
with gr.Column(scale=3):
|
| 124 |
+
s_answer = gr.Textbox(
|
| 125 |
+
label="Resposta final",
|
| 126 |
+
lines=8,
|
| 127 |
+
interactive=False,
|
| 128 |
+
)
|
| 129 |
+
s_trace = gr.Markdown(label="Trace")
|
| 130 |
+
|
| 131 |
+
s_button.click(
|
| 132 |
+
fn=handle_single,
|
| 133 |
+
inputs=s_input,
|
| 134 |
+
outputs=[s_answer, s_trace],
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# ---------------------------------------------------------------------
|
| 138 |
+
# Tab 2: Multi LangGraph
|
| 139 |
+
# ---------------------------------------------------------------------
|
| 140 |
+
with gr.Tab("Multi LangGraph · estruturado"):
|
| 141 |
+
gr.Markdown(
|
| 142 |
+
"**Plan-and-execute com self-critique**: 4 nós sequenciais "
|
| 143 |
+
"(planner → researcher → writer → critic). Mais lento, "
|
| 144 |
+
"mais estruturado. Padrão usado por Devin e Agentforce."
|
| 145 |
+
)
|
| 146 |
+
with gr.Row():
|
| 147 |
+
with gr.Column(scale=2):
|
| 148 |
+
m_input = gr.Textbox(
|
| 149 |
+
label="Sua pergunta",
|
| 150 |
+
placeholder=_EXAMPLE_PROMPTS[0],
|
| 151 |
+
lines=3,
|
| 152 |
+
)
|
| 153 |
+
m_button = gr.Button("Executar pipeline", variant="primary")
|
| 154 |
+
with gr.Column(scale=3):
|
| 155 |
+
m_answer = gr.Textbox(
|
| 156 |
+
label="Resposta final",
|
| 157 |
+
lines=6,
|
| 158 |
+
interactive=False,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
gr.Markdown("### Trace dos 4 nós")
|
| 162 |
+
with gr.Row():
|
| 163 |
+
m_plan = gr.Textbox(label="1. PLAN", lines=4, interactive=False)
|
| 164 |
+
m_context = gr.Textbox(label="2. CONTEXT", lines=4, interactive=False)
|
| 165 |
+
with gr.Row():
|
| 166 |
+
m_draft = gr.Textbox(label="3. DRAFT", lines=4, interactive=False)
|
| 167 |
+
m_critique = gr.Textbox(label="4. CRITIQUE", lines=4, interactive=False)
|
| 168 |
+
|
| 169 |
+
m_button.click(
|
| 170 |
+
fn=handle_multi,
|
| 171 |
+
inputs=m_input,
|
| 172 |
+
outputs=[m_answer, m_plan, m_context, m_draft, m_critique],
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
gr.Markdown(
|
| 176 |
+
"""
|
| 177 |
+
---
|
| 178 |
+
Engenharia de IA · Prof. Sergio Gaiotto · 2026.
|
| 179 |
+
Código completo em [GitHub](https://github.com/) · Model Card em `docs/MODEL_CARD_v4.md`.
|
| 180 |
+
"""
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# Entry point do Space — HF chama assim
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
demo.queue() # habilita fila para múltiplos usuários simultâneos
|
| 187 |
+
demo.launch(theme=gr.themes.Soft())
|
config/products.yaml
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# Configuração dos produtos da turma
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# O aluno escolhe UM produto via variável de ambiente PRODUCT no .env.
|
| 5 |
+
# Esta config define: persona do agente, tools habilitadas, exemplos de prompt.
|
| 6 |
+
|
| 7 |
+
educiacao:
|
| 8 |
+
name: "EducIAção"
|
| 9 |
+
description: "Tutor pedagógico para alunos em situação de vulnerabilidade"
|
| 10 |
+
persona: |
|
| 11 |
+
Você é um tutor pedagógico chamado EducIAção. Sua missão é ajudar
|
| 12 |
+
alunos do ensino fundamental e médio brasileiro, especialmente
|
| 13 |
+
aqueles em situação de vulnerabilidade social.
|
| 14 |
+
|
| 15 |
+
Princípios:
|
| 16 |
+
- Tom acolhedor, sem ser infantil. Trate o aluno com respeito.
|
| 17 |
+
- Explique passo a passo. Use exemplos do cotidiano brasileiro.
|
| 18 |
+
- NUNCA julgue o aluno por não saber. Reforce que está ali para ajudar.
|
| 19 |
+
- Se a pergunta sair do escopo educacional, redirecione com gentileza.
|
| 20 |
+
- Use ferramentas (tools) quando precisar consultar conteúdo da base
|
| 21 |
+
curricular ou calcular algo. Não invente fatos pedagógicos.
|
| 22 |
+
|
| 23 |
+
tools:
|
| 24 |
+
- knowledge_base_query
|
| 25 |
+
- calculator
|
| 26 |
+
- grade_level_classifier
|
| 27 |
+
|
| 28 |
+
example_prompts:
|
| 29 |
+
- "Não entendi fração equivalente. Pode me ensinar com um exemplo simples?"
|
| 30 |
+
- "Como dividir 3/4 por 2/5? Me explica passo a passo."
|
| 31 |
+
- "Estou no 8º ano e tenho dificuldade em equação do 1º grau."
|
| 32 |
+
- "Como organizar meus estudos para a prova de matemática de quinta?"
|
| 33 |
+
|
| 34 |
+
knowledge_base:
|
| 35 |
+
- id: "kb_matematica_fundamental"
|
| 36 |
+
title: "Matemática Ensino Fundamental"
|
| 37 |
+
content: |
|
| 38 |
+
Frações equivalentes: duas frações são equivalentes quando
|
| 39 |
+
representam a mesma quantidade. Exemplo: 1/2 = 2/4 = 4/8.
|
| 40 |
+
Para verificar, multiplique cruzado: a/b = c/d se a*d = b*c.
|
| 41 |
+
|
| 42 |
+
Divisão de frações: mantenha a primeira, inverta a segunda,
|
| 43 |
+
multiplique. Exemplo: 3/4 ÷ 2/5 = 3/4 × 5/2 = 15/8.
|
| 44 |
+
|
| 45 |
+
- id: "kb_matematica_medio"
|
| 46 |
+
title: "Matemática Ensino Médio"
|
| 47 |
+
content: |
|
| 48 |
+
Equação do 1º grau: ax + b = 0, onde a ≠ 0. Solução: x = -b/a.
|
| 49 |
+
Equação do 2º grau: ax² + bx + c = 0. Fórmula de Bhaskara:
|
| 50 |
+
x = (-b ± √(b²-4ac)) / 2a.
|
| 51 |
+
|
| 52 |
+
- id: "kb_estudos_estrategia"
|
| 53 |
+
title: "Estratégias de estudo"
|
| 54 |
+
content: |
|
| 55 |
+
Pomodoro adaptado: 25 min foco + 5 min pausa. Para escolas
|
| 56 |
+
em vulnerabilidade, sugerir blocos de 20+5 dada a maior
|
| 57 |
+
variabilidade de ambiente em casa. Revisão espaçada:
|
| 58 |
+
revisar conteúdo 1 dia, 3 dias, 1 semana depois.
|
| 59 |
+
|
| 60 |
+
designmind:
|
| 61 |
+
name: "DesignMind AI"
|
| 62 |
+
description: "Multi-agente de Design Thinking para PMEs brasileiras"
|
| 63 |
+
persona: |
|
| 64 |
+
Você é o DesignMind AI, um facilitador de Design Thinking para
|
| 65 |
+
pequenas e médias empresas brasileiras. Você guia o usuário
|
| 66 |
+
pelas 5 fases: Empatizar, Definir, Idear, Prototipar, Testar.
|
| 67 |
+
|
| 68 |
+
Princípios:
|
| 69 |
+
- Tom profissional mas acessível. PMEs brasileiras não têm
|
| 70 |
+
consultoria cara — você é a alternativa.
|
| 71 |
+
- SEMPRE identifique em qual fase o usuário está antes de sugerir.
|
| 72 |
+
- Use ferramentas para validar fase, gerar prompts de ideação,
|
| 73 |
+
ou estruturar um teste com clientes.
|
| 74 |
+
- Saídas precisam ser ACIONÁVEIS. Frases vagas ("converse com
|
| 75 |
+
seu cliente") são proibidas. Dê passos concretos.
|
| 76 |
+
- Se o problema sair de DT (ex: questão jurídica, financeira),
|
| 77 |
+
redirecione para consultor especializado.
|
| 78 |
+
|
| 79 |
+
tools:
|
| 80 |
+
- design_phase_validator
|
| 81 |
+
- knowledge_base_query
|
| 82 |
+
- ideation_prompt_generator
|
| 83 |
+
|
| 84 |
+
example_prompts:
|
| 85 |
+
- "Tenho uma loja de doces em SP e quero entender por que clientes não voltam."
|
| 86 |
+
- "Já entrevistei 5 clientes. Como sintetizar insights?"
|
| 87 |
+
- "Preciso gerar ideias de novos sabores. Me ajude com brainstorm estruturado."
|
| 88 |
+
- "Como testar um sabor novo sem gastar muito em produção?"
|
| 89 |
+
|
| 90 |
+
knowledge_base:
|
| 91 |
+
- id: "kb_dt_empatizar"
|
| 92 |
+
title: "Fase 1: Empatizar"
|
| 93 |
+
content: |
|
| 94 |
+
Empatizar = entender profundamente o usuário. Ferramentas:
|
| 95 |
+
entrevistas qualitativas (5-7 pessoas), observação direta
|
| 96 |
+
(shadowing), mapa de empatia. Para PMEs: comece pelos 3
|
| 97 |
+
clientes que mais frequentam e os 3 que pararam de comprar.
|
| 98 |
+
|
| 99 |
+
- id: "kb_dt_definir"
|
| 100 |
+
title: "Fase 2: Definir"
|
| 101 |
+
content: |
|
| 102 |
+
Definir = transformar dados de empatia em problema claro.
|
| 103 |
+
Use Point of View: "[usuário] precisa de [necessidade]
|
| 104 |
+
porque [insight surpreendente]". Evite definir problema
|
| 105 |
+
como "falta marketing" — isso é solução disfarçada.
|
| 106 |
+
|
| 107 |
+
- id: "kb_dt_idear"
|
| 108 |
+
title: "Fase 3: Idear"
|
| 109 |
+
content: |
|
| 110 |
+
Brainstorming estruturado: How Might We (HMW). Exemplo:
|
| 111 |
+
"Como podemos fazer X sem Y?". Quantidade > qualidade
|
| 112 |
+
nesta fase. Meta: 30+ ideias antes de filtrar.
|
| 113 |
+
|
| 114 |
+
- id: "kb_dt_prototipar"
|
| 115 |
+
title: "Fase 4: Prototipar"
|
| 116 |
+
content: |
|
| 117 |
+
Prototipar barato e rápido. PMEs não têm budget de R&D.
|
| 118 |
+
Use: storyboard, mockup em papel, MVP de baixa fidelidade.
|
| 119 |
+
Regra: protótipo deve ser descartável. Se você ama o
|
| 120 |
+
protótipo, está investindo demais.
|
| 121 |
+
|
| 122 |
+
- id: "kb_dt_testar"
|
| 123 |
+
title: "Fase 5: Testar"
|
| 124 |
+
content: |
|
| 125 |
+
Testar com 5-7 usuários reais. Não pergunte "você gostou?"
|
| 126 |
+
— pergunte "o que você fez aqui?". Observe comportamento,
|
| 127 |
+
não opinião. Coletar: o que funcionou, o que confundiu,
|
| 128 |
+
o que surpreendeu.
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dependências do Hugging Face Space
|
| 2 |
+
# Subset enxuto do pyproject.toml — sem FastAPI, sem dev tools, sem typer/rich.
|
| 3 |
+
# Versões fixadas para reprodutibilidade.
|
| 4 |
+
|
| 5 |
+
gradio>=4.44.0
|
| 6 |
+
openai>=1.55.0
|
| 7 |
+
langgraph>=0.2.50
|
| 8 |
+
langchain-core>=0.3.20
|
| 9 |
+
langchain-openai>=0.2.10
|
| 10 |
+
pydantic>=2.9.0
|
| 11 |
+
pydantic-settings>=2.6.0
|
| 12 |
+
pyyaml>=6.0.2
|
| 13 |
+
python-dotenv>=1.0.1
|
src/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Aula 07 · Agentes de IA · Engenharia de IA · Sergio Gaiotto."""
|
| 2 |
+
|
| 3 |
+
__version__ = "1.0.0"
|
src/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (268 Bytes). View file
|
|
|
src/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (249 Bytes). View file
|
|
|
src/__pycache__/cli.cpython-311.pyc
ADDED
|
Binary file (10.9 kB). View file
|
|
|
src/__pycache__/cli.cpython-312.pyc
ADDED
|
Binary file (9.53 kB). View file
|
|
|
src/__pycache__/config.cpython-311.pyc
ADDED
|
Binary file (3.61 kB). View file
|
|
|
src/__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (3.08 kB). View file
|
|
|
src/__pycache__/llm.cpython-311.pyc
ADDED
|
Binary file (2 kB). View file
|
|
|
src/__pycache__/llm.cpython-312.pyc
ADDED
|
Binary file (1.88 kB). View file
|
|
|
src/agents/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Agentes da aplicação."""
|
src/agents/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (187 Bytes). View file
|
|
|
src/agents/__pycache__/multi_agent.cpython-312.pyc
ADDED
|
Binary file (9.32 kB). View file
|
|
|
src/agents/__pycache__/single_agent.cpython-312.pyc
ADDED
|
Binary file (5.12 kB). View file
|
|
|
src/agents/multi_agent.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pipeline multi-agente em LangGraph.
|
| 2 |
+
|
| 3 |
+
Quatro nós em sequência condicional:
|
| 4 |
+
|
| 5 |
+
[planner] → [researcher] → [writer] → [critic]
|
| 6 |
+
↓
|
| 7 |
+
(revisar) ← ← ← (refazer)
|
| 8 |
+
|
| 9 |
+
- planner: decompõe a pergunta em sub-tarefas
|
| 10 |
+
- researcher: usa tools para coletar contexto factual
|
| 11 |
+
- writer: redige resposta final usando o contexto
|
| 12 |
+
- critic: avalia se a resposta atende, decide se refaz ou aprova
|
| 13 |
+
|
| 14 |
+
Este é o padrão "plan-and-execute com self-critique" que aparece em
|
| 15 |
+
sistemas de produção como Devin, Cursor agents, Salesforce Agentforce.
|
| 16 |
+
"""
|
| 17 |
+
import json
|
| 18 |
+
from typing import Annotated, Literal, TypedDict
|
| 19 |
+
|
| 20 |
+
from langgraph.graph import END, START, StateGraph
|
| 21 |
+
from langgraph.graph.message import add_messages
|
| 22 |
+
|
| 23 |
+
from src.config import get_product_config, get_settings
|
| 24 |
+
from src.llm import chat_completion
|
| 25 |
+
from src.tools import execute_tool, get_tools_for_product
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# =============================================================================
|
| 29 |
+
# Estado compartilhado entre os nós
|
| 30 |
+
# =============================================================================
|
| 31 |
+
class GraphState(TypedDict):
|
| 32 |
+
"""Estado que flui entre todos os nós do grafo."""
|
| 33 |
+
|
| 34 |
+
user_query: str
|
| 35 |
+
plan: str
|
| 36 |
+
context: str
|
| 37 |
+
draft_answer: str
|
| 38 |
+
critique: str
|
| 39 |
+
final_answer: str
|
| 40 |
+
iteration: int
|
| 41 |
+
max_iterations: int
|
| 42 |
+
messages: Annotated[list[dict], add_messages]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# =============================================================================
|
| 46 |
+
# Nó 1: Planner
|
| 47 |
+
# =============================================================================
|
| 48 |
+
def planner_node(state: GraphState) -> dict:
|
| 49 |
+
"""Decompõe a pergunta em 2-4 sub-tarefas concretas."""
|
| 50 |
+
config = get_product_config()
|
| 51 |
+
system = (
|
| 52 |
+
f"Você é o PLANNER do agente {config['name']}. "
|
| 53 |
+
"Sua função: receber uma pergunta do usuário e decompor em "
|
| 54 |
+
"2 a 4 sub-tarefas concretas para o agente RESEARCHER executar. "
|
| 55 |
+
"Saída: lista numerada, ATÔMICA, em português. "
|
| 56 |
+
"NÃO responda a pergunta. Apenas planeje."
|
| 57 |
+
)
|
| 58 |
+
msg = chat_completion(
|
| 59 |
+
messages=[
|
| 60 |
+
{"role": "system", "content": system},
|
| 61 |
+
{"role": "user", "content": state["user_query"]},
|
| 62 |
+
],
|
| 63 |
+
temperature=0.3,
|
| 64 |
+
)
|
| 65 |
+
plan = msg.get("content") or "1. Responder diretamente."
|
| 66 |
+
return {"plan": plan}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# =============================================================================
|
| 70 |
+
# Nó 2: Researcher (usa tools)
|
| 71 |
+
# =============================================================================
|
| 72 |
+
def researcher_node(state: GraphState) -> dict:
|
| 73 |
+
"""Executa o plano usando as tools disponíveis para coletar contexto."""
|
| 74 |
+
config = get_product_config()
|
| 75 |
+
tools = get_tools_for_product(config)
|
| 76 |
+
|
| 77 |
+
system = (
|
| 78 |
+
f"Você é o RESEARCHER do agente {config['name']}. "
|
| 79 |
+
"Você recebeu um PLANO de sub-tarefas. Para cada sub-tarefa, "
|
| 80 |
+
"decida se precisa chamar uma tool. Chame tools quando precisar "
|
| 81 |
+
"de fato verificável. NÃO redija a resposta final — apenas colete "
|
| 82 |
+
"o CONTEXTO factual relevante para o WRITER usar depois. "
|
| 83 |
+
"Quando terminar de pesquisar, responda em texto livre resumindo "
|
| 84 |
+
"tudo que você descobriu."
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
messages: list[dict] = [
|
| 88 |
+
{"role": "system", "content": system},
|
| 89 |
+
{
|
| 90 |
+
"role": "user",
|
| 91 |
+
"content": (
|
| 92 |
+
f"PERGUNTA ORIGINAL DO USUÁRIO:\n{state['user_query']}\n\n"
|
| 93 |
+
f"PLANO:\n{state['plan']}\n\n"
|
| 94 |
+
"Execute o plano usando tools quando necessário."
|
| 95 |
+
),
|
| 96 |
+
},
|
| 97 |
+
]
|
| 98 |
+
|
| 99 |
+
# Loop de tools até research final
|
| 100 |
+
max_tool_iterations = 5
|
| 101 |
+
for _ in range(max_tool_iterations):
|
| 102 |
+
msg = chat_completion(
|
| 103 |
+
messages=messages,
|
| 104 |
+
tools=tools if tools else None,
|
| 105 |
+
temperature=0.3,
|
| 106 |
+
)
|
| 107 |
+
messages.append(msg)
|
| 108 |
+
tool_calls = msg.get("tool_calls") or []
|
| 109 |
+
if not tool_calls:
|
| 110 |
+
break
|
| 111 |
+
for tool_call in tool_calls:
|
| 112 |
+
fn = tool_call["function"]
|
| 113 |
+
tool_name = fn["name"]
|
| 114 |
+
try:
|
| 115 |
+
tool_args = json.loads(fn.get("arguments") or "{}")
|
| 116 |
+
except json.JSONDecodeError:
|
| 117 |
+
tool_args = {}
|
| 118 |
+
result = execute_tool(tool_name, tool_args)
|
| 119 |
+
messages.append(
|
| 120 |
+
{"role": "tool", "tool_call_id": tool_call["id"], "content": result}
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# Último msg é o contexto coletado
|
| 124 |
+
context = (messages[-1].get("content") if messages else "") or ""
|
| 125 |
+
return {"context": context}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# =============================================================================
|
| 129 |
+
# Nó 3: Writer
|
| 130 |
+
# =============================================================================
|
| 131 |
+
def writer_node(state: GraphState) -> dict:
|
| 132 |
+
"""Redige a resposta final ao usuário usando o contexto coletado."""
|
| 133 |
+
config = get_product_config()
|
| 134 |
+
system = (
|
| 135 |
+
f"{config['persona']}\n\n"
|
| 136 |
+
"Você está na função WRITER deste sistema multi-agente. "
|
| 137 |
+
"Use o CONTEXTO fornecido para redigir a resposta final ao usuário. "
|
| 138 |
+
"Tom: conforme a persona acima. Não invente fatos que não estejam "
|
| 139 |
+
"no contexto. Se algo está faltando, diga claramente."
|
| 140 |
+
)
|
| 141 |
+
user = (
|
| 142 |
+
f"PERGUNTA DO USUÁRIO:\n{state['user_query']}\n\n"
|
| 143 |
+
f"CONTEXTO COLETADO PELO RESEARCHER:\n{state['context']}\n\n"
|
| 144 |
+
)
|
| 145 |
+
if state.get("critique") and state.get("iteration", 0) > 0:
|
| 146 |
+
user += (
|
| 147 |
+
f"\nCRÍTICA DA VERSÃO ANTERIOR:\n{state['critique']}\n\n"
|
| 148 |
+
"Refaça incorporando os pontos da crítica."
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
msg = chat_completion(
|
| 152 |
+
messages=[
|
| 153 |
+
{"role": "system", "content": system},
|
| 154 |
+
{"role": "user", "content": user},
|
| 155 |
+
],
|
| 156 |
+
temperature=0.6,
|
| 157 |
+
)
|
| 158 |
+
draft = msg.get("content") or ""
|
| 159 |
+
return {"draft_answer": draft}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# =============================================================================
|
| 163 |
+
# Nó 4: Critic
|
| 164 |
+
# =============================================================================
|
| 165 |
+
def critic_node(state: GraphState) -> dict:
|
| 166 |
+
"""Avalia a draft. Decide aprovar ou pedir refação."""
|
| 167 |
+
config = get_product_config()
|
| 168 |
+
system = (
|
| 169 |
+
f"Você é o CRITIC do agente {config['name']}. "
|
| 170 |
+
"Sua função: avaliar se a DRAFT atende à pergunta do usuário de "
|
| 171 |
+
"forma completa, factualmente correta (à luz do CONTEXTO), e "
|
| 172 |
+
"no tom da persona. Devolva JSON com duas chaves: "
|
| 173 |
+
'"verdict" (uma string: "APROVADO" ou "REFAZER") e "feedback" '
|
| 174 |
+
"(uma string em PT-BR explicando o motivo). "
|
| 175 |
+
"Seja RIGOROSO mas justo: aprove quando estiver bom. NÃO peça "
|
| 176 |
+
"refação para detalhes cosméticos."
|
| 177 |
+
)
|
| 178 |
+
user = (
|
| 179 |
+
f"PERGUNTA:\n{state['user_query']}\n\n"
|
| 180 |
+
f"CONTEXTO:\n{state['context']}\n\n"
|
| 181 |
+
f"DRAFT:\n{state['draft_answer']}\n"
|
| 182 |
+
)
|
| 183 |
+
msg = chat_completion(
|
| 184 |
+
messages=[
|
| 185 |
+
{"role": "system", "content": system},
|
| 186 |
+
{"role": "user", "content": user},
|
| 187 |
+
],
|
| 188 |
+
temperature=0.2,
|
| 189 |
+
response_format={"type": "json_object"},
|
| 190 |
+
)
|
| 191 |
+
raw = msg.get("content") or '{"verdict":"APROVADO","feedback":"ok"}'
|
| 192 |
+
try:
|
| 193 |
+
parsed = json.loads(raw)
|
| 194 |
+
critique = parsed.get("feedback", "")
|
| 195 |
+
verdict = parsed.get("verdict", "APROVADO").upper()
|
| 196 |
+
except json.JSONDecodeError:
|
| 197 |
+
critique = raw
|
| 198 |
+
verdict = "APROVADO"
|
| 199 |
+
|
| 200 |
+
new_iteration = state.get("iteration", 0) + 1
|
| 201 |
+
|
| 202 |
+
# Se atingiu max ou aprovou: promove draft para final
|
| 203 |
+
if verdict == "APROVADO" or new_iteration >= state.get("max_iterations", 2):
|
| 204 |
+
return {
|
| 205 |
+
"critique": critique,
|
| 206 |
+
"iteration": new_iteration,
|
| 207 |
+
"final_answer": state["draft_answer"],
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
return {"critique": critique, "iteration": new_iteration}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# =============================================================================
|
| 214 |
+
# Roteamento condicional
|
| 215 |
+
# =============================================================================
|
| 216 |
+
def should_continue(state: GraphState) -> Literal["writer", "end"]:
|
| 217 |
+
"""Decide se volta ao writer (refazer) ou termina."""
|
| 218 |
+
if state.get("final_answer"):
|
| 219 |
+
return "end"
|
| 220 |
+
return "writer"
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
# =============================================================================
|
| 224 |
+
# Construtor do grafo
|
| 225 |
+
# =============================================================================
|
| 226 |
+
def build_graph():
|
| 227 |
+
"""Constrói o StateGraph LangGraph com os 4 nós e o ciclo de revisão."""
|
| 228 |
+
graph = StateGraph(GraphState)
|
| 229 |
+
|
| 230 |
+
graph.add_node("planner", planner_node)
|
| 231 |
+
graph.add_node("researcher", researcher_node)
|
| 232 |
+
graph.add_node("writer", writer_node)
|
| 233 |
+
graph.add_node("critic", critic_node)
|
| 234 |
+
|
| 235 |
+
graph.add_edge(START, "planner")
|
| 236 |
+
graph.add_edge("planner", "researcher")
|
| 237 |
+
graph.add_edge("researcher", "writer")
|
| 238 |
+
graph.add_edge("writer", "critic")
|
| 239 |
+
graph.add_conditional_edges(
|
| 240 |
+
"critic",
|
| 241 |
+
should_continue,
|
| 242 |
+
{"writer": "writer", "end": END},
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
return graph.compile()
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# =============================================================================
|
| 249 |
+
# Entry point conveniente
|
| 250 |
+
# =============================================================================
|
| 251 |
+
def run_multi_agent(user_query: str, max_iterations: int = 2) -> dict:
|
| 252 |
+
"""Roda o pipeline e retorna estado final."""
|
| 253 |
+
app = build_graph()
|
| 254 |
+
initial_state: GraphState = {
|
| 255 |
+
"user_query": user_query,
|
| 256 |
+
"plan": "",
|
| 257 |
+
"context": "",
|
| 258 |
+
"draft_answer": "",
|
| 259 |
+
"critique": "",
|
| 260 |
+
"final_answer": "",
|
| 261 |
+
"iteration": 0,
|
| 262 |
+
"max_iterations": max_iterations,
|
| 263 |
+
"messages": [],
|
| 264 |
+
}
|
| 265 |
+
final_state = app.invoke(initial_state)
|
| 266 |
+
return final_state
|
src/agents/single_agent.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agente single ReAct usando OpenAI tools nativo.
|
| 2 |
+
|
| 3 |
+
Implementação minimalista e didática do padrão ReAct: o LLM raciocina,
|
| 4 |
+
decide qual tool chamar, recebe o resultado, e itera até produzir resposta final.
|
| 5 |
+
|
| 6 |
+
Esta implementação NÃO depende de smolagents (que adiciona uma camada de
|
| 7 |
+
abstração e dependências pesadas). Aqui usamos diretamente o SDK OpenAI,
|
| 8 |
+
o que torna o código mais fácil de auditar e ensinar.
|
| 9 |
+
"""
|
| 10 |
+
import json
|
| 11 |
+
from dataclasses import dataclass, field
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
from src.config import get_product_config, get_settings
|
| 15 |
+
from src.llm import chat_completion
|
| 16 |
+
from src.tools import execute_tool, get_tools_for_product
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class AgentStep:
|
| 21 |
+
"""Um passo do loop ReAct."""
|
| 22 |
+
|
| 23 |
+
step_number: int
|
| 24 |
+
thought: str | None = None
|
| 25 |
+
tool_name: str | None = None
|
| 26 |
+
tool_args: dict | None = None
|
| 27 |
+
tool_result: str | None = None
|
| 28 |
+
is_final: bool = False
|
| 29 |
+
final_answer: str | None = None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass
|
| 33 |
+
class AgentRun:
|
| 34 |
+
"""Resultado de uma execução completa do agente."""
|
| 35 |
+
|
| 36 |
+
user_query: str
|
| 37 |
+
final_answer: str
|
| 38 |
+
steps: list[AgentStep] = field(default_factory=list)
|
| 39 |
+
total_tokens: int = 0
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class SingleAgent:
|
| 43 |
+
"""Agente single ReAct com loop limitado.
|
| 44 |
+
|
| 45 |
+
Limite de iterações evita loops infinitos quando o LLM não converge.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
MAX_ITERATIONS = 8
|
| 49 |
+
|
| 50 |
+
def __init__(self, product_config: dict | None = None):
|
| 51 |
+
self.product_config: dict = product_config or get_product_config()
|
| 52 |
+
self.settings = get_settings()
|
| 53 |
+
self.system_prompt: str = self.product_config["persona"]
|
| 54 |
+
self.tools: list[dict] = get_tools_for_product(self.product_config)
|
| 55 |
+
|
| 56 |
+
def run(self, user_query: str, verbose: bool = False) -> AgentRun:
|
| 57 |
+
"""Executa o loop ReAct até resposta final ou MAX_ITERATIONS."""
|
| 58 |
+
messages: list[dict[str, Any]] = [
|
| 59 |
+
{"role": "system", "content": self.system_prompt},
|
| 60 |
+
{"role": "user", "content": user_query},
|
| 61 |
+
]
|
| 62 |
+
run = AgentRun(user_query=user_query, final_answer="")
|
| 63 |
+
|
| 64 |
+
for i in range(1, self.MAX_ITERATIONS + 1):
|
| 65 |
+
step = AgentStep(step_number=i)
|
| 66 |
+
|
| 67 |
+
response_msg = chat_completion(
|
| 68 |
+
messages=messages,
|
| 69 |
+
tools=self.tools if self.tools else None,
|
| 70 |
+
temperature=0.7,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# Acumula no histórico (formato OpenAI espera tool_calls intactas)
|
| 74 |
+
messages.append(response_msg)
|
| 75 |
+
|
| 76 |
+
tool_calls = response_msg.get("tool_calls") or []
|
| 77 |
+
|
| 78 |
+
if not tool_calls:
|
| 79 |
+
# Sem mais ferramentas → resposta final
|
| 80 |
+
step.is_final = True
|
| 81 |
+
step.final_answer = response_msg.get("content") or ""
|
| 82 |
+
run.steps.append(step)
|
| 83 |
+
run.final_answer = step.final_answer
|
| 84 |
+
if verbose:
|
| 85 |
+
print(f"[passo {i}] FINAL: {step.final_answer[:200]}")
|
| 86 |
+
break
|
| 87 |
+
|
| 88 |
+
# Há chamadas de tools — execute cada uma e siga
|
| 89 |
+
for tool_call in tool_calls:
|
| 90 |
+
fn = tool_call["function"]
|
| 91 |
+
tool_name = fn["name"]
|
| 92 |
+
try:
|
| 93 |
+
tool_args = json.loads(fn.get("arguments") or "{}")
|
| 94 |
+
except json.JSONDecodeError:
|
| 95 |
+
tool_args = {}
|
| 96 |
+
|
| 97 |
+
step.tool_name = tool_name
|
| 98 |
+
step.tool_args = tool_args
|
| 99 |
+
|
| 100 |
+
tool_result = execute_tool(tool_name, tool_args)
|
| 101 |
+
step.tool_result = tool_result
|
| 102 |
+
|
| 103 |
+
messages.append(
|
| 104 |
+
{
|
| 105 |
+
"role": "tool",
|
| 106 |
+
"tool_call_id": tool_call["id"],
|
| 107 |
+
"content": tool_result,
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
if verbose:
|
| 112 |
+
print(f"[passo {i}] tool={tool_name} args={tool_args}")
|
| 113 |
+
print(f"[passo {i}] result={tool_result[:200]}")
|
| 114 |
+
|
| 115 |
+
run.steps.append(step)
|
| 116 |
+
|
| 117 |
+
if not run.final_answer:
|
| 118 |
+
# MAX_ITERATIONS atingido sem resposta final
|
| 119 |
+
run.final_answer = (
|
| 120 |
+
"(O agente atingiu o limite de iterações sem produzir resposta final. "
|
| 121 |
+
"Reformule sua pergunta de forma mais específica.)"
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
return run
|
src/api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI app que serve os agentes via HTTP."""
|
src/api/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (200 Bytes). View file
|
|
|
src/api/__pycache__/app.cpython-312.pyc
ADDED
|
Binary file (7.07 kB). View file
|
|
|
src/api/app.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI app que expõe os agentes via HTTP.
|
| 2 |
+
|
| 3 |
+
Endpoints:
|
| 4 |
+
GET / → info do serviço
|
| 5 |
+
GET /health → healthcheck simples
|
| 6 |
+
GET /product → config do produto ativo
|
| 7 |
+
POST /agent/single → roda agente single ReAct
|
| 8 |
+
POST /agent/multi → roda agente multi LangGraph
|
| 9 |
+
|
| 10 |
+
Rode com: make serve (escuta em 0.0.0.0:8000)
|
| 11 |
+
"""
|
| 12 |
+
from contextlib import asynccontextmanager
|
| 13 |
+
|
| 14 |
+
from fastapi import FastAPI, HTTPException
|
| 15 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
+
from pydantic import BaseModel, Field
|
| 17 |
+
|
| 18 |
+
from src.agents.multi_agent import run_multi_agent
|
| 19 |
+
from src.agents.single_agent import SingleAgent
|
| 20 |
+
from src.config import get_product_config, get_settings
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# =============================================================================
|
| 24 |
+
# Lifespan
|
| 25 |
+
# =============================================================================
|
| 26 |
+
@asynccontextmanager
|
| 27 |
+
async def lifespan(app: FastAPI):
|
| 28 |
+
"""Startup/shutdown da API."""
|
| 29 |
+
settings = get_settings()
|
| 30 |
+
print(f"[API] Produto ativo: {settings.product}")
|
| 31 |
+
print(f"[API] Modelo: {settings.openai_model}")
|
| 32 |
+
yield
|
| 33 |
+
print("[API] Encerrando.")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
app = FastAPI(
|
| 37 |
+
title="Aula 07 · Agent API",
|
| 38 |
+
description="Endpoints para os agentes single e multi.",
|
| 39 |
+
version="1.0.0",
|
| 40 |
+
lifespan=lifespan,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# CORS aberto para uso em sala (Codespaces)
|
| 44 |
+
app.add_middleware(
|
| 45 |
+
CORSMiddleware,
|
| 46 |
+
allow_origins=["*"],
|
| 47 |
+
allow_credentials=True,
|
| 48 |
+
allow_methods=["*"],
|
| 49 |
+
allow_headers=["*"],
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# =============================================================================
|
| 54 |
+
# Schemas
|
| 55 |
+
# =============================================================================
|
| 56 |
+
class AgentRequest(BaseModel):
|
| 57 |
+
query: str = Field(..., min_length=3, description="Pergunta do usuário")
|
| 58 |
+
max_iterations: int = Field(default=2, ge=1, le=4, description="Limite multi-agent")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class StepInfo(BaseModel):
|
| 62 |
+
step_number: int
|
| 63 |
+
tool_name: str | None = None
|
| 64 |
+
tool_args: dict | None = None
|
| 65 |
+
tool_result: str | None = None
|
| 66 |
+
is_final: bool = False
|
| 67 |
+
final_answer: str | None = None
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class AgentResponse(BaseModel):
|
| 71 |
+
product: str
|
| 72 |
+
user_query: str
|
| 73 |
+
final_answer: str
|
| 74 |
+
steps: list[StepInfo] = []
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class MultiAgentResponse(BaseModel):
|
| 78 |
+
product: str
|
| 79 |
+
user_query: str
|
| 80 |
+
plan: str
|
| 81 |
+
context: str
|
| 82 |
+
draft_answer: str
|
| 83 |
+
critique: str
|
| 84 |
+
final_answer: str
|
| 85 |
+
iterations: int
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# =============================================================================
|
| 89 |
+
# Endpoints
|
| 90 |
+
# =============================================================================
|
| 91 |
+
@app.get("/")
|
| 92 |
+
def root() -> dict:
|
| 93 |
+
settings = get_settings()
|
| 94 |
+
return {
|
| 95 |
+
"service": "Aula 07 Agent API",
|
| 96 |
+
"version": "1.0.0",
|
| 97 |
+
"active_product": settings.product,
|
| 98 |
+
"model": settings.openai_model,
|
| 99 |
+
"endpoints": [
|
| 100 |
+
"/health", "/product",
|
| 101 |
+
"/agent/single", "/agent/multi",
|
| 102 |
+
],
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@app.get("/health")
|
| 107 |
+
def health() -> dict:
|
| 108 |
+
return {"status": "ok"}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@app.get("/product")
|
| 112 |
+
def product() -> dict:
|
| 113 |
+
"""Retorna a config do produto ativo (sem persona completa por brevidade)."""
|
| 114 |
+
config = get_product_config()
|
| 115 |
+
return {
|
| 116 |
+
"name": config["name"],
|
| 117 |
+
"description": config["description"],
|
| 118 |
+
"tools": config["tools"],
|
| 119 |
+
"example_prompts": config["example_prompts"],
|
| 120 |
+
"kb_documents": [d["title"] for d in config.get("knowledge_base", [])],
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@app.post("/agent/single", response_model=AgentResponse)
|
| 125 |
+
def agent_single(req: AgentRequest) -> AgentResponse:
|
| 126 |
+
"""Roda o agente single ReAct."""
|
| 127 |
+
try:
|
| 128 |
+
agent = SingleAgent()
|
| 129 |
+
result = agent.run(req.query, verbose=False)
|
| 130 |
+
return AgentResponse(
|
| 131 |
+
product=get_settings().product,
|
| 132 |
+
user_query=result.user_query,
|
| 133 |
+
final_answer=result.final_answer,
|
| 134 |
+
steps=[
|
| 135 |
+
StepInfo(
|
| 136 |
+
step_number=s.step_number,
|
| 137 |
+
tool_name=s.tool_name,
|
| 138 |
+
tool_args=s.tool_args,
|
| 139 |
+
tool_result=s.tool_result[:1000] if s.tool_result else None,
|
| 140 |
+
is_final=s.is_final,
|
| 141 |
+
final_answer=s.final_answer,
|
| 142 |
+
)
|
| 143 |
+
for s in result.steps
|
| 144 |
+
],
|
| 145 |
+
)
|
| 146 |
+
except Exception as exc: # noqa: BLE001
|
| 147 |
+
raise HTTPException(500, detail=str(exc)) from exc
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@app.post("/agent/multi", response_model=MultiAgentResponse)
|
| 151 |
+
def agent_multi(req: AgentRequest) -> MultiAgentResponse:
|
| 152 |
+
"""Roda o agente multi LangGraph (planner → researcher → writer → critic)."""
|
| 153 |
+
try:
|
| 154 |
+
state = run_multi_agent(req.query, max_iterations=req.max_iterations)
|
| 155 |
+
return MultiAgentResponse(
|
| 156 |
+
product=get_settings().product,
|
| 157 |
+
user_query=state.get("user_query", req.query),
|
| 158 |
+
plan=state.get("plan", ""),
|
| 159 |
+
context=state.get("context", "")[:2000],
|
| 160 |
+
draft_answer=state.get("draft_answer", ""),
|
| 161 |
+
critique=state.get("critique", ""),
|
| 162 |
+
final_answer=state.get("final_answer", state.get("draft_answer", "")),
|
| 163 |
+
iterations=state.get("iteration", 0),
|
| 164 |
+
)
|
| 165 |
+
except Exception as exc: # noqa: BLE001
|
| 166 |
+
raise HTTPException(500, detail=str(exc)) from exc
|
src/cli.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI principal da aula. Wrapper Typer sobre todos os entry points.
|
| 2 |
+
|
| 3 |
+
Comandos:
|
| 4 |
+
smoke → testa OpenAI key + imports
|
| 5 |
+
demo → roda um exemplo simples do agente single
|
| 6 |
+
ask → faz uma pergunta ao agente single
|
| 7 |
+
multi → roda o agente multi LangGraph
|
| 8 |
+
serve → inicia FastAPI
|
| 9 |
+
mcp → inicia servidor MCP local
|
| 10 |
+
eval → roda avaliação BFCL local
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import typer
|
| 15 |
+
from rich.console import Console
|
| 16 |
+
from rich.panel import Panel
|
| 17 |
+
from rich.table import Table
|
| 18 |
+
|
| 19 |
+
console = Console()
|
| 20 |
+
app = typer.Typer(help="Aula 07 · CLI dos agentes")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@app.command()
|
| 24 |
+
def smoke() -> None:
|
| 25 |
+
"""Smoke test: imports + chave OpenAI + chamada nano de 1 token."""
|
| 26 |
+
console.print(Panel.fit("Smoke test", style="cyan"))
|
| 27 |
+
|
| 28 |
+
# 1. imports
|
| 29 |
+
try:
|
| 30 |
+
import langgraph # noqa: F401
|
| 31 |
+
import openai # noqa: F401
|
| 32 |
+
from fastapi import FastAPI # noqa: F401
|
| 33 |
+
|
| 34 |
+
console.print(" [green]✓[/green] imports OK")
|
| 35 |
+
except ImportError as exc:
|
| 36 |
+
console.print(f" [red]✗[/red] import falhou: {exc}")
|
| 37 |
+
raise typer.Exit(1) from exc
|
| 38 |
+
|
| 39 |
+
# 2. settings
|
| 40 |
+
try:
|
| 41 |
+
from src.config import get_product_config, get_settings
|
| 42 |
+
|
| 43 |
+
settings = get_settings()
|
| 44 |
+
product = get_product_config()
|
| 45 |
+
console.print(f" [green]✓[/green] produto ativo: {product['name']}")
|
| 46 |
+
console.print(f" [green]✓[/green] modelo: {settings.openai_model}")
|
| 47 |
+
except Exception as exc: # noqa: BLE001
|
| 48 |
+
console.print(f" [red]✗[/red] config falhou: {exc}")
|
| 49 |
+
raise typer.Exit(1) from exc
|
| 50 |
+
|
| 51 |
+
# 3. chamada nano
|
| 52 |
+
try:
|
| 53 |
+
from src.llm import chat_completion
|
| 54 |
+
|
| 55 |
+
msg = chat_completion(
|
| 56 |
+
messages=[{"role": "user", "content": "Responda só com a palavra: pong"}],
|
| 57 |
+
model="gpt-4.1-nano",
|
| 58 |
+
temperature=0,
|
| 59 |
+
)
|
| 60 |
+
content = (msg.get("content") or "").strip()
|
| 61 |
+
if "pong" in content.lower():
|
| 62 |
+
console.print(f" [green]✓[/green] OpenAI respondeu: '{content}'")
|
| 63 |
+
else:
|
| 64 |
+
console.print(f" [yellow]?[/yellow] OpenAI respondeu (inesperado): '{content}'")
|
| 65 |
+
except Exception as exc: # noqa: BLE001
|
| 66 |
+
console.print(f" [red]✗[/red] chamada OpenAI falhou: {exc}")
|
| 67 |
+
raise typer.Exit(1) from exc
|
| 68 |
+
|
| 69 |
+
console.print(Panel.fit("[bold green]Smoke test OK[/bold green]"))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@app.command()
|
| 73 |
+
def demo() -> None:
|
| 74 |
+
"""Roda um exemplo simples (primeira pergunta do products.yaml)."""
|
| 75 |
+
from src.agents.single_agent import SingleAgent
|
| 76 |
+
from src.config import get_product_config
|
| 77 |
+
|
| 78 |
+
config = get_product_config()
|
| 79 |
+
query = config["example_prompts"][0]
|
| 80 |
+
|
| 81 |
+
console.print(Panel.fit(f"Demo · {config['name']}", style="cyan"))
|
| 82 |
+
console.print(f"[bold]Pergunta:[/bold] {query}\n")
|
| 83 |
+
|
| 84 |
+
agent = SingleAgent(product_config=config)
|
| 85 |
+
result = agent.run(query, verbose=False)
|
| 86 |
+
|
| 87 |
+
_print_run_table(result)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@app.command()
|
| 91 |
+
def ask(query: str = typer.Argument(..., help="Pergunta para o agente")) -> None:
|
| 92 |
+
"""Faz uma pergunta ao agente single ReAct."""
|
| 93 |
+
from src.agents.single_agent import SingleAgent
|
| 94 |
+
|
| 95 |
+
console.print(Panel.fit(f"Pergunta: {query}", style="cyan"))
|
| 96 |
+
agent = SingleAgent()
|
| 97 |
+
result = agent.run(query, verbose=False)
|
| 98 |
+
_print_run_table(result)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@app.command()
|
| 102 |
+
def multi(query: str = typer.Argument(..., help="Pergunta para o agente multi")) -> None:
|
| 103 |
+
"""Roda o agente multi (LangGraph: planner → researcher → writer → critic)."""
|
| 104 |
+
from src.agents.multi_agent import run_multi_agent
|
| 105 |
+
|
| 106 |
+
console.print(Panel.fit(f"Multi-agente · Pergunta: {query}", style="cyan"))
|
| 107 |
+
state = run_multi_agent(query)
|
| 108 |
+
|
| 109 |
+
console.print(Panel(state.get("plan", ""), title="1. PLAN", style="blue"))
|
| 110 |
+
console.print(
|
| 111 |
+
Panel((state.get("context", "")[:800] + "..."), title="2. CONTEXT", style="magenta")
|
| 112 |
+
)
|
| 113 |
+
console.print(Panel(state.get("draft_answer", ""), title="3. DRAFT", style="yellow"))
|
| 114 |
+
console.print(Panel(state.get("critique", ""), title="4. CRITIQUE", style="red"))
|
| 115 |
+
console.print(
|
| 116 |
+
Panel.fit(state.get("final_answer", state.get("draft_answer", "")),
|
| 117 |
+
title="RESPOSTA FINAL", style="green")
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@app.command()
|
| 122 |
+
def serve() -> None:
|
| 123 |
+
"""Inicia o FastAPI em 0.0.0.0:8000."""
|
| 124 |
+
import uvicorn
|
| 125 |
+
|
| 126 |
+
from src.config import get_settings
|
| 127 |
+
|
| 128 |
+
settings = get_settings()
|
| 129 |
+
console.print(f"[cyan]Iniciando API em http://{settings.api_host}:{settings.api_port}[/cyan]")
|
| 130 |
+
uvicorn.run("src.api.app:app", host=settings.api_host, port=settings.api_port, reload=False)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@app.command()
|
| 134 |
+
def mcp() -> None:
|
| 135 |
+
"""Inicia o servidor MCP local mock."""
|
| 136 |
+
import uvicorn
|
| 137 |
+
|
| 138 |
+
from src.config import get_settings
|
| 139 |
+
|
| 140 |
+
settings = get_settings()
|
| 141 |
+
console.print(f"[cyan]Iniciando MCP em http://{settings.mcp_host}:{settings.mcp_port}[/cyan]")
|
| 142 |
+
uvicorn.run("src.mcp.server:app", host=settings.mcp_host, port=settings.mcp_port, reload=False)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@app.command()
|
| 146 |
+
def eval() -> None:
|
| 147 |
+
"""Roda avaliação BFCL local."""
|
| 148 |
+
from evals.run_bfcl import run as run_bfcl
|
| 149 |
+
|
| 150 |
+
run_bfcl()
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _print_run_table(result) -> None:
|
| 154 |
+
"""Pretty print do AgentRun."""
|
| 155 |
+
table = Table(title="Trace do agente")
|
| 156 |
+
table.add_column("Passo", style="cyan", width=6)
|
| 157 |
+
table.add_column("Tipo", style="magenta", width=10)
|
| 158 |
+
table.add_column("Detalhe", style="white")
|
| 159 |
+
|
| 160 |
+
for step in result.steps:
|
| 161 |
+
if step.is_final:
|
| 162 |
+
table.add_row(str(step.step_number), "FINAL", step.final_answer[:300] or "")
|
| 163 |
+
else:
|
| 164 |
+
detail = f"tool={step.tool_name} args={step.tool_args}\n result={(step.tool_result or '')[:200]}"
|
| 165 |
+
table.add_row(str(step.step_number), "TOOL", detail)
|
| 166 |
+
console.print(table)
|
| 167 |
+
console.print(Panel.fit(result.final_answer, title="Resposta final", style="green"))
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
app()
|
src/config.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configurações centralizadas da aplicação.
|
| 2 |
+
|
| 3 |
+
Carrega de variáveis de ambiente (.env) e do arquivo config/products.yaml.
|
| 4 |
+
Validado por pydantic — falha cedo se algo crítico estiver faltando.
|
| 5 |
+
"""
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Literal
|
| 9 |
+
|
| 10 |
+
import yaml
|
| 11 |
+
from pydantic import Field
|
| 12 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 13 |
+
|
| 14 |
+
ROOT_DIR = Path(__file__).resolve().parent.parent
|
| 15 |
+
CONFIG_DIR = ROOT_DIR / "config"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Settings(BaseSettings):
|
| 19 |
+
"""Variáveis de ambiente da aplicação."""
|
| 20 |
+
|
| 21 |
+
# OpenAI
|
| 22 |
+
openai_api_key: str = Field(..., description="Chave da OpenAI (sk-...)")
|
| 23 |
+
openai_model: str = Field(default="gpt-4.1-mini")
|
| 24 |
+
openai_judge_model: str = Field(default="gpt-4.1")
|
| 25 |
+
|
| 26 |
+
# Produto ativo
|
| 27 |
+
product: Literal["educiacao", "designmind"] = Field(default="educiacao")
|
| 28 |
+
|
| 29 |
+
# API
|
| 30 |
+
api_host: str = Field(default="0.0.0.0")
|
| 31 |
+
api_port: int = Field(default=8000)
|
| 32 |
+
|
| 33 |
+
# MCP
|
| 34 |
+
mcp_host: str = Field(default="127.0.0.1")
|
| 35 |
+
mcp_port: int = Field(default=8001)
|
| 36 |
+
|
| 37 |
+
# Logging
|
| 38 |
+
log_level: str = Field(default="INFO")
|
| 39 |
+
|
| 40 |
+
model_config = SettingsConfigDict(
|
| 41 |
+
env_file=ROOT_DIR / ".env",
|
| 42 |
+
env_file_encoding="utf-8",
|
| 43 |
+
case_sensitive=False,
|
| 44 |
+
extra="ignore",
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@lru_cache
|
| 49 |
+
def get_settings() -> Settings:
|
| 50 |
+
"""Singleton de Settings. Carrega uma vez e reusa."""
|
| 51 |
+
return Settings() # type: ignore[call-arg]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@lru_cache
|
| 55 |
+
def get_product_config() -> dict:
|
| 56 |
+
"""Carrega config do produto ativo a partir do config/products.yaml."""
|
| 57 |
+
settings = get_settings()
|
| 58 |
+
products_file = CONFIG_DIR / "products.yaml"
|
| 59 |
+
with products_file.open(encoding="utf-8") as f:
|
| 60 |
+
all_products = yaml.safe_load(f)
|
| 61 |
+
|
| 62 |
+
if settings.product not in all_products:
|
| 63 |
+
raise ValueError(
|
| 64 |
+
f"Produto '{settings.product}' não encontrado no products.yaml. "
|
| 65 |
+
f"Opções: {list(all_products.keys())}"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
return all_products[settings.product]
|
src/llm.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cliente OpenAI compartilhado.
|
| 2 |
+
|
| 3 |
+
Um único OpenAI() reusado em toda a aplicação. Cobre tanto LLM quanto juiz.
|
| 4 |
+
"""
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
|
| 7 |
+
from openai import OpenAI
|
| 8 |
+
|
| 9 |
+
from src.config import get_settings
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@lru_cache
|
| 13 |
+
def get_openai_client() -> OpenAI:
|
| 14 |
+
"""Singleton do cliente OpenAI."""
|
| 15 |
+
settings = get_settings()
|
| 16 |
+
return OpenAI(api_key=settings.openai_api_key)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def chat_completion(
|
| 20 |
+
messages: list[dict],
|
| 21 |
+
model: str | None = None,
|
| 22 |
+
tools: list[dict] | None = None,
|
| 23 |
+
tool_choice: str | dict = "auto",
|
| 24 |
+
temperature: float = 0.7,
|
| 25 |
+
response_format: dict | None = None,
|
| 26 |
+
) -> dict:
|
| 27 |
+
"""Wrapper sobre chat.completions.create com defaults sensatos.
|
| 28 |
+
|
| 29 |
+
Retorna o primeiro `choice.message` como dict (já serializado).
|
| 30 |
+
"""
|
| 31 |
+
client = get_openai_client()
|
| 32 |
+
settings = get_settings()
|
| 33 |
+
|
| 34 |
+
kwargs: dict = {
|
| 35 |
+
"model": model or settings.openai_model,
|
| 36 |
+
"messages": messages,
|
| 37 |
+
"temperature": temperature,
|
| 38 |
+
}
|
| 39 |
+
if tools:
|
| 40 |
+
kwargs["tools"] = tools
|
| 41 |
+
kwargs["tool_choice"] = tool_choice
|
| 42 |
+
if response_format:
|
| 43 |
+
kwargs["response_format"] = response_format
|
| 44 |
+
|
| 45 |
+
response = client.chat.completions.create(**kwargs)
|
| 46 |
+
message = response.choices[0].message
|
| 47 |
+
return message.model_dump()
|
src/mcp/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""MCP local mock — protocolo MCP da Anthropic via FastAPI."""
|
src/mcp/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (219 Bytes). View file
|
|
|
src/mcp/__pycache__/server.cpython-312.pyc
ADDED
|
Binary file (4.27 kB). View file
|
|
|
src/mcp/server.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Servidor MCP local (mock).
|
| 2 |
+
|
| 3 |
+
Implementação minimalista do protocolo MCP (Model Context Protocol) da
|
| 4 |
+
Anthropic. NÃO é uma implementação completa do spec — é didática.
|
| 5 |
+
|
| 6 |
+
Expõe duas tools via endpoints HTTP:
|
| 7 |
+
POST /mcp/list_tools → lista das tools disponíveis (schema)
|
| 8 |
+
POST /mcp/call_tool → executa uma tool e retorna resultado
|
| 9 |
+
|
| 10 |
+
O aluno aprende como um agente comunicaria com servidor MCP REAL
|
| 11 |
+
(GitHub, Slack, Filesystem, etc.) usando o mesmo padrão de chamada.
|
| 12 |
+
|
| 13 |
+
Rode com: make mcp (escuta em 127.0.0.1:8001)
|
| 14 |
+
"""
|
| 15 |
+
from datetime import datetime, timezone
|
| 16 |
+
|
| 17 |
+
from fastapi import FastAPI, HTTPException
|
| 18 |
+
from pydantic import BaseModel
|
| 19 |
+
|
| 20 |
+
app = FastAPI(
|
| 21 |
+
title="Aula 07 · MCP Local Mock",
|
| 22 |
+
description="Servidor MCP didático com 2 tools de exemplo.",
|
| 23 |
+
version="1.0.0",
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# =============================================================================
|
| 28 |
+
# Tools disponíveis no MCP local
|
| 29 |
+
# =============================================================================
|
| 30 |
+
MCP_TOOLS = {
|
| 31 |
+
"current_datetime": {
|
| 32 |
+
"name": "current_datetime",
|
| 33 |
+
"description": "Retorna data e hora atuais em UTC e horário de Brasília.",
|
| 34 |
+
"inputSchema": {
|
| 35 |
+
"type": "object",
|
| 36 |
+
"properties": {},
|
| 37 |
+
"required": [],
|
| 38 |
+
},
|
| 39 |
+
},
|
| 40 |
+
"format_brazilian_currency": {
|
| 41 |
+
"name": "format_brazilian_currency",
|
| 42 |
+
"description": "Formata um número como moeda brasileira (R$).",
|
| 43 |
+
"inputSchema": {
|
| 44 |
+
"type": "object",
|
| 45 |
+
"properties": {
|
| 46 |
+
"amount": {"type": "number", "description": "Valor numérico"},
|
| 47 |
+
},
|
| 48 |
+
"required": ["amount"],
|
| 49 |
+
},
|
| 50 |
+
},
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# =============================================================================
|
| 55 |
+
# Implementações das tools
|
| 56 |
+
# =============================================================================
|
| 57 |
+
def _impl_current_datetime() -> dict:
|
| 58 |
+
now_utc = datetime.now(timezone.utc)
|
| 59 |
+
# Brasília = UTC-3
|
| 60 |
+
from datetime import timedelta
|
| 61 |
+
|
| 62 |
+
now_brt = now_utc - timedelta(hours=3)
|
| 63 |
+
return {
|
| 64 |
+
"utc": now_utc.strftime("%Y-%m-%d %H:%M:%S UTC"),
|
| 65 |
+
"brasilia": now_brt.strftime("%Y-%m-%d %H:%M:%S BRT"),
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _impl_format_brazilian_currency(amount: float) -> dict:
|
| 70 |
+
formatted = f"R$ {amount:,.2f}".replace(",", "X").replace(".", ",").replace("X", ".")
|
| 71 |
+
return {"formatted": formatted, "raw": amount}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
_TOOL_IMPLEMENTATIONS = {
|
| 75 |
+
"current_datetime": _impl_current_datetime,
|
| 76 |
+
"format_brazilian_currency": _impl_format_brazilian_currency,
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# =============================================================================
|
| 81 |
+
# Endpoints MCP
|
| 82 |
+
# =============================================================================
|
| 83 |
+
class CallToolRequest(BaseModel):
|
| 84 |
+
name: str
|
| 85 |
+
arguments: dict
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@app.get("/")
|
| 89 |
+
def root() -> dict:
|
| 90 |
+
return {
|
| 91 |
+
"service": "Aula 07 MCP Local Mock",
|
| 92 |
+
"protocol": "MCP-like",
|
| 93 |
+
"endpoints": ["/mcp/list_tools", "/mcp/call_tool"],
|
| 94 |
+
"tools_available": list(MCP_TOOLS.keys()),
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@app.post("/mcp/list_tools")
|
| 99 |
+
def list_tools() -> dict:
|
| 100 |
+
"""Retorna lista de tools no formato MCP."""
|
| 101 |
+
return {"tools": list(MCP_TOOLS.values())}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@app.post("/mcp/call_tool")
|
| 105 |
+
def call_tool(req: CallToolRequest) -> dict:
|
| 106 |
+
"""Executa uma tool e retorna o resultado."""
|
| 107 |
+
if req.name not in _TOOL_IMPLEMENTATIONS:
|
| 108 |
+
raise HTTPException(404, detail=f"Tool '{req.name}' não encontrada")
|
| 109 |
+
try:
|
| 110 |
+
impl = _TOOL_IMPLEMENTATIONS[req.name]
|
| 111 |
+
result = impl(**req.arguments)
|
| 112 |
+
return {"name": req.name, "result": result, "isError": False}
|
| 113 |
+
except Exception as exc: # noqa: BLE001
|
| 114 |
+
return {"name": req.name, "result": str(exc), "isError": True}
|
src/tools/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Registry de ferramentas disponíveis para os agentes.
|
| 2 |
+
|
| 3 |
+
Cada tool é uma função pura com docstring e type hints.
|
| 4 |
+
A função `get_tools_for_product` retorna o subset configurado no products.yaml.
|
| 5 |
+
"""
|
| 6 |
+
from src.tools.calculator import calculator_tool, run_calculator
|
| 7 |
+
from src.tools.design_validator import design_phase_validator_tool, run_design_phase_validator
|
| 8 |
+
from src.tools.grade_classifier import grade_level_classifier_tool, run_grade_level_classifier
|
| 9 |
+
from src.tools.ideation_generator import (
|
| 10 |
+
ideation_prompt_generator_tool,
|
| 11 |
+
run_ideation_prompt_generator,
|
| 12 |
+
)
|
| 13 |
+
from src.tools.knowledge_base import knowledge_base_query_tool, run_knowledge_base_query
|
| 14 |
+
|
| 15 |
+
# Mapeamento nome → (schema OpenAI, função executora)
|
| 16 |
+
TOOL_REGISTRY: dict[str, tuple[dict, callable]] = {
|
| 17 |
+
"calculator": (calculator_tool, run_calculator),
|
| 18 |
+
"knowledge_base_query": (knowledge_base_query_tool, run_knowledge_base_query),
|
| 19 |
+
"grade_level_classifier": (grade_level_classifier_tool, run_grade_level_classifier),
|
| 20 |
+
"design_phase_validator": (design_phase_validator_tool, run_design_phase_validator),
|
| 21 |
+
"ideation_prompt_generator": (ideation_prompt_generator_tool, run_ideation_prompt_generator),
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_tools_for_product(product_config: dict) -> list[dict]:
|
| 26 |
+
"""Retorna os schemas OpenAI das tools habilitadas para o produto."""
|
| 27 |
+
enabled = product_config.get("tools", [])
|
| 28 |
+
schemas = []
|
| 29 |
+
for tool_name in enabled:
|
| 30 |
+
if tool_name not in TOOL_REGISTRY:
|
| 31 |
+
raise ValueError(f"Tool '{tool_name}' não está no registry.")
|
| 32 |
+
schema, _ = TOOL_REGISTRY[tool_name]
|
| 33 |
+
schemas.append(schema)
|
| 34 |
+
return schemas
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def execute_tool(tool_name: str, arguments: dict) -> str:
|
| 38 |
+
"""Executa uma tool pelo nome com os argumentos fornecidos.
|
| 39 |
+
|
| 40 |
+
Retorna sempre string (formato esperado pelo OpenAI tool_result).
|
| 41 |
+
"""
|
| 42 |
+
if tool_name not in TOOL_REGISTRY:
|
| 43 |
+
return f"ERRO: tool '{tool_name}' não existe. Tools disponíveis: {list(TOOL_REGISTRY)}"
|
| 44 |
+
_, fn = TOOL_REGISTRY[tool_name]
|
| 45 |
+
try:
|
| 46 |
+
return fn(**arguments)
|
| 47 |
+
except Exception as exc: # noqa: BLE001
|
| 48 |
+
return f"ERRO ao executar '{tool_name}': {exc}"
|
src/tools/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (2.57 kB). View file
|
|
|
src/tools/__pycache__/calculator.cpython-312.pyc
ADDED
|
Binary file (3.9 kB). View file
|
|
|
src/tools/__pycache__/design_validator.cpython-312.pyc
ADDED
|
Binary file (3.79 kB). View file
|
|
|
src/tools/__pycache__/grade_classifier.cpython-312.pyc
ADDED
|
Binary file (3.47 kB). View file
|
|
|
src/tools/__pycache__/ideation_generator.cpython-312.pyc
ADDED
|
Binary file (2.93 kB). View file
|
|
|
src/tools/__pycache__/knowledge_base.cpython-312.pyc
ADDED
|
Binary file (5.4 kB). View file
|
|
|
src/tools/calculator.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tool: calculadora aritmética segura.
|
| 2 |
+
|
| 3 |
+
Avalia expressões matemáticas básicas (+, -, *, /, **, parênteses).
|
| 4 |
+
Usada principalmente pelo EducIAção em exemplos de matemática.
|
| 5 |
+
"""
|
| 6 |
+
import ast
|
| 7 |
+
import operator
|
| 8 |
+
|
| 9 |
+
# Operadores permitidos
|
| 10 |
+
_OPS: dict = {
|
| 11 |
+
ast.Add: operator.add,
|
| 12 |
+
ast.Sub: operator.sub,
|
| 13 |
+
ast.Mult: operator.mul,
|
| 14 |
+
ast.Div: operator.truediv,
|
| 15 |
+
ast.Pow: operator.pow,
|
| 16 |
+
ast.Mod: operator.mod,
|
| 17 |
+
ast.FloorDiv: operator.floordiv,
|
| 18 |
+
ast.USub: operator.neg,
|
| 19 |
+
ast.UAdd: operator.pos,
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _safe_eval(node: ast.AST) -> float:
|
| 24 |
+
"""Avalia AST de forma segura, sem chamar eval() bruto."""
|
| 25 |
+
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
|
| 26 |
+
return node.value
|
| 27 |
+
if isinstance(node, ast.BinOp):
|
| 28 |
+
op_type = type(node.op)
|
| 29 |
+
if op_type not in _OPS:
|
| 30 |
+
raise ValueError(f"Operador {op_type.__name__} não permitido")
|
| 31 |
+
return _OPS[op_type](_safe_eval(node.left), _safe_eval(node.right))
|
| 32 |
+
if isinstance(node, ast.UnaryOp):
|
| 33 |
+
op_type = type(node.op)
|
| 34 |
+
if op_type not in _OPS:
|
| 35 |
+
raise ValueError(f"Operador unário {op_type.__name__} não permitido")
|
| 36 |
+
return _OPS[op_type](_safe_eval(node.operand))
|
| 37 |
+
raise ValueError(f"Nó AST não permitido: {type(node).__name__}")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def run_calculator(expression: str) -> str:
|
| 41 |
+
"""Avalia uma expressão matemática e retorna string formatada."""
|
| 42 |
+
try:
|
| 43 |
+
tree = ast.parse(expression, mode="eval")
|
| 44 |
+
result = _safe_eval(tree.body)
|
| 45 |
+
# Formato: inteiro se possível, senão float com 6 casas
|
| 46 |
+
if isinstance(result, float) and result.is_integer():
|
| 47 |
+
result = int(result)
|
| 48 |
+
elif isinstance(result, float):
|
| 49 |
+
result = round(result, 6)
|
| 50 |
+
return f"{expression} = {result}"
|
| 51 |
+
except (SyntaxError, ValueError, ZeroDivisionError) as exc:
|
| 52 |
+
return f"ERRO ao calcular '{expression}': {exc}"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
calculator_tool: dict = {
|
| 56 |
+
"type": "function",
|
| 57 |
+
"function": {
|
| 58 |
+
"name": "calculator",
|
| 59 |
+
"description": (
|
| 60 |
+
"Avalia uma expressão matemática (números, +, -, *, /, **, parênteses). "
|
| 61 |
+
"Use SEMPRE que precisar fazer conta exata. Não invente resultados."
|
| 62 |
+
),
|
| 63 |
+
"parameters": {
|
| 64 |
+
"type": "object",
|
| 65 |
+
"properties": {
|
| 66 |
+
"expression": {
|
| 67 |
+
"type": "string",
|
| 68 |
+
"description": (
|
| 69 |
+
"Expressão matemática em formato Python. "
|
| 70 |
+
"Exemplos: '3/4 * 5/2', '2 ** 10', '(15 + 7) * 3'"
|
| 71 |
+
),
|
| 72 |
+
}
|
| 73 |
+
},
|
| 74 |
+
"required": ["expression"],
|
| 75 |
+
"additionalProperties": False,
|
| 76 |
+
},
|
| 77 |
+
},
|
| 78 |
+
}
|
src/tools/design_validator.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tool: identifica em qual fase de Design Thinking o usuário está.
|
| 2 |
+
|
| 3 |
+
Útil para o agente DesignMind saber se deve guiar o usuário a continuar
|
| 4 |
+
na fase atual ou avançar para a próxima.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
_PHASES: dict[str, list[str]] = {
|
| 8 |
+
"empatizar": [
|
| 9 |
+
"entender cliente", "entrevista", "pesquisa", "observar",
|
| 10 |
+
"por que cliente", "feedback negativo", "queixa", "dor do usuário",
|
| 11 |
+
"não sei o que clientes querem", "shadowing", "mapa de empatia",
|
| 12 |
+
],
|
| 13 |
+
"definir": [
|
| 14 |
+
"sintetizar", "padrão nos dados", "principal problema",
|
| 15 |
+
"ponto de vista", "point of view", "como definir",
|
| 16 |
+
"qual é o problema real", "insight",
|
| 17 |
+
],
|
| 18 |
+
"idear": [
|
| 19 |
+
"brainstorm", "ideias", "como gerar", "soluções possíveis",
|
| 20 |
+
"how might we", "criatividade", "alternativas",
|
| 21 |
+
],
|
| 22 |
+
"prototipar": [
|
| 23 |
+
"protótipo", "mvp", "esboço", "mockup", "construir versão",
|
| 24 |
+
"testar versão", "fazer rápido", "low fidelity",
|
| 25 |
+
],
|
| 26 |
+
"testar": [
|
| 27 |
+
"testar com cliente", "feedback do protótipo", "validar",
|
| 28 |
+
"experimentar", "piloto", "usabilidade",
|
| 29 |
+
],
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def run_design_phase_validator(user_description: str) -> str:
|
| 34 |
+
"""Identifica fase atual do DT e dá orientação curta sobre próximo passo."""
|
| 35 |
+
text = user_description.lower()
|
| 36 |
+
|
| 37 |
+
scores: dict[str, int] = {}
|
| 38 |
+
for phase, keywords in _PHASES.items():
|
| 39 |
+
scores[phase] = sum(1 for kw in keywords if kw in text)
|
| 40 |
+
|
| 41 |
+
if all(v == 0 for v in scores.values()):
|
| 42 |
+
return (
|
| 43 |
+
"FASE: indefinida. Recomendação: pergunte ao usuário em qual fase "
|
| 44 |
+
"ele está (empatizar, definir, idear, prototipar, testar) ou ajude "
|
| 45 |
+
"a começar pela fase 1 (Empatizar)."
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
phase: str = max(scores, key=lambda k: scores[k])
|
| 49 |
+
|
| 50 |
+
next_step: dict[str, str] = {
|
| 51 |
+
"empatizar": "Próximo passo: realizar 5-7 entrevistas qualitativas com clientes reais.",
|
| 52 |
+
"definir": "Próximo passo: usar formato Point of View [usuário] precisa de [necessidade] porque [insight].",
|
| 53 |
+
"idear": "Próximo passo: aplicar How Might We — meta de 30+ ideias antes de filtrar.",
|
| 54 |
+
"prototipar": "Próximo passo: construir protótipo descartável (storyboard, papel, mockup).",
|
| 55 |
+
"testar": "Próximo passo: testar com 5-7 usuários, observe COMPORTAMENTO, não pergunte opinião.",
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
return f"FASE identificada: {phase.upper()}. {next_step[phase]}"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
design_phase_validator_tool: dict = {
|
| 62 |
+
"type": "function",
|
| 63 |
+
"function": {
|
| 64 |
+
"name": "design_phase_validator",
|
| 65 |
+
"description": (
|
| 66 |
+
"Identifica em qual das 5 fases de Design Thinking (Empatizar, "
|
| 67 |
+
"Definir, Idear, Prototipar, Testar) o usuário está. Use SEMPRE "
|
| 68 |
+
"no início da conversa para orientar a próxima ação."
|
| 69 |
+
),
|
| 70 |
+
"parameters": {
|
| 71 |
+
"type": "object",
|
| 72 |
+
"properties": {
|
| 73 |
+
"user_description": {
|
| 74 |
+
"type": "string",
|
| 75 |
+
"description": "Texto que o usuário enviou descrevendo onde está.",
|
| 76 |
+
}
|
| 77 |
+
},
|
| 78 |
+
"required": ["user_description"],
|
| 79 |
+
"additionalProperties": False,
|
| 80 |
+
},
|
| 81 |
+
},
|
| 82 |
+
}
|
src/tools/grade_classifier.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tool: classifica em qual nível escolar um conteúdo se encaixa.
|
| 2 |
+
|
| 3 |
+
Heurística simples baseada em palavras-chave do currículo BNCC.
|
| 4 |
+
Útil quando o aluno descreve um problema sem dizer a série.
|
| 5 |
+
"""
|
| 6 |
+
from typing import Literal
|
| 7 |
+
|
| 8 |
+
_KEYWORDS_FUNDAMENTAL_1: list[str] = [
|
| 9 |
+
"soma", "subtração", "adição", "tabuada", "número natural",
|
| 10 |
+
"alfabeto", "sílaba", "leitura", "primeiro ano", "segundo ano",
|
| 11 |
+
"terceiro ano", "quarto ano", "quinto ano",
|
| 12 |
+
]
|
| 13 |
+
_KEYWORDS_FUNDAMENTAL_2: list[str] = [
|
| 14 |
+
"fração", "decimal", "porcentagem", "regra de três", "mmc", "mdc",
|
| 15 |
+
"área", "perímetro", "ângulo", "polígono", "sexto ano", "sétimo ano",
|
| 16 |
+
"oitavo ano", "nono ano",
|
| 17 |
+
]
|
| 18 |
+
_KEYWORDS_MEDIO: list[str] = [
|
| 19 |
+
"equação", "função", "logaritmo", "trigonometria", "matriz",
|
| 20 |
+
"vetor", "bhaskara", "primeiro grau", "segundo grau", "geometria analítica",
|
| 21 |
+
"ensino médio", "vestibular", "enem",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def run_grade_level_classifier(text: str) -> str:
|
| 26 |
+
"""Classifica em qual etapa da educação básica o tema se encaixa."""
|
| 27 |
+
t = text.lower()
|
| 28 |
+
|
| 29 |
+
def _count(keywords: list[str]) -> int:
|
| 30 |
+
return sum(1 for kw in keywords if kw in t)
|
| 31 |
+
|
| 32 |
+
scores = {
|
| 33 |
+
"fundamental_anos_iniciais": _count(_KEYWORDS_FUNDAMENTAL_1),
|
| 34 |
+
"fundamental_anos_finais": _count(_KEYWORDS_FUNDAMENTAL_2),
|
| 35 |
+
"ensino_medio": _count(_KEYWORDS_MEDIO),
|
| 36 |
+
}
|
| 37 |
+
best: str = max(scores, key=lambda k: scores[k])
|
| 38 |
+
if scores[best] == 0:
|
| 39 |
+
return (
|
| 40 |
+
"Não foi possível classificar com confiança. "
|
| 41 |
+
"Sugestão: pedir ao aluno em qual série/ano ele está."
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
labels: dict[str, str] = {
|
| 45 |
+
"fundamental_anos_iniciais": "Ensino Fundamental · Anos Iniciais (1º-5º)",
|
| 46 |
+
"fundamental_anos_finais": "Ensino Fundamental · Anos Finais (6º-9º)",
|
| 47 |
+
"ensino_medio": "Ensino Médio (1º-3º ano)",
|
| 48 |
+
}
|
| 49 |
+
return (
|
| 50 |
+
f"Nível classificado: {labels[best]} "
|
| 51 |
+
f"(score: {scores[best]} palavras-chave encontradas). "
|
| 52 |
+
f"Adapte sua resposta para este nível."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
grade_level_classifier_tool: dict = {
|
| 57 |
+
"type": "function",
|
| 58 |
+
"function": {
|
| 59 |
+
"name": "grade_level_classifier",
|
| 60 |
+
"description": (
|
| 61 |
+
"Classifica em qual etapa da educação básica brasileira (Fund. Iniciais, "
|
| 62 |
+
"Fund. Finais, Ensino Médio) o conteúdo se encaixa. Use no INÍCIO da "
|
| 63 |
+
"interação quando o aluno não especifica a série."
|
| 64 |
+
),
|
| 65 |
+
"parameters": {
|
| 66 |
+
"type": "object",
|
| 67 |
+
"properties": {
|
| 68 |
+
"text": {
|
| 69 |
+
"type": "string",
|
| 70 |
+
"description": "Texto a classificar (a pergunta do aluno ou tópico).",
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
"required": ["text"],
|
| 74 |
+
"additionalProperties": False,
|
| 75 |
+
},
|
| 76 |
+
},
|
| 77 |
+
}
|
src/tools/ideation_generator.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tool: gera prompts How Might We (HMW) estruturados.
|
| 2 |
+
|
| 3 |
+
Útil na fase Idear: transforma um problema bruto em N prompts de brainstorm.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def run_ideation_prompt_generator(problem: str, count: int = 5) -> str:
|
| 8 |
+
"""Gera 'count' prompts HMW a partir de uma descrição de problema."""
|
| 9 |
+
count = max(3, min(count, 10))
|
| 10 |
+
|
| 11 |
+
templates = [
|
| 12 |
+
"Como podemos {p} sem aumentar custos?",
|
| 13 |
+
"Como podemos {p} em menos de uma semana?",
|
| 14 |
+
"Como podemos {p} envolvendo o cliente desde o início?",
|
| 15 |
+
"Como podemos {p} usando recursos que já temos?",
|
| 16 |
+
"Como podemos {p} de forma que clientes recomendem a amigos?",
|
| 17 |
+
"Como podemos {p} mantendo a identidade da marca?",
|
| 18 |
+
"Como podemos {p} sem depender de tecnologia cara?",
|
| 19 |
+
"Como podemos {p} aprendendo com concorrentes diretos?",
|
| 20 |
+
"Como podemos {p} criando uma experiência memorável?",
|
| 21 |
+
"Como podemos {p} reduzindo o esforço do cliente?",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
selected = templates[:count]
|
| 25 |
+
p_norm = problem.strip().rstrip(".").lower()
|
| 26 |
+
prompts = [t.format(p=p_norm) for t in selected]
|
| 27 |
+
|
| 28 |
+
out = [
|
| 29 |
+
f"Problema base: {problem.strip()}",
|
| 30 |
+
f"\n{count} prompts HMW para brainstorm:",
|
| 31 |
+
]
|
| 32 |
+
out.extend(f" {i}. {prompt}" for i, prompt in enumerate(prompts, 1))
|
| 33 |
+
out.append("\nRegra: gere pelo menos 5 ideias para cada prompt antes de avaliar.")
|
| 34 |
+
return "\n".join(out)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
ideation_prompt_generator_tool: dict = {
|
| 38 |
+
"type": "function",
|
| 39 |
+
"function": {
|
| 40 |
+
"name": "ideation_prompt_generator",
|
| 41 |
+
"description": (
|
| 42 |
+
"Gera prompts How Might We (HMW) estruturados para sessão de "
|
| 43 |
+
"brainstorm. Use na fase Idear do Design Thinking, depois de já "
|
| 44 |
+
"ter um problema bem definido pela fase Definir."
|
| 45 |
+
),
|
| 46 |
+
"parameters": {
|
| 47 |
+
"type": "object",
|
| 48 |
+
"properties": {
|
| 49 |
+
"problem": {
|
| 50 |
+
"type": "string",
|
| 51 |
+
"description": "Problema definido na fase 2. Ex: 'reter clientes recorrentes'",
|
| 52 |
+
},
|
| 53 |
+
"count": {
|
| 54 |
+
"type": "integer",
|
| 55 |
+
"description": "Quantos prompts HMW gerar (3-10, padrão: 5)",
|
| 56 |
+
"default": 5,
|
| 57 |
+
},
|
| 58 |
+
},
|
| 59 |
+
"required": ["problem"],
|
| 60 |
+
"additionalProperties": False,
|
| 61 |
+
},
|
| 62 |
+
},
|
| 63 |
+
}
|
src/tools/knowledge_base.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tool: consulta à base de conhecimento do produto ativo.
|
| 2 |
+
|
| 3 |
+
Implementação simples por palavras-chave (TF-IDF leve em memória).
|
| 4 |
+
Em produção, isso seria substituído por RAG real (Aula 05).
|
| 5 |
+
Aqui o objetivo é ensinar o PADRÃO de tool de busca, não a engine de busca.
|
| 6 |
+
"""
|
| 7 |
+
import re
|
| 8 |
+
from typing import Iterable
|
| 9 |
+
|
| 10 |
+
from src.config import get_product_config
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _stem(token: str) -> str:
|
| 14 |
+
"""Stemming português curto para casar singular/plural.
|
| 15 |
+
|
| 16 |
+
Casos cobertos:
|
| 17 |
+
frações → fraç fração → fraç
|
| 18 |
+
equações → equaç equação → equaç
|
| 19 |
+
ideias → idei ideia → idei
|
| 20 |
+
cliente → client clientes → client
|
| 21 |
+
"""
|
| 22 |
+
if len(token) > 4 and (token.endswith("ções") or token.endswith("ões")):
|
| 23 |
+
# frações → fraç ; equações → equaç ; reflexões → reflex
|
| 24 |
+
return token[:-4] if token.endswith("ções") else token[:-3]
|
| 25 |
+
if len(token) > 4 and (token.endswith("ção") or token.endswith("ão")):
|
| 26 |
+
return token[:-3] if token.endswith("ção") else token[:-2]
|
| 27 |
+
if len(token) > 4 and token.endswith("es"):
|
| 28 |
+
return token[:-2]
|
| 29 |
+
if len(token) > 3 and token.endswith("s"):
|
| 30 |
+
return token[:-1]
|
| 31 |
+
if len(token) > 3 and token.endswith("a"):
|
| 32 |
+
# ideia → idei ; idéia → idéi
|
| 33 |
+
return token[:-1]
|
| 34 |
+
return token
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _tokenize(text: str) -> list[str]:
|
| 38 |
+
"""Tokeniza: minúsculo, remove pontuação, splita, stemiza por aproximação."""
|
| 39 |
+
text = text.lower()
|
| 40 |
+
text = re.sub(r"[^\w\sáéíóúâêôãõàç]", " ", text)
|
| 41 |
+
return [_stem(t) for t in text.split() if len(t) >= 3]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _score(query_tokens: Iterable[str], doc_tokens: Iterable[str]) -> int:
|
| 45 |
+
"""Score = quantidade de tokens stemizados da query presentes no doc."""
|
| 46 |
+
doc_set = set(doc_tokens)
|
| 47 |
+
return sum(1 for t in query_tokens if t in doc_set)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def run_knowledge_base_query(query: str, top_k: int = 2) -> str:
|
| 51 |
+
"""Busca os top_k documentos mais relevantes da KB do produto ativo."""
|
| 52 |
+
config = get_product_config()
|
| 53 |
+
kb = config.get("knowledge_base", [])
|
| 54 |
+
if not kb:
|
| 55 |
+
return "Base de conhecimento vazia para este produto."
|
| 56 |
+
|
| 57 |
+
query_tokens = _tokenize(query)
|
| 58 |
+
|
| 59 |
+
scored: list[tuple[int, dict]] = []
|
| 60 |
+
for doc in kb:
|
| 61 |
+
all_text = f"{doc['title']} {doc['content']}"
|
| 62 |
+
doc_tokens = _tokenize(all_text)
|
| 63 |
+
score = _score(query_tokens, doc_tokens)
|
| 64 |
+
scored.append((score, doc))
|
| 65 |
+
|
| 66 |
+
# Ordena por score desc, mantém só os com score > 0
|
| 67 |
+
scored = sorted(scored, key=lambda x: x[0], reverse=True)
|
| 68 |
+
relevant = [doc for score, doc in scored if score > 0][:top_k]
|
| 69 |
+
|
| 70 |
+
if not relevant:
|
| 71 |
+
return f"Nenhum documento relevante encontrado para a query: '{query}'"
|
| 72 |
+
|
| 73 |
+
out_lines = [f"Encontrados {len(relevant)} documento(s):"]
|
| 74 |
+
for i, doc in enumerate(relevant, 1):
|
| 75 |
+
out_lines.append(f"\n--- Documento {i}: {doc['title']} ---")
|
| 76 |
+
out_lines.append(doc["content"].strip())
|
| 77 |
+
return "\n".join(out_lines)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
knowledge_base_query_tool: dict = {
|
| 81 |
+
"type": "function",
|
| 82 |
+
"function": {
|
| 83 |
+
"name": "knowledge_base_query",
|
| 84 |
+
"description": (
|
| 85 |
+
"Busca conteúdo na base de conhecimento curada do produto. "
|
| 86 |
+
"Use SEMPRE que precisar de fato pedagógico (EducIAção) ou "
|
| 87 |
+
"de orientação de fase de Design Thinking (DesignMind). "
|
| 88 |
+
"NÃO invente conteúdo da KB — sempre busque primeiro."
|
| 89 |
+
),
|
| 90 |
+
"parameters": {
|
| 91 |
+
"type": "object",
|
| 92 |
+
"properties": {
|
| 93 |
+
"query": {
|
| 94 |
+
"type": "string",
|
| 95 |
+
"description": "Palavras-chave da busca. Exemplo: 'fração equivalente'",
|
| 96 |
+
},
|
| 97 |
+
"top_k": {
|
| 98 |
+
"type": "integer",
|
| 99 |
+
"description": "Número de documentos a retornar (padrão: 2)",
|
| 100 |
+
"default": 2,
|
| 101 |
+
},
|
| 102 |
+
},
|
| 103 |
+
"required": ["query"],
|
| 104 |
+
"additionalProperties": False,
|
| 105 |
+
},
|
| 106 |
+
},
|
| 107 |
+
}
|