Update modules/chatbot/chat_process.py
Browse files- modules/chatbot/chat_process.py +60 -15
modules/chatbot/chat_process.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1 |
# modules/chatbot/chatbot/chat_process.py
|
2 |
import anthropic
|
|
|
3 |
import logging
|
4 |
from typing import Dict, Generator
|
5 |
|
@@ -7,36 +8,80 @@ logger = logging.getLogger(__name__)
|
|
7 |
|
8 |
class ChatProcessor:
|
9 |
def __init__(self):
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
#
|
22 |
-
|
|
|
|
|
|
|
23 |
model="claude-3-opus-20240229",
|
24 |
-
|
25 |
-
max_tokens_to_sample=300,
|
26 |
temperature=0.7,
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
)
|
29 |
|
30 |
-
#
|
31 |
full_response = ""
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
except Exception as e:
|
41 |
logger.error(f"Error en process_chat_input: {str(e)}")
|
42 |
-
yield f"Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
# modules/chatbot/chatbot/chat_process.py
|
2 |
import anthropic
|
3 |
+
import os
|
4 |
import logging
|
5 |
from typing import Dict, Generator
|
6 |
|
|
|
8 |
|
9 |
class ChatProcessor:
|
10 |
def __init__(self):
|
11 |
+
"""
|
12 |
+
Inicializa el procesador de chat con la API de Claude
|
13 |
+
Raises:
|
14 |
+
ValueError: Si no se encuentra la clave API
|
15 |
+
"""
|
16 |
+
api_key = os.environ.get("ANTHROPIC_API_KEY")
|
17 |
+
if not api_key:
|
18 |
+
raise ValueError("No se encontr贸 ANTHROPIC_API_KEY en las variables de entorno")
|
19 |
+
|
20 |
+
self.client = anthropic.Anthropic(api_key=api_key)
|
21 |
self.conversation_history = []
|
22 |
|
23 |
def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
|
24 |
"""
|
25 |
Procesa el input del chat y genera respuestas por chunks
|
26 |
+
Args:
|
27 |
+
message: Mensaje del usuario
|
28 |
+
lang_code: C贸digo del idioma para contexto
|
29 |
+
Yields:
|
30 |
+
str: Chunks de la respuesta
|
31 |
"""
|
32 |
try:
|
33 |
# Agregar mensaje a la historia
|
34 |
self.conversation_history.append(f"Human: {message}")
|
35 |
|
36 |
+
# Construir el prompt con contexto del idioma
|
37 |
+
system_prompt = f"You are an AI assistant for AIdeaText. Respond in {lang_code}."
|
38 |
+
|
39 |
+
# Generar respuesta usando Claude API
|
40 |
+
response = self.client.messages.create(
|
41 |
model="claude-3-opus-20240229",
|
42 |
+
max_tokens=300,
|
|
|
43 |
temperature=0.7,
|
44 |
+
system=system_prompt,
|
45 |
+
messages=[
|
46 |
+
{
|
47 |
+
"role": "user",
|
48 |
+
"content": message
|
49 |
+
}
|
50 |
+
],
|
51 |
+
stream=True
|
52 |
)
|
53 |
|
54 |
+
# Procesar la respuesta en streaming
|
55 |
full_response = ""
|
56 |
+
try:
|
57 |
+
for chunk in response:
|
58 |
+
if chunk.delta.text: # Verificar si hay texto en el chunk
|
59 |
+
chunk_text = chunk.delta.text
|
60 |
+
yield chunk_text
|
61 |
+
full_response += chunk_text
|
62 |
+
|
63 |
+
# Guardar la respuesta completa en el historial
|
64 |
+
if full_response:
|
65 |
+
self.conversation_history.append(f"Assistant: {full_response}")
|
66 |
+
|
67 |
+
except Exception as e:
|
68 |
+
logger.error(f"Error en streaming de respuesta: {str(e)}")
|
69 |
+
yield f"Error en la comunicaci贸n: {str(e)}"
|
70 |
|
71 |
except Exception as e:
|
72 |
logger.error(f"Error en process_chat_input: {str(e)}")
|
73 |
+
yield f"Error: {str(e)}"
|
74 |
+
|
75 |
+
def get_conversation_history(self) -> list:
|
76 |
+
"""
|
77 |
+
Retorna el historial de la conversaci贸n
|
78 |
+
Returns:
|
79 |
+
list: Lista de mensajes
|
80 |
+
"""
|
81 |
+
return self.conversation_history
|
82 |
+
|
83 |
+
def clear_history(self):
|
84 |
+
"""
|
85 |
+
Limpia el historial de la conversaci贸n
|
86 |
+
"""
|
87 |
+
self.conversation_history = []
|