"""Free ZeroGPU demonstration and submission of genuinely evaluated answers.""" import json import os import re from pathlib import Path import spaces import gradio as gr import requests import torch from transformers import AutoModelForCausalLM, AutoTokenizer from agent import API, EvidenceAgent MODEL = "Qwen/Qwen2.5-3B-Instruct" tokenizer = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForCausalLM.from_pretrained(MODEL, torch_dtype=torch.float16) @spaces.GPU(duration=60) def complete(messages, tools=None): prompt = tokenizer.apply_chat_template(messages, tools=tools, tokenize=False, add_generation_prompt=True) model.to("cuda") batch = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=14000).to("cuda") with torch.inference_mode(): output = model.generate(**batch, max_new_tokens=1000, do_sample=False, pad_token_id=tokenizer.eos_token_id) text = tokenizer.decode(output[0, batch.input_ids.shape[-1]:], skip_special_tokens=True) calls = [] for raw in re.findall(r"\s*(.*?)\s*", text, flags=re.S): try: value = json.loads(raw) calls.append({"function": value}) except json.JSONDecodeError: pass return {"role": "assistant", "content": re.sub(r".*?", "", text, flags=re.S).strip(), "tool_calls": calls} def ask(question): if not question.strip(): raise gr.Error("Enter a question first.") run = EvidenceAgent(model=MODEL, completion=complete, max_steps=5).solve(question) return run["answer"], run["tools"] def load_results(): path = Path("evaluation_results.json") return json.loads(path.read_text(encoding="utf-8")) if path.exists() else [] def submit(profile: gr.OAuthProfile | None): if not profile or profile.username != "TFWLKR": raise gr.Error("Only the project owner can submit this evaluation.") results = load_results() if not results: raise gr.Error("Run the local evaluation and upload its results first.") response = requests.post(f"{API}/submit", json={ "username": profile.username, "agent_code": f"https://huggingface.co/spaces/{os.environ['SPACE_ID']}/tree/main", "answers": [{"task_id": row["task_id"], "submitted_answer": row["answer"]} for row in results], }, timeout=90) response.raise_for_status() return response.json() with gr.Blocks(title="Evidence Agent") as demo: gr.Markdown("# Evidence Agent\nA LangGraph research and retrieval agent with free local inference. " "The live demo uses Qwen 2.5 3B on the free ZeroGPU tier. The final recorded evaluation " "uses this agent's external-model adapter with ChatGPT Work Mode as its reasoning controller. " "No paid inference APIs, embedded credentials, or answer lookup tables.") with gr.Tab("Try the agent"): question = gr.Textbox(label="Question", lines=3, value="How does agentic RAG use retrieval tools? Check the bundled notes.") button = gr.Button("Ask agent") answer = gr.Textbox(label="Answer") evidence = gr.JSON(label="Tool calls and source observations") button.click(ask, question, [answer, evidence]) gr.Markdown("The demo is text-only. Image/audio tasks are marked unsupported instead of being guessed. " "Free GPU quota limits may pause live inference.") with gr.Tab("Course evaluation"): gr.Markdown("The entries below are actual saved runs from `python evaluate.py`. " "Each records its model, timestamp, tool calls, source excerpts, and final answer. " "Full web observations are represented by concise excerpts and hashes. " "Reproduce with a compatible external LLM controller, try local Ollama, " "or use the live demo for individual questions.") gr.JSON(load_results(), label="Evaluation evidence") gr.LoginButton() submit_button = gr.Button("Submit evaluated answers") score_path = Path("submission_result.json") recorded_score = json.loads(score_path.read_text(encoding="utf-8")) if score_path.exists() else None result = gr.JSON(value=recorded_score, label="Official scoring response") submit_button.click(submit, outputs=result) if __name__ == "__main__": demo.queue(default_concurrency_limit=1).launch()