How do I create document embeddings with Ollama on a Mac?

To create document embeddings with Ollama on a Mac, choose a model that supports embeddings and call /api/embed. A chat response is not an embedding. Start with a few passages and verify that a question retrieves the right ones before connecting a chat model to generate answers.

Separate retrieval from answer generation

Document retrieval and answer generation are separate tasks. An embedding model turns text into a sequence of numbers so that software can compare semantic distances. A chat model uses the retrieved material to compose an answer. The former does not automatically produce summaries, and the latter does not automatically build a reusable document index.

This article uses the multilingual model bge-m3, a suitable starting point for testing retrieval over Chinese-language documents. Both documents and questions must go through the same embedding model. Do not embed one with one model and send the other to a chat model.

Vector similarity measures how close texts are in meaning. It does not establish that an answer is true, nor is it the “probability that the answer is correct.” Keep the retrieved source text so you can verify where the information came from.

Prepare three to five questions whose answers you already know, such as “How long are logs retained after a build fails?” These will expose chunking and ranking problems more readily than connecting your entire document collection at the outset.

Prepare the model

Make sure Ollama is installed on your Mac, then launch the application. Run the following in Terminal:

ollama pull bge-m3
ollama list

The first command downloads the model; the second confirms that it is available locally. Once the download is complete, the embedding calculations in this article run locally, without sending your documents to an external inference endpoint.

The example below uses an existing Python 3 environment and only the standard library. It connects to the default local port, 11434. If the connection is refused, first check that Ollama is running. Do not repeatedly download the model or start multiple server processes at once.

Teams that already have a dedicated SSHMini physical machine can also run this retrieval workflow on their cloud Mac, scheduling it separately from build jobs. Keep the embedding service accessible only from the local machine to start with. Do not expose its port directly to the public internet just to enable remote calls.

Save the following as search_docs.py. The two passages are replaceable test content, not a statement of any platform’s service policies.

import http.client
import json
import math

model = "bge-m3"
documents = [
    "团队约定:构建失败后,日志保留七天,由流水线负责人检查。",
    "团队约定:发布前检查签名证书,并保存最终安装包。"
]
question = "构建出错了,日志还能查多久?"

payload = json.dumps({
    "model": model,
    "input": documents + [question],
    "truncate": False
}).encode("utf-8")

connection = http.client.HTTPConnection(
    "127.0.0.1", 11434, timeout=180
)
connection.request(
    "POST",
    "/api/embed",
    body=payload,
    headers={"Content-Type": "application/json"}
)
response = connection.getresponse()
body = response.read().decode("utf-8")
connection.close()

if response.status != 200:
    raise RuntimeError(body)

vectors = json.loads(body)["embeddings"]

def cosine(left, right):
    dot = sum(a * b for a, b in zip(left, right))
    norm = math.sqrt(
        sum(a * a for a in left) *
        sum(b * b for b in right)
    )
    return dot / norm if norm else 0.0

query = vectors[-1]
ranked = sorted(
    [
        (cosine(vector, query), text)
        for vector, text in zip(vectors[:-1], documents)
    ],
    reverse=True
)

for score, text in ranked:
    print(f"{score:.4f}\t{text}")

Run it with:

python3 search_docs.py

The program prints each score alongside its source text. Check that the passage about logs ranks first, then change the question to “What needs to be checked before a release?” Do not treat this article as a reference for fixed scores: changes to the model files, text, or runtime environment can all affect the results.

The example combines documents and the question into a single request to keep the code short. In actual use, calculate document embeddings only when documents are added or changed, and calculate a question embedding for each query. There is no need to reprocess the entire collection every time.

Split long documents into chunks

Start by splitting documents at headings and paragraph boundaries, keeping each chunk focused on one topic. For Chinese text, roughly three hundred to six hundred characters per chunk is a reasonable starting point for testing, not a model limit. Character counts are not the same as token counts.

Preserve headings, filenames, and paragraph numbers. When instructions span multiple paragraphs, include a small amount of overlap between adjacent chunks so that a phrase such as “perform this action” is not separated from the action it refers to.

The example sets truncate: false. If an input exceeds the length supported by the model, the request fails rather than silently discarding the end of the text. When this happens, shorten individual chunks. If the issue is simply excessive resource use during batch processing, reduce the number of chunks per batch.

Extract text from scanned documents first, and retain column names and units when processing tables. The embedding endpoint processes the text you send it; it does not parse an entire folder or interpret image attachments for you.

Check the results

Review the top three source passages before considering answer generation. If the correct material is not among them, switching to a larger chat model usually will not solve the problem. First check whether information is missing, whether chunking has separated relevant conditions, and whether the question contains team-specific abbreviations.

Record each chunk’s text, source, content hash, and model identifier. When a document changes, update only the affected chunks. When changing embedding models, rebuild all vectors; do not mix embeddings from different models, even if their dimensions match. Production indexes should also record the model digest to prevent old and new results from being mixed after a model tag is updated.

The first request may include model loading time, so it is not a reliable measure of sustained throughput. During testing, record the first request and subsequent requests separately, and monitor memory pressure. On a machine also used for builds, start by processing one batch at a time.

Finally, add a realistic test question whose answer is not in the documents. If there is no reliable supporting passage, report that no supporting information was found. Do not force an answer simply because the ranking always produces a first-place result. A local knowledge base built this way helps the team understand where answers come from and when to stop asking it for more.

Frequently asked questions

Can I use Ollama's chat API to create document embeddings?

Use an embedding-capable model and /api/embed. Text generated by the chat API is not an embedding vector for document search.

Do I need to rebuild embeddings after changing models?

Yes. Re-embed the documents with the new model and use that same model for queries. Matching vector dimensions do not make two models' embedding spaces compatible.

Move builds to a dedicated physical Mac

Compare the Apple M4 and Apple M4 Pro Mac mini to find the right configuration and billing term for your team’s CI pipeline.

Rent now

Set up your runner

Choose a dedicated physical Mac mini and run your team’s builds on your own Apple Silicon node.