Spaces:
Sleeping
Sleeping
derek
commited on
Commit
·
e9a915f
1
Parent(s):
f5442e4
new smolagent
Browse files- app.py +352 -200
- core_agent.py +493 -0
- main.py +278 -0
- requirements.txt +4 -15
app.py
CHANGED
|
@@ -1,215 +1,367 @@
|
|
| 1 |
-
"""LangGraph Agent"""
|
| 2 |
import os
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
from
|
| 8 |
-
from langchain_groq import ChatGroq
|
| 9 |
-
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
|
| 10 |
-
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 11 |
-
from langchain_community.document_loaders import WikipediaLoader
|
| 12 |
-
from langchain_community.document_loaders import ArxivLoader
|
| 13 |
-
from langchain_community.vectorstores import SupabaseVectorStore
|
| 14 |
-
from langchain_core.messages import SystemMessage, HumanMessage
|
| 15 |
-
from langchain_core.tools import tool
|
| 16 |
-
from langchain.tools.retriever import create_retriever_tool
|
| 17 |
-
from supabase.client import Client, create_client
|
| 18 |
-
|
| 19 |
-
load_dotenv()
|
| 20 |
-
|
| 21 |
-
@tool
|
| 22 |
-
def multiply(a: int, b: int) -> int:
|
| 23 |
-
"""Multiply two numbers.
|
| 24 |
-
|
| 25 |
-
Args:
|
| 26 |
-
a: first int
|
| 27 |
-
b: second int
|
| 28 |
-
"""
|
| 29 |
-
return a * b
|
| 30 |
|
| 31 |
-
|
| 32 |
-
def
|
| 33 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
Args:
|
| 46 |
-
a: first int
|
| 47 |
-
b: second int
|
| 48 |
-
"""
|
| 49 |
-
return a - b
|
| 50 |
|
| 51 |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us of two numbers.
|
| 66 |
-
|
| 67 |
-
Args:
|
| 68 |
-
a: first int
|
| 69 |
-
b: second int
|
| 70 |
"""
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
Args:
|
| 78 |
-
query: The search query."""
|
| 79 |
-
search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
| 80 |
-
formatted_search_docs = "\n\n---\n\n".join(
|
| 81 |
-
[
|
| 82 |
-
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
|
| 83 |
-
for doc in search_docs
|
| 84 |
-
])
|
| 85 |
-
return {"wiki_results": formatted_search_docs}
|
| 86 |
-
|
| 87 |
-
@tool
|
| 88 |
-
def web_search(query: str) -> str:
|
| 89 |
-
"""Search Tavily for a query and return maximum 3 results.
|
| 90 |
-
|
| 91 |
-
Args:
|
| 92 |
-
query: The search query."""
|
| 93 |
-
search_docs = TavilySearchResults(max_results=3).invoke(query=query)
|
| 94 |
-
formatted_search_docs = "\n\n---\n\n".join(
|
| 95 |
-
[
|
| 96 |
-
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
|
| 97 |
-
for doc in search_docs
|
| 98 |
-
])
|
| 99 |
-
return {"web_results": formatted_search_docs}
|
| 100 |
-
|
| 101 |
-
@tool
|
| 102 |
-
def arvix_search(query: str) -> str:
|
| 103 |
-
"""Search Arxiv for a query and return maximum 3 result.
|
| 104 |
-
|
| 105 |
-
Args:
|
| 106 |
-
query: The search query."""
|
| 107 |
-
search_docs = ArxivLoader(query=query, load_max_docs=3).load()
|
| 108 |
-
formatted_search_docs = "\n\n---\n\n".join(
|
| 109 |
-
[
|
| 110 |
-
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
|
| 111 |
-
for doc in search_docs
|
| 112 |
-
])
|
| 113 |
-
return {"arvix_results": formatted_search_docs}
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
# load the system prompt from the file
|
| 118 |
-
with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
| 119 |
-
system_prompt = f.read()
|
| 120 |
-
|
| 121 |
-
# System message
|
| 122 |
-
sys_msg = SystemMessage(content=system_prompt)
|
| 123 |
-
|
| 124 |
-
# build a retriever
|
| 125 |
-
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
|
| 126 |
-
supabase: Client = create_client(
|
| 127 |
-
#os.environ.get("SUPABASE_URL"),
|
| 128 |
-
#os.environ.get("SUPABASE_SERVICE_KEY"))
|
| 129 |
-
vector_store = SupabaseVectorStore(
|
| 130 |
-
client=supabase,
|
| 131 |
-
embedding= embeddings,
|
| 132 |
-
table_name="documents",
|
| 133 |
-
query_name="match_documents_langchain",
|
| 134 |
-
)
|
| 135 |
-
create_retriever_tool = create_retriever_tool(
|
| 136 |
-
retriever=vector_store.as_retriever(),
|
| 137 |
-
name="Question Search",
|
| 138 |
-
description="A tool to retrieve similar questions from a vector store.",
|
| 139 |
-
)
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
tools = [
|
| 144 |
-
multiply,
|
| 145 |
-
add,
|
| 146 |
-
subtract,
|
| 147 |
-
divide,
|
| 148 |
-
modulus,
|
| 149 |
-
wiki_search,
|
| 150 |
-
web_search,
|
| 151 |
-
arvix_search,
|
| 152 |
-
]
|
| 153 |
-
|
| 154 |
-
# Build graph function
|
| 155 |
-
def build_graph(provider: str = "groq"):
|
| 156 |
-
"""Build the graph"""
|
| 157 |
-
# Load environment variables from .env file
|
| 158 |
-
if provider == "google":
|
| 159 |
-
# Google Gemini
|
| 160 |
-
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
|
| 161 |
-
elif provider == "groq":
|
| 162 |
-
# Groq https://console.groq.com/docs/models
|
| 163 |
-
llm = ChatGroq(model="qwen-qwq-32b", temperature=0) # optional : qwen-qwq-32b gemma2-9b-it
|
| 164 |
-
elif provider == "huggingface":
|
| 165 |
-
# TODO: Add huggingface endpoint
|
| 166 |
-
llm = ChatHuggingFace(
|
| 167 |
-
llm=HuggingFaceEndpoint(
|
| 168 |
-
url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
|
| 169 |
-
temperature=0,
|
| 170 |
-
),
|
| 171 |
-
)
|
| 172 |
else:
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
)
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
)
|
| 200 |
-
builder.add_edge("tools", "assistant")
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
-
# test
|
| 206 |
if __name__ == "__main__":
|
| 207 |
-
|
| 208 |
-
#
|
| 209 |
-
|
| 210 |
-
#
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import inspect
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from core_agent import GAIAAgent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
# Debug function to show available environment variables
|
| 9 |
+
def debug_environment():
|
| 10 |
+
"""Print available environment variables related to API keys (with values hidden)"""
|
| 11 |
+
debug_vars = [
|
| 12 |
+
"HF_API_TOKEN", "HUGGINGFACEHUB_API_TOKEN",
|
| 13 |
+
"OPENAI_API_KEY", "XAI_API_KEY",
|
| 14 |
+
"AGENT_MODEL_TYPE", "AGENT_MODEL_ID",
|
| 15 |
+
"AGENT_TEMPERATURE", "AGENT_VERBOSE"
|
| 16 |
+
]
|
| 17 |
|
| 18 |
+
print("=== DEBUG: Environment Variables ===")
|
| 19 |
+
for var in debug_vars:
|
| 20 |
+
if os.environ.get(var):
|
| 21 |
+
# Hide actual values for security
|
| 22 |
+
print(f"{var}: [SET]")
|
| 23 |
+
else:
|
| 24 |
+
print(f"{var}: [NOT SET]")
|
| 25 |
+
print("===================================")
|
| 26 |
|
| 27 |
+
# (Keep Constants as is)
|
| 28 |
+
# --- Constants ---
|
| 29 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# --- Basic Agent Definition ---
|
| 32 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 33 |
+
class BasicAgent:
|
| 34 |
+
def __init__(self):
|
| 35 |
+
print("BasicAgent initialized.")
|
| 36 |
+
|
| 37 |
+
# Call debug function to show available environment variables
|
| 38 |
+
debug_environment()
|
| 39 |
+
|
| 40 |
+
# Initialize the GAIAAgent with local execution
|
| 41 |
+
try:
|
| 42 |
+
# Load environment variables if dotenv is available
|
| 43 |
+
try:
|
| 44 |
+
import dotenv
|
| 45 |
+
dotenv.load_dotenv()
|
| 46 |
+
print("Loaded environment variables from .env file")
|
| 47 |
+
except ImportError:
|
| 48 |
+
print("python-dotenv not installed, continuing with environment as is")
|
| 49 |
+
|
| 50 |
+
# Try to load API keys from environment
|
| 51 |
+
# Check both HF_API_TOKEN and HUGGINGFACEHUB_API_TOKEN (HF Spaces uses HF_API_TOKEN)
|
| 52 |
+
hf_token = os.environ.get("HF_API_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
|
| 53 |
+
openai_key = os.environ.get("OPENAI_API_KEY")
|
| 54 |
+
xai_key = os.environ.get("XAI_API_KEY")
|
| 55 |
+
|
| 56 |
+
# If we have at least one API key, use a model-based approach
|
| 57 |
+
if hf_token or openai_key or xai_key:
|
| 58 |
+
# Default model parameters - read directly from environment
|
| 59 |
+
model_type = os.environ.get("AGENT_MODEL_TYPE", "OpenAIServerModel")
|
| 60 |
+
model_id = os.environ.get("AGENT_MODEL_ID", "gpt-4o")
|
| 61 |
+
temperature = float(os.environ.get("AGENT_TEMPERATURE", "0.2"))
|
| 62 |
+
verbose = os.environ.get("AGENT_VERBOSE", "false").lower() == "true"
|
| 63 |
+
|
| 64 |
+
print(f"Agent config - Model Type: {model_type}, Model ID: {model_id}")
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
if xai_key:
|
| 68 |
+
# Use X.AI API with OpenAIServerModel
|
| 69 |
+
api_base = os.environ.get("XAI_API_BASE", "https://api.x.ai/v1")
|
| 70 |
+
self.gaia_agent = GAIAAgent(
|
| 71 |
+
model_type="OpenAIServerModel",
|
| 72 |
+
model_id="grok-3-latest", # X.AI's model
|
| 73 |
+
api_key=xai_key,
|
| 74 |
+
api_base=api_base,
|
| 75 |
+
temperature=temperature,
|
| 76 |
+
executor_type="local",
|
| 77 |
+
verbose=verbose
|
| 78 |
+
)
|
| 79 |
+
print(f"Using OpenAIServerModel with X.AI API at {api_base}")
|
| 80 |
+
elif model_type == "HfApiModel" and hf_token:
|
| 81 |
+
# Use Hugging Face API
|
| 82 |
+
self.gaia_agent = GAIAAgent(
|
| 83 |
+
model_type="HfApiModel",
|
| 84 |
+
model_id=model_id,
|
| 85 |
+
api_key=hf_token,
|
| 86 |
+
temperature=temperature,
|
| 87 |
+
executor_type="local",
|
| 88 |
+
verbose=verbose
|
| 89 |
+
)
|
| 90 |
+
print(f"Using HfApiModel with model_id: {model_id}")
|
| 91 |
+
elif openai_key:
|
| 92 |
+
# Default to OpenAI API
|
| 93 |
+
api_base = os.environ.get("AGENT_API_BASE")
|
| 94 |
+
kwargs = {
|
| 95 |
+
"model_type": "OpenAIServerModel",
|
| 96 |
+
"model_id": model_id,
|
| 97 |
+
"api_key": openai_key,
|
| 98 |
+
"temperature": temperature,
|
| 99 |
+
"executor_type": "local",
|
| 100 |
+
"verbose": verbose
|
| 101 |
+
}
|
| 102 |
+
if api_base:
|
| 103 |
+
kwargs["api_base"] = api_base
|
| 104 |
+
print(f"Using custom API base: {api_base}")
|
| 105 |
+
|
| 106 |
+
self.gaia_agent = GAIAAgent(**kwargs)
|
| 107 |
+
print(f"Using OpenAIServerModel with model_id: {model_id}")
|
| 108 |
+
else:
|
| 109 |
+
# Fallback to using whatever token we have
|
| 110 |
+
print("WARNING: Using fallback initialization with available token")
|
| 111 |
+
if hf_token:
|
| 112 |
+
self.gaia_agent = GAIAAgent(
|
| 113 |
+
model_type="HfApiModel",
|
| 114 |
+
model_id="mistralai/Mistral-7B-Instruct-v0.2",
|
| 115 |
+
api_key=hf_token,
|
| 116 |
+
temperature=temperature,
|
| 117 |
+
executor_type="local",
|
| 118 |
+
verbose=verbose
|
| 119 |
+
)
|
| 120 |
+
elif openai_key:
|
| 121 |
+
self.gaia_agent = GAIAAgent(
|
| 122 |
+
model_type="OpenAIServerModel",
|
| 123 |
+
model_id="gpt-3.5-turbo",
|
| 124 |
+
api_key=openai_key,
|
| 125 |
+
temperature=temperature,
|
| 126 |
+
executor_type="local",
|
| 127 |
+
verbose=verbose
|
| 128 |
+
)
|
| 129 |
+
else:
|
| 130 |
+
self.gaia_agent = GAIAAgent(
|
| 131 |
+
model_type="OpenAIServerModel",
|
| 132 |
+
model_id="grok-3-latest",
|
| 133 |
+
api_key=xai_key,
|
| 134 |
+
api_base=os.environ.get("XAI_API_BASE", "https://api.x.ai/v1"),
|
| 135 |
+
temperature=temperature,
|
| 136 |
+
executor_type="local",
|
| 137 |
+
verbose=verbose
|
| 138 |
+
)
|
| 139 |
+
except ImportError as ie:
|
| 140 |
+
# Handle OpenAI module errors specifically
|
| 141 |
+
if "openai" in str(ie).lower() and hf_token:
|
| 142 |
+
print(f"OpenAI module error: {ie}. Falling back to HfApiModel.")
|
| 143 |
+
self.gaia_agent = GAIAAgent(
|
| 144 |
+
model_type="HfApiModel",
|
| 145 |
+
model_id="mistralai/Mistral-7B-Instruct-v0.2",
|
| 146 |
+
api_key=hf_token,
|
| 147 |
+
temperature=temperature,
|
| 148 |
+
executor_type="local",
|
| 149 |
+
verbose=verbose
|
| 150 |
+
)
|
| 151 |
+
print(f"Using HfApiModel with model_id: mistralai/Mistral-7B-Instruct-v0.2 (fallback)")
|
| 152 |
+
else:
|
| 153 |
+
raise
|
| 154 |
+
else:
|
| 155 |
+
# No API keys available, log the error
|
| 156 |
+
print("ERROR: No API keys found. Please set at least one of these environment variables:")
|
| 157 |
+
print("- HUGGINGFACEHUB_API_TOKEN or HF_API_TOKEN")
|
| 158 |
+
print("- OPENAI_API_KEY")
|
| 159 |
+
print("- XAI_API_KEY")
|
| 160 |
+
self.gaia_agent = None
|
| 161 |
+
print("WARNING: No API keys found. Agent will not be able to answer questions.")
|
| 162 |
+
|
| 163 |
+
except Exception as e:
|
| 164 |
+
print(f"Error initializing GAIAAgent: {e}")
|
| 165 |
+
self.gaia_agent = None
|
| 166 |
+
print("WARNING: Failed to initialize agent. Falling back to basic responses.")
|
| 167 |
+
|
| 168 |
+
def __call__(self, question: str) -> str:
|
| 169 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 170 |
+
|
| 171 |
+
# Check if we have a functioning GAIA agent
|
| 172 |
+
if self.gaia_agent:
|
| 173 |
+
try:
|
| 174 |
+
# Process the question using the GAIA agent
|
| 175 |
+
answer = self.gaia_agent.answer_question(question)
|
| 176 |
+
print(f"Agent generated answer: {answer[:50]}..." if len(answer) > 50 else f"Agent generated answer: {answer}")
|
| 177 |
+
return answer
|
| 178 |
+
except Exception as e:
|
| 179 |
+
print(f"Error processing question: {e}")
|
| 180 |
+
# Fall back to a simple response on error
|
| 181 |
+
return "An error occurred while processing your question. Please check the agent logs for details."
|
| 182 |
+
else:
|
| 183 |
+
# We don't have a valid agent, provide a basic response
|
| 184 |
+
return "The agent is not properly initialized. Please check your API keys and configuration."
|
| 185 |
|
| 186 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
"""
|
| 188 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 189 |
+
and displays the results.
|
| 190 |
+
"""
|
| 191 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 192 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 193 |
|
| 194 |
+
if profile:
|
| 195 |
+
username= f"{profile.username}"
|
| 196 |
+
print(f"User logged in: {username}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
else:
|
| 198 |
+
print("User not logged in.")
|
| 199 |
+
return "Please Login to Hugging Face with the button.", None
|
| 200 |
+
|
| 201 |
+
api_url = DEFAULT_API_URL
|
| 202 |
+
questions_url = f"{api_url}/questions"
|
| 203 |
+
submit_url = f"{api_url}/submit"
|
| 204 |
+
|
| 205 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 206 |
+
try:
|
| 207 |
+
agent = BasicAgent()
|
| 208 |
+
|
| 209 |
+
# Check if agent is properly initialized
|
| 210 |
+
if not agent.gaia_agent:
|
| 211 |
+
print("ERROR: Agent was not properly initialized")
|
| 212 |
+
return "ERROR: Agent was not properly initialized. Check the logs for details on missing API keys or configuration.", None
|
| 213 |
+
|
| 214 |
+
except Exception as e:
|
| 215 |
+
print(f"Error instantiating agent: {e}")
|
| 216 |
+
return f"Error initializing agent: {e}", None
|
| 217 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
| 218 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 219 |
+
print(agent_code)
|
| 220 |
+
|
| 221 |
+
# 2. Fetch Questions
|
| 222 |
+
print(f"Fetching questions from: {questions_url}")
|
| 223 |
+
try:
|
| 224 |
+
response = requests.get(questions_url, timeout=15)
|
| 225 |
+
response.raise_for_status()
|
| 226 |
+
questions_data = response.json()
|
| 227 |
+
if not questions_data:
|
| 228 |
+
print("Fetched questions list is empty.")
|
| 229 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 230 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 231 |
+
except requests.exceptions.RequestException as e:
|
| 232 |
+
print(f"Error fetching questions: {e}")
|
| 233 |
+
return f"Error fetching questions: {e}", None
|
| 234 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 235 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 236 |
+
print(f"Response text: {response.text[:500]}")
|
| 237 |
+
return f"Error decoding server response for questions: {e}", None
|
| 238 |
+
except Exception as e:
|
| 239 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 240 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 241 |
+
|
| 242 |
+
# 3. Run your Agent
|
| 243 |
+
results_log = []
|
| 244 |
+
answers_payload = []
|
| 245 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 246 |
+
for item in questions_data:
|
| 247 |
+
task_id = item.get("task_id")
|
| 248 |
+
question_text = item.get("question")
|
| 249 |
+
if not task_id or question_text is None:
|
| 250 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 251 |
+
continue
|
| 252 |
+
try:
|
| 253 |
+
submitted_answer = agent(question_text)
|
| 254 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 255 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 256 |
+
except Exception as e:
|
| 257 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 258 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 259 |
+
|
| 260 |
+
if not answers_payload:
|
| 261 |
+
print("Agent did not produce any answers to submit.")
|
| 262 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 263 |
+
|
| 264 |
+
# 4. Prepare Submission
|
| 265 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 266 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 267 |
+
print(status_update)
|
| 268 |
+
|
| 269 |
+
# 5. Submit
|
| 270 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 271 |
+
try:
|
| 272 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 273 |
+
response.raise_for_status()
|
| 274 |
+
result_data = response.json()
|
| 275 |
+
final_status = (
|
| 276 |
+
f"Submission Successful!\n"
|
| 277 |
+
f"User: {result_data.get('username')}\n"
|
| 278 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 279 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 280 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 281 |
)
|
| 282 |
+
print("Submission successful.")
|
| 283 |
+
results_df = pd.DataFrame(results_log)
|
| 284 |
+
return final_status, results_df
|
| 285 |
+
except requests.exceptions.HTTPError as e:
|
| 286 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 287 |
+
try:
|
| 288 |
+
error_json = e.response.json()
|
| 289 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 290 |
+
except requests.exceptions.JSONDecodeError:
|
| 291 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 292 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 293 |
+
print(status_message)
|
| 294 |
+
results_df = pd.DataFrame(results_log)
|
| 295 |
+
return status_message, results_df
|
| 296 |
+
except requests.exceptions.Timeout:
|
| 297 |
+
status_message = "Submission Failed: The request timed out."
|
| 298 |
+
print(status_message)
|
| 299 |
+
results_df = pd.DataFrame(results_log)
|
| 300 |
+
return status_message, results_df
|
| 301 |
+
except requests.exceptions.RequestException as e:
|
| 302 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 303 |
+
print(status_message)
|
| 304 |
+
results_df = pd.DataFrame(results_log)
|
| 305 |
+
return status_message, results_df
|
| 306 |
+
except Exception as e:
|
| 307 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 308 |
+
print(status_message)
|
| 309 |
+
results_df = pd.DataFrame(results_log)
|
| 310 |
+
return status_message, results_df
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
# --- Build Gradio Interface using Blocks ---
|
| 314 |
+
with gr.Blocks() as demo:
|
| 315 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 316 |
+
gr.Markdown(
|
| 317 |
+
"""
|
| 318 |
+
**Instructions:**
|
| 319 |
+
|
| 320 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 321 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 322 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 323 |
+
|
| 324 |
+
---
|
| 325 |
+
**Disclaimers:**
|
| 326 |
+
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
| 327 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
| 328 |
+
"""
|
| 329 |
)
|
|
|
|
| 330 |
|
| 331 |
+
gr.LoginButton()
|
| 332 |
+
|
| 333 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 334 |
+
|
| 335 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 336 |
+
# Removed max_rows=10 from DataFrame constructor
|
| 337 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 338 |
+
|
| 339 |
+
run_button.click(
|
| 340 |
+
fn=run_and_submit_all,
|
| 341 |
+
outputs=[status_output, results_table]
|
| 342 |
+
)
|
| 343 |
|
|
|
|
| 344 |
if __name__ == "__main__":
|
| 345 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 346 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 347 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 348 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 349 |
+
|
| 350 |
+
if space_host_startup:
|
| 351 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 352 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 353 |
+
else:
|
| 354 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 355 |
+
|
| 356 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 357 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 358 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 359 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 360 |
+
else:
|
| 361 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 362 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from smolagents import (
|
| 2 |
+
CodeAgent,
|
| 3 |
+
DuckDuckGoSearchTool,
|
| 4 |
+
HfApiModel,
|
| 5 |
+
LiteLLMModel,
|
| 6 |
+
OpenAIServerModel,
|
| 7 |
+
PythonInterpreterTool,
|
| 8 |
+
tool,
|
| 9 |
+
InferenceClientModel
|
| 10 |
+
)
|
| 11 |
+
from typing import List, Dict, Any, Optional
|
| 12 |
+
import os
|
| 13 |
+
import tempfile
|
| 14 |
+
import re
|
| 15 |
+
import json
|
| 16 |
+
import requests
|
| 17 |
+
from urllib.parse import urlparse
|
| 18 |
+
|
| 19 |
+
@tool
|
| 20 |
+
def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
|
| 21 |
+
"""
|
| 22 |
+
Save content to a temporary file and return the path.
|
| 23 |
+
Useful for processing files from the GAIA API.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
content: The content to save to the file
|
| 27 |
+
filename: Optional filename, will generate a random name if not provided
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
Path to the saved file
|
| 31 |
+
"""
|
| 32 |
+
temp_dir = tempfile.gettempdir()
|
| 33 |
+
if filename is None:
|
| 34 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False)
|
| 35 |
+
filepath = temp_file.name
|
| 36 |
+
else:
|
| 37 |
+
filepath = os.path.join(temp_dir, filename)
|
| 38 |
+
|
| 39 |
+
# Write content to the file
|
| 40 |
+
with open(filepath, 'w') as f:
|
| 41 |
+
f.write(content)
|
| 42 |
+
|
| 43 |
+
return f"File saved to {filepath}. You can read this file to process its contents."
|
| 44 |
+
|
| 45 |
+
@tool
|
| 46 |
+
def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
|
| 47 |
+
"""
|
| 48 |
+
Download a file from a URL and save it to a temporary location.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
url: The URL to download from
|
| 52 |
+
filename: Optional filename, will generate one based on URL if not provided
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
Path to the downloaded file
|
| 56 |
+
"""
|
| 57 |
+
try:
|
| 58 |
+
# Parse URL to get filename if not provided
|
| 59 |
+
if not filename:
|
| 60 |
+
path = urlparse(url).path
|
| 61 |
+
filename = os.path.basename(path)
|
| 62 |
+
if not filename:
|
| 63 |
+
# Generate a random name if we couldn't extract one
|
| 64 |
+
import uuid
|
| 65 |
+
filename = f"downloaded_{uuid.uuid4().hex[:8]}"
|
| 66 |
+
|
| 67 |
+
# Create temporary file
|
| 68 |
+
temp_dir = tempfile.gettempdir()
|
| 69 |
+
filepath = os.path.join(temp_dir, filename)
|
| 70 |
+
|
| 71 |
+
# Download the file
|
| 72 |
+
response = requests.get(url, stream=True)
|
| 73 |
+
response.raise_for_status()
|
| 74 |
+
|
| 75 |
+
# Save the file
|
| 76 |
+
with open(filepath, 'wb') as f:
|
| 77 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 78 |
+
f.write(chunk)
|
| 79 |
+
|
| 80 |
+
return f"File downloaded to {filepath}. You can now process this file."
|
| 81 |
+
except Exception as e:
|
| 82 |
+
return f"Error downloading file: {str(e)}"
|
| 83 |
+
|
| 84 |
+
@tool
|
| 85 |
+
def extract_text_from_image(image_path: str) -> str:
|
| 86 |
+
"""
|
| 87 |
+
Extract text from an image using pytesseract (if available).
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
image_path: Path to the image file
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
Extracted text or error message
|
| 94 |
+
"""
|
| 95 |
+
try:
|
| 96 |
+
# Try to import pytesseract
|
| 97 |
+
import pytesseract
|
| 98 |
+
from PIL import Image
|
| 99 |
+
|
| 100 |
+
# Open the image
|
| 101 |
+
image = Image.open(image_path)
|
| 102 |
+
|
| 103 |
+
# Extract text
|
| 104 |
+
text = pytesseract.image_to_string(image)
|
| 105 |
+
|
| 106 |
+
return f"Extracted text from image:\n\n{text}"
|
| 107 |
+
except ImportError:
|
| 108 |
+
return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system."
|
| 109 |
+
except Exception as e:
|
| 110 |
+
return f"Error extracting text from image: {str(e)}"
|
| 111 |
+
|
| 112 |
+
@tool
|
| 113 |
+
def analyze_csv_file(file_path: str, query: str) -> str:
|
| 114 |
+
"""
|
| 115 |
+
Analyze a CSV file using pandas and answer a question about it.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
file_path: Path to the CSV file
|
| 119 |
+
query: Question about the data
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
Analysis result or error message
|
| 123 |
+
"""
|
| 124 |
+
try:
|
| 125 |
+
import pandas as pd
|
| 126 |
+
|
| 127 |
+
# Read the CSV file
|
| 128 |
+
df = pd.read_csv(file_path)
|
| 129 |
+
|
| 130 |
+
# Run various analyses based on the query
|
| 131 |
+
result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
| 132 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
| 133 |
+
|
| 134 |
+
# Add summary statistics
|
| 135 |
+
result += "Summary statistics:\n"
|
| 136 |
+
result += str(df.describe())
|
| 137 |
+
|
| 138 |
+
return result
|
| 139 |
+
except ImportError:
|
| 140 |
+
return "Error: pandas is not installed. Please install it with 'pip install pandas'."
|
| 141 |
+
except Exception as e:
|
| 142 |
+
return f"Error analyzing CSV file: {str(e)}"
|
| 143 |
+
|
| 144 |
+
@tool
|
| 145 |
+
def analyze_excel_file(file_path: str, query: str) -> str:
|
| 146 |
+
"""
|
| 147 |
+
Analyze an Excel file using pandas and answer a question about it.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
file_path: Path to the Excel file
|
| 151 |
+
query: Question about the data
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
Analysis result or error message
|
| 155 |
+
"""
|
| 156 |
+
try:
|
| 157 |
+
import pandas as pd
|
| 158 |
+
|
| 159 |
+
# Read the Excel file
|
| 160 |
+
df = pd.read_excel(file_path)
|
| 161 |
+
|
| 162 |
+
# Run various analyses based on the query
|
| 163 |
+
result = f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
| 164 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
| 165 |
+
|
| 166 |
+
# Add summary statistics
|
| 167 |
+
result += "Summary statistics:\n"
|
| 168 |
+
result += str(df.describe())
|
| 169 |
+
|
| 170 |
+
return result
|
| 171 |
+
except ImportError:
|
| 172 |
+
return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'."
|
| 173 |
+
except Exception as e:
|
| 174 |
+
return f"Error analyzing Excel file: {str(e)}"
|
| 175 |
+
|
| 176 |
+
class GAIAAgent:
|
| 177 |
+
def __init__(
|
| 178 |
+
self,
|
| 179 |
+
model_type: str = "HfApiModel",
|
| 180 |
+
model_id: Optional[str] = None,
|
| 181 |
+
api_key: Optional[str] = None,
|
| 182 |
+
api_base: Optional[str] = None,
|
| 183 |
+
temperature: float = 0.2,
|
| 184 |
+
executor_type: str = "local", # Changed from use_e2b to executor_type
|
| 185 |
+
additional_imports: List[str] = None,
|
| 186 |
+
additional_tools: List[Any] = None,
|
| 187 |
+
system_prompt: Optional[str] = None, # We'll still accept this parameter but not use it directly
|
| 188 |
+
verbose: bool = False,
|
| 189 |
+
provider: Optional[str] = None, # Add provider for InferenceClientModel
|
| 190 |
+
timeout: Optional[int] = None # Add timeout for InferenceClientModel
|
| 191 |
+
):
|
| 192 |
+
"""
|
| 193 |
+
Initialize a GAIAAgent with specified configuration
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
model_type: Type of model to use (HfApiModel, LiteLLMModel, OpenAIServerModel, InferenceClientModel)
|
| 197 |
+
model_id: ID of the model to use
|
| 198 |
+
api_key: API key for the model provider
|
| 199 |
+
api_base: Base URL for API calls
|
| 200 |
+
temperature: Temperature for text generation
|
| 201 |
+
executor_type: Type of executor for code execution ('local' or 'e2b')
|
| 202 |
+
additional_imports: Additional Python modules to allow importing
|
| 203 |
+
additional_tools: Additional tools to provide to the agent
|
| 204 |
+
system_prompt: Custom system prompt to use (not directly used, kept for backward compatibility)
|
| 205 |
+
verbose: Enable verbose logging
|
| 206 |
+
provider: Provider for InferenceClientModel (e.g., "hf-inference")
|
| 207 |
+
timeout: Timeout in seconds for API calls
|
| 208 |
+
"""
|
| 209 |
+
# Set verbosity
|
| 210 |
+
self.verbose = verbose
|
| 211 |
+
self.system_prompt = system_prompt # Store for potential future use
|
| 212 |
+
|
| 213 |
+
# Initialize model based on configuration
|
| 214 |
+
if model_type == "HfApiModel":
|
| 215 |
+
if api_key is None:
|
| 216 |
+
api_key = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 217 |
+
if not api_key:
|
| 218 |
+
raise ValueError("No Hugging Face token provided. Please set HUGGINGFACEHUB_API_TOKEN environment variable or pass api_key parameter.")
|
| 219 |
+
|
| 220 |
+
if self.verbose:
|
| 221 |
+
print(f"Using Hugging Face token: {api_key[:5]}...")
|
| 222 |
+
|
| 223 |
+
self.model = HfApiModel(
|
| 224 |
+
model_id=model_id or "meta-llama/Llama-3-70B-Instruct",
|
| 225 |
+
token=api_key,
|
| 226 |
+
temperature=temperature
|
| 227 |
+
)
|
| 228 |
+
elif model_type == "InferenceClientModel":
|
| 229 |
+
if api_key is None:
|
| 230 |
+
api_key = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 231 |
+
if not api_key:
|
| 232 |
+
raise ValueError("No Hugging Face token provided. Please set HUGGINGFACEHUB_API_TOKEN environment variable or pass api_key parameter.")
|
| 233 |
+
|
| 234 |
+
if self.verbose:
|
| 235 |
+
print(f"Using Hugging Face token: {api_key[:5]}...")
|
| 236 |
+
|
| 237 |
+
self.model = InferenceClientModel(
|
| 238 |
+
model_id=model_id or "meta-llama/Llama-3-70B-Instruct",
|
| 239 |
+
provider=provider or "hf-inference",
|
| 240 |
+
token=api_key,
|
| 241 |
+
timeout=timeout or 120,
|
| 242 |
+
temperature=temperature
|
| 243 |
+
)
|
| 244 |
+
elif model_type == "LiteLLMModel":
|
| 245 |
+
from smolagents import LiteLLMModel
|
| 246 |
+
self.model = LiteLLMModel(
|
| 247 |
+
model_id=model_id or "gpt-4o",
|
| 248 |
+
api_key=api_key or os.getenv("OPENAI_API_KEY"),
|
| 249 |
+
temperature=temperature
|
| 250 |
+
)
|
| 251 |
+
elif model_type == "OpenAIServerModel":
|
| 252 |
+
# Check for xAI API key and base URL first
|
| 253 |
+
xai_api_key = os.getenv("XAI_API_KEY")
|
| 254 |
+
xai_api_base = os.getenv("XAI_API_BASE")
|
| 255 |
+
|
| 256 |
+
# If xAI credentials are available, use them
|
| 257 |
+
if xai_api_key and api_key is None:
|
| 258 |
+
api_key = xai_api_key
|
| 259 |
+
if self.verbose:
|
| 260 |
+
print(f"Using xAI API key: {api_key[:5]}...")
|
| 261 |
+
|
| 262 |
+
# If no API key specified, fall back to OPENAI_API_KEY
|
| 263 |
+
if api_key is None:
|
| 264 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 265 |
+
if not api_key:
|
| 266 |
+
raise ValueError("No OpenAI API key provided. Please set OPENAI_API_KEY or XAI_API_KEY environment variable or pass api_key parameter.")
|
| 267 |
+
|
| 268 |
+
# If xAI API base is available and no api_base is provided, use it
|
| 269 |
+
if xai_api_base and api_base is None:
|
| 270 |
+
api_base = xai_api_base
|
| 271 |
+
if self.verbose:
|
| 272 |
+
print(f"Using xAI API base URL: {api_base}")
|
| 273 |
+
|
| 274 |
+
# If no API base specified but environment variable available, use it
|
| 275 |
+
if api_base is None:
|
| 276 |
+
api_base = os.getenv("AGENT_API_BASE")
|
| 277 |
+
if api_base and self.verbose:
|
| 278 |
+
print(f"Using API base from AGENT_API_BASE: {api_base}")
|
| 279 |
+
|
| 280 |
+
self.model = OpenAIServerModel(
|
| 281 |
+
model_id=model_id or "gpt-4o",
|
| 282 |
+
api_key=api_key,
|
| 283 |
+
api_base=api_base,
|
| 284 |
+
temperature=temperature
|
| 285 |
+
)
|
| 286 |
+
else:
|
| 287 |
+
raise ValueError(f"Unknown model type: {model_type}")
|
| 288 |
+
|
| 289 |
+
if self.verbose:
|
| 290 |
+
print(f"Initialized model: {model_type} - {model_id}")
|
| 291 |
+
|
| 292 |
+
# Initialize default tools
|
| 293 |
+
self.tools = [
|
| 294 |
+
DuckDuckGoSearchTool(),
|
| 295 |
+
PythonInterpreterTool(),
|
| 296 |
+
save_and_read_file,
|
| 297 |
+
download_file_from_url,
|
| 298 |
+
analyze_csv_file,
|
| 299 |
+
analyze_excel_file
|
| 300 |
+
]
|
| 301 |
+
|
| 302 |
+
# Add extract_text_from_image if PIL and pytesseract are available
|
| 303 |
+
try:
|
| 304 |
+
import pytesseract
|
| 305 |
+
from PIL import Image
|
| 306 |
+
self.tools.append(extract_text_from_image)
|
| 307 |
+
if self.verbose:
|
| 308 |
+
print("Added image processing tool")
|
| 309 |
+
except ImportError:
|
| 310 |
+
if self.verbose:
|
| 311 |
+
print("Image processing libraries not available")
|
| 312 |
+
|
| 313 |
+
# Add any additional tools
|
| 314 |
+
if additional_tools:
|
| 315 |
+
self.tools.extend(additional_tools)
|
| 316 |
+
|
| 317 |
+
if self.verbose:
|
| 318 |
+
print(f"Initialized with {len(self.tools)} tools")
|
| 319 |
+
|
| 320 |
+
# Setup imports allowed
|
| 321 |
+
self.imports = ["pandas", "numpy", "datetime", "json", "re", "math", "os", "requests", "csv", "urllib"]
|
| 322 |
+
if additional_imports:
|
| 323 |
+
self.imports.extend(additional_imports)
|
| 324 |
+
|
| 325 |
+
# Initialize the CodeAgent
|
| 326 |
+
executor_kwargs = {}
|
| 327 |
+
if executor_type == "e2b":
|
| 328 |
+
try:
|
| 329 |
+
# Try to import e2b dependencies to check if they're available
|
| 330 |
+
from e2b_code_interpreter import Sandbox
|
| 331 |
+
if self.verbose:
|
| 332 |
+
print("Using e2b executor")
|
| 333 |
+
except ImportError:
|
| 334 |
+
if self.verbose:
|
| 335 |
+
print("e2b dependencies not found, falling back to local executor")
|
| 336 |
+
executor_type = "local" # Fallback to local if e2b is not available
|
| 337 |
+
|
| 338 |
+
self.agent = CodeAgent(
|
| 339 |
+
tools=self.tools,
|
| 340 |
+
model=self.model,
|
| 341 |
+
additional_authorized_imports=self.imports,
|
| 342 |
+
executor_type=executor_type,
|
| 343 |
+
executor_kwargs=executor_kwargs,
|
| 344 |
+
verbosity_level=2 if self.verbose else 0
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
if self.verbose:
|
| 348 |
+
print("Agent initialized and ready")
|
| 349 |
+
|
| 350 |
+
def answer_question(self, question: str, task_file_path: Optional[str] = None) -> str:
|
| 351 |
+
"""
|
| 352 |
+
Process a GAIA benchmark question and return the answer
|
| 353 |
+
|
| 354 |
+
Args:
|
| 355 |
+
question: The question to answer
|
| 356 |
+
task_file_path: Optional path to a file associated with the question
|
| 357 |
+
|
| 358 |
+
Returns:
|
| 359 |
+
The answer to the question
|
| 360 |
+
"""
|
| 361 |
+
try:
|
| 362 |
+
if self.verbose:
|
| 363 |
+
print(f"Processing question: {question}")
|
| 364 |
+
if task_file_path:
|
| 365 |
+
print(f"With associated file: {task_file_path}")
|
| 366 |
+
|
| 367 |
+
# Create a context with file information if available
|
| 368 |
+
context = question
|
| 369 |
+
file_content = None
|
| 370 |
+
|
| 371 |
+
# If there's a file, read it and include its content in the context
|
| 372 |
+
if task_file_path:
|
| 373 |
+
try:
|
| 374 |
+
with open(task_file_path, 'r') as f:
|
| 375 |
+
file_content = f.read()
|
| 376 |
+
|
| 377 |
+
# Determine file type from extension
|
| 378 |
+
import os
|
| 379 |
+
file_ext = os.path.splitext(task_file_path)[1].lower()
|
| 380 |
+
|
| 381 |
+
context = f"""
|
| 382 |
+
Question: {question}
|
| 383 |
+
|
| 384 |
+
This question has an associated file. Here is the file content:
|
| 385 |
+
|
| 386 |
+
```{file_ext}
|
| 387 |
+
{file_content}
|
| 388 |
+
```
|
| 389 |
+
|
| 390 |
+
Analyze the file content above to answer the question.
|
| 391 |
+
"""
|
| 392 |
+
except Exception as file_e:
|
| 393 |
+
context = f"""
|
| 394 |
+
Question: {question}
|
| 395 |
+
|
| 396 |
+
This question has an associated file at path: {task_file_path}
|
| 397 |
+
However, there was an error reading the file: {file_e}
|
| 398 |
+
You can still try to answer the question based on the information provided.
|
| 399 |
+
"""
|
| 400 |
+
|
| 401 |
+
# Check for special cases that need specific formatting
|
| 402 |
+
# Reversed text questions
|
| 403 |
+
if question.startswith(".") or ".rewsna eht sa" in question:
|
| 404 |
+
context = f"""
|
| 405 |
+
This question appears to be in reversed text. Here's the reversed version:
|
| 406 |
+
{question[::-1]}
|
| 407 |
+
|
| 408 |
+
Now answer the question above. Remember to format your answer exactly as requested.
|
| 409 |
+
"""
|
| 410 |
+
|
| 411 |
+
# Add a prompt to ensure precise answers
|
| 412 |
+
full_prompt = f"""{context}
|
| 413 |
+
|
| 414 |
+
When answering, provide ONLY the precise answer requested.
|
| 415 |
+
Do not include explanations, steps, reasoning, or additional text.
|
| 416 |
+
Be direct and specific. GAIA benchmark requires exact matching answers.
|
| 417 |
+
For example, if asked "What is the capital of France?", respond simply with "Paris".
|
| 418 |
+
"""
|
| 419 |
+
|
| 420 |
+
# Run the agent with the question
|
| 421 |
+
answer = self.agent.run(full_prompt)
|
| 422 |
+
|
| 423 |
+
# Clean up the answer to ensure it's in the expected format
|
| 424 |
+
# Remove common prefixes that models often add
|
| 425 |
+
answer = self._clean_answer(answer)
|
| 426 |
+
|
| 427 |
+
if self.verbose:
|
| 428 |
+
print(f"Generated answer: {answer}")
|
| 429 |
+
|
| 430 |
+
return answer
|
| 431 |
+
except Exception as e:
|
| 432 |
+
error_msg = f"Error answering question: {e}"
|
| 433 |
+
if self.verbose:
|
| 434 |
+
print(error_msg)
|
| 435 |
+
return error_msg
|
| 436 |
+
|
| 437 |
+
def _clean_answer(self, answer: any) -> str:
|
| 438 |
+
"""
|
| 439 |
+
Clean up the answer to remove common prefixes and formatting
|
| 440 |
+
that models often add but that can cause exact match failures.
|
| 441 |
+
|
| 442 |
+
Args:
|
| 443 |
+
answer: The raw answer from the model
|
| 444 |
+
|
| 445 |
+
Returns:
|
| 446 |
+
The cleaned answer as a string
|
| 447 |
+
"""
|
| 448 |
+
# Convert non-string types to strings
|
| 449 |
+
if not isinstance(answer, str):
|
| 450 |
+
# Handle numeric types (float, int)
|
| 451 |
+
if isinstance(answer, float):
|
| 452 |
+
# Format floating point numbers properly
|
| 453 |
+
# Check if it's an integer value in float form (e.g., 12.0)
|
| 454 |
+
if answer.is_integer():
|
| 455 |
+
formatted_answer = str(int(answer))
|
| 456 |
+
else:
|
| 457 |
+
# For currency values that might need formatting
|
| 458 |
+
if abs(answer) >= 1000:
|
| 459 |
+
formatted_answer = f"${answer:,.2f}"
|
| 460 |
+
else:
|
| 461 |
+
formatted_answer = str(answer)
|
| 462 |
+
return formatted_answer
|
| 463 |
+
elif isinstance(answer, int):
|
| 464 |
+
return str(answer)
|
| 465 |
+
else:
|
| 466 |
+
# For any other type
|
| 467 |
+
return str(answer)
|
| 468 |
+
|
| 469 |
+
# Now we know answer is a string, so we can safely use string methods
|
| 470 |
+
# Normalize whitespace
|
| 471 |
+
answer = answer.strip()
|
| 472 |
+
|
| 473 |
+
# Remove common prefixes and formatting that models add
|
| 474 |
+
prefixes_to_remove = [
|
| 475 |
+
"The answer is ",
|
| 476 |
+
"Answer: ",
|
| 477 |
+
"Final answer: ",
|
| 478 |
+
"The result is ",
|
| 479 |
+
"To answer this question: ",
|
| 480 |
+
"Based on the information provided, ",
|
| 481 |
+
"According to the information: ",
|
| 482 |
+
]
|
| 483 |
+
|
| 484 |
+
for prefix in prefixes_to_remove:
|
| 485 |
+
if answer.startswith(prefix):
|
| 486 |
+
answer = answer[len(prefix):].strip()
|
| 487 |
+
|
| 488 |
+
# Remove quotes if they wrap the entire answer
|
| 489 |
+
if (answer.startswith('"') and answer.endswith('"')) or (answer.startswith("'") and answer.endswith("'")):
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import traceback
|
| 6 |
+
from core_agent import GAIAAgent
|
| 7 |
+
from api_integration import GAIAApiClient
|
| 8 |
+
|
| 9 |
+
# Constants
|
| 10 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
+
|
| 12 |
+
def save_task_file(file_content, task_id):
|
| 13 |
+
"""
|
| 14 |
+
Save a task file to a temporary location
|
| 15 |
+
"""
|
| 16 |
+
if not file_content:
|
| 17 |
+
return None
|
| 18 |
+
|
| 19 |
+
# Create a temporary file
|
| 20 |
+
temp_dir = tempfile.gettempdir()
|
| 21 |
+
file_path = os.path.join(temp_dir, f"gaia_task_{task_id}.txt")
|
| 22 |
+
|
| 23 |
+
# Write content to the file
|
| 24 |
+
with open(file_path, 'wb') as f:
|
| 25 |
+
f.write(file_content)
|
| 26 |
+
|
| 27 |
+
print(f"File saved to {file_path}")
|
| 28 |
+
return file_path
|
| 29 |
+
|
| 30 |
+
def get_agent_configuration():
|
| 31 |
+
"""
|
| 32 |
+
Get the agent configuration based on environment variables
|
| 33 |
+
"""
|
| 34 |
+
# Default configuration
|
| 35 |
+
config = {
|
| 36 |
+
"model_type": "OpenAIServerModel", # Default to OpenAIServerModel
|
| 37 |
+
"model_id": "gpt-4o", # Default model for OpenAI
|
| 38 |
+
"temperature": 0.2,
|
| 39 |
+
"executor_type": "local",
|
| 40 |
+
"verbose": False,
|
| 41 |
+
"provider": "hf-inference", # For InferenceClientModel
|
| 42 |
+
"timeout": 120 # For InferenceClientModel
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
# Check for xAI API key and base URL
|
| 46 |
+
xai_api_key = os.getenv("XAI_API_KEY")
|
| 47 |
+
xai_api_base = os.getenv("XAI_API_BASE")
|
| 48 |
+
|
| 49 |
+
# If we have xAI credentials, use them
|
| 50 |
+
if xai_api_key:
|
| 51 |
+
config["api_key"] = xai_api_key
|
| 52 |
+
if xai_api_base:
|
| 53 |
+
config["api_base"] = xai_api_base
|
| 54 |
+
# Use a model that works well with xAI
|
| 55 |
+
config["model_id"] = "mixtral-8x7b-32768"
|
| 56 |
+
|
| 57 |
+
# Override with environment variables if present
|
| 58 |
+
if os.getenv("AGENT_MODEL_TYPE"):
|
| 59 |
+
config["model_type"] = os.getenv("AGENT_MODEL_TYPE")
|
| 60 |
+
|
| 61 |
+
if os.getenv("AGENT_MODEL_ID"):
|
| 62 |
+
config["model_id"] = os.getenv("AGENT_MODEL_ID")
|
| 63 |
+
|
| 64 |
+
if os.getenv("AGENT_TEMPERATURE"):
|
| 65 |
+
config["temperature"] = float(os.getenv("AGENT_TEMPERATURE"))
|
| 66 |
+
|
| 67 |
+
if os.getenv("AGENT_EXECUTOR_TYPE"):
|
| 68 |
+
config["executor_type"] = os.getenv("AGENT_EXECUTOR_TYPE")
|
| 69 |
+
|
| 70 |
+
if os.getenv("AGENT_VERBOSE") is not None:
|
| 71 |
+
config["verbose"] = os.getenv("AGENT_VERBOSE").lower() == "true"
|
| 72 |
+
|
| 73 |
+
if os.getenv("AGENT_API_BASE"):
|
| 74 |
+
config["api_base"] = os.getenv("AGENT_API_BASE")
|
| 75 |
+
|
| 76 |
+
# InferenceClientModel specific settings
|
| 77 |
+
if os.getenv("AGENT_PROVIDER"):
|
| 78 |
+
config["provider"] = os.getenv("AGENT_PROVIDER")
|
| 79 |
+
|
| 80 |
+
if os.getenv("AGENT_TIMEOUT"):
|
| 81 |
+
config["timeout"] = int(os.getenv("AGENT_TIMEOUT"))
|
| 82 |
+
|
| 83 |
+
return config
|
| 84 |
+
|
| 85 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 86 |
+
"""
|
| 87 |
+
Fetches all questions, runs the GAIAAgent on them, submits all answers,
|
| 88 |
+
and displays the results.
|
| 89 |
+
"""
|
| 90 |
+
# Check for user login
|
| 91 |
+
if not profile:
|
| 92 |
+
return "Please Login to Hugging Face with the button.", None
|
| 93 |
+
|
| 94 |
+
username = profile.username
|
| 95 |
+
print(f"User logged in: {username}")
|
| 96 |
+
|
| 97 |
+
# Get SPACE_ID for code link
|
| 98 |
+
space_id = os.getenv("SPACE_ID")
|
| 99 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 100 |
+
|
| 101 |
+
# Initialize API client
|
| 102 |
+
api_client = GAIAApiClient(DEFAULT_API_URL)
|
| 103 |
+
|
| 104 |
+
# Initialize Agent with configuration
|
| 105 |
+
try:
|
| 106 |
+
agent_config = get_agent_configuration()
|
| 107 |
+
print(f"Using agent configuration: {agent_config}")
|
| 108 |
+
|
| 109 |
+
agent = GAIAAgent(**agent_config)
|
| 110 |
+
print("Agent initialized successfully")
|
| 111 |
+
except Exception as e:
|
| 112 |
+
error_details = traceback.format_exc()
|
| 113 |
+
print(f"Error initializing agent: {e}\n{error_details}")
|
| 114 |
+
return f"Error initializing agent: {e}", None
|
| 115 |
+
|
| 116 |
+
# Fetch questions
|
| 117 |
+
try:
|
| 118 |
+
questions_data = api_client.get_questions()
|
| 119 |
+
if not questions_data:
|
| 120 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 121 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 122 |
+
except Exception as e:
|
| 123 |
+
error_details = traceback.format_exc()
|
| 124 |
+
print(f"Error fetching questions: {e}\n{error_details}")
|
| 125 |
+
return f"Error fetching questions: {e}", None
|
| 126 |
+
|
| 127 |
+
# Run agent on questions
|
| 128 |
+
results_log = []
|
| 129 |
+
answers_payload = []
|
| 130 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 131 |
+
|
| 132 |
+
# Progress tracking
|
| 133 |
+
total_questions = len(questions_data)
|
| 134 |
+
completed = 0
|
| 135 |
+
failed = 0
|
| 136 |
+
|
| 137 |
+
for item in questions_data:
|
| 138 |
+
task_id = item.get("task_id")
|
| 139 |
+
question_text = item.get("question")
|
| 140 |
+
if not task_id or question_text is None:
|
| 141 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 142 |
+
continue
|
| 143 |
+
|
| 144 |
+
try:
|
| 145 |
+
# Update progress
|
| 146 |
+
completed += 1
|
| 147 |
+
print(f"Processing question {completed}/{total_questions}: Task ID {task_id}")
|
| 148 |
+
|
| 149 |
+
# Check if the question has an associated file
|
| 150 |
+
file_path = None
|
| 151 |
+
try:
|
| 152 |
+
file_content = api_client.get_file(task_id)
|
| 153 |
+
print(f"Downloaded file for task {task_id}")
|
| 154 |
+
file_path = save_task_file(file_content, task_id)
|
| 155 |
+
except Exception as file_e:
|
| 156 |
+
print(f"No file found for task {task_id} or error: {file_e}")
|
| 157 |
+
|
| 158 |
+
# Run the agent to get the answer
|
| 159 |
+
submitted_answer = agent.answer_question(question_text, file_path)
|
| 160 |
+
|
| 161 |
+
# Add to results
|
| 162 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 163 |
+
results_log.append({
|
| 164 |
+
"Task ID": task_id,
|
| 165 |
+
"Question": question_text,
|
| 166 |
+
"Submitted Answer": submitted_answer
|
| 167 |
+
})
|
| 168 |
+
except Exception as e:
|
| 169 |
+
# Update error count
|
| 170 |
+
failed += 1
|
| 171 |
+
error_details = traceback.format_exc()
|
| 172 |
+
print(f"Error running agent on task {task_id}: {e}\n{error_details}")
|
| 173 |
+
|
| 174 |
+
# Add error to results
|
| 175 |
+
error_msg = f"AGENT ERROR: {e}"
|
| 176 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": error_msg})
|
| 177 |
+
results_log.append({
|
| 178 |
+
"Task ID": task_id,
|
| 179 |
+
"Question": question_text,
|
| 180 |
+
"Submitted Answer": error_msg
|
| 181 |
+
})
|
| 182 |
+
|
| 183 |
+
# Print summary
|
| 184 |
+
print(f"\nProcessing complete: {completed} questions processed, {failed} failures")
|
| 185 |
+
|
| 186 |
+
if not answers_payload:
|
| 187 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 188 |
+
|
| 189 |
+
# Submit answers
|
| 190 |
+
submission_data = {
|
| 191 |
+
"username": username.strip(),
|
| 192 |
+
"agent_code": agent_code,
|
| 193 |
+
"answers": answers_payload
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
print(f"Submitting {len(answers_payload)} answers for username '{username}'...")
|
| 197 |
+
|
| 198 |
+
try:
|
| 199 |
+
result_data = api_client.submit_answers(
|
| 200 |
+
username.strip(),
|
| 201 |
+
agent_code,
|
| 202 |
+
answers_payload
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# Calculate success rate
|
| 206 |
+
correct_count = result_data.get('correct_count', 0)
|
| 207 |
+
total_attempted = result_data.get('total_attempted', len(answers_payload))
|
| 208 |
+
success_rate = (correct_count / total_attempted) * 100 if total_attempted > 0 else 0
|
| 209 |
+
|
| 210 |
+
final_status = (
|
| 211 |
+
f"Submission Successful!\n"
|
| 212 |
+
f"User: {result_data.get('username')}\n"
|
| 213 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 214 |
+
f"({correct_count}/{total_attempted} correct, {success_rate:.1f}% success rate)\n"
|
| 215 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
print("Submission successful.")
|
| 219 |
+
return final_status, pd.DataFrame(results_log)
|
| 220 |
+
except Exception as e:
|
| 221 |
+
error_details = traceback.format_exc()
|
| 222 |
+
status_message = f"Submission Failed: {e}\n{error_details}"
|
| 223 |
+
print(status_message)
|
| 224 |
+
return status_message, pd.DataFrame(results_log)
|
| 225 |
+
|
| 226 |
+
# Build Gradio Interface
|
| 227 |
+
with gr.Blocks() as demo:
|
| 228 |
+
gr.Markdown("# GAIA Agent Evaluation Runner")
|
| 229 |
+
gr.Markdown(
|
| 230 |
+
"""
|
| 231 |
+
**Instructions:**
|
| 232 |
+
|
| 233 |
+
1. Log in to your Hugging Face account using the button below.
|
| 234 |
+
2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 235 |
+
|
| 236 |
+
**Configuration:**
|
| 237 |
+
|
| 238 |
+
You can configure the agent by setting these environment variables:
|
| 239 |
+
- `AGENT_MODEL_TYPE`: Model type (HfApiModel, InferenceClientModel, LiteLLMModel, OpenAIServerModel)
|
| 240 |
+
- `AGENT_MODEL_ID`: Model ID
|
| 241 |
+
- `AGENT_TEMPERATURE`: Temperature for generation (0.0-1.0)
|
| 242 |
+
- `AGENT_EXECUTOR_TYPE`: Type of executor ('local' or 'e2b')
|
| 243 |
+
- `AGENT_VERBOSE`: Enable verbose logging (true/false)
|
| 244 |
+
- `AGENT_API_BASE`: Base URL for API calls (for OpenAIServerModel)
|
| 245 |
+
|
| 246 |
+
**xAI Support:**
|
| 247 |
+
- `XAI_API_KEY`: Your xAI API key
|
| 248 |
+
- `XAI_API_BASE`: Base URL for xAI API (default: https://api.groq.com/openai/v1)
|
| 249 |
+
- When using xAI, set AGENT_MODEL_TYPE=OpenAIServerModel and AGENT_MODEL_ID=mixtral-8x7b-32768
|
| 250 |
+
|
| 251 |
+
**InferenceClientModel specific settings:**
|
| 252 |
+
- `AGENT_PROVIDER`: Provider for InferenceClientModel (e.g., "hf-inference")
|
| 253 |
+
- `AGENT_TIMEOUT`: Timeout in seconds for API calls
|
| 254 |
+
"""
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
gr.LoginButton()
|
| 258 |
+
|
| 259 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 260 |
+
|
| 261 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 262 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 263 |
+
|
| 264 |
+
run_button.click(
|
| 265 |
+
fn=run_and_submit_all,
|
| 266 |
+
outputs=[status_output, results_table]
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
if __name__ == "__main__":
|
| 270 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 271 |
+
|
| 272 |
+
# Check for environment variables
|
| 273 |
+
config = get_agent_configuration()
|
| 274 |
+
print(f"Agent configuration: {config}")
|
| 275 |
+
|
| 276 |
+
# Run the Gradio app
|
| 277 |
+
demo.launch(debug=True, share=False)
|
| 278 |
+
|
requirements.txt
CHANGED
|
@@ -1,19 +1,8 @@
|
|
| 1 |
gradio
|
| 2 |
requests
|
| 3 |
-
|
| 4 |
-
langchain-community
|
| 5 |
-
langchain-core
|
| 6 |
-
langchain-google-genai
|
| 7 |
-
langchain-huggingface
|
| 8 |
-
langchain-groq
|
| 9 |
-
langchain-tavily
|
| 10 |
-
langchain-chroma
|
| 11 |
-
langgraph
|
| 12 |
-
huggingface_hub
|
| 13 |
-
pgvector
|
| 14 |
-
supabase
|
| 15 |
-
arxiv
|
| 16 |
-
pymupdf
|
| 17 |
-
wikipedia
|
| 18 |
python-dotenv
|
|
|
|
|
|
|
|
|
|
| 19 |
|
|
|
|
| 1 |
gradio
|
| 2 |
requests
|
| 3 |
+
smolagents[openai]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
python-dotenv
|
| 5 |
+
pandas
|
| 6 |
+
numpy
|
| 7 |
+
openai
|
| 8 |
|