ZekeeSenju commited on
Commit
f11ce14
·
verified ·
1 Parent(s): 28c2038

changed to fix multiline error

Browse files
Files changed (1) hide show
  1. zekee_agent.py +38 -26
zekee_agent.py CHANGED
@@ -8,20 +8,25 @@ import wikipedia as wiki
8
  from markdownify import markdownify as to_markdown
9
  from functools import lru_cache
10
 
 
 
 
 
 
 
11
 
12
-
13
- # --- Tools to use---
14
 
15
  class VideoWatchingTool(Tool):
16
  name = "watch_video"
17
  description = "Watch a video and answer a question about its content."
18
  inputs = {
19
  "video_url": {"type": "string", "description": "URL of the video."},
20
- "user_query": {"type": "string", "description": "What to answer about the video."}
21
  }
22
  output_type = "string"
23
 
24
- def __init__(self, model_name, **kwargs):
25
  super().__init__(**kwargs)
26
  self.model_name = model_name
27
 
@@ -35,11 +40,14 @@ class VideoWatchingTool(Tool):
35
  }
36
  api_url = (
37
  f"https://generativelanguage.googleapis.com/v1beta/models/"
38
- f"{self.model_name}:generateContent?key='AIzaSyDz6V86ekxxKPYZiX1UaqMfmZb8fNMjuJk'"
39
  )
40
- r = requests.post(api_url, json=payload, timeout=30)
41
- r.raise_for_status()
42
- parts = r.json()["candidates"][0]["content"]["parts"]
 
 
 
43
  return "".join(p.get("text", "") for p in parts).strip()
44
 
45
  class GoogleSearchTool(Tool):
@@ -48,13 +56,12 @@ class GoogleSearchTool(Tool):
48
  inputs = {"query": {"type": "string", "description": "Search query."}}
49
  output_type = "string"
50
 
51
- def __init__(self, client, model_name, **kwargs):
52
  super().__init__(**kwargs)
53
  self.client = client
54
  self.model_name = model_name
55
 
56
  def forward(self, query: str) -> str:
57
- # Use genai.Tool for structured search
58
  tool = types.Tool(google_search=types.GoogleSearch())
59
  resp = self.client.models.generate_content(
60
  model=self.model_name,
@@ -72,7 +79,7 @@ class WikipediaTitleSearchTool(Tool):
72
  inputs = {"query": {"type": "string", "description": "Search term."}}
73
  output_type = "string"
74
 
75
- @lru_cache(maxsize=128)
76
  def forward(self, query: str) -> str:
77
  results = wiki.search(query)
78
  return ", ".join(results) if results else "No results found."
@@ -83,7 +90,7 @@ class WikipediaPageTool(Tool):
83
  inputs = {"page_title": {"type": "string", "description": "Exact page title."}}
84
  output_type = "string"
85
 
86
- @lru_cache(maxsize=64)
87
  def forward(self, page_title: str) -> str:
88
  try:
89
  page = wiki.page(page_title)
@@ -95,23 +102,27 @@ class FileAttachmentQueryTool(Tool):
95
  name = "run_query_with_file"
96
  description = "Download an attached file and answer a question about it."
97
  inputs = {
98
- "task_id": {"type": "string", "description": "ID to download the file."},
99
- "mime_type": {"type": "string", "nullable": True, "description": "Optional MIME type."},
100
  "user_query": {"type": "string", "description": "Question about the file."}
101
  }
102
  output_type = "string"
103
 
104
- def __init__(self, client, model_name, **kwargs):
105
  super().__init__(**kwargs)
106
  self.client = client
107
  self.model_name = model_name
108
 
109
  def forward(self, task_id: str, mime_type: Optional[str], user_query: str) -> str:
110
  url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
111
- resp = requests.get(url, timeout=15)
112
- resp.raise_for_status()
 
 
 
113
  data = resp.content
114
  mime = mime_type or resp.headers.get("Content-Type", "application/octet-stream")
 
115
  response = self.client.models.generate_content(
116
  model=self.model_name,
117
  contents=[
@@ -121,7 +132,7 @@ class FileAttachmentQueryTool(Tool):
121
  )
122
  return response.text.strip()
123
 
124
- # --- Agent---
125
 
126
  class Agent:
127
  """
@@ -131,11 +142,11 @@ class Agent:
131
  MODEL_NAME = "gemini-2.0-flash"
132
 
133
  def __init__(self, api_key: Optional[str] = None):
134
- api_key = api_key or "AIzaSyDz6V86ekxxKPYZiX1UaqMfmZb8fNMjuJk"
135
  self.model = LiteLLMModel(model_id=f"gemini/{self.MODEL_NAME}", api_key=api_key)
136
  self.client = genai.Client(api_key=api_key)
137
 
138
- # This prompt tells the agent to think internally but only output the exact final answer:
139
  self.system_prompt = (
140
  "You are a GAIA Level-1 evaluation assistant. For each question:\n"
141
  "1) You may think step-by-step internally, but do NOT output your reasoning.\n"
@@ -147,6 +158,7 @@ class Agent:
147
  "4) Do NOT include any extra text, punctuation, or 'Final Answer' tokens."
148
  )
149
 
 
150
  self.agent = ToolCallingAgent(
151
  model=self.model,
152
  tools=[
@@ -156,19 +168,19 @@ class Agent:
156
  WikipediaPageTool(),
157
  FileAttachmentQueryTool(client=self.client, model_name=self.MODEL_NAME),
158
  ],
159
- system_prompt=self.system_prompt,
160
  max_steps=10,
161
  planning_interval=2,
162
  return_intermediate_steps=False,
163
  )
164
 
165
  def __call__(self, question: str) -> str:
166
- # Prepend system prompt and delegate to the tool-calling agent
167
- return self.agent.run(question).strip()
 
168
 
169
 
170
- # Quick test
171
  if __name__ == "__main__":
172
  agent = Agent()
173
- q = "What year was the first iPhone released and was it before or after ipod?"
174
- print(agent(q))
 
8
  from markdownify import markdownify as to_markdown
9
  from functools import lru_cache
10
 
11
+ # ----------------------------------------------------------------
12
+ # Make sure your GOOGLE_API_KEY is set in your Space’s secrets.
13
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
14
+ if not GOOGLE_API_KEY:
15
+ raise RuntimeError("Please set the GOOGLE_API_KEY environment variable.")
16
+ # ----------------------------------------------------------------
17
 
18
+ # --- Tools to use ---
 
19
 
20
  class VideoWatchingTool(Tool):
21
  name = "watch_video"
22
  description = "Watch a video and answer a question about its content."
23
  inputs = {
24
  "video_url": {"type": "string", "description": "URL of the video."},
25
+ "user_query": {"type": "string", "description": "Question about the video."}
26
  }
27
  output_type = "string"
28
 
29
+ def __init__(self, model_name: str, **kwargs):
30
  super().__init__(**kwargs)
31
  self.model_name = model_name
32
 
 
40
  }
41
  api_url = (
42
  f"https://generativelanguage.googleapis.com/v1beta/models/"
43
+ f"{self.model_name}:generateContent?key={GOOGLE_API_KEY}"
44
  )
45
+ try:
46
+ r = requests.post(api_url, json=payload, timeout=30)
47
+ r.raise_for_status()
48
+ except requests.RequestException as e:
49
+ return f"[VideoTool error] {e}"
50
+ parts = r.json().get("candidates", [{}])[0].get("content", {}).get("parts", [])
51
  return "".join(p.get("text", "") for p in parts).strip()
52
 
53
  class GoogleSearchTool(Tool):
 
56
  inputs = {"query": {"type": "string", "description": "Search query."}}
57
  output_type = "string"
58
 
59
+ def __init__(self, client: genai.Client, model_name: str, **kwargs):
60
  super().__init__(**kwargs)
61
  self.client = client
62
  self.model_name = model_name
63
 
64
  def forward(self, query: str) -> str:
 
65
  tool = types.Tool(google_search=types.GoogleSearch())
66
  resp = self.client.models.generate_content(
67
  model=self.model_name,
 
79
  inputs = {"query": {"type": "string", "description": "Search term."}}
80
  output_type = "string"
81
 
82
+ @lru_cache(maxsize=256)
83
  def forward(self, query: str) -> str:
84
  results = wiki.search(query)
85
  return ", ".join(results) if results else "No results found."
 
90
  inputs = {"page_title": {"type": "string", "description": "Exact page title."}}
91
  output_type = "string"
92
 
93
+ @lru_cache(maxsize=128)
94
  def forward(self, page_title: str) -> str:
95
  try:
96
  page = wiki.page(page_title)
 
102
  name = "run_query_with_file"
103
  description = "Download an attached file and answer a question about it."
104
  inputs = {
105
+ "task_id": {"type": "string", "description": "ID to download the file."},
106
+ "mime_type": {"type": "string", "nullable": True, "description": "Optional MIME type."},
107
  "user_query": {"type": "string", "description": "Question about the file."}
108
  }
109
  output_type = "string"
110
 
111
+ def __init__(self, client: genai.Client, model_name: str, **kwargs):
112
  super().__init__(**kwargs)
113
  self.client = client
114
  self.model_name = model_name
115
 
116
  def forward(self, task_id: str, mime_type: Optional[str], user_query: str) -> str:
117
  url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
118
+ try:
119
+ resp = requests.get(url, timeout=15)
120
+ resp.raise_for_status()
121
+ except requests.RequestException as e:
122
+ return f"[FileTool error] {e}"
123
  data = resp.content
124
  mime = mime_type or resp.headers.get("Content-Type", "application/octet-stream")
125
+
126
  response = self.client.models.generate_content(
127
  model=self.model_name,
128
  contents=[
 
132
  )
133
  return response.text.strip()
134
 
135
+ # --- Agent Container ---
136
 
137
  class Agent:
138
  """
 
142
  MODEL_NAME = "gemini-2.0-flash"
143
 
144
  def __init__(self, api_key: Optional[str] = None):
145
+ api_key = api_key or GOOGLE_API_KEY
146
  self.model = LiteLLMModel(model_id=f"gemini/{self.MODEL_NAME}", api_key=api_key)
147
  self.client = genai.Client(api_key=api_key)
148
 
149
+ # Our instructions: agent “thinks” internally, but outputs ONLY the final answer.
150
  self.system_prompt = (
151
  "You are a GAIA Level-1 evaluation assistant. For each question:\n"
152
  "1) You may think step-by-step internally, but do NOT output your reasoning.\n"
 
158
  "4) Do NOT include any extra text, punctuation, or 'Final Answer' tokens."
159
  )
160
 
161
+ # NOTE: `ToolCallingAgent` no longer accepts `system_prompt=` here.
162
  self.agent = ToolCallingAgent(
163
  model=self.model,
164
  tools=[
 
168
  WikipediaPageTool(),
169
  FileAttachmentQueryTool(client=self.client, model_name=self.MODEL_NAME),
170
  ],
 
171
  max_steps=10,
172
  planning_interval=2,
173
  return_intermediate_steps=False,
174
  )
175
 
176
  def __call__(self, question: str) -> str:
177
+ # Prepend our system prompt at runtime
178
+ prompt = f"{self.system_prompt}\n{question}"
179
+ return self.agent.run(prompt).strip()
180
 
181
 
182
+ # Quick sanity test
183
  if __name__ == "__main__":
184
  agent = Agent()
185
+ q = "What year was the first iPhone released and was it before or after iPod?"
186
+ print(agent(q)) # should print e.g. "2007, after"