Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| from mistralai.client import MistralClient | |
| # --- Configuração da API da Mistral --- | |
| api_key = os.environ.get("CHAT01") | |
| mistral_client = None | |
| if not api_key: | |
| print("AVISO: A chave da API Mistral (CHAT01) não está configurada nas variáveis de ambiente.") | |
| else: | |
| try: | |
| mistral_client = MistralClient(api_key=api_key) | |
| print("✅ Cliente Mistral inicializado com sucesso!") | |
| except Exception as e: | |
| print(f"❌ ERRO ao inicializar o cliente Mistral: {e}") | |
| mistral_client = None | |
| # --- Função de resposta do chatbot --- | |
| def chatbot_response(messages): | |
| """ | |
| messages: lista de mensagens no formato [{role: "user", content: "..."}, {role: "assistant", content: "..."}] | |
| """ | |
| if mistral_client is None: | |
| return {"role": "assistant", "content": "⚠️ Serviço de IA indisponível. Verifique a chave da API."} | |
| try: | |
| print(f"📤 Enviando para a API: {messages[-1]['content'][:50]}...") | |
| chat_response = mistral_client.chat( | |
| model="mistral-large-latest", | |
| messages=messages | |
| ) | |
| resposta_bot = chat_response.choices[0].message["content"] | |
| print(f"📥 Resposta recebida: {resposta_bot[:50]}...") | |
| return {"role": "assistant", "content": resposta_bot} | |
| except Exception as e: | |
| print(f"❌ ERRO ao chamar a API da Mistral: {e}") | |
| return {"role": "assistant", "content": f"Erro ao processar sua solicitação: {e}"} | |
| # --- Interface do Gradio --- | |
| interface = gr.ChatInterface( | |
| fn=chatbot_response, | |
| title="🤖 Meu Chatbot com Mistral AI", | |
| description="Converse com um modelo da Mistral AI em tempo real!", | |
| examples=[ | |
| [{"role": "user", "content": "Qual a capital do Brasil?"}], | |
| [{"role": "user", "content": "Explique o que é inteligência artificial."}], | |
| [{"role": "user", "content": "Sugira 3 nomes para um cachorro."}], | |
| ], | |
| chatbot=gr.Chatbot() # <--- Corrigido aqui, removido "type" | |
| ) | |
| # --- Lançamento da aplicação --- | |
| if __name__ == "__main__": | |
| interface.launch() | |