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-key

Mistral AI Free Plan: what is free and how to get a key

  1. 1Guess

    What is an embedding for?
  2. 2Read

    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.

  3. 3Code

    Two texts, two vectors

    1 / 2
    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"]
      }'
    

    Read the program. What will it print?

  4. 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.

  5. 5Code

    Rank help-centre pages for a question

    1 / 2
    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])
    	}
    }
    

    Read the program. What will it print?

  6. 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])
    }
    
    The query changes to "Can I get my money back?". Which document ranks first?
  7. 7Say it back

  8. 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

  1. AgentRouter Free Credits

    Free AI coding credits: $25 per daily check-in and $50 per invite

    No cardVerified

  2. Google Gemini Developer API Free Tier

    Free Gemini API tier with rate-limited access to Flash models and Gemini 2.5 Pro

    No cardVerified

  3. Groq Free Tier

    Free rate-limited Groq API access to hosted open models, no card

    No cardVerified

All free ai api credits →

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

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

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer