Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import dotenv
|
3 |
+
import requests
|
4 |
+
from transformers import AutoTokenizer
|
5 |
+
import streamlit as st
|
6 |
+
|
7 |
+
|
8 |
+
dotenv.load_dotenv()
|
9 |
+
token = os.environ['HF_TOKEN']
|
10 |
+
|
11 |
+
|
12 |
+
# add models here
|
13 |
+
modelos = {
|
14 |
+
'Felladrin/Llama-68M-Chat-v1': '[/INST]',
|
15 |
+
'google/gemma-7b-it': '<start_of_turn>model\n',
|
16 |
+
'google/gemma-2-2b-it': '<start_of_turn>model\n'
|
17 |
+
}
|
18 |
+
|
19 |
+
nome_modelo = st.selectbox('select a model:', options=modelos)
|
20 |
+
token_modelo = modelos[nome_modelo]
|
21 |
+
|
22 |
+
url = f"https://api-inference.huggingface.co/models/{nome_modelo}"
|
23 |
+
tokenizer = AutoTokenizer.from_pretrained(nome_modelo)
|
24 |
+
|
25 |
+
if 'modelo_atual' not in st.session_state or st.session_state['modelo_atual'] != nome_modelo:
|
26 |
+
st.session_state['modelo_atual'] = nome_modelo
|
27 |
+
st.session_state['mensagens'] = []
|
28 |
+
|
29 |
+
mensagens = st.session_state['mensagens']
|
30 |
+
|
31 |
+
area_chat = st.empty()
|
32 |
+
pergunta_usuario = st.chat_input('Do you question here: ')
|
33 |
+
|
34 |
+
if pergunta_usuario:
|
35 |
+
mensagens.append({'role': 'user', 'content': pergunta_usuario})
|
36 |
+
inputs = tokenizer.apply_chat_template(mensagens, tokenize=False, add_generation_prompt=True)
|
37 |
+
json = {
|
38 |
+
'inputs': inputs,
|
39 |
+
'parameters': {'max_new_tokens': 1_000},
|
40 |
+
'options': {'use_cache': False, 'wait_for_model': True},
|
41 |
+
}
|
42 |
+
headers = {
|
43 |
+
'Authorization': f'Bearer {token}',
|
44 |
+
}
|
45 |
+
|
46 |
+
# Send request and verify response
|
47 |
+
response = requests.post(url, json=json, headers=headers).json()
|
48 |
+
|
49 |
+
# verify if response is valid
|
50 |
+
if isinstance(response, list) and len(response) > 0 and 'generated_text' in response[0]:
|
51 |
+
resposta_chatbot = response[0]['generated_text'].split(token_modelo)[-1]
|
52 |
+
mensagens.append({'role': 'assistant', 'content': resposta_chatbot})
|
53 |
+
else:
|
54 |
+
mensagens.append({'role': 'assistant', 'content': "Desculpe, algo deu errado ao processar sua solicitação."})
|
55 |
+
|
56 |
+
with area_chat.container():
|
57 |
+
for mensagem in mensagens:
|
58 |
+
chat = st.chat_message(mensagem['role'])
|
59 |
+
chat.markdown(mensagem['content'])
|