File size: 13,504 Bytes
45b200f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "Preparations",
   "id": "85e57249794e16a7"
  },
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-06-08T16:21:51.896485Z",
     "start_time": "2025-06-08T16:21:51.893462Z"
    }
   },
   "source": [
    "from globals import *\n",
    "DEFAULT_API_URL = \"https://agents-course-unit4-scoring.hf.space\"\n",
    "api_url = DEFAULT_API_URL\n",
    "questions_url = f\"{api_url}/questions\"\n",
    "submit_url = f\"{api_url}/submit\"\n",
    "file_url = f\"{api_url}/files\""
   ],
   "outputs": [],
   "execution_count": 32
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-07T14:46:28.498789Z",
     "start_time": "2025-06-07T14:46:27.794622Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# get questions\n",
    "response = requests.get(questions_url, timeout=15)\n",
    "response.raise_for_status()\n",
    "questions_data = response.json()"
   ],
   "id": "2fc7ef4f0959246b",
   "outputs": [],
   "execution_count": 28
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-08T16:49:29.230136Z",
     "start_time": "2025-06-08T16:49:29.227812Z"
    }
   },
   "cell_type": "code",
   "source": [
    "for item_num, item in enumerate(questions_data):\n",
    "    # dict_keys(['task_id', 'question', 'Level', 'file_name'])\n",
    "    # print(item['question'])\n",
    "    # print('---')\n",
    "    # print(f\"{item['task_id']}\")\n",
    "    print(f\"Task {item_num} has file: {item['file_name']}\")\n",
    "    # print(f\"The question: \\n {item['question']} \\n\")"
   ],
   "id": "8a00fe57d4ec29bb",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Task 0 has file: \n",
      "Task 1 has file: \n",
      "Task 2 has file: \n",
      "Task 3 has file: cca530fc-4052-43b2-b130-b30968d8aa44.png\n",
      "Task 4 has file: \n",
      "Task 5 has file: \n",
      "Task 6 has file: \n",
      "Task 7 has file: \n",
      "Task 8 has file: \n",
      "Task 9 has file: 99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3\n",
      "Task 10 has file: \n",
      "Task 11 has file: f918266a-b3e0-4914-865d-4faa564f1aef.py\n",
      "Task 12 has file: \n",
      "Task 13 has file: 1f975693-876d-457b-a649-393859e79bf3.mp3\n",
      "Task 14 has file: \n",
      "Task 15 has file: \n",
      "Task 16 has file: \n",
      "Task 17 has file: \n",
      "Task 18 has file: 7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx\n",
      "Task 19 has file: \n"
     ]
    }
   ],
   "execution_count": 38
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-04T18:23:01.054690Z",
     "start_time": "2025-06-04T18:22:59.280217Z"
    }
   },
   "cell_type": "code",
   "source": [
    "train_dataset = load_dataset(\"gaia-benchmark/GAIA\", '2023_level1', split=\"validation\")\n",
    "len(train_dataset)"
   ],
   "id": "d6216c8b17766ad8",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "53"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-04T18:24:32.847570Z",
     "start_time": "2025-06-04T18:24:32.844925Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(train_dataset[0].keys())\n",
    "item_0 = train_dataset[0]\n",
    "# for item in train_dataset:\n",
    "#     print(item)"
   ],
   "id": "ace71ed85c088f6e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['task_id', 'Question', 'Level', 'Final answer', 'file_name', 'file_path', 'Annotator Metadata'])\n"
     ]
    }
   ],
   "execution_count": 25
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "Simplest approach - just ask LLM",
   "id": "81dbae05a73009a4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-06T17:02:03.029164Z",
     "start_time": "2025-06-06T17:02:02.986724Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from globals import *\n",
    "from tools import *\n",
    "\n",
    "# ------------------------------------------------------ #\n",
    "# MODELS & TOOLS\n",
    "# ------------------------------------------------------ #\n",
    "chat_llm = ChatTogether(model=\"meta-llama/Llama-3.3-70B-Instruct-Turbo-Free\", api_key=os.getenv(\"TOGETHER_API_KEY\"))\n",
    "\n",
    "# ------------------------------------------------------ #\n",
    "# STATE\n",
    "# ------------------------------------------------------ #\n",
    "class AgentState(TypedDict):\n",
    "    # messages: list[AnyMessage, add_messages]\n",
    "    messages: list[AnyMessage]\n",
    "    # final_output_is_good: bool\n",
    "\n",
    "# ------------------------------------------------------ #\n",
    "# HELP FUNCTIONS\n",
    "# ------------------------------------------------------ #\n",
    "def step_print(state: AgentState, step_label: str):\n",
    "    print(f'<<--- [{len(state[\"messages\"])}] Starting {step_label}... --->>')\n",
    "\n",
    "def messages_print(messages_to_print: List[AnyMessage]):\n",
    "    print('--- Message/s ---')\n",
    "    for m in messages_to_print:\n",
    "        print(f'{m.type} ({m.name}): \\n{m.content}')\n",
    "    print(f'<<--- *** --->>')\n",
    "\n",
    "# ------------------------------------------------------ #\n",
    "# NODES\n",
    "# ------------------------------------------------------ #\n",
    "def preprocessing(state: AgentState):\n",
    "    step_print(state, 'Preprocessing')\n",
    "    messages_print(state['messages'][-1:])\n",
    "    return {\n",
    "        \"messages\": [SystemMessage(content=DEFAULT_SYSTEM_PROMPT)] + state[\"messages\"]\n",
    "    }\n",
    "\n",
    "\n",
    "def assistant(state: AgentState):\n",
    "    # state[\"messages\"] = [SystemMessage(content=DEFAULT_SYSTEM_PROMPT)] + state[\"messages\"]\n",
    "    step_print(state, 'assistant')\n",
    "    ai_message = chat_llm.invoke(state[\"messages\"])\n",
    "    messages_print([ai_message])\n",
    "    return {\n",
    "        'messages': state[\"messages\"] + [ai_message]\n",
    "    }\n",
    "\n",
    "\n",
    "base_tool_node = ToolNode(tools)\n",
    "def wrapped_tool_node(state: AgentState):\n",
    "    step_print(state, 'Tools')\n",
    "    # Call the original ToolNode\n",
    "    result = base_tool_node.invoke(state)\n",
    "    messages_print(result[\"messages\"])\n",
    "    # Append to the messages list instead of replacing it\n",
    "    state[\"messages\"] += result[\"messages\"]\n",
    "    return {\"messages\": state[\"messages\"]}\n",
    "\n",
    "\n",
    "# ------------------------------------------------------ #\n",
    "# CONDITIONAL FUNCTIONS\n",
    "# ------------------------------------------------------ #\n",
    "def condition_tools_or_continue(\n",
    "    state: Union[list[AnyMessage], dict[str, Any], BaseModel],\n",
    "    messages_key: str = \"messages\",\n",
    ") -> Literal[\"tools\", \"__end__\"]:\n",
    "\n",
    "    if isinstance(state, list):\n",
    "        ai_message = state[-1]\n",
    "    elif isinstance(state, dict) and (messages := state.get(messages_key, [])):\n",
    "        ai_message = messages[-1]\n",
    "    elif messages := getattr(state, messages_key, []):\n",
    "        ai_message = messages[-1]\n",
    "    else:\n",
    "        raise ValueError(f\"No messages found in input state to tool_edge: {state}\")\n",
    "    if hasattr(ai_message, \"tool_calls\") and len(ai_message.tool_calls) > 0:\n",
    "        return \"tools\"\n",
    "    # return \"checker_final_answer\"\n",
    "    return \"__end__\"\n",
    "\n",
    "\n",
    "# ------------------------------------------------------ #\n",
    "# BUILDERS\n",
    "# ------------------------------------------------------ #\n",
    "def workflow_simple() -> Tuple[StateGraph, str]:\n",
    "    i_builder = StateGraph(AgentState)\n",
    "    # Nodes\n",
    "    i_builder.add_node('preprocessing', preprocessing)\n",
    "    i_builder.add_node('assistant', assistant)\n",
    "\n",
    "    # Edges\n",
    "    i_builder.add_edge(START, 'preprocessing')\n",
    "    i_builder.add_edge('preprocessing', 'assistant')\n",
    "    return i_builder, 'workflow_simple'\n",
    "\n",
    "\n",
    "# ------------------------------------------------------ #\n",
    "# COMPILATION\n",
    "# ------------------------------------------------------ #\n",
    "builder, builder_name = workflow_simple()\n",
    "alfred = builder.compile()"
   ],
   "id": "9dda3c180ddb1cf6",
   "outputs": [],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-06T17:02:14.364108Z",
     "start_time": "2025-06-06T17:02:04.962236Z"
    }
   },
   "cell_type": "code",
   "source": "response = alfred.invoke({'messages': [HumanMessage(content=\"If Eliud Kipchoge could maintain his record-making marathon pace indefinitely, how many thousand hours would it take him to run the distance between the Earth and the Moon its closest approach? Please use the minimum perigee value on the Wikipedia page for the Moon when carrying out your calculation. Round your result to the nearest 1000 hours and do not use any comma separators if necessary.\")]})",
   "id": "817c59e55d4ccd37",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<<--- [1] Starting Preprocessing... --->>\n",
      "--- Message/s ---\n",
      "human (None): \n",
      "If Eliud Kipchoge could maintain his record-making marathon pace indefinitely, how many thousand hours would it take him to run the distance between the Earth and the Moon its closest approach? Please use the minimum perigee value on the Wikipedia page for the Moon when carrying out your calculation. Round your result to the nearest 1000 hours and do not use any comma separators if necessary.\n",
      "<<--- *** --->>\n",
      "<<--- [2] Starting assistant... --->>\n",
      "--- Message/s ---\n",
      "ai (None): \n",
      "To calculate the time it would take Eliud Kipchoge to run from the Earth to the Moon at its closest approach, we first need to find out the distance between the Earth and the Moon at its closest approach and Eliud Kipchoge's speed.\n",
      "\n",
      "The minimum perigee value for the Moon, according to Wikipedia, is approximately 356400 kilometers.\n",
      "\n",
      "Eliud Kipchoge's record-making marathon pace is 2:01:39 hours for 42.195 kilometers. To find his speed in kilometers per hour, we divide the distance by the time. \n",
      "\n",
      "First, convert 2:01:39 hours to just hours: 2 + (1/60) + (39/3600) = 2 + 0.0167 + 0.0108 = 2.0275 hours.\n",
      "\n",
      "Now, calculate his speed: 42.195 km / 2.0275 hours = 20.818 km/h.\n",
      "\n",
      "Now, calculate the time it would take to run 356400 km at this speed: 356400 km / 20.818 km/h = 17127 hours.\n",
      "\n",
      "To convert this to thousand hours, divide by 1000: 17127 / 1000 = 17.127.\n",
      "\n",
      "Rounded to the nearest 1000 hours, this is 17 thousand hours, but since the answer should not use comma separators or units, and should be rounded to the nearest 1000, we get 17000.\n",
      "\n",
      "FINAL ANSWER: 17000\n",
      "<<--- *** --->>\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-06T16:58:44.774532Z",
     "start_time": "2025-06-06T16:58:42.601012Z"
    }
   },
   "cell_type": "code",
   "source": "response1 = chat_llm.invoke([SystemMessage(content=DEFAULT_SYSTEM_PROMPT), HumanMessage(content=\"If Eliud Kipchoge could maintain his record-making marathon pace indefinitely, how many thousand hours would it take him to run the distance between the Earth and the Moon its closest approach? Please use the minimum perigee value on the Wikipedia page for the Moon when carrying out your calculation. Round your result to the nearest 1000 hours and do not use any comma separators if necessary.\")])",
   "id": "ef5b5fafeaff660b",
   "outputs": [],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-06T16:59:57.792887Z",
     "start_time": "2025-06-06T16:59:55.855377Z"
    }
   },
   "cell_type": "code",
   "source": "response2 = chat_llm.invoke([SystemMessage(content=DEFAULT_SYSTEM_PROMPT), HumanMessage(content=\"If Eliud Kipchoge could maintain his record-making marathon pace indefinitely, how many thousand hours would it take him to run the distance between the Earth and the Moon its closest approach? Please use the minimum perigee value on the Wikipedia page for the Moon when carrying out your calculation. Round your result to the nearest 1000 hours and do not use any comma separators if necessary.\"), response1])",
   "id": "7462e130d047c1be",
   "outputs": [],
   "execution_count": 8
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}