@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-openaiPeer 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?)—optionsis{ tools?, signal?, system? }(InvokeOptions). Translates harnessMessage[]andTool[]to Responses input items and function tools (strict: false), callsresponses.create(), and maps the output items back to anLLMResponse(the text and the tool calls of one reply, and a requiredusage: { inputTokens, outputTokens, reasoningTokens?, cacheReadTokens, cacheWriteTokens?, cacheWriteTokensByTtl?, contextWindowSize? }field;contextWindowSizeis resolved from@noetaris/harness-openai-models; see Prompt caching).reasoningTokensis OpenAI'soutput_tokens_details.reasoning_tokens, a part ofoutputTokens, present when OpenAI reports it.reasoningholds 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 (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: 'openai', callId }) before the call and an"llm.response"event ({ tokens: { input, output, reasoning?, cacheRead, cacheWrite? }, modelId, stopReason, providerName, contextWindowSize?, callId }) from the responseusageafter 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.- Stop reasons —
stopReasonis'tool_use'when the reply has function calls,'max_tokens'forincomplete_details.reasonmax_output_tokens, and'refusal'forcontent_filteror a refusal part in the reply (its text goes intext). Anything else is'end'.providerStopReasonis the rawincomplete_details.reason, or else the responsestatus('completed'). A cut-off reply returns no tool calls. Afailedresponse throws. - Request scope — inside
agent.run(), the provider request (responses.create()) 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.
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: falseis 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 asproviderState.openai, plain JSON. Copyresponse.toolCallsinto the assistant message as they are, and the adapter sends the items back with their calls on the nextinvoke. 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
providerStateare ignored, and badly shapedopenaivalues 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.requestevent is emitted:Error: Unsupported image media type "image/bmp" for OpenAI. Supported: image/jpeg, image/png, image/gif, image/webp. datais raw base64. The adapter builds thedata:<mediaType>;base64,<data>URL itself and sends it as aninput_imagepart withdetail: 'auto'. Ifdataalready starts withdata:, 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,developermessages replacesystemmessages. The adapter does not useinstructions, which cannot hold a cache breakpoint. - A string is sent as a string; text blocks are sent as
input_textparts, in order. A block'scachePointbecomes a cache breakpoint on its part (see below). - No
systemoption: no developer message is added. An empty string or empty array is sent as given. - The meaning of the option is in the
typesREADME.
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 (acceptsCacheBreakpointsin@noetaris/harness-openai-models). TherecachePointhas 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; removecachePointfor it.
Usage.
usage.cacheReadTokensis always present: thecached_tokensOpenAI reports, or0when it reports none.usage.cacheWriteTokensis OpenAI'scache_write_tokens, present only on models that get cache breakpoints (see above). Older models always send0, even when they write the cache, so there it is absent: the number of tokens written is unknown, not0.usage.inputTokensis OpenAI'sinput_tokens, which already includes the cached tokens. Both cache counts are parts of it.usage.cacheWriteTokensByTtlsplitscacheWriteTokensby TTL, with the keys'30m'and'12h'. It comes from OpenAI'scache_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 tocacheWriteTokens, it is absent. It is also absent wherevercacheWriteTokensis.- The
"llm.response"event carries the same numbers astokens.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 })invokerejects withsignal.reason(anAbortErrororTimeoutErrorDOMExceptionfor the default reasons), not with the SDK'sAPIUserAbortError.- 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. - 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 invokemaxRetries: 0turns the SDK's retries off. Use it when your code owns the retry policy, or when asignaldeadline 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 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 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
@noetaris/harness— core execution engine@noetaris/harness-types— shared LLM type contract@noetaris/harness-openai-models— OpenAI model facts: context windows and cache-breakpoint support@noetaris/harness-anthropic— Anthropic Claude 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
