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-openai

v0.15.0

Published

OpenAI adapter for @noetaris/harness

Readme

@noetaris/harness-openai

OpenAI adapter for @noetaris/harness.

Overview

@noetaris/harness-openai provides an OpenAI class that implements the LLM and ObserverAware interfaces from @noetaris/harness. It handles translation between the harness message format and the OpenAI Responses API (responses.create), and emits telemetry events (token usage, model ID) through an attached Observer.

Models that are not on the Responses API, such as gpt-5-search-api, do not work with this adapter. SUPPORTED-MODELS.md lists which models were checked.

Installation

pnpm add @noetaris/harness-openai

Peer dependencies:

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

@noetaris/harness-openai-models supplies the OpenAI model facts the adapter looks up by model ID: the context window that populates contextWindowSize on responses and usage events, and whether the model accepts cache breakpoints.

Requires Node.js ≥ 22, @noetaris/harness 0.7.0 or later (the provider request runs inside TelemetryContext.within), @noetaris/harness-types 0.12.0 or later, and @noetaris/harness-openai-models 0.2.2 or later. The adapter uses the openai SDK 7.32 or later.

Usage

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

// The model ID is the required first argument; options are optional.
const llm = new OpenAI('gpt-4o-mini') // apiKey defaults to the OPENAI_API_KEY env var

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 })

API

OpenAI

new OpenAI(model: string, options?: OpenAIOptions)

Implements LLM and ObserverAware. OpenAIOptions accepts apiKey, maxRetries (see Retries) and the generation parameters temperature, maxTokens, topP, and reasoningEffort (see Reasoning and tool calls), captureIO (below), and cacheTtl, promptCacheRetention and promptCacheKey (see Prompt caching). maxTokens is sent as max_output_tokens (reasoning tokens included). temperature and topP are sent as given; many reasoning models reject them with a 400.

  • invoke(messages, options?) — options is { tools?, signal?, system? } (InvokeOptions). Translates harness Message[] and Tool[] to Responses input items and function tools (strict: false), calls responses.create(), and maps the output items back to an LLMResponse (the text and the tool calls of one reply, and a required usage: { inputTokens, outputTokens, reasoningTokens?, cacheReadTokens, cacheWriteTokens?, cacheWriteTokensByTtl?, contextWindowSize? } field; contextWindowSize is resolved from @noetaris/harness-openai-models; see Prompt caching). reasoningTokens is OpenAI's output_tokens_details.reasoning_tokens, a part of outputTokens, present when OpenAI reports it. reasoning holds the text of the reasoning summaries in the output, joined by blank lines. The adapter does not ask for summaries, so it is usually absent.
  • 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: 'openai', callId }) before the call and an "llm.response" event ({ tokens: { input, output, reasoning?, cacheRead, cacheWrite? }, modelId, stopReason, providerName, contextWindowSize?, callId }) from the response usage 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.
  • Stop reasons — stopReason is 'tool_use' when the reply has function calls, 'max_tokens' for incomplete_details.reason max_output_tokens, and 'refusal' for content_filter or a refusal part in the reply (its text goes in text). Anything else is 'end'. providerStopReason is the raw incomplete_details.reason, or else the response status ('completed'). A cut-off reply returns no tool calls. A failed response throws.
  • Request scope — inside agent.run(), the provider request (responses.create()) 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.

Reasoning and tool calls

reasoningEffort is sent as reasoning.effort ('none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'). The model decides which values it accepts; models without reasoning reject the field. When it is absent, the model's default applies.

const llm = new OpenAI('gpt-6.2-sol', { reasoningEffort: 'high' })
  • store: false is always sent, so OpenAI keeps no copy of the response. There is no option to change it.
  • Reasoning items come back encrypted (include: ['reasoning.encrypted_content']). The items that came before a function call go on that tool call as providerState.openai, plain JSON. Copy response.toolCalls into the assistant message as they are, and the adapter sends the items back with their calls on the next invoke. The model then does not reason again from the start.
  • Order sent back: the first call's items, the assistant text, then each call, with a later call's items right before it.
  • Items after the last call, or in a reply without calls, are not kept. Other providers' keys in providerState are ignored, and badly shaped openai values are skipped.

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:

import { readFileSync } from 'node:fs'
import { OpenAI } from '@noetaris/harness-openai'

const llm = new OpenAI('gpt-4o-mini')

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/gif, image/webp. The match is exact and case-sensitive. OpenAI's vision guide lists PNG, JPEG, WEBP and non-animated GIF.
  • Anything else throws before any request is sent, and no llm.request event is emitted: Error: Unsupported image media type "image/bmp" for OpenAI. Supported: image/jpeg, image/png, image/gif, image/webp.
  • data is raw base64. The adapter builds the data:<mediaType>;base64,<data> URL itself and sends it as an input_image part with detail: 'auto'. If data already starts with data:, the prefix is not removed and ends up doubled.
  • String content is sent as before. An array becomes one part per block, in the same order.
  • The adapter does not check that the model can read images. The provider decides.
  • Images kept in session state are stored again on every run. See Large media in session state.

System prompt

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

await llm.invoke(messages, { system: 'You are a careful code reviewer.' })
// → [{ role: 'developer', 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: 'developer', content: [{ type: 'input_text', text: … }, { type: 'input_text', text: … }] }, ...messages]
  • The role is always developer. OpenAI's API reference says that with o1 models and newer, developer messages replace system messages. The adapter does not use instructions, which cannot hold a cache breakpoint.
  • A string is sent as a string; text blocks are sent as input_text parts, in order. A block's cachePoint becomes a cache breakpoint on its part (see below).
  • No system option: no developer message is added. An empty string or empty array is sent as given.
  • The meaning of the option is in the types README.

Prompt caching

OpenAI caches the start of long prompts by itself. On gpt-5.6 and later, the end of each message, the developer (system) message included, is cached with nothing marked.

Cache points. cachePoint: true on a text block (system or user) or an image block is sent as prompt_cache_breakpoint: { mode: 'explicit' } on that part. It ends a reusable prefix inside a message, for example a system prompt split into a stable block (marked) and a per-session block:

await llm.invoke(messages, {
  system: [{ type: 'text', text: styleGuide, cachePoint: true }, { type: 'text', text: sessionNotes }],
})
// → developer content: [{ type: 'input_text', text: …, prompt_cache_breakpoint: { mode: 'explicit' } }, { type: 'input_text', text: … }]
  • Observed on gpt-5.6 (October 2026): only the first cache point of a request takes effect, and a cache point earlier in the developer message stops the end of that message from being cached. OpenAI documents up to three. Put the most valuable cache point first.
  • At most 3 cache points per request (system and messages together) on models that get the field. More throws before the call, with no events. Anthropic allows 4, so an agent that also runs on Anthropic should stay within 3.
  • Models before gpt-5.6 reject the field. The adapter leaves it out, and does not count cache points, for models known by name to be older: gpt-3.5, gpt-4.x, chatgpt-, o1/o3/o4, gpt-5 through gpt-5.5, and ft: fine-tunes of them (acceptsCacheBreakpoints in @noetaris/harness-openai-models). There cachePoint has no effect.
  • Other names (Azure deployments, new models) get the field. If such a model is older than gpt-5.6, OpenAI returns a 400 prompt_cache_breakpoint is not supported on this model; remove cachePoint for it.

Usage.

  • usage.cacheReadTokens is always present: the cached_tokens OpenAI reports, or 0 when it reports none.
  • usage.cacheWriteTokens is OpenAI's cache_write_tokens, present only on models that get cache breakpoints (see above). Older models always send 0, even when they write the cache, so there it is absent: the number of tokens written is unknown, not 0.
  • usage.inputTokens is OpenAI's input_tokens, which already includes the cached tokens. Both cache counts are parts of it.
  • usage.cacheWriteTokensByTtl splits cacheWriteTokens by TTL, with the keys '30m' and '12h'. It comes from OpenAI's cache_write_tokens_details (ttl_30m_tokens, ttl_12h_tokens), with zero entries left out, so no writes give {}. When OpenAI sends no details, it is { '30m': cacheWriteTokens }, OpenAI's default TTL. If the details do not add up to cacheWriteTokens, it is absent. It is also absent wherever cacheWriteTokens is.
  • The "llm.response" event carries the same numbers as tokens.cacheRead / tokens.cacheWrite / tokens.cacheWriteByTtl.

Cache TTL. cacheTtl sets the minimum lifetime of every cache write in the request, sent as prompt_cache_options.ttl: '30m' (OpenAI's default) or '12h'. When absent, no prompt_cache_options is sent. Only gpt-5.6 and later take it. Like cachePoint, it is not sent to models known by name to be older (acceptsCacheBreakpoints), so there it has no effect. Writes made with it show up under '12h' in usage.cacheWriteTokensByTtl.

new OpenAI('gpt-5.6-terra', { cacheTtl: '12h' })

Retention. promptCacheRetention sets how long OpenAI may keep the cached prefixes, sent as prompt_cache_retention: 'in_memory' (about 5–10 minutes idle, at most 1 hour) or '24h' (up to 24 hours). It is a maximum. When absent, OpenAI's default applies: 24h, or in_memory for organizations with zero data retention. gpt-5.5 and later accept only '24h'; the adapter does not check the model. OpenAI's SDK marks prompt_cache_retention deprecated in favour of prompt_cache_options.ttl (cacheTtl above). promptCacheRetention still works and is still sent. The two are independent: retention is a maximum, the TTL a minimum, and both can be set. Retention remains the only choice for models before gpt-5.6.

Cache key. promptCacheKey is sent as prompt_cache_key. Requests with the same prefix and key go to the same cache, which raises the hit rate. Keep each key under about 15 requests per minute; above that, requests spread over more machines and hit less often. On gpt-5.6, requests with different keys do not share cache entries (observed October 2026), so a per-tenant key also keeps tenants' cached prefixes apart. The key is a constructor option, so use one instance per tenant:

const llmFor = (tenantId: string) =>
  new OpenAI('gpt-5.5', { promptCacheRetention: '24h', promptCacheKey: tenantId })

The price formula is in the types README.

Cancelling a call

Pass an AbortSignal as signal. The adapter hands it to the OpenAI SDK, which closes the HTTP request when it aborts:

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), not with the SDK's APIUserAbortError.
  • 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.
  • Aborting frees the caller and closes the connection. It does not guarantee that OpenAI stops billing for the request.

The full rules are in the types README.

Retries

The OpenAI SDK retries a failed request by itself. It retries connection errors, 408, 409, 429 and 5xx, twice by default. One invoke then emits one "llm.request" / "llm.response" pair, but the provider may get up to three requests.

Set maxRetries to change this. The adapter passes it to the SDK client:

const llm = new OpenAI('gpt-4o-mini', { maxRetries: 0 }) // one request per invoke
  • maxRetries: 0 turns the SDK's retries off. Use it when your code owns the retry policy, or when a signal deadline should not be spent on retries.
  • No maxRetries: the SDK default applies (2 retries).
  • The adapter has no retry of its own.

MockOpenAI

A deterministic test double for use in tests and demos without a real API key.

new MockOpenAI(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 MockOpenAI(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