Skip to content

Commit 5d54a36

Browse files
Peter Steinbergersteipete
authored andcommitted
fix(google): surface blocked Gemini prompts
1 parent 25bb1da commit 5d54a36

4 files changed

Lines changed: 161 additions & 22 deletions

File tree

‎extensions/google/transport-stream.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,61 @@ describe("google transport stream", () => {
541541
expect(result.content[2]).toHaveProperty("thoughtSignature", "Y2FsbF9zaWdfMQ==");
542542
});
543543

544+
it.each([
545+
{
546+
provider: "google",
547+
feedback: { blockReason: "SAFETY" },
548+
expectedCode: "SAFETY",
549+
expectedMessage: "Google prompt blocked (SAFETY)",
550+
},
551+
{
552+
provider: "google",
553+
feedback: {},
554+
expectedCode: "PROMPT_BLOCKED",
555+
expectedMessage: "Google prompt blocked (PROMPT_BLOCKED)",
556+
},
557+
{
558+
provider: "google-vertex",
559+
feedback: {
560+
blockReason: "PROHIBITED_CONTENT",
561+
blockReasonMessage: "Prompt violates provider safety policy",
562+
},
563+
expectedCode: "PROHIBITED_CONTENT",
564+
expectedMessage:
565+
"Google prompt blocked (PROHIBITED_CONTENT): Prompt violates provider safety policy",
566+
},
567+
{
568+
provider: "google-vertex",
569+
feedback: { blockReasonMessage: "Prompt violates provider safety policy" },
570+
expectedCode: "PROMPT_BLOCKED",
571+
expectedMessage:
572+
"Google prompt blocked (PROMPT_BLOCKED): Prompt violates provider safety policy",
573+
},
574+
])(
575+
"surfaces blocked $provider prompts as typed stream errors",
576+
async ({ provider, feedback, expectedCode, expectedMessage }) => {
577+
guardedFetchMock.mockResolvedValueOnce(buildSseResponse([{ promptFeedback: feedback }]));
578+
if (provider === "google-vertex") {
579+
vi.stubEnv("GOOGLE_CLOUD_PROJECT", "vertex-project");
580+
vi.stubEnv("GOOGLE_CLOUD_LOCATION", "global");
581+
googleAuthGetAccessTokenMock.mockResolvedValueOnce("ya29.vertex-token");
582+
}
583+
584+
const result =
585+
provider === "google-vertex"
586+
? await runGoogleVertexStreamResult({ fetch: guardedFetchMock })
587+
: await runGeminiStreamResult({ options: { apiKey: "gemini-api-key" } });
588+
589+
expect(result).toMatchObject({
590+
stopReason: "error",
591+
errorCode: expectedCode,
592+
errorType: "google_prompt_blocked",
593+
errorMessage: expectedMessage,
594+
content: [],
595+
});
596+
},
597+
);
598+
544599
it("rotates Gemini LLM API keys when a pre-stream request is rate limited", async () => {
545600
vi.stubEnv("OPENCLAW_LIVE_GEMINI_KEY", "");
546601
vi.stubEnv("GEMINI_API_KEYS", "gemini-key-2");

‎extensions/google/transport-stream.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,10 @@ const GOOGLE_VERTEX_DEFAULT_API_VERSION = "v1";
130130

131131
type GoogleSseChunk = {
132132
responseId?: string;
133+
promptFeedback?: {
134+
blockReason?: string;
135+
blockReasonMessage?: string;
136+
};
133137
candidates?: Array<{
134138
content?: {
135139
parts?: Array<{
@@ -1343,6 +1347,17 @@ function createGoogleTransportStreamFn(kind: CanonicalGoogleTransportApi): Strea
13431347
output.responseId ||= chunk.responseId;
13441348
updateUsage(output, model, chunk);
13451349
const candidate = chunk.candidates?.[0];
1350+
const promptFeedback = chunk.promptFeedback;
1351+
if (!candidate && promptFeedback) {
1352+
const blockReason =
1353+
normalizeOptionalString(promptFeedback.blockReason) ?? "PROMPT_BLOCKED";
1354+
const blockMessage = normalizeOptionalString(promptFeedback.blockReasonMessage);
1355+
const message = `Google prompt blocked (${blockReason})${blockMessage ? `: ${blockMessage}` : ""}`;
1356+
throw Object.assign(new Error(message), {
1357+
code: blockReason,
1358+
type: "google_prompt_blocked",
1359+
});
1360+
}
13461361
if (candidate?.content?.parts) {
13471362
for (const part of candidate.content.parts) {
13481363
const hasThoughtSignature =

‎packages/ai/src/providers/google-shared.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,66 @@ describe("consumeGoogleGenerateContentStream", () => {
264264
});
265265

266266
describe("runGoogleGenerateContentLifecycle", () => {
267+
it.each([
268+
{ api: "google-generative-ai", blockReason: "SAFETY" },
269+
{ api: "google-generative-ai", blockReason: undefined },
270+
{ api: "google-vertex", blockReason: "SAFETY" },
271+
{ api: "google-vertex", blockReason: undefined },
272+
] as const)(
273+
"surfaces blocked $api prompts as typed stream errors when blockReason is $blockReason",
274+
async ({ api, blockReason }) => {
275+
const targetModel = {
276+
...model,
277+
api,
278+
provider: api === "google-vertex" ? "google-vertex" : "google",
279+
} satisfies Model<"google-generative-ai" | "google-vertex">;
280+
const output: AssistantMessage = {
281+
...createOutput(),
282+
api: targetModel.api,
283+
provider: targetModel.provider,
284+
};
285+
const stream = new AssistantMessageEventStream();
286+
287+
await runGoogleGenerateContentLifecycle({
288+
stream,
289+
model: targetModel,
290+
output,
291+
createClient: () => ({
292+
models: {
293+
generateContentStream: async () =>
294+
chunks([
295+
{
296+
promptFeedback: {
297+
...(blockReason ? { blockReason } : {}),
298+
blockReasonMessage: "Prompt violates provider safety policy",
299+
},
300+
usageMetadata: {
301+
promptTokenCount: 12,
302+
cachedContentTokenCount: 2,
303+
totalTokenCount: 12,
304+
},
305+
} as GenerateContentResponse,
306+
]),
307+
},
308+
}),
309+
buildParams: () => ({ model: targetModel.id, contents: [] }),
310+
nextToolCallId: () => "call_1",
311+
});
312+
313+
const result = await stream.result();
314+
const expectedBlockReason = blockReason ?? "PROMPT_BLOCKED";
315+
expect(result).toMatchObject({
316+
stopReason: "error",
317+
errorCode: expectedBlockReason,
318+
errorType: "google_prompt_blocked",
319+
errorMessage: `Google prompt blocked (${expectedBlockReason}): Prompt violates provider safety policy`,
320+
content: [],
321+
usage: { input: 10, cacheRead: 2, totalTokens: 12 },
322+
});
323+
expect(result.usage.cost.total).toBeGreaterThan(0);
324+
},
325+
);
326+
267327
it("surfaces HTTP response body text from Google-compatible errors", async () => {
268328
const output = createOutput();
269329
const stream = new AssistantMessageEventStream();

‎packages/ai/src/providers/google-shared.ts‎

Lines changed: 31 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -779,7 +779,38 @@ export async function consumeGoogleGenerateContentStream<T extends GoogleApiType
779779

780780
for await (const chunk of params.chunks) {
781781
params.output.responseId ||= chunk.responseId;
782+
if (chunk.usageMetadata) {
783+
params.output.usage = {
784+
input:
785+
(chunk.usageMetadata.promptTokenCount || 0) -
786+
(chunk.usageMetadata.cachedContentTokenCount || 0),
787+
output:
788+
(chunk.usageMetadata.candidatesTokenCount || 0) +
789+
(chunk.usageMetadata.thoughtsTokenCount || 0),
790+
cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,
791+
cacheWrite: 0,
792+
totalTokens: chunk.usageMetadata.totalTokenCount || 0,
793+
cost: {
794+
input: 0,
795+
output: 0,
796+
cacheRead: 0,
797+
cacheWrite: 0,
798+
total: 0,
799+
},
800+
};
801+
calculateCost(params.model, params.output.usage);
802+
}
782803
const candidate = chunk.candidates?.[0];
804+
const promptFeedback = chunk.promptFeedback;
805+
if (!candidate && promptFeedback) {
806+
const blockReason = promptFeedback.blockReason ?? "PROMPT_BLOCKED";
807+
const blockMessage = promptFeedback.blockReasonMessage?.trim();
808+
params.output.errorCode = blockReason;
809+
params.output.errorType = "google_prompt_blocked";
810+
throw new Error(
811+
`Google prompt blocked (${blockReason})${blockMessage ? `: ${blockMessage}` : ""}`,
812+
);
813+
}
783814
if (candidate?.content?.parts) {
784815
for (const part of candidate.content.parts) {
785816
if (part.text !== undefined) {
@@ -881,28 +912,6 @@ export async function consumeGoogleGenerateContentStream<T extends GoogleApiType
881912
params.output.stopReason = "toolUse";
882913
}
883914
}
884-
885-
if (chunk.usageMetadata) {
886-
params.output.usage = {
887-
input:
888-
(chunk.usageMetadata.promptTokenCount || 0) -
889-
(chunk.usageMetadata.cachedContentTokenCount || 0),
890-
output:
891-
(chunk.usageMetadata.candidatesTokenCount || 0) +
892-
(chunk.usageMetadata.thoughtsTokenCount || 0),
893-
cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,
894-
cacheWrite: 0,
895-
totalTokens: chunk.usageMetadata.totalTokenCount || 0,
896-
cost: {
897-
input: 0,
898-
output: 0,
899-
cacheRead: 0,
900-
cacheWrite: 0,
901-
total: 0,
902-
},
903-
};
904-
calculateCost(params.model, params.output.usage);
905-
}
906915
}
907916

908917
endCurrentBlock();

0 commit comments

Comments
 (0)