@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-ollamaPeer dependencies:
pnpm add @noetaris/harness @noetaris/harness-typesRequires 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?)—optionsis{ tools?, signal?, system? }(InvokeOptions). Translates harnessMessage[]andTool[]to the Ollama format, calls/api/chatwithstream: false, and maps the response back to anLLMResponse(including a requiredusage: { inputTokens, outputTokens, contextWindowSize? }field; see Prompt caching and token counts). A thinking model'smessage.thinkingisreasoning, apart fromtext.usage.reasoningTokensis never set: Ollama counts thinking insideeval_countand reports no separate count. A non-2xx response throwsOllamaApiError, which carriesstatus.withTelemetry(telemetry)— returns a per-call-scoped view of the adapter (anLLM). The harness calls it once per step, and once per branch, and installs the result asctx.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 outsideagent.run()can instead passtelemetryoninvoke's options. Eachinvokeemits 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 samecallId, so an observer can pair them.- Request scope — inside
agent.run(), the HTTP exchange with the server (fetchand reading the response body, including an error body) runs insidetc.within('llm.request', { callId }), the scope of the"llm.request"event. With the OTel observer and its GenAI extension (@noetaris/harness-otel-genai) thechatspan 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(defaultfalse) — withtrue,"llm.request"also carriesmessages,toolsandsystem(the harness values passed toinvoke, not the translated provider payload;toolsandsystemonly when you passed them) and"llm.response"carriesoutput, theLLMResponsereturned to you. They may contain sensitive data. The GenAI extension records them only when itscaptureInputs/captureOutputsoption 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.requestevent 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 anOllamaApiError. - 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 onecontentstring, and the images go in a separateimageslist. Texts keep their order and images keep theirs, but the order between text and images is lost. Images only gives an emptycontent. datais raw base64, passed through unchanged. Do not add adata: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
imageskey. - 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.contextWindowSizeandcontextWindowSizeon"llm.response".GET /api/pson the server shows it ascontext_lengthof the loaded model. - Unset. No
num_ctxis sent, and nooptionskey at all when the generation parameters are unset too. The server picks the context length: itsOLLAMA_CONTEXT_LENGTHsetting, the model's Modelfile, or Ollama's own default. The adapter does not ask the server for that number, socontextWindowSizeis 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_ctxafter one with it. That takes seconds and drops the prompt cache. Use onenumCtxfor all instances and clients that share a model on a server. - Memory. A larger window takes more memory. On one machine
qwen3:4btook 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: falseturns thinking off. The answer then gets the wholemaxTokensbudget, and the call is faster.think: trueturns it on. The thinking comes back asreasoning.- No
think: nothing is sent, and the server's default applies. - For a model that cannot think, the server rejects
think: truewith HTTP 400, soinvokethrowsOllamaApiError. 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. cachePointis not sent. Nosystemoption: 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
typesREADME.
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.cacheReadTokensandusage.cacheWriteTokensare never set (absent means unknown, not0), and neither aretokens.cacheRead/tokens.cacheWriteon"llm.response". cachePointon a block is ignored.usage.cacheWriteTokensByTtlis not reported.- Token counts on cache reuse:
usage.inputTokensis Ollama'sprompt_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, whileprompt_eval_durationfell 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 aprompt_eval_cached_countfield, 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 })invokerejects withsignal.reason(anAbortErrororTimeoutErrorDOMExceptionfor the default reasons).- Already aborted when
invokeis called: it rejects at once, with no event and no request. - Aborted after
"llm.request":"llm.error"is emitted witherror: signal.reason, theninvokerejects 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 themessages,toolsandsystempassed toinvokeas given (the mock does no translation) and"llm.response"carries the returned response asoutput.latencyMs— waits that long before answering. The wait listens to the call'ssignal, so a test can cut a slow call withAbortSignal.timeout()orctx.signal.- Abort behaves as in the adapter: already aborted → rejects with
signal.reasonand emits nothing; aborted while waiting →"llm.error"withsignal.reason, then rejects with it. "llm.response"tokensare theusageof the returned response (reasoning/cacheRead/cacheWrite/cacheWriteByTtlonly when that usage has them).lastMessagesandlastOptionshold the messages and the options (tools,signal,system; nottelemetry) 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
@noetaris/harness— core execution engine@noetaris/harness-types— shared LLM type contract@noetaris/harness-anthropic— Anthropic Claude adapter@noetaris/harness-openai— OpenAI adapter@noetaris/harness-google— Google Gemini adapter@noetaris/harness-otel— OpenTelemetry observer bridge@noetaris/harness-otel-genai— GenAI semantic-conventions extension (chatspans, token metrics)
License
MIT
