Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import base64
|
| 6 |
-
import
|
| 7 |
-
|
|
|
|
| 8 |
from llama_index.readers.web import SimpleWebPageReader
|
| 9 |
from llama_index.llms.gemini import Gemini
|
| 10 |
from llama_index.tools.wikipedia import WikipediaToolSpec
|
|
@@ -13,14 +13,6 @@ from llama_index.core.tools import FunctionTool
|
|
| 13 |
from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec
|
| 14 |
from llama_index.tools.arxiv import ArxivToolSpec
|
| 15 |
from llama_index.core.agent.workflow import AgentWorkflow
|
| 16 |
-
from llama_index.vector_stores.chroma import ChromaVectorStore
|
| 17 |
-
from llama_index.core.schema import Document
|
| 18 |
-
import pandas as pd
|
| 19 |
-
import asyncio
|
| 20 |
-
import chromadb
|
| 21 |
-
from dotenv import load_dotenv
|
| 22 |
-
|
| 23 |
-
nest_asyncio.apply()
|
| 24 |
|
| 25 |
# --- Constants ---
|
| 26 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
@@ -29,8 +21,11 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 29 |
class BasicAgent:
|
| 30 |
def __init__(self):
|
| 31 |
# Initialize LLM
|
|
|
|
| 32 |
self.llm = Gemini(
|
| 33 |
-
model_name="models/gemini-2.0-flash"
|
|
|
|
|
|
|
| 34 |
)
|
| 35 |
|
| 36 |
# Define tools
|
|
@@ -101,111 +96,39 @@ class BasicAgent:
|
|
| 101 |
description="Search Wikipedia and convert the results into a high-quality response."
|
| 102 |
)
|
| 103 |
|
| 104 |
-
def search_arxiv(query: str, max_results: int = 3) -> dict:
|
| 105 |
-
"""Search scientific articles on arXiv."""
|
| 106 |
-
try:
|
| 107 |
-
tool_spec = ArxivToolSpec()
|
| 108 |
-
papers = tool_spec.query_papers(query, max_results=max_results)
|
| 109 |
-
|
| 110 |
-
results = []
|
| 111 |
-
for paper in papers:
|
| 112 |
-
results.append(f"Title: {paper.title}\nAuthors: {', '.join(paper.authors)}\n"
|
| 113 |
-
f"Published: {paper.published}\nSummary: {paper.summary}\n"
|
| 114 |
-
f"URL: {paper.pdf_url}")
|
| 115 |
-
|
| 116 |
-
return {"arxiv_results": "\n\n".join(results)}
|
| 117 |
-
except Exception as e:
|
| 118 |
-
return {"arxiv_results": f"Error searching arXiv: {str(e)}"}
|
| 119 |
-
|
| 120 |
-
arxiv_search_tool = FunctionTool.from_defaults(
|
| 121 |
-
search_arxiv,
|
| 122 |
-
name="search_arxiv",
|
| 123 |
-
description="Search scientific articles on arXiv about a given topic."
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
# Define basic math tools
|
| 127 |
-
def add(a: int, b: int) -> int:
|
| 128 |
-
"""Add two numbers."""
|
| 129 |
-
return a + b
|
| 130 |
-
|
| 131 |
-
def subtract(a: int, b: int) -> int:
|
| 132 |
-
"""Subtract b from a."""
|
| 133 |
-
return a - b
|
| 134 |
-
|
| 135 |
-
def multiply(a: int, b: int) -> int:
|
| 136 |
-
"""Multiply two numbers."""
|
| 137 |
-
return a * b
|
| 138 |
-
|
| 139 |
-
def divide(a: int, b: int) -> float:
|
| 140 |
-
"""Divide a by b."""
|
| 141 |
-
if b == 0:
|
| 142 |
-
raise ValueError("Cannot divide by zero.")
|
| 143 |
-
return a / b
|
| 144 |
-
|
| 145 |
-
def modulus(a: int, b: int) -> int:
|
| 146 |
-
"""Get the modulus of a divided by b."""
|
| 147 |
-
if b == 0:
|
| 148 |
-
raise ValueError("Cannot calculate modulus with zero.")
|
| 149 |
-
return a % b
|
| 150 |
-
|
| 151 |
# Create a list of all tools
|
| 152 |
tools = [
|
| 153 |
duckduckgo_search_tool,
|
| 154 |
load_video_transcript_tool,
|
| 155 |
wikipedia_search_tool,
|
| 156 |
-
web_page_reader_tool
|
| 157 |
-
arxiv_search_tool,
|
| 158 |
-
FunctionTool.from_defaults(add),
|
| 159 |
-
FunctionTool.from_defaults(subtract),
|
| 160 |
-
FunctionTool.from_defaults(multiply),
|
| 161 |
-
FunctionTool.from_defaults(divide),
|
| 162 |
-
FunctionTool.from_defaults(modulus)
|
| 163 |
]
|
| 164 |
|
| 165 |
# Create system prompt
|
| 166 |
system_prompt = """
|
| 167 |
You're an AI agent designed for question answering. Keep your answers concise or even one word when possible.
|
| 168 |
You have access to a bunch of tools, utilize them well to reach answers.
|
| 169 |
-
|
| 170 |
-
Your answer should only start with "FINAL ANSWER: ", then follows with the answer.
|
| 171 |
"""
|
| 172 |
|
| 173 |
# Initialize the agent workflow
|
| 174 |
self.agent = AgentWorkflow.from_tools_or_functions(tools, llm=self.llm, system_prompt=system_prompt)
|
| 175 |
-
print("BasicAgent initialized
|
| 176 |
|
| 177 |
-
async def run_agent(self, question: str):
|
| 178 |
-
# Check if question contains file data
|
| 179 |
-
if "file_data:" in question:
|
| 180 |
-
try:
|
| 181 |
-
# Split question and file data
|
| 182 |
-
parts = question.split("file_data:", 1)
|
| 183 |
-
question_text = parts[0].strip()
|
| 184 |
-
file_data_base64 = parts[1].strip()
|
| 185 |
-
|
| 186 |
-
# Process file data (just mentioning it for now)
|
| 187 |
-
question = f"{question_text}\n[This question includes attached file data]"
|
| 188 |
-
except Exception as e:
|
| 189 |
-
print(f"Error processing file data: {e}")
|
| 190 |
-
|
| 191 |
-
# Run agent and return response
|
| 192 |
-
return await self.agent.run(question)
|
| 193 |
-
|
| 194 |
def __call__(self, question: str) -> str:
|
| 195 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 196 |
|
| 197 |
try:
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
#
|
| 201 |
-
|
| 202 |
-
final_answer = response.response.blocks[0].text
|
| 203 |
-
else:
|
| 204 |
-
final_answer = response.response
|
| 205 |
|
| 206 |
-
# Extract final answer
|
| 207 |
-
|
| 208 |
-
final_answer = final_answer.split("FINAL ANSWER:")[1].strip()
|
| 209 |
|
| 210 |
print(f"Agent returning answer: {final_answer[:50]}...")
|
| 211 |
return final_answer
|
|
@@ -214,7 +137,7 @@ class BasicAgent:
|
|
| 214 |
print(error_message)
|
| 215 |
return error_message
|
| 216 |
|
| 217 |
-
|
| 218 |
"""
|
| 219 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 220 |
and displays the results.
|
|
@@ -223,7 +146,7 @@ async def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 223 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 224 |
|
| 225 |
if profile:
|
| 226 |
-
username= f"{profile.username}"
|
| 227 |
print(f"User logged in: {username}")
|
| 228 |
else:
|
| 229 |
print("User not logged in.")
|
|
@@ -270,7 +193,7 @@ async def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 270 |
answers_payload = []
|
| 271 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 272 |
for item in questions_data:
|
| 273 |
-
|
| 274 |
task_id = item.get("task_id")
|
| 275 |
question_text = item.get("question")
|
| 276 |
if not task_id or question_text is None:
|
|
@@ -397,4 +320,5 @@ if __name__ == "__main__":
|
|
| 397 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 398 |
|
| 399 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 400 |
-
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import base64
|
| 5 |
+
import time
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
from llama_index.readers.web import SimpleWebPageReader
|
| 9 |
from llama_index.llms.gemini import Gemini
|
| 10 |
from llama_index.tools.wikipedia import WikipediaToolSpec
|
|
|
|
| 13 |
from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec
|
| 14 |
from llama_index.tools.arxiv import ArxivToolSpec
|
| 15 |
from llama_index.core.agent.workflow import AgentWorkflow
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# --- Constants ---
|
| 18 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 21 |
class BasicAgent:
|
| 22 |
def __init__(self):
|
| 23 |
# Initialize LLM
|
| 24 |
+
load_dotenv()
|
| 25 |
self.llm = Gemini(
|
| 26 |
+
model_name="models/gemini-2.0-flash",
|
| 27 |
+
temperature=0.1,
|
| 28 |
+
max_tokens=4096
|
| 29 |
)
|
| 30 |
|
| 31 |
# Define tools
|
|
|
|
| 96 |
description="Search Wikipedia and convert the results into a high-quality response."
|
| 97 |
)
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
# Create a list of all tools
|
| 100 |
tools = [
|
| 101 |
duckduckgo_search_tool,
|
| 102 |
load_video_transcript_tool,
|
| 103 |
wikipedia_search_tool,
|
| 104 |
+
web_page_reader_tool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
]
|
| 106 |
|
| 107 |
# Create system prompt
|
| 108 |
system_prompt = """
|
| 109 |
You're an AI agent designed for question answering. Keep your answers concise or even one word when possible.
|
| 110 |
You have access to a bunch of tools, utilize them well to reach answers.
|
|
|
|
|
|
|
| 111 |
"""
|
| 112 |
|
| 113 |
# Initialize the agent workflow
|
| 114 |
self.agent = AgentWorkflow.from_tools_or_functions(tools, llm=self.llm, system_prompt=system_prompt)
|
| 115 |
+
print("BasicAgent initialized.")
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
def __call__(self, question: str) -> str:
|
| 118 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 119 |
|
| 120 |
try:
|
| 121 |
+
# Process file data if present
|
| 122 |
+
if "file_data:" in question:
|
| 123 |
+
parts = question.split("file_data:", 1)
|
| 124 |
+
question_text = parts[0].strip()
|
| 125 |
+
question = f"{question_text}\n[This question includes attached file data]"
|
| 126 |
|
| 127 |
+
# Run the agent
|
| 128 |
+
response = self.agent.run(question)
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
# Extract final answer
|
| 131 |
+
final_answer = response.response
|
|
|
|
| 132 |
|
| 133 |
print(f"Agent returning answer: {final_answer[:50]}...")
|
| 134 |
return final_answer
|
|
|
|
| 137 |
print(error_message)
|
| 138 |
return error_message
|
| 139 |
|
| 140 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 141 |
"""
|
| 142 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 143 |
and displays the results.
|
|
|
|
| 146 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 147 |
|
| 148 |
if profile:
|
| 149 |
+
username = f"{profile.username}"
|
| 150 |
print(f"User logged in: {username}")
|
| 151 |
else:
|
| 152 |
print("User not logged in.")
|
|
|
|
| 193 |
answers_payload = []
|
| 194 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 195 |
for item in questions_data:
|
| 196 |
+
time.sleep(20) # Added delay between questions
|
| 197 |
task_id = item.get("task_id")
|
| 198 |
question_text = item.get("question")
|
| 199 |
if not task_id or question_text is None:
|
|
|
|
| 320 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 321 |
|
| 322 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 323 |
+
# Use a different port to avoid conflicts
|
| 324 |
+
demo.launch(debug=True, share=False, server_port=7861)
|