Search by meaning with embeddings
Learn LLMs · Beginner · 15 min · After Call a chat completion API with curl and Go
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.
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_EMBED_MODEL=mistral-embed-2312
export LLM_API_KEY=your-key1Guess
2Read
The embeddings endpoint
POST <base URL>/embeddingstakes amodelid and aninput: one string or a list of strings. It returnsdata, a list with one object per text, in the same order, each with anembedding: a vector of numbers. The embedding model is not the chat model, so this lesson reads its id fromLLM_EMBED_MODEL.3Code
Two texts, two vectors
1 / 2curl -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"] }'Read the program. What will it print?
4Read
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.
5Code
Rank help-centre pages for a question
1 / 2package 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]) } }Read the program. What will it print?
6Guess
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]) }7Say it back
8Mission · 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.
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
Free AI API credits to practise with
- AgentRouter Free Credits
Free AI coding credits: $25 per daily check-in and $50 per invite
No cardVerified
- Google Gemini Developer API Free Tier
Free Gemini API tier with rate-limited access to Flash models and Gemini 2.5 Pro
No cardVerified
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
Published Dec 3, 2026 · Updated Dec 3, 2026