Tool Masking with Context-Aware State Machines
Learn how to build a context-aware state machine that selects Auto, Required, or Specified tool modes for each turn. You’ll compare tool_choice masking with dropping tools, measure cache effects, preserve conversation history, and handle models that reject forced tool calls.
We'll cover the following...
In the previous lesson, we kept the start of every request identical so the provider could reuse its cache. The tools and the system prompt never changed. A real incident needs more control than that. On some turns, the assistant should be free to answer directly. On others, it must look something up before answering. And sometimes our code already knows exactly which tool comes next.
In this lesson, we’ll build a small state machine that picks one of three tool modes for each turn. We’ll see why the mode belongs in the tool_choice setting and never in the tool list, measure what each approach does to the cache, and handle models that don’t accept a forced tool call.
Three tool modes
LiteLLM’s tool_choice parameter, in the OpenAI format we’ve used all along, controls how the model may use the tools it’s given. We’ll use three modes:
Auto (
"auto"): The model may call any tool or answer with no tool call.Required (
"required"): The model must call a tool, but it can choose which one.Specified: The model must call one named tool, written as
{"type": "function", "function": {"name": ...}}.
Narrowing what the model may do on a turn, without changing the tool list, is often called tool masking. The tools stay defined. We just mask which ones the model may use right now. Manus, the agent company we mentioned in the previous lesson, described the same idea: keep tool definitions fixed and constrain the model’s choice per step instead.
Let’s write a function that turns a mode into the right tool_choice value, using the four tools from the previous lesson.
In the code above:
Line 3: We name the three modes as constants.
Line 4: We collect the names of the four defined ...