---
title: "Search by meaning with embeddings"
slug: "embeddings-search"
description: "Turn texts into vectors with an embeddings API, compare them with cosine similarity and rank help-centre documents for a question in Go."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-llm/embeddings-search"
---

# Search by meaning with embeddings

How do you find the document that answers a question when it shares no words with it?

## Run it against a real free API

The outputs in this lesson are simulated by a local mock server. To get real answers, create a free key at Mistral AI Free Plan and set these variables. Never put the key in your code.

```sh
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_EMBED_MODEL=mistral-embed-2312
export LLM_API_KEY=your-key
```

[Mistral AI Free Plan: what is free and how to get a key](https://aifree.dev/offer/mistral-ai-free-plan)

## Predict

What is an embedding for?

- To compress a text so it takes less space
- To turn a text into numbers so texts with similar meaning end up close together
- To translate a text into another language

Answer: To turn a text into numbers so texts with similar meaning end up close together — That is the point: you compare numbers instead of words.

Close numbers mean close meaning, and that lets you search without matching words.

## The embeddings endpoint

`POST <base URL>/embeddings` takes a `model` id and an `input`: one string or a list of strings. It returns `data`, a list with one object per text, in the same order, each with an `embedding`: a vector of numbers. The embedding model is not the chat model, so this lesson reads its id from `LLM_EMBED_MODEL`.

## Two texts, two vectors

```sh
curl -s "$LLM_BASE_URL/embeddings" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $LLM_API_KEY" \
  -d '{
    "model": "'"$LLM_EMBED_MODEL"'",
    "input": ["I forgot my password", "Reset your login and track your order"]
  }'
```

Output:

```
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [
        1,
        0,
        0,
        0,
        0,
        0,
        0,
        0
      ]
    },
    {
      "object": "embedding",
      "index": 1,
      "embedding": [
        0.8944,
        0,
        0.4472,
        0,
        0,
        0,
        0,
        0
      ]
    }
  ],
  "model": "mock-embed-1",
  "usage": {
    "prompt_tokens": 11,
    "total_tokens": 11
  }
}
```

_Simulated response (local mock server), 2026-12-03._

These 8-number vectors are illustrative, made by the mock server from keyword topics. A real model returns hundreds or thousands of learned dimensions.

## Cosine similarity

To compare two vectors, use **cosine similarity**: the dot product divided by the product of their lengths. It is 1 when two vectors point the same way, near 0 when they are unrelated. To search, embed your documents once, embed the question, score every document against it and sort. The best score is the closest meaning, even when no word is shared.

## Rank help-centre pages for a question

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"math"
	"net/http"
	"os"
	"sort"
)

var docs = []string{
	"How to recover access to your account",
	"Track your parcel with the courier tracking number",
	"Pay an invoice or update your card",
	"Return an item for a refund",
	"Change the email on your account and your delivery address",
}

func embed(texts []string) [][]float64 {
	payload, _ := json.Marshal(map[string]any{
		"model": os.Getenv("LLM_EMBED_MODEL"),
		"input": texts,
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/embeddings", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()
	var out struct {
		Data []struct {
			Embedding []float64 `json:"embedding"`
		} `json:"data"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	vectors := make([][]float64, len(out.Data))
	for i, d := range out.Data {
		vectors[i] = d.Embedding
	}
	return vectors
}

func cosine(a, b []float64) float64 {
	var dot, na, nb float64
	for i := range a {
		dot += a[i] * b[i]
		na += a[i] * a[i]
		nb += b[i] * b[i]
	}
	return dot / (math.Sqrt(na) * math.Sqrt(nb))
}

func main() {
	vectors := embed(append([]string{"I forgot my password"}, docs...))
	query, docVectors := vectors[0], vectors[1:]

	order := []int{0, 1, 2, 3, 4}
	sort.Slice(order, func(i, j int) bool {
		return cosine(query, docVectors[order[i]]) > cosine(query, docVectors[order[j]])
	})
	for _, i := range order {
		fmt.Printf("%.2f  %s\n", cosine(query, docVectors[i]), docs[i])
	}
}
```

Output:

```
1.00  How to recover access to your account
0.71  Change the email on your account and your delivery address
0.00  Track your parcel with the courier tracking number
0.00  Pay an invoice or update your card
0.00  Return an item for a refund
```

_Simulated response (local mock server), 2026-12-03._

The ranking is an illustration from the mock's keyword topics. "recover access to your account" wins for "I forgot my password" without sharing a word with it.

## Predict

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"math"
	"net/http"
	"os"
)

var docs = []string{
	"How to recover access to your account",
	"Track your parcel with the courier tracking number",
	"Pay an invoice or update your card",
	"Return an item for a refund",
	"Change the email on your account and your delivery address",
}

func embed(texts []string) [][]float64 {
	payload, _ := json.Marshal(map[string]any{
		"model": os.Getenv("LLM_EMBED_MODEL"),
		"input": texts,
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/embeddings", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()
	var out struct {
		Data []struct {
			Embedding []float64 `json:"embedding"`
		} `json:"data"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	vectors := make([][]float64, len(out.Data))
	for i, d := range out.Data {
		vectors[i] = d.Embedding
	}
	return vectors
}

func cosine(a, b []float64) float64 {
	var dot, na, nb float64
	for i := range a {
		dot += a[i] * b[i]
		na += a[i] * a[i]
		nb += b[i] * b[i]
	}
	return dot / (math.Sqrt(na) * math.Sqrt(nb))
}

func main() {
	vectors := embed(append([]string{"Can I get my money back?"}, docs...))
	query, docVectors := vectors[0], vectors[1:]

	best := 0
	for i := range docs {
		if cosine(query, docVectors[i]) > cosine(query, docVectors[best]) {
			best = i
		}
	}
	fmt.Println(docs[best])
}
```

The query changes to "Can I get my money back?". Which document ranks first?

- How to recover access to your account
- Return an item for a refund
- Pay an invoice or update your card

Answer: Return an item for a refund — A refund is getting money back, so this one is closest in meaning.

Output:

```
Return an item for a refund
```

_Simulated response (local mock server), 2026-12-03._

The ranking comes from the meaning of the texts, not from shared words. Here the mock's topics stand in for what a real model learned.

## Say it back

Explain how a question finds the right page even when they share no words.

Our sentence: Both texts are turned into vectors by an embedding model, and texts with similar meaning get vectors that point the same way. I score every document against the question with cosine similarity and sort, so the closest meaning comes first, whatever words it uses.

## Mission (15 min)

Use your free key from the offer at the top. Set LLM_EMBED_MODEL to the embedding model id and run the ranking program on your own ten short documents. Try three questions and see whether the order matches what you expect.

```sh
export LLM_BASE_URL=<base URL from the offer page>
export LLM_EMBED_MODEL=<embedding model id from the offer page>
export LLM_API_KEY=<your key>
go run main.go
```

## Common questions

### What is the difference between an embedding model and a chat model?

A chat model writes text. An embedding model only turns a text into a vector and writes nothing. They are separate models with separate ids, often with separate prices and limits. For search you embed the documents and the question with the same embedding model, because vectors from different models cannot be compared.

### Why does the lesson use 8-number vectors?

The mock server builds each vector from eight keyword topics so you can see how the numbers work and so results are the same on every run. Real embedding models return hundreds or thousands of dimensions that they learned from data, and they capture far more meaning than keywords. The ranking idea stays the same.

### How many documents can I search this way?

The program here compares the query with every document, which is fine for a few thousand. Beyond that, store the vectors in a database with a vector index so you do not score every document each time. Embed each document once and keep the vectors, and embed only the new question on each search.

## Sources

- https://platform.openai.com/docs/api-reference/embeddings (read 2026-12-03)
- https://docs.mistral.ai/capabilities/embeddings/overview/ (read 2026-12-03)
- https://pkg.go.dev/encoding/json (read 2026-12-03)
- https://pkg.go.dev/net/http (read 2026-12-03)

Simulated responses from a local mock server, not from a real model. Run with local mock server (scripts/course-llm-mock.ts), go1.27.4 darwin/arm64, curl on 2026-12-03.
