Create chatbot.py
Browse files- 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)
|