Multimodal, Embedding and Reranking Models

The chat model gets the attention. These other models decide what it gets to see.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Multimodal models accept images, audio, video or documents as well as text. Embedding models turn content into vectors so that similar meanings can be found. Rerankers read a query and a candidate together to order results more carefully. Agents use embeddings for fast recall, rerankers for precision and multimodal models for inputs that are not plain text. Evaluate each on your own data.

What you will learn: what each model type does, its limits, how two-stage retrieval works, how to size vector storage and how to choose and change models safely.
Prerequisites: How LLMs Power Agents: Transformers, Tokens and Sampling. Basic Python for the code.

Beginner Three kinds of helper

Where they fit

InputsText, pages, images, sound
UnderstandMultimodal or OCR, speech
Embed and indexVectors plus text
RerankOrder the shortlist
Agent modelReads and decides

Multimodal models

InputUseful forCommon weaknessesCheck with
ImagesScreenshots, photographs, chartsSmall text, counting, precise positionsRealistic resolution and lighting
DocumentsForms, invoices, reports with layoutDense tables, handwriting, poor scansField-level accuracy
AudioCalls, meetings, voice commandsNoise, overlapping speakers, names and numbersAccents and real recording conditions
VideoProcedures, inspections, demonstrationsBrief events missed between sampled frames; costEvents of different duration

Inputs are converted into tokens or similar units, so large images, long recordings and many pages add cost and delay. Sending a smaller image saves money until it hides the detail you need; find that point by testing.

Two routes for documents and sound

You can give the original to a multimodal model, or first convert it with a specialized tool such as optical character recognition or speech-to-text and send the result.

AspectDirect multimodal inputConvert first
Layout, tone, visual cuesCan be usedOften lost
Searchable textNot produced unless askedProduced
Checking and correctionHarder to see what was readIntermediate text can be inspected
PipelineFewer partsMore parts, each replaceable

Many systems combine them: extract text for search, keep the original page for the model or a person to verify. See Multimodal, Vision, Video and Document Agents and Voice Agent Architecture and Real-Time Audio.

Content can carry instructions

Text inside an image, a document or a recording can try to direct the agent. Treat all of it as untrusted data, exactly like a web page. See Prompt Injection Attacks and Defenses.

Embeddings

An embedding model turns a piece of content into a list of numbers, a vector. Content with related meaning tends to land close together, measured for example by cosine similarity. This lets a search for "refund for broken item" find a passage about "money back on damaged goods" even without shared words.

Agent useWhat is embedded
Knowledge retrievalDocument passages and questions
MemoryPast events, notes and preferences
Tool selectionTool descriptions, to shortlist from a large set
Routing and groupingRequests compared with examples
Duplicate detectionTickets or records that say the same thing

Similar is not the same as true, current or permitted. A close passage may be outdated, may state the opposite or may belong to another customer. Filter by permission and date, and let the agent check the content.

An example: a damage claim

A customer sends a photograph of a broken lamp, a voice note and a scanned receipt, and asks for a refund. Here is how the different models might share the work in an illustrative design.

StepModel or toolOutputCheck
Transcribe the voice noteSpeech-to-textText with the stated problemConfirm names and order numbers
Read the receiptDocument extraction or multimodal modelDate, amount, order identifierMatch against the order system
Describe the photographMultimodal modelVisible damage, with uncertaintyA person reviews doubtful cases
Find the relevant policyEmbedding search and rerankerCurrent policy passagesFilter by country and date
Propose a decisionAgent modelRecommendation citing the policyRules and approval for the refund

No model here decides the refund alone. Each produces evidence that can be checked, and the money moves only through the same controls as any other refund. A photograph can be old, edited or of a different item, so the design should not treat an image description as proof. Keep the originals linked to the case so that a reviewer can look for themselves.

Intermediate Two-stage retrieval

Why rerank

An embedding model usually encodes query and passage separately, so passage vectors can be prepared in advance and searched quickly. A reranker, often called a cross-encoder, reads the query and one passage together. It can judge the relationship more closely, but must run once for every pair, so it is applied to a shortlist.

AspectEmbedding searchReranker
ReadsEach text on its ownQuery and passage together
PrecomputedYes, for passagesNo
Scales toVery large collections with an indexA shortlist of candidates
RoleDo not miss itPut it first

Two stages in miniature

The scoring functions below are deliberately simple stand-ins, not real models, so that you can see the structure and one important limit.

"""Two-stage retrieval in miniature: fast recall, then careful ordering.

The scoring functions are simple stand-ins so this runs anywhere. A real
system uses an embedding model for stage one and a reranking model for two.
"""
import math
import re
from collections import Counter

DOCS = {
    "D1": "Refunds for damaged items are paid within five days.",
    "D2": "Refund requests: damaged, damaged box, damaged label, items.",
    "D3": "Refunds are not paid for items damaged after delivery.",
    "D4": "Our warehouse opens at eight and closes at six.",
    "D5": "If your parcel arrives broken, we return your money in five days.",
}

def words(text):
    return re.findall(r"[a-z]+", text.lower())

def embed(text):
    """A bag-of-words vector. Real embeddings capture meaning, not spelling."""
    return Counter(words(text))

def cosine(a, b):
    dot = sum(a[key] * b[key] for key in a)
    size = math.sqrt(sum(v * v for v in a.values()))
    size *= math.sqrt(sum(v * v for v in b.values()))
    return dot / size if size else 0.0

SAME = {"broken": "damaged", "money": "refunds", "return": "paid",
        "refund": "refunds"}

def rerank_score(query, doc):
    """Reads query and document together: synonyms, order and negation."""
    q = [SAME.get(w, w) for w in words(query)]
    d = [SAME.get(w, w) for w in words(doc)]
    cover = len(set(q) & set(d)) / len(set(q))
    pairs = set(zip(q, q[1:])) & set(zip(d, d[1:]))
    penalty = 0.5 if ("not" in d and "not" not in q) else 0.0
    return cover + 0.2 * len(pairs) - penalty

if __name__ == "__main__":
    query = "refunds for damaged items"
    q = embed(query)
    first = sorted(DOCS, key=lambda k: cosine(q, embed(DOCS[k])), reverse=True)
    print("stage 1 (recall):")
    for key in first:
        print(f"  {key} {cosine(q, embed(DOCS[key])):.2f}  {DOCS[key]}")
    shortlist = first[:4]
    second = sorted(shortlist, key=lambda k: rerank_score(query, DOCS[k]),
                    reverse=True)
    print("stage 2 (rerank top 4):", " > ".join(second))
    print("D5 means the same as D1 but was in the shortlist:", "D5" in shortlist)

Output:

stage 1 (recall):
  D1 0.67  Refunds for damaged items are paid within five days.
  D3 0.67  Refunds are not paid for items damaged after delivery.
  D2 0.53  Refund requests: damaged, damaged box, damaged label, items.
  D4 0.00  Our warehouse opens at eight and closes at six.
  D5 0.00  If your parcel arrives broken, we return your money in five days.
stage 2 (rerank top 4): D1 > D2 > D3 > D4
D5 means the same as D1 but was in the shortlist: False

The first stage gave the correct passage D1 and the opposite statement D3 the same score. The reranker separated them, keeping D1 first and moving D3 below the others that mention the subject. It could not rescue passage D5, which means the same as D1 but shares no words with the query, because the first stage never passed it on. The stand-in first stage fails where a real embedding model is designed to help, and the principle remains: reranking cannot recover what retrieval missed. Measure recall at the first stage separately.

Combine meaning and exact words

Embeddings can miss product codes, names, error numbers and rare terms. Keyword search handles those well. Hybrid search runs both and merges the results before reranking. Embeddings, Vector and Hybrid Search, Reranking shows the methods.

Choosing an embedding model

  • Languages and domain: test with your own vocabulary.
  • Input length: know what is cut off, and chunk to fit. See Document Ingestion, Parsing and Chunking.
  • Query and document modes: some models expect a prefix or setting for each; use them consistently.
  • Dimensions: larger vectors cost more to store and search.
  • License and data path: the same review as for any model.
  • Similarity measure: use the one the model is documented for.

Public leaderboards such as MTEB compare embedding models across many tasks. They are a place to build a shortlist, not a substitute for testing retrieval on your data.

Measure retrieval

MeasureQuestion
Recall at kIs the needed passage among the first k?
Precision at kHow much of the shortlist is relevant?
Rank of first relevant resultDoes the best material come early?
Answer correctness and groundingDid better retrieval produce better answers?
Latency and costWhat did each stage add?

Build the test set from real questions, label which passages answer each one and include questions that have no answer. RAG Evaluation, Grounding and Debugging goes further.

Expert Scale, cost and change

Where cost and delay come from

StageCost driverReduce it by
IndexingAmount of content embedded and re-embeddedEmbed only changed passages; remove duplicates
Query embeddingNumber of queriesCache exact repeats with care
Vector searchVectors, dimensions, replicasFilters, compact formats, retiring old data
RerankingCandidates times passage lengthSmaller shortlist, shorter passages
Multimodal readingPages, image size, audio and video lengthSend only relevant pages or clips; test lower resolution
Final answerPassages placed in contextBetter ranking so fewer passages are needed

Measure the whole path. A reranker that adds a little delay may reduce the number of passages sent to the agent model, which can save more time and money than it costs. The opposite is also possible, so compare complete runs and not stages in isolation. Process large collections as background jobs with checkpoints, and plan how failed items are retried and reported.

Size the storage

Raw vector memory is the number of vectors times dimensions times bytes per value. Indexes, metadata, text and replicas come on top.

"""How much memory do your vectors need? Raw vectors only, before indexes."""

BYTES = {"float32": 4, "float16": 2, "int8": 1, "binary": 1 / 8}

def gigabytes(vectors, dimensions, kind):
    return vectors * dimensions * BYTES[kind] / 1_000_000_000

if __name__ == "__main__":
    chunks = 20_000_000
    print(f"{chunks:,} chunks, raw vector storage in GB")
    print("dimensions" + "".join(f"{kind:>10}" for kind in BYTES))
    for dims in (384, 1024, 3072):
        row = "".join(f"{gigabytes(chunks, dims, kind):>10.1f}" for kind in BYTES)
        print(f"{dims:>10}{row}")

Output:

20,000,000 chunks, raw vector storage in GB
dimensions   float32   float16      int8    binary
       384      30.7      15.4       7.7       1.0
      1024      81.9      41.0      20.5       2.6
      3072     245.8     122.9      61.4       7.7

Smaller number formats and fewer dimensions save a great deal of memory and can lose accuracy. A frequent design searches a compact form first, then rescores the top results using a fuller form. Some models are trained so that vectors can be shortened, a technique described as Matryoshka representation learning. Shorten a vector only when its model supports it, and measure recall afterward.

Evaluate multimodal reading

A model that describes images fluently may still misread the one number that matters. Score the facts your process depends on, field by field, on material of realistic quality. Include rotated pages, glare, stamps over text, mixed languages, background noise and files that are not what they claim to be. Ask the model to report when something is unreadable, and test that it does, because a confident guess is more harmful than a gap. Where an answer can be verified against another source, such as a total against line items or an identifier against a database, build that check into the pipeline. Keep a sample of production items for periodic human review, with consent and retention rules in place, so that a change in input quality is noticed early.

Changing the embedding model

Vectors from different models, or versions, are not comparable. Changing model means embedding the collection again.

  1. Record the model and version with every vector.
  2. Build a second index beside the old one.
  3. Run the retrieval test set against both.
  4. Switch queries and index together, then keep the old index until confident.
  5. Keep source text, so that re-embedding is always possible.

Privacy and access

  • Treat vectors as sensitive: they are derived from the content and may reveal parts of it.
  • Apply the source document's permissions at query time.
  • Delete vectors, caches and extracted text when the source is deleted.
  • Obtain consent where recording voices or processing images of people requires it.
  • Check rules before processing biometric or health data.

Typical failures

SymptomLikely causeTry
Obvious document not foundChunking, truncation or exact-term missInspect chunks; add keyword search
Opposite statement ranked highSimilarity ignores negationRerank; make the agent verify
Quality drops after updateMixed embedding versionsRebuild and record versions
Wrong numbers from a scanLow resolution or table layoutBetter capture, extraction check, human review
Slow responsesShortlist too large for rerankerReduce candidates and measure the effect

Frequently asked questions

Can the chat model do the reranking?

Yes, by asking it to order candidates, usually at higher cost and delay than a dedicated reranker. Compare both on your test set.

How many candidates should I rerank?

Increase the number until recall stops improving enough to justify the added time. The answer depends on your data.

Are similarity scores probabilities?

Generally not. Do not compare thresholds across models; calibrate on labeled examples.

Do I need embeddings at all?

Not always. For small collections or exact lookups, keyword search or a database query may be better.

References and further reading

Next steps