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.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

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.

Beginner Uncertainty

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.

IdeaMeaningAgent example
RateSuccesses divided by trialsTasks completed correctly
Independent eventsOne does not change the chance of anotherOften untrue: retries share the same cause
CompoundingProbabilities of required steps multiplyTen steps at 95% give about 60% overall, if independent
Conditional probabilityChance given that something is knownFailure rate when the document is scanned
Base rateHow common something is to begin withA good fraud detector still raises many false alarms when fraud is rare
PercentileValue below which a share of results fallsThe 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.

Many comparisons find lucky winners

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.

Intermediate Vectors and search

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.

OperationMeaningNote
Dot productMultiply matching positions and addGrows with vector length
Length (norm)Square root of the dot product with itselfUsed to normalize
Cosine similarityDot product divided by both lengthsCompares direction only
Euclidean distanceStraight-line distanceRanks like cosine when vectors have length one
Matrix multiplicationMany dot products at onceThe core of model computation
Dimension reductionFewer numbers per vectorSaves 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 measureAnswers
Recall at kWas the needed item among the first k?
Precision at kHow many of the first k were relevant?
Mean reciprocal rankHow high was the first relevant item?
nDCGAre 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 methodTypical costWhere it appears in agents
Hash map lookupConstant on averageCaches, idempotency keys
Binary search in sorted dataLogarithmicFinding a value by time
Priority queue (heap)Logarithmic insert and removeBest-first search, scheduling
Sortingn log nRanking results
Graph traversalLinear in nodes plus edgesWorkflows and dependencies
Comparing every pairQuadraticNaive duplicate detection; use blocking
Trying every planExponentialNeeds 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.

Expert Optimization and decisions

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

ConceptMeaningAgent use
ObjectiveWhat you try to maximize or minimizeSuccessful tasks per unit of cost
ConstraintA limit that must holdResponse time, budget, safety rules
Trade-off frontierOptions where improving one measure worsens anotherChoosing models, see Model Routing, Fallbacks and Gateways
Greedy methodBest immediate choiceFast, can miss better plans
Search with budgetExplore alternatives within limitsPlanning
Proxy problemOptimizing a stand-in measureAnswers 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.
Illustrative example: a prompt change

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

OrderTopicYou can then
1Rates, percentiles, intervalsJudge whether a change helped
2Vectors and similarity, BM25Debug retrieval
3Cost of data structures, graph traversalFind slow designs
4Expected cost and calibrationSet thresholds for review
5Queueing and optimizationPlan 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

Next steps