Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from huggingface_hub import InferenceClient
|
| 5 |
+
|
| 6 |
+
# Carrega o token da API do arquivo .env (crie o arquivo com HF_API_TOKEN=seu_token)
|
| 7 |
+
load_dotenv()
|
| 8 |
+
api_key = os.getenv("HF_API_TOKEN")
|
| 9 |
+
|
| 10 |
+
# Inicializa o cliente de inferência (usa a API gratuita do HF)
|
| 11 |
+
client = InferenceClient(token=api_key) # Sem provider específico, usa o padrão do HF para Mistral
|
| 12 |
+
|
| 13 |
+
# Função do chatbot: Lida com histórico e prompt do usuário
|
| 14 |
+
def chat_with_llm(message, history):
|
| 15 |
+
try:
|
| 16 |
+
# Constrói o histórico de mensagens no formato esperado (multi-turn)
|
| 17 |
+
messages = []
|
| 18 |
+
for user_msg, bot_msg in history:
|
| 19 |
+
messages.append({"role": "user", "content": user_msg})
|
| 20 |
+
if bot_msg:
|
| 21 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 22 |
+
messages.append({"role": "user", "content": message})
|
| 23 |
+
|
| 24 |
+
# Chama a API do Mistral
|
| 25 |
+
response = client.chat.completions.create(
|
| 26 |
+
model="mistralai/Mistral-7B-Instruct-v0.3",
|
| 27 |
+
messages=messages,
|
| 28 |
+
max_tokens=150, # Limite de tokens gerados (ajuste para mais/menos)
|
| 29 |
+
temperature=0.7, # Controle de criatividade (0.0 a 1.0)
|
| 30 |
+
)
|
| 31 |
+
return response.choices[0].message.content
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return f"Erro: {str(e)}. Verifique seu token API ou limites de uso."
|
| 34 |
+
|
| 35 |
+
# Cria a interface do chatbot no Gradio
|
| 36 |
+
demo = gr.ChatInterface(
|
| 37 |
+
fn=chat_with_llm,
|
| 38 |
+
title="Chatbot com Mistral (Gratuito via HF API)",
|
| 39 |
+
description="Teste o chatbot usando Mistral. Plano gratuito com limites.",
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
# Lança o app (no Spaces, isso é automático)
|
| 43 |
+
if __name__ == "__main__":
|
| 44 |
+
demo.launch()
|