Tool use and agents
Let a model call functions, loop over tool results like an agent, and keep that loop safe.
- Follow the tool-calling loop between an app and a model
- Validate and dispatch tool calls safely
- Bound an agent loop and require confirmation for risky actions
An LLM can only produce text - but that text can be a structured request to call a tool. The application describes available tools (name, description, JSON schema for arguments); the model replies with a tool call; your code runs the function and sends the result back; the model continues. Protocols like MCP standardize how tools are offered.
An agent is that loop running until the task is done: the model plans, calls tools, reads results and decides what next - searching, editing files, running tests.
Try it
One tool call, step by step
Follow a weather question through the tool-calling loop. Predict the marked steps.
1import json
2TOOLS = {"add": lambda a, b: a + b}
3call = json.loads('{"tool": "add", "arguments": {"a": 2, "b": 3}}')
4print(TOOLS[call["tool"]](**call["arguments"]))5
Key takeaways
Models request tool calls as structured text; applications execute them.
An agent loops: think, call tools, read results, repeat - until done or stopped.
Validate arguments, cap steps, least privilege, confirm risky actions, distrust tool output.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Python
Write Python in the editor and run it against sample inputs. Python runs locally in your browser using a WebAssembly runtime.
Dispatch tool calls safely
Each line is a JSON tool call {"tool": ..., "arguments": {...}}. Only add(a, b) (two numbers) and get_forecast(city) (from the FORECASTS table) exist. Print the result, or error: unknown tool NAME, error: bad arguments (wrong names or types), or error: no forecast for CITY.
- Five calls
Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.
Run a bounded agent loop
Line 1 is the step limit. Each following line is the model’s next reply, as JSON: either {"tool": "search", "query": "..."} or {"answer": "..."}. Run the loop:
- for a search, look the query up in
INDEX(orno results) and printstep N: search(QUERY) -> RESULT; - for an answer, print
answer: TEXTand stop; - if the step limit is reached before an answer, print
stopped: step limit reached.
- Answers in time
- Runs out of steps
Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…