Skip to Content
ZeroLeaksDocs
Shield SDKProvider wrappers

Google Gen AI

Wrap your Google Gen AI SDK client with Shield to harden the system instruction, detect injection in user input and tool results, and guard output.

shieldGoogleGenAI wraps your GoogleGenAI client from @google/genai. It intercepts models.generateContent, models.generateContentStream, and chats created with chats.create.

Usage

import { GoogleGenAI } from "@google/genai";
import { shieldGoogleGenAI } from "@zeroleaks/shield/google";

const ai = shieldGoogleGenAI(
  new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }),
  { systemPrompt: "You are a support agent..." }
);

const response = await ai.models.generateContent({
  model: "gemini-3.8-flash",
  contents: userInput,
  config: { systemInstruction: "You are a support agent..." },
});

console.log(response.text); // guarded

What Shield checks

Shield applies the shared behavior to these fields:

StepFields
Hardenconfig.systemInstruction. A string stays a string. In a part, a list of parts, or a content, Shield joins the text parts with newlines, hardens them, and stores the combined text in the first text part. Other parts keep their positions.
Detect user inputEvery user turn in contents, with its text parts joined. As in the SDK, a string, a part, or a list of parts is one user turn. In a list of contents, a turn is a user turn when its role is "user" or missing. Model turns are not scanned.
Detect tool resultsIn every turn: the string values of each functionResponse part's response, and each inlineData part with a text/*, application/json, or application/xml MIME type, whose first 64KB are decoded as UTF-8. Callable tools in config.tools are wrapped; see Automatic function calling.
GuardFor every candidate, its text parts, joined. The result is written back over the same parts: each part keeps its original character count, and the last part receives the remaining text. Every string in each functionCall part's args and partialArgs is also guarded. When a candidate's text is redacted, its logprobsResult is removed.

The wrapper modifies the SDK's own GenerateContentResponse in place, so response.text and response.functionCalls return the guarded values. onOutputFindings is called once per candidate's text and once per function call.

Chats

ai.chats.create() on the wrapped client returns the SDK's own Chat, set up to call the wrapped models, so sendMessage() and sendMessageStream() are guarded like the calls above:

const chat = ai.chats.create({
  model: "gemini-3.8-flash",
  config: { systemInstruction: "You are a support agent..." },
});

const reply = await chat.sendMessage({ message: userInput });

Each turn sends the chat's full history for another check, and the detection cache reuses earlier results. The history stores the guarded text of each reply.

Chats rely on an internal SDK field: the Chats object stores the models its chats call in modelsModule, and the wrapped client's chats points that field at the wrapped models. The integration is tested against @google/genai 2.24. If an SDK version lacks that field, the wrapped client's ai.chats uses the SDK's original implementation and its chats are not guarded. Call ai.models directly in that case.

Automatic function calling

When config.tools contains callable tools, such as one from mcpToTool(), the SDK runs them itself. Within one generateContent call, it calls the model, runs the requested tools, and sends their results back until the model answers. Shield does not see those internal requests, so it wraps each callable tool (unless scanToolResults: false). The parts returned by a tool's callTool() are checked like function responses before the SDK sends them to the model. An injection throws InjectionDetectedError with source: "tool" from generateContent() or the stream.

The final response is guarded as usual.

Options

shieldGoogleGenAI accepts the shared options. One row differs:

OptionTypeDefaultDescription
systemPromptstringconfig.systemInstructionThe system prompt to check output against. Defaults to the text of config.systemInstruction, with its text parts joined with newlines, before hardening.

Streaming

generateContentStream() resolves to an async generator of response chunks. It follows the shared modes like this:

ModeBehavior
"buffer"The promise resolves once the whole stream has been read, and rejects if the stream fails or a leak or finding throws. Each candidate's text across all chunks is guarded as one text and written back over the same parts, each keeping its length and the last one taking the rest. Function calls are guarded part by part. You get every chunk the SDK sent, as the same objects and in order, with finish reasons, usage metadata, and every non-text part.
"chunked"Each candidate's text is guarded every streamingChunkSize characters. Every chunk is kept, with its text parts holding the text that is safe to send so far, which can be empty. Chunks are yielded one behind the stream, so the text still held back at the end goes into the last chunk, ahead of its finish reason and usage. Function calls are guarded part by part, and logprobsResult is removed from chunks with text.

Nothing is dropped and every candidate is guarded. "passthrough" returns the SDK's generator unchanged. With throwOnLeak or blockOnOutputFindings, a finding in function call arguments throws as soon as its chunk arrives. Findings in text throw as described under Chunk boundaries.

Thought parts (thought: true) pass through unchanged in every mode.

Limitations

  • Other models methods, such as embedContent(), countTokens(), and generateImages(), are not guarded. Other client properties, such as ai.files and ai.caches, keep working but are not guarded.
  • ai.interactions, ai.live, and ai.batches are not guarded.
  • These parts are not read: thought parts, executableCode and codeExecutionResult parts, and images, audio, video, and fileData parts, whose files are given by URI and not fetched.
  • Chats depend on the SDK internal described under Chats. Chats created from your unwrapped client are not guarded.
  • With automatic function calling, the model's intermediate turns and response.automaticFunctionCallingHistory are not guarded.

See Limitations for what no wrapper covers.

On this page