import os import gradio as gr import requests import pandas as pd from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM # --- Constants --- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" # --- Smart Agent Definition Using Open LLM --- class BasicAgent: def __init__(self): print("Loading open instruct model...") model_id = "meta-llama/Llama-3-8B-instruct" # <— change to a model you have access to self.tokenizer = AutoTokenizer.from_pretrained(model_id) self.model = AutoModelForCausalLM.from_pretrained(model_id) self.pipeline = pipeline( "text-generation", model=self.model, tokenizer=self.tokenizer, max_new_tokens=150, temperature=0.3, do_sample=False, ) def __call__(self, question: str) -> str: print(f"Agent received question: {question[:60]}") prompt = f"""You are a helpful assistant. Answer the question concisely and output only the final answer (no explanation). Question: {question} Answer:""" try: output = self.pipeline(prompt)[0]["generated_text"] # After generation, remove the prompt part answer = output[len(prompt):].strip() # Sometimes model may append new lines or extra text; trim to first line answer = answer.split("\n")[0].strip() return answer except Exception as e: print("Error during inference:", e) return "I don't know" def run_and_submit_all(profile: gr.OAuthProfile | None): space_id = os.getenv("SPACE_ID") if profile: username = profile.username else: return "Please Login to Hugging Face with the button.", None questions_url = f"{DEFAULT_API_URL}/questions" submit_url = f"{DEFAULT_API_URL}/submit" try: agent = BasicAgent() except Exception as e: return f"Error initializing agent: {e}", None agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" try: response = requests.get(questions_url, timeout=15) response.raise_for_status() questions_data = response.json() except Exception as e: return f"Error fetching questions: {e}", None results_log = [] answers_payload = [] for item in questions_data: task_id = item.get("task_id") question_text = item.get("question") if not task_id or question_text is None: continue try: answer = agent(question_text) answers_payload.append({"task_id": task_id, "submitted_answer": answer}) results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": answer}) except Exception as e: results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"}) if not answers_payload: return "No answers to submit.", pd.DataFrame(results_log) submission_data = { "username": username.strip(), "agent_code": agent_code, "answers": answers_payload } try: resp = requests.post(submit_url, json=submission_data, timeout=60) resp.raise_for_status() result = resp.json() final_status = ( f"Submission Successful!\n" f"User: {result.get('username')}\n" f"Score: {result.get('score', 'N/A')}% " f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')})\n" f"Message: {result.get('message', '')}" ) return final_status, pd.DataFrame(results_log) except Exception as e: return f"Submission Failed: {e}", pd.DataFrame(results_log) with gr.Blocks() as demo: gr.Markdown("# Basic Agent Evaluation Runner") gr.Markdown("This uses an open access instruct model (no gated repo).") gr.LoginButton() run_button = gr.Button("Run Evaluation & Submit All Answers") status_output = gr.Textbox(label="Run Status", lines=5, interactive=False) results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table]) if __name__ == "__main__": demo.launch(debug=True, share=False)