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

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.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?) — options is { tools?, signal?, system? } (InvokeOptions). Translates harness Message[] and Tool[] to Google Generative AI SDK format, calls generateContent(), and maps the response back to an LLMResponse (including function-call extraction from candidates and a required usage: { inputTokens, outputTokens, reasoningTokens?, cacheReadTokens, contextWindowSize? } field; see Prompt caching). Parts marked thought are left out of text; their text is reasoning.
  • 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: 'gcp.gemini', callId }) before the call and an "llm.response" event ({ tokens: { input, output, reasoning?, cacheRead }, modelId, stopReason, providerName, contextWindowSize?, callId }) from the response usageMetadata 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 provider request (generateContent()) 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. 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 (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:

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 mediaType as inlineData.mimeType and throws nothing. The provider decides. Gemini's image guide lists PNG, JPEG, WEBP, HEIC and HEIF.
  • data is raw base64, passed through unchanged. Do not add a data: 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 an inlineData part (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 toBlocks from @noetaris/harness-types at 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. cachePoint is not sent (see below).
  • No system option: no systemInstruction is sent. An empty string is sent as '', an empty array as { parts: [] }.
  • The meaning of the option is in the types README.

Prompt caching

Gemini caches repeated prompt prefixes by itself (implicit caching); there is nothing to mark.

  • cachePoint on a block is ignored: the adapter does not send it.
  • usage.cacheReadTokens is always present: Gemini's cachedContentTokenCount, or 0 when it reports none.
  • usage.cacheWriteTokens is never present: Gemini does not report how many tokens it wrote to its cache.
  • usage.cacheWriteTokensByTtl is never present.
  • usage.inputTokens is Gemini's promptTokenCount, which already includes the cached tokens.
  • usage.outputTokens is Gemini's candidatesTokenCount plus thoughtsTokenCount, so it includes thinking tokens.
  • usage.reasoningTokens is Gemini's thoughtsTokenCount, a part of outputTokens. It is absent when Gemini does not report it.
  • The "llm.response" event carries the same numbers as tokens.cacheRead.
  • Explicit caching (Gemini's CachedContent API) 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.toolCalls in the history as they are. The signature then survives a session store and a resume on a new Gemini instance.
  • 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 value skip_thought_signature_validator. The request works, but the model loses its earlier thinking.
  • Other providers' keys in providerState are 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 })
  • invoke rejects with signal.reason (an AbortError or TimeoutError DOMException for the default reasons), not with the SDK's own error.
  • 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 one-time context-window lookup on the first call is not cancelled; if the signal aborts during it, invoke rejects 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: { ... } }
  • providerStopReason is the raw blockReason, such as SAFETY, OTHER, BLOCKLIST or PROHIBITED_CONTENT.
  • usage comes from usageMetadata, as for any response.
  • "llm.response" is emitted, not "llm.error".
  • A response with no candidates and no blockReason still throws Gemini 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 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 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

License

MIT