Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,75 +4,14 @@ import pandas as pd
|
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
from langchain import hub
|
| 7 |
-
from
|
| 8 |
-
from
|
|
|
|
| 9 |
from langchain_tavily import TavilySearch
|
| 10 |
|
| 11 |
# --- Constants ---
|
| 12 |
API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
|
| 14 |
-
# --- GAIA Agent Definition ---
|
| 15 |
-
class GaiaAgent:
|
| 16 |
-
"""A sophisticated agent designed to solve GAIA challenges."""
|
| 17 |
-
|
| 18 |
-
def __init__(self):
|
| 19 |
-
"""
|
| 20 |
-
Initializes the agent with its core components: LLM, tools, and executor.
|
| 21 |
-
Relies on HUGGING_FACE_HUB_TOKEN and TAVILY_API_KEY environment variables.
|
| 22 |
-
"""
|
| 23 |
-
print("Initializing GaiaAgent...")
|
| 24 |
-
if not os.getenv("HUGGING_FACE_HUB_TOKEN"):
|
| 25 |
-
raise ValueError("HUGGING_FACE_HUB_TOKEN environment variable is not set. Please set it in your Space secrets.")
|
| 26 |
-
if not os.getenv("TAVILY_API_KEY"):
|
| 27 |
-
raise ValueError("TAVILY_API_KEY environment variable is not set. Please set it in your Space secrets.")
|
| 28 |
-
|
| 29 |
-
# 1. Set up the LLM using a recommended model endpoint
|
| 30 |
-
# The token is read automatically from the HUGGING_FACE_HUB_TOKEN secret
|
| 31 |
-
llm = HuggingFaceEndpoint(
|
| 32 |
-
repo_id="HuggingFaceH4/zephyr-7b-beta",
|
| 33 |
-
task="text-generation",
|
| 34 |
-
max_new_tokens=1024,
|
| 35 |
-
do_sample=False,
|
| 36 |
-
)
|
| 37 |
-
chat_model = ChatHuggingFace(llm=llm)
|
| 38 |
-
|
| 39 |
-
# 2. Define the tools the agent can use
|
| 40 |
-
tools = [TavilySearch(
|
| 41 |
-
max_results=5,
|
| 42 |
-
description="A search engine useful for answering questions about current events and general knowledge."
|
| 43 |
-
)]
|
| 44 |
-
|
| 45 |
-
# 3. Create the agent using a standard ReAct prompt
|
| 46 |
-
prompt = hub.pull("hwchase17/react-chat")
|
| 47 |
-
agent = create_react_agent(chat_model, tools, prompt)
|
| 48 |
-
|
| 49 |
-
# 4. Create the Agent Executor
|
| 50 |
-
self.agent_executor = AgentExecutor(
|
| 51 |
-
agent=agent,
|
| 52 |
-
tools=tools,
|
| 53 |
-
verbose=True,
|
| 54 |
-
handle_parsing_errors="Check your output and make sure it conforms to the format.",
|
| 55 |
-
max_iterations=5,
|
| 56 |
-
)
|
| 57 |
-
print("GaiaAgent initialized successfully.")
|
| 58 |
-
|
| 59 |
-
def __call__(self, question: str) -> str:
|
| 60 |
-
"""
|
| 61 |
-
Invokes the agent to process a single question.
|
| 62 |
-
"""
|
| 63 |
-
print(f"Agent received question (first 80 chars): {question[:80]}...")
|
| 64 |
-
try:
|
| 65 |
-
response = self.agent_executor.invoke({
|
| 66 |
-
"input": question,
|
| 67 |
-
"chat_history": []
|
| 68 |
-
})
|
| 69 |
-
answer = response.get("output", "Error: No answer was generated.")
|
| 70 |
-
print(f"Agent returning answer (first 80 chars): {answer[:80]}...")
|
| 71 |
-
return answer
|
| 72 |
-
except Exception as e:
|
| 73 |
-
print(f"An error occurred while running the agent: {e}")
|
| 74 |
-
return f"AGENT_EXECUTION_ERROR: {str(e)}"
|
| 75 |
-
|
| 76 |
# --- Gradio Event Handlers ---
|
| 77 |
|
| 78 |
def store_username(request: gr.Request):
|
|
@@ -98,12 +37,47 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 98 |
print("User not logged in.")
|
| 99 |
return "Please Login to Hugging Face with the button.", None
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
questions_url = f"{API_BASE_URL}/questions"
|
| 102 |
submit_url = f"{API_BASE_URL}/submit"
|
| 103 |
|
| 104 |
# 2. Instantiate Agent
|
| 105 |
try:
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
except Exception as e:
|
| 108 |
print(f"Error instantiating agent: {e}")
|
| 109 |
return f"Error initializing agent: {e}", None
|
|
@@ -143,7 +117,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 143 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 144 |
continue
|
| 145 |
try:
|
| 146 |
-
submitted_answer =
|
| 147 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 148 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 149 |
except Exception as e:
|
|
|
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
from langchain import hub
|
| 7 |
+
from langchain_openai import ChatOpenAI
|
| 8 |
+
from langchain.agents import create_openai_functions_agent, AgentExecutor
|
| 9 |
+
from langchain_experimental.tools import PythonAstREPLTool
|
| 10 |
from langchain_tavily import TavilySearch
|
| 11 |
|
| 12 |
# --- Constants ---
|
| 13 |
API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
# --- Gradio Event Handlers ---
|
| 16 |
|
| 17 |
def store_username(request: gr.Request):
|
|
|
|
| 37 |
print("User not logged in.")
|
| 38 |
return "Please Login to Hugging Face with the button.", None
|
| 39 |
|
| 40 |
+
# Retrieve API keys from environment variables (Hugging Face Space Secrets)
|
| 41 |
+
try:
|
| 42 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 43 |
+
tavily_api_key = os.getenv("TAVILY_API_KEY")
|
| 44 |
+
|
| 45 |
+
if not openai_api_key:
|
| 46 |
+
raise ValueError("OPENAI_API_KEY secret not found. Please set it in your Space settings.")
|
| 47 |
+
if not tavily_api_key:
|
| 48 |
+
raise ValueError("TAVILY_API_KEY secret not found. Please set it in your Space settings.")
|
| 49 |
+
except ValueError as e:
|
| 50 |
+
return str(e), None
|
| 51 |
+
|
| 52 |
questions_url = f"{API_BASE_URL}/questions"
|
| 53 |
submit_url = f"{API_BASE_URL}/submit"
|
| 54 |
|
| 55 |
# 2. Instantiate Agent
|
| 56 |
try:
|
| 57 |
+
# LLM: Use gpt-4o for its advanced reasoning and tool-use capabilities.
|
| 58 |
+
llm = ChatOpenAI(model="gpt-4o", temperature=0, openai_api_key=openai_api_key)
|
| 59 |
+
|
| 60 |
+
# Tools: A powerful combination of web search and a code interpreter.
|
| 61 |
+
tools = [
|
| 62 |
+
TavilySearch(max_results=5, description="A search engine useful for answering questions about current events and general knowledge.", tavily_api_key=tavily_api_key),
|
| 63 |
+
PythonAstREPLTool()
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
# Agent Prompt: Use a standard prompt designed for OpenAI function-calling agents.
|
| 67 |
+
prompt = hub.pull("hwchase17/openai-functions-agent")
|
| 68 |
+
|
| 69 |
+
# Agent: Create the agent by combining the LLM, tools, and prompt.
|
| 70 |
+
agent = create_openai_functions_agent(llm, tools, prompt)
|
| 71 |
+
|
| 72 |
+
# Agent Executor: The runnable part that executes the agent's logic.
|
| 73 |
+
agent_executor = AgentExecutor(
|
| 74 |
+
agent=agent,
|
| 75 |
+
tools=tools,
|
| 76 |
+
verbose=True,
|
| 77 |
+
handle_parsing_errors=True, # More robust error handling
|
| 78 |
+
max_iterations=10 # Increased for complex tasks
|
| 79 |
+
)
|
| 80 |
+
print("High-performance agent initialized successfully.")
|
| 81 |
except Exception as e:
|
| 82 |
print(f"Error instantiating agent: {e}")
|
| 83 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 117 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 118 |
continue
|
| 119 |
try:
|
| 120 |
+
submitted_answer = agent_executor.invoke(question_text)
|
| 121 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 122 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 123 |
except Exception as e:
|