AIdeaText commited on
Commit
0a34bb0
verified
1 Parent(s): c743fe6

Create chat_process-backUp-19-5-2025.py

Browse files
modules/chatbot/chat_process-backUp-19-5-2025.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modules/chatbot/chat_process.py
2
+ import os
3
+ import anthropic
4
+ import logging
5
+ from typing import Dict, Generator
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ ####################################################
10
+ class ChatProcessor:
11
+ def __init__(self):
12
+ """Inicializa el procesador de chat con la API de Claude"""
13
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
14
+ if not api_key:
15
+ raise ValueError("No se encontr贸 la clave API de Anthropic. Aseg煤rate de configurarla en las variables de entorno.")
16
+ self.client = anthropic.Anthropic(api_key=api_key)
17
+ self.conversation_history = []
18
+
19
+ def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
20
+ """Procesa el mensaje y genera una respuesta"""
21
+ try:
22
+ # Agregar mensaje a la historia
23
+ self.conversation_history.append({"role": "user", "content": message})
24
+
25
+ # Generar respuesta usando la API de Claude
26
+ response = self.client.messages.create(
27
+ model="claude-3-5-sonnet-20241022",
28
+ messages=self.conversation_history,
29
+ max_tokens=8000, # A帽adimos este par谩metro requerido
30
+ temperature=0.7,
31
+ )
32
+
33
+ # Procesar la respuesta
34
+ claude_response = response.content[0].text
35
+ self.conversation_history.append({"role": "assistant", "content": claude_response})
36
+
37
+ # Mantener un historial limitado
38
+ if len(self.conversation_history) > 10:
39
+ self.conversation_history = self.conversation_history[-10:]
40
+
41
+ # Dividir la respuesta en palabras para streaming
42
+ words = claude_response.split()
43
+ for word in words:
44
+ yield word + " "
45
+
46
+ except Exception as e:
47
+ logger.error(f"Error en process_chat_input: {str(e)}")
48
+ yield f"Error: {str(e)}"
49
+
50
+ def get_conversation_history(self) -> list:
51
+ """Retorna el historial de la conversaci贸n"""
52
+ return self.conversation_history
53
+
54
+ def clear_history(self):
55
+ """Limpia el historial de la conversaci贸n"""
56
+ self.conversation_history = []