Quickstart: find the closest text with embeddings

In this quickstart, you turn three short documents and a question into embeddings, then compare them to find the document closest in meaning to the question, even when they share no words. It takes about 5 minutes. For models and dimensions, see Embeddings.

Before you begin

Before you begin

Set up your environment

Set up your environment

Create a project, install the Mistral SDK, and export your API key:

uv init embeddings --python 3.12 && cd embeddings
uv add mistralai
export MISTRAL_API_KEY="your-api-key"
1. Write the script

1. Write the script

Create embeddings.py. It embeds the documents and the question in one call, then scores each document by cosine similarity:

import math
import os

from mistralai.client import Mistral

client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])

documents = [
    "Our support team answers Monday to Friday, 9:00 to 18:00 CET.",
    "Annual plans can be refunded within 30 days of purchase.",
    "The API rate limit depends on your workspace tier.",
]
question = "Can I get my money back?"

response = client.embeddings.create(model="mistral-embed", inputs=documents + [question])
vectors = [item.embedding for item in response.data]
question_vector = vectors[-1]


def cosine(a: list[float], b: list[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))


scores = [cosine(question_vector, vector) for vector in vectors[:-1]]
for document, score in zip(documents, scores):
    print(f"{score:.3f}  {document}")

best = max(range(len(documents)), key=lambda i: scores[i])
print(f"\nClosest document: {documents[best]}")
2. Run it

2. Run it

uv run embeddings.py
You should see

You should see

A similarity score for each document, then the closest one. The refund policy wins, although the question never says "refund":

0.675  Our support team answers Monday to Friday, 9:00 to 18:00 CET.
0.722  Annual plans can be refunded within 30 days of purchase.
0.616  The API rate limit depends on your workspace tier.

Closest document: Annual plans can be refunded within 30 days of purchase.

The exact scores vary with the model version; the order is what matters.

Going further

Going further