test2 / modules /chatbot.py
AIdeaText's picture
Create chatbot.py
76e552d verified
raw
history blame
1.87 kB
import os
import anthropic
import streamlit as st
class ClaudeAPIChat:
def __init__(self):
api_key = os.environ.get("ANTHROPIC_API_KEY")
if not api_key:
raise ValueError("No se encontr贸 la clave API de Anthropic. Aseg煤rate de configurarla en las variables de entorno.")
self.client = anthropic.Anthropic(api_key=api_key)
self.conversation_history = []
def generate_response(self, prompt, lang_code):
self.conversation_history.append(f"Human: {prompt}")
full_message = "\n".join(self.conversation_history)
try:
response = self.client.completions.create(
model="claude-2",
prompt=f"{full_message}\n\nAssistant:",
max_tokens_to_sample=300,
temperature=0.7,
stop_sequences=["Human:"]
)
claude_response = response.completion.strip()
self.conversation_history.append(f"Assistant: {claude_response}")
if len(self.conversation_history) > 10:
self.conversation_history = self.conversation_history[-10:]
return claude_response
except anthropic.APIError as e:
st.error(f"Error al llamar a la API de Claude: {str(e)}")
return "Lo siento, hubo un error al procesar tu solicitud."
def initialize_chatbot():
return ClaudeAPIChat()
def get_chatbot_response(chatbot, prompt, lang_code):
if 'api_calls' not in st.session_state:
st.session_state.api_calls = 0
if st.session_state.api_calls >= 50: # L铆mite de 50 llamadas por sesi贸n
return "Lo siento, has alcanzado el l铆mite de consultas para esta sesi贸n."
st.session_state.api_calls += 1
return chatbot.generate_response(prompt, lang_code)