@noetaris/harness-google
v0.15.1
Published
Google Gemini adapter for @noetaris/harness
Downloads
1,330
Readme
@noetaris/harness-google
Google Gemini adapter for @noetaris/harness.
Overview
@noetaris/harness-google provides a Gemini class that implements the LLM and ObserverAware interfaces from @noetaris/harness. It handles translation between the harness message format and the Google Generative AI SDK (generateContent) format, and emits telemetry events (token usage, model ID) through an attached Observer.
Installation
pnpm add @noetaris/harness-googlePeer 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.12.0 or later.
Usage
import { createHarness, createAgent, field, runtime } from '@noetaris/harness'
import type { LLM, Message } from '@noetaris/harness-types'
import { Gemini } from '@noetaris/harness-google'
// The model ID is the required first argument; options are optional.
const llm = new Gemini('gemini-2.5-flash-lite') // apiKey defaults to the GEMINI_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
Gemini
new Gemini(model: string, options?: GeminiOptions)Implements LLM and ObserverAware. GeminiOptions accepts apiKey (defaults
to the GEMINI_API_KEY env var) and the generation parameters temperature,
maxTokens, topP, topK, and thinkingConfig, and captureIO (below).
thinkingConfig takes a budget or a level, not both, and includeThoughts:
| Field | Models |
|---|---|
| thinkingBudget: number | Gemini 2.5. Gemini 3 accepts it too; Gemini 4 maps it to the nearest level. |
| thinkingLevel: 'minimal' \| 'low' \| 'medium' \| 'high' \| 'xhigh' | Gemini 3 and later. Each model accepts only some levels; see Google's thinking guide. |
| includeThoughts: boolean | Models that think. With true, Gemini returns a summary of its thinking as LLMResponse.reasoning. Default: no summary. |
The adapter sends it as is, so the API rejects a value the model does not accept.
invoke(messages, options?)—optionsis{ tools?, signal?, system? }(InvokeOptions). Translates harnessMessage[]andTool[]to Google Generative AI SDK format, callsgenerateContent(), and maps the response back to anLLMResponse(including function-call extraction from candidates and a requiredusage: { inputTokens, outputTokens, reasoningTokens?, cacheReadTokens, contextWindowSize? }field; see Prompt caching). Parts markedthoughtare left out oftext; their text isreasoning.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: 'gcp.gemini', callId }) before the call and an"llm.response"event ({ tokens: { input, output, reasoning?, cacheRead }, modelId, stopReason, providerName, contextWindowSize?, callId }) from the responseusageMetadataafter 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 provider request (generateContent()) 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. The one-time context-window lookup runs before the request, outside that scope. 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:
import { readFileSync } from 'node:fs'
import { Gemini } from '@noetaris/harness-google'
const llm = new Gemini('gemini-2.5-flash-lite')
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' },
],
},
])- No type check. The adapter sends any
mediaTypeasinlineData.mimeTypeand throws nothing. The provider decides. Gemini's image guide lists PNG, JPEG, WEBP, HEIC and HEIF. datais raw base64, passed through unchanged. Do not add adata:prefix.- Size: Gemini's guide says inline image data limits the total request size (text, system instructions and inline bytes) to 20 MB.
- API shape: the adapter calls
generateContent, which takes aninlineDatapart (mimeType,data). Gemini's image guide shows base64 in the Interactions API shape, so do not copy its snippet. - 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.
- The adapter imports
toBlocksfrom@noetaris/harness-typesat runtime, so that package must be installed (it is listed above as a peer dependency). - Images kept in session state are stored again on every run. See Large media in session state.
Image output
Image output is not supported. If Gemini returns image parts (inlineData), the adapter drops them and returns the rest of the response as usual. It emits one Node process warning per process, so the loss is visible. Other parts it cannot map (fileData, executableCode, codeExecutionResult) are dropped the same way, with one warning per kind.
System prompt
Pass system to invoke. The adapter sends it as Gemini's config.systemInstruction:
await llm.invoke(messages, { system: 'You are a careful code reviewer.' })
// → config.systemInstruction: 'You are a careful code reviewer.'
await llm.invoke(messages, {
system: [{ type: 'text', text: styleGuide }, { type: 'text', text: 'Review the diff below.' }],
})
// → config.systemInstruction: { parts: [{ text: … }, { text: … }] }- A string is sent as a string. Text blocks are sent as one content with one text part per block, in order, and no role.
cachePointis not sent (see below). - No
systemoption: nosystemInstructionis sent. An empty string is sent as'', an empty array as{ parts: [] }. - The meaning of the option is in the
typesREADME.
Prompt caching
Gemini caches repeated prompt prefixes by itself (implicit caching); there is nothing to mark.
cachePointon a block is ignored: the adapter does not send it.usage.cacheReadTokensis always present: Gemini'scachedContentTokenCount, or0when it reports none.usage.cacheWriteTokensis never present: Gemini does not report how many tokens it wrote to its cache.usage.cacheWriteTokensByTtlis never present.usage.inputTokensis Gemini'spromptTokenCount, which already includes the cached tokens.usage.outputTokensis Gemini'scandidatesTokenCountplusthoughtsTokenCount, so it includes thinking tokens.usage.reasoningTokensis Gemini'sthoughtsTokenCount, a part ofoutputTokens. It is absent when Gemini does not report it.- The
"llm.response"event carries the same numbers astokens.cacheRead. - Explicit caching (Gemini's
CachedContentAPI) is not supported by this adapter.
The price formula is in the types README.
Thought signatures
Gemini 3 and later return a thought signature with a function call. It must go back with the call on the next request, or the API answers 400. The adapter keeps it on the tool call, so it is saved with the conversation:
res.toolCalls[0].providerState // { gemini: { thoughtSignature: 'Cq0C…' } }- Put
res.toolCallsin the history as they are. The signature then survives a session store and a resume on a newGeminiinstance. - The adapter sends each stored signature back on the same function call.
- The first call of a turn with no signature (history from another provider, or calls rebuilt as
{ id, name, input }) gets Google's dummy valueskip_thought_signature_validator. The request works, but the model loses its earlier thinking. - Other providers' keys in
providerStateare ignored.
The field is described in the types README.
Cancelling a call
Pass an AbortSignal as signal. The adapter hands it to the SDK as config.abortSignal:
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's own error.- 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 one-time context-window lookup on the first call is not cancelled; if the signal aborts during it,
invokerejects right after it, with no event. - Gemini's own caveat: the SDK says an abort is client-only. It does not cancel the request in the service, and you are still charged for it. Aborting frees your code from waiting; it does not save the cost.
The full rules are in the types README.
Blocked prompts
Gemini can block the prompt itself. Then the response has no candidates, only promptFeedback.blockReason. The adapter returns this as a refusal, the same way it returns a blocked answer:
{ text: '', toolCalls: [], stopReason: 'refusal', providerStopReason: 'SAFETY', usage: { ... } }providerStopReasonis the rawblockReason, such asSAFETY,OTHER,BLOCKLISTorPROHIBITED_CONTENT.usagecomes fromusageMetadata, as for any response."llm.response"is emitted, not"llm.error".- A response with no candidates and no
blockReasonstill throwsGemini response contained no candidates.
A blocked answer (a candidate with finishReason such as SAFETY) also gives stopReason: 'refusal', with the raw finishReason on providerStopReason.
Retries
The adapter does not retry a failed call. It makes one request per invoke. The @google/genai SDK retries only when httpOptions.retryOptions is set, and the adapter does not set it. If you want retries, add them around invoke.
MockGemini
A deterministic test double for use in tests and demos without a real API key.
new MockGemini(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 MockGemini(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-otel— OpenTelemetry observer bridge@noetaris/harness-otel-genai— GenAI semantic-conventions extension (chatspans, token metrics)
License
MIT
