Builds a numeric matrix of embeddings for each text unit. Row names come from by (data frame) or from names(corpus) / corpus (character vector). Use the result with search_vector for semantic search.

util_fetch_embeddings(
  corpus,
  by = NULL,
  model = "all-minilm",
  base_url = "http://localhost:11434/v1",
  api_key = NULL,
  batch_size = 64L,
  max_chars = 1000L
)

Arguments

corpus

A data frame with text and by columns, or a character vector of texts. If a named character vector, names become row names; if unnamed, the strings themselves are used as row names.

by

Character vector of identifier columns; required when corpus is a data frame (row names), ignored when corpus is a character vector.

model

Embedding model name (default "all-minilm").

base_url

Base URL of an OpenAI-compatible API (default local Ollama, "http://localhost:11434/v1").

api_key

API key, sent as a bearer token. Not needed for local servers.

batch_size

Number of texts sent per request (default 64).

max_chars

Texts longer than this many characters are cut before sending (default 1000). Small models such as all-minilm read about 256 tokens and Ollama rejects longer input rather than truncating it. Use NULL to send full text to models with a longer context.

Value

Numeric matrix with row names (unit ids).

Details

By default this calls a local Ollama server with the small all-minilm model, so no account or API key is needed. Install Ollama, then run ollama pull all-minilm once. Any service that offers an OpenAI-compatible /embeddings endpoint (OpenAI, LM Studio, llama.cpp, and many hosted providers) works by changing base_url, model, and api_key. Embeddings from any other source can be passed to search_vector directly as a matrix with row names.

Examples

if (FALSE) { # \dontrun{
# Requires a running Ollama server: ollama pull all-minilm
emb <- util_fetch_embeddings(c(a = "Gen Z voters", b = "Baby Boomers"))
search_vector(emb, "a", n = 2)

# OpenAI instead
emb <- util_fetch_embeddings(
  c(a = "Gen Z voters", b = "Baby Boomers"),
  model = "text-embedding-3-small",
  base_url = "https://api.openai.com/v1",
  api_key = Sys.getenv("OPENAI_API_KEY")
)
} # }