Spaces:
Runtime error
Runtime error
.env
#1
by
RodriiS
- opened
- app.py +18 -39
- requirements.txt +0 -8
app.py
CHANGED
@@ -1,65 +1,44 @@
|
|
1 |
import os
|
2 |
from dotenv import load_dotenv
|
3 |
import gradio as gr
|
4 |
-
from
|
5 |
|
6 |
-
# Carrega
|
7 |
load_dotenv()
|
8 |
api_key = os.getenv("HF_API_TOKEN")
|
9 |
-
if not api_key:
|
10 |
-
raise ValueError("Erro: HF_API_TOKEN não encontrado. Configure-o nas secrets do Space.")
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
-
load_in_4bit=True,
|
15 |
-
bnb_4bit_quant_type="nf4",
|
16 |
-
bnb_4bit_use_double_quant=True,
|
17 |
-
bnb_4bit_compute_dtype="bfloat16"
|
18 |
-
)
|
19 |
-
|
20 |
-
# Inicializa o modelo e o tokenizer
|
21 |
-
model_id = "Qwen/Qwen2-7B-Instruct-GPTQ-Int4" # Modelo GPTQ oficial da Qwen
|
22 |
-
tokenizer = AutoTokenizer.from_pretrained(model_id, token=api_key)
|
23 |
-
model = AutoModelForCausalLM.from_pretrained(
|
24 |
-
model_id,
|
25 |
-
quantization_config=quant_config,
|
26 |
-
device_map="auto",
|
27 |
-
token=api_key
|
28 |
-
)
|
29 |
|
30 |
-
# Função do chatbot
|
31 |
def chat_with_llm(message, history):
|
32 |
try:
|
33 |
-
# Constrói o histórico de mensagens
|
34 |
messages = []
|
35 |
for user_msg, bot_msg in history:
|
36 |
messages.append({"role": "user", "content": user_msg})
|
37 |
if bot_msg:
|
38 |
messages.append({"role": "assistant", "content": bot_msg})
|
39 |
messages.append({"role": "user", "content": message})
|
40 |
-
|
41 |
-
# Tokeniza a entrada
|
42 |
-
inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to("cuda")
|
43 |
|
44 |
-
#
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
do_sample=True
|
51 |
)
|
52 |
-
response
|
53 |
-
return response
|
54 |
except Exception as e:
|
55 |
-
return f"Erro: {str(e)}. Verifique
|
56 |
|
57 |
-
#
|
58 |
demo = gr.ChatInterface(
|
59 |
fn=chat_with_llm,
|
60 |
-
title="Chatbot com
|
61 |
-
description="
|
62 |
)
|
63 |
|
|
|
64 |
if __name__ == "__main__":
|
65 |
demo.launch()
|
|
|
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()
|
requirements.txt
DELETED
@@ -1,8 +0,0 @@
|
|
1 |
-
gradio==4.40.0
|
2 |
-
huggingface_hub==0.23.4
|
3 |
-
python-dotenv==1.0.1
|
4 |
-
transformers
|
5 |
-
bitsandbytes
|
6 |
-
accelerate
|
7 |
-
gradio
|
8 |
-
python-dotenv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|