File size: 2,418 Bytes
76e552d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44a288d
 
 
76e552d
44a288d
 
 
 
 
 
 
 
76e552d
44a288d
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
            yield "Lo siento, has alcanzado el l铆mite de consultas para esta sesi贸n."
            return
    
        try:
            st.session_state.api_calls += 1
            response = chatbot.generate_response(prompt, lang_code)
            
            # Dividir la respuesta en palabras
            words = response.split()
            
            # Devolver las palabras una por una
            for word in words:
                yield word + " "
        except Exception as e:
            yield f"Error: {str(e)}"