Who Controls the Control Flow? Designing Tool Invocation in LLM Agents
Imagine asking a flight-booking agent:
Find me a flight from Chennai to London tomorrow for ₹45,000 or less.
The agent searches for flights and returns the available options. But then you change your mind:
Actually, what about Leeds?
Can the agent simply search again? Or does it need to complete the current workflow before returning to flight search?
Interestingly, the answer depends less on the language model itself and more on how the developer designed tool invocation.
I built three versions of a flight-booking agent using the same underlying tools: one where Python determines the execution sequence, another where the model can choose tools within application-defined stages, and a third where the model dynamically chooses from a broader set of tools throughout the conversation.
All three use an LLM, but they differ in an important way: who decides which tool runs next?
That decision affects how flexible the agent is, how predictable its execution becomes, and how easily developers can understand, debug, and maintain its behavior.
Let's examine those trade-offs through the implementations.
A tool call starts as a proposal
When the model requests a tool, it supplies a name and arguments. In these demos, Python receives the request, checks the tool name against the tools available at that point, and invokes the matching function. It sends the result back to the model, which can use it to answer the traveler or, if the loop allows, ask for another tool call.
sequenceDiagram
participant U as User
participant L as LLM
participant A as Application
participant T as Tool
U->>A: Ask for a flight
A->>L: Send request and available tools
L-->>A: Propose tool call with arguments
A->>T: Check request and execute permitted call
T-->>A: Return result
A->>L: Provide tool result
L-->>A: Generate reply
A-->>U: Display reply
For the Chennai-to-London request, the model can translate “tomorrow” into a date and the budget into max_fare. You can call the same tool directly from the project directory to see what those arguments return.
from datetime import date, timedelta
from flight_tools import search_flight
flights = search_flight.invoke({
"origin": "Chennai",
"destination": "London",
"departure_date": (date.today() + timedelta(days=1)).isoformat(),
"max_fare": 45_000,
})
The mock data returns one match, FL004, departing at 08:00 for ₹39,500. Shared flight tools
Tool definitions tell the model which names and arguments are available. The prompt and conversation help it decide whether to call a tool and what values to supply. The application controls which requests run. That division applies to booking too, where the model can propose a call with passenger details and Python decides whether it can reach the booking function.
There are two decisions here. One is who chooses the next tool from the options the application makes available. The other is what the application requires before it executes that request. The three demos vary the first decision and make the importance of the second easier to see.
flowchart LR
C["Code-driven"] --> C1["Python names the next eligible tool"]
H["Hybrid"] --> H1["Python sets the stage, LLM chooses within it"]
L["LLM-driven"] --> L1["LLM chooses from a fixed tool set"]
Each demo prints Tools visible to the agent: so you can see those choices in the terminal. Enter /quit at an input prompt to exit any of the three.
Put the sequence in Python
The smallest workflow has three stages. At each user turn, the script binds just the current tool. The model can supply arguments or reply without making a call, for example to ask for a missing passenger name. Python rejects requests for any other tool and runs at most one call per turn. Code-driven agent
stages = [search_flight, create_booking, get_booking]
stage = 0
visible_tool = stages[stage]
An empty search leaves the stage unchanged. As soon as the London search finds FL004, Python advances to booking for the next user turn. If the traveler now asks about Leeds, the model has no search tool available and the script has no transition back to search. A code-driven workflow could support that change with a branch. It could also retry an operation or loop back to collect new details. In this version, the empty search is the only tool outcome that keeps the workflow in its current stage.
The booking stage shows why a predictable sequence can still produce the wrong outcome. The prompt tells the model to wait until the traveler chooses a flight and supplies passenger details. The model supplies the flight ID, and create_booking checks that it exists. A different existing ID would pass that check, even if the search returned only FL004. A nonexistent ID produces an error string, but the loop advances to get_booking after any normal return from create_booking. The lookup takes a flight ID from the model and lists its active bookings. It does not look up the reservation by booking ID.
Python calls the model with no tools bound to summarize each result, then ends the session after the lookup. If the workflow required a successful reservation before that final step, success would need to be part of the transition condition. An application could also ask the model to extract structured information and invoke the next function directly in Python. In this demo, the model still proposes the call.
Keep search open until Python records a selection
The hybrid version starts with search_flight and select_flight available together. If the traveler asks about Leeds while both tools are available, the model can search again. If it proposes a selection and that ID is unknown, the tool reports the failure without recording a selection. Once select_flight finds a valid ID, it stores the normalized value in selected_flight_id, and Python switches the available tools. Hybrid agent
# Python switches the available tools after a valid selection.
if selected_flight_id is not None and select_flight in tools:
tools = [book_selected_flight]
print(f"Tools visible to the agent: {book_selected_flight.name}")
In the terminal, the initial search_flight, select_flight line gives way to book_selected_flight, then to none for the final summary. The booking tool takes the passenger’s name and passport number. It gets the flight ID from Python state, so if the application recorded FL004, the model cannot substitute another ID in the booking call. If the wrong flight is booked, I’d start with the selection call and the ID it recorded.
The prompt asks the model to show search results and then wait for the traveler to choose. The selection function checks only that the ID exists. It has no record of whether the traveler chose that ID or whether it appeared in the search results. The loop can also invoke the model again immediately after selection, so it can request booking in the same user turn if it has the passenger details. After selection there’s no path back to search or reselection. After the booking tool returns, the script summarizes the result and exits.
That boundary is useful because it preserves a specific piece of state across calls. Adding another stage would help if it enforced another requirement, such as recording a fresh choice after the traveler changes destinations. It would also add transitions to implement and test.
Let the conversation determine the sequence
The LLM-driven version binds the same seven tools once for the whole session: search_flight, get_baggage_policy, create_booking, get_booking, change_booking_flight, get_cancellation_quote, and cancel_booking. The traveler can ask about baggage for FL004, switch the search to Leeds, or return later in the same session with a booking ID and ask for a cancellation quote. The application has no workflow-stage variable. The model sees the accumulated conversation and tool results, and the shared in-memory repository holds the bookings. Python looks up each requested tool in the fixed set and returns an “unavailable” result for names outside it. LLM-driven agent
If a cancellation quote is requested with an unknown booking ID, the tool returns a message explaining that the booking wasn’t found. The model can use that result to ask for a corrected ID. Cancellation itself is different. The prompt tells the model to show the quote and wait for confirmation, but the dispatcher runs cancel_booking whenever the model requests it with valid arguments. Given an active booking ID, the tool removes the booking. A production dispatcher could require application-recorded confirmation before invoking the same tool while still letting the model choose when to propose it.
Across the three demos, a returned error string goes back to the model as a tool result. An exception escaping a tool invocation is a different case. None of these loops catches it or implements an exception retry.
What the developer has to keep in mind
In his 1972 Turing Award lecture, The Humble Programmer, Edsger W. Dijkstra observed that programs for the same task can differ greatly in how manageable they are for a programmer to reason about. The three booking loops make that idea concrete. Each dispatcher is small. The work of explaining a particular outcome depends on what the dispatcher leaves to the model. The Humble Programmer
For the model, a larger tool set can mean more similar names, descriptions, and argument schemas to distinguish. Imagine offering a general flight search alongside separate searches by date, price, airline, and direct routes. Several of those tools could look plausible for the same request. The shared search_flight tool handles departure date, earliest departure time, and maximum fare with optional arguments. Tool definitions and any prior results sent with the conversation also take up input context. Tool count alone tells you little about reliability. Descriptions, schema design, conversation context, the model’s capabilities, and the application’s execution checks all shape the outcome.
For the developer, every tool that can follow another creates another path to consider. If 30 tools are available for each of exactly five calls and repeats are allowed, there are 30⁵ = 24,300,000 possible sequences of tool names. A real workflow can rule out many of those sequences, and the same sequence can use different arguments or produce different results. A stale flight ID in the conversation can lead to the wrong booking even when every function behaves as written.
A useful test focuses on an invariant, such as whether the hybrid booking always uses the ID that Python recorded. To investigate a particular failure, I’d want the available tools, the proposed call and its arguments, the application’s execution decision, and the result. Python’s transitions are visible in the loop. For a model-selected path, I’d also inspect the prompt and conversation as they stood when the call was proposed. A change to a tool’s description or schema can change which tool the model chooses even when its Python function stays the same.
Choosing what to delegate
For a reservation workflow with strict dependencies, I’d start with code-driven orchestration. If the business requires a successful reservation before issuing a receipt, I want a transition I can test against both success and failure. Explicit transitions are easy to inspect. They take more implementation work as the workflow adds supported changes, such as returning to search after the traveler changes destinations.
For a booking conversation that mixes exploration with a controlled operation, I’d keep the search flexible and put the commitment boundary in code. The hybrid demo shows how to carry a selected ID forward. For a real reservation, I’d also define how the traveler can change the selection and what counts as authorization to book. Restricting tools limits which actions the model can request at a stage. Argument validation, authorization, and business rules still belong at execution.
For an open-ended travel assistant that handles search, baggage questions, changes, and refunds in different orders, I’d consider model-directed orchestration. It saves wiring a branch for every valid conversation. It also shifts work toward evaluating realistic conversations, tracing model-selected calls, and testing the execution checks around state-changing tools.
I’d use five questions to make that choice for a specific workflow.
| Question | What to look for |
|---|---|
| Does execution order matter? | Enforce dependencies such as successful booking before issuing a receipt. |
| How much flexibility does the task require? | Identify where travelers can change dates, destinations, or the operation they want. |
| What happens if the model chooses the wrong tool? | Decide what arguments, permissions, and authorization Python must verify before execution. |
| How difficult will failures be to investigate? | Make it possible to reconstruct what tools were available, what the model proposed, and why the application accepted or rejected the call. |
| How often will the workflow change? | Put stable requirements in explicit transitions and account for the cost of maintaining branches for legitimate variation. |
I’d delegate the decisions that need to adapt to the conversation and encode the ones the application has to enforce. The traveler can change their mind about London whenever the workflow supports it. The rules for which flight gets booked, and when a cancellation can run, should be precise enough for a developer to test.