AIdeaText commited on
Commit
76e552d
1 Parent(s): 3997599

Create chatbot.py

Browse files
Files changed (1) hide show
  1. modules/chatbot.py +50 -0
modules/chatbot.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
11
+ self.client = anthropic.Anthropic(api_key=api_key)
12
+ self.conversation_history = []
13
+
14
+ def generate_response(self, prompt, lang_code):
15
+ self.conversation_history.append(f"Human: {prompt}")
16
+ full_message = "\n".join(self.conversation_history)
17
+
18
+ try:
19
+ response = self.client.completions.create(
20
+ model="claude-2",
21
+ prompt=f"{full_message}\n\nAssistant:",
22
+ max_tokens_to_sample=300,
23
+ temperature=0.7,
24
+ stop_sequences=["Human:"]
25
+ )
26
+
27
+ claude_response = response.completion.strip()
28
+ self.conversation_history.append(f"Assistant: {claude_response}")
29
+
30
+ if len(self.conversation_history) > 10:
31
+ self.conversation_history = self.conversation_history[-10:]
32
+
33
+ return claude_response
34
+
35
+ except anthropic.APIError as e:
36
+ st.error(f"Error al llamar a la API de Claude: {str(e)}")
37
+ return "Lo siento, hubo un error al procesar tu solicitud."
38
+
39
+ def initialize_chatbot():
40
+ return ClaudeAPIChat()
41
+
42
+ def get_chatbot_response(chatbot, prompt, lang_code):
43
+ if 'api_calls' not in st.session_state:
44
+ st.session_state.api_calls = 0
45
+
46
+ if st.session_state.api_calls >= 50: # Límite de 50 llamadas por sesión
47
+ return "Lo siento, has alcanzado el límite de consultas para esta sesión."
48
+
49
+ st.session_state.api_calls += 1
50
+ return chatbot.generate_response(prompt, lang_code)