KaiserShultz commited on
Commit
bc8cde1
·
1 Parent(s): 3e43a4b

Initial commit for Spaces

Browse files
Files changed (3) hide show
  1. src/config.py +2 -0
  2. src/main.py +338 -0
  3. src/workflow_test.ipynb +18 -18
src/config.py CHANGED
@@ -5,6 +5,8 @@ from langgraph.prebuilt import ToolNode
5
  from schemas import PlannerPlan
6
  from utils.utils import log_stage
7
  from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessage
 
 
8
 
9
  config = {"configurable": {"thread_id": "1"}, "recursion_limit" : 50}
10
 
 
5
  from schemas import PlannerPlan
6
  from utils.utils import log_stage
7
  from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessage
8
+ from dotenv import load_dotenv
9
+ load_dotenv()
10
 
11
  config = {"configurable": {"thread_id": "1"}, "recursion_limit" : 50}
12
 
src/main.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ankelodon Agent Adapter for the Hugging Face Agents Course evaluator.
2
+
3
+ This module exposes a simple Gradio-powered wrapper around the
4
+ `ankelodon_multiagent_system` project. It follows the same high-level flow
5
+ as the official GAIA template provided in the course materials: fetch
6
+ evaluation questions from the GAIA API, run your agent to produce
7
+ responses, and submit those responses back to the leaderboard.
8
+
9
+ The key differences between this adapter and the GAIA template are:
10
+
11
+ * It imports and uses your multi‑agent system defined in the `src`
12
+ package (see `src/agent.py`) via the `build_workflow` function. This
13
+ function returns a `langgraph` state machine capable of planning,
14
+ reasoning and executing tools. The adapter calls into this workflow
15
+ with a properly initialised `AgentState` and extracts the final
16
+ answer from the resulting state.
17
+ * It automatically downloads any file attachments associated with a
18
+ task (via the `/files/{task_id}` endpoint exposed by the evaluation
19
+ server) and saves them into a temporary directory. The local file
20
+ paths are passed into the agent through the `files` field of the
21
+ state. Your existing file handling logic (e.g. `preprocess_files`
22
+ in `src/tools/tools.py`) will detect the file type and suggest
23
+ appropriate tools.
24
+ * It strips any leading ``Final answer:`` prefix from the agent's
25
+ response. The evaluation server performs an exact string match
26
+ against the ground truth answer【842261069842380†L108-L112】, so it is
27
+ important that the returned text contains only the answer and
28
+ nothing else.
29
+
30
+ Before running this script yourself, make sure all dependencies in
31
+ `requirements.txt` are installed. To use the Gradio interface locally,
32
+ run `python ankelodon_adapter.py` from the project root. When deploying
33
+ as a Hugging Face Space for leaderboard submission, ensure the
34
+ `SPACE_ID` environment variable is set by the platform; it is used to
35
+ construct a link back to your code for verification.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import os
41
+ import tempfile
42
+ from typing import Optional, List, Dict, Any
43
+
44
+ import requests
45
+ import gradio as gr
46
+ import pandas as pd
47
+
48
+ try:
49
+ # Import the multi‑agent system components. When running as a script
50
+ # within the project root, Python's module search path should
51
+ # already include the `src` directory. If you get import errors,
52
+ # ensure that the working directory is the repository root or
53
+ # append `src` to `sys.path` manually before these imports.
54
+ from agent import build_workflow
55
+ from config import config as WORKFLOW_CONFIG
56
+ from state import AgentState
57
+ except Exception as import_err:
58
+ raise RuntimeError(
59
+ "Failed to import the Ankelodon multi-agent system. "
60
+ "Make sure you are running this script from the repository root "
61
+ "and that the project has been installed correctly."
62
+ ) from import_err
63
+
64
+ DEFAULT_API_URL: str = "https://agents-course-unit4-scoring.hf.space"
65
+
66
+
67
+ class AnkelodonAgent:
68
+ """Simple callable wrapper around the Ankelodon multi‑agent system.
69
+
70
+ Instances of this class can be called directly with a natural
71
+ language question and an optional task identifier. Under the hood it
72
+ builds a `langgraph` workflow using ``build_workflow()``, prepares
73
+ an initial state, fetches any file attachments associated with
74
+ the task, and invokes the workflow to compute a final answer.
75
+ """
76
+
77
+ def __init__(self) -> None:
78
+ # Initialise the workflow once per agent. Subsequent calls reuse
79
+ # the compiled state machine, which is more efficient than
80
+ # rebuilding it on every question.
81
+ self.workflow = build_workflow()
82
+
83
+ def _download_attachment(self, task_id: str) -> List[str]:
84
+ """Download a file attachment for the given task ID.
85
+
86
+ The evaluation API exposes a ``/files/{task_id}`` endpoint【842261069842380†L95-L107】.
87
+ This helper downloads the content, infers a file extension
88
+ from the HTTP ``Content-Type`` header and writes the bytes to a
89
+ temporary file. It returns a list of file paths (zero or one
90
+ element) to be included in the agent state.
91
+ """
92
+ files: List[str] = []
93
+ url = f"{DEFAULT_API_URL}/files/{task_id}"
94
+ try:
95
+ resp = requests.get(url, timeout=15, allow_redirects=True)
96
+ if resp.status_code == 200 and resp.content:
97
+ # Map common MIME substrings to file extensions. The
98
+ # multi‑agent system's file handling tools use the
99
+ # extension to determine how to process the file.
100
+ ctype = resp.headers.get("content-type", "").lower()
101
+ ext_map = {
102
+ "excel": ".xlsx",
103
+ "sheet": ".xlsx",
104
+ "csv": ".csv",
105
+ "python": ".py",
106
+ "audio": ".mp3",
107
+ "image": ".jpg",
108
+ }
109
+ extension = ""
110
+ for key, val in ext_map.items():
111
+ if key in ctype:
112
+ extension = val
113
+ break
114
+ tmp_dir = tempfile.mkdtemp(prefix="ankelodon_task_")
115
+ filename = f"attachment{extension}"
116
+ path = os.path.join(tmp_dir, filename)
117
+ with open(path, "wb") as fh:
118
+ fh.write(resp.content)
119
+ files.append(path)
120
+ except Exception as e:
121
+ # Log the error to console but don't fail the entire task.
122
+ print(f"[WARNING] Failed to fetch attachment for task {task_id}: {e}")
123
+ return files
124
+
125
+ def __call__(self, question: str, task_id: Optional[str] = None) -> str:
126
+ """Run the multi‑agent system to answer a question.
127
+
128
+ Parameters
129
+ ----------
130
+ question: str
131
+ The natural language query to answer.
132
+ task_id: Optional[str]
133
+ If provided, the ID used to fetch any associated file
134
+ attachment from the evaluation API. Attachments are stored
135
+ locally and passed into the agent via the ``files`` field.
136
+
137
+ Returns
138
+ -------
139
+ str
140
+ The final answer produced by the agent, with any "final
141
+ answer" prefix removed. If no answer is produced the empty
142
+ string is returned.
143
+ """
144
+ # Build the initial agent state. The AgentState type defines
145
+ # numerous fields, many of which the workflow populates
146
+ # internally. We set only the essentials here. Unrecognised
147
+ # keys are ignored by the underlying state machine.
148
+ state: Dict[str, Any] = {
149
+ "query": question,
150
+ "final_answer": "",
151
+ "plan": None,
152
+ "complexity_assessment": None,
153
+ "current_step": 0,
154
+ "reasoning_done": False,
155
+ "messages": [],
156
+ "files": [],
157
+ "file_contents": {},
158
+ "critique_feedback": None,
159
+ "iteration_count": 0,
160
+ "max_iterations": 3,
161
+ "execution_report": None,
162
+ "previous_tool_results": {},
163
+ }
164
+
165
+ # If a task ID is provided, attempt to download its attachment.
166
+ if task_id:
167
+ attachment_paths = self._download_attachment(task_id)
168
+ if attachment_paths:
169
+ state["files"] = attachment_paths
170
+
171
+ # Invoke the workflow. The `config` parameter defines runtime
172
+ # options such as recursion limits and thread identifiers. It is
173
+ # imported from `src.config`.
174
+ try:
175
+ result_state = self.workflow.invoke(state, config=WORKFLOW_CONFIG)
176
+ except Exception as e:
177
+ print(f"[ERROR] Failed to run workflow: {e}")
178
+ return ""
179
+
180
+ # Extract the final answer. Depending on the branch taken,
181
+ # either the ``final_answer`` key or a generic ``answer`` key may
182
+ # be present. Use whichever exists. Some nodes may prepend
183
+ # "final answer:"; remove it for exact match scoring【842261069842380†L108-L112】.
184
+ answer = ""
185
+ if isinstance(result_state, dict):
186
+ answer = result_state.get("final_answer") or result_state.get("answer") or ""
187
+ if answer:
188
+ answer = answer.replace("Final answer:", "").replace("final answer:", "").strip()
189
+ return answer
190
+
191
+
192
+ def run_and_submit_all(profile: Optional[gr.OAuthProfile]) -> tuple[str, pd.DataFrame | None]:
193
+ """Fetch all questions, run the agent, and submit the answers.
194
+
195
+ This function replicates the behaviour of the GAIA template's
196
+ ``run_and_submit_all`` function【566837548679297†L247-L306】 but uses the
197
+ ``AnkelodonAgent`` class defined above. It is bound to a Gradio
198
+ button in the UI. On success it returns a status message and a
199
+ DataFrame of results; on failure it returns an error message and
200
+ ``None`` or an empty DataFrame.
201
+ """
202
+ # Require the user to be logged in so we can report the username.
203
+ if not profile:
204
+ return "Please Login to Hugging Face with the button.", None
205
+ username = getattr(profile, "username", "").strip()
206
+
207
+ api_url = DEFAULT_API_URL
208
+ questions_url = f"{api_url}/questions"
209
+ submit_url = f"{api_url}/submit"
210
+
211
+ # Instantiate the agent once.
212
+ try:
213
+ agent = AnkelodonAgent()
214
+ print("Ankelodon agent initialised successfully")
215
+ except Exception as e:
216
+ err_msg = f"Error initialising agent: {e}"
217
+ print(err_msg)
218
+ return err_msg, None
219
+
220
+ # Fetch questions from the evaluation API.【566837548679297†L247-L268】
221
+ try:
222
+ print(f"Fetching questions from: {questions_url}")
223
+ resp = requests.get(questions_url, timeout=15)
224
+ resp.raise_for_status()
225
+ questions_data = resp.json()
226
+ if not questions_data:
227
+ return "Fetched questions list is empty or invalid format.", None
228
+ print(f"Fetched {len(questions_data)} questions.")
229
+ except Exception as e:
230
+ err_msg = f"Error fetching questions: {e}"
231
+ print(err_msg)
232
+ return err_msg, None
233
+
234
+ # Run the agent on each question.
235
+ results_log: List[Dict[str, Any]] = []
236
+ answers_payload: List[Dict[str, str]] = []
237
+ print(f"Running agent on {len(questions_data)} questions…")
238
+ for item in questions_data:
239
+ task_id = item.get("task_id")
240
+ question_text = item.get("question")
241
+ if not task_id or question_text is None:
242
+ print(f"Skipping item with missing task_id or question: {item}")
243
+ continue
244
+ try:
245
+ answer = agent(question_text, task_id)
246
+ answers_payload.append({"task_id": task_id, "submitted_answer": answer})
247
+ results_log.append({
248
+ "Task ID": task_id,
249
+ "Question": question_text,
250
+ "Submitted Answer": answer,
251
+ })
252
+ except Exception as e:
253
+ print(f"Error running agent on task {task_id}: {e}")
254
+ results_log.append({
255
+ "Task ID": task_id,
256
+ "Question": question_text,
257
+ "Submitted Answer": f"AGENT ERROR: {e}",
258
+ })
259
+
260
+ if not answers_payload:
261
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
262
+
263
+ # Prepare submission payload. The leaderboard displays a link to your
264
+ # code; this is constructed from the SPACE_ID environment variable.
265
+ space_id = os.getenv("SPACE_ID", "")
266
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else ""
267
+ submission_data = {
268
+ "username": username,
269
+ "agent_code": agent_code,
270
+ "answers": answers_payload,
271
+ }
272
+
273
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
274
+ try:
275
+ submission_resp = requests.post(submit_url, json=submission_data, timeout=60)
276
+ submission_resp.raise_for_status()
277
+ result_data = submission_resp.json()
278
+ final_status = (
279
+ f"Submission Successful!\n"
280
+ f"User: {result_data.get('username')}\n"
281
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
282
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
283
+ f"Message: {result_data.get('message', 'No message received.')}"
284
+ )
285
+ print("Submission successful.")
286
+ return final_status, pd.DataFrame(results_log)
287
+ except Exception as e:
288
+ err_msg = f"Submission Failed: {e}"
289
+ print(err_msg)
290
+ return err_msg, pd.DataFrame(results_log)
291
+
292
+
293
+ # Build the Gradio interface. This interface resembles the official
294
+ # GAIA template【566837548679297†L372-L401】 but runs your Ankelodon agent.
295
+ with gr.Blocks() as demo:
296
+ gr.Markdown("# Ankelodon Agent Evaluation Runner")
297
+ gr.Markdown(
298
+ """
299
+ **Instructions**
300
+
301
+ 1. Clone this repository or duplicate the associated Hugging Face Space.
302
+ 2. Log in to your Hugging Face account using the button below. Your HF
303
+ username is used to attribute your submission on the leaderboard.
304
+ 3. Click **Run Evaluation & Submit All Answers** to fetch the questions,
305
+ run the Ankelodon agent on each one, submit your answers, and display
306
+ the resulting score and answers.
307
+
308
+ ---
309
+ This template is intentionally lightweight. Feel free to customise it –
310
+ add caching, parallel execution or additional logging as you see fit.
311
+ """
312
+ )
313
+ gr.LoginButton()
314
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
315
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
316
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
317
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
318
+
319
+
320
+ if __name__ == "__main__":
321
+ # When running locally, print some information about the environment.
322
+ print("\n" + "-" * 30 + " Ankelodon Adapter Starting " + "-" * 30)
323
+ space_host_startup = os.getenv("SPACE_HOST")
324
+ space_id_startup = os.getenv("SPACE_ID")
325
+ if space_host_startup:
326
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
327
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
328
+ else:
329
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
330
+ if space_id_startup:
331
+ print(f"✅ SPACE_ID found: {space_id_startup}")
332
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
333
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
334
+ else:
335
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
336
+ print("-" * (60 + len(" Ankelodon Adapter Starting ")) + "\n")
337
+ # Launch the Gradio app.
338
+ demo.launch(debug=True, share=False)
src/workflow_test.ipynb CHANGED
@@ -46,19 +46,19 @@
46
  "=== COMPLEXITY ASSESSMENT ===\n",
47
  "Complexity: simple\n",
48
  "Needs planning: False\n",
49
- "Reasoning: Initial state: 200 coins, all but 30 are face-up 30 face-down (tails). He takes 30 coins; if x of those were face-down, the remaining pile has 30−x face-down. Flipping the 30-coin pile turns its face-down count into 30−x as well, so both piles have equal face-down coins. The larger pile was observed to have 14 face-down coins, so his pile also has 14 face-down coins. His reward is 2 gold coins per face-down coin in his pile: 14×2 = 28.\n",
50
  "=== SIMPLE EXECUTION ===\n",
51
  "Response generated for simple query.\n",
52
  "=== GENERATING EXECUTION REPORT ===\n",
53
  "Report generated - Confidence: high\n",
54
- "Key findings: 5\n",
55
  "Data sources: 2\n",
56
- "query_summary='Riddle: 200 coins where all but 30 are face-up (so 30 face-down). The adventurer removed 30 coins as his pile (unknown orientations), flipped each coin in that pile, then observed the larger pile contained 14 face-down coins. Determine whether he succeeded and how many coins he won (2 gold per face-down coin in his pile).' approach_used=\"Algebraic reasoning with simple variables: let x = number of face-down coins initially in the 30-coin pile removed. Use conservation of face-down coins to compute final counts after flipping, then compute reward = 2 * (final face-downs in adventurer's pile).\" tools_executed=[] key_findings=['Total coins = 200. Initially face-down coins = 30 (since all but 30 are face-up).', 'Let x = number of face-down coins among the 30 coins removed. After flipping those 30 coins, that pile has (30 - x) face-down coins.', 'The remaining (larger) pile has initial face-down coins = 30 - x, which matches (30 - x) after the flip, so both piles have equal face-down counts.', 'Given the larger pile was observed to have 14 face-down coins, 30 - x = 14 => x = 16.', \"Therefore the adventurer's pile also has 14 face-down coins after flipping, yielding a reward of 14 * 2 = 28 coins.\"] data_sources=['Problem statement provided in the query', 'Basic arithmetic/algebra reasoning'] assumptions_made=[\"Interpretation 'all but 30 are face-up' means exactly 30 coins are face-down initially.\", \"The adventurer's pile is the 30-coin pile he removed and flipped; the 'larger pile' refers to the remaining 170-coin pile.\", \"Reward is exactly 2 gold coins per face-down coin in the adventurer's pile, as stated.\"] confidence_level='high' limitations=['Solution depends on standard interpretation of the riddle wording; if alternative interpretations were intended, results could differ.', 'No external references were used; reasoning is self-contained.'] final_answer='28'\n",
57
  "=== ENHANCED ANSWER CRITIQUE ===\n",
58
  "Quality Score: 8/10\n",
59
  "Complete: True\n",
60
  "Accurate: True\n",
61
- "Issues found: [\"Minor imprecise phrasing: the report mentions 'conservation of face-down coins' which is misleading — flipping changes the total number of face-down coins. The correct point is that after flipping the removed 30 coins, the removed pile ends up with (30 - x) face-down coins, which equals the remaining pile's unchanged count of (30 - x).\", 'No explicit, single-sentence statement answering the two parts of the query (Did he succeed? How many gold coins did he win?). The final numeric answer is present but the success statement is implicit.']\n",
62
  "=== REPLAN DECISION ===\n",
63
  "Iteration: 1/10\n",
64
  "Quality score: 8\n",
@@ -68,7 +68,7 @@
68
  }
69
  ],
70
  "source": [
71
- "query = \"Here's a fun riddle that I'd like you to try.\\n\\nAn adventurer exploring an ancient tomb came across a horde of gold coins, all neatly stacked in columns. As he reached to scoop them into his backpack, a mysterious voice filled the room. \\\"You have fallen for my trap adventurer,\\\" the voice began, and suddenly the doorway to the chamber was sealed by a heavy rolling disk of stone. The adventurer tried to move the stone disk but was unable to budge the heavy stone. Trapped, he was startled when the voice again spoke. \\n\\n\\\"If you solve my riddle, I will reward you with a portion of my riches, but if you are not clever, you will never leave this treasure chamber. Before you are 200 gold coins. I pose a challenge to you, adventurer. Within these stacks of coins, all but 30 are face-up. You must divide the coins into two piles, one is yours, and one is mine. You may place as many coins as you like in either pile. You may flip any coins over, but you may not balance any coins on their edges. For every face-down coin in your pile, you will be rewarded with two gold coins. But be warned, if both piles do not contain the same number of face-down coins, the door will remain sealed for all eternity!\\\"\\n\\nThe adventurer smiled, as this would be an easy task. All he had to do was flip over every coin so it was face down, and he would win the entire treasure! As he moved to the columns of coins, however, the light suddenly faded, and he was left in total darkness. The adventurer reached forward and picked up one of the coins, and was shocked when he realized that both sides felt almost the same. Without the light, he was unable to determine which side of the coin was heads and which side was tails. He carefully replaced the coin in its original orientation and tried to think of a way to solve the puzzle. Finally, out of desperation, the adventurer removed 30 coins to create his pile. He then carefully flipped over each coin in his pile, so its orientation was inverted from its original state.\\n\\n\\\"I've finished,\\\" he said, and the lights returned. Looking at the two piles, he noticed that the larger pile contained 14 face-down coins.\\n\\nWhat was the outcome for the adventurer? If he failed the challenge, please respond with \\\"The adventurer died.\\\" Otherwise, please provide the number of coins the adventurer won at the conclusion of the riddle. If the adventurer won any coins, provide your response as the number of coins, with no other text.\"\n",
72
  "result = graph.invoke({\"query\" : query, \"current_step\": 0, \"reasoning_done\": False, \"files\" : [], \"files_contents\" : {}, \"iteration_count\" : 0, \"max_iterations\" : 10, \"plan\" : None} , config = config)"
73
  ]
74
  },
@@ -81,7 +81,7 @@
81
  "name": "stdout",
82
  "output_type": "stream",
83
  "text": [
84
- "FINAL ANSWER: 28\n"
85
  ]
86
  }
87
  ],
@@ -97,20 +97,20 @@
97
  {
98
  "data": {
99
  "text/plain": [
100
- "{'messages': [SystemMessage(content='You are a COMPLEXITY ASSESSOR for a multi-tool agent system.\\nYour job is to analyze user queries and determine their complexity level and processing requirements.\\n\\nCOMPLEXITY LEVELS:\\n1. SIMPLE: Direct questions that can be answered immediately without tools or with single tool use\\n - Examples: \"What is photosynthesis?\", \"Define machine learning\", \"What\\'s the capital of France?\"\\n - NOTE: Simple math like \"2+2\" still requires calculator tool but counts as SIMPLE\\n\\n !ALSO: It can be a logical reasoning or explanation task that does not require tools.\\n \\n2. MODERATE: Questions requiring 2-4 tool calls or basic multi-step analysis\\n - Examples: \"Search for recent news about AI\", \"Analyze this CSV file for trends\", \"Calculate ROI from this data\"\\n - \"Compare two datasets\", \"Summarize multiple documents\"\\n \\n3. COMPLEX: Multi-step problems requiring planning, multiple tools, and sophisticated reasoning\\n - Examples: \"Research market trends and create investment strategy\", \"Analyze multiple data sources and predict outcomes\"\\n - \"Build comprehensive report from various inputs\", \"Multi-stage data processing with validation\"\\n\\nMOST OF THE LOGICAL TASKS ARE SIMPLE, UNLESS THEY REQUIRE TOOLS.\\n\\nASSESSMENT CRITERIA:\\n- Number of distinct steps likely needed (1 = Simple, 2-4 = Moderate, 5+ = Complex)\\n- Tool complexity and dependencies between steps\\n- Data processing requirements and validation needs\\n- Need for intermediate reasoning and synthesis\\n- Risk of failure without proper step-by-step planning\\n- Presence of calculations (automatically requires tool usage)\\n\\nSPECIAL CONSIDERATIONS:\\n- Any calculation/counting task requires tools (affects complexity assessment)\\n- File analysis tasks usually need multiple steps (load + analyze + calculate)\\n- Research tasks typically need search + fetch + synthesis steps\\n- Comparison tasks need separate analysis steps for each item being compared\\n\\nRULES:\\n- SIMPLE queries may bypass planning for non-calculation tasks\\n- MODERATE queries benefit from lightweight planning\\n- COMPLEX queries require full planning with fallbacks\\n- When in doubt, err toward higher complexity\\n- Calculation tasks are never truly \"simple\" due to mandatory tool usage\\n\\nAnalyze the query and respond with your assessment.', additional_kwargs={}, response_metadata={}, id='26e46b0a-44ea-4f15-be78-dd9e141ac21b'),\n",
101
- " HumanMessage(content='Query: Here\\'s a fun riddle that I\\'d like you to try.\\n\\nAn adventurer exploring an ancient tomb came across a horde of gold coins, all neatly stacked in columns. As he reached to scoop them into his backpack, a mysterious voice filled the room. \"You have fallen for my trap adventurer,\" the voice began, and suddenly the doorway to the chamber was sealed by a heavy rolling disk of stone. The adventurer tried to move the stone disk but was unable to budge the heavy stone. Trapped, he was startled when the voice again spoke. \\n\\n\"If you solve my riddle, I will reward you with a portion of my riches, but if you are not clever, you will never leave this treasure chamber. Before you are 200 gold coins. I pose a challenge to you, adventurer. Within these stacks of coins, all but 30 are face-up. You must divide the coins into two piles, one is yours, and one is mine. You may place as many coins as you like in either pile. You may flip any coins over, but you may not balance any coins on their edges. For every face-down coin in your pile, you will be rewarded with two gold coins. But be warned, if both piles do not contain the same number of face-down coins, the door will remain sealed for all eternity!\"\\n\\nThe adventurer smiled, as this would be an easy task. All he had to do was flip over every coin so it was face down, and he would win the entire treasure! As he moved to the columns of coins, however, the light suddenly faded, and he was left in total darkness. The adventurer reached forward and picked up one of the coins, and was shocked when he realized that both sides felt almost the same. Without the light, he was unable to determine which side of the coin was heads and which side was tails. He carefully replaced the coin in its original orientation and tried to think of a way to solve the puzzle. Finally, out of desperation, the adventurer removed 30 coins to create his pile. He then carefully flipped over each coin in his pile, so its orientation was inverted from its original state.\\n\\n\"I\\'ve finished,\" he said, and the lights returned. Looking at the two piles, he noticed that the larger pile contained 14 face-down coins.\\n\\nWhat was the outcome for the adventurer? If he failed the challenge, please respond with \"The adventurer died.\" Otherwise, please provide the number of coins the adventurer won at the conclusion of the riddle. If the adventurer won any coins, provide your response as the number of coins, with no other text.', additional_kwargs={}, response_metadata={}, id='85bfac92-7cdb-48f0-b211-9593a6dfc851'),\n",
102
- " AIMessage(content='28', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 970, 'prompt_tokens': 2706, 'total_tokens': 3676, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 960, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-5-mini-2025-08-07', 'system_fingerprint': None, 'id': 'chatcmpl-CIbxZ2RCMWUu7YmfpqFUpa2eMG39g', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='run--fd1c06e8-0aa2-49db-8693-33ac60a1b382-0', usage_metadata={'input_tokens': 2706, 'output_tokens': 970, 'total_tokens': 3676, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 960}})],\n",
103
- " 'query': 'Here\\'s a fun riddle that I\\'d like you to try.\\n\\nAn adventurer exploring an ancient tomb came across a horde of gold coins, all neatly stacked in columns. As he reached to scoop them into his backpack, a mysterious voice filled the room. \"You have fallen for my trap adventurer,\" the voice began, and suddenly the doorway to the chamber was sealed by a heavy rolling disk of stone. The adventurer tried to move the stone disk but was unable to budge the heavy stone. Trapped, he was startled when the voice again spoke. \\n\\n\"If you solve my riddle, I will reward you with a portion of my riches, but if you are not clever, you will never leave this treasure chamber. Before you are 200 gold coins. I pose a challenge to you, adventurer. Within these stacks of coins, all but 30 are face-up. You must divide the coins into two piles, one is yours, and one is mine. You may place as many coins as you like in either pile. You may flip any coins over, but you may not balance any coins on their edges. For every face-down coin in your pile, you will be rewarded with two gold coins. But be warned, if both piles do not contain the same number of face-down coins, the door will remain sealed for all eternity!\"\\n\\nThe adventurer smiled, as this would be an easy task. All he had to do was flip over every coin so it was face down, and he would win the entire treasure! As he moved to the columns of coins, however, the light suddenly faded, and he was left in total darkness. The adventurer reached forward and picked up one of the coins, and was shocked when he realized that both sides felt almost the same. Without the light, he was unable to determine which side of the coin was heads and which side was tails. He carefully replaced the coin in its original orientation and tried to think of a way to solve the puzzle. Finally, out of desperation, the adventurer removed 30 coins to create his pile. He then carefully flipped over each coin in his pile, so its orientation was inverted from its original state.\\n\\n\"I\\'ve finished,\" he said, and the lights returned. Looking at the two piles, he noticed that the larger pile contained 14 face-down coins.\\n\\nWhat was the outcome for the adventurer? If he failed the challenge, please respond with \"The adventurer died.\" Otherwise, please provide the number of coins the adventurer won at the conclusion of the riddle. If the adventurer won any coins, provide your response as the number of coins, with no other text.',\n",
104
- " 'final_answer': 'FINAL ANSWER: 28',\n",
105
  " 'plan': None,\n",
106
- " 'complexity_assessment': ComplexityLevel(level='simple', reasoning='Initial state: 200 coins, all but 30 are face-up 30 face-down (tails). He takes 30 coins; if x of those were face-down, the remaining pile has 30−x face-down. Flipping the 30-coin pile turns its face-down count into 30−x as well, so both piles have equal face-down coins. The larger pile was observed to have 14 face-down coins, so his pile also has 14 face-down coins. His reward is 2 gold coins per face-down coin in his pile: 14×2 = 28.', needs_planning=False, suggested_approach='Use simple counting: compute initial number of face-down coins (30), let x be face-down among the 30 taken, show flipping yields equal counts, then multiply the final face-down count in his pile by 2 to get the reward.'),\n",
107
  " 'current_step': 0,\n",
108
  " 'reasoning_done': False,\n",
109
  " 'files': [],\n",
110
- " 'critique_feedback': CritiqueFeedback(quality_score=8, is_complete=True, is_accurate=True, missing_elements=[], errors_found=[\"Minor imprecise phrasing: the report mentions 'conservation of face-down coins' which is misleading — flipping changes the total number of face-down coins. The correct point is that after flipping the removed 30 coins, the removed pile ends up with (30 - x) face-down coins, which equals the remaining pile's unchanged count of (30 - x).\", 'No explicit, single-sentence statement answering the two parts of the query (Did he succeed? How many gold coins did he win?). The final numeric answer is present but the success statement is implicit.'], suggested_improvements=[\"Clarify the flipping logic and avoid the word 'conservation' for face-down coins; explicitly show how removed-pile face-down count transforms from x to (30 - x).\", \"Add an explicit conclusion sentence: e.g., 'Yes — he succeeded; his pile has 14 face-down coins after flipping, so he wins 14 * 2 = 28 gold.'\", 'Add a brief sanity check (optional): pick an example x (like x = 16) and show counts before and after flipping to demonstrate consistency.', 'If following strict tooling policies, note that no external tools were required for this simple algebraic reasoning. If automated-tool usage is mandatory in your environment, run a quick symbolic/numeric check with the chosen tool and cite it.'], needs_replanning=False, replan_instructions=None),\n",
111
  " 'iteration_count': 1,\n",
112
  " 'max_iterations': 10,\n",
113
- " 'execution_report': ExecutionReport(query_summary='Riddle: 200 coins where all but 30 are face-up (so 30 face-down). The adventurer removed 30 coins as his pile (unknown orientations), flipped each coin in that pile, then observed the larger pile contained 14 face-down coins. Determine whether he succeeded and how many coins he won (2 gold per face-down coin in his pile).', approach_used=\"Algebraic reasoning with simple variables: let x = number of face-down coins initially in the 30-coin pile removed. Use conservation of face-down coins to compute final counts after flipping, then compute reward = 2 * (final face-downs in adventurer's pile).\", tools_executed=[], key_findings=['Total coins = 200. Initially face-down coins = 30 (since all but 30 are face-up).', 'Let x = number of face-down coins among the 30 coins removed. After flipping those 30 coins, that pile has (30 - x) face-down coins.', 'The remaining (larger) pile has initial face-down coins = 30 - x, which matches (30 - x) after the flip, so both piles have equal face-down counts.', 'Given the larger pile was observed to have 14 face-down coins, 30 - x = 14 => x = 16.', \"Therefore the adventurer's pile also has 14 face-down coins after flipping, yielding a reward of 14 * 2 = 28 coins.\"], data_sources=['Problem statement provided in the query', 'Basic arithmetic/algebra reasoning'], assumptions_made=[\"Interpretation 'all but 30 are face-up' means exactly 30 coins are face-down initially.\", \"The adventurer's pile is the 30-coin pile he removed and flipped; the 'larger pile' refers to the remaining 170-coin pile.\", \"Reward is exactly 2 gold coins per face-down coin in the adventurer's pile, as stated.\"], confidence_level='high', limitations=['Solution depends on standard interpretation of the riddle wording; if alternative interpretations were intended, results could differ.', 'No external references were used; reasoning is self-contained.'], final_answer='28')}"
114
  ]
115
  },
116
  "execution_count": 5,
@@ -129,10 +129,10 @@
129
  "outputs": [],
130
  "source": [
131
  "#TO-DO\n",
132
- "#1. Check routing with REPLANNER -> может придумывать несуществующие инструменты\n",
133
- "#2. Add crawling tool\n",
134
- "#3. Enhance description of coder tool and прописать более четко в промпте важность вывода через print() или return или result/_\n",
135
- "#4. Смягчить критика"
136
  ]
137
  }
138
  ],
 
46
  "=== COMPLEXITY ASSESSMENT ===\n",
47
  "Complexity: simple\n",
48
  "Needs planning: False\n",
49
+ "Reasoning: This is a single-step arithmetic question (2+2). Although calculations technically require a tool per the special considerations, this is trivial and requires only one immediate operation, so it is SIMPLE.\n",
50
  "=== SIMPLE EXECUTION ===\n",
51
  "Response generated for simple query.\n",
52
  "=== GENERATING EXECUTION REPORT ===\n",
53
  "Report generated - Confidence: high\n",
54
+ "Key findings: 3\n",
55
  "Data sources: 2\n",
56
+ "query_summary=\"User asked for the numeric result of the arithmetic expression '2+2'.\" approach_used=\"Direct evaluation using basic arithmetic: interpreted '+' as standard integer addition and computed the sum mentally without invoking external tools or files.\" tools_executed=[] key_findings=[\"The expression '2+2' was interpreted as standard integer addition.\", 'Computed result is 4.', 'No external tools or data were required to compute the result.'] data_sources=['Basic arithmetic rules (internal knowledge)', 'Conversation history confirming the query and an earlier direct answer'] assumptions_made=[\"The '+' operator denotes standard arithmetic addition on integers.\", 'Numbers are in the usual base-10 system and no special context (e.g., modular arithmetic or symbolic manipulation) was intended.'] confidence_level='high' limitations=['If the user intended a nonstandard context (modulo arithmetic, different base, or overloaded operator semantics), the answer could differ.', 'Extremely simple query; few realistic limitations beyond contextual ambiguity.'] final_answer='4'\n",
57
  "=== ENHANCED ANSWER CRITIQUE ===\n",
58
  "Quality Score: 8/10\n",
59
  "Complete: True\n",
60
  "Accurate: True\n",
61
+ "Issues found: [\"Performed the calculation mentally rather than using an external computational tool (triggers the evaluation framework's manual-calculation penalty).\"]\n",
62
  "=== REPLAN DECISION ===\n",
63
  "Iteration: 1/10\n",
64
  "Quality score: 8\n",
 
68
  }
69
  ],
70
  "source": [
71
+ "query = \"What is 2+2\"\n",
72
  "result = graph.invoke({\"query\" : query, \"current_step\": 0, \"reasoning_done\": False, \"files\" : [], \"files_contents\" : {}, \"iteration_count\" : 0, \"max_iterations\" : 10, \"plan\" : None} , config = config)"
73
  ]
74
  },
 
81
  "name": "stdout",
82
  "output_type": "stream",
83
  "text": [
84
+ "FINAL ANSWER: 4\n"
85
  ]
86
  }
87
  ],
 
97
  {
98
  "data": {
99
  "text/plain": [
100
+ "{'messages': [SystemMessage(content='You are a COMPLEXITY ASSESSOR for a multi-tool agent system.\\nYour job is to analyze user queries and determine their complexity level and processing requirements.\\n\\nCOMPLEXITY LEVELS:\\n1. SIMPLE: Direct questions that can be answered immediately without tools or with single tool use\\n - Examples: \"What is photosynthesis?\", \"Define machine learning\", \"What\\'s the capital of France?\"\\n - NOTE: Simple math like \"2+2\" still requires calculator tool but counts as SIMPLE\\n\\n !ALSO: It can be a logical reasoning or explanation task that does not require tools.\\n \\n2. MODERATE: Questions requiring 2-4 tool calls or basic multi-step analysis\\n - Examples: \"Search for recent news about AI\", \"Analyze this CSV file for trends\", \"Calculate ROI from this data\"\\n - \"Compare two datasets\", \"Summarize multiple documents\"\\n \\n3. COMPLEX: Multi-step problems requiring planning, multiple tools, and sophisticated reasoning\\n - Examples: \"Research market trends and create investment strategy\", \"Analyze multiple data sources and predict outcomes\"\\n - \"Build comprehensive report from various inputs\", \"Multi-stage data processing with validation\"\\n\\nMOST OF THE LOGICAL TASKS ARE SIMPLE, UNLESS THEY REQUIRE TOOLS.\\n\\nASSESSMENT CRITERIA:\\n- Number of distinct steps likely needed (1 = Simple, 2-4 = Moderate, 5+ = Complex)\\n- Tool complexity and dependencies between steps\\n- Data processing requirements and validation needs\\n- Need for intermediate reasoning and synthesis\\n- Risk of failure without proper step-by-step planning\\n- Presence of calculations (automatically requires tool usage)\\n\\nSPECIAL CONSIDERATIONS:\\n- Any calculation/counting task requires tools (affects complexity assessment)\\n- File analysis tasks usually need multiple steps (load + analyze + calculate)\\n- Research tasks typically need search + fetch + synthesis steps\\n- Comparison tasks need separate analysis steps for each item being compared\\n\\nRULES:\\n- SIMPLE queries may bypass planning for non-calculation tasks\\n- MODERATE queries benefit from lightweight planning\\n- COMPLEX queries require full planning with fallbacks\\n- When in doubt, err toward higher complexity\\n- Calculation tasks are never truly \"simple\" due to mandatory tool usage\\n\\nAnalyze the query and respond with your assessment.', additional_kwargs={}, response_metadata={}, id='db109164-6e6e-4c1f-82bb-93d6d9b64e6a'),\n",
101
+ " HumanMessage(content='Query: What is 2+2', additional_kwargs={}, response_metadata={}, id='6b9afadb-3463-40a2-989b-19f8a237f7fc'),\n",
102
+ " AIMessage(content='2 + 2 = 4', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 80, 'prompt_tokens': 1638, 'total_tokens': 1718, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 64, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-5-mini-2025-08-07', 'system_fingerprint': None, 'id': 'chatcmpl-CId3zSwgGIoDxYMuwG2xJfCLDiVuM', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='run--210d298d-a542-4458-8933-93ebf4c7bac0-0', usage_metadata={'input_tokens': 1638, 'output_tokens': 80, 'total_tokens': 1718, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 64}})],\n",
103
+ " 'query': 'What is 2+2',\n",
104
+ " 'final_answer': 'FINAL ANSWER: 4',\n",
105
  " 'plan': None,\n",
106
+ " 'complexity_assessment': ComplexityLevel(level='simple', reasoning='This is a single-step arithmetic question (2+2). Although calculations technically require a tool per the special considerations, this is trivial and requires only one immediate operation, so it is SIMPLE.', needs_planning=False, suggested_approach='Perform the basic arithmetic (2+2) and return the result (4). No detailed planning or multi-step processing needed.'),\n",
107
  " 'current_step': 0,\n",
108
  " 'reasoning_done': False,\n",
109
  " 'files': [],\n",
110
+ " 'critique_feedback': CritiqueFeedback(quality_score=8, is_complete=True, is_accurate=True, missing_elements=[], errors_found=[\"Performed the calculation mentally rather than using an external computational tool (triggers the evaluation framework's manual-calculation penalty).\"], suggested_improvements=['Use a computational tool or explicitly show the calculation steps even for trivial arithmetic to avoid the manual-calculation policy violation (e.g., evaluate with a calculator tool or print the operation and result).', \"Explicitly state assumptions up front (that '+' is standard integer addition in base 10) and, when relevant, ask a clarifying question if the user might have meant a nonstandard interpretation (modular arithmetic, different base, operator overloading).\", 'For transparency, include a short note citing the arithmetic rule used (e.g., basic integer addition) when delivering the result, even though the operation is trivial.'], needs_replanning=False, replan_instructions=None),\n",
111
  " 'iteration_count': 1,\n",
112
  " 'max_iterations': 10,\n",
113
+ " 'execution_report': ExecutionReport(query_summary=\"User asked for the numeric result of the arithmetic expression '2+2'.\", approach_used=\"Direct evaluation using basic arithmetic: interpreted '+' as standard integer addition and computed the sum mentally without invoking external tools or files.\", tools_executed=[], key_findings=[\"The expression '2+2' was interpreted as standard integer addition.\", 'Computed result is 4.', 'No external tools or data were required to compute the result.'], data_sources=['Basic arithmetic rules (internal knowledge)', 'Conversation history confirming the query and an earlier direct answer'], assumptions_made=[\"The '+' operator denotes standard arithmetic addition on integers.\", 'Numbers are in the usual base-10 system and no special context (e.g., modular arithmetic or symbolic manipulation) was intended.'], confidence_level='high', limitations=['If the user intended a nonstandard context (modulo arithmetic, different base, or overloaded operator semantics), the answer could differ.', 'Extremely simple query; few realistic limitations beyond contextual ambiguity.'], final_answer='4')}"
114
  ]
115
  },
116
  "execution_count": 5,
 
129
  "outputs": [],
130
  "source": [
131
  "#TO-DO\n",
132
+ "#1. Check routing with REPLANNER -> может придумывать несуществующие инструменты -> PARTIALLY COMPLETED\n",
133
+ "#2. Add crawling tool \n",
134
+ "#3. Enhance description of coder tool and прописать более четко в промпте важность вывода через print() или return или result/_ -> COMPLETED?\n",
135
+ "#4. Смягчить критика COMPLETED"
136
  ]
137
  }
138
  ],