behemot-framework 0.3.0__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.
Files changed (94) hide show
  1. behemot_framework-0.3.0/CHANGELOG.md +75 -0
  2. behemot_framework-0.3.0/LICENSE +21 -0
  3. behemot_framework-0.3.0/MANIFEST.in +9 -0
  4. behemot_framework-0.3.0/PKG-INFO +476 -0
  5. behemot_framework-0.3.0/README.md +351 -0
  6. behemot_framework-0.3.0/behemot_framework/__init__.py +10 -0
  7. behemot_framework-0.3.0/behemot_framework/assistants/__init__.py +0 -0
  8. behemot_framework-0.3.0/behemot_framework/assistants/assistant.py +522 -0
  9. behemot_framework-0.3.0/behemot_framework/cli/__init__.py +1 -0
  10. behemot_framework-0.3.0/behemot_framework/cli/admin.py +406 -0
  11. behemot_framework-0.3.0/behemot_framework/commandos/__init__.py +54 -0
  12. behemot_framework-0.3.0/behemot_framework/commandos/admin_commands.py +238 -0
  13. behemot_framework-0.3.0/behemot_framework/commandos/command_handler.py +968 -0
  14. behemot_framework-0.3.0/behemot_framework/commandos/permissions.py +282 -0
  15. behemot_framework-0.3.0/behemot_framework/commandos/rag_commands.py +548 -0
  16. behemot_framework-0.3.0/behemot_framework/commandos/session_analyzer.py +640 -0
  17. behemot_framework-0.3.0/behemot_framework/commandos/system_monitor.py +416 -0
  18. behemot_framework-0.3.0/behemot_framework/commandos/system_status.py +278 -0
  19. behemot_framework-0.3.0/behemot_framework/config.py +338 -0
  20. behemot_framework-0.3.0/behemot_framework/connectors/__init__.py +0 -0
  21. behemot_framework-0.3.0/behemot_framework/connectors/api_connector.py +48 -0
  22. behemot_framework-0.3.0/behemot_framework/connectors/google_chat_connector.py +191 -0
  23. behemot_framework-0.3.0/behemot_framework/connectors/gradio_connector.py +335 -0
  24. behemot_framework-0.3.0/behemot_framework/connectors/telegram_connector.py +146 -0
  25. behemot_framework-0.3.0/behemot_framework/connectors/whatsapp_connector.py +342 -0
  26. behemot_framework-0.3.0/behemot_framework/context.py +89 -0
  27. behemot_framework-0.3.0/behemot_framework/core/__init__.py +0 -0
  28. behemot_framework-0.3.0/behemot_framework/core/middleware/__init__.py +0 -0
  29. behemot_framework-0.3.0/behemot_framework/core/middleware/date_middleware.py +39 -0
  30. behemot_framework-0.3.0/behemot_framework/core/tools/__init__.py +0 -0
  31. behemot_framework-0.3.0/behemot_framework/core/tools/date_tools.py +88 -0
  32. behemot_framework-0.3.0/behemot_framework/factory.py +1104 -0
  33. behemot_framework-0.3.0/behemot_framework/models/__init__.py +31 -0
  34. behemot_framework-0.3.0/behemot_framework/models/base_model.py +96 -0
  35. behemot_framework-0.3.0/behemot_framework/models/gemini_model.py +456 -0
  36. behemot_framework-0.3.0/behemot_framework/models/gemini_model_fixed.py +288 -0
  37. behemot_framework-0.3.0/behemot_framework/models/gemini_model_original.py +241 -0
  38. behemot_framework-0.3.0/behemot_framework/models/gemini_model_simple_backup.py +184 -0
  39. behemot_framework-0.3.0/behemot_framework/models/gpt_model.py +130 -0
  40. behemot_framework-0.3.0/behemot_framework/models/model_factory.py +101 -0
  41. behemot_framework-0.3.0/behemot_framework/models/vertex_model.py +332 -0
  42. behemot_framework-0.3.0/behemot_framework/morphing/__init__.py +20 -0
  43. behemot_framework-0.3.0/behemot_framework/morphing/ab_testing.py +470 -0
  44. behemot_framework-0.3.0/behemot_framework/morphing/feedback_system.py +283 -0
  45. behemot_framework-0.3.0/behemot_framework/morphing/gradual_analyzer.py +249 -0
  46. behemot_framework-0.3.0/behemot_framework/morphing/instant_triggers.py +73 -0
  47. behemot_framework-0.3.0/behemot_framework/morphing/metrics.py +174 -0
  48. behemot_framework-0.3.0/behemot_framework/morphing/morphing_manager.py +463 -0
  49. behemot_framework-0.3.0/behemot_framework/morphing/state_manager.py +92 -0
  50. behemot_framework-0.3.0/behemot_framework/morphing/transition_manager.py +95 -0
  51. behemot_framework-0.3.0/behemot_framework/rag/__init__.py +0 -0
  52. behemot_framework-0.3.0/behemot_framework/rag/document_loader.py +458 -0
  53. behemot_framework-0.3.0/behemot_framework/rag/embeddings.py +165 -0
  54. behemot_framework-0.3.0/behemot_framework/rag/processors.py +138 -0
  55. behemot_framework-0.3.0/behemot_framework/rag/rag_manager.py +162 -0
  56. behemot_framework-0.3.0/behemot_framework/rag/rag_pipeline.py +348 -0
  57. behemot_framework-0.3.0/behemot_framework/rag/retriever.py +128 -0
  58. behemot_framework-0.3.0/behemot_framework/rag/source_guard.py +201 -0
  59. behemot_framework-0.3.0/behemot_framework/rag/tools.py +80 -0
  60. behemot_framework-0.3.0/behemot_framework/rag/vector_store.py +473 -0
  61. behemot_framework-0.3.0/behemot_framework/routes/__init__.py +0 -0
  62. behemot_framework-0.3.0/behemot_framework/routes/status.py +914 -0
  63. behemot_framework-0.3.0/behemot_framework/security/__init__.py +0 -0
  64. behemot_framework-0.3.0/behemot_framework/security/langchain_safety.py +147 -0
  65. behemot_framework-0.3.0/behemot_framework/services/__init__.py +0 -0
  66. behemot_framework-0.3.0/behemot_framework/services/transcription_service.py +29 -0
  67. behemot_framework-0.3.0/behemot_framework/startup.py +396 -0
  68. behemot_framework-0.3.0/behemot_framework/startup_backup.py +463 -0
  69. behemot_framework-0.3.0/behemot_framework/tooling.py +145 -0
  70. behemot_framework-0.3.0/behemot_framework/users/__init__.py +4 -0
  71. behemot_framework-0.3.0/behemot_framework/users/user_tracker.py +221 -0
  72. behemot_framework-0.3.0/behemot_framework/utils/__init__.py +0 -0
  73. behemot_framework-0.3.0/behemot_framework/utils/logger.py +97 -0
  74. behemot_framework-0.3.0/behemot_framework/utils/markdown_converter.py +97 -0
  75. behemot_framework-0.3.0/behemot_framework.egg-info/PKG-INFO +476 -0
  76. behemot_framework-0.3.0/behemot_framework.egg-info/SOURCES.txt +92 -0
  77. behemot_framework-0.3.0/behemot_framework.egg-info/dependency_links.txt +1 -0
  78. behemot_framework-0.3.0/behemot_framework.egg-info/entry_points.txt +2 -0
  79. behemot_framework-0.3.0/behemot_framework.egg-info/requires.txt +96 -0
  80. behemot_framework-0.3.0/behemot_framework.egg-info/top_level.txt +1 -0
  81. behemot_framework-0.3.0/examples/api_assistant.py +41 -0
  82. behemot_framework-0.3.0/examples/config_api.yaml +34 -0
  83. behemot_framework-0.3.0/examples/config_google_chat.yaml +30 -0
  84. behemot_framework-0.3.0/examples/config_minimal.yaml +26 -0
  85. behemot_framework-0.3.0/examples/config_telegram.yaml +33 -0
  86. behemot_framework-0.3.0/examples/config_whatsapp.yaml +34 -0
  87. behemot_framework-0.3.0/examples/config_with_admin_users.yaml +66 -0
  88. behemot_framework-0.3.0/examples/google_chat_assistant.py +33 -0
  89. behemot_framework-0.3.0/examples/gradio_whatsapp_example.py +60 -0
  90. behemot_framework-0.3.0/examples/minimal_assistant.py +36 -0
  91. behemot_framework-0.3.0/examples/telegram_assistant.py +39 -0
  92. behemot_framework-0.3.0/examples/whatsapp_assistant.py +42 -0
  93. behemot_framework-0.3.0/setup.cfg +4 -0
  94. behemot_framework-0.3.0/setup.py +120 -0
@@ -0,0 +1,75 @@
1
+ # Changelog
2
+
3
+ Todas las mejoras y cambios importantes de Behemot Framework se documentan en este archivo.
4
+
5
+ ## [0.1.2] - 2025-01-03
6
+
7
+ ### ✨ Nuevas Características
8
+
9
+ #### Sistema de Permisos Granular
10
+ - **Sistema de permisos completo** con control granular de acceso a comandos administrativos
11
+ - **Modos de administración**: `dev` (todos son admin) y `production` (solo usuarios configurados)
12
+ - **Permisos disponibles**:
13
+ - `user_info` - Ver información propia
14
+ - `broadcast` - Envío masivo de mensajes
15
+ - `user_management` - Gestión de usuarios y sesiones
16
+ - `system` - Comandos de sistema y monitoreo
17
+ - `super_admin` - Acceso total a todos los comandos
18
+
19
+ #### Nuevo Comando &whoami
20
+ - **Comando `&whoami`** para que usuarios vean su información y permisos
21
+ - **Información detallada** por plataforma (Telegram, WhatsApp, Google Chat, API)
22
+ - **Lista de comandos disponibles** basada en permisos reales
23
+ - **Metadata específica**: username, teléfono, email, IP según la plataforma
24
+
25
+ #### Sistema de Mensajería Masiva
26
+ - **Comando `&sendmsg`** para envío masivo a todos los usuarios activos
27
+ - **Envío por plataforma específica** con parámetro `platform`
28
+ - **Comando `&list_users`** para ver usuarios activos por plataforma
29
+ - **Tracking automático** de usuarios que interactúan con el bot
30
+ - **Metadata enriquecida** para marketing y análisis
31
+
32
+ #### Filtro de Seguridad Configurable
33
+ - **`SAFETY_LEVEL` configurable**: `off`, `low`, `medium`, `high`
34
+ - **Filtro mejorado** que permite conversaciones normales (nombres, edad, fechas)
35
+ - **Protección contra prompt injection** y contenido inapropiado
36
+ - **Fail-safe**: permite contenido en caso de errores del filtro
37
+
38
+ ### 🔧 Mejoras
39
+
40
+ #### Configuración
41
+ - **Nuevas opciones de configuración** para permisos y seguridad
42
+ - **CLI actualizado** con configuración de permisos en proyectos nuevos
43
+ - **Archivo de ejemplo** `config_with_admin_users.yaml`
44
+ - **Documentación mejorada** en README con ejemplos de configuración
45
+
46
+ #### Sistema de Comandos
47
+ - **Verificación de permisos** integrada en comandos administrativos
48
+ - **Mensajes de error informativos** para acceso denegado
49
+ - **Logging mejorado** con emojis para mejor debugging
50
+
51
+ ### 📚 Documentación
52
+ - **Sección de permisos** en README con ejemplos completos
53
+ - **Comandos útiles** documentados (`&whoami`, `&help`)
54
+ - **Configuración paso a paso** para diferentes modos de administración
55
+
56
+ ### 🐛 Correcciones
57
+ - **Filtro de seguridad** ya no bloquea conversaciones normales
58
+ - **Contexto mantenido** correctamente en todas las plataformas
59
+ - **Mejor manejo de errores** en comandos administrativos
60
+
61
+ ## [0.1.1] - 2025-01-02
62
+
63
+ ### Mejoras anteriores
64
+ - Sistema RAG con múltiples proveedores de embeddings
65
+ - Soporte para modelos Gemini y OpenAI
66
+ - Conectores para múltiples plataformas
67
+ - Interfaz de prueba local con Gradio
68
+
69
+ ## [0.1.0] - 2025-01-01
70
+
71
+ ### Lanzamiento inicial
72
+ - Framework base para asistentes IA multimodales
73
+ - Soporte para herramientas extensibles
74
+ - Sistema de configuración YAML
75
+ - CLI para generación de proyectos
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bruno Hernandez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,9 @@
1
+ include README.md
2
+ include LICENSE
3
+ include CHANGELOG.md
4
+ recursive-include examples *.py *.yaml
5
+ recursive-exclude * __pycache__
6
+ recursive-exclude * *.py[co]
7
+ recursive-exclude test *
8
+ prune test
9
+ prune knowledge
@@ -0,0 +1,476 @@
1
+ Metadata-Version: 2.4
2
+ Name: behemot_framework
3
+ Version: 0.3.0
4
+ Summary: A modular framework for building multimodal AI assistants.
5
+ Home-page: https://github.com/hernandezbg/behemot_framework
6
+ Author: Bruno Hernandez
7
+ Author-email: hernandezbg@gmail.com
8
+ License: MIT
9
+ Project-URL: Source, https://github.com/hernandezbg/behemot_framework
10
+ Project-URL: Issues, https://github.com/hernandezbg/behemot_framework/issues
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Development Status :: 4 - Beta
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Framework :: FastAPI
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: fastapi
26
+ Requires-Dist: uvicorn
27
+ Requires-Dist: requests
28
+ Requires-Dist: python-dotenv
29
+ Requires-Dist: pydantic>=2
30
+ Requires-Dist: openai
31
+ Requires-Dist: redis
32
+ Requires-Dist: python-multipart
33
+ Requires-Dist: jsonschema
34
+ Requires-Dist: beautifulsoup4
35
+ Provides-Extra: rag
36
+ Requires-Dist: langchain>=0.1.0; extra == "rag"
37
+ Requires-Dist: langchain-core>=0.1.0; extra == "rag"
38
+ Requires-Dist: langchain-community>=0.0.13; extra == "rag"
39
+ Requires-Dist: langchain-text-splitters>=0.0.1; extra == "rag"
40
+ Requires-Dist: langchain-openai>=0.0.5; extra == "rag"
41
+ Requires-Dist: langchain-classic>=1.0.0; extra == "rag"
42
+ Requires-Dist: langchain-chroma>=0.1.0; extra == "rag"
43
+ Requires-Dist: chromadb>=0.4.22; extra == "rag"
44
+ Requires-Dist: tiktoken>=0.5.1; extra == "rag"
45
+ Requires-Dist: pypdf>=3.17.1; extra == "rag"
46
+ Requires-Dist: unstructured>=0.4.16; extra == "rag"
47
+ Requires-Dist: markdown; extra == "rag"
48
+ Requires-Dist: sentence-transformers; extra == "rag"
49
+ Requires-Dist: faiss-cpu>=1.7.4; extra == "rag"
50
+ Provides-Extra: voice
51
+ Requires-Dist: openai-whisper; extra == "voice"
52
+ Requires-Dist: faster-whisper; extra == "voice"
53
+ Requires-Dist: pydub; extra == "voice"
54
+ Requires-Dist: ffmpeg-python; extra == "voice"
55
+ Requires-Dist: SpeechRecognition; extra == "voice"
56
+ Requires-Dist: soundfile; extra == "voice"
57
+ Requires-Dist: deepgram-sdk; extra == "voice"
58
+ Provides-Extra: gemini
59
+ Requires-Dist: google-generativeai>=0.3.0; extra == "gemini"
60
+ Requires-Dist: langchain-google-genai>=1.0.0; extra == "gemini"
61
+ Provides-Extra: cloud
62
+ Requires-Dist: google-cloud-storage>=2.9.0; extra == "cloud"
63
+ Requires-Dist: google-api-python-client; extra == "cloud"
64
+ Requires-Dist: google-auth==2.28.1; extra == "cloud"
65
+ Requires-Dist: boto3; extra == "cloud"
66
+ Provides-Extra: telegram
67
+ Requires-Dist: python-telegram-bot; extra == "telegram"
68
+ Provides-Extra: whatsapp
69
+ Requires-Dist: twilio; extra == "whatsapp"
70
+ Provides-Extra: gradio
71
+ Requires-Dist: gradio>=4.0.0; extra == "gradio"
72
+ Requires-Dist: Pillow>=10.0.0; extra == "gradio"
73
+ Provides-Extra: dev
74
+ Requires-Dist: pytest; extra == "dev"
75
+ Requires-Dist: pytest-asyncio; extra == "dev"
76
+ Requires-Dist: respx; extra == "dev"
77
+ Requires-Dist: httpx; extra == "dev"
78
+ Requires-Dist: build; extra == "dev"
79
+ Requires-Dist: twine; extra == "dev"
80
+ Provides-Extra: all
81
+ Requires-Dist: Pillow>=10.0.0; extra == "all"
82
+ Requires-Dist: SpeechRecognition; extra == "all"
83
+ Requires-Dist: boto3; extra == "all"
84
+ Requires-Dist: chromadb>=0.4.22; extra == "all"
85
+ Requires-Dist: deepgram-sdk; extra == "all"
86
+ Requires-Dist: faiss-cpu>=1.7.4; extra == "all"
87
+ Requires-Dist: faster-whisper; extra == "all"
88
+ Requires-Dist: ffmpeg-python; extra == "all"
89
+ Requires-Dist: google-api-python-client; extra == "all"
90
+ Requires-Dist: google-auth==2.28.1; extra == "all"
91
+ Requires-Dist: google-cloud-storage>=2.9.0; extra == "all"
92
+ Requires-Dist: google-generativeai>=0.3.0; extra == "all"
93
+ Requires-Dist: gradio>=4.0.0; extra == "all"
94
+ Requires-Dist: langchain-chroma>=0.1.0; extra == "all"
95
+ Requires-Dist: langchain-classic>=1.0.0; extra == "all"
96
+ Requires-Dist: langchain-community>=0.0.13; extra == "all"
97
+ Requires-Dist: langchain-core>=0.1.0; extra == "all"
98
+ Requires-Dist: langchain-google-genai>=1.0.0; extra == "all"
99
+ Requires-Dist: langchain-openai>=0.0.5; extra == "all"
100
+ Requires-Dist: langchain-text-splitters>=0.0.1; extra == "all"
101
+ Requires-Dist: langchain>=0.1.0; extra == "all"
102
+ Requires-Dist: markdown; extra == "all"
103
+ Requires-Dist: openai-whisper; extra == "all"
104
+ Requires-Dist: pydub; extra == "all"
105
+ Requires-Dist: pypdf>=3.17.1; extra == "all"
106
+ Requires-Dist: python-telegram-bot; extra == "all"
107
+ Requires-Dist: sentence-transformers; extra == "all"
108
+ Requires-Dist: soundfile; extra == "all"
109
+ Requires-Dist: tiktoken>=0.5.1; extra == "all"
110
+ Requires-Dist: twilio; extra == "all"
111
+ Requires-Dist: unstructured>=0.4.16; extra == "all"
112
+ Dynamic: author
113
+ Dynamic: author-email
114
+ Dynamic: classifier
115
+ Dynamic: description
116
+ Dynamic: description-content-type
117
+ Dynamic: home-page
118
+ Dynamic: license
119
+ Dynamic: license-file
120
+ Dynamic: project-url
121
+ Dynamic: provides-extra
122
+ Dynamic: requires-dist
123
+ Dynamic: requires-python
124
+ Dynamic: summary
125
+
126
+ # Behemot Framework
127
+
128
+ **Framework modular para crear asistentes IA multimodales**
129
+
130
+ La filosofía es simple: **el framework proporciona el motor; tú proporcionas la personalidad (configuración) y las habilidades (herramientas).**
131
+
132
+ ## 🚀 Inicio Rápido
133
+
134
+ ### Paso 1: Crear el Proyecto
135
+
136
+ ```bash
137
+ # Crear directorio del proyecto
138
+ mkdir mi_asistente
139
+ cd mi_asistente
140
+
141
+ # Crear entorno virtual
142
+ python -m venv venv
143
+ source venv/bin/activate # Windows: venv\Scripts\activate
144
+ ```
145
+
146
+ ### Paso 2: Instalar Behemot Framework
147
+
148
+ Instala solo el core (modelos OpenAI + API REST):
149
+
150
+ ```bash
151
+ pip install behemot-framework
152
+ ```
153
+
154
+ O añade los extras que necesites:
155
+
156
+ ```bash
157
+ pip install "behemot-framework[rag]" # Retrieval-Augmented Generation
158
+ pip install "behemot-framework[voice]" # Transcripción Whisper
159
+ pip install "behemot-framework[gemini]" # Google Gemini
160
+ pip install "behemot-framework[gradio]" # Interfaz local de pruebas
161
+ pip install "behemot-framework[rag,voice,gradio]" # Combinables
162
+ pip install "behemot-framework[all]" # Todo
163
+ ```
164
+
165
+ También puedes instalar desde el repositorio (siempre la última versión):
166
+
167
+ ```bash
168
+ pip install git+https://github.com/hernandezbg/behemot_framework.git
169
+ ```
170
+
171
+ ### Paso 3: Generar Estructura del Proyecto
172
+
173
+ ```bash
174
+ behemot-admin create-agent mi_asistente
175
+ ```
176
+
177
+ Este comando crea automáticamente:
178
+ - `config/mi_asistente.yaml` - Configuración del asistente
179
+ - `tools/` - Directorio para herramientas personalizadas
180
+ - `main.py` - Punto de entrada principal
181
+ - `.env.example` - Plantilla de variables de entorno
182
+ - `README.md` - Documentación del proyecto
183
+
184
+ ### Paso 4: Configurar Variables de Entorno
185
+
186
+ ```bash
187
+ cp .env.example .env
188
+ # Editar .env con tus API keys
189
+ ```
190
+
191
+ ### Paso 5: Ejecutar tu Asistente
192
+
193
+ ```bash
194
+ python main.py
195
+ ```
196
+
197
+ ¡Tu asistente estará corriendo en http://localhost:8000!
198
+
199
+ ## 🛠️ Personalización Avanzada
200
+
201
+ ### Configuración del Asistente
202
+
203
+ Edita `config/mi_asistente.yaml` para personalizar tu asistente:
204
+
205
+ ```yaml
206
+ # Configuración del modelo
207
+ MODEL_PROVIDER: "openai" # openai, gemini, vertex
208
+ MODEL_NAME: "gpt-4o-mini"
209
+
210
+ # Prompt del sistema - Define la personalidad de tu asistente
211
+ PROMPT_SISTEMA: |
212
+ Eres un asistente especializado en [tu dominio].
213
+ Siempre eres amable, preciso y útil.
214
+
215
+ # Configuración de seguridad
216
+ SAFETY_LEVEL: "medium" # low, medium, high
217
+
218
+ # RAG (Retrieval Augmented Generation) - Conocimiento personalizado
219
+ ENABLE_RAG: true
220
+ RAG_FOLDERS: ["./docs"] # Carpetas locales, gcp://bucket/path, s3://bucket/key
221
+ RAG_EMBEDDING_PROVIDER: "openai" # openai, google, huggingface
222
+ ```
223
+
224
+ ### Crear Herramientas Personalizadas
225
+
226
+ Las herramientas son las "habilidades" de tu asistente. Créalas en el directorio `tools/`:
227
+
228
+ **`tools/mi_herramienta.py`:**
229
+ ```python
230
+ from behemot_framework.tooling import tool, Param
231
+
232
+ @tool(
233
+ "mi_herramienta",
234
+ "Descripción de lo que hace la herramienta",
235
+ [
236
+ Param("parametro", "string", "Descripción del parámetro", required=True)
237
+ ]
238
+ )
239
+ async def mi_herramienta(parametro: str):
240
+ # Tu lógica aquí
241
+ return f"Resultado procesando: {parametro}"
242
+ ```
243
+
244
+ Luego agrégala a `main.py`:
245
+ ```python
246
+ app = create_behemot_app(
247
+ # ... otras configuraciones
248
+ use_tools=["mi_herramienta"], # Agregar aquí
249
+ )
250
+ ```
251
+
252
+ ### Habilitar RAG (Conocimiento Personalizado)
253
+
254
+ Agrega documentos a tu asistente para que responda basándose en tu contenido:
255
+
256
+ ```yaml
257
+ # En config/mi_asistente.yaml
258
+ ENABLE_RAG: true
259
+ RAG_FOLDERS: ["./docs", "gcp://mi-bucket/documentos", "s3://bucket/archivos"]
260
+ ```
261
+
262
+ **Formatos soportados**: PDF, TXT, Markdown, CSV, URLs
263
+ **El asistente leerá automáticamente** todo el contenido y podrá responder preguntas sobre tus documentos.
264
+
265
+ ### Habilitar Canales de Comunicación
266
+
267
+ En `main.py`, activa los canales que necesites:
268
+
269
+ ```python
270
+ app = create_behemot_app(
271
+ enable_api=True, # API REST
272
+ enable_telegram=True, # Bot de Telegram
273
+ enable_whatsapp=True, # WhatsApp Business
274
+ enable_google_chat=True, # Google Chat
275
+ enable_voice=True, # Procesamiento de voz
276
+ enable_test_local=True, # Interfaz de prueba local con Gradio
277
+ config_path="config/mi_asistente.yaml",
278
+ )
279
+ ```
280
+
281
+ ### Interfaz de Prueba Local
282
+
283
+ Para probar tu asistente de forma visual antes de desplegarlo:
284
+
285
+ ```python
286
+ # En main.py
287
+ app = create_behemot_app(
288
+ enable_test_local=True, # Activar interfaz visual
289
+ config_path="config/mi_asistente.yaml",
290
+ )
291
+ ```
292
+
293
+ Esto creará una interfaz web en http://localhost:7860 con:
294
+ - 💬 **Chat interactivo con tema oscuro** - Interfaz moderna y elegante
295
+ - 🎤 **Entrada de voz** - Si `enable_voice=True`
296
+ - 🔧 **Panel de herramientas** - Ve las herramientas disponibles
297
+ - ⚙️ **Configuración** - Revisa la configuración actual
298
+ - 🌐 **Compartir públicamente** - Configura `GRADIO_SHARE=true` para obtener URL pública
299
+
300
+ #### Configurar acceso público (opcional)
301
+
302
+ ```yaml
303
+ # En config/mi_asistente.yaml
304
+ GRADIO_SHARE: true
305
+ ```
306
+
307
+ O con variable de entorno:
308
+ ```bash
309
+ export GRADIO_SHARE=true
310
+ python main.py
311
+ ```
312
+
313
+ ### Configurar Filtro de Seguridad
314
+
315
+ El framework incluye un filtro de seguridad configurable para proteger contra contenido inapropiado:
316
+
317
+ ```yaml
318
+ # En config/mi_asistente.yaml
319
+ SAFETY_LEVEL: "medium" # off, low, medium, high
320
+ ```
321
+
322
+ **Niveles disponibles:**
323
+ - `"off"` - **Filtro deshabilitado** - Permite todo el contenido
324
+ - `"low"` - **Muy permisivo** - Solo bloquea contenido extremadamente peligroso
325
+ - `"medium"` - **Equilibrado** *(recomendado)* - Bloquea contenido inapropiado, permite conversación normal
326
+ - `"high"` - **Estricto** - Filtrado más riguroso para entornos sensibles
327
+
328
+ **Nota**: El filtro permite automáticamente conversaciones normales como preguntas sobre nombres, edad, fechas, etc.
329
+
330
+ ### Configurar Sistema de Permisos
331
+
332
+ El framework incluye un sistema de permisos granular para comandos administrativos. **Por defecto ningún usuario es admin** — debes declarar explícitamente quién puede ejecutar comandos privilegiados.
333
+
334
+ ```yaml
335
+ # En config/mi_asistente.yaml
336
+ ADMIN_MODE: "production" # default seguro
337
+
338
+ ADMIN_USERS:
339
+ - user_id: "1069636329" # Tu ID de usuario
340
+ platform: "telegram" # telegram, whatsapp, google_chat, api
341
+ permissions: ["super_admin"] # super_admin, broadcast, user_management, system, rag_admin
342
+ ```
343
+
344
+ **Permisos disponibles:**
345
+ - `"user_info"` - Ver información propia (`&whoami`)
346
+ - `"broadcast"` - Envío masivo (`&sendmsg`, `&list_users`)
347
+ - `"user_management"` - Gestión de usuarios (`&delete_session`, `&list_sessions`)
348
+ - `"system"` - Comandos de sistema (`&status`, `&monitor`, `&clear_msg`)
349
+ - `"rag"` - Consulta del sistema RAG (`&rag_search`, `&rag_status`)
350
+ - `"rag_admin"` - Reindexación RAG (`&reindex_rag`) — separado para minimizar superficie
351
+ - `"super_admin"` - **Todos los comandos** (acceso total)
352
+
353
+ **Comandos útiles:**
354
+ - `&whoami` - Ver tu ID de usuario y permisos actuales
355
+ - `&help` - Lista completa de comandos disponibles
356
+
357
+ ### 🔐 Seguridad — Variables clave para producción
358
+
359
+ El framework aplica defaults seguros, pero hay variables que **debes configurar antes de exponer un agente a internet**:
360
+
361
+ ```bash
362
+ # .env
363
+
364
+ # --- Webhooks firmados (CRÍTICO en producción) ---
365
+ TELEGRAM_WEBHOOK_SECRET=... # auto-generado si falta (no persiste entre réplicas)
366
+ WHATSAPP_APP_SECRET=... # del Meta Developer Console — sin esto el webhook acepta cualquier POST
367
+
368
+ # --- RAG anti-path-traversal / anti-SSRF ---
369
+ RAG_ALLOWED_ROOTS=./docs,./manuals # paths permitidos para fuentes locales
370
+ RAG_ALLOWED_URL_HOSTS=docs.miempresa.com # whitelist opcional para URLs HTTP/HTTPS
371
+ # RAG_ALLOW_PRIVATE_NETWORKS=false # default: rechaza IPs privadas/loopback/metadata cloud
372
+
373
+ # --- Endpoints expuestos ---
374
+ STATUS_API_TOKEN=... # Bearer token para /status; sin esto queda abierto
375
+ API_AUTH_MODE=api_key # none | api_key
376
+ API_KEYS=key-1,key-2 # solo si API_AUTH_MODE=api_key
377
+ API_RATE_LIMIT_PER_MINUTE=60 # 0 desactiva
378
+ API_MAX_REQUEST_SIZE=10485760 # 10MB
379
+ API_MAX_AUDIO_SIZE=26214400 # 25MB
380
+
381
+ # --- Privacidad de logs ---
382
+ LOG_REDACT_PII=true # enmascara emails, teléfonos y tokens largos
383
+ ```
384
+
385
+ **Garantías que ofrece el framework:**
386
+
387
+ | Vector | Mitigación |
388
+ |---|---|
389
+ | Suplantación de mensajes en webhooks | Validación de `X-Telegram-Bot-Api-Secret-Token` y `X-Hub-Signature-256` (HMAC-SHA256) |
390
+ | Path traversal en RAG | `realpath` + lista blanca `RAG_ALLOWED_ROOTS` |
391
+ | SSRF a metadata cloud | Bloqueo de IPs privadas, link-local y dominios `metadata.*.internal` |
392
+ | Tool poisoning vía prompt injection | Validación JSONSchema de argumentos antes de invocar handlers |
393
+ | Prompt injection vía RAG | Marcadores `<untrusted_context>` + sanitización HTML al cargar URLs |
394
+ | Bypass del filtro de seguridad | Fail-closed ante errores; aplica a cualquier `MODEL_PROVIDER` |
395
+ | Fuga de secretos en logs | Filtro automático de patrones (OpenAI/Anthropic/GitHub/Slack/Telegram) y PII |
396
+ | DoS económico en `/api/chat` | Rate limiting por IP + límites de body/audio |
397
+
398
+ ### Configurar Variables de Entorno
399
+
400
+ Edita tu archivo `.env`:
401
+
402
+ ```bash
403
+ # OpenAI
404
+ GPT_API_KEY=sk-...
405
+
406
+ # Google Gemini (opcional)
407
+ GEMINI_API_KEY=AI...
408
+
409
+ # Google Vertex AI (opcional)
410
+ VERTEX_PROJECT_ID=mi-proyecto-gcp
411
+ VERTEX_LOCATION=us-central1
412
+
413
+ # Redis para persistencia (opcional)
414
+ REDIS_PUBLIC_URL=redis://localhost:6379
415
+
416
+ # Telegram (opcional)
417
+ TELEGRAM_TOKEN=...
418
+ TELEGRAM_WEBHOOK_URL=https://tu-dominio.com/webhook
419
+
420
+ # WhatsApp Business (opcional)
421
+ WHATSAPP_TOKEN=...
422
+ WHATSAPP_VERIFY_TOKEN=...
423
+ WHATSAPP_WEBHOOK_URL=https://tu-dominio.com/whatsapp-webhook
424
+
425
+ # API REST - Para plataformas web personalizadas (opcional)
426
+ API_WEBHOOK_URL=https://tu-plataforma-web.com/api
427
+
428
+ # Google Chat (opcional)
429
+ GC_PROJECT_ID=...
430
+ GC_PRIVATE_KEY=...
431
+ GC_CLIENT_EMAIL=...
432
+ ```
433
+
434
+ ## 🌟 Características
435
+
436
+ - **🤖 Múltiples Modelos IA**: OpenAI GPT, Google Gemini y Vertex AI
437
+ - **📱 Múltiples Canales**: API REST, Telegram, WhatsApp, Google Chat
438
+ - **🧠 RAG Integrado**: Lee carpetas locales, GCP, S3, Google Drive automáticamente
439
+ - **🔧 Herramientas Extensibles**: Sistema de plugins simple
440
+ - **🎤 Procesamiento de Voz**: Transcripción automática de audio
441
+ - **🔒 Filtros de Seguridad**: Contenido seguro por defecto (configurable)
442
+ - **👥 Sistema de Permisos**: Control granular de acceso a comandos administrativos
443
+ - **📨 Mensajería Masiva**: Envío de mensajes a todos los usuarios activos
444
+ - **💾 Persistencia de Contexto**: Conversaciones continuas con Redis
445
+ - **📊 Diagnósticos**: Monitoreo automático de componentes
446
+
447
+ ## 📂 Ejemplos
448
+
449
+ El directorio [`examples/`](./examples) contiene plantillas listas para arrancar:
450
+
451
+ | Ejemplo | Qué muestra |
452
+ |---|---|
453
+ | [`minimal_assistant.py`](./examples/minimal_assistant.py) + [`config_minimal.yaml`](./examples/config_minimal.yaml) | Configuración mínima absoluta (solo API REST + Gradio local) |
454
+ | [`telegram_assistant.py`](./examples/telegram_assistant.py) + [`config_telegram.yaml`](./examples/config_telegram.yaml) | Bot de Telegram con firma de webhook |
455
+ | [`whatsapp_assistant.py`](./examples/whatsapp_assistant.py) + [`config_whatsapp.yaml`](./examples/config_whatsapp.yaml) | WhatsApp Business con HMAC validation |
456
+ | [`google_chat_assistant.py`](./examples/google_chat_assistant.py) + [`config_google_chat.yaml`](./examples/config_google_chat.yaml) | Bot para Google Chat |
457
+ | [`api_assistant.py`](./examples/api_assistant.py) + [`config_api.yaml`](./examples/config_api.yaml) | Endpoint REST con auth `X-API-Key` y rate limiting |
458
+
459
+ Cada ejemplo es ejecutable directamente con `python examples/<nombre>.py`.
460
+
461
+ ## 📚 Documentación Adicional
462
+
463
+ Para casos de uso avanzados, configuraciones especiales y ejemplos completos, consulta la documentación en el repositorio.
464
+
465
+ ## 🤝 Contribuir
466
+
467
+ ¡Las contribuciones son bienvenidas! Por favor:
468
+
469
+ 1. Haz fork del repositorio
470
+ 2. Crea una rama para tu feature
471
+ 3. Haz commit de tus cambios
472
+ 4. Abre un Pull Request
473
+
474
+ ## 📄 Licencia
475
+
476
+ Este proyecto está bajo la Licencia MIT. Ver el archivo `LICENSE` para más detalles.