Update modules/chatbot/chat_process.py
Browse files- modules/chatbot/chat_process.py +24 -45
modules/chatbot/chat_process.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
-
# modules/chatbot/
|
2 |
-
import anthropic
|
3 |
import os
|
|
|
4 |
import logging
|
5 |
from typing import Dict, Generator
|
6 |
|
@@ -10,63 +10,44 @@ 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贸
|
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
|
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 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
max_tokens=300,
|
43 |
temperature=0.7,
|
44 |
-
|
45 |
-
messages=[
|
46 |
-
{
|
47 |
-
"role": "user",
|
48 |
-
"content": message
|
49 |
-
}
|
50 |
-
],
|
51 |
-
stream=True
|
52 |
)
|
53 |
|
54 |
-
# Procesar la respuesta
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
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)}")
|
@@ -75,8 +56,6 @@ class ChatProcessor:
|
|
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 |
|
|
|
1 |
+
# modules/chatbot/chat_process.py
|
|
|
2 |
import os
|
3 |
+
import anthropic
|
4 |
import logging
|
5 |
from typing import Dict, Generator
|
6 |
|
|
|
10 |
def __init__(self):
|
11 |
"""
|
12 |
Inicializa el procesador de chat con la API de Claude
|
|
|
|
|
13 |
"""
|
14 |
api_key = os.environ.get("ANTHROPIC_API_KEY")
|
15 |
if not api_key:
|
16 |
+
raise ValueError("No se encontr贸 la clave API de Anthropic. Aseg煤rate de configurarla en las variables de entorno.")
|
17 |
|
18 |
self.client = anthropic.Anthropic(api_key=api_key)
|
19 |
self.conversation_history = []
|
20 |
|
21 |
def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
|
22 |
"""
|
23 |
+
Procesa el mensaje y genera una respuesta
|
|
|
|
|
|
|
|
|
|
|
24 |
"""
|
25 |
try:
|
26 |
# Agregar mensaje a la historia
|
27 |
self.conversation_history.append(f"Human: {message}")
|
28 |
+
full_message = "\n".join(self.conversation_history)
|
29 |
+
|
30 |
+
# Generar respuesta usando la API de Claude
|
31 |
+
response = self.client.completions.create(
|
32 |
+
model="claude-2",
|
33 |
+
prompt=f"{full_message}\n\nAssistant:",
|
34 |
+
max_tokens_to_sample=300,
|
|
|
35 |
temperature=0.7,
|
36 |
+
stop_sequences=["Human:"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
)
|
38 |
|
39 |
+
# Procesar la respuesta
|
40 |
+
claude_response = response.completion.strip()
|
41 |
+
self.conversation_history.append(f"Assistant: {claude_response}")
|
42 |
+
|
43 |
+
# Mantener un historial limitado
|
44 |
+
if len(self.conversation_history) > 10:
|
45 |
+
self.conversation_history = self.conversation_history[-10:]
|
46 |
+
|
47 |
+
# Dividir la respuesta en palabras para streaming
|
48 |
+
words = claude_response.split()
|
49 |
+
for word in words:
|
50 |
+
yield word + " "
|
|
|
|
|
|
|
|
|
51 |
|
52 |
except Exception as e:
|
53 |
logger.error(f"Error en process_chat_input: {str(e)}")
|
|
|
56 |
def get_conversation_history(self) -> list:
|
57 |
"""
|
58 |
Retorna el historial de la conversaci贸n
|
|
|
|
|
59 |
"""
|
60 |
return self.conversation_history
|
61 |
|