
Retrieval-augmented generation (RAG) in Go, with the standard library
Split documents into chunks, embed them, search in memory, and answer from what the search found.
On the agent compass Stage 1 of 4 · Build the requestA model knows what was in its training data, and nothing about your service’s documentation, your runbooks, or last week’s design notes. When the answer to a question is in documents like those, the program has to find the right passages and put them in front of the model.
The search is usually by meaning rather than by keyword. An embeddings model turns each passage into a vector, a list of numbers, placed so that passages about similar things have similar vectors; the question is turned into a vector the same way, and the closest passages win. Everything on this page is standard-library Go: the embeddings come from an HTTP API, and the search is a loop.
Run it first
The program is rag in the companion code.
It answers questions about the documentation of shortlink, a small URL shortener made up for the purpose: 25 Markdown files, about 53 KB.
From the repository’s code directory, with no API key:
$ go run ./rag
Without a key, it replays a recorded run: the replies of xiaomi/mimo-v2.6-pro for the answers and of voyageai/voyage-4-lite for the embeddings, recorded on October 19, 2026.
The chunking and the search run for real.
It asks 16 questions three ways, and this page builds the first, rag; the others are the subject of RAG or agentic search?.
index: 140 chunks, $0.00028 to embed
approach correct calls tokens in out cost
rag 16/16 32 8714 3685 $0.0064
rag-tool 16/16 72 25834 6103 $0.0128
files 16/16 54 43201 6098 $0.0151
With OPENROUTER_API_KEY set (getting set up shows how; this makes live calls), ask your own question:
$ go run ./rag -ask rag "How do I make redirects permanent?"
There are four pieces: split the documents into chunks, embed every chunk, search the chunks for each question, and answer from what the search found.
Split the documents into chunks
A whole document is the wrong unit to search.
A long page about deployment matches many questions a little, and sending all of it spends tokens on paragraphs that don’t matter.
A sentence is too small: it loses the context that says what it is about.
Documentation is written in sections, so the sections are the chunks here.
chunkDocs walks every Markdown file, starts a new chunk at each heading, and cuts a long section at paragraph breaks:
// Chunk is one piece of one document: the unit that is embedded,
// searched, and handed to the model.
type Chunk struct {
Doc string `json:"doc"` // the file it came from
Heading string `json:"heading"` // the nearest heading above it
Text string `json:"text"`
}
// chunkDocs splits every Markdown file under docs into chunks, one per
// section: the text under each heading, with long sections cut at
// paragraph breaks so no chunk passes maxChunk bytes.
func chunkDocs(docs fs.FS, maxChunk int) ([]Chunk, error) {
var out []Chunk
err := fs.WalkDir(docs, ".", func(p string, d fs.DirEntry,
err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(p, ".md") {
return err
}
data, err := fs.ReadFile(docs, p)
if err != nil {
return fmt.Errorf("read %s: %w", p, err)
}
heading, body := "", ""
flush := func() {
for _, part := range splitParas(body, maxChunk) {
out = append(out, Chunk{Doc: p, Heading: heading, Text: part})
}
body = ""
}
for line := range strings.SplitSeq(string(data), "\n") {
if h, ok := strings.CutPrefix(line, "#"); ok {
flush()
heading = strings.TrimSpace(strings.TrimLeft(h, "#"))
continue
}
body += line + "\n"
}
flush()
return nil
})
if err != nil {
return nil, fmt.Errorf("chunk docs: %w", err)
}
return out, nil
}
Each chunk is the text under one heading, cut at paragraph breaks when a section runs past 700 bytes. The 25 files make 140 chunks.
A chunk carries its document’s path and its heading.
“Set trusted_proxies” means little on its own; under “Behind a reverse proxy” in docs/deploy.md, it answers a question.
So the text that is embedded, and later shown to the model, starts with both:
[docs/deploy.md: Behind a reverse proxy]
When shortlink runs behind a reverse proxy such as nginx, every request
appears to come from the proxy's address, so every user shares one rate
limit. ...
The headings also let the model cite where each fact came from, which the prompt below asks for.
Embed the chunks
OpenRouter serves embeddings models from the same API, with the same key, as the chat models. The request is a model and a list of texts, and the reply holds one vector per text:
// Embed turns texts into vectors with an embeddings model, through
// the same API and key as the chat calls.
func (c *Client) Embed(ctx context.Context, model string,
texts []string) ([][]float64, error) {
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
body, err := json.Marshal(map[string]any{
"model": model, "input": texts, "dimensions": embedDims,
})
if err != nil {
return nil, fmt.Errorf("encode embeddings request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
c.BaseURL+"/embeddings", bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("build embeddings request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.APIKey)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient().Do(req)
if err != nil {
return nil, fmt.Errorf("send embeddings request: %w", err)
}
defer resp.Body.Close()
return c.readEmbeddings(resp, len(texts))
}
All 140 chunks go in one request, which cost $0.00028 with voyageai/voyage-4-lite.
Embedding costs little next to the answers: the 16 questions’ answers cost about 20 times as much as building the index.
The request asks for 256 numbers per vector, through the dimensions field; this model makes 1024 by default.
Shorter vectors take a quarter of the storage, and a quarter of the arithmetic in every comparison.
The questions must be embedded by the same model, with the same number of dimensions, as the chunks, or the vectors can’t be compared.
Search in memory
To compare two vectors, the program uses cosine similarity: it measures the angle between them and ignores their length.
It is 1 for vectors that point the same way and near 0 for unrelated ones.
The search computes it against every chunk and keeps the best.
A Hit is a Chunk plus a Score (embedding Chunk in the struct gives Hit all of its fields), and the sort compares b.Score with a.Score in that order so the highest scores come first:
// Index holds every chunk with its vector, and finds the chunks
// closest to a question by cosine similarity: an in-memory vector
// search, which for a few thousand chunks needs no database.
type Index struct {
Chunks []Chunk
Vectors [][]float64
}
// Hit is one search result.
type Hit struct {
Chunk
Score float64 // cosine similarity, from -1 to 1
}
// Search returns the k chunks most similar to the question's vector,
// best first.
func (ix *Index) Search(q []float64, k int) []Hit {
hits := make([]Hit, len(ix.Chunks))
for i, v := range ix.Vectors {
hits[i] = Hit{ix.Chunks[i], cosine(q, v)}
}
slices.SortFunc(hits, func(a, b Hit) int {
return cmp.Compare(b.Score, a.Score)
})
return hits[:min(k, len(hits))]
}
func cosine(a, b []float64) float64 {
var dot, na, nb float64
for i := range min(len(a), len(b)) {
dot += a[i] * b[i]
na += a[i] * a[i]
nb += b[i] * b[i]
}
if na == 0 || nb == 0 {
return 0
}
return dot / (math.Sqrt(na) * math.Sqrt(nb))
}
Comparing the question with every chunk is a brute-force search, and for a few thousand chunks it needs no database. Larger sets keep their vectors in a store with a vector index, which finds close vectors without comparing every one; the rest of the program stays the same.
Answer from the passages
The question is embedded, the four closest chunks are found, and one chat call gets the passages and the question:
const ragPrompt = `Answer the question using only the passages from
shortlink's documentation that come with it. Name the document each
fact comes from. If the passages don't answer the question, say that
the documentation doesn't say.`
// askRAG is retrieval-augmented generation in one call: embed the
// question, find the closest chunks, and send them with the question.
func askRAG(ctx context.Context, c *Client, ix *Index, embedModel,
question string) (string, error) {
qv, err := c.Embed(ctx, embedModel, []string{question})
if err != nil {
return "", err
}
var passages []string
for _, h := range ix.Search(qv[0], topK) {
passages = append(passages, h.passage())
}
msgs := []Message{
{Role: "system", Content: ragPrompt},
{Role: "user", Content: "Passages:\n\n" +
strings.Join(passages, "\n\n") + "\n\nQuestion: " + question},
}
reply, err := c.Chat(ctx, msgs, nil)
if err != nil {
return "", err
}
if reply.FinishReason == "length" {
return "", errCutOff
}
return reply.Message.Content, nil
}
The system prompt makes three rules: answer only from the passages, name the document each fact comes from, and say so when the passages don’t answer the question.
The last rule matters as much as the first two.
Search always returns four passages, whether or not any of them is relevant, and a model given passages tends to answer from them.
The 16th question asks whether shortlink can make QR codes, which no document mentions; rag answered:
The documentation doesn't say. None of the provided passages mention
QR codes ...
Measured result
16 of 16 questions answered right, for $0.0064 in all
The cost includes embedding each question. One run on one model is a single sample: it shows that the pipeline works on these documents, not a rate you can expect elsewhere.
- Task
- 16 questions about shortlink’s 25 documents, from a single setting’s default to a two-step upgrade and one question the documents don’t answer, graded by the phrases a right answer must contain
- Models
- xiaomi/mimo-v2.6-pro for the answers, voyageai/voyage-4-lite for the embeddings, through OpenRouter
- Runs
- one run of the 16 questions; 32 API calls, two per question, after one call to build the index
- Date
- October 2026
Measured with the companion codeThe comparison with agentic search
Retrieval as a tool
The same search can be a tool instead, so that a model in an agent loop decides when to search and what to search for:
const toolPrompt = `You answer questions about shortlink from its
documentation. Use search_docs to find passages; if the first results
don't answer the question, search again with other words. Answer only
from what you found, name the documents you used, and if the
documentation doesn't answer the question, say so.`
// searchTool is retrieval as a tool: the model decides when to search
// and what to search for, and can search again.
func searchTool(c *Client, ix *Index, embedModel string) Tool {
return Tool{
Name: "search_docs",
Description: "Search shortlink's documentation. Returns the " +
"passages closest in meaning to the query, best first.",
Parameters: []byte(`{"type": "object", "properties": {"query":
{"type": "string"}}, "required": ["query"]}`),
Run: func(ctx context.Context, args string) (string, error) {
var a struct {
Query string `json:"query"`
}
if err := json.Unmarshal([]byte(args), &a); err != nil {
return "", fmt.Errorf("arguments: %w", err)
}
qv, err := c.Embed(ctx, embedModel, []string{a.Query})
if err != nil {
return "", err
}
var out []string
for _, h := range ix.Search(qv[0], topK) {
out = append(out, h.passage())
}
return strings.Join(out, "\n\n"), nil
},
}
}
With the tool, the model can search again with other words when the first results miss, and on these questions it searched more than once on 13 of 16. That costs calls and tokens; RAG or agentic search? compares it with one-shot RAG and with an agent that reads the files itself.
What to watch
Retrieval can miss. When the right chunk isn’t among the four returned, the model can’t answer, and with the prompt above it says it can’t. Check retrieval on its own: for each test question, note which document holds the answer, and count how often a chunk from it comes back. That tells you whether a wrong answer came from the search or from the model, something an eval of the answers alone cannot do.
The index goes stale. Vectors describe the documents as they were when they were embedded. Rebuild the index when the documents change, or embed only the files that changed.
Retrieved text is untrusted input. The passages come from documents, and anyone who can edit a document can write instructions into it. Treat them as data in the prompt, the way prompt injection describes for any tool result.
Chunk size is a trade-off. Larger chunks carry more context and spend more tokens on each answer; smaller ones are more precise and lose context. Splitting by heading suits documentation; for text without headings, split by paragraph and keep a little overlap between neighbors.
Try it
- Run
go run ./rag(no key needed) and readrag/testdata/run.json, from thecodedirectory, for one question: the embedding request, the four passages in the chat request, and the answer. - With a key (this makes live calls), ask a question whose answer spans two documents, such as which setting turns webhooks on and which metric counts failed deliveries, and see whether four chunks are enough.
- Change
topKinrag/answer.goto 2, record a run with-record my-run.json(needs an API key and makes live calls), and compare the scores and the cost. - Change
embedDimsinrag/retrieve.goto 1024 (digits only, no comma), record a run the same way (needs an API key and makes live calls), and compare the size of the recording and the answers.
To undo the edits to the source, run git restore rag from the code directory.
type Chunk struct {
Doc string `json:"doc"` // the file it came from
Heading string `json:"heading"` // the nearest heading above it
Text string `json:"text"`
}
Chunk is one piece of one document: the unit that is embedded, searched, and handed to the model.
Chunk is one piece of one document: the unit that is embedded, searched, and handed to the model. type Chunk struct { Doc string `json:"doc"` // the file it came from Heading string `json:"heading"` // the nearest heading above it Text string `json:"text"` }. In rag/retrieve.go, line 22.
field Doc string `json:"doc"`
the file it came from
the file it came from field Doc string `json:"doc"`. In rag/retrieve.go, line 23.
type string string
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text.
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. type string string. Documented at pkg.go.dev, builtin.string.
field Heading string `json:"heading"`
the nearest heading above it
the nearest heading above it field Heading string `json:"heading"`. In rag/retrieve.go, line 24.
field Text string `json:"text"`
field Text string `json:"text"`. In rag/retrieve.go, line 25.
func chunkDocs(docs fs.FS, maxChunk int) ([]Chunk, error)
chunkDocs splits every Markdown file under docs into chunks, one per section: the text under each heading, with long sections cut at paragraph breaks so no chunk passes maxChunk bytes.
chunkDocs splits every Markdown file under docs into chunks, one per section: the text under each heading, with long sections cut at paragraph breaks so no chunk passes maxChunk bytes. func chunkDocs(docs fs.FS, maxChunk int) ([]Chunk, error). In rag/retrieve.go, line 31.
package fs ("io/fs")
Package fs defines basic interfaces to a file system.
Package fs defines basic interfaces to a file system. package fs ("io/fs"). Documented at pkg.go.dev, io/fs.
type FS interface {
// Open opens the named file.
// [File.Close] must be called to release any associated resources.
//
// When Open returns an error, it should be of type *PathError
// with the Op field set to "open", the Path field set to name,
// and the Err field describing the problem.
//
// Open should reject attempts to open names that do not satisfy
// ValidPath(name), returning a *PathError with Err set to
// ...
}
An FS provides access to a hierarchical file system.
An FS provides access to a hierarchical file system. type FS interface { // Open opens the named file. // [File.Close] must be called to release any associated resources. // // When Open returns an error, it should be of type *PathError // with the Op field set to "open", the Path field set to name, // and the Err field describing the problem. // // Open should reject attempts to open names that do not satisfy // ValidPath(name), returning a *PathError with Err set to // ... }. Documented at pkg.go.dev, io/fs.FS.
type int int
int is a signed integer type that is at least 32 bits in size.
int is a signed integer type that is at least 32 bits in size. type int int. Documented at pkg.go.dev, builtin.int.
type error interface {
Error() string
}
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error. type error interface { Error() string }. Documented at pkg.go.dev, builtin.error.
func WalkDir(fsys FS, root string, fn WalkDirFunc) error
WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.
WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root. func WalkDir(fsys FS, root string, fn WalkDirFunc) error. Documented at pkg.go.dev, io/fs.WalkDir.
type DirEntry interface {
// Name returns the name of the file (or subdirectory) described by the entry.
// This name is only the final element of the path (the base name), not the entire path.
// For example, Name would return "hello.go" not "home/gopher/hello.go".
Name() string
// IsDir reports whether the entry describes a directory.
IsDir() bool
// Type returns the type bits for the entry.
// ...
}
A DirEntry is an entry read from a directory (using the [ReadDir] function or a [ReadDirFile]'s ReadDir method).
A DirEntry is an entry read from a directory (using the [ReadDir] function or a [ReadDirFile]'s ReadDir method). type DirEntry interface { // Name returns the name of the file (or subdirectory) described by the entry. // This name is only the final element of the path (the base name), not the entire path. // For example, Name would return "hello.go" not "home/gopher/hello.go". Name() string // IsDir reports whether the entry describes a directory. IsDir() bool // Type returns the type bits for the entry. // ... }. Documented at pkg.go.dev, io/fs.DirEntry.
var nil Type
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type. var nil Type. Documented at pkg.go.dev, builtin.nil.
func (DirEntry) IsDir() bool
IsDir reports whether the entry describes a directory.
IsDir reports whether the entry describes a directory. func (DirEntry) IsDir() bool. Documented at pkg.go.dev, io/fs.DirEntry.IsDir.
package strings ("strings")
Package strings implements simple functions to manipulate UTF-8 encoded strings.
Package strings implements simple functions to manipulate UTF-8 encoded strings. package strings ("strings"). Documented at pkg.go.dev, strings.
func HasSuffix(s, suffix string) bool
HasSuffix reports whether the string s ends with suffix.
HasSuffix reports whether the string s ends with suffix. func HasSuffix(s, suffix string) bool. Documented at pkg.go.dev, strings.HasSuffix.
func ReadFile(fsys FS, name string) ([]byte, error)
ReadFile reads the named file from the file system fsys and returns its contents.
ReadFile reads the named file from the file system fsys and returns its contents. func ReadFile(fsys FS, name string) ([]byte, error). Documented at pkg.go.dev, io/fs.ReadFile.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Errorf(format string, a ...any) (err error)
Errorf formats according to a format specifier and returns the string as a value that satisfies error.
Errorf formats according to a format specifier and returns the string as a value that satisfies error. func Errorf(format string, a ...any) (err error). Documented at pkg.go.dev, fmt.Errorf.
func splitParas(text string, limit int) []string
splitParas cuts text at blank lines into parts no longer than limit bytes, keeping paragraphs whole where it can.
splitParas cuts text at blank lines into parts no longer than limit bytes, keeping paragraphs whole where it can. func splitParas(text string, limit int) []string. In rag/retrieve.go, line 70.
func append(slice []Type, elems ...Type) []Type
The append built-in function appends elements to the end of a slice.
The append built-in function appends elements to the end of a slice. func append(slice []Type, elems ...Type) []Type. Documented at pkg.go.dev, builtin.append.
func SplitSeq(s, sep string) iter.Seq[string]
SplitSeq returns an iterator over all substrings of s separated by sep.
SplitSeq returns an iterator over all substrings of s separated by sep. func SplitSeq(s, sep string) iter.Seq[string]. Documented at pkg.go.dev, strings.SplitSeq.
func CutPrefix(s, prefix string) (after string, found bool)
CutPrefix returns s without the provided leading prefix string and reports whether it found the prefix.
CutPrefix returns s without the provided leading prefix string and reports whether it found the prefix. func CutPrefix(s, prefix string) (after string, found bool). Documented at pkg.go.dev, strings.CutPrefix.
func TrimSpace(s string) string
TrimSpace returns a slice (substring) of the string s, with all leading and trailing white space removed, as defined by Unicode.
TrimSpace returns a slice (substring) of the string s, with all leading and trailing white space removed, as defined by Unicode. func TrimSpace(s string) string. Documented at pkg.go.dev, strings.TrimSpace.
func TrimLeft(s, cutset string) string
TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed.
TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed. func TrimLeft(s, cutset string) string. Documented at pkg.go.dev, strings.TrimLeft.
type Client struct {
BaseURL string // such as https://openrouter.ai/api/v1
APIKey string // sent as a bearer token
Model string // such as anthropic/claude-haiku-5.5
HTTP *http.Client // http.DefaultClient if nil
Calls int // chat and embedding calls made so far
Spent Usage // what they used and cost
}
Client calls a model through an OpenAI-compatible chat completions API, such as OpenRouter's.
Client calls a model through an OpenAI-compatible chat completions API, such as OpenRouter's. type Client struct { BaseURL string // such as https://openrouter.ai/api/v1 APIKey string // sent as a bearer token Model string // such as anthropic/claude-haiku-5.5 HTTP *http.Client // http.DefaultClient if nil Calls int // chat and embedding calls made so far Spent Usage // what they used and cost }. In rag/client.go, line 18.
func (c *Client) Embed(ctx context.Context, model string,
texts []string) ([][]float64, error)
Embed turns texts into vectors with an embeddings model, through the same API and key as the chat calls.
Embed turns texts into vectors with an embeddings model, through the same API and key as the chat calls. func (c *Client) Embed(ctx context.Context, model string, texts []string) ([][]float64, error). In rag/retrieve.go, line 98.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// ...
}
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
A Context carries a deadline, a cancellation signal, and other values across API boundaries. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // The close of the Done channel may happen asynchronously, // ... }. Documented at pkg.go.dev, context.Context.
type float64 float64
float64 is the set of all IEEE 754 64-bit floating-point numbers.
float64 is the set of all IEEE 754 64-bit floating-point numbers. type float64 float64. Documented at pkg.go.dev, builtin.float64.
var cancel context.CancelFunc
var cancel context.CancelFunc. In rag/retrieve.go, line 100.
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc). Documented at pkg.go.dev, context.WithTimeout.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
const Minute = 60 * Second
const Minute = 60 * Second. Documented at pkg.go.dev, time.Minute.
package json ("encoding/json/v2")
Package json implements semantic processing of JSON as specified in RFC 8259.
Package json implements semantic processing of JSON as specified in RFC 8259. package json ("encoding/json/v2"). Documented at pkg.go.dev, encoding/json/v2.
func Marshal(in any, opts ...Options) (out []byte, err error)
Marshal serializes a Go value as a []byte according to the provided marshal and encode options (while ignoring unmarshal or decode options).
Marshal serializes a Go value as a []byte according to the provided marshal and encode options (while ignoring unmarshal or decode options). func Marshal(in any, opts ...Options) (out []byte, err error). Documented at pkg.go.dev, encoding/json/v2.Marshal.
type any = interface{}
any is an alias for interface{} and is equivalent to interface{} in all ways.
any is an alias for interface{} and is equivalent to interface{} in all ways. type any = interface{}. Documented at pkg.go.dev, builtin.any.
const embedDims = 256
embedDims is the length of each vector.
embedDims is the length of each vector. const embedDims = 256. In rag/retrieve.go, line 92.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
NewRequestWithContext returns a new [Request] given a method, URL, and optional body.
net/http.NewRequestWithContext
NewRequestWithContext returns a new [Request] given a method, URL, and optional body. func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error). Documented at pkg.go.dev, net/http.NewRequestWithContext.
const MethodPost = "POST"
const MethodPost = "POST". Documented at pkg.go.dev, net/http.MethodPost.
field BaseURL string
such as https://openrouter.ai/api/v1
such as https://openrouter.ai/api/v1 field BaseURL string. In rag/client.go, line 19.
package bytes ("bytes")
Package bytes implements functions for the manipulation of byte slices.
Package bytes implements functions for the manipulation of byte slices. package bytes ("bytes"). Documented at pkg.go.dev, bytes.
func NewReader(b []byte) *Reader
NewReader returns a new [Reader] reading from b.
NewReader returns a new [Reader] reading from b. func NewReader(b []byte) *Reader. Documented at pkg.go.dev, bytes.NewReader.
field Header Header
Header contains the request header fields either received by the server or to be sent by the client.
Header contains the request header fields either received by the server or to be sent by the client. field Header Header. Documented at pkg.go.dev, net/http.Request.Header.
func (h Header) Set(key, value string)
Set sets the header entries associated with key to the single element value.
Set sets the header entries associated with key to the single element value. func (h Header) Set(key, value string). Documented at pkg.go.dev, net/http.Header.Set.
field APIKey string
sent as a bearer token
sent as a bearer token field APIKey string. In rag/client.go, line 20.
func (c *Client) httpClient() *http.Client
func (c *Client) httpClient() *http.Client. In rag/client.go, line 146.
func (c *Client) Do(req *Request) (*Response, error)
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client. func (c *Client) Do(req *Request) (*Response, error). Documented at pkg.go.dev, net/http.Client.Do.
field Body io.ReadCloser
Body represents the response body.
Body represents the response body. field Body io.ReadCloser. Documented at pkg.go.dev, net/http.Response.Body.
func (Closer) Close() error
func (Closer) Close() error. Documented at pkg.go.dev, io.Closer.Close.
func (c *Client) readEmbeddings(resp *http.Response,
n int) ([][]float64, error)
func (c *Client) readEmbeddings(resp *http.Response, n int) ([][]float64, error). In rag/retrieve.go, line 125.
func len(v Type) int
The len built-in function returns the length of v, according to its type:
The len built-in function returns the length of v, according to its type: func len(v Type) int. Documented at pkg.go.dev, builtin.len.
type Index struct {
Chunks []Chunk
Vectors [][]float64
}
Index holds every chunk with its vector, and finds the chunks closest to a question by cosine similarity: an in-memory vector search, which for a few thousand chunks needs no database.
Index holds every chunk with its vector, and finds the chunks closest to a question by cosine similarity: an in-memory vector search, which for a few thousand chunks needs no database. type Index struct { Chunks []Chunk Vectors [][]float64 }. In rag/retrieve.go, line 170.
field Vectors [][]float64
field Vectors [][]float64. In rag/retrieve.go, line 172.
type Hit struct {
Chunk
Score float64 // cosine similarity, from -1 to 1
}
Hit is one search result.
Hit is one search result. type Hit struct { Chunk Score float64 // cosine similarity, from -1 to 1 }. In rag/retrieve.go, line 176.
field Score float64
cosine similarity, from -1 to 1
cosine similarity, from -1 to 1 field Score float64. In rag/retrieve.go, line 178.
func (ix *Index) Search(q []float64, k int) []Hit
Search returns the k chunks most similar to the question's vector, best first.
Search returns the k chunks most similar to the question's vector, best first. func (ix *Index) Search(q []float64, k int) []Hit. In rag/retrieve.go, line 183.
func make(t Type, size ...IntegerType) Type
The make built-in function allocates and initializes an object of type slice, map, or chan (only).
The make built-in function allocates and initializes an object of type slice, map, or chan (only). func make(t Type, size ...IntegerType) Type. Documented at pkg.go.dev, builtin.make.
func cosine(a, b []float64) float64
func cosine(a, b []float64) float64. In rag/retrieve.go, line 194.
package slices ("slices")
Package slices defines various functions useful with slices of any type.
Package slices defines various functions useful with slices of any type. package slices ("slices"). Documented at pkg.go.dev, slices.
func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int)
SortFunc sorts the slice x in ascending order as determined by the cmp function.
SortFunc sorts the slice x in ascending order as determined by the cmp function. func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int). Documented at pkg.go.dev, slices.SortFunc.
package cmp ("cmp")
Package cmp provides types and functions related to comparing ordered values.
Package cmp provides types and functions related to comparing ordered values. package cmp ("cmp"). Documented at pkg.go.dev, cmp.
func Compare[T Ordered](x, y T) int
Compare returns
Compare returns func Compare[T Ordered](x, y T) int. Documented at pkg.go.dev, cmp.Compare.
func min[T cmp.Ordered](x T, y ...T) T
The min built-in function returns the smallest value of a fixed number of arguments of cmp.Ordered types.
The min built-in function returns the smallest value of a fixed number of arguments of cmp.Ordered types. func min[T cmp.Ordered](x T, y ...T) T. Documented at pkg.go.dev, builtin.min.
package math ("math")
Package math provides basic constants and mathematical functions.
Package math provides basic constants and mathematical functions. package math ("math"). Documented at pkg.go.dev, math.
func Sqrt(x float64) float64
Sqrt returns the square root of x.
Sqrt returns the square root of x. func Sqrt(x float64) float64. Documented at pkg.go.dev, math.Sqrt.
const ragPrompt = `Answer the question using only the passages from ...
const ragPrompt = `Answer the question using only the passages from .... In rag/answer.go, line 16.
func askRAG(ctx context.Context, c *Client, ix *Index, embedModel,
question string) (string, error)
askRAG is retrieval-augmented generation in one call: embed the question, find the closest chunks, and send them with the question.
askRAG is retrieval-augmented generation in one call: embed the question, find the closest chunks, and send them with the question. func askRAG(ctx context.Context, c *Client, ix *Index, embedModel, question string) (string, error). In rag/answer.go, line 23.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
func (ch Chunk) passage() string
passage is the chunk as it is embedded and shown to the model: its document and heading first, so the text carries its context.
passage is the chunk as it is embedded and shown to the model: its document and heading first, so the text carries its context. func (ch Chunk) passage() string. In rag/retrieve.go, line 229.
type Message struct {
Role string `json:"role"` // system, user, assistant, tool
Content string `json:"content,omitzero"`
ToolCalls []ToolCall `json:"tool_calls,omitzero"`
ToolCallID string `json:"tool_call_id,omitzero"`
// Reasoning some models return, sent back unchanged.
Reasoning jsontext.Value `json:"reasoning_details,omitzero"`
}
Message is one entry in the conversation.
Message is one entry in the conversation. type Message struct { Role string `json:"role"` // system, user, assistant, tool Content string `json:"content,omitzero"` ToolCalls []ToolCall `json:"tool_calls,omitzero"` ToolCallID string `json:"tool_call_id,omitzero"` // Reasoning some models return, sent back unchanged. Reasoning jsontext.Value `json:"reasoning_details,omitzero"` }. In rag/agent.go, line 14.
field Role string `json:"role"`
system, user, assistant, tool
system, user, assistant, tool field Role string `json:"role"`. In rag/agent.go, line 15.
field Content string `json:"content,omitzero"`
field Content string `json:"content,omitzero"`. In rag/agent.go, line 16.
package strings ("strings")
Package strings implements simple functions to manipulate UTF-8 encoded strings.
Package strings implements simple functions to manipulate UTF-8 encoded strings. package strings ("strings"). Documented at pkg.go.dev, strings.
func Join(elems []string, sep string) string
Join concatenates the elements of its first argument to create a single string.
Join concatenates the elements of its first argument to create a single string. func Join(elems []string, sep string) string. Documented at pkg.go.dev, strings.Join.
func (c *Client) Chat(ctx context.Context, msgs []Message,
tools []Tool) (Reply, error)
Chat sends the conversation and the tool definitions, and returns the model's reply.
Chat sends the conversation and the tool definitions, and returns the model's reply. func (c *Client) Chat(ctx context.Context, msgs []Message, tools []Tool) (Reply, error). In rag/client.go, line 72.
field FinishReason string
stop, tool_calls, or length
stop, tool_calls, or length field FinishReason string. In rag/client.go, line 31.
var errCutOff = errors.New("firstagent: reply cut off")
errCutOff means the model ran out of room partway through a reply.
errCutOff means the model ran out of room partway through a reply. var errCutOff = errors.New("firstagent: reply cut off"). In rag/agent.go, line 46.
const toolPrompt = `You answer questions about shortlink from its ...
const toolPrompt = `You answer questions about shortlink from its .... In rag/answer.go, line 52.
func searchTool(c *Client, ix *Index, embedModel string) Tool
searchTool is retrieval as a tool: the model decides when to search and what to search for, and can search again.
searchTool is retrieval as a tool: the model decides when to search and what to search for, and can search again. func searchTool(c *Client, ix *Index, embedModel string) Tool. In rag/answer.go, line 60.
type Tool struct {
Name string
Description string
Parameters jsontext.Value // a JSON Schema for the arguments
Run func(ctx context.Context, args string) (string, error)
}
Tool is something the agent can do: a definition the model reads, and a Go function the model never sees.
Tool is something the agent can do: a definition the model reads, and a Go function the model never sees. type Tool struct { Name string Description string Parameters jsontext.Value // a JSON Schema for the arguments Run func(ctx context.Context, args string) (string, error) }. In rag/agent.go, line 35.
field Parameters jsontext.Value
a JSON Schema for the arguments
a JSON Schema for the arguments field Parameters jsontext.Value. In rag/agent.go, line 38.
type byte = uint8
byte is an alias for uint8 and is equivalent to uint8 in all ways.
byte is an alias for uint8 and is equivalent to uint8 in all ways. type byte = uint8. Documented at pkg.go.dev, builtin.byte.
field Run func(ctx context.Context, args string) (string, error)
field Run func(ctx context.Context, args string) (string, error). In rag/agent.go, line 39.
var a struct{Query string "json:\"query\""}
var a struct{Query string "json:\"query\""}. In rag/answer.go, line 68.
package json ("encoding/json/v2")
Package json implements semantic processing of JSON as specified in RFC 8259.
Package json implements semantic processing of JSON as specified in RFC 8259. package json ("encoding/json/v2"). Documented at pkg.go.dev, encoding/json/v2.
func Unmarshal(in []byte, out any, opts ...Options) (err error)
Unmarshal decodes a []byte input into a Go value according to the provided unmarshal and decode options (while ignoring marshal or encode options).
Unmarshal decodes a []byte input into a Go value according to the provided unmarshal and decode options (while ignoring marshal or encode options). func Unmarshal(in []byte, out any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.Unmarshal.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.

