Update app.py
Browse files
app.py
CHANGED
|
@@ -3,26 +3,24 @@ import litellm
|
|
| 3 |
import json
|
| 4 |
import asyncio
|
| 5 |
import os
|
| 6 |
-
from ddgs import DDGS
|
| 7 |
-
from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool, VisitWebpageTool, Tool,OpenAIServerModel, LiteLLMModel
|
| 8 |
-
from PIL import Image
|
| 9 |
-
from transformers import pipeline
|
| 10 |
import logging
|
|
|
|
| 11 |
|
|
|
|
| 12 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 13 |
|
| 14 |
litellm.drop_params = True
|
| 15 |
|
| 16 |
-
#
|
| 17 |
|
| 18 |
class TranscriptionTool(Tool):
|
| 19 |
name = "transcriber"
|
| 20 |
-
description = "Use this when you need to understand an audio file.
|
| 21 |
inputs = {"audio_path": {"type": "string", "description": "Local path to the audio file."}}
|
| 22 |
output_type = "string"
|
| 23 |
|
| 24 |
def forward(self, audio_path: str) -> str:
|
| 25 |
-
# We return a instruction to the agent
|
| 26 |
return f"I have accessed the audio at {audio_path}. Please analyze its content natively."
|
| 27 |
|
| 28 |
class VisionTool(Tool):
|
|
@@ -36,47 +34,21 @@ class VisionTool(Tool):
|
|
| 36 |
|
| 37 |
def forward(self, image_path: str, question: str) -> str:
|
| 38 |
return f"I have the image at {image_path}. Question: {question}. Please analyze this image natively."
|
| 39 |
-
|
| 40 |
-
# Agent Initialization
|
| 41 |
-
|
| 42 |
-
#model = InferenceClientModel(token=os.getenv("HF_TOKEN"))
|
| 43 |
-
#model = InferenceClientModel(
|
| 44 |
-
# model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 45 |
-
# token=os.getenv("HF_TOKEN")
|
| 46 |
-
#)
|
| 47 |
-
|
| 48 |
-
"""model = OpenAIServerModel(
|
| 49 |
-
model_id="gpt-4o", # This must match your 'Deployment Name' in Azure Studio
|
| 50 |
-
api_base=os.getenv("AZURE_OPENAI_ENDPOINT"),
|
| 51 |
-
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
|
| 52 |
-
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
|
| 53 |
-
)
|
| 54 |
|
|
|
|
| 55 |
|
| 56 |
-
model = LiteLLMModel(
|
| 57 |
-
model_id="gemini/gemini-2.5-flash",
|
| 58 |
-
api_key=os.getenv("GEMINI_API_KEY"),
|
| 59 |
-
max_tokens=1024,
|
| 60 |
-
timeout=60
|
| 61 |
-
)
|
| 62 |
-
"""
|
| 63 |
-
|
| 64 |
-
# --- CRITICAL AUTH CHECK ---
|
| 65 |
gemini_api_key = os.getenv("GEMINI_API_KEY")
|
| 66 |
hf_token = os.getenv("HF_TOKEN")
|
| 67 |
|
| 68 |
if not gemini_api_key:
|
| 69 |
-
|
| 70 |
-
raise ValueError("CRITICAL: GEMINI_API_KEY is not found in environment variables. "
|
| 71 |
-
"Check your Hugging Face Space Secrets.")
|
| 72 |
|
| 73 |
-
# --- REVISED MODEL CONFIG ---
|
| 74 |
model = LiteLLMModel(
|
| 75 |
-
model_id="gemini/gemini-1.5-flash",
|
| 76 |
api_key=gemini_api_key,
|
| 77 |
fallbacks=[
|
| 78 |
{
|
| 79 |
-
"model": "huggingface/Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 80 |
"api_key": hf_token
|
| 81 |
}
|
| 82 |
],
|
|
@@ -85,8 +57,7 @@ model = LiteLLMModel(
|
|
| 85 |
timeout=60
|
| 86 |
)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
# 3. Agent Setup
|
| 90 |
agent = CodeAgent(
|
| 91 |
tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), TranscriptionTool(), VisionTool()],
|
| 92 |
model=model,
|
|
@@ -95,29 +66,17 @@ agent = CodeAgent(
|
|
| 95 |
verbosity_level=2
|
| 96 |
)
|
| 97 |
|
| 98 |
-
|
| 99 |
-
#model = HfModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct",token=hf_token)
|
| 100 |
-
#model=InferenceClientModel()
|
| 101 |
-
agent = CodeAgent(
|
| 102 |
-
tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), TranscriptionTool(), VisionTool()],
|
| 103 |
-
model=model,
|
| 104 |
-
add_base_tools=True, # Essential for Excel (pandas) and Python file execution
|
| 105 |
-
max_steps=15,
|
| 106 |
-
verbosity_level=2
|
| 107 |
-
)
|
| 108 |
-
|
| 109 |
-
# The Processing Logic
|
| 110 |
|
| 111 |
async def run_gaia_tasks(json_input):
|
| 112 |
try:
|
| 113 |
tasks = json.loads(json_input)
|
| 114 |
-
except:
|
| 115 |
-
return "Invalid JSON input
|
| 116 |
|
| 117 |
results = []
|
| 118 |
|
| 119 |
for task in tasks:
|
| 120 |
-
# Construct the prompt with strict formatting rules
|
| 121 |
prompt = f"""
|
| 122 |
TASK: {task['question']}
|
| 123 |
FILE: {task.get('file_name', 'None')}
|
|
@@ -126,27 +85,27 @@ async def run_gaia_tasks(json_input):
|
|
| 126 |
1. If a file is mentioned, use Python to open/analyze it.
|
| 127 |
2. YOUR FINAL ANSWER MUST BE THE RAW VALUE ONLY.
|
| 128 |
3. No explanations, no units, no 'The answer is'.
|
| 129 |
-
Example: If the answer is 5, output '5'.
|
| 130 |
"""
|
| 131 |
|
| 132 |
try:
|
| 133 |
-
|
|
|
|
| 134 |
results.append({"task_id": task["task_id"], "answer": str(answer).strip()})
|
| 135 |
except Exception as e:
|
|
|
|
| 136 |
results.append({"task_id": task["task_id"], "answer": f"Error: {str(e)}"})
|
| 137 |
|
| 138 |
-
# Save to a file for download
|
| 139 |
output_file = "submission.json"
|
| 140 |
with open(output_file, "w") as f:
|
| 141 |
json.dump(results, f, indent=4)
|
| 142 |
|
| 143 |
return json.dumps(results, indent=4), output_file
|
| 144 |
|
| 145 |
-
# Gradio Interface
|
| 146 |
|
| 147 |
-
with gr.Blocks(title="Certification Agent") as
|
| 148 |
gr.Markdown("# 🤖 Agent Solver")
|
| 149 |
-
gr.Markdown("Paste your task JSON below. Ensure all referenced files
|
| 150 |
|
| 151 |
input_json = gr.Textbox(label="Input Tasks (JSON)", lines=10)
|
| 152 |
run_btn = gr.Button("Run Agent", variant="primary")
|
|
@@ -155,7 +114,15 @@ with gr.Blocks(title="Certification Agent") as agent:
|
|
| 155 |
output_text = gr.Code(label="Agent Results", language="json")
|
| 156 |
output_file = gr.File(label="Download submission.json")
|
| 157 |
|
| 158 |
-
run_btn.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
if __name__ == "__main__":
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import json
|
| 4 |
import asyncio
|
| 5 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import logging
|
| 7 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, Tool, LiteLLMModel
|
| 8 |
|
| 9 |
+
# Setup Logging
|
| 10 |
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
litellm.drop_params = True
|
| 14 |
|
| 15 |
+
# --- Custom Tools ---
|
| 16 |
|
| 17 |
class TranscriptionTool(Tool):
|
| 18 |
name = "transcriber"
|
| 19 |
+
description = "Use this when you need to understand an audio file."
|
| 20 |
inputs = {"audio_path": {"type": "string", "description": "Local path to the audio file."}}
|
| 21 |
output_type = "string"
|
| 22 |
|
| 23 |
def forward(self, audio_path: str) -> str:
|
|
|
|
| 24 |
return f"I have accessed the audio at {audio_path}. Please analyze its content natively."
|
| 25 |
|
| 26 |
class VisionTool(Tool):
|
|
|
|
| 34 |
|
| 35 |
def forward(self, image_path: str, question: str) -> str:
|
| 36 |
return f"I have the image at {image_path}. Question: {question}. Please analyze this image natively."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
# --- Agent Initialization ---
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
gemini_api_key = os.getenv("GEMINI_API_KEY")
|
| 41 |
hf_token = os.getenv("HF_TOKEN")
|
| 42 |
|
| 43 |
if not gemini_api_key:
|
| 44 |
+
raise ValueError("CRITICAL: GEMINI_API_KEY is not found in environment variables.")
|
|
|
|
|
|
|
| 45 |
|
|
|
|
| 46 |
model = LiteLLMModel(
|
| 47 |
+
model_id="gemini/gemini-1.5-flash",
|
| 48 |
api_key=gemini_api_key,
|
| 49 |
fallbacks=[
|
| 50 |
{
|
| 51 |
+
"model": "huggingface/Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 52 |
"api_key": hf_token
|
| 53 |
}
|
| 54 |
],
|
|
|
|
| 57 |
timeout=60
|
| 58 |
)
|
| 59 |
|
| 60 |
+
# Initialize Agent once
|
|
|
|
| 61 |
agent = CodeAgent(
|
| 62 |
tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), TranscriptionTool(), VisionTool()],
|
| 63 |
model=model,
|
|
|
|
| 66 |
verbosity_level=2
|
| 67 |
)
|
| 68 |
|
| 69 |
+
# --- Processing Logic ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
async def run_gaia_tasks(json_input):
|
| 72 |
try:
|
| 73 |
tasks = json.loads(json_input)
|
| 74 |
+
except Exception as e:
|
| 75 |
+
return f"Invalid JSON input: {str(e)}", None
|
| 76 |
|
| 77 |
results = []
|
| 78 |
|
| 79 |
for task in tasks:
|
|
|
|
| 80 |
prompt = f"""
|
| 81 |
TASK: {task['question']}
|
| 82 |
FILE: {task.get('file_name', 'None')}
|
|
|
|
| 85 |
1. If a file is mentioned, use Python to open/analyze it.
|
| 86 |
2. YOUR FINAL ANSWER MUST BE THE RAW VALUE ONLY.
|
| 87 |
3. No explanations, no units, no 'The answer is'.
|
|
|
|
| 88 |
"""
|
| 89 |
|
| 90 |
try:
|
| 91 |
+
# Run the synchronous agent.run in a separate thread to keep Gradio responsive
|
| 92 |
+
answer = await asyncio.to_thread(agent.run, prompt)
|
| 93 |
results.append({"task_id": task["task_id"], "answer": str(answer).strip()})
|
| 94 |
except Exception as e:
|
| 95 |
+
logger.error(f"Error processing task {task.get('task_id')}: {e}")
|
| 96 |
results.append({"task_id": task["task_id"], "answer": f"Error: {str(e)}"})
|
| 97 |
|
|
|
|
| 98 |
output_file = "submission.json"
|
| 99 |
with open(output_file, "w") as f:
|
| 100 |
json.dump(results, f, indent=4)
|
| 101 |
|
| 102 |
return json.dumps(results, indent=4), output_file
|
| 103 |
|
| 104 |
+
# --- Gradio Interface ---
|
| 105 |
|
| 106 |
+
with gr.Blocks(title="Certification Agent") as demo:
|
| 107 |
gr.Markdown("# 🤖 Agent Solver")
|
| 108 |
+
gr.Markdown("Paste your task JSON below. Ensure all referenced files are uploaded to the Space.")
|
| 109 |
|
| 110 |
input_json = gr.Textbox(label="Input Tasks (JSON)", lines=10)
|
| 111 |
run_btn = gr.Button("Run Agent", variant="primary")
|
|
|
|
| 114 |
output_text = gr.Code(label="Agent Results", language="json")
|
| 115 |
output_file = gr.File(label="Download submission.json")
|
| 116 |
|
| 117 |
+
run_btn.click(
|
| 118 |
+
fn=run_gaia_tasks,
|
| 119 |
+
inputs=input_json,
|
| 120 |
+
outputs=[output_text, output_file]
|
| 121 |
+
)
|
| 122 |
|
| 123 |
if __name__ == "__main__":
|
| 124 |
+
demo.launch(
|
| 125 |
+
server_name="0.0.0.0",
|
| 126 |
+
server_port=7860,
|
| 127 |
+
ssr_mode=False # Disabling SSR prevents the 'Invalid file descriptor' error
|
| 128 |
+
)
|