Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

CODING CHALLENGE · N°16

Parse a Tool Call

Medium AI EngineeringAgentsTool Calling

When a model wants to act, it emits a tool call like search(query=cats, limit=5). Before your harness can run it, you have to parse that string into a name and typed arguments. Build the little parser that turns a model's intent into a dispatchable call.

The problem

Implement parse_tool_call(s). The input is a call of the form name(k1=v1, k2=v2, …). Return a dict with the function name and an args dict of its keyword arguments. Strip surrounding quotes from string values, and convert values that are whole integers (optionally negative) to int. A call with no arguments — now() — has an empty args dict.

SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? open the hints under the problem, or Reveal solution is one click away.

YOUR TASK

Implement parse_tool_call(s) — split a name(k=v, …) call string into {name, args}, unquoting strings and converting integer values.

CPython · WebAssembly
Examples and constraints 5 examples
EXAMPLE 1
Input search(query=cats, limit=5)
Output {'name': 'search', 'args': {'query': 'cats', 'limit': 5}}
limit becomes an int
EXAMPLE 2
Input now()
Output {'name': 'now', 'args': {}}
no arguments
EXAMPLE 3
Input calc(x=-3)
Output {'name': 'calc', 'args': {'x': -3}}
negative integers parse too
EXAMPLE 4
Input send(to="a@b.com")
Output {'name': 'send', 'args': {'to': 'a@b.com'}}
surrounding quotes are stripped from string values
EXAMPLE 5
Input f(expr=a=b)
Output {'name': 'f', 'args': {'expr': 'a=b'}}
edge case: only the first = separates the key from the value
CONSTRAINTS
  • The name is everything before the first (; the arguments are between the outer parentheses.
  • Split arguments on commas and each key=value on the first =; trim whitespace.
  • Strip a single layer of surrounding single or double quotes from values.
  • Convert values matching an optional - followed by digits to an integer; leave everything else as a string. (Test inputs have no commas inside values.)
Hints 4 ideas
HINTS — 4 IDEAS
  1. name = the text before the first "("; inner = the text between the first "(" and last ")".
  2. If inner is empty, args is {} — return early-ish.
  3. For each comma-separated part, split once on "=" into key and value, and strip whitespace.
  4. Strip surrounding quotes; if the value is all digits (allowing a leading "-"), int() it.
Approach, complexity & discussion — open after you solve

Start from brute force

The tempting shortcut is to let the language parse it: define a stub such as def search(**kw): return kw and call eval(s). For well-formed Python-style input the interpreter does all the splitting, in O(n) time and space. It is wrong twice. The first example’s query=cats is a bare word, so eval raises NameError instead of returning the string 'cats'. Worse, eval runs whatever the model wrote: an argument such as __import__('os').system(…) executes a shell command with your program’s permissions before any check can run. Model output is untrusted input; it must be parsed, never executed.

The approach

The call grammar is flat: a name, one pair of parentheses, and comma-separated key=value pairs. So four delimiters do all the work: the first ( ends the name, the last ) ends the arguments, commas separate pairs, and the first = in each pair separates key from value. Splitting only on the first = keeps a=b intact as a value, and slicing to the last ) keeps g(1) intact.

The reference strips s, takes name = s[:s.index("(")] and inner = s[s.index("(") + 1:s.rindex(")")], and returns an empty args when inner.strip() is empty, which covers now(). Otherwise each part of inner.split(",") goes through k, v = part.split("=", 1); both sides are stripped and v.strip('"').strip("'") removes the quotes. A value that passes v.lstrip("-").isdigit() becomes int(v); anything else stays a string. The types come from each value’s shape, not from a schema.

search(index 6query=1st =cats,split(',')limit=1st =5)rindex 26name: "search"query: 'cats' strlimit: 5 intfirst ( ends the name, last ) ends the args, first = splits each pair'5' passes lstrip('-').isdigit(), so it becomes the int 5
The first example cut at its four kinds of delimiter (highlighted). The parser keeps no state beyond two positions, the first ( and the last ); everything between them is split on commas, and each piece on its first =. The type of each value is decided by its shape alone: cats stays a string, 5 becomes an integer.

Walk through an example

Trace the first example, parse_tool_call("search(query=cats, limit=5)"), one line of the reference per row.

stepcoderesult
1s.index("(")6, so name = "search"
2s.rindex(")")26, so inner = "query=cats, limit=5"
3inner.split(",")["query=cats", " limit=5"]
4part.split("=", 1) on "query=cats"k = "query", v = "cats": not digits, stays a string
5part.split("=", 1) on " limit=5"k = "limit", v = "5": digits, becomes 5
6return{"name": "search", "args": {"query": "cats", "limit": 5}}

Complexity

Optimal: O(n) time, because index, rindex, split and strip each scan the string a constant number of times, and O(n) space for the substrings and the args dict. Brute force (eval): O(n) to parse, but evaluating untrusted code has no bound on time, memory or side effects.

Edge cases to test

  • Quoted numbers become integers: f(zip="02134") → {'zip': 2134} in both languages, because the quotes are removed before the integer check, so the leading zero is lost.
  • A comma inside a quoted value: search(query="cats, dogs") makes Python raise ValueError, since the second piece has no =, while the TypeScript reference returns {'query': 'cats', 'dogs': 'dogs'}, an argument the model never sent.
  • Repeated quotes: Python’s strip('"') removes every quote character at each end, so f(x=""a"") gives 'a', while the TypeScript regex removes one character per side and gives '"a"', which is what the constraint’s “single layer” describes.
  • A double minus: f(x=--5) raises ValueError in Python, because lstrip("-") removes both dashes before isdigit() and then int("--5") fails; the TypeScript regex ^-?\d+$ keeps it as the string '--5'.
  • Malformed calls: now with no parentheses raises ValueError from s.index("("), and so does the trailing comma in f(a=1,). TypeScript’s indexOf returns -1 instead of raising, so the same inputs give {'name': 'no', 'args': {'n': 'no'}} and an extra empty-string key.
  • An = or parentheses inside a value are fine: f(expr=a=b) → {'expr': 'a=b'} and f(x=g(1)) → {'x': 'g(1)'}, thanks to split("=", 1) and rindex(")").

Common mistakes

  • Assuming the call is always well-formed. Models emit truncated calls, stray commas and unbalanced quotes, and this split-based parser raises ValueError on all of them, so catch it and report a parse error instead of crashing the agent loop.
  • Splitting each pair on every = instead of the first one, which breaks any value that contains an equals sign.
  • Skipping the empty-arguments check: "".split("=", 1) yields a single piece, so now() crashes on the unpacking unless that case returns early.
  • Executing the parsed call without checking the name against the registered tools and the arguments against the tool’s parameters, so a hallucinated tool or argument reaches real code.

Follow-ups an interviewer asks next

Real APIs return tool arguments as JSON. What changes?
The splitting goes away: OpenAI returns arguments as a JSON string, and Anthropic returns input as an already-parsed object. Parse the string with json.loads inside a try, validate the result against the tool’s JSON Schema, and on any failure send the error back to the model as the tool result so it can correct the call, rather than raising.
How would you support commas inside quoted values?
Replace split(",") with a one-pass scanner that tracks whether it is inside quotes, which quote character opened them, backslash escapes and parenthesis depth, and splits only on commas outside all of them. It stays O(n). Python’s ast.parse(s, mode="eval") is another option: it builds a syntax tree without executing anything, though it rejects input that is not valid Python.
How would you give the arguments their correct types?
Stop guessing from shape. Look up each parameter’s declared type in the tool’s schema: convert to an integer only where the schema says integer, keep "02134" as a string where it says string, parse true and false only for booleans, and reject unknown keys and missing required ones, collecting every problem into one message for the model.
What if the model emits several calls, or streams one?
Treat a call as complete only when its closing parenthesis arrives outside any quotes; buffer the partial text until then and never act on a prefix. With several complete calls, check whether they depend on each other: independent ones can run in parallel, and each result goes back to the model tagged with the call it answers.

Where this shows up

This is the exact boundary between model and harness in every agent: the model proposes a typed call, your code validates and runs it. Robust parsing and schema-validation here is what stops a hallucinated or malformed call from crashing the loop or doing something unintended — the airlock of tool use. Production APIs usually deliver the arguments as JSON rather than k=v text, but the discipline is the same: parse, check, then run.

Text-format calls have not gone away. When a model is prompted to act without a native tool-calling API, or a smaller self-hosted model is asked to follow a tool format written in the prompt, the call arrives embedded in ordinary output and the harness has to find and parse it, exactly as here. A production harness wraps this parser in four checks: the name must be on an allow-list of registered tools; every argument must match the declared parameter and type; the raw string is logged next to the parsed result, so a bad call can be replayed while debugging; and any failure goes back to the model as a short, specific error message (“unknown argument limt; did you mean limit?”) instead of an exception that ends the run. That last step matters most, because a model given a precise error can often repair the call on its next turn, while an exception gives it nothing to work with.

Check yourself

Predict parse_tool_call("book(city='Paris', nights=3, adults=-2)").

{'name': 'book', 'args': {'city': 'Paris', 'nights': 3, 'adults': -2}}. The single quotes are stripped from 'Paris', 3 is all digits, and -2 passes once lstrip("-") removes its sign, so both numbers become integers.

What does parse_tool_call("f(price=4.50, qty=3)") return, and why might that hurt downstream?

{'name': 'f', 'args': {'price': '4.50', 'qty': 3}}. The dot makes isdigit() false, so the price stays the string '4.50' while the quantity is an int. A tool that multiplies them gets a type error, or in JavaScript a silent string-to-number coercion; schema-driven typing fixes this.

A variant ends the arguments at the first ) instead of the last. What does it return for f(x=g(1), y=2)?

{'name': 'f', 'args': {'x': 'g(1'}}, with no error. The inner text is cut at the ) inside g(1), so x loses its parenthesis and y disappears entirely. The reference’s rindex(")") returns {'x': 'g(1)', 'y': 2}. A silent wrong answer is worse than the crash a malformed call usually causes.

Another variant splits each pair with part.split("=") instead of part.split("=", 1). What happens on f(expr=a=b)?

Python raises ValueError: too many values to unpack (expected 2), because the piece splits into three parts. The maxsplit of 1 is what lets a value carry its own =, which is common in model output such as URLs with query strings or equations.

Reference solution

Reference solution — Python
def parse_tool_call(s):
    s = s.strip()
    name = s[:s.index("(")]
    inner = s[s.index("(") + 1:s.rindex(")")]
    args = {}
    if inner.strip():
        for part in inner.split(","):
            k, v = part.split("=", 1)
            k = k.strip()
            v = v.strip().strip('"').strip("'")
            if v.lstrip("-").isdigit():
                v = int(v)
            args[k] = v
    return {"name": name, "args": args}


print(parse_tool_call("search(query=cats, limit=5)"))
# -> {'name': 'search', 'args': {'query': 'cats', 'limit': 5}}
Reference solution — TypeScript
type ToolCall = { name: string; args: Record<string, string | number> };

function parseToolCall(s: string): ToolCall {
  s = s.trim();
  const name = s.slice(0, s.indexOf("("));
  const inner = s.slice(s.indexOf("(") + 1, s.lastIndexOf(")"));
  const args: Record<string, string | number> = {};
  if (inner.trim()) {
    for (const part of inner.split(",")) {
      const eq = part.indexOf("=");
      const k = part.slice(0, eq).trim();
      const v = part.slice(eq + 1).trim().replace(/^["']|["']$/g, "");
      args[k] = /^-?\d+$/.test(v) ? parseInt(v, 10) : v;
    }
  }
  return { name, args };
}

console.log(parseToolCall("search(query=cats, limit=5)"));
// -> { name: 'search', args: { query: 'cats', limit: 5 } }

Questions about Parse a Tool Call

How do you parse a function call string in Python without eval?

For a flat call such as search(query=cats, limit=5), plain string operations are enough: the name is everything before the first opening parenthesis, the arguments sit between that parenthesis and the last closing one, commas separate the arguments, and the first equals sign in each separates the key from the value. Then strip quotes and convert integer-looking values. If the input is valid Python syntax, the ast module can parse it into a tree with ast.parse in eval mode, which reads the structure without executing anything. What you should never do with model output is pass it to eval or exec.

Why is using eval on an LLM tool call dangerous?

Because eval executes the string as code, and a model’s output is untrusted input: it can be steered by prompt injection from a web page, an email or a document the model read. A call whose argument imports the os module and runs a shell command would execute that command with your program’s permissions before any validation happens. Even without an attacker, eval fails on harmless input such as an unquoted word, which it treats as a variable name. Parsing turns text into data you can inspect; evaluating hands the text control of your process.

How do LLM tool calls work?

The model never runs anything itself. Your application describes the available tools, each with a name, a description and its parameters, and when the model decides a tool would help, it replies with a structured request naming the tool and the arguments to pass. Your harness parses that request, checks it, runs the real function, and sends the result back to the model in the next message, and the model continues from there. Parsing is the boundary step: it is where free-form model output becomes a typed call your code can trust or reject.

Should a tool call parser convert numbers automatically?

Only when it knows the intended type. Guessing from the shape of the value, as this challenge does, is convenient for simple cases, but it is lossy: a quoted zip code such as 02134 becomes the integer 2134 and loses its leading zero, and an id that happens to be all digits stops being a string. Production harnesses use the tool’s declared parameter schema instead, converting a value to an integer only where the schema says integer, and reporting a clear error for anything that does not fit.

Finished this one? 0 / 76 Challenges done
NextRun the Goal Loop Next on the “Agents & loop engineering” ladder · rung 4 of 9

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Challenges