Skip to content

Commit 22ceafa

Browse files
committed
Catch and return tool validation errors to LLM
Wrap tool.ainvoke() in try/except to catch validation errors and send them back to the LLM as error messages in ToolMessage. This allows the LLM to see what went wrong and retry with correct arguments.
1 parent 5396372 commit 22ceafa

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

python-recipes/context-engineering/notebooks/section-3-memory/04_memory_tools.ipynb

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -275,13 +275,18 @@
275275
" # Find and execute the tool\n",
276276
" tool = next((t for t in memory_tools if t.name == tool_call['name']), None)\n",
277277
" if tool:\n",
278-
" result = await tool.ainvoke(tool_call['args'])\n",
279-
" print(f\" Result: {result}\")\n",
278+
" try:\n",
279+
" result = await tool.ainvoke(tool_call['args'])\n",
280+
" print(f\" Result: {result}\")\n",
281+
" result_content = str(result)\n",
282+
" except Exception as e:\n",
283+
" print(f\" Error: {e}\")\n",
284+
" result_content = f\"Error: {str(e)}\"\n",
280285
" \n",
281286
" # Add tool result to messages\n",
282287
" messages.append(response)\n",
283288
" messages.append(ToolMessage(\n",
284-
" content=str(result),\n",
289+
" content=result_content,\n",
285290
" tool_call_id=tool_call['id']\n",
286291
" ))\n",
287292
" \n",
@@ -336,14 +341,19 @@
336341
" # Find and execute the tool\n",
337342
" tool = next((t for t in memory_tools if t.name == tool_call['name']), None)\n",
338343
" if tool:\n",
339-
" result = await tool.ainvoke(tool_call['args'])\n",
340-
" print(f\"\\n Retrieved memories:\")\n",
341-
" print(f\" {result}\")\n",
344+
" try:\n",
345+
" result = await tool.ainvoke(tool_call['args'])\n",
346+
" print(f\"\\n Retrieved memories:\")\n",
347+
" print(f\" {result}\")\n",
348+
" result_content = str(result)\n",
349+
" except Exception as e:\n",
350+
" print(f\"\\n Error: {e}\")\n",
351+
" result_content = f\"Error: {str(e)}\"\n",
342352
" \n",
343353
" # Add tool result to messages\n",
344354
" messages.append(response)\n",
345355
" messages.append(ToolMessage(\n",
346-
" content=str(result),\n",
356+
" content=result_content,\n",
347357
" tool_call_id=tool_call['id']\n",
348358
" ))\n",
349359
" \n",

0 commit comments

Comments
 (0)