chatgraph 1.2.6__tar.gz → 1.3.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {chatgraph-1.2.6 → chatgraph-1.3.1}/.env.example +9 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/.gitignore +5 -1
- {chatgraph-1.2.6 → chatgraph-1.3.1}/PKG-INFO +2 -2
- chatgraph-1.3.1/PROGRESS.md +179 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/__init__.py +40 -29
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/auth/credentials.py +6 -2
- chatgraph-1.3.1/chatgraph/bot/chatbot_model.py +390 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/bot/chatbot_router.py +2 -3
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/bot/default_functions.py +1 -1
- chatgraph-1.3.1/chatgraph/cli/__init__.py +234 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/gRPC/gRPCCall.py +34 -35
- chatgraph-1.3.1/chatgraph/history/__init__.py +16 -0
- chatgraph-1.3.1/chatgraph/history/entry.py +58 -0
- chatgraph-1.3.1/chatgraph/history/keys.py +22 -0
- chatgraph-1.3.1/chatgraph/history/store.py +62 -0
- chatgraph-1.3.1/chatgraph/logger/logger.py +3 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/logger/user_logger.py +16 -9
- chatgraph-1.3.1/chatgraph/messages/__init__.py +4 -0
- chatgraph-1.3.1/chatgraph/messages/log_publisher.py +189 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/messages/message_consumer.py +72 -1
- chatgraph-1.3.1/chatgraph/models/__init__.py +13 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/models/actions.py +37 -37
- chatgraph-1.3.1/chatgraph/models/log_envelope.py +97 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/models/userstate.py +9 -2
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/pb/router_pb2.py +53 -52
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/pb/router_pb2_grpc.py +101 -94
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/services/router_http_client.py +102 -52
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/types/background_task.py +8 -5
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/types/usercall.py +115 -2
- {chatgraph-1.2.6 → chatgraph-1.3.1}/pyproject.toml +1 -1
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/integration/test_router_client_integration.py +63 -63
- chatgraph-1.3.1/tests/unit/test_chatbot_app_log_publisher.py +152 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/test_default_guard.py +10 -3
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/test_guard.py +165 -164
- chatgraph-1.3.1/tests/unit/test_history_integration.py +297 -0
- chatgraph-1.3.1/tests/unit/test_history_store.py +278 -0
- chatgraph-1.3.1/tests/unit/test_log_envelope.py +110 -0
- chatgraph-1.3.1/tests/unit/test_log_publisher.py +438 -0
- chatgraph-1.3.1/tests/unit/test_message_consumer_log_publisher.py +129 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/test_models_actions.py +8 -2
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/test_models_message.py +5 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/test_models_userstate.py +21 -2
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/test_router_http_client.py +94 -37
- chatgraph-1.3.1/tests/unit/test_user_logger.py +251 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/test_usercall.py +100 -16
- chatgraph-1.2.6/chatgraph/bot/chatbot_model.py +0 -262
- chatgraph-1.2.6/chatgraph/cli/__init__.py +0 -187
- chatgraph-1.2.6/chatgraph/logger/logger.py +0 -3
- chatgraph-1.2.6/tests/unit/test_user_logger.py +0 -146
- {chatgraph-1.2.6 → chatgraph-1.3.1}/.github/agents/SkillManager.agent.md +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/.github/agents/architect.agent.md +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/.github/agents/code-reviewer.agent.md +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/.github/agents/developer.agent.md +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/.github/copilot-instructions.md +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/.github/skills/chatgraph-framework/SKILL.md +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/.python-version +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/LICENSE +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/README.md +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/bot/default_guard.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/container/container.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/error/chatbot_error.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/error/route_error.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/logger/__init__.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/models/http_responses.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/models/message.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/models/platform_state.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/pb/router.proto +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/services/__init__.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/types/end_types.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/chatgraph/types/route.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/docs/gaps-go-to-python.md +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/docs/gaps-python-to-go.md +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/example.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/example2.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/jsons/voll_return.json +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/poetry.lock +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/__init__.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/integration/__init__.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/integration/conftest.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/__init__.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/conftest.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/test_message_consumer.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/tests/unit/test_models_platform_state.py +0 -0
- {chatgraph-1.2.6 → chatgraph-1.3.1}/uv.lock +0 -0
|
@@ -35,3 +35,12 @@ ROUTER_API_PASSWORD=f078b1cf-b4c8-11f0-b4fe-0242ac140002
|
|
|
35
35
|
# IDs para testes (OPCIONAL - valores padrão serão usados)
|
|
36
36
|
TEST_USER_ID=6107
|
|
37
37
|
TEST_COMPANY_ID=business-tech
|
|
38
|
+
|
|
39
|
+
# Log Publisher (RabbitMQ - opcional)
|
|
40
|
+
# Defina LOG_RABBIT_QUEUE para ativar o envio de logs de erro para fila RabbitMQ.
|
|
41
|
+
# O exchange e routing key padrão seguem o padrão do Go: exchange = vhost, routing key = chatbot.{queue}
|
|
42
|
+
# Com RABBIT_VHOST='/' não existe exchange homônima: cai na exchange
|
|
43
|
+
# default do AMQP e a routing key passa a ser o próprio nome da fila.
|
|
44
|
+
LOG_RABBIT_QUEUE=logs
|
|
45
|
+
LOG_RABBIT_EXCHANGE=chatbot-hml
|
|
46
|
+
# LOG_RABBIT_ROUTING_KEY=chatbot.logs # opcional: default = chatbot.{LOG_RABBIT_QUEUE}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: chatgraph
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.3.1
|
|
4
4
|
Summary: A user-friendly chatbot library
|
|
5
5
|
Project-URL: Homepage, https://github.com/irissonnlima/chatgraph
|
|
6
6
|
Project-URL: Repository, https://github.com/irissonnlima/chatgraph
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# Progresso do Projeto ChatGraph
|
|
2
|
+
|
|
3
|
+
**Última atualização:** 2026-08-05
|
|
4
|
+
|
|
5
|
+
## 1. Visão Geral do Projeto
|
|
6
|
+
|
|
7
|
+
**ChatGraph** é uma biblioteca Python 3.12+ para criação de chatbots interativos e modulares, com suporte a gRPC e RabbitMQ para gerenciamento de fluxos complexos de mensagens.
|
|
8
|
+
|
|
9
|
+
## 2. Arquitetura
|
|
10
|
+
|
|
11
|
+
### Padrão: Modular / Layered
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
chatgraph/
|
|
15
|
+
├── auth/ # Gerenciamento de credenciais
|
|
16
|
+
├── bot/ # Lógica principal do chatbot (ChatbotApp, ChatbotRouter, guards)
|
|
17
|
+
├── cli/ # CLI com Typer
|
|
18
|
+
├── container/ # Container de dependências
|
|
19
|
+
├── error/ # Exceções customizadas
|
|
20
|
+
├── gRPC/ # Comunicação gRPC
|
|
21
|
+
├── history/ # Histórico de mensagens plugável (HistoryStore, MemoryHistoryStore)
|
|
22
|
+
├── logger/ # Logging por usuário e sistema
|
|
23
|
+
├── messages/ # Consumidor RabbitMQ + LogPublisher (envio de erros)
|
|
24
|
+
├── models/ # Modelos de dados (UserState, Message, PlatformState, LogEnvelope, etc.)
|
|
25
|
+
├── pb/ # Arquivos protobuf gerados
|
|
26
|
+
├── services/ # Clientes HTTP (RouterHTTPClient)
|
|
27
|
+
└── types/ # Tipos do framework (Route, UserCall, EndTypes, BackgroundTask)
|
|
28
|
+
tests/
|
|
29
|
+
├── unit/ # Testes unitários com pytest + respx
|
|
30
|
+
└── integration/ # Testes de integração com APIs reais
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## 3. Tecnologias Principais
|
|
34
|
+
|
|
35
|
+
| Categoria | Tecnologia |
|
|
36
|
+
|-----------|-----------|
|
|
37
|
+
| Linguagem | Python 3.12+ |
|
|
38
|
+
| Async | asyncio + aio-pika |
|
|
39
|
+
| Mensageria | RabbitMQ (pika / aio-pika) |
|
|
40
|
+
| gRPC | grpcio + protobuf |
|
|
41
|
+
| HTTP | httpx |
|
|
42
|
+
| CLI | typer |
|
|
43
|
+
| Logging | rich |
|
|
44
|
+
| Testes | pytest + pytest-asyncio + respx |
|
|
45
|
+
| Lint | ruff |
|
|
46
|
+
|
|
47
|
+
## 4. Linha do Tempo
|
|
48
|
+
|
|
49
|
+
### 2026-08
|
|
50
|
+
|
|
51
|
+
| Data | Commit | Descrição |
|
|
52
|
+
|------|--------|-----------|
|
|
53
|
+
| 2026-08-05 | `c24cbbd` | **Fix: acúmulo de `[ChatID: ...]` nos logs:** `ChatIDFilter.filter()` tornado idempotente (verifica `startswith` antes de prefixar); `remove_user_logger()` agora remove instâncias de `ChatIDFilter` antes de fechar handlers; `ChatID.__str__` adicionado (`user_id:company_id`); prefixo hardcoded removido da exceção em `UserCall.__send()`. Testes: `TestChatIDFilter` (3 novos), `test_remove_user_logger_removes_chatid_filters`, `test_remove_then_get_has_exactly_one_chatid_filter`, `test_chatid_str`, `TestSendException`. Revisão: ⚠️ CUIDADO — edge case `startswith` com `record.msg` não-string; teste de exceção poderia validar ausência de prefixo com `assert '[ChatID:' not in ...`. |
|
|
54
|
+
| 2026-08-04 | `672e4df` | **LogPublisher + integração final do histórico:** `LogPublisher` para publicação de erros via RabbitMQ com auto-configuração via `load_dotenv()`; `LogEnvelope`, `ErrorLogPayload`, `EventType` e mapeamento `error_code` por tipo de exceção. Integração completa do `HistoryStore` no pipeline: hooks `MESSAGE_IN`/`MESSAGE_OUT`/`ROUTE_CHANGE`/`TRANSFER`/`END_CHAT` no `UserCall` e `ChatbotApp`; repasse via `MessageConsumer`. Novas properties em `UserCall`: `user_state`, `session_id`, `message`, `history`. Publicação de erros em `ChatbotApp._publish_error_log` e `MessageConsumer._process_message_callback`. |
|
|
55
|
+
| 2026-08-04 | `c24cbbd` | **Testes:** `TestLogPublisher`, `TestLogEnvelope`, `TestChatbotAppLogPublisher`, `TestMessageConsumerLogPublisher`, `TestHistoryStore`, `TestHistoryIntegration`, `TestUserStateProperty`. Total: 283 testes unitários. |
|
|
56
|
+
|
|
57
|
+
### 2026-07
|
|
58
|
+
|
|
59
|
+
| Data | Commit | Descrição |
|
|
60
|
+
|------|--------|-----------|
|
|
61
|
+
| 2026-07-08 | - | Atualização dos agentes de desenvolvimento (Architect, Developer, CodeReviewer) |
|
|
62
|
+
| 2026-07-22 | - | Sistema de Histórico de Mensagens plugável (pacote `chatgraph/history/`): `HistoryEntry`/enums, `generate_idempotency_key` (SHA-256), `HistoryStore` (Protocol) + `MemoryHistoryStore` (FIFO/dedup), hooks em `UserCall` (MESSAGE_OUT/ROUTE_CHANGE/TRANSFER/END_CHAT) e `ChatbotApp.process_message` (MESSAGE_IN), repasse via `MessageConsumer`. Store opcional (retrocompatível), fire-and-forget. |
|
|
63
|
+
| 2026-07-22 | - | Revisão de follow-up (5 correções): `MESSAGE_IN` passou a registrar `Message.to_dict()` completo; hooks isolados em `try/except BaseException` fora do try principal; escopo limpo (revertidos `message.py`/`example.py`/`pyproject.toml`/`test_message_consumer.py`); E501 corrigido; testes ampliados (dedup com instâncias distintas + hook MESSAGE_IN + idempotência no reprocessamento). 23 testes de histórico, 253 unitários no total, sem regressão. |
|
|
64
|
+
|
|
65
|
+
## 5. Estado Atual por Área
|
|
66
|
+
|
|
67
|
+
| Área | Status | Descrição |
|
|
68
|
+
|------|--------|-----------|
|
|
69
|
+
| **Core Framework** | ✅ | Estrutura base de rotas, tipos e modelos implementada |
|
|
70
|
+
| **History Store** | ✅ | Pacote `chatgraph/history/` plugável (Protocol + MemoryHistoryStore) com hooks de mensagem/rota/transfer/end; `MESSAGE_IN` registra `to_dict()` completo; registro fire-and-forget (`BaseException`) |
|
|
71
|
+
| **LogPublisher** | ✅ | `LogPublisher` com auto-configuração via `load_dotenv()`; `LogEnvelope`, `ErrorLogPayload`, `EventType`; publicação de erros via RabbitMQ em `ChatbotApp` e `MessageConsumer`; mapeamento `error_code` por tipo de exceção |
|
|
72
|
+
| **RabbitMQ Consumer** | ✅ | MessageConsumer com suporte a modo passive (fallback), heartbeat e reconexão automática; integração com HistoryStore e LogPublisher |
|
|
73
|
+
| **gRPC Integration** | ✅ | Suporte a chamadas gRPC via gRPCCall |
|
|
74
|
+
| **HTTP Router Client** | ✅ | RouterHTTPClient para integração com API REST |
|
|
75
|
+
| **Logging** | ✅ | UserLoggerManager com logs por usuário e sistema |
|
|
76
|
+
| **CLI** | ✅ | Comandos básicos (campaigns, delete-ustate) |
|
|
77
|
+
| **Testes Unitários** | ✅ | 283 testes passando (histórico + log publisher + UserState) |
|
|
78
|
+
| **Testes de Integração** | ⚠️ | Requer variáveis de ambiente configuradas |
|
|
79
|
+
| **Documentação** | ⚠️ | README completo, falta docs/ detalhada |
|
|
80
|
+
|
|
81
|
+
**Legenda:**
|
|
82
|
+
- ✅ Completo
|
|
83
|
+
- ⚠️ Parcial ou requer configuração
|
|
84
|
+
- ❌ Não iniciado
|
|
85
|
+
|
|
86
|
+
## 6. Convenções Estabelecidas
|
|
87
|
+
|
|
88
|
+
### Código
|
|
89
|
+
- **Lint**: ruff com line-length 79 e aspas simples
|
|
90
|
+
- **Tipagem**: Annotations do typing (Python 3.12+)
|
|
91
|
+
- **Async**: Suporte a sync e async nas rotas
|
|
92
|
+
- **Interfaces**: Sem prefixo I, tipagem por anotações
|
|
93
|
+
- **Construtores**: `__init__` + métodos factory `from_dict()`, `from_name()`
|
|
94
|
+
- **Injeção**: Manual via construtores
|
|
95
|
+
- **Logs**: `UserLoggerManager` (nunca print)
|
|
96
|
+
|
|
97
|
+
### Testes
|
|
98
|
+
- **Framework**: pytest + pytest-asyncio + respx
|
|
99
|
+
- **Estrutura**: Classes descritivas (`Test<Nome>Scenario`)
|
|
100
|
+
- **Fixtures**: Em `conftest.py`
|
|
101
|
+
- **Markers**: `@pytest.mark.unit` e `@pytest.mark.integration`
|
|
102
|
+
- **Mock HTTP**: `respx_mock`
|
|
103
|
+
|
|
104
|
+
### Rotas
|
|
105
|
+
- Convenção de nome: `start`, `start.choice`, `start.choice.about`
|
|
106
|
+
- Decorators: `@app.route()` e `@router.route()`
|
|
107
|
+
- Handlers recebem: `UserCall` e opcionalmente `Route`
|
|
108
|
+
- Default functions: regex matching antes das rotas
|
|
109
|
+
- Guard/Auth: `auth_level` por rota com `guard` customizável
|
|
110
|
+
|
|
111
|
+
## 7. Configuração de Ambiente
|
|
112
|
+
|
|
113
|
+
### Variáveis Obrigatórias
|
|
114
|
+
```bash
|
|
115
|
+
RABBIT_USER=seu_usuario
|
|
116
|
+
RABBIT_PASS=sua_senha
|
|
117
|
+
RABBIT_URI=amqp://localhost
|
|
118
|
+
RABBIT_QUEUE=chat_queue
|
|
119
|
+
RABBIT_PREFETCH=1
|
|
120
|
+
RABBIT_VHOST=/
|
|
121
|
+
ROUTER_URL=https://api.example.com/v1/actions
|
|
122
|
+
ROUTER_TOKEN=seu_token
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Variáveis Opcionais — Log Publisher
|
|
126
|
+
```bash
|
|
127
|
+
# Defina LOG_RABBIT_QUEUE para ativar o envio de logs de erro para RabbitMQ
|
|
128
|
+
LOG_RABBIT_QUEUE=logs
|
|
129
|
+
LOG_RABBIT_EXCHANGE=chatbot-hml
|
|
130
|
+
# LOG_RABBIT_ROUTING_KEY=chatbot.logs # default = chatbot.{LOG_RABBIT_QUEUE}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Testes
|
|
134
|
+
```bash
|
|
135
|
+
# Unitários
|
|
136
|
+
poetry run pytest tests/unit/ -v
|
|
137
|
+
|
|
138
|
+
# Com cobertura
|
|
139
|
+
poetry run pytest --cov=chatgraph --cov-report=html
|
|
140
|
+
|
|
141
|
+
# Integração (requer env vars)
|
|
142
|
+
poetry run pytest tests/integration/ -v
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Lint e Formatação
|
|
146
|
+
```bash
|
|
147
|
+
poetry run ruff check . && ruff format .
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## 8. Decisões Técnicas Importantes
|
|
151
|
+
|
|
152
|
+
| Tópico | Decisão | Justificativa |
|
|
153
|
+
|--------|---------|---------------|
|
|
154
|
+
| Estado | Externo (via API) | Escalabilidade e persistência |
|
|
155
|
+
| Async/Sync | Suporte a ambos | Flexibilidade para handlers |
|
|
156
|
+
| RabbitMQ | Modo passive primeiro | Evita PRECONDITION_FAILED em filas existentes |
|
|
157
|
+
| HTTP Client | httpx | Async nativo e moderno |
|
|
158
|
+
| gRPC | protobuf | Contratos tipados e performance |
|
|
159
|
+
| History Store | Protocol (não ABC) | Plugável, sem acoplamento a classe base |
|
|
160
|
+
| Log Publisher | load_dotenv() + opcional | Retrocompatível — se `LOG_RABBIT_QUEUE` não estiver definido, o publisher é `None` e os erros não são publicados |
|
|
161
|
+
|
|
162
|
+
## 9. Trabalhos Pendentes
|
|
163
|
+
|
|
164
|
+
| Prioridade | Tarefa | Área | Status |
|
|
165
|
+
|------------|--------|------|--------|
|
|
166
|
+
| Alta | Eliminar duplicação de lógica de registro entre `ChatbotApp.__record_message_in` e `UserCall.__record_history` | chatgraph/bot + types | ⚠️ |
|
|
167
|
+
| Média | Documentação técnica detalhada | docs/ | ❌ |
|
|
168
|
+
| Média | Mais testes de integração | tests/integration/ | ⚠️ |
|
|
169
|
+
| Baixa | Exemplos adicionais | examples/ | ❌ |
|
|
170
|
+
| Baixa | Suporte a mais plataformas | bot/ | ❌ |
|
|
171
|
+
|
|
172
|
+
## 10. Notas e Observações
|
|
173
|
+
|
|
174
|
+
- **MessageConsumer**: Implementado com fallback para modo passive quando fila já existe (resolve PRECONDITION_FAILED). Integrado com `HistoryStore` (repasse para `UserCall`) e `LogPublisher` (captura de exceções no callback).
|
|
175
|
+
- **RouterHTTPClient**: Integração via HTTP/REST com retry e timeout configuráveis
|
|
176
|
+
- **Id Positiva**: Integração via endpoint `/v1/id-positiva/`
|
|
177
|
+
- **History Store**: Plugável via `Protocol` (não ABC); `MemoryHistoryStore` padrão em memória com FIFO e dedup por idempotency key (SHA-256). Store opcional (`None` = no-op, retrocompatível). Registro fire-and-forget (hooks isolados em `try/except BaseException` fora do try principal; falhas geram warning, não propagam `Exception`/`BaseException`). Hooks em `UserCall` (MESSAGE_OUT/ROUTE_CHANGE/TRANSFER/END_CHAT) e `ChatbotApp.process_message` (MESSAGE_IN, payload `Message.to_dict()` completo). Pendência: lógica de registro duplicada entre `ChatbotApp.__record_message_in` e `UserCall.__record_history`.
|
|
178
|
+
- **LogPublisher**: Auto-configuração via `load_dotenv()`; se `LOG_RABBIT_QUEUE` não estiver definido, retorna `None` (no-op). Exchange e routing key configuráveis; default do routing key: `chatbot.{queue_name}`. Publicação fire-and-forget (falhas geram warning, não propagam). Erros capturados em `ChatbotApp.process_message` e `MessageConsumer._process_message_callback`. `LogEnvelope` com `ErrorLogPayload`, `EventType` e mapeamento `error_code` por classe de exceção (`ChatbotMessageError`, `ChatbotError`, `ValueError`, `TypeError`, `KeyError`, fallback `UNKNOWN_ERROR`).
|
|
179
|
+
- **UserCall**: Novas properties: `user_state` (UserState completo), `session_id` (int | None), `message` (Message), `history` (HistoryStore | None). `__record_history` privado com idempotency key SHA-256.
|
|
@@ -4,7 +4,13 @@ from .bot.chatbot_router import ChatbotRouter
|
|
|
4
4
|
from .bot.default_guard import default_guard
|
|
5
5
|
from .container.container import Container
|
|
6
6
|
from .logger import logger, set_level
|
|
7
|
+
from .messages.log_publisher import LogPublisher
|
|
7
8
|
from .messages.message_consumer import MessageConsumer
|
|
9
|
+
from .models.log_envelope import (
|
|
10
|
+
ErrorLogPayload,
|
|
11
|
+
EventType,
|
|
12
|
+
LogEnvelope,
|
|
13
|
+
)
|
|
8
14
|
from .models.message import Button, File, Message, SendType, TextMessage
|
|
9
15
|
from .models.platform_state import PlatformState, VollStateData
|
|
10
16
|
from .models.userstate import (
|
|
@@ -28,33 +34,38 @@ from .types.route import Route
|
|
|
28
34
|
from .types.usercall import UserCall
|
|
29
35
|
|
|
30
36
|
__all__ = [
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
37
|
+
'set_level',
|
|
38
|
+
'ChatbotApp',
|
|
39
|
+
'Credential',
|
|
40
|
+
'UserCall',
|
|
41
|
+
'ChatbotRouter',
|
|
42
|
+
'RedirectResponse',
|
|
43
|
+
'MessageConsumer',
|
|
44
|
+
'LogPublisher',
|
|
45
|
+
'LogEnvelope',
|
|
46
|
+
'ErrorLogPayload',
|
|
47
|
+
'EventType',
|
|
48
|
+
'Route',
|
|
49
|
+
'EndChatResponse',
|
|
50
|
+
'TransferToHuman',
|
|
51
|
+
'TransferToMenu',
|
|
52
|
+
'UserState',
|
|
53
|
+
'ChatID',
|
|
54
|
+
'Menu',
|
|
55
|
+
'AuthLevel',
|
|
56
|
+
'User',
|
|
57
|
+
'UserData',
|
|
58
|
+
'UserIdentity',
|
|
59
|
+
'UserInternal',
|
|
60
|
+
'Message',
|
|
61
|
+
'Button',
|
|
62
|
+
'File',
|
|
63
|
+
'TextMessage',
|
|
64
|
+
'SendType',
|
|
65
|
+
'BackgroundTask',
|
|
66
|
+
'Container',
|
|
67
|
+
'logger',
|
|
68
|
+
'default_guard',
|
|
69
|
+
'PlatformState',
|
|
70
|
+
'VollStateData',
|
|
60
71
|
]
|
|
@@ -6,7 +6,9 @@ class Credential:
|
|
|
6
6
|
Classe para gerenciar credenciais de usuário e senha, com suporte a variáveis de ambiente.
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
|
-
def __init__(
|
|
9
|
+
def __init__(
|
|
10
|
+
self, username: str | None = None, password: str | None = None
|
|
11
|
+
):
|
|
10
12
|
"""
|
|
11
13
|
Inicializa a classe Credential com um nome de usuário e senha.
|
|
12
14
|
|
|
@@ -48,7 +50,9 @@ class Credential:
|
|
|
48
50
|
return self.__username
|
|
49
51
|
|
|
50
52
|
@classmethod
|
|
51
|
-
def load_dotenv(
|
|
53
|
+
def load_dotenv(
|
|
54
|
+
cls, user_env: str = 'CHATBOT_USER', pass_env: str = 'CHATBOT_PASS'
|
|
55
|
+
) -> 'Credential':
|
|
52
56
|
"""
|
|
53
57
|
Carrega as credenciais de variáveis de ambiente e retorna uma instância da classe Credential.
|
|
54
58
|
|