Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Parse a Tool Call
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.
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.
Implement parse_tool_call(s) — split a name(k=v, …) call string into {name, args}, unquoting strings and converting integer values.
Examples and constraints 5 examples
search(query=cats, limit=5){'name': 'search', 'args': {'query': 'cats', 'limit': 5}}now(){'name': 'now', 'args': {}}calc(x=-3){'name': 'calc', 'args': {'x': -3}}send(to="a@b.com"){'name': 'send', 'args': {'to': 'a@b.com'}}f(expr=a=b){'name': 'f', 'args': {'expr': 'a=b'}}- The name is everything before the first
(; the arguments are between the outer parentheses. - Split arguments on commas and each
key=valueon 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
- name = the text before the first "("; inner = the text between the first "(" and last ")".
- If inner is empty, args is {} — return early-ish.
- For each comma-separated part, split once on "=" into key and value, and strip whitespace.
- 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.
( 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.
| step | code | result |
|---|---|---|
| 1 | s.index("(") | 6, so name = "search" |
| 2 | s.rindex(")") | 26, so inner = "query=cats, limit=5" |
| 3 | inner.split(",") | ["query=cats", " limit=5"] |
| 4 | part.split("=", 1) on "query=cats" | k = "query", v = "cats": not digits, stays a string |
| 5 | part.split("=", 1) on " limit=5" | k = "limit", v = "5": digits, becomes 5 |
| 6 | return | {"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 raiseValueError, 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, sof(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)raisesValueErrorin Python, becauselstrip("-")removes both dashes beforeisdigit()and thenint("--5")fails; the TypeScript regex^-?\d+$keeps it as the string'--5'. - Malformed calls:
nowwith no parentheses raisesValueErrorfroms.index("("), and so does the trailing comma inf(a=1,). TypeScript’sindexOfreturns -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'}andf(x=g(1))→{'x': 'g(1)'}, thanks tosplit("=", 1)andrindex(")").
Common mistakes
- Assuming the call is always well-formed. Models emit truncated calls, stray commas and unbalanced quotes, and this split-based parser raises
ValueErroron 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, sonow()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
argumentsas a JSON string, and Anthropic returnsinputas an already-parsed object. Parse the string withjson.loadsinside atry, 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 staysO(n). Python’sast.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, parsetrueandfalseonly 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.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Challenges
- Retry with Exponential BackoffTools time out and APIs rate-limit — a production agent retries without hammering. Exponential backoff waits longer after each failure (1s, 2s, 4s, 8s…) up to a cap. Compute the delay schedule: delay[i] = min(cap, base·2ⁱ). Solve it in Python or TypeScript.Read →
- Trim History to a Token BudgetEvery agent turn re-sends the whole conversation, so history must fit the context budget. Keep the most recent messages that fit and drop the oldest — the trimmer at the heart of context management. Solve it in Python or TypeScript.Read →
- Run the Goal LoopThe engine of loop engineering: attempt the front task, let an independent verifier judge it, retry failures with state untouched, and stop when the goal is met — or loudly when the cap trips. Implement the whole outer loop as one pure, testable function. Solve it in Python or TypeScript.Read →
- Write a VerifierIn RL from verifiable rewards, the verifier IS the reward — and a gameable one is worse than none, because every false positive is a lie the model learns. Write a verifier a reward-hacking agent can’t fool: recompute the score from ground truth, demand exact task coverage, and compare types-intact. Solve it in Python or TypeScript, with hidden tests.Read →
- Build Your Own Agent LoopStrip an "AI agent" of its mystique and what’s left is a loop: read the model’s next move — tool call or final answer — run the tool, feed the observation back, repeat until it answers or the step cap trips. Implement the whole ReAct inner loop as one pure function. Solve it in Python or TypeScript, with hidden tests.Read →
- Re-Engineer a Legacy ETLYou inherit an aggregation nobody can explain and the totals are wrong. Three planted defects — an exclude-list where the spec wants an include-list, a dedupe key missing a field, and pre-seeded customers that should never appear. The FDE re-engineering round. Solve it in Python or TypeScript, with hidden tests.Read →