Agents & tool use: ReAct, function calling, MCP
Turn an LLM into an agent that acts: the observe–think–act loop, ReAct, function calling with JSON schemas, the Model Context Protocol, memory and planning, how to evaluate agents, and how to keep them safe.
On its own, an LLM can only produce text. Give it tools — web search, a code interpreter, a database, a calendar API — and a loop that feeds tool results back, and it becomes an Agent (LLM agent): a system that decides which actions to take, observes the outcome, and keeps going until the task is done. Tool use is what lets assistants book meetings, fix bugs in a repository, or answer questions using live data.
Workflows vs. agents
Not every LLM application needs an autonomous agent. Workflows orchestrate LLM calls along predefined code paths — prompt chaining, routing to specialized prompts, running steps in parallel. Agents let the model decide the steps dynamically. Agents handle open-ended tasks but cost more, are slower and are harder to test; a common recommendation is to start with the simplest design that works and add autonomy only when it clearly helps[6].
- a_t
- action at step t: a tool call (name + JSON arguments) or a final answer
- LLM(context_t)
- one model call on the current context
- o_t
- observation: what the tool returned
- execute(a_t)
- your code validating and running the requested tool
- context_{t+1}
- the context for the next step (it only grows)
- ⊕
- append (concatenate) to the message history
- max_steps
- a hard limit on the number of iterations
▸Worked example
ReAct: reasoning + acting
Yao et al. showed that interleaving free-text reasoning (“Thought”) with actions (tool calls) and observations (tool results) beats both reasoning-only and acting-only prompting on question answering and interactive tasks: reasoning helps plan and handle exceptions, actions fetch real information that reduces hallucination[1]. Toolformer showed that a model can even learn by itself, in a self-supervised way, when to call APIs like a calculator or search engine[2].
Question: Is it likely to rain in Bandung tomorrow, and should I move my 10:00 outdoor meeting?
Thought: I need tomorrow's forecast for Bandung and my calendar.
Action: get_forecast(city="Bandung", day="tomorrow")
Observation: {"rain_probability": 0.8, "rain_hours": "09:00-13:00"}
Thought: 80% chance of rain during the meeting. Check the calendar.
Action: find_event(query="outdoor meeting", day="tomorrow")
Observation: {"id": "evt_42", "start": "10:00", "location": "Taman kampus"}
Thought: Recommend moving it; do not change the calendar without confirmation.
Final Answer: Rain is likely (80%, 09:00-13:00). I suggest moving "evt_42" indoors or to 14:00. Shall I update it?Function calling, step by step
- You describe each tool: a name, a clear description (when to use it), and parameters as a JSON Schema.
- The model decides whether to answer directly or to emit a structured tool call (tool name + JSON arguments).
- Your code validates the arguments and executes the function. The model never runs anything itself.
- You append the result as a tool message and call the model again.
- Repeat until the model produces a final answer — or you hit a step, time or cost limit[4].
import json
from openai import OpenAI
client = OpenAI()
tools = [{
"type": "function",
"function": {
"name": "get_forecast",
"description": "Weather forecast for a city. Use for any question about rain or temperature.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"},
"day": {"type": "string", "enum": ["today", "tomorrow"]}},
"required": ["city", "day"],
},
},
}]
def get_forecast(city, day):
return {"city": city, "day": day, "rain_probability": 0.8} # call a real API here
messages = [{"role": "user", "content": "Besok di Bandung hujan nggak?"}]
for step in range(6): # max_steps guard
msg = client.chat.completions.create(model="MODEL_NAME", messages=messages,
tools=tools, temperature=0).choices[0].message
messages.append(msg)
if not msg.tool_calls: # final answer
print(msg.content)
break
for call in msg.tool_calls:
args = json.loads(call.function.arguments) # validate before executing!
result = get_forecast(**args)
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result)})The Model Context Protocol (MCP)
Every app used to wire up tools in its own way. The Model Context Protocol is an open standard, introduced by Anthropic in late 2024 and since adopted widely, for connecting LLM applications to tools and data[3]. An MCP host (a chat app, IDE or agent) runs clients that connect to MCP servers; each server exposes tools (functions the model can call), resources (data such as files or records) and prompts (reusable templates). Messages use JSON-RPC 2.0 over stdio (local) or HTTP (remote). Write a server once — for your database, ticketing system or internal API — and any MCP-compatible host can use it.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("library")
@mcp.tool()
def search_books(query: str, limit: int = 5) -> list[dict]:
"""Search the library catalogue by title or author."""
return [{"title": "Laskar Pelangi", "author": "Andrea Hirata"}][:limit]
@mcp.resource("library://opening-hours")
def opening_hours() -> str:
"""Opening hours of the library."""
return "Mon-Fri 08:00-20:00, Sat 09:00-14:00"
if __name__ == "__main__":
mcp.run() # stdio transport: a host app launches this processMemory, planning and multiple agents
- Short-term memory is the conversation in the Context window. Long tasks overflow it, so agents summarize old steps or drop verbose tool outputs.
- Long-term memory lives outside the model: notes files, a database, or a vector store searched like RAG.
- Planning: plan-then-execute, explicit to-do lists, and self-reflection (“check your result against the goal”) reduce wandering.
- Multi-agent setups (an orchestrator delegating to specialized workers) can parallelize research or coding, at a multiple of the token cost and with new coordination failures.
- What it is
- Maximum number of loop iterations (tool calls) before the agent must stop.
- ↑ If you increase it
- Can finish longer, harder tasks; but runaway loops cost more and errors compound over more steps.
- ↓ If you decrease it
- Cheap and predictable; complex tasks get cut off before completion.
- Typical values
- 5–15 for assistants; 50+ for coding/research agents, always with cost and time budgets.
- What it is
- How many tool definitions are put in the model’s context.
- ↑ If you increase it
- More capabilities; but tool descriptions eat tokens and similar tools confuse the model, so wrong-tool calls rise.
- ↓ If you decrease it
- Sharper, more reliable selection; may lack the tool needed for some requests.
- Typical values
- A handful to a few dozen well-described tools; route or load tools dynamically beyond that.
- What it is
- Sampling randomness for the agent’s decisions and arguments.
- ↑ If you increase it
- More exploration of alternative approaches; also more malformed arguments and inconsistent runs.
- ↓ If you decrease it
- Reproducible, precise tool calls; can get stuck retrying the same failing action.
- Typical values
- 0–0.3 for tool-calling agents.
- What it is
- How much conversation and tool output you keep in the prompt (full history, truncation, or summaries).
- ↑ If you increase it
- The agent remembers more detail; cost per step grows with every turn and important facts can get buried.
- ↓ If you decrease it
- Cheaper, faster steps; risk of forgetting earlier results and repeating work.
- Typical values
- Keep the task, plan and recent steps verbatim; summarize or trim old, large tool outputs.
Evaluating agents
Agents fail in more ways than chatbots: wrong tool, wrong arguments, loops, giving up early, or “succeeding” in a way that breaks something. Errors also compound: with 95% success per step, a 20-step task succeeds only about 36% of the time.
- P(task)
- probability that the whole multi-step task succeeds
- p_step^n
- per-step success rate raised to the number of steps n (assumes independent steps)
- pass^k
- probability that the agent succeeds on all k independent trials of the same task
- p^k
- single-trial success rate p raised to k
▸Worked example
- Task success rate on realistic tasks with automatic checkers, e.g. SWE-bench, where an agent must resolve real GitHub issues and the repository’s tests decide success[5].
- Reliability: run each task several times; report pass@k (any success) *and* pass^k (all succeed) — users experience the latter.
- Trajectory quality: correct tool choices and arguments, number of steps, unnecessary actions.
- Cost and latency per task, and safety violations (actions taken without required confirmation).
- Run evals in sandboxed environments with resettable state so results are repeatable.
▸Go deeper: designing good tools
- Name and describe tools for a reader with no context: what it does, when to use it, what it returns, an example call.
- Prefer a few high-level tools (
schedule_meeting) over many low-level ones (list_users,list_events,create_event) when the workflow is predictable. - Return concise, relevant output and helpful error messages (“date must be YYYY-MM-DD”) — the model reads them to recover.
- Make actions idempotent where possible so a retried call does not double-charge or double-send.
Quiz
References
- [1]ReAct: Synergizing Reasoning and Acting in Language ModelsPaperYao et al.2023arxiv.org
- [2]Toolformer: Language Models Can Teach Themselves to Use ToolsPaperSchick et al.2023arxiv.org
- [3]Model Context Protocol — documentation and specificationDocsModel Context Protocolmodelcontextprotocol.io
- [4]Function calling guideDocsOpenAIdevelopers.openai.com
- [5]SWE-bench: Can Language Models Resolve Real-World GitHub Issues?PaperJimenez et al.2024arxiv.org
- [6]Building effective agentsArticleAnthropic2024anthropic.com