CourseFinalHandOn / app_1.py
anup220799's picture
final commit
a0960b4
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel
import json
import requests
import ast
agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=InferenceClientModel())
questions = requests.get("https://agents-course-unit4-scoring.hf.space/questions").json()
answers = []
for q in questions:
question_text = q.get("question")
task_id = q.get("task_id")
response = agent.run(f"{question_text} Return JSON {{'answer': ''}}", max_steps=2)
# Normalize response
if isinstance(response, dict):
answer = response.get("answer")
elif isinstance(response, (int, float)):
answer = response
elif isinstance(response, str):
try:
json_start = response.find("{")
json_text = response[json_start:] if json_start != -1 else response
parsed = json.loads(json_text)
answer = parsed.get("answer", parsed) if isinstance(parsed, dict) else parsed
except json.JSONDecodeError:
answer = response.strip()
else:
answer = response
answers.append({
"task_id": task_id,
"answer": answer
})
print(answers)
answers_payload = [
{
"task_id": r["task_id"],
"submitted_answer": str(r["answer"])
}
for r in answers
]
payload = {
"username": "Monika Vivek Raj",
"agent_code": "new_agent_monika",
"answers": answers_payload
}
api_url = "https://agents-course-unit4-scoring.hf.space/submit"
response = requests.post(api_url, json=payload)
# Check response
if response.status_code == 200:
print("Results submitted successfully!")
print(response.json())
else:
print("Failed to submit results:", response.status_code, response.text)