Skip to main content

05 - Local LLMs with Ollama: AI Without Cloud

How to run a model with Ollama and use it from TypeScript: context, the OpenAI-compatible API, Modelfile and the Docker port, with listings that were run.

What do you think about this article?

At a Glance

How to run a model with Ollama and use it from TypeScript: context, the OpenAI-compatible API, Modelfile and the Docker port, with listings that were run.

You have an application that has to get a language model to answer, and two obstacles: your users' texts cannot leave your infrastructure, or you do not want to pay for every request while you develop and test. The short answer is a model that runs on your own machine, and the most widespread tool for doing it is Ollama: it downloads a model's weights, loads it into memory and exposes it through an HTTP API on 127.0.0.1:11434. The rest of this article is about the things the average tutorial skips, and which are the ones where you get hurt: a context window that stays small without raising errors, a "compatible" API that is compatible only in part, a port that with Docker ends up open to the network, and a speed that you measure on your machine and cannot read off a table.

The method is that of the rest of the series: no model was downloaded or run to write these pages. The ollama package and the openai SDK accept a fetch option, and I pass a fake one that answers with a declared script: the clients' code (building the address, reading the stream, handling errors) really runs, while the token and duration numbers you will see are those of the script, not measurements. The shell commands, the Modelfile and the Docker container are instead schemas to adapt, not run. If you are coming from Integrating the OpenAI and Anthropic APIs you will find the same request shapes again; for the context of RAG see What is RAG.

What you are deciding when you choose a local model

"Local" is a decision about three things, not a virtue. Before installing anything it is worth knowing what they are, because each one has a cost that the tutorial does not show.

  • Where the data lives. With a local model the text stays on the machine; with a model in an external service it leaves with the request.
  • Who pays for the computation. No bill per token, but memory, CPU or GPU time and energy are yours.
  • How capable the model is. What fits in your memory may be smaller than what an external service makes available, and it has to be tried on your task.

None of the three wins over the others: they depend on the case. For a professional firm sorting emails with client data the first weighs most, and local is often the only road; for an assistant that has to reason about long problems the third weighs most, and local should be compared with an external service on real examples before deciding. The second is the most underrated: "free" holds as long as the machine you have is enough.

A clarification on the first item. Ollama can also use models hosted in its cloud service, and its FAQ distinguishes the two cases: when you run locally it does not see your prompts, when you use a cloud model it processes them. If the project's promise is "no data leaves", the feature gets switched off: in the official FAQ the variable OLLAMA_NO_CLOUD=1 or disable_ollama_cloud in ~/.ollama/server.json is enough, and you lose cloud models and web search.

Installing Ollama and downloading a model

On Linux the official documentation points to a one-line script; on macOS and Windows there is an installer. The manual installation described on the same page clarifies what is underneath: a binary that starts with ollama serve, which on distributions with systemd is best handed to a service, so that it starts at boot and restarts on its own. The listing gathers the everyday commands; the name llama3.2 is the one used in the documentation's examples, and you replace it with the model you have chosen.

Listing 1: installing and managing models (shell commands, not run here)
# Linux: the script indicated by the official documentation
curl -fsSL https://ollama.com/install.sh | sh
# macOS and Windows: installer from the page https://ollama.com/download

ollama -v                      # does the client answer? (the server must be started separately)
ollama pull llama3.2           # downloads the weights, only once
ollama list                    # models present on disk
ollama run llama3.2            # chat in the terminal
ollama ps                      # models in memory: SIZE, PROCESSOR, CONTEXT, UNTIL
ollama show llama3.2           # model details
ollama show --modelfile llama3.2   # the Modelfile it starts from
ollama stop llama3.2           # removes it from memory
ollama cp llama3.2 my-assistant    # copy under another name
ollama rm my-assistant             # delete the copy

Two commands deserve attention. ollama pull downloads the weights once and keeps them on disk, while ollama ps shows what is really in memory right now, with the PROCESSOR column saying whether the model runs on the GPU, on the CPU or split between the two, and the CONTEXT column saying how much window it has been given. By default a model stays in memory for 5 minutes after the last request (official FAQ): it is the reason why the first question after a pause is slower than the following ones, and ollama stop frees it immediately if the RAM is needed for something else.

Which models to download, and how much memory they need, you will not find in a table in this article: the list changes within weeks, and a line "8 GB for 7 billion parameters" written today is wrong for tomorrow's models. The number that matters you read yourself, in ollama ps, after loading the model with the context window you will actually use.

The two APIs: the native one and the one compatible with OpenAI

Ollama exposes two interfaces on the same port. The native API lives under /api (/api/chat, /api/embed, /api/tags) and knows everything Ollama can do; the compatible one lives under /v1 and reproduces the shape of OpenAI's so that existing clients can be reused. One detail explains the first stumble: on the native one, if you do not write "stream" the response arrives in pieces, one JSON line at a time (newline-delimited JSON format, as the streaming page says), while the ollama package for JavaScript, when you do not pass stream, sends false and returns the whole response. Whoever moves from curl to the client finds a different behavior without having changed a line of the prompt.

Listing 2: the official client with a fake fetch (Node 24.11, ollama 0.6.4)
import { Ollama } from "ollama";

// Declared script: every response is written here, not produced by a model.
const requests: { url: string; body: any }[] = [];
const enc = new TextEncoder();

function ndjson(lines: object[]): string {
  return lines.map((r) => JSON.stringify(r)).join("\n") + "\n";
}

// Cut the text into blocks of N bytes, even in the middle of a line or of an accented letter.
function inBlocks(text: string, n: number): Uint8Array[] {
  const bytes = enc.encode(text);
  const out: Uint8Array[] = [];
  for (let i = 0; i < bytes.length; i += n) out.push(bytes.slice(i, i + n));
  return out;
}

const fakeFetch: typeof fetch = async (url, init) => {
  const body = JSON.parse(String(init?.body));
  requests.push({ url: String(url), body });
  if (String(url).endsWith("/api/embed")) {
    return Response.json({ model: body.model, embeddings: [[0.5, 0.5], [1, 0]], prompt_eval_count: 7 });
  }
  const final = { model: body.model, done: true, done_reason: "stop", prompt_eval_count: 21, eval_count: 4, eval_duration: 2_000_000_000 };
  if (body.stream) {
    const lines = [
      { model: body.model, message: { role: "assistant", content: "Ciao, è " }, done: false },
      { model: body.model, message: { role: "assistant", content: "tutto " }, done: false },
      { model: body.model, message: { role: "assistant", content: "finto." }, done: false },
      { ...final, message: { role: "assistant", content: "" } },
    ];
    const pieces = inBlocks(ndjson(lines), 76); // the first cut falls in the middle of the "è" (two bytes)
    const streamBody = new ReadableStream<Uint8Array>({
      start(c) { pieces.forEach((p) => c.enqueue(p)); c.close(); },
    });
    return new Response(streamBody, { headers: { "content-type": "application/x-ndjson" } });
  }
  return Response.json({ ...final, message: { role: "assistant", content: "Fake full response." } });
};

const ollama = new Ollama({ host: "http://localhost:11434", fetch: fakeFetch });

const whole = await ollama.chat({ model: "test-model", messages: [{ role: "user", content: "Ciao" }] });
console.log("without stream ->", whole.message.content);

const flow = await ollama.chat({ model: "test-model", messages: [{ role: "user", content: "Ciao" }], stream: true });
let text = "";
let last: any;
for await (const piece of flow) { text += piece.message.content; last = piece; }
console.log("with stream    ->", JSON.stringify(text), "| eval_count:", last.eval_count);

const emb = await ollama.embed({ model: "embedding-model", input: ["a", "b"] });
console.log("embed          ->", emb.embeddings.length, "vectors of", emb.embeddings[0].length, "numbers");

for (const r of requests) console.log(r.url, "stream =", JSON.stringify(r.body.stream));

// Output:
// without stream -> Fake full response.
// with stream    -> "Ciao, è tutto finto." | eval_count: 4
// embed          -> 2 vectors of 2 numbers
// http://localhost:11434/api/chat stream = false
// http://localhost:11434/api/chat stream = true
// http://localhost:11434/api/embed stream = undefined

The listing builds an Ollama with a fake fetch, which records the address and body of every request. The streaming response is an NDJSON flow cut into blocks of 76 bytes, so that the first cut falls in the middle of the "è" (two bytes in UTF-8) and in the middle of a line. The scripted text is Italian on purpose, because that is the accented letter that makes the test: the reassembled text, "Ciao, è tutto finto." ("Hello, it's all fake."), arrives whole, so the library puts back together split lines and characters. The last three lines of the output show the difference described above: stream = false for the first call, which did not specify it. The eval_count field of the last piece is the number of tokens generated according to the server, here written in the script.

For embeddings the current API is /api/embed, which accepts a string or a list of strings and returns embeddings, one vector per input, already normalized to length one (the embeddings page says so). On computing the cosine and why normalization matters, see Vector databases for web developers. Two rules from the same page always hold: use the same model to index and to query, and use a model designed for embeddings instead of the one you chat with. For overly long input the truncate field is true by default (API schema): the excess text is discarded, not reported, unless you set it to false.

Listing 3: the same request from the native API, with per-request options (curl, not run)
# Without "stream": the native API answers with JSON lines, one per piece
curl http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [{ "role": "user", "content": "Explain the Strategy pattern in two sentences." }],
  "options": { "num_ctx": 8192, "temperature": 0.2 },
  "keep_alive": "10m"
}'

Here options overrides, for this request only, the model's values (num_ctx and temperature are among the options documented in the API schema), and keep_alive decides how long the model stays in memory after the response. The OpenAI-compatible form has nowhere to put num_ctx, and that is the case the next section deals with.

The context window: the defect that produces no errors

The context window is the maximum number of tokens the model keeps in mind: prompt, history and response together. Take an assistant with retrieval like the one in RAG with TypeScript and LangChain.js: if each retrieved snippet weighs 500 tokens and you insert six, the context alone is worth 3,000 tokens, before the question and before the answer (arithmetic of an example, not a measurement). A window of 2,048 tokens does not contain them, and the application throws no exception: the model answers, perhaps well, based on only a part of what you retrieved.

The default value is not the same throughout the documentation: the Modelfile page indicates 2048 for num_ctx, the one dedicated to context length says it depends on video memory (4k under 24 GiB, higher for larger machines). The two pages say different things because they reflect different versions of the program, and that is the argument for trusting neither of them: look at the CONTEXT column of ollama ps on your installation. In the pages I read there is no description of what happens to a prompt longer than the window, and I did not try it here; the signal to check is the prompt_eval_count field of the response, the number of prompt tokens according to the server.

  • In the Modelfile: PARAMETER num_ctx 8192 fixes the value for that model.
  • In the native request: "options": { "num_ctx": 8192 } changes it for one call.
  • On the server: the OLLAMA_CONTEXT_LENGTH variable changes the value for all models.

They are three entry points of increasing scope: one call, one model, the whole server. If you use the API compatible with OpenAI, which does not let you indicate the context (its page says so: you need a Modelfile with PARAMETER num_ctx and a new model created with ollama create), the per-call route does not exist. More context is not free: the memory required grows, and with parallel requests it grows with the product of OLLAMA_NUM_PARALLEL and the context length, as the FAQ writes.

Listing 4: configuring the systemd service (schema to adapt, not run)
# /etc/systemd/system/ollama.service.d/override.conf  (created with: sudo systemctl edit ollama)
[Service]
Environment="OLLAMA_CONTEXT_LENGTH=8192"
Environment="OLLAMA_KEEP_ALIVE=30m"
Environment="OLLAMA_NUM_PARALLEL=1"

The file, which is created with sudo systemctl edit ollama as the documentation's Linux page indicates, sets three environment variables for the service's process only: a larger context, the model kept in memory for 30 minutes instead of 5, a single request per model at a time. Choose the values with ollama ps in front of you: if the PROCESSOR column starts to show a split between GPU and CPU, you have asked for more memory than the card has, and generation slows down.

A custom model with the Modelfile

A Modelfile is the file with which you create a variant of an existing model: starting model (FROM), system message (SYSTEM) and parameters (PARAMETER). It resembles a Dockerfile, but it builds a new name in your list of models, which you then call like any other. It is the way to bring into a service the settings you would otherwise repeat in every request, and the only one to fix the context when you use the OpenAI-compatible API.

Listing 5: a code reviewer (Modelfile, not run)
# Modelfile: starts from an already downloaded model and fixes its behavior
FROM llama3.2

SYSTEM """
You are a TypeScript and Angular code reviewer.
For each snippet state the most serious defect first, then propose the fix.
Answer in English and do not invent APIs: if you are not sure, say so.
"""

PARAMETER temperature 0.2
PARAMETER num_ctx 8192
PARAMETER num_predict 1024

FROM is mandatory and writes the source: an already downloaded model, a folder of weights or a GGUF file. SYSTEM writes the stable instructions; the low temperature (0.2) makes the responses more repeatable, useful in a review, and num_predict limits the length of the response, where the default is no limit. I deliberately left out TEMPLATE: it is the prompt template specific to the model family, and many examples in circulation copy by hand the one for Llama 3 with its special markers. If you then change the FROM to a model of another family, that template presents the model with a format it does not know. The starting model already has one, which ollama show --modelfile llama3.2 displays (the Modelfile page gives an example): rewrite it only if you know which format the model expects.

Listing 6: creating and using the model (shell, not run)
ollama create reviewer -f ./Modelfile     # builds the "reviewer" model
ollama list                               # now it shows up next to the others
ollama run reviewer                       # you try it in the terminal

# From the app, "reviewer" is a model name like any other:
curl http://localhost:11434/v1/chat/completions -d '{
  "model": "reviewer",
  "messages": [{ "role": "user", "content": "const d = await fetch(url).then(r => r.json());" }]
}'

ollama create reviewer -f ./Modelfile downloads nothing new if the starting model's weights are already on disk: it adds an entry with your settings. The call to /v1/chat/completions with "model": "reviewer" shows the practical gain: the app does not know the system message, the context or the temperature, which live in the model. Changing them does not require touching or redeploying the code, just as it happens for a parameter in an environment variable.

Ollama in a Docker container

For a shared machine or a server the container gives a reproducible environment, and the official documentation proposes one command for CPU only and one for NVIDIA or AMD GPUs (which require the respective drivers or toolkit on the host). In the command you see below I have one difference from the documentation's: the port is published as 127.0.0.1:11434:11434 instead of 11434:11434.

Listing 7: Ollama in Docker, CPU only (not run, no Docker on this machine)
# CPU only. The 127.0.0.1 in front of the port is the difference between "only me" and "the whole network"
docker run -d -v ollama:/root/.ollama -p 127.0.0.1:11434:11434 --name ollama ollama/ollama

# Download and run a model inside the container
docker exec -it ollama ollama run llama3.2

The difference is all about security. Docker's guide on publishing ports says that, without an address, the port is published on all of the host's interfaces and that publishing ports is "insecure by default"; it talks about firewall rules that Docker writes on its own, so do not take for granted that the host's firewall stops that port: try to reach it from another machine. Ollama has no authentication of its own: its FAQ says it normally binds to 127.0.0.1 and that to expose it on the network you change OLLAMA_HOST. Whoever reaches the port can have models run, download new ones and consume your CPU. If another machine has to reach it, put a reverse proxy in front of it (the same FAQ shows an Nginx example) to which you add authentication yourself.

Moving from local to an external service without rewriting

Since Ollama understands the shape of OpenAI's requests on /v1, the openai SDK works by changing the base address. The apiKey field is mandatory for the constructor but Ollama ignores it, as the documentation writes. The good practice, already seen in the article on the APIs, is that address, key and model name live in configuration, not in the code: that way you develop against the local model and in production you change three variables.

Listing 8: a single point where we decide whom we talk to (run with a fake fetch, openai 7.56.0)
import OpenAI from "openai";

interface Config {
  AI_BASE_URL?: string; // absent = the SDK's default address
  AI_API_KEY?: string;
  AI_MODEL?: string;
}

// A single point where we decide whom we talk to. The rest of the app only sees "client" and "model".
export function createClient(env: Config, testFetch?: typeof fetch) {
  if (!env.AI_MODEL) throw new Error("AI_MODEL missing: the model name belongs in the configuration");
  const client = new OpenAI({
    baseURL: env.AI_BASE_URL,
    apiKey: env.AI_API_KEY ?? "not-set",
    maxRetries: 0, // here the caller governs the retries: in a test you want just one attempt
    fetch: testFetch,
  });
  return { client, model: env.AI_MODEL };
}

// Fake fetch: records address and header, answers with a scripted Chat Completions.
const seen: string[] = [];
const fake: typeof fetch = async (url, init) => {
  const h = new Headers(init?.headers);
  const body = JSON.parse(String(init?.body));
  seen.push(`${String(url)} | Authorization: ${h.get("authorization")} | model: ${body.model}`);
  return Response.json({
    id: "test", object: "chat.completion", created: 0, model: body.model,
    choices: [{ index: 0, finish_reason: "stop", message: { role: "assistant", content: "ok", refusal: null } }],
    usage: { prompt_tokens: 3, completion_tokens: 1, total_tokens: 4 },
  });
};

const configs: Record<string, Config> = {
  development: { AI_BASE_URL: "http://localhost:11434/v1", AI_API_KEY: "ollama", AI_MODEL: "local-model" },
  production: { AI_API_KEY: "test-secret-key", AI_MODEL: "provider-model" },
};

for (const [name, cfg] of Object.entries(configs)) {
  const { client, model } = createClient(cfg, fake);
  const r = await client.chat.completions.create({ model, messages: [{ role: "user", content: "Hello" }] });
  console.log(name.padEnd(11), "->", r.choices[0].message.content);
}
seen.forEach((v) => console.log(v));

try { createClient({ AI_API_KEY: "x" }); } catch (e) { console.log("expected error:", (e as Error).message); }

// Output:
// development -> ok
// production  -> ok
// http://localhost:11434/v1/chat/completions | Authorization: Bearer ollama | model: local-model
// https://api.openai.com/v1/chat/completions | Authorization: Bearer test-secret-key | model: provider-model
// expected error: AI_MODEL missing: the model name belongs in the configuration

The createClient function is the only one to know the address. With AI_BASE_URL absent the SDK uses its default address, and the output shows the two requests: to localhost:11434/v1 with the Bearer ollama header, and to the default address with the test key. maxRetries: 0 is a choice of this test, not general advice: normally SDKs retry on their own, as the article on the APIs explains. The error on the last line is intended: a missing model name must stop startup, not silently pick a value.

"Compatible" does not mean identical, and that is the point the switch does not solve. The compatibility page lists the supported request fields, and for those that do not appear it does not say what happens: try them before counting on them. Besides this, a local model and an external one answer the same prompt differently. An application that works in development therefore does not prove that it works in production with another model: you need a test on the same set of questions. LM Studio, an alternative with a graphical interface, also exposes a compatible server; its documentation assumes port 1234 and shows the TypeScript example with baseUrl (wrong capitalization: the SDK's option is called baseURL, as in the listing above).

Handling the two ways it breaks

A local client fails in two different ways that require different actions. If the server is not started no response arrives: fetch throws a network exception. If the server is there but the model has not been downloaded, an HTTP response arrives with a code and a JSON body, and the ollama package turns it into an exception with status_code. Telling them apart lets you say to the user, or to the log, which of the two commands is missing: ollama serve or ollama pull.

Listing 9: telling a stopped server from a missing model (run with a fake fetch)
import { Ollama } from "ollama";

// The ResponseError class exists in the package (0.6.4) but is not exported: it is recognized by name.
interface ServerError extends Error { status_code: number }
const isServerError = (e: unknown): e is ServerError => e instanceof Error && e.name === "ResponseError";

// Two different failures, simulated with a fake fetch:
//  - the server is not there (the connection is refused: fetch throws an exception)
//  - the server is there but the model has not been downloaded (404 response with a JSON body)
const mode = { current: "off" as "off" | "no-model" };
const fakeFetch: typeof fetch = async () => {
  if (mode.current === "off") throw new TypeError("fetch failed");
  return Response.json({ error: "scripted message: model not found" }, { status: 404 });
};
const ollama = new Ollama({ host: "http://localhost:11434", fetch: fakeFetch });

async function ask(): Promise<string> {
  try {
    const r = await ollama.chat({ model: "test-model", messages: [{ role: "user", content: "Hello" }] });
    return r.message.content;
  } catch (e) {
    if (isServerError(e)) {
      // The server answered: the HTTP status says what to do.
      return e.status_code === 404
        ? `[404] model missing: run "ollama pull" and try again (${e.message})`
        : `[${e.status_code}] server error: ${e.message}`;
    }
    // No answer: server off, wrong port, network.
    return `[no response] is ollama serve running? (${(e as Error).message})`;
  }
}

for (const m of ["off", "no-model"] as const) {
  mode.current = m;
  console.log(m.padEnd(14), "->", await ask());
}

// Output:
// off            -> [no response] is ollama serve running? (fetch failed)
// no-model       -> [404] model missing: run "ollama pull" and try again (scripted message: model not found)

In the 0.6.4 package the ResponseError class exists but is not exported (tried: the import fails with "does not provide an export named"), so the listing recognizes it by name, with the ServerError type written by hand. If you update the package and the export appears, switch to instanceof. The messages in the output are those of the script, not those of the real server: you will read the real text on your first try.

Measuring speed on your machine

A benchmark that counts the pieces of the stream and calls them tokens is wrong, because a piece can contain more than one token. The server declares in the final response how many it generated (eval_count) and in how many nanoseconds (eval_duration), with load_duration for loading the model and prompt_eval_count for the prompt. Dividing the first two is the generation speed, with no estimates.

Listing 10: tokens per second from the server's fields (run with a script, these are not measurements)
import { Ollama } from "ollama";

// Script: the duration and token numbers are written here. They are NOT measurements of a model.
const SCRIPT = [
  { load_duration: 4_000_000_000, eval_count: 100, eval_duration: 10_000_000_000, prompt_eval_count: 30 },
  { load_duration: 20_000_000, eval_count: 120, eval_duration: 12_000_000_000, prompt_eval_count: 30 },
  { load_duration: 18_000_000, eval_count: 90, eval_duration: 10_000_000_000, prompt_eval_count: 30 },
  { load_duration: 21_000_000, eval_count: 110, eval_duration: 10_000_000_000, prompt_eval_count: 30 },
];
let call = 0;
const fakeFetch: typeof fetch = async (_url, init) => {
  const c = SCRIPT[call++ % SCRIPT.length];
  return Response.json({ model: JSON.parse(String(init?.body)).model, done: true, done_reason: "stop",
    message: { role: "assistant", content: "..." }, ...c });
};

const ollama = new Ollama({ host: "http://localhost:11434", fetch: fakeFetch });

interface Step { tokensPerSecond: number; loadMs: number; promptTokens: number }

async function oneMeasurement(model: string, prompt: string): Promise<Step> {
  const r = await ollama.chat({ model, messages: [{ role: "user", content: prompt }] });
  // Durations in nanoseconds, tokens counted by the server: no counting of the stream's pieces.
  return {
    tokensPerSecond: r.eval_count / (r.eval_duration / 1e9),
    loadMs: r.load_duration / 1e6,
    promptTokens: r.prompt_eval_count,
  };
}

const trials = 4;
const steps: Step[] = [];
for (let i = 0; i < trials; i++) steps.push(await oneMeasurement("test-model", "Explain the Observer pattern."));

steps.forEach((p, i) => console.log(`trial ${i + 1}: ${p.tokensPerSecond.toFixed(1)} tokens/s, load ${p.loadMs.toFixed(0)} ms, prompt ${p.promptTokens} tokens`));

const warm = steps.slice(1).map((p) => p.tokensPerSecond); // the first trial pays for loading the model
console.log(`warm: from ${Math.min(...warm).toFixed(1)} to ${Math.max(...warm).toFixed(1)} tokens/s over ${warm.length} trials`);

// Output:
// trial 1: 10.0 tokens/s, load 4000 ms, prompt 30 tokens
// trial 2: 10.0 tokens/s, load 20 ms, prompt 30 tokens
// trial 3: 9.0 tokens/s, load 18 ms, prompt 30 tokens
// trial 4: 11.0 tokens/s, load 21 ms, prompt 30 tokens
// warm: from 9.0 to 11.0 tokens/s over 3 trials

The first trial has a load of 4,000 ms in the script, the following ones about twenty: the first pays for loading the model, so it is discarded (slice(1)) and a range is reported, not an average of a single run. The script's values, from 9 to 11 tokens per second, are written to make the listing run, not measured. On your machine repeat the trial several times, with prompts of a length similar to the real ones, and note the machine, the Ollama version and the model: the speed changes with the available memory, with the context length and with the load of the moment.

When local is not enough

The local model is the right choice in some specific cases, and the wrong one in others. Three questions help to decide, and they are more useful than a table of advantages.

  • Can the data leave? If not, local is mandatory and the comparison is among local models.
  • How many requests at once? One model at a time is comfortable for a developer, not for a hundred simultaneous users.
  • How good does it need to be? If the task requires long reasoning, compare the local model and an external service on your own examples.

The second question is the one that surprises most: by default Ollama processes in parallel a limited number of requests per model (OLLAMA_NUM_PARALLEL, it is 1 in the FAQ) and queues the others up to OLLAMA_MAX_QUEUE before rejecting them. An interface that serves many users together needs a deliberate queue, not luck. When you need to specialize the behavior beyond the prompt, the next step is to work out whether retrieval or training pays off, the subject of Fine-tuning vs RAG.

What you can do now

You can choose between local and external on the three things that matter, and you know that the data constraint holds only if you switch off the cloud features. You can use Ollama's two APIs, and know where the behavior changes (the default streaming, the context that cannot be set in the compatible API). You can fix the context window in three places and check it with ollama ps, create a variant with a Modelfile without overriding the template, publish the container's port only locally, separate the model's address in configuration and measure tokens per second with the fields the server declares. What stays outside a test without a model is the quality of the answers and the real speed: they are measured on your machine. The next step is to give the model tools to use, in AI Agents.

Frequently asked questions

Is Ollama really private?

With a local model, yes: the official FAQ says that locally Ollama does not see the prompts. With the cloud models that Ollama itself offers, no, because its service processes them. If the requirement is that nothing leaves, switch off the cloud features with OLLAMA_NO_CLOUD=1 and protect the port, because the server has no authentication.

Can I use the OpenAI SDK with Ollama?

Yes, by changing baseURL to http://localhost:11434/v1 and passing any key, which Ollama ignores. Check the supported fields on the compatibility page, though, and remember that the context size cannot be set from that API: it has to be fixed with a Modelfile or with the server configuration.

How much memory does a model need?

It depends on the model, on its quantization and on the context window you ask for, and a number written in an article gets old. Load the model with the context you will use and read the SIZE column of ollama ps: it is the answer for your machine.

Sources

Listings 2, 8, 9 and 10 were run with Node 24.11 without a network, with ollama 0.6.4 and openai 7.56.0 and a fake fetch following a script, twice with identical output; they compile with TypeScript 7.0.2. Tokens, durations and error messages in the output are those of the script. Listings 1, 3, 4, 5, 6 and 7 are schemas to adapt and were not run: no model was downloaded or called, no server started, no container created.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects