Math, Search and Algorithms for Agent Engineers
A small amount of mathematics answers everyday questions: is it better, what is similar, what to rank first and whether to act.
Agent engineers need a working grasp of a few ideas: uncertainty in measured pass rates, vectors and similarity, ranking for search, the cost of common data structures and algorithms, and expected cost for decisions. These explain why a test of ten cases proves little, why keyword and meaning search disagree, and when an agent should check or ask before acting.
What you will learn: probability and confidence intervals, embeddings and linear algebra basics, BM25 and vector retrieval, algorithms and data structures, and optimization and decision theory.
Prerequisites: school algebra and basic Python.
Probability in agent work
A language model can answer the same request differently on different runs, so quality is a rate, not a fact. A probability is a number from 0 to 1 describing how likely something is. A few ideas carry most of the weight.
| Idea | Meaning | Agent example |
|---|---|---|
| Rate | Successes divided by trials | Tasks completed correctly |
| Independent events | One does not change the chance of another | Often untrue: retries share the same cause |
| Compounding | Probabilities of required steps multiply | Ten steps at 95% give about 60% overall, if independent |
| Conditional probability | Chance given that something is known | Failure rate when the document is scanned |
| Base rate | How common something is to begin with | A good fraud detector still raises many false alarms when fraud is rare |
| Percentile | Value below which a share of results falls | The slowest 5% of requests |
The base-rate effect surprises people. Suppose 1 in 1,000 requests is malicious, a filter catches 99% of those and wrongly flags 1% of normal ones. Out of 100,000 requests it flags about 99 malicious and 999 harmless ones. Most alarms are false, even though both percentages sound excellent.
How sure are you?
A pass rate measured on a sample is an estimate. A confidence interval gives a range of plausible underlying values. The Wilson score interval behaves sensibly even when every test passes.
"""How sure can you be about a pass rate measured on a few test cases?"""
from math import sqrt
def wilson(passed, total, z=1.96):
"""95% score interval for a proportion."""
p = passed / total
scale = 1 + z * z / total
center = (p + z * z / (2 * total)) / scale
half = z * sqrt(p * (1 - p) / total + z * z / (4 * total ** 2)) / scale
return max(0.0, center - half), min(1.0, center + half)
for label, passed, total in [("10 of 10", 10, 10), ("100 of 100", 100, 100),
("old: 82/100", 82, 100),
("new: 88/100", 88, 100),
("old: 820/1000", 820, 1000),
("new: 880/1000", 880, 1000)]:
low, high = wilson(passed, total)
print(f"{label:<14} {passed / total:.0%} likely {low:.1%} to {high:.1%}")
# Chance that a test set misses a failure that happens 2% of the time
for n in (10, 50, 150):
print(f"{n:>3} cases: {0.98 ** n:.0%} chance of seeing no failure")
Output:
10 of 10 100% likely 72.2% to 100.0%
100 of 100 100% likely 96.3% to 100.0%
old: 82/100 82% likely 73.3% to 88.3%
new: 88/100 88% likely 80.2% to 93.0%
old: 820/1000 82% likely 79.5% to 84.3%
new: 880/1000 88% likely 85.8% to 89.9%
10 cases: 82% chance of seeing no failure
50 cases: 36% chance of seeing no failure
150 cases: 5% chance of seeing no failure
Ten successes out of ten are compatible with a true success rate in the low seventies. A move from 82 to 88 out of 100 leaves intervals that overlap widely, while the same rates on 1,000 cases separate clearly. The last lines show why rare failures hide: with a 2% failure rate, a ten-case test sees nothing most of the time. A useful shortcut, the rule of three, says that after n independent trials with no failures, an approximate 95% upper bound on the failure rate is 3 divided by n.
When two versions run on the same cases, compare them case by case: count how many were fixed and how many broke. A paired comparison is more sensitive than comparing two separate intervals. The intervals also assume that cases are independent and representative. A hundred paraphrases of one question are not a hundred pieces of evidence. See Golden Datasets, Synthetic Data and Simulation and Agent Evaluation Framework.
Try twenty prompt variants on one small test set and one will probably look better by chance. Confirm the winner on cases that played no part in choosing it.
Linear algebra you will actually use
An embedding turns text or an image into a list of numbers, a vector, so that items with related meaning tend to lie close together.
| Operation | Meaning | Note |
|---|---|---|
| Dot product | Multiply matching positions and add | Grows with vector length |
| Length (norm) | Square root of the dot product with itself | Used to normalize |
| Cosine similarity | Dot product divided by both lengths | Compares direction only |
| Euclidean distance | Straight-line distance | Ranks like cosine when vectors have length one |
| Matrix multiplication | Many dot products at once | The core of model computation |
| Dimension reduction | Fewer numbers per vector | Saves space, may lose distinctions |
Use the similarity measure that the embedding model's documentation recommends. A similarity score is not a probability of relevance, and scores from different models cannot be compared. Choose cut-off values from your own labeled examples.
Search fundamentals
Classic search builds an inverted index: for each word, the list of documents containing it. The BM25 formula then ranks documents by rewarding rare query words, counting repeats with diminishing returns and adjusting for document length. Vector search ranks by closeness in meaning.
"""BM25 keyword ranking and cosine similarity, from first principles."""
from collections import Counter
from math import log, sqrt
docs = {
"A": "refund policy refunds are paid within five days",
"B": "refund refund refund refund",
"C": "how to return a damaged item and get your money back " * 3,
"D": "office opening hours and holiday calendar",
}
tokens = {k: v.split() for k, v in docs.items()}
average = sum(map(len, tokens.values())) / len(tokens)
def bm25(query, doc, k1=1.2, b=0.75):
counts, score = Counter(tokens[doc]), 0.0
for term in query.split():
holding = sum(term in t for t in tokens.values())
idf = log(1 + (len(tokens) - holding + 0.5) / (holding + 0.5))
tf = counts[term]
norm = k1 * (1 - b + b * len(tokens[doc]) / average)
score += idf * tf * (k1 + 1) / (tf + norm)
return score
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
return dot / (sqrt(sum(x * x for x in a)) * sqrt(sum(y * y for y in b)))
for query in ("refund", "refund policy"):
ranked = sorted(docs, key=lambda d: -bm25(query, d))
print(f"{query!r}:", ", ".join(f"{d}={bm25(query, d):.2f}" for d in ranked))
# Hand-made 3-number "embeddings": (money, returns, calendar)
vectors = {"A": (0.9, 0.5, 0.0), "C": (0.6, 0.9, 0.0), "D": (0.0, 0.1, 0.9)}
question = (0.7, 0.8, 0.0)
for name, vector in sorted(vectors.items(),
key=lambda kv: -cosine(question, kv[1])):
print(f"meaning match {name}: {cosine(question, vector):.3f}")
Output:
'refund': B=1.33, A=0.82, C=0.00, D=0.00
'refund policy': A=2.24, B=1.33, C=0.00, D=0.00
meaning match C: 0.991
meaning match A: 0.941
meaning match D: 0.083
For the single word "refund", the keyword-stuffed document B outranks the real policy, although repetition earns less each time. Adding "policy" lifts A to the top because that word is rare in the collection. Document C is about returning goods and getting money back, yet scores zero in keyword search because it never uses the word. The hand-made vectors place it first by meaning. Real embeddings are produced by a model and have hundreds or thousands of dimensions, but the lesson holds: the two methods fail differently, which is why hybrid search is common. See Embeddings, Vector and Hybrid Search, Reranking.
| Retrieval measure | Answers |
|---|---|
| Recall at k | Was the needed item among the first k? |
| Precision at k | How many of the first k were relevant? |
| Mean reciprocal rank | How high was the first relevant item? |
| nDCG | Are the most relevant items ranked highest? |
Algorithms and data structures
Big O notation describes how work grows with input size. It explains why a design that works for a hundred items stalls at a million.
| Structure or method | Typical cost | Where it appears in agents |
|---|---|---|
| Hash map lookup | Constant on average | Caches, idempotency keys |
| Binary search in sorted data | Logarithmic | Finding a value by time |
| Priority queue (heap) | Logarithmic insert and remove | Best-first search, scheduling |
| Sorting | n log n | Ranking results |
| Graph traversal | Linear in nodes plus edges | Workflows and dependencies |
| Comparing every pair | Quadratic | Naive duplicate detection; use blocking |
| Trying every plan | Exponential | Needs heuristics and limits |
In an agent, the dominant cost is often a model or network call, not local computation. Count calls first. A loop that calls a model once for each pair of fifty documents makes 1,225 calls. Search methods such as A* and beam search are covered in Planning and Search Algorithms.
Randomness and reproducibility
Sampling settings, shuffled data and parallel execution all introduce variation. Fix random seeds in your own code, record settings and model versions, and repeat measurements. Hosted models may still differ between runs, so store the actual outputs you evaluated.
Expected cost and the value of checking
Decision theory combines probabilities with consequences. The expected cost of an option is each outcome's cost weighted by its probability. The example compares acting at once, running a check that catches most errors, and asking a person.
"""Act, check first, or ask a person? Compare expected costs."""
COST_CHECK = 0.40 # run a verification tool
COST_ASK = 3.00 # interrupt a person
CHECK_MISSES = 0.10 # share of wrong answers the check fails to catch
def options(p_right, cost_wrong):
p_wrong = 1 - p_right
return {
"act": p_wrong * cost_wrong,
# if the check catches a problem, a person is asked
"check": COST_CHECK + p_wrong * (
CHECK_MISSES * cost_wrong + (1 - CHECK_MISSES) * COST_ASK),
"ask": COST_ASK,
}
print("p(right) cost if wrong act check ask choose")
for p_right, cost_wrong in [(0.99, 10), (0.90, 10), (0.90, 100),
(0.60, 100), (0.99, 1000)]:
o = options(p_right, cost_wrong)
best = min(o, key=o.get)
print(f"{p_right:>8.2f} {cost_wrong:>13} {o['act']:>5.2f} "
f"{o['check']:>6.2f} {o['ask']:>6.2f} {best}")
Output:
p(right) cost if wrong act check ask choose
0.99 10 0.10 0.44 3.00 act
0.90 10 1.00 0.77 3.00 check
0.90 100 10.00 1.67 3.00 check
0.60 100 40.00 5.48 3.00 ask
0.99 1000 10.00 1.43 3.00 check
When errors are cheap and unlikely, act. As the consequence grows, a cheap check pays for itself, even at 99% confidence if the damage is large. When the agent is often wrong and errors are costly, ask immediately. The model assumes that a person resolves the case correctly at the stated price, and that the probability of being right is known. In practice a model's stated confidence is often poorly calibrated, so estimate probabilities from measured results for each task type.
Some actions should not be decided by expected cost at all. Where harm is severe or irreversible, or the law requires a person, apply a fixed rule. See Action Guardrails and Policy Engines.
Calibration
A score is calibrated if, among cases scored 0.8, about 80% turn out right. Check it by grouping past predictions into bands and comparing each band's score with its real success rate. If bands disagree, map scores to observed rates or stop using them for decisions. Recheck after model, prompt or data changes.
Optimization in practice
| Concept | Meaning | Agent use |
|---|---|---|
| Objective | What you try to maximize or minimize | Successful tasks per unit of cost |
| Constraint | A limit that must hold | Response time, budget, safety rules |
| Trade-off frontier | Options where improving one measure worsens another | Choosing models, see Model Routing, Fallbacks and Gateways |
| Greedy method | Best immediate choice | Fast, can miss better plans |
| Search with budget | Explore alternatives within limits | Planning |
| Proxy problem | Optimizing a stand-in measure | Answers that please a judge but fail users |
Write the constraints separately from the objective. If safety is only a small penalty inside a score, an optimizer may trade it away for speed.
Reporting results honestly
- State the number of cases and an interval, not only a percentage.
- Report fixed and broken cases when comparing versions.
- Show results by category, since an average can hide a weak group.
- Give high percentiles for latency and cost.
- Say how cases were chosen and what they leave out.
A team sees a new prompt pass 46 of 50 cases against 43 before and wants to ship it. Case-level comparison shows five fixed and two broken, one of them a refund limit. They fix that case, add two hundred cases drawn from real requests, and decide only after rerunning both versions on the larger set.
Waiting lines
Agent services queue for model capacity, tools and people. A little queueing arithmetic prevents surprises. Little's law says that in a stable system the average number of items in progress equals the average arrival rate multiplied by the average time each spends there. If 4 tasks arrive each second and each takes 30 seconds, about 120 tasks are in progress at once. Your connection limits, memory and rate limits must cover that number.
Waiting time also rises sharply as a resource approaches full use. A worker pool that is half busy absorbs bursts easily, while one that is almost always busy builds long queues from small variations. Plan spare capacity, set a maximum queue length and decide what happens beyond it. Latency, Load Testing and Capacity Planning develops this.
A study order that pays off
| Order | Topic | You can then |
|---|---|---|
| 1 | Rates, percentiles, intervals | Judge whether a change helped |
| 2 | Vectors and similarity, BM25 | Debug retrieval |
| 3 | Cost of data structures, graph traversal | Find slow designs |
| 4 | Expected cost and calibration | Set thresholds for review |
| 5 | Queueing and optimization | Plan capacity and trade-offs |
Common mistakes
- Treating a perfect score on a few cases as proof.
- Multiplying step success rates while ignoring shared causes, or ignoring compounding altogether.
- Reading similarity scores as probabilities.
- Averaging latency and hiding the slow tail.
- Trusting self-reported confidence.
- Choosing a variant and evaluating it on the same cases.
- Optimizing a proxy until it stops meaning anything.
Checklist
- Evaluation results include sample size and uncertainty.
- Version comparisons are made case by case.
- Similarity thresholds come from labeled data.
- Retrieval has recall measured separately.
- Model and tool calls per task are counted.
- Decision thresholds use measured success rates.
- Hard constraints are not folded into scores.
- Queue limits and capacity margins are set.
Frequently asked questions
How much mathematics do I need to build agents?
Very little to start. Rates, similarity and basic complexity cover most early work. Learn more when a specific problem calls for it.
How many test cases are enough?
Enough to make the uncertainty smaller than the difference or failure rate you care about. Rare, serious failures need many cases or targeted tests.
Is cosine similarity always best?
Use what the embedding model was designed for. For normalized vectors, several common measures give the same ranking.
Can expected cost justify risky automation?
Not by itself. Estimates are uncertain and some harms are unacceptable at any average. Combine calculations with fixed limits and accountable owners.
References and further reading
- Manning, Raghavan and Schütze: Introduction to Information Retrieval
- NIST handbook: confidence intervals for proportions
- Miller: Adding error bars to evals
- Malkov and Yashunin: HNSW
- Python heapq documentation
Next steps
Distributed Systems, Networking and Databases
Handle failure across machines.
Task, Tool and Planning Metrics
Choose what to measure.
Graph, Game, Control Theory and Reinforcement Learning
Graphs, feedback and learning.