Spaces:
Sleeping
Sleeping
| import os | |
| import requests | |
| import gradio as gr | |
| API_KEY = os.environ.get("OPENROUTER_API_KEY") | |
| if not API_KEY: | |
| raise ValueError("OPENROUTER_API_KEY não definida nos secrets!") | |
| API_URL = "https://openrouter.ai/api/v1/chat/completions" | |
| HEADERS = { | |
| "Authorization": f"Bearer {API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| MODEL_1 = "meta-llama/llama-3.2-1b-instruct:free" | |
| MODEL_2 = "mistralai/mistral-7b-instruct:free" | |
| MODEL_3 = "google/gemma-2-9b-it:free" | |
| def call_model(model_name, messages): | |
| payload = { | |
| "model": model_name, | |
| "messages": messages, | |
| "max_tokens": 512, | |
| "temperature": 0.7, | |
| "top_p": 0.95 | |
| } | |
| try: | |
| response = requests.post(API_URL, headers=HEADERS, json=payload) | |
| response.raise_for_status() | |
| return response.json()["choices"][0]["message"]["content"].strip() | |
| except Exception as e: | |
| return f"Erro no modelo {model_name}: {str(e)}" | |
| def generate_and_judge(user_input): | |
| system_prompt = {"role": "system", "content": "Você é um assistente útil e objetivo."} | |
| user_msg = {"role": "user", "content": user_input} | |
| messages = [system_prompt, user_msg] | |
| response1 = call_model(MODEL_1, messages) | |
| response2 = call_model(MODEL_2, messages) | |
| judge_prompt = f""" | |
| Você é um avaliador imparcial. Dadas duas respostas para a mesma pergunta escolha uma, seus critérios de julgamento são: | |
| 1. Pertinência | |
| 2. Objetividade | |
| 3. Veracidade | |
| Pergunta: {user_input} | |
| Resposta 1: {response1} | |
| Resposta 2: {response2} | |
| Indique qual resposta é melhor (Resposta 1 ou Resposta 2) e explique brevemente sua escolha, tambêm faça um breve resumo bem objetivo da resposta selecionada | |
| Use linguagem clara e objetiva. | |
| Não utilize negrito, itálico ou qualquer formatação como **asteriscos** ou _sublinhados_. | |
| Apenas texto puro. | |
| Resposta: | |
| """ | |
| judgment_msg = [{"role": "system", "content": "Você é um avaliador objetivo."}, | |
| {"role": "user", "content": judge_prompt}] | |
| judgment = call_model(MODEL_3, judgment_msg) | |
| return response1, response2, judgment | |
| with gr.Blocks() as demo: | |
| gr.Markdown("💡 Comparador de Respostas com 3 LLMs") | |
| user_input = gr.Textbox(label="Digite sua pergunta") | |
| generate_button = gr.Button("Gerar e Avaliar") | |
| with gr.Row(): | |
| response1_out = gr.Textbox(label="Resposta LLM 1") | |
| response2_out = gr.Textbox(label="Resposta LLM 2") | |
| judgment_out = gr.Textbox(label="🔎 Julgamento Final") | |
| generate_button.click(generate_and_judge, inputs=user_input, | |
| outputs=[response1_out, response2_out, judgment_out]) | |
| demo.launch() |