Pedro Henrique Ton Pauletti
commited on
Commit
·
9f47485
1
Parent(s):
11f2aae
feat: Add env example and update app
Browse files- .env.example +8 -0
- .gitignore +1 -0
- app.py +161 -42
- imgs/chatbot-avatar-open.png +0 -0
- requirements.txt +4 -1
.env.example
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
AZURE_AISEARCH_API_KEY=
|
2 |
+
AZURE_AISEARCH_ENDPOINT=https://search-legislation.search.windows.net
|
3 |
+
AZURE_AISEARCH_INDEX=
|
4 |
+
AOAI_API_KEY=
|
5 |
+
AOAI_ENDPOINT=https://openai-chabot.openai.azure.com/
|
6 |
+
AOAI_API_VERSION=2023-03-15-preview
|
7 |
+
AZURE_ML_ENDPOINT=https://Phi-3-5-mini-instruct-pzgvm.eastus.models.ai.azure.com/chat/completions
|
8 |
+
AZURE_ML_API_KEY=
|
.gitignore
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
.env
|
app.py
CHANGED
@@ -1,21 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
|
10 |
def respond(
|
11 |
message,
|
12 |
history: list[tuple[str, str]],
|
13 |
-
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
):
|
18 |
-
messages = [
|
19 |
|
20 |
for val in history:
|
21 |
if val[0]:
|
@@ -27,38 +74,110 @@ def respond(
|
|
27 |
|
28 |
response = ""
|
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 |
if __name__ == "__main__":
|
64 |
-
demo.launch()
|
|
|
1 |
+
import time
|
2 |
+
from dotenv import load_dotenv
|
3 |
+
import os
|
4 |
+
from azure.search.documents import SearchClient
|
5 |
+
from azure.core.credentials import AzureKeyCredential
|
6 |
import gradio as gr
|
7 |
+
import random
|
8 |
+
from openai import AzureOpenAI
|
9 |
+
import requests
|
10 |
+
import json
|
11 |
+
from requests.auth import HTTPBasicAuth
|
12 |
|
13 |
+
load_dotenv()
|
14 |
+
|
15 |
+
# Set up the search client with your service details
|
16 |
+
search_client = SearchClient(endpoint=os.getenv("AZURE_AISEARCH_ENDPOINT"),
|
17 |
+
index_name=os.getenv("AZURE_AISEARCH_INDEX"),
|
18 |
+
credential=AzureKeyCredential(os.getenv("AZURE_AISEARCH_API_KEY")))
|
19 |
+
|
20 |
+
client = AzureOpenAI(
|
21 |
+
api_key= os.getenv("AOAI_API_KEY"),
|
22 |
+
api_version= os.getenv("AOAI_API_VERSION"),
|
23 |
+
azure_endpoint= os.getenv("AOAI_ENDPOINT"),
|
24 |
+
)
|
25 |
+
|
26 |
+
# Informações do endpoint
|
27 |
+
azure_ml_endpoint_url = os.getenv("AZURE_ML_ENDPOINT")
|
28 |
+
azure_ml_api_key = os.getenv("AZURE_ML_API_KEY")
|
29 |
+
|
30 |
+
# Headers para autenticação e conteúdo
|
31 |
+
headers = {
|
32 |
+
"Content-Type": "application/json",
|
33 |
+
"Authorization": f"{azure_ml_api_key}"
|
34 |
+
}
|
35 |
+
|
36 |
+
def search(user_query):
|
37 |
+
search_results = search_client.search(
|
38 |
+
search_text=user_query,
|
39 |
+
highlight_fields="content", # Indicar o campo que deve ser realçado
|
40 |
+
top=3 # Limitar o número de resultados retornados
|
41 |
+
)
|
42 |
+
|
43 |
+
# Estruturar os resultados
|
44 |
+
contents = []
|
45 |
+
sources = []
|
46 |
+
for result in search_results:
|
47 |
+
document_name = result['metadata_storage_name']
|
48 |
+
formatted_name = document_name.replace("_", " ").replace(".pdf", "").upper()
|
49 |
+
sources.append(formatted_name)
|
50 |
+
|
51 |
+
# Pegar os highlights e unificar em uma string
|
52 |
+
highlights = " ".join(result.get('@search.highlights', {}).get('content', []))
|
53 |
+
contents.append(f"Fonte: {formatted_name}\nTrecho destacado: {highlights}")
|
54 |
+
|
55 |
+
# Combinar os resultados em uma única string
|
56 |
+
highlighted_content = "\n\n".join(contents)
|
57 |
+
return highlighted_content
|
58 |
|
59 |
|
60 |
def respond(
|
61 |
message,
|
62 |
history: list[tuple[str, str]],
|
63 |
+
model
|
|
|
|
|
|
|
64 |
):
|
65 |
+
messages = []
|
66 |
|
67 |
for val in history:
|
68 |
if val[0]:
|
|
|
74 |
|
75 |
response = ""
|
76 |
|
77 |
+
highlighted_content = search(message)
|
78 |
+
GROUNDED_PROMPT = f"""
|
79 |
+
Você é um assistente virtual amigável especializado em responder questões sobre a legislação das Resoluções e Portarias da universidade Unesp. O conteúdo dos atos normativos é de responsabilidade do Grupo Técnico de Informação e Documentação da Secretaria Geral (GTID/SG).
|
80 |
+
|
81 |
+
Instruções:
|
82 |
+
1. Responda à pergunta usando **somente** as fontes fornecidas abaixo.
|
83 |
+
2. Seja amigável e conciso em suas respostas.
|
84 |
+
3. Cite a fonte utilizada durante e ao final da resposta.
|
85 |
+
4. Responda **apenas** com os fatos relacionados nas fontes fornecidas.
|
86 |
+
5. Se não houver informações suficientes nas fontes abaixo, informe que não sabe.
|
87 |
+
6. Não gere respostas que não usem as fontes fornecidas.
|
88 |
+
7. Formate o nome do arquivo da fonte para apenas o nome da fonte (exemplo: RESOLUÇÃO_UNESP_Nº_05_DE_07_DE_FEVEREIRO_DE_2024.pdf -> RESOLUÇÃO UNESP Nº05 DE 07 DE FEVEREIRO DE 2024).
|
89 |
+
8. Sempre que possível, cite no início da resposta o artigo, parágrafo, inciso, alíneas e/ou itens que foi retirado a resposta.
|
90 |
+
|
91 |
+
Fontes e Trechos Destacados:
|
92 |
+
{highlighted_content}
|
93 |
+
|
94 |
+
Pergunta:
|
95 |
+
{message}
|
96 |
+
|
97 |
+
Formato de Resposta:
|
98 |
+
1. **Introdução**: Comece com uma saudação amigável e uma breve introdução.
|
99 |
+
2. **Resposta**: Forneça a resposta à pergunta de forma clara e concisa.
|
100 |
+
3. **Citação de Fontes**: Cite a fonte utilizada durante e ao final da resposta.
|
101 |
+
4. **Conclusão**: Termine com uma frase de encerramento amigável.
|
102 |
+
|
103 |
+
Exemplo de Resposta:
|
104 |
+
|
105 |
+
Olá! Obrigado por sua pergunta.
|
106 |
+
|
107 |
+
[resposta]
|
108 |
+
|
109 |
+
Fonte(s): [nome da fonte usada].
|
110 |
+
"""
|
111 |
+
print("Modelo = ", model)
|
112 |
+
if model == "gpt-4" or model == "gpt-35-turbo":
|
113 |
+
completion = client.chat.completions.create(
|
114 |
+
model="gpt-35-turbo",
|
115 |
+
messages=[
|
116 |
+
{
|
117 |
+
"role": "user",
|
118 |
+
"content": GROUNDED_PROMPT,
|
119 |
+
},
|
120 |
+
],
|
121 |
+
)
|
122 |
+
token = completion.choices[0].message.content
|
123 |
+
else: #Phi
|
124 |
+
data = {
|
125 |
+
"messages": [
|
126 |
+
{"role": "user", "content": GROUNDED_PROMPT}
|
127 |
+
],
|
128 |
+
"temperature": 0.8,
|
129 |
+
"top_p": 0.1,
|
130 |
+
"max_tokens": 2048
|
131 |
+
}
|
132 |
+
|
133 |
+
# Converta para JSON
|
134 |
+
payload = json.dumps(data)
|
135 |
+
# Realizar a inferência
|
136 |
+
response_api = requests.post(azure_ml_endpoint_url, headers=headers, data=payload)
|
137 |
+
response_json = response_api.json()
|
138 |
+
content = response_json['choices'][0]['message']['content']
|
139 |
+
token = content.strip()
|
140 |
+
|
141 |
+
response += token
|
142 |
+
# yield response
|
143 |
+
|
144 |
+
# Envia o texto gradualmente (efeito de digitação)
|
145 |
+
displayed_response = ""
|
146 |
+
for char in response:
|
147 |
+
displayed_response += char
|
148 |
+
time.sleep(0.01) # Intervalo entre os caracteres para o efeito de digitação
|
149 |
+
yield displayed_response
|
150 |
+
|
151 |
+
|
152 |
+
examplesChatbot = [
|
153 |
+
["Quais são Instrumentos para a Execução da Política de SANS da UNESP?"],
|
154 |
+
["Qual é o prazo de integralização do curso de graduação em Medicina Veterinária?"],
|
155 |
+
["Qual a estrutura curricular do Curso de Engenharia Agronômica da Faculdade de Ciências Agrárias e Veterinárias do câmpus de Jaboticabal?"],
|
156 |
+
["Quais são os membros da Comissão Permanente de Avaliação - CPA para o exercício de 2024?"]
|
157 |
+
|
158 |
+
]
|
159 |
+
|
160 |
+
chatbot = gr.Chatbot(
|
161 |
+
placeholder="<strong>Sou o Chatbot de Legislação da Unesp</strong><br>Fique à vontade para fazer perguntas",
|
162 |
+
bubble_full_width=True,
|
163 |
+
avatar_images=(None, os.path.join("imgs", "chatbot-avatar-open.png")),
|
164 |
+
)
|
165 |
+
text = gr.Textbox(placeholder="Faça uma pergunta sobre a Legislação da Unesp", submit_btn=True)
|
166 |
+
dropdown = gr.Dropdown(["gpt-35-turbo", "gpt-4", "Phi-3-5-mini-instruct"], label='Modelo',)
|
167 |
|
168 |
+
with gr.Blocks() as demo:
|
169 |
+
chat = gr.ChatInterface(
|
170 |
+
respond,
|
171 |
+
textbox=text,
|
172 |
+
additional_inputs=[
|
173 |
+
dropdown,
|
174 |
+
],
|
175 |
+
additional_inputs_accordion = 'Configurações',
|
176 |
+
chatbot=chatbot,
|
177 |
+
# examples= examplesChatbot,
|
178 |
+
# theme = 'soft'
|
179 |
+
)
|
180 |
+
examples_list = gr.Examples(examples=examplesChatbot, inputs=text)
|
181 |
|
182 |
if __name__ == "__main__":
|
183 |
+
demo.launch(debug=True)
|
imgs/chatbot-avatar-open.png
ADDED
![]() |
requirements.txt
CHANGED
@@ -1 +1,4 @@
|
|
1 |
-
huggingface_hub==0.25.2
|
|
|
|
|
|
|
|
1 |
+
huggingface_hub==0.25.2
|
2 |
+
openai
|
3 |
+
azure-search-documents
|
4 |
+
azure-core
|