Create chat_process.py
Browse files
modules/chatbot/chat_process.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modules/chatbot/chatbot/chat_process.py
|
2 |
+
import anthropic
|
3 |
+
import logging
|
4 |
+
from typing import Dict, Generator
|
5 |
+
|
6 |
+
logger = logging.getLogger(__name__)
|
7 |
+
|
8 |
+
class ChatProcessor:
|
9 |
+
def __init__(self):
|
10 |
+
self.client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
|
11 |
+
self.conversation_history = []
|
12 |
+
|
13 |
+
def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
|
14 |
+
"""
|
15 |
+
Procesa el input del chat y genera respuestas por chunks
|
16 |
+
"""
|
17 |
+
try:
|
18 |
+
# Agregar mensaje a la historia
|
19 |
+
self.conversation_history.append(f"Human: {message}")
|
20 |
+
|
21 |
+
# Generar respuesta
|
22 |
+
response = self.client.completions.create(
|
23 |
+
model="claude-3-opus-20240229",
|
24 |
+
prompt=f"{message}\n\nAssistant:",
|
25 |
+
max_tokens_to_sample=300,
|
26 |
+
temperature=0.7,
|
27 |
+
stream=True # Habilitar streaming
|
28 |
+
)
|
29 |
+
|
30 |
+
# Retornar chunks de la respuesta
|
31 |
+
full_response = ""
|
32 |
+
for chunk in response:
|
33 |
+
if chunk.completion:
|
34 |
+
yield chunk.completion
|
35 |
+
full_response += chunk.completion
|
36 |
+
|
37 |
+
# Guardar respuesta completa en la historia
|
38 |
+
self.conversation_history.append(f"Assistant: {full_response}")
|
39 |
+
|
40 |
+
except Exception as e:
|
41 |
+
logger.error(f"Error en process_chat_input: {str(e)}")
|
42 |
+
yield f"Error: {str(e)}"
|