rasao's picture
Update app.py
56c9337 verified
Raw History Blame Contribute Delete
3.56 kB
import gradio as gr
import litellm
import json
import os
import logging
from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, Tool, LiteLLMModel
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
litellm.set_verbose = True
litellm.drop_params = True
def get_clean_secret(key_name):
val = os.getenv(key_name, "")
if not val:
return ""
cleaned = val.strip().replace('"', '').replace("'", "").replace("export ", "")
return cleaned
gemini_api_key = get_clean_secret("GEMINI_API_KEY")
hf_token = get_clean_secret("HF_TOKEN")
if gemini_api_key:
logger.info(f"GEMINI_API_KEY loaded. Length: {len(gemini_api_key)} chars.")
else:
logger.error("GEMINI_API_KEY IS COMPLETELY EMPTY!")
# --- Custom Tools ---
class TranscriptionTool(Tool):
name = "transcriber"
description = "Use this to understand audio files."
inputs = {"audio_path": {"type": "string", "description": "Local path to the audio file."}}
output_type = "string"
def forward(self, audio_path: str) -> str:
return f"Audio accessed at {audio_path}. Analyze content natively."
class VisionTool(Tool):
name = "image_analyzer"
description = "Use this for analyzing images or visual data."
inputs = {
"image_path": {"type": "string", "description": "Local path to the image."},
"question": {"type": "string", "description": "Specific question about the image."}
}
output_type = "string"
def forward(self, image_path: str, question: str) -> str:
return f"Image accessed at {image_path}. Analyze natively."
# --- Model Configuration ---
# Force Gemini provider string
model = LiteLLMModel(
model_id="gemini/gemini-2.5-flash-lite",
api_key=gemini_api_key,
max_retries=1, # Reduced to stop the infinite fallback/loop error
timeout=60
)
agent = CodeAgent(
tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), TranscriptionTool(), VisionTool()],
model=model,
add_base_tools=True,
max_steps=12
)
# --- Logic ---
def run_solver(json_input):
if not gemini_api_key:
return "CRITICAL: GEMINI_API_KEY is not set in Space Secrets.", None
try:
tasks = json.loads(json_input)
except Exception as e:
return f"JSON Error: {str(e)}", None
results = []
for task in tasks:
prompt = f"TASK: {task['question']}\nFILE: {task.get('file_name', 'None')}\nFinal answer must be RAW VALUE only."
try:
# We call this directly; Gradio's thread will manage the blocking call.
answer = agent.run(prompt)
results.append({"task_id": task["task_id"], "answer": str(answer).strip()})
except Exception as e:
logger.error(f"Failed task: {e}")
results.append({"task_id": task["task_id"], "answer": f"Execution Error: {str(e)}"})
output_path = "submission.json"
with open(output_path, "w") as f:
json.dump(results, f, indent=4)
return json.dumps(results, indent=4), output_path
# --- UI ---
with gr.Blocks() as demo:
gr.Markdown("# 🤖 Agent Certification")
input_box = gr.Textbox(label="Task JSON", lines=10)
run_btn = gr.Button("Execute", variant="primary")
with gr.Row():
out_json = gr.Code(label="Response", language="json")
out_file = gr.File(label="Download")
run_btn.click(fn=run_solver, inputs=input_box, outputs=[out_json, out_file])
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)