Commit ·
1a5f164
1
Parent(s): 81917a3
Add first attempt agent code
Browse files- app.py +60 -7
- requirements.txt +3 -1
app.py
CHANGED
|
@@ -3,21 +3,68 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
|
|
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
|
@@ -37,6 +84,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 37 |
api_url = DEFAULT_API_URL
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
|
|
|
| 40 |
|
| 41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
try:
|
|
@@ -76,11 +124,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 76 |
for item in questions_data:
|
| 77 |
task_id = item.get("task_id")
|
| 78 |
question_text = item.get("question")
|
|
|
|
| 79 |
if not task_id or question_text is None:
|
| 80 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
continue
|
| 82 |
try:
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 86 |
except Exception as e:
|
|
@@ -91,7 +144,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 91 |
print("Agent did not produce any answers to submit.")
|
| 92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
|
| 94 |
-
# 4. Prepare Submission
|
| 95 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 96 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 97 |
print(status_update)
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
import asyncio
|
| 7 |
+
import sys
|
| 8 |
+
from llama_index.llms.google_genai import GoogleGenAI
|
| 9 |
+
from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec
|
| 10 |
+
from llama_index.core.agent.workflow import AgentWorkflow
|
| 11 |
+
from llama_index.core.workflow import Context
|
| 12 |
+
from llama_index.core.tools import FunctionTool
|
| 13 |
+
from llama_index.core.llms import ChatMessage, ImageBlock, TextBlock
|
| 14 |
+
|
| 15 |
|
| 16 |
# (Keep Constants as is)
|
| 17 |
# --- Constants ---
|
| 18 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 19 |
|
| 20 |
+
SYSTEM_PROMPT = "You are a general AI assistant. I will ask you a question. Reply only with YOUR FINAL ANSWER. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."
|
| 21 |
# --- Basic Agent Definition ---
|
| 22 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 23 |
class BasicAgent:
|
| 24 |
def __init__(self):
|
| 25 |
+
gemini_api_key = os.getenv("GEMINI_API_KEY")
|
| 26 |
+
if not gemini_api_key:
|
| 27 |
+
raise ValueError("GEMINI_API_KEY not set in environment variables.")
|
| 28 |
+
|
| 29 |
+
self.model = GoogleGenAI(
|
| 30 |
+
model="gemini-2.0-flash",
|
| 31 |
+
api_key=gemini_api_key
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
tool_list = DuckDuckGoSearchToolSpec().to_tool_list()
|
| 35 |
+
tool_list.append(FunctionTool.from_defaults(fn=reversed_string))
|
| 36 |
+
tool_list.append(FunctionTool.from_defaults(fn=download_file))
|
| 37 |
+
self.agent = AgentWorkflow.from_tools_or_functions(
|
| 38 |
+
tool_list,
|
| 39 |
+
llm=self.model,
|
| 40 |
+
system_prompt=SYSTEM_PROMPT,
|
| 41 |
+
verbose=True,
|
| 42 |
+
)
|
| 43 |
+
self.ctx = Context(agent);
|
| 44 |
+
self.api_url = DEFAULT_API_URL
|
| 45 |
+
self.download_url = f"{self.api_url}/files/"
|
| 46 |
+
|
| 47 |
+
def create_block(self, item):
|
| 48 |
+
if item.endswith(".png"):
|
| 49 |
+
return ImageBlock(url=self.download_url + item.replace(".png", ""))
|
| 50 |
+
else:
|
| 51 |
+
return TextBlock(text=item)
|
| 52 |
+
|
| 53 |
+
def __call__(self, messages) -> str:
|
| 54 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 55 |
+
blocks = list(map(create_block, messages))
|
| 56 |
+
request = ChatMessage(role="user", blocks=blocks)
|
| 57 |
+
response = await agent.run(request, ctx=ctx)
|
| 58 |
+
print(f"Agent returning fixed answer: {response}")
|
| 59 |
+
return response
|
| 60 |
+
|
| 61 |
+
def reversed_string(a_string: str):
|
| 62 |
+
"""Reverses a string"""
|
| 63 |
+
return a_string[::-1]
|
| 64 |
+
|
| 65 |
+
def download_file(file_name: str):
|
| 66 |
+
"""Get the contents of a file."""
|
| 67 |
+
return requests.get(download_url + file_name).content
|
| 68 |
|
| 69 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 70 |
"""
|
|
|
|
| 84 |
api_url = DEFAULT_API_URL
|
| 85 |
questions_url = f"{api_url}/questions"
|
| 86 |
submit_url = f"{api_url}/submit"
|
| 87 |
+
download_url = f"{api_url}/files/"
|
| 88 |
|
| 89 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 90 |
try:
|
|
|
|
| 124 |
for item in questions_data:
|
| 125 |
task_id = item.get("task_id")
|
| 126 |
question_text = item.get("question")
|
| 127 |
+
file_name = item.get("file_name")
|
| 128 |
if not task_id or question_text is None:
|
| 129 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 130 |
continue
|
| 131 |
try:
|
| 132 |
+
messages = [question_text]
|
| 133 |
+
if file_name:
|
| 134 |
+
file_url = download_url + file_name
|
| 135 |
+
messages.append(file_url)
|
| 136 |
+
submitted_answer = asyncio.run(agent(messages))
|
| 137 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 138 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 139 |
except Exception as e:
|
|
|
|
| 144 |
print("Agent did not produce any answers to submit.")
|
| 145 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 146 |
|
| 147 |
+
# 4. Prepare Submission
|
| 148 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 149 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 150 |
print(status_update)
|
requirements.txt
CHANGED
|
@@ -1,2 +1,4 @@
|
|
| 1 |
gradio
|
| 2 |
-
requests
|
|
|
|
|
|
|
|
|
| 1 |
gradio
|
| 2 |
+
requests
|
| 3 |
+
llama-index-llms-google-genai
|
| 4 |
+
llama-index-tools-duckduckgo
|