npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@noetaris/harness-ollama

v0.13.0

Published

Ollama adapter for @noetaris/harness

Readme

@noetaris/harness-ollama

Ollama adapter for @noetaris/harness.

Overview

@noetaris/harness-ollama provides an Ollama class that implements the LLM and ObserverAware interfaces from @noetaris/harness. It talks to a local Ollama server through POST /api/chat with the built-in fetch, so it has no SDK dependency. It translates harness messages and tools to the Ollama format, and emits telemetry events (token usage, model ID) through an attached Observer.

Installation

pnpm add @noetaris/harness-ollama

Peer dependencies:

pnpm add @noetaris/harness @noetaris/harness-types

Requires Node.js ≥ 22, @noetaris/harness 0.7.0 or later (the provider request runs inside TelemetryContext.within), and @noetaris/harness-types 0.9.0 or later.

Usage

import { createHarness, createAgent, field, runtime } from '@noetaris/harness'
import type { LLM, Message } from '@noetaris/harness-types'
import { Ollama } from '@noetaris/harness-ollama'

// The model tag is the required first argument; options are optional.
const llm = new Ollama('llama3.2', {
  baseUrl: 'http://localhost:11434', // the default
})

const h = createHarness<{ llm: LLM }>()({
  messages: field<Message[]>({ default: () => [], reduce: (a, b) => [...a, ...b] }),
})
  .provide('llm', runtime()) // supplied at agent.run()
  .loop((loop) => {
    loop.start().step('reply', {
      run: async (state, ctx) => {
        const res = await ctx.llm.invoke(state.messages, {
          system: 'You are a helpful assistant.',
          signal: ctx.signal, // let run.stop() cut the call
        })
        return { messages: [{ role: 'assistant', content: res.text }] }
      },
      route: () => 'done',
    }).on('done').end()
  })

const agent = createAgent('my-agent', h, {})
const outcome = await agent.run({ messages: [{ role: 'user', content: 'Hello' }] }, { llm })

No API key is needed.

API

Ollama

new Ollama(model: string, options?: OllamaOptions)

Implements LLM and ObserverAware. OllamaOptions accepts baseUrl (default http://localhost:11434), the generation parameters temperature, maxTokens, topP and topK, and numCtx, captureIO (below), keepAlive (see Prompt caching and token counts), and think (see Thinking). numCtx sets the context window: see Context window.

  • invoke(messages, options?) — options is { tools?, signal?, system? } (InvokeOptions). Translates harness Message[] and Tool[] to the Ollama format, calls /api/chat with stream: false, and maps the response back to an LLMResponse (including a required usage: { inputTokens, outputTokens, contextWindowSize? } field; see Prompt caching and token counts). A thinking model's message.thinking is reasoning, apart from text. usage.reasoningTokens is never set: Ollama counts thinking inside eval_count and reports no separate count. A non-2xx response throws OllamaApiError, which carries status.
  • withTelemetry(telemetry) — returns a per-call-scoped view of the adapter (an LLM). The harness calls it once per step, and once per branch, and installs the result as ctx.llm, so telemetry travels with each call — concurrent fork branches that share one instance are attributed to their own branch, with no shared field to race on. Callers outside agent.run() can instead pass telemetry on invoke's options. Each invoke emits an "llm.request" event ({ modelId, providerName: 'ollama', callId }) before the call and an "llm.response" event ({ tokens: { input, output }, modelId, stopReason, providerName, contextWindowSize?, callId }) after it. If the call throws after "llm.request", an "llm.error" event ({ modelId, providerName, callId, error }, with the thrown value) is emitted instead of "llm.response", and the error then propagates unchanged. Each "llm.request" is followed by exactly one of the two, with the same callId, so an observer can pair them.
  • Request scope — inside agent.run(), the HTTP exchange with the server (fetch and reading the response body, including an error body) runs inside tc.within('llm.request', { callId }), the scope of the "llm.request" event. With the OTel observer and its GenAI extension (@noetaris/harness-otel-genai) the chat span is the active span there, so auto-instrumented HTTP calls nest under it. A provider error emits "llm.error" instead of "llm.response" and propagates unchanged.
  • captureIO (default false) — with true, "llm.request" also carries messages, tools and system (the harness values passed to invoke, not the translated provider payload; tools and system only when you passed them) and "llm.response" carries output, the LLMResponse returned to you. They may contain sensitive data. The GenAI extension records them only when its captureInputs / captureOutputs option is on as well — see Content capture.

Image input

Image input needs @noetaris/harness-types 0.5.0 or later.

A user message can carry images next to text. Pass blocks instead of a string, and use a model that can read images:

import { readFileSync } from 'node:fs'
import { Ollama } from '@noetaris/harness-ollama'

const llm = new Ollama('qwen3.5:4b') // a vision model

const response = await llm.invoke([
  {
    role: 'user',
    content: [
      { type: 'text', text: 'What is in this picture?' },
      { type: 'image', data: readFileSync('photo.png').toString('base64'), mediaType: 'image/png' },
    ],
  },
])
  • Accepted types: image/jpeg, image/png, image/webp, image/bmp. The match is exact and case-sensitive.
  • Anything else throws before any request is sent, and no llm.request event is emitted: Error: Unsupported image media type "image/gif" for Ollama. Supported: image/jpeg, image/png, image/webp, image/bmp.
  • How the list was checked: by hand against Ollama 0.24.0 with one vision model (qwen3.5:4b). On that server, a GIF failed with HTTP 500 (image: unknown format). A different model may not decode every listed type. Then the server returns an error, and you get an OllamaApiError.
  • A text-only model ignores images without an error. The server answers HTTP 200, so the reply may say it cannot see the image, or make something up. Use a vision model. The adapter does not check this.
  • Text and images are not interleaved. Text blocks are joined with a blank line (\n\n) into one content string, and the images go in a separate images list. Texts keep their order and images keep theirs, but the order between text and images is lost. Images only gives an empty content.
  • data is raw base64, passed through unchanged. Do not add a data: prefix. The Ollama API has no field for the media type, so the label is only checked by the adapter. A wrongly labelled image is not detected.
  • String content is sent as before, with no images key.
  • Images kept in session state are stored again on every run. See Large media in session state.

Context window

numCtx is the context window in tokens. The adapter sends it as options.num_ctx on every call, and the server loads the model with that context length:

const llm = new Ollama('qwen3:4b', { numCtx: 8192 })

const res = await llm.invoke(messages)
res.usage.contextWindowSize // 8192
  • Reported size. The same number is usage.contextWindowSize and contextWindowSize on "llm.response". GET /api/ps on the server shows it as context_length of the loaded model.
  • Unset. No num_ctx is sent, and no options key at all when the generation parameters are unset too. The server picks the context length: its OLLAMA_CONTEXT_LENGTH setting, the model's Modelfile, or Ollama's own default. The adapter does not ask the server for that number, so contextWindowSize is absent (unknown).
  • A different value reloads the model. The context length belongs to the loaded model. A call that asks for another value than the loaded one makes the server load the model again, and so does a call without num_ctx after one with it. That takes seconds and drops the prompt cache. Use one numCtx for all instances and clients that share a model on a server.
  • Memory. A larger window takes more memory. On one machine qwen3:4b took 2.9 GB loaded with 2,048 tokens and 3.9 GB with 8,192.
  • No check in the adapter. The value is sent as given. The adapter does not compare it with the model's limit, and the reported number is the value you gave, not one read back from the server.

Checked on Ollama 0.40.5 with qwen3:4b: numCtx 2048, 3000 and 8192 each gave the same context_length in /api/ps, and a call without numCtx reloaded the model with 4096, that server's default.

Thinking

A thinking model writes its thinking before the answer. Ollama counts those tokens against maxTokens (num_predict). If the model thinks long, it can use the whole budget and stop with stopReason: 'max_tokens' and empty text.

Set think to turn thinking on or off. The adapter sends it as think on /api/chat:

const llm = new Ollama('qwen3.5:4b', { think: false, maxTokens: 1024 })
  • think: false turns thinking off. The answer then gets the whole maxTokens budget, and the call is faster.
  • think: true turns it on. The thinking comes back as reasoning.
  • No think: nothing is sent, and the server's default applies.
  • For a model that cannot think, the server rejects think: true with HTTP 400, so invoke throws OllamaApiError. The adapter does not check the model first.

OllamaApiError

Thrown by invoke when the server returns a non-2xx status. It has status (also as statusCode), and its message holds the response body.

System prompt

Pass system to invoke. The adapter sends it as the first message, with role system:

await llm.invoke(messages, { system: 'You are a careful code reviewer.' })
// → [{ role: 'system', content: 'You are a careful code reviewer.' }, ...messages]

await llm.invoke(messages, {
  system: [{ type: 'text', text: styleGuide }, { type: 'text', text: 'Review the diff below.' }],
})
// → [{ role: 'system', content: '<styleGuide>\n\nReview the diff below.' }, ...messages]
  • Ollama takes one string per message, so text blocks are joined with a blank line (\n\n), the same way user text blocks are.
  • cachePoint is not sent. No system option: no system message is added. An empty string or empty array is sent as a system message with empty content.
  • The meaning of the option is in the types README.

Prompt caching and token counts

Ollama keeps a prompt cache (the KV cache) for the loaded model and reuses a prefix it has just processed; there is nothing to mark. The cache lives only as long as the model stays loaded.

keepAlive. How long the server keeps the model loaded after a call, sent as keep_alive: a duration string ('10m', '1h') or a number of seconds. 0 unloads the model right after the call (so nothing is reused), and a negative value keeps it loaded until the server stops. When absent, a loaded model keeps its current duration (the last value any request set); a model loaded fresh gets the server's default (5 minutes, or OLLAMA_KEEP_ALIVE). Checked on Ollama 0.24.0. Values are sent as given; the server rejects what it cannot parse (OllamaApiError).

const llm = new Ollama('qwen3:4b', { keepAlive: '1h' })

keep_alive acts on the whole server, not only this instance. A long value keeps this model's memory taken from other models on a shared server, and another client's request for the same model can change it.

  • Ollama reports no cache counts, so usage.cacheReadTokens and usage.cacheWriteTokens are never set (absent means unknown, not 0), and neither are tokens.cacheRead / tokens.cacheWrite on "llm.response".
  • cachePoint on a block is ignored.
  • usage.cacheWriteTokensByTtl is not reported.
  • Token counts on cache reuse: usage.inputTokens is Ollama's prompt_eval_count. On Ollama 0.24.0 it is the full prompt size even when the KV cache was reused: three calls sharing a 2,949-token prefix all reported 2,949, while prompt_eval_duration fell from 1,284 ms to 13 ms. The reuse shows only in the response time, which the adapter does not report. Older Ollama versions may count only the newly evaluated tokens. Ollama's documentation lists a prompt_eval_cached_count field, but 0.24.0 does not return it, so the adapter does not map it.

Cancelling a call

Pass an AbortSignal as signal. The adapter hands it to fetch, so it cuts both the request and the reading of the response body:

await llm.invoke(messages, { signal: AbortSignal.timeout(30_000) })

// inside a step: let run.stop() cut the call
await ctx.llm.invoke(state.messages, { signal: ctx.signal })
  • invoke rejects with signal.reason (an AbortError or TimeoutError DOMException for the default reasons).
  • Already aborted when invoke is called: it rejects at once, with no event and no request.
  • Aborted after "llm.request": "llm.error" is emitted with error: signal.reason, then invoke rejects with it.
  • The adapter only closes the connection. Whether the Ollama server then stops generating is up to the server.

The full rules are in the types README.

Retries

The adapter does not retry a failed call. It makes one fetch to /api/chat per invoke. If you want retries, add them around invoke.

MockOllama

A deterministic test double for use in tests and demos without a running server.

new MockOllama(responses?, { captureIO, latencyMs }):

  • captureIO: true — "llm.request" carries the messages, tools and system passed to invoke as given (the mock does no translation) and "llm.response" carries the returned response as output.
  • latencyMs — waits that long before answering. The wait listens to the call's signal, so a test can cut a slow call with AbortSignal.timeout() or ctx.signal.
  • Abort behaves as in the adapter: already aborted → rejects with signal.reason and emits nothing; aborted while waiting → "llm.error" with signal.reason, then rejects with it.
  • "llm.response" tokens are the usage of the returned response (reasoning / cacheRead / cacheWrite / cacheWriteByTtl only when that usage has them).
  • lastMessages and lastOptions hold the messages and the options (tools, signal, system; not telemetry) of the last call. Both are set when the call starts, so they are there even when it fails:
const llm = new MockOllama(response, { latencyMs: 5_000 })
// ... run a step that calls ctx.llm.invoke(messages, { signal: ctx.signal })
expect(llm.lastOptions.signal).toBeDefined()

Like the adapter, it answers inside tc.within('llm.request', { callId }). When its queue is empty it emits "llm.error" with the empty-queue error, then throws it.

Related Packages

License

MIT