AIdeaText commited on
Commit
5d255fb
1 Parent(s): 2598968

Create chatbot/chatbot.py

Browse files
Files changed (1) hide show
  1. modules/chatbot/chatbot.py +55 -0
modules/chatbot/chatbot.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import anthropic
3
+ import streamlit as st
4
+
5
+ class ClaudeAPIChat:
6
+ def __init__(self):
7
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
8
+ if not api_key:
9
+ raise ValueError("No se encontró la clave API de Anthropic. Asegúrate de configurarla en las variables de entorno.")
10
+ self.client = anthropic.Anthropic(api_key=api_key)
11
+ self.conversation_history = []
12
+
13
+ def generate_response(self, prompt, lang_code):
14
+ self.conversation_history.append(f"Human: {prompt}")
15
+ full_message = "\n".join(self.conversation_history)
16
+ try:
17
+ response = self.client.completions.create(
18
+ model="claude-2",
19
+ prompt=f"{full_message}\n\nAssistant:",
20
+ max_tokens_to_sample=300,
21
+ temperature=0.7,
22
+ stop_sequences=["Human:"]
23
+ )
24
+ claude_response = response.completion.strip()
25
+ self.conversation_history.append(f"Assistant: {claude_response}")
26
+ if len(self.conversation_history) > 10:
27
+ self.conversation_history = self.conversation_history[-10:]
28
+ return claude_response
29
+ except anthropic.APIError as e:
30
+ st.error(f"Error al llamar a la API de Claude: {str(e)}")
31
+ return "Lo siento, hubo un error al procesar tu solicitud."
32
+
33
+ def initialize_chatbot():
34
+ return ClaudeAPIChat()
35
+
36
+ def get_chatbot_response(chatbot, prompt, lang_code):
37
+ if 'api_calls' not in st.session_state:
38
+ st.session_state.api_calls = 0
39
+
40
+ if st.session_state.api_calls >= 50: # Límite de 50 llamadas por sesión
41
+ yield "Lo siento, has alcanzado el límite de consultas para esta sesión."
42
+ return
43
+
44
+ try:
45
+ st.session_state.api_calls += 1
46
+ response = chatbot.generate_response(prompt, lang_code)
47
+
48
+ # Dividir la respuesta en palabras
49
+ words = response.split()
50
+
51
+ # Devolver las palabras una por una
52
+ for word in words:
53
+ yield word + " "
54
+ except Exception as e:
55
+ yield f"Error: {str(e)}"