Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,10 +2,10 @@ import os
|
|
| 2 |
from dotenv import load_dotenv
|
| 3 |
from langchain_openai import ChatOpenAI
|
| 4 |
from langchain.prompts import PromptTemplate
|
| 5 |
-
from langchain.chains import ConversationChain
|
| 6 |
-
from langchain.memory import ConversationBufferMemory
|
| 7 |
import gradio as gr
|
| 8 |
-
import traceback
|
| 9 |
|
| 10 |
# Carrega a chave da API
|
| 11 |
load_dotenv()
|
|
@@ -20,35 +20,22 @@ os.environ["OPENAI_API_BASE"] = "https://openrouter.ai/api/v1"
|
|
| 20 |
|
| 21 |
# Instancia o modelo
|
| 22 |
llm = ChatOpenAI(
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
temperature=0.5 # Slightly increased temperature for potentially more varied explanations
|
| 26 |
)
|
| 27 |
|
| 28 |
-
#
|
| 29 |
subjects = [
|
| 30 |
-
"Python",
|
| 31 |
-
"
|
| 32 |
-
"Ruby",
|
| 33 |
-
"Golang",
|
| 34 |
-
"C++",
|
| 35 |
-
"C#",
|
| 36 |
-
"Rust",
|
| 37 |
-
"SQL",
|
| 38 |
-
"Tableau",
|
| 39 |
-
"Power BI",
|
| 40 |
-
"Excel",
|
| 41 |
-
"Looker",
|
| 42 |
-
"Solidity"
|
| 43 |
]
|
| 44 |
|
| 45 |
-
# --- Template
|
| 46 |
-
#
|
| 47 |
-
template_string = """Você é um assistente virtual e tutor especialista
|
| 48 |
-
Ajude os alunos com dúvidas sobre
|
| 49 |
-
Adapte a profundidade da sua resposta ao nível aparente da pergunta.
|
| 50 |
-
|
| 51 |
-
Concentre-se estritamente em {subject}, a menos que o aluno peça explicitamente para comparar com outra tecnologia.
|
| 52 |
|
| 53 |
Histórico da conversa:
|
| 54 |
{history}
|
|
@@ -56,55 +43,56 @@ Histórico da conversa:
|
|
| 56 |
Aluno: {input}
|
| 57 |
Resposta:"""
|
| 58 |
|
|
|
|
| 59 |
template = PromptTemplate(
|
| 60 |
-
input_variables=["history", "input"
|
| 61 |
template=template_string
|
| 62 |
)
|
| 63 |
|
| 64 |
-
# --- Memória da Conversa
|
| 65 |
-
#
|
| 66 |
-
#
|
| 67 |
-
memoria = ConversationBufferMemory(return_messages=True)
|
| 68 |
|
| 69 |
-
# --- Criação da Chain
|
| 70 |
-
#
|
| 71 |
-
#
|
| 72 |
-
# Alternatively, you could create a new chain object on each call, but that's less efficient.
|
| 73 |
chat_chain = ConversationChain(
|
| 74 |
llm=llm,
|
| 75 |
memory=memoria,
|
| 76 |
-
prompt=template, #
|
| 77 |
-
|
|
|
|
| 78 |
)
|
| 79 |
|
| 80 |
-
# --- Função para Responder com Contexto
|
| 81 |
def responder(subject, user_message):
|
| 82 |
"""
|
| 83 |
-
|
| 84 |
"""
|
| 85 |
if not subject:
|
| 86 |
return "⚠️ Por favor, selecione uma matéria primeiro."
|
| 87 |
-
if not user_message:
|
| 88 |
return "⚠️ Por favor, digite sua dúvida."
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
try:
|
| 91 |
-
#
|
| 92 |
-
|
| 93 |
-
response = chat_chain.run(input=user_message, subject=subject)
|
| 94 |
return response
|
| 95 |
except Exception as e:
|
| 96 |
-
# Log the full error for debugging
|
| 97 |
print(f"❌ Erro ao processar a solicitação:\n{traceback.format_exc()}")
|
| 98 |
-
# Return a user-friendly error message
|
| 99 |
return f"❌ Desculpe, ocorreu um erro ao processar sua solicitação. Detalhes: {str(e)}"
|
| 100 |
|
| 101 |
-
# --- Interface Gradio
|
| 102 |
-
with gr.Blocks() as app:
|
| 103 |
gr.Markdown("# Tutor Poliglota com IA 🤖🎓")
|
| 104 |
gr.Markdown("Selecione a matéria e tire suas dúvidas com um assistente que lembra da conversa.")
|
| 105 |
|
| 106 |
with gr.Row():
|
| 107 |
-
# Dropdown para selecionar a matéria
|
| 108 |
subject_selector = gr.Dropdown(
|
| 109 |
choices=subjects,
|
| 110 |
label="Selecione a Matéria",
|
|
@@ -112,44 +100,45 @@ with gr.Blocks() as app:
|
|
| 112 |
)
|
| 113 |
|
| 114 |
with gr.Row():
|
| 115 |
-
# Textbox para a pergunta do usuário
|
| 116 |
input_textbox = gr.Textbox(
|
| 117 |
placeholder="Ex: Como declarar uma variável em Java?",
|
| 118 |
label="Sua Dúvida",
|
| 119 |
-
lines=3
|
|
|
|
| 120 |
)
|
| 121 |
|
| 122 |
with gr.Row():
|
| 123 |
-
# Botão
|
| 124 |
-
submit_button = gr.Button("Perguntar ao Tutor")
|
| 125 |
|
| 126 |
with gr.Row():
|
| 127 |
-
# Textbox para a resposta do assistente
|
| 128 |
output_textbox = gr.Textbox(
|
| 129 |
label="Resposta do Tutor",
|
| 130 |
-
lines=
|
|
|
|
| 131 |
)
|
| 132 |
|
| 133 |
-
# Adiciona um botão para limpar a conversa (opcional, mas útil)
|
| 134 |
clear_button = gr.ClearButton(
|
| 135 |
-
components=[input_textbox, output_textbox],
|
| 136 |
-
value="Limpar
|
| 137 |
)
|
| 138 |
|
| 139 |
-
# Define a ação do botão de envio
|
| 140 |
submit_button.click(
|
| 141 |
fn=responder,
|
| 142 |
-
inputs=[subject_selector, input_textbox],
|
| 143 |
outputs=output_textbox
|
| 144 |
)
|
| 145 |
|
| 146 |
-
# Define a ação do botão Limpar para também limpar a memória da chain
|
| 147 |
def clear_memory_and_interface():
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
| 152 |
|
|
|
|
|
|
|
| 153 |
|
| 154 |
# Lança a aplicação
|
| 155 |
-
app.launch(share=True)
|
|
|
|
| 2 |
from dotenv import load_dotenv
|
| 3 |
from langchain_openai import ChatOpenAI
|
| 4 |
from langchain.prompts import PromptTemplate
|
| 5 |
+
from langchain.chains import ConversationChain # Keep using this for now, despite deprecation
|
| 6 |
+
from langchain.memory import ConversationBufferMemory # Keep using this for now
|
| 7 |
import gradio as gr
|
| 8 |
+
import traceback
|
| 9 |
|
| 10 |
# Carrega a chave da API
|
| 11 |
load_dotenv()
|
|
|
|
| 20 |
|
| 21 |
# Instancia o modelo
|
| 22 |
llm = ChatOpenAI(
|
| 23 |
+
model="mistralai/mistral-7b-instruct:free",
|
| 24 |
+
temperature=0.5
|
|
|
|
| 25 |
)
|
| 26 |
|
| 27 |
+
# Lista de Tutores/Matérias
|
| 28 |
subjects = [
|
| 29 |
+
"Python", "Java", "Ruby", "Golang", "C++", "C#", "Rust",
|
| 30 |
+
"SQL", "Tableau", "Power BI", "Excel", "Looker", "Solidity"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
]
|
| 32 |
|
| 33 |
+
# --- Template Modificado ---
|
| 34 |
+
# Agora SÓ espera 'history' e 'input'. O contexto da matéria será parte do 'input'.
|
| 35 |
+
template_string = """Você é um assistente virtual e tutor especialista. A especialidade desejada pelo aluno está indicada claramente no início da pergunta dele (procure por 'Especialidade Foco:').
|
| 36 |
+
Ajude os alunos com dúvidas sobre a especialidade mencionada na pergunta atual, sempre de forma clara, objetiva e com exemplos didáticos.
|
| 37 |
+
Adapte a profundidade da sua resposta ao nível aparente da pergunta. Se a pergunta for muito vaga, peça mais detalhes.
|
| 38 |
+
Concentre-se estritamente na especialidade indicada na pergunta atual, a menos que o aluno peça explicitamente para comparar com outra tecnologia.
|
|
|
|
| 39 |
|
| 40 |
Histórico da conversa:
|
| 41 |
{history}
|
|
|
|
| 43 |
Aluno: {input}
|
| 44 |
Resposta:"""
|
| 45 |
|
| 46 |
+
# Prompt agora só precisa de 'history' e 'input'
|
| 47 |
template = PromptTemplate(
|
| 48 |
+
input_variables=["history", "input"], # APENAS history e input
|
| 49 |
template=template_string
|
| 50 |
)
|
| 51 |
|
| 52 |
+
# --- Memória da Conversa ---
|
| 53 |
+
# Aviso de Depreciação: ConversationBufferMemory está sendo substituída.
|
| 54 |
+
# Para agora, ela funciona, mas considere migrar para RunnableWithMessageHistory no futuro.
|
| 55 |
+
memoria = ConversationBufferMemory(return_messages=True) # memory_key='history' é o padrão
|
| 56 |
|
| 57 |
+
# --- Criação da Chain ---
|
| 58 |
+
# Aviso de Depreciação: ConversationChain está sendo substituída.
|
| 59 |
+
# Para agora, ela funciona com o prompt ajustado.
|
|
|
|
| 60 |
chat_chain = ConversationChain(
|
| 61 |
llm=llm,
|
| 62 |
memory=memoria,
|
| 63 |
+
prompt=template, # Passa o prompt que agora só espera 'history' e 'input'
|
| 64 |
+
input_key='input', # Confirma que a chave de entrada principal é 'input' (padrão)
|
| 65 |
+
verbose=False
|
| 66 |
)
|
| 67 |
|
| 68 |
+
# --- Função para Responder com Contexto Formatado ---
|
| 69 |
def responder(subject, user_message):
|
| 70 |
"""
|
| 71 |
+
Formata a entrada e gera a resposta do LLM.
|
| 72 |
"""
|
| 73 |
if not subject:
|
| 74 |
return "⚠️ Por favor, selecione uma matéria primeiro."
|
| 75 |
+
if not user_message or not user_message.strip(): # Verifica se a mensagem não está vazia ou só espaços
|
| 76 |
return "⚠️ Por favor, digite sua dúvida."
|
| 77 |
|
| 78 |
+
# **Importante:** Formata a entrada para incluir o contexto da matéria
|
| 79 |
+
# É ESSENCIAL que o LLM veja essa informação claramente no início do input.
|
| 80 |
+
formatted_input = f"**Especialidade Foco:** {subject}\n\n**Dúvida do Aluno:** {user_message}"
|
| 81 |
+
|
| 82 |
try:
|
| 83 |
+
# Passa a string formatada como a única entrada 'input' para a chain
|
| 84 |
+
response = chat_chain.run(formatted_input)
|
|
|
|
| 85 |
return response
|
| 86 |
except Exception as e:
|
|
|
|
| 87 |
print(f"❌ Erro ao processar a solicitação:\n{traceback.format_exc()}")
|
|
|
|
| 88 |
return f"❌ Desculpe, ocorreu um erro ao processar sua solicitação. Detalhes: {str(e)}"
|
| 89 |
|
| 90 |
+
# --- Interface Gradio (sem alterações na estrutura) ---
|
| 91 |
+
with gr.Blocks(theme=gr.themes.Soft()) as app: # Adicionando um tema suave
|
| 92 |
gr.Markdown("# Tutor Poliglota com IA 🤖🎓")
|
| 93 |
gr.Markdown("Selecione a matéria e tire suas dúvidas com um assistente que lembra da conversa.")
|
| 94 |
|
| 95 |
with gr.Row():
|
|
|
|
| 96 |
subject_selector = gr.Dropdown(
|
| 97 |
choices=subjects,
|
| 98 |
label="Selecione a Matéria",
|
|
|
|
| 100 |
)
|
| 101 |
|
| 102 |
with gr.Row():
|
|
|
|
| 103 |
input_textbox = gr.Textbox(
|
| 104 |
placeholder="Ex: Como declarar uma variável em Java?",
|
| 105 |
label="Sua Dúvida",
|
| 106 |
+
lines=3,
|
| 107 |
+
show_copy_button=True
|
| 108 |
)
|
| 109 |
|
| 110 |
with gr.Row():
|
| 111 |
+
submit_button = gr.Button("Perguntar ao Tutor", variant="primary") # Botão com destaque
|
|
|
|
| 112 |
|
| 113 |
with gr.Row():
|
|
|
|
| 114 |
output_textbox = gr.Textbox(
|
| 115 |
label="Resposta do Tutor",
|
| 116 |
+
lines=10, # Mais espaço para resposta
|
| 117 |
+
show_copy_button=True
|
| 118 |
)
|
| 119 |
|
|
|
|
| 120 |
clear_button = gr.ClearButton(
|
| 121 |
+
components=[input_textbox, output_textbox, subject_selector], # Limpa também o dropdown
|
| 122 |
+
value="Limpar Campos e Memória"
|
| 123 |
)
|
| 124 |
|
|
|
|
| 125 |
submit_button.click(
|
| 126 |
fn=responder,
|
| 127 |
+
inputs=[subject_selector, input_textbox],
|
| 128 |
outputs=output_textbox
|
| 129 |
)
|
| 130 |
|
|
|
|
| 131 |
def clear_memory_and_interface():
|
| 132 |
+
try:
|
| 133 |
+
memoria.clear() # Limpa a memória da conversa
|
| 134 |
+
print("Memória da conversa limpa.")
|
| 135 |
+
except Exception as e:
|
| 136 |
+
print(f"Erro ao limpar a memória: {e}")
|
| 137 |
+
# Retorna valor padrão para dropdown (None) e vazio para textbox
|
| 138 |
+
return [None, "", ""]
|
| 139 |
|
| 140 |
+
# Atualiza a ação do clear_button para retornar valores para todos os componentes
|
| 141 |
+
clear_button.click(fn=clear_memory_and_interface, outputs=[subject_selector, input_textbox, output_textbox])
|
| 142 |
|
| 143 |
# Lança a aplicação
|
| 144 |
+
app.launch(share=True, debug=True) # Adiciona debug=True para mais informações no console
|