Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,169 +1,46 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import requests
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
-
import gradio as gr
|
| 5 |
-
import tempfile
|
| 6 |
-
import json
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
from typing import Union, Optional
|
| 9 |
-
from smolagents import LiteLLMModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool
|
| 10 |
-
from smolagents.tools import Tool
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
# --- Function to Configure Google Credentials (ESSENTIAL) ---
|
| 14 |
-
def setup_google_credentials():
|
| 15 |
-
"""
|
| 16 |
-
Reads Google Cloud credential JSON content from an environment variable,
|
| 17 |
-
writes it to a temporary file, and sets the GOOGLE_APPLICATION_CREDENTIALS
|
| 18 |
-
environment variable to the path of that file.
|
| 19 |
-
|
| 20 |
-
This function should be called before any Google Cloud client library
|
| 21 |
-
(like the one used by LiteLLM for Vertex AI) is initialized.
|
| 22 |
-
|
| 23 |
-
Requires the service account key JSON content to be stored in an
|
| 24 |
-
environment variable named 'GOOGLE_APPLICATION_CREDENTIALS_JSON'.
|
| 25 |
-
Set this in your Hugging Face Space secrets.
|
| 26 |
-
"""
|
| 27 |
-
credentials_json_str = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS_JSON")
|
| 28 |
-
if not credentials_json_str:
|
| 29 |
-
print("ERROR: 'GOOGLE_APPLICATION_CREDENTIALS_JSON' secret not found in environment variables.")
|
| 30 |
-
print(" Please ensure you have set this secret in your Hugging Face Space settings.")
|
| 31 |
-
# Depending on requirements, you might want to raise an error here
|
| 32 |
-
# raise ValueError("Secret 'GOOGLE_APPLICATION_CREDENTIALS_JSON' not set.")
|
| 33 |
-
return False # Indicate failure
|
| 34 |
-
|
| 35 |
-
try:
|
| 36 |
-
# Create a secure temporary file to store the credentials
|
| 37 |
-
# delete=False ensures the file persists until the process exits or it's manually cleaned up.
|
| 38 |
-
# We need the file path to set the environment variable.
|
| 39 |
-
with tempfile.NamedTemporaryFile(mode='w', suffix=".json", delete=False, encoding='utf-8') as temp_f:
|
| 40 |
-
temp_f.write(credentials_json_str)
|
| 41 |
-
credentials_path = temp_f.name # Get the path to the temporary file
|
| 42 |
-
|
| 43 |
-
# Set the environment variable that Google client libraries expect
|
| 44 |
-
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_path
|
| 45 |
-
print(f"Google Application Credentials successfully set to temporary file: {credentials_path}")
|
| 46 |
-
return True # Indicate success
|
| 47 |
-
except json.JSONDecodeError:
|
| 48 |
-
print("ERROR: Failed to parse the content of 'GOOGLE_APPLICATION_CREDENTIALS_JSON'. Ensure it's valid JSON.")
|
| 49 |
-
return False
|
| 50 |
-
except OSError as e:
|
| 51 |
-
print(f"ERROR: Failed to write credentials to temporary file: {e}")
|
| 52 |
-
return False
|
| 53 |
-
except Exception as e:
|
| 54 |
-
print(f"ERROR: An unexpected error occurred during Google credential setup: {e}")
|
| 55 |
-
# You might want to re-raise the exception depending on your error handling strategy
|
| 56 |
-
# raise e
|
| 57 |
-
return False
|
| 58 |
-
|
| 59 |
-
# --- Call Credential Setup EARLY ---
|
| 60 |
-
# This needs to run before any code (like BasicAgent initialization) tries to use Google Cloud services.
|
| 61 |
-
print("Attempting to configure Google Cloud credentials...")
|
| 62 |
-
CREDENTIALS_CONFIGURED = setup_google_credentials()
|
| 63 |
-
if not CREDENTIALS_CONFIGURED:
|
| 64 |
-
print("WARNING: Google Cloud credentials setup failed. Agent initialization might fail.")
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
# (Keep Constants as is)
|
| 68 |
# --- Constants ---
|
| 69 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 70 |
|
| 71 |
-
|
| 72 |
-
### Defining tools ###
|
| 73 |
-
|
| 74 |
-
class ExcelToTextTool(Tool):
|
| 75 |
-
"""Render an Excel worksheet as Markdown text."""
|
| 76 |
-
|
| 77 |
-
name = "excel_to_text"
|
| 78 |
-
description = (
|
| 79 |
-
"Read an Excel file and return a Markdown table of the requested sheet. "
|
| 80 |
-
"Accepts either the sheet name or the zero-based index."
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
inputs = {
|
| 84 |
-
"excel_path": {
|
| 85 |
-
"type": "string",
|
| 86 |
-
"description": "Path to the Excel file (.xlsx / .xls).",
|
| 87 |
-
},
|
| 88 |
-
"sheet_name": {
|
| 89 |
-
"type": "string",
|
| 90 |
-
"description": (
|
| 91 |
-
"Worksheet name or zero‑based index *as a string* (optional; default first sheet)."
|
| 92 |
-
),
|
| 93 |
-
"nullable": True,
|
| 94 |
-
},
|
| 95 |
-
}
|
| 96 |
-
|
| 97 |
-
output_type = "string"
|
| 98 |
-
|
| 99 |
-
def forward(
|
| 100 |
-
self,
|
| 101 |
-
excel_path: str,
|
| 102 |
-
sheet_name: Optional[str] = None,
|
| 103 |
-
) -> str:
|
| 104 |
-
"""Load *excel_path* and return the sheet as a Markdown table."""
|
| 105 |
-
|
| 106 |
-
path = Path(excel_path).expanduser().resolve()
|
| 107 |
-
if not path.exists():
|
| 108 |
-
return f"Error: Excel file not found at {path}"
|
| 109 |
-
|
| 110 |
-
try:
|
| 111 |
-
# Interpret sheet identifier
|
| 112 |
-
sheet: Union[str, int]
|
| 113 |
-
if sheet_name is None or sheet_name == "":
|
| 114 |
-
sheet = 0 # first sheet
|
| 115 |
-
else:
|
| 116 |
-
# If the user passed a numeric string (e.g. "1"), cast to int
|
| 117 |
-
sheet = int(sheet_name) if sheet_name.isdigit() else sheet_name
|
| 118 |
-
|
| 119 |
-
# Load worksheet
|
| 120 |
-
df = pd.read_excel(path, sheet_name=sheet)
|
| 121 |
-
|
| 122 |
-
# Render to Markdown, fallback to tabulate if needed
|
| 123 |
-
if hasattr(pd.DataFrame, "to_markdown"):
|
| 124 |
-
return df.to_markdown(index=False)
|
| 125 |
-
from tabulate import tabulate
|
| 126 |
-
|
| 127 |
-
return tabulate(df, headers="keys", tablefmt="github", showindex=False)
|
| 128 |
-
|
| 129 |
-
except Exception as exc: # broad catch keeps the agent chat‑friendly
|
| 130 |
-
return f"Error reading Excel file: {exc}"
|
| 131 |
-
|
| 132 |
-
|
| 133 |
# --- Basic Agent Definition ---
|
| 134 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 135 |
class BasicAgent:
|
| 136 |
def __init__(self):
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
| 147 |
|
| 148 |
-
#
|
| 149 |
-
# if not CREDENTIALS_CONFIGURED:
|
| 150 |
-
# raise ValueError("Google Cloud credentials could not be configured. Check startup logs and HF Secrets (ensure 'GOOGLE_APPLICATION_CREDENTIALS_JSON' is set correctly).")
|
| 151 |
|
| 152 |
-
#
|
| 153 |
-
os.environ["DEEPSEEK_API_KEY"] = deepseek_api_key
|
| 154 |
-
|
| 155 |
-
self.agent = CodeAgent(
|
| 156 |
-
model=LiteLLMModel(model_id="deepseek-chat"),
|
| 157 |
-
tools=[DuckDuckGoSearchTool(), WikipediaSearchTool(), ExcelToTextTool()],
|
| 158 |
-
add_base_tools=True,
|
| 159 |
-
additional_authorized_imports=['pandas','numpy','csv','subprocess']
|
| 160 |
-
)
|
| 161 |
print("BasicAgent initialized.")
|
| 162 |
-
|
| 163 |
def __call__(self, question: str) -> str:
|
| 164 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 165 |
fixed_answer = self.agent.run(question)
|
| 166 |
-
print(f"Agent returning answer: {fixed_answer}")
|
| 167 |
return fixed_answer
|
| 168 |
|
| 169 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
@@ -220,7 +97,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 220 |
results_log = []
|
| 221 |
answers_payload = []
|
| 222 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 223 |
-
for item in questions_data:
|
| 224 |
task_id = item.get("task_id")
|
| 225 |
question_text = item.get("question")
|
| 226 |
if not task_id or question_text is None:
|
|
@@ -233,6 +110,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 233 |
except Exception as e:
|
| 234 |
print(f"Error running agent on task {task_id}: {e}")
|
| 235 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
|
| 236 |
|
| 237 |
if not answers_payload:
|
| 238 |
print("Agent did not produce any answers to submit.")
|
|
@@ -340,4 +218,4 @@ if __name__ == "__main__":
|
|
| 340 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 341 |
|
| 342 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 343 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
import requests
|
| 4 |
+
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
from smolagents import (
|
| 8 |
+
ToolCallingAgent,
|
| 9 |
+
CodeAgent,
|
| 10 |
+
DuckDuckGoSearchTool,
|
| 11 |
+
InferenceClientModel,
|
| 12 |
+
HfApiModel,
|
| 13 |
+
OpenAIServerModel
|
| 14 |
+
)
|
| 15 |
|
| 16 |
# (Keep Constants as is)
|
| 17 |
# --- Constants ---
|
| 18 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
# --- Basic Agent Definition ---
|
| 21 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 22 |
class BasicAgent:
|
| 23 |
def __init__(self):
|
| 24 |
+
self.model = OpenAIServerModel(
|
| 25 |
+
model_id='deepseek-chat',
|
| 26 |
+
api_base="https://api.deepseek.com",
|
| 27 |
+
api_key=os.environ["DEEPSEEK_API_KEY"],
|
| 28 |
+
)
|
| 29 |
+
self.agent = ToolCallingAgent(
|
| 30 |
+
tools=[DuckDuckGoSearchTool()],
|
| 31 |
+
model=self.model,
|
| 32 |
+
add_base_tools=True
|
| 33 |
+
)
|
| 34 |
+
#self.agent.prompt_templates['system_prompt'] = """
|
| 35 |
|
| 36 |
+
#You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [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.
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
#"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
print("BasicAgent initialized.")
|
|
|
|
| 40 |
def __call__(self, question: str) -> str:
|
| 41 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 42 |
fixed_answer = self.agent.run(question)
|
| 43 |
+
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 44 |
return fixed_answer
|
| 45 |
|
| 46 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
|
|
| 97 |
results_log = []
|
| 98 |
answers_payload = []
|
| 99 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 100 |
+
for i, item in enumerate(questions_data):
|
| 101 |
task_id = item.get("task_id")
|
| 102 |
question_text = item.get("question")
|
| 103 |
if not task_id or question_text is None:
|
|
|
|
| 110 |
except Exception as e:
|
| 111 |
print(f"Error running agent on task {task_id}: {e}")
|
| 112 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 113 |
+
|
| 114 |
|
| 115 |
if not answers_payload:
|
| 116 |
print("Agent did not produce any answers to submit.")
|
|
|
|
| 218 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 219 |
|
| 220 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 221 |
+
demo.launch(debug=True, share=False)
|