Capability Frontiers › Code Implementation
Language AI HandbookAll chapters Capability Frontiers › Code ImplementationOne section · Sections in this chapter9 / 11 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
This section demonstrates several of the capability concepts discussed above through concrete implementation examples. We will explore in-context learning, chain-of-thought prompting, and tool-augmented reasoning using simulated environments so that the code runs without requiring API access.
Simulating In-Context Learning
In-context learning can be studied in miniature by examining how a model's behavior changes as more examples are added to the context. We will build a simple demonstration using a k-nearest-neighbor classifier that approximates the mechanics of in-context pattern matching. The key idea is that adding more examples to the context gives the learner more information about the task distribution, which reduces uncertainty and improves accuracy, exactly as adding more in-context examples helps a language model characterize the target task.
from collections import Counter
import numpy as np
# Simulate in-context learning with a simple k-NN model
# The "context" is the set of examples provided before the test query
def knn_predict(examples, query, k=3):
"""
Classify query using k nearest neighbors from examples.
Mimics in-context learning: more examples = richer context.
"""
if not examples:
# No examples: return random guess
return np.random.choice(["positive", "negative"])
X = np.array([ex["embedding"] for ex in examples])
y = [ex["label"] for ex in examples]
# Compute distances
distances = np.linalg.norm(X - query, axis=1)
sorted_idx = np.argsort(distances)
# Get k nearest neighbors
k_actual = min(k, len(examples))
neighbors = [y[i] for i in sorted_idx[:k_actual]]
# Majority vote
vote = Counter(neighbors).most_common(1)[0][0]
return vote
np.random.seed(42)
# Create a simple 2D classification problem
# Positive class: centered at (1, 1)
# Negative class: centered at (-1, -1)
n_per_class = 50
pos_examples = [
{
"embedding": np.array([1.0, 1.0]) + np.random.randn(2) * 0.5,
"label": "positive",
}
for _ in range(n_per_class)
]
neg_examples = [
{
"embedding": np.array([-1.0, -1.0]) + np.random.randn(2) * 0.5,
"label": "negative",
}
for _ in range(n_per_class)
]
all_examples = pos_examples + neg_examples
# Test queries
test_queries = [
np.array([1.2, 0.9]) + np.random.randn(2) * 0.3 for _ in range(20)
]
test_labels = ["positive"] * 20
# Evaluate accuracy as a function of number of in-context examples
shot_counts = [0, 1, 2, 4, 8, 16, 32, 64]
accuracies = []
for n_shots in shot_counts:
ctx = all_examples[:n_shots]
correct = sum(
knn_predict(ctx, q) == lbl for q, lbl in zip(test_queries, test_labels)
)
accuracies.append(correct / len(test_labels))0-shot accuracy: 50% 1-shot accuracy: 100% 2-shot accuracy: 100% 4-shot accuracy: 100% 8-shot accuracy: 100% 16-shot accuracy: 100% 32-shot accuracy: 100% 64-shot accuracy: 100%
The accuracy rises quickly as examples are added, then levels off once the model has enough context to characterize the task. This mirrors the behavior observed in real in-context learning, where a few well-chosen examples often capture most of the benefit. The diminishing returns beyond a modest example count suggest that the bottleneck shifts from task characterization (which improves with each new example) to the model's intrinsic capability on the task (which does not change with context).

Simulating Chain-of-Thought Reasoning
Chain-of-thought prompting improves performance by externalizing intermediate steps. We can demonstrate the core mechanism with a simple arithmetic reasoning task: computing the result of a multi-step word problem.
The key insight is that breaking a problem into steps reduces the complexity of each individual step. Even a simple calculator-style model improves when given intermediate results rather than being asked to compute everything at once. In the simulation below, direct solving accumulates noise proportional to problem length (simulating how errors compound when all computation must happen "in one go"), while chain-of-thought keeps each step's noise small (simulating how externalizing intermediate state prevents error accumulation).
def solve_direct(problem_steps):
"""
Direct answer: try to compute the final answer in one step.
Simulates a model without chain-of-thought.
Introduces noise proportional to problem complexity.
"""
# Each step adds complexity and potential error
true_answer = sum(step["delta"] for step in problem_steps)
noise_std = len(problem_steps) * 2.0 # more steps = more error
answer = true_answer + np.random.randn() * noise_std
return round(answer)
def solve_chain_of_thought(problem_steps):
"""
Step-by-step answer: compute each step explicitly.
Simulates chain-of-thought: each step is independently (noisily) computed.
"""
running_total = 0
for step in problem_steps:
# Each individual step is computed with small noise
step_result = step["delta"] + np.random.randn() * 0.5
running_total += step_result
return round(running_total)
# Create word problems of varying complexity
def make_problem(n_steps):
deltas = np.random.randint(-20, 20, size=n_steps)
steps = [{"delta": int(d)} for d in deltas]
true_answer = int(deltas.sum())
return steps, true_answer
np.random.seed(0)
step_counts = [2, 3, 4, 5, 6, 8, 10]
n_trials = 200
results = {}
for n_steps in step_counts:
direct_correct = 0
cot_correct = 0
for trial in range(n_trials):
problem_steps, true_answer = make_problem(n_steps)
tol = max(1, abs(true_answer) // 10 + 1)
direct_answer = solve_direct(problem_steps)
cot_answer = solve_chain_of_thought(problem_steps)
if abs(direct_answer - true_answer) <= tol:
direct_correct += 1
if abs(cot_answer - true_answer) <= tol:
cot_correct += 1
results[n_steps] = {
"direct": direct_correct / n_trials,
"cot": cot_correct / n_trials,
} Steps Direct Chain-of-Thought Improvement
--------------------------------------------------
2 49.5% 99.5% +50.0%
3 37.5% 98.0% +60.5%
4 31.5% 95.5% +64.0%
5 24.0% 95.0% +71.0%
6 26.5% 95.5% +69.0%
8 14.5% 93.5% +79.0%
10 9.5% 84.0% +74.5%As expected, direct solving degrades sharply with problem complexity while chain-of-thought maintains higher accuracy across all step counts. The gap widens with longer reasoning chains. In real language models, the improvement is even more pronounced because the model can also use the verbalized intermediate steps to catch logical errors that would be invisible if computation were done implicitly.

Modeling Capability Emergence
The emergent capability phenomenon, where performance jumps at scale thresholds, can be visualized by modeling performance as a function of scale with a sigmoid transition curve. The model below represents two tasks that exhibit sharp emergence at different scale thresholds and one task that scales smoothly across all model sizes. This reflects the empirical finding that different capabilities have different scaling profiles, with some requiring a minimum capacity before they are exhibited at all.
import numpy as np
def emergent_performance(
log_params, threshold, sharpness, baseline=0.1, ceiling=0.9
):
"""
Models emergent capability: near-random performance below threshold,
rapid improvement around threshold, saturation above it.
"""
return baseline + (ceiling - baseline) / (
1.0 + np.exp(-sharpness * (log_params - threshold))
)
def smooth_performance(log_params, slope=0.08, baseline=0.3):
"""
Models a gradually scaling capability with no sharp threshold.
"""
return np.clip(baseline + slope * log_params, 0, 1)
log_params = np.linspace(
7, 12, 300
) # from ~10M to ~160B parameters (log10 scale)
# Three tasks: emergent at different thresholds, and one smooth scaler
tasks = {
"Task A (emergent, threshold=9)": emergent_performance(
log_params, threshold=9.0, sharpness=3.0
),
"Task B (emergent, threshold=10)": emergent_performance(
log_params, threshold=10.0, sharpness=4.0
),
"Task C (smooth scaling)": smooth_performance(log_params),
}
The chart illustrates why emergent capabilities are surprising and difficult to predict. Below the threshold, more compute produces almost no benefit on the emergent tasks. Above it, a relatively small increase in scale produces dramatic improvement. For researchers and engineers planning compute budgets, this profile is challenging: you cannot see the capability coming before you have crossed the threshold. Tasks A and B also demonstrate that different capabilities emerge at different scales, so a model that exhibits one emergent capability may not yet have crossed the threshold for another.
Tool-Augmented Reasoning
Tool use is one of the most practically important capability frontiers. We can demonstrate the pattern with a simple agent loop that decides when to call an external function and integrates the result. The key design elements are: the agent embeds structured tool calls within its output, an executor dispatches those calls to the appropriate functions, and results are returned and integrated into the agent's running context.
import re
# Simulated tools available to the agent
def calculator(expression):
"""Safely evaluate a simple arithmetic expression using operator decomposition."""
try:
# Support only simple two-operand arithmetic to avoid arbitrary execution
match = re.fullmatch(
r"\s*([+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?)\s*"
r"([+\-*/])\s*"
r"([+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?)\s*",
expression,
)
if match:
a, op, b = (
float(match.group(1)),
match.group(2),
float(match.group(3)),
)
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/" and b != 0:
return a / b
except Exception:
pass
return None
def lookup_fact(query):
"""Simulated knowledge base lookup."""
facts = {
"population of earth": 8_100_000_000,
"speed of light km/s": 299_792,
"pi": 3.14159265,
"avogadro number": 6.022e23,
}
return facts.get(query.lower().strip())
def agent_solve(problem, available_tools):
"""
Simple tool-use agent.
Parses structured tool calls from the problem string and executes them.
"""
tool_calls = []
for tool_name, pattern, func in available_tools:
for match_obj in re.finditer(pattern, problem, re.IGNORECASE):
arg = match_obj.group(1).strip()
result = func(arg)
if result is not None:
tool_calls.append(
{
"tool": tool_name,
"arg": arg,
"result": result,
}
)
return tool_calls
# Define tool dispatch
tools = [
("calculator", r"CALC\(([^)]+)\)", calculator),
("lookup", r"LOOKUP\(([^)]+)\)", lookup_fact),
]
# Sample problems with embedded tool calls
problems = [
"Speed of light: LOOKUP(speed of light km/s) km/s. "
"Seconds per year: CALC(3600 * 24) times CALC(365 * 1.0) = distance per year.",
"Earth population: LOOKUP(population of earth) people. "
"Divided equally among CALC(195 * 1.0) countries.",
"Pi value from lookup: LOOKUP(pi). Area of circle r=5: CALC(78.54 * 1.0).",
]Problem: Speed of light: LOOKUP(speed of light km/s) km/s. Seconds per year: CALC(3600 * ...
Tool: calculator('3600 * 24') => 8.64e+04
Tool: calculator('365 * 1.0') => 365
Tool: lookup('speed of light km/s') => 2.998e+05
Problem: Earth population: LOOKUP(population of earth) people. Divided equally among CALC...
Tool: calculator('195 * 1.0') => 195
Tool: lookup('population of earth') => 8.1e+09
Problem: Pi value from lookup: LOOKUP(pi). Area of circle r=5: CALC(78.54 * 1.0).
Tool: calculator('78.54 * 1.0') => 78.54
Tool: lookup('pi') => 3.142This simple loop illustrates the structure of tool-augmented agents: the model generates text that embeds structured tool calls, an executor dispatches those calls, and the results are returned to the model for integration. Real systems use the same pattern at much larger scale, with the model generating natural-language-style tool invocations that are parsed and dispatched. The critical advantage over pure language generation is grounding: tool results are correct by construction (assuming correctly implemented tools), so the model does not have to rely on internalized knowledge that might be outdated or wrong.

The benchmark chart reveals an important asymmetry in current capability profiles: models score very high on instruction following, in-context learning, and classical reasoning benchmarks, but substantially lower on multimodal reasoning tasks that require integrating visual and linguistic information. This uneven profile reflects both the maturity of different training paradigms and the fundamental difficulty of tasks that require grounded perception. Language-only capabilities have benefited from far more training compute and data curation effort than multimodal capabilities, and the gap in benchmark performance roughly tracks this difference in research investment.