GoReed commited on
Commit
020caac
·
verified ·
1 Parent(s): db622b0

Create agent.py

Browse files
Files changed (1) hide show
  1. agent.py +138 -0
agent.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # agent.py
2
+
3
+ import os
4
+ import json
5
+ import pandas as pd
6
+ from smolagents import (
7
+ CodeAgent,
8
+ LiteLLMModel,
9
+ DuckDuckGoSearchTool,
10
+ FinalAnswerTool,
11
+ VisitWebpageTool,
12
+ WikipediaSearchTool,
13
+ WebSearchTool,
14
+ tool,
15
+ OpenAIServerModel
16
+ )
17
+ from langchain_community.document_loaders import ArxivLoader
18
+ from dotenv import load_dotenv
19
+ import requests
20
+ import yaml
21
+
22
+ load_dotenv()
23
+
24
+ # Custom tools
25
+ @tool
26
+ def arxiv_search(query: str) -> str:
27
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
28
+ return "\n\n---\n\n".join([
29
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
30
+ for doc in search_docs
31
+ ])
32
+
33
+ @tool
34
+ def extract_text_from_image(image_path: str) -> str:
35
+ try:
36
+ import pytesseract
37
+ from PIL import Image
38
+ image = Image.open(image_path)
39
+ text = pytesseract.image_to_string(image)
40
+ return f"Extracted text from image:\n\n{text}"
41
+ except ImportError:
42
+ return "Error: pytesseract is not installed."
43
+ except Exception as e:
44
+ return f"Error extracting text: {str(e)}"
45
+
46
+ # Model and agent setup
47
+ API_KEY = os.getenv("OPENAI_API_KEY_AG")
48
+ MODEL_ID = "openai/gpt-4.1-nano"
49
+
50
+ model = OpenAIServerModel(model_id="gpt-4.1-nano", api_key=API_KEY)
51
+
52
+ agent = CodeAgent(
53
+ model=model,
54
+ tools=[
55
+ WebSearchTool(),
56
+ VisitWebpageTool(),
57
+ WikipediaSearchTool(),
58
+ arxiv_search,
59
+ FinalAnswerTool(),
60
+ extract_text_from_image
61
+ ],
62
+ planning_interval=3,
63
+ max_steps=10,
64
+ verbosity_level=-1,
65
+ additional_authorized_imports=[
66
+ "pandas", "numpy", "requests", "os", "math", "sympy", "scipy",
67
+ "markdownify", "unicodedata", "stat", "datetime", "random", "itertools",
68
+ "statistics", "queue", "time", "collections", "re"
69
+ ],
70
+ add_base_tools=True
71
+ )
72
+
73
+ def fetch_questions():
74
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
75
+ try:
76
+ response = requests.get(f"{DEFAULT_API_URL}/questions")
77
+ response.raise_for_status()
78
+ data = response.json()
79
+ return data
80
+ except Exception as e:
81
+ print(f"Error fetching questions: {e}")
82
+ return []
83
+
84
+ def fetch_file(task_id: str, file_name: str):
85
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
86
+ try:
87
+ response = requests.get(f"{DEFAULT_API_URL}/files/{task_id}")
88
+ response.raise_for_status()
89
+ os.makedirs("data/question_files", exist_ok=True)
90
+ path = f"data/question_files/{file_name}"
91
+ with open(path, "wb") as f:
92
+ f.write(response.content)
93
+ return path
94
+ except Exception as e:
95
+ print(f"Error fetching file: {e}")
96
+ return None
97
+
98
+ def run_agent_on_question(q):
99
+ if q.get("file_name"):
100
+ file_path = fetch_file(q["task_id"], q["file_name"])
101
+ prompt = f"""You are a general AI assistant. Use tools and web search as needed.
102
+ Question: {q['question']}
103
+ file_path: {file_path}
104
+ YOUR FINAL ANSWER should be a number OR few words OR comma-separated values. Follow instructions strictly."""
105
+ else:
106
+ prompt = f"""You are a general AI assistant. Use tools and web search as needed.
107
+ Question: {q['question']}
108
+ YOUR FINAL ANSWER should be a number OR few words OR comma-separated values. Follow instructions strictly."""
109
+
110
+ output = agent.run(prompt)
111
+
112
+ # Optional: Extract final answer if embedded in logs
113
+ if isinstance(output, str):
114
+ return output.strip()
115
+ elif isinstance(output, dict):
116
+ return output.get("final_answer", str(output))
117
+ else:
118
+ return str(output)
119
+
120
+ def submit_answers(answers):
121
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
122
+ request_payload = {
123
+ "username": "GoReed",
124
+ "agent_code": "test",
125
+ "answers": answers
126
+ }
127
+ try:
128
+ response = requests.post(
129
+ f"{DEFAULT_API_URL}/submit",
130
+ json=request_payload # ✅ FIXED
131
+ )
132
+ response.raise_for_status()
133
+ print("✅ Submission success:", response.json())
134
+ except requests.exceptions.HTTPError as http_err:
135
+ print(f"❌ HTTP Error: {http_err}")
136
+ print("Response text:", response.text)
137
+ except Exception as e:
138
+ print(f"❌ Submission Error: {e}")