The Future of NLP: Agents, Tool Use, and World Models
Module: Natural Language Processing | Difficulty: Advanced
What You'll Learn
- 1Write the observe, reason, act loop that defines a language agent
- 2Compute how per step reliability compounds across multi step tasks
- 3Explain how tool selection is scored and how memory is queried
- 4Describe what a world model predicts and why planning needs one
Language models answer in one shot. Agents decompose a task, call external tools, read the result, and decide what to do next until the goal is met. The open questions are how to plan reliably, choose tools, and connect language to environments that push back.
The Agent Loop
An agent is a model plus tools plus memory, driven by a loop. At each step the agent observes an environment state, produces a reasoning trace, selects an action, and appends the observation to its history.
Early evidence came from Toolformer (Schick et al., 2023), which taught a model to insert API calls, and ReAct (Yao et al., 2022), which showed that interleaving thoughts with actions lowers hallucination on Fever and multi hop question answering, because a Wikipedia lookup can correct a guess before it becomes an answer.
This product rule is the reason agents are hard: each individual call can be strong while the whole trajectory is not. Planning is search over the same action space, maximizing discounted reward:
Tool Selection and Memory
Tools are described in text, so choosing one is a retrieval problem: score the query against each tool description and take a softmax. ToolBench (Qin et al., 2023) reports that a clear name and description raise accuracy more than adding another hundred tools, which is why tool documentation is now written for a model rather than for a human.
Memory works the same way: short term context lives in the prompt, while long term memory is a store queried by similarity, as MemGPT does when paging records between context window and external storage:
World Models and Grounding
A world model predicts what an action will do before it is taken: . Agents trained with one plan by imagining rollouts instead of executing every candidate, as in Dreamer style agents, while Voyager accumulates a skill library in Minecraft rather than re planning each episode.
| Benchmark | Task shape | What it stresses |
|---|---|---|
| GAIA | General assistant questions with tool use | Trailing hops, browsing, arithmetic |
| WebShop | Simulated shopping site, reward per episode | Navigation and preference matching |
| ALFWorld | Six household task types in text | Long horizon instructions |
| SWE-bench Verified | 500 human validated GitHub issues | Real code edits and tests |
GAIA illustrates the gap: when it was introduced, people solved more than 90 percent of level 1 questions while GPT-4 with plugins solved about 15 percent, and humans averaged a reward near 78 on WebShop while agents sat well below it. SWE-bench Verified keeps 500 human validated issues, so a resolve rate is a claim about real repository changes rather than paraphrase.
Grounding remains the theoretical gap. Symbols acquire meaning through contact with perception and action rather than through other symbols, so a model trained on text alone can recombine mentions of fire without knowing what fire does. World models and embodied environments are the proposed answers; Bender and Koller argue that scaling text does not close the gap.
Worked Code
The first program is a ReAct style loop with a deterministic stand in for the model: it chooses an action from the observation, executes a real tool, and stops with an answer.
import re
TOOLS = {"lookup": {"springfield": 116_000, "shelbyville": 42_000}}
def calculator(expr):
if not re.fullmatch(r"[0-9+\-*/(). ]+", expr):
raise ValueError("unsafe expression")
return eval(expr, {"__builtins__": {}}, {})
def tool_call(name, arg):
if name == "calc":
return calculator(arg)
if name == "lookup":
return TOOLS["lookup"].get(arg.lower(), "unknown")
raise ValueError("no such tool: " + name)
def policy(obs, step):
if "population" in obs and "springfield" in obs and step == 0:
return "thought", "I need the population before multiplying"
if step == 1:
return "act", "lookup:springfield"
if step == 2:
return "act", "calc:116000 * 3"
return "answer", "348000"
def react(task, max_steps=6):
history, obs = [], task
for step in range(max_steps):
kind, payload = policy(obs, step)
history.append((kind, payload))
if kind == "answer":
return payload, history
if kind == "act":
name, arg = payload.split(":", 1)
obs = str(tool_call(name, arg))
history.append(("observe", obs))
return None, history
answer, trace = react("What is three times the population of Springfield?")
for kind, payload in trace:
print(kind + ":", payload)
print("answer:", answer)
The second program builds an explicit world model, plans with breadth first search, and evaluates the plan with discounted reward.
from collections import deque
GOAL = (3, 3)
ACTIONS = {"up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1)}
WALLS = {(1, 1), (2, 1)}
def world_model(state, action):
drow, dcol = ACTIONS[action]
nxt = (state[0] + drow, state[1] + dcol)
if not (0 <= nxt[0] < 4 and 0 <= nxt[1] < 4) or nxt in WALLS:
return state, -0.1
return nxt, -0.1 + (1.0 if nxt == GOAL else 0.0)
def plan(start, gamma=0.9):
queue = deque([(start, [], 0.0)])
seen = {start}
while queue:
state, path, value = queue.popleft()
if state == GOAL:
return path, round(value, 3)
for action in ACTIONS:
nxt, reward = world_model(state, action)
if nxt not in seen:
seen.add(nxt)
queue.append((nxt, path + [action], reward + gamma * value))
return [], 0.0
path, value = plan((0, 0))
print("plan:", " -> ".join(path) if path else "unreachable")
state = (0, 0)
total = 0.0
for i, action in enumerate(path):
state, reward = world_model(state, action)
total += (0.9 ** i) * reward
print("executed:", state, "discounted reward:", round(total, 3))
print("sticking at start costs:", round(-0.1 * len(path), 3))
Real-World Applications
- Software maintenance: agents edit files and run tests until the patch passes, which is the setting SWE-bench Verified grades.
- Operations: an agent queries metrics and logs before proposing a rollback, with a human on the final action.
- Customer workflows: booking and refund flows chain several authenticated calls, where the product rule above is the acceptance criterion.
đĄGrade trajectories, not just answers
Common Mistakes
Adding tools without distinct descriptions
Fix: Write descriptions with different verbs so the selection softmax separates them
Relying on long context as memory
Fix: Store durable facts externally and retrieve them, as MemGPT does
Reporting only final answer accuracy
Fix: Report trajectory validity, step level success, and cost per task
Best Practices
- Bound the loop with a step budget and a verified stop condition
- Give every tool a strict schema and validate arguments before execution
- Re plan when an observation contradicts the current plan instead of continuing
Key Takeaways
- An agent interleaves reasoning with tool calls, using each observation in later steps
- Per step reliability multiplies, so eight steps at 0.93 succeed only 56 percent of the time
- Tool choice is a softmax over description similarity, so wording is a modeling decision
- A world model predicts next state and reward, enabling planning by imagined rollout
Frequently Asked Questions
Why not solve everything with a longer context?
Context grows cost and distracts the model with stale steps. Tools return fresh evidence, and external memory keeps the prompt short.
What distinguishes an agent from a chain prompt?
A fixed chain runs the same steps every time; an agent branches when an observation changes the plan or ends the episode.
Is a world model required for planning?
Not strictly, since search can call the environment directly. A learned model makes planning cheap when actions are slow or irreversible.
Interview Questions
Q1: Why does multi step tool use reduce hallucination?
The agent verifies a fact with an observation before asserting it, so claims anchor to evidence rather than parametric memory
Q2: How would you evaluate an agent you ship?
A fixed benchmark plus trajectory logging: end to end success, step validity, cost, and safety on blocked actions
Q3: What does a world model add over retrieval?
Retrieval describes what is true now; a world model predicts what becomes true after an action