BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Agents28 of 28 in topic

816. Plan the cheapest tool chain with Dijkstra

MediumAgents Pro

Why it matters Tool-using agents and workflow planners route between formats and services by cost, which is a shortest path problem.

An agent can turn one artefact into another with tools (pdf -> text, text -> summary, audio -> text), and each tool has a cost. The cheapest way from what you have to what you need is a shortest path.

Write cheapest_chain(tools, start, goal). tools is a list of (name, src, dst, cost) with cost >= 0. Return (total_cost, [tool names in order]) for the cheapest path from start to goal using Dijkstra's algorithm, or (None, []) if goal cannot be reached. If start == goal return (0, []). When two paths cost the same, prefer the one whose list of tool names is smaller in Python list order.

Functiondef cheapest_chain(tools, start, goal)

Example 1

Input: cheapest_chain([('a', 'x', 'y', 1), ('b', 'y', 'z', 1), ('c', 'x', 'z', 5)], 'x', 'z')

Output: (2, ['a', 'b'])

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

Build an adjacency list from src to (dst, cost, name).

Hint 2

Use heapq with (cost, path, node) so ties compare paths.

Hint 3

Mark a node done when it is popped, not when it is pushed.

Common mistakes
  • Breadth-first search, which finds the fewest tools rather than the cheapest.
  • Marking nodes visited at push time, which can lock in a costlier path.
Understand the idea

Dijkstra always expands the cheapest frontier node next. With non-negative costs, the first time the goal is popped its cost is optimal. Putting the path into the heap entry after the cost makes ties fall back to comparing tool name lists.

Worked example

x -> y -> z costs 2, beating the direct tool at 5.

pop (cost, path, node); skip if done; return on goal; push neighbours
Topics
Agents
Similar questions
  • Write the loop that runs a tool-calling agentMedium
  • Retry a flaky tool with exponential backoffMedium
  • Extract a JSON tool call from messy model outputMedium
  • Enforce token and dollar budgets on an agent runMedium
All Agents problems
Report
816 / 903
Python 3solution.pyPython idle
1
2
3
4
5
import heapq
def cheapest_chain(tools, start, goal):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS