Skip to content

Commit 9179a98

Browse files
steipetefr-meyer
andcommitted
fix(google): honor stable Gemini embedding task contracts
Co-authored-by: Franck MEYER <[email protected]>
1 parent 61d2a65 commit 9179a98

5 files changed

Lines changed: 146 additions & 37 deletions

File tree

‎docs/reference/memory-config.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ Use `provider: "openai-compatible"` for a generic OpenAI-compatible
228228
explicitly set. After upgrade, an absent setting resolves to 3072, while an
229229
explicit 768, 1536, or 3072 setting becomes part of the identity. For either
230230
path, check the affected agent with
231-
`openclaw memory status --index --agent <id>`, then rebuild when ready with
231+
`openclaw memory status --deep --agent <id>`, then rebuild when ready with
232232
`openclaw memory index --force --agent <id>`.
233233
</Warning>
234234

@@ -436,7 +436,7 @@ Index images and audio alongside Markdown using Gemini Embedding 2:
436436
Only applies to files in `extraPaths`. Default memory roots stay Markdown-only. Requires `gemini-embedding-2` (the legacy preview identifier is also accepted). `fallback` must be `"none"`.
437437
</Note>
438438

439-
Supported formats: `.jpg`, `.jpeg`, `.png`, `.webp`, `.gif`, `.heic`, `.heif` (images); `.mp3`, `.wav`, `.ogg`, `.opus`, `.m4a`, `.aac`, `.flac` (audio).
439+
Supported formats: `.jpg`, `.jpeg`, `.png` (images); `.mp3`, `.wav` (audio).
440440

441441
---
442442

‎extensions/google/embedding-provider.test.ts‎

Lines changed: 71 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -241,8 +241,7 @@ describe("Gemini embedding provider", () => {
241241
);
242242
expect(fetchJsonBody(fetchMock, 0)).toEqual({
243243
outputDimensionality: 768,
244-
taskType: "SEMANTIC_SIMILARITY",
245-
content: { parts: [{ text: "test query" }] },
244+
content: { parts: [{ text: "task: sentence similarity | query: test query" }] },
246245
});
247246
expect(fetchJsonBody(fetchMock, 1)).toEqual({
248247
requests: [
@@ -254,7 +253,6 @@ describe("Gemini embedding provider", () => {
254253
{ inlineData: { mimeType: "image/png", data: "img" } },
255254
],
256255
},
257-
taskType: "SEMANTIC_SIMILARITY",
258256
outputDimensionality: 768,
259257
},
260258
{
@@ -265,7 +263,6 @@ describe("Gemini embedding provider", () => {
265263
{ inlineData: { mimeType: "audio/wav", data: "aud" } },
266264
],
267265
},
268-
taskType: "SEMANTIC_SIMILARITY",
269266
outputDimensionality: 768,
270267
},
271268
],
@@ -337,6 +334,76 @@ describe("Gemini embedding provider", () => {
337334
expect(requireFirstFetchInput(fetchMock)).toBe(
338335
"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:embedContent",
339336
);
337+
expect(fetchJsonBody(fetchMock, 0)).toEqual({
338+
content: { parts: [{ text: "test query" }] },
339+
taskType: "RETRIEVAL_QUERY",
340+
outputDimensionality: 768,
341+
});
342+
});
343+
344+
it("formats stable Gemini retrieval requests without unsupported task types", async () => {
345+
const fetchMock = installFetchMock((input) => {
346+
const url = input instanceof URL ? input.href : typeof input === "string" ? input : input.url;
347+
return url.endsWith(":batchEmbedContents")
348+
? { embeddings: [{ values: axisVector(768) }] }
349+
: { embedding: { values: axisVector(768) } };
350+
});
351+
const { provider } = await createGeminiEmbeddingProvider({
352+
config: {} as never,
353+
provider: "gemini",
354+
remote: { apiKey: "test-key" },
355+
model: "gemini-embedding-2",
356+
outputDimensionality: 768,
357+
fallback: "none",
358+
});
359+
360+
await provider.embedQuery("find this");
361+
await provider.embedBatch(["remember this"]);
362+
363+
expect(fetchJsonBody(fetchMock, 0)).toEqual({
364+
content: { parts: [{ text: "task: search result | query: find this" }] },
365+
outputDimensionality: 768,
366+
});
367+
expect(fetchJsonBody(fetchMock, 1)).toEqual({
368+
requests: [
369+
{
370+
content: { parts: [{ text: "title: none | text: remember this" }] },
371+
model: "models/gemini-embedding-2",
372+
outputDimensionality: 768,
373+
},
374+
],
375+
});
376+
});
377+
378+
it.each([
379+
["QUESTION_ANSWERING", "question answering"],
380+
["FACT_VERIFICATION", "fact checking"],
381+
] as const)("keeps %s query and document instructions asymmetric", async (taskType, task) => {
382+
const fetchMock = installFetchMock((input) => {
383+
const url = input instanceof URL ? input.href : typeof input === "string" ? input : input.url;
384+
return url.endsWith(":batchEmbedContents")
385+
? { embeddings: [{ values: axisVector(768) }] }
386+
: { embedding: { values: axisVector(768) } };
387+
});
388+
const { provider } = await createGeminiEmbeddingProvider({
389+
config: {} as never,
390+
provider: "gemini",
391+
remote: { apiKey: "test-key" },
392+
model: "gemini-embedding-2",
393+
outputDimensionality: 768,
394+
taskType,
395+
fallback: "none",
396+
});
397+
398+
await provider.embedQuery("find this");
399+
await provider.embedBatch(["remember this"]);
400+
401+
expect(fetchJsonBody(fetchMock, 0)).toMatchObject({
402+
content: { parts: [{ text: `task: ${task} | query: find this` }] },
403+
});
404+
expect(fetchJsonBody(fetchMock, 1)).toMatchObject({
405+
requests: [{ content: { parts: [{ text: "title: none | text: remember this" }] } }],
406+
});
340407
});
341408

342409
it("rejects Gemini 2 responses that drift from the requested dimensions", async () => {

‎extensions/google/embedding-provider.ts‎

Lines changed: 42 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,15 @@ const GEMINI_EMBEDDING_2_MODELS = new Set(["gemini-embedding-2", "gemini-embeddi
5656

5757
const GEMINI_EMBEDDING_2_DEFAULT_DIMENSIONS = 3072;
5858
const GEMINI_EMBEDDING_2_VALID_DIMENSIONS = [768, 1536, 3072] as const;
59+
const GEMINI_EMBEDDING_2_TASK_PREFIXES: Record<GeminiTaskType, string> = {
60+
RETRIEVAL_QUERY: "task: search result | query:",
61+
RETRIEVAL_DOCUMENT: "title: none | text:",
62+
SEMANTIC_SIMILARITY: "task: sentence similarity | query:",
63+
CLASSIFICATION: "task: classification | query:",
64+
CLUSTERING: "task: clustering | query:",
65+
QUESTION_ANSWERING: "task: question answering | query:",
66+
FACT_VERIFICATION: "task: fact checking | query:",
67+
};
5968

6069
type GeminiTextPart = { text: string };
6170
type GeminiInlinePart = {
@@ -65,7 +74,7 @@ type GeminiPart = GeminiTextPart | GeminiInlinePart;
6574
type GeminiEmbeddingInputPart = NonNullable<EmbeddingInput["parts"]>[number];
6675
type GeminiEmbeddingRequest = {
6776
content: { parts: GeminiPart[] };
68-
taskType: GeminiTaskType;
77+
taskType?: GeminiTaskType;
6978
outputDimensionality?: number;
7079
model?: string;
7180
};
@@ -115,39 +124,38 @@ function readGeminiBatchEmbeddings(
115124
});
116125
}
117126

118-
/** Builds the text-only Gemini embedding request shape used across direct and batch APIs. */
119-
function buildGeminiTextEmbeddingRequest(params: {
120-
text: string;
121-
taskType: GeminiTaskType;
122-
outputDimensionality?: number;
123-
modelPath?: string;
124-
}): GeminiTextEmbeddingRequest {
125-
return buildGeminiEmbeddingRequest({
126-
input: { text: params.text },
127-
taskType: params.taskType,
128-
outputDimensionality: params.outputDimensionality,
129-
modelPath: params.modelPath,
130-
});
131-
}
132-
133127
export function buildGeminiEmbeddingRequest(params: {
134128
input: EmbeddingInput;
129+
model: string;
130+
role: "query" | "document";
135131
taskType: GeminiTaskType;
136132
outputDimensionality?: number;
137133
modelPath?: string;
138134
}): GeminiEmbeddingRequest {
139-
const request: GeminiEmbeddingRequest = {
140-
content: {
141-
parts: params.input.parts?.map((part: GeminiEmbeddingInputPart) =>
142-
part.type === "text"
143-
? ({ text: part.text } satisfies GeminiTextPart)
144-
: ({
145-
inlineData: { mimeType: part.mimeType, data: part.data },
146-
} satisfies GeminiInlinePart),
147-
) ?? [{ text: params.input.text }],
148-
},
149-
taskType: params.taskType,
150-
};
135+
const parts = params.input.parts?.map((part: GeminiEmbeddingInputPart) =>
136+
part.type === "text"
137+
? ({ text: part.text } satisfies GeminiTextPart)
138+
: ({
139+
inlineData: { mimeType: part.mimeType, data: part.data },
140+
} satisfies GeminiInlinePart),
141+
) ?? [{ text: params.input.text }];
142+
const isStableEmbedding2 = normalizeGeminiModel(params.model) === "gemini-embedding-2";
143+
const request: GeminiEmbeddingRequest = { content: { parts } };
144+
if (isStableEmbedding2 && parts.every((part) => "text" in part)) {
145+
const first = parts[0];
146+
if (first && "text" in first) {
147+
const taskType =
148+
params.role === "document" &&
149+
(params.taskType === "RETRIEVAL_QUERY" ||
150+
params.taskType === "QUESTION_ANSWERING" ||
151+
params.taskType === "FACT_VERIFICATION")
152+
? "RETRIEVAL_DOCUMENT"
153+
: params.taskType;
154+
first.text = `${GEMINI_EMBEDDING_2_TASK_PREFIXES[taskType]} ${first.text}`;
155+
}
156+
} else if (!isStableEmbedding2) {
157+
request.taskType = params.taskType;
158+
}
151159
if (params.modelPath) {
152160
request.model = params.modelPath;
153161
}
@@ -307,8 +315,10 @@ export async function createGeminiEmbeddingProvider(
307315
const payload = await fetchGeminiEmbeddingPayload({
308316
client,
309317
endpoint: embedUrl,
310-
body: buildGeminiTextEmbeddingRequest({
311-
text,
318+
body: buildGeminiEmbeddingRequest({
319+
input: { text },
320+
model: client.model,
321+
role: "query",
312322
taskType: options.taskType ?? "RETRIEVAL_QUERY",
313323
outputDimensionality: isV2 ? outputDimensionality : undefined,
314324
}),
@@ -334,6 +344,8 @@ export async function createGeminiEmbeddingProvider(
334344
requests: inputs.map((input) =>
335345
buildGeminiEmbeddingRequest({
336346
input,
347+
model: client.model,
348+
role: "document",
337349
modelPath: client.modelPath,
338350
taskType: options.taskType ?? "RETRIEVAL_DOCUMENT",
339351
outputDimensionality: isV2 ? outputDimensionality : undefined,

‎extensions/google/memory-embedding-adapter.test.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ vi.mock("./embedding-provider.js", async (importOriginal) => {
1515
return {
1616
...actual,
1717
createGeminiEmbeddingProvider: mocks.createGeminiEmbeddingProvider,
18-
buildGeminiEmbeddingRequest: vi.fn(),
1918
};
2019
});
2120

@@ -78,6 +77,35 @@ describe("Gemini memory embedding adapter", () => {
7877
).toBe(false);
7978
});
8079

80+
it("formats stable Gemini asynchronous batch documents without a task type", async () => {
81+
const result = await createAdapterWithHeaders({});
82+
83+
await result.runtime?.batchEmbed?.({
84+
agentId: "main",
85+
chunks: [{ text: "remember this" }],
86+
wait: true,
87+
concurrency: 1,
88+
pollIntervalMs: 1000,
89+
timeoutMs: 60_000,
90+
debug: () => {},
91+
});
92+
93+
expect(mocks.runGeminiEmbeddingBatches).toHaveBeenCalledWith(
94+
expect.objectContaining({
95+
requests: [
96+
{
97+
custom_id: "0",
98+
request: {
99+
content: { parts: [{ text: "title: none | text: remember this" }] },
100+
model: "models/gemini-embedding-2",
101+
outputDimensionality: 768,
102+
},
103+
},
104+
],
105+
}),
106+
);
107+
});
108+
81109
it("keeps durable identity stable across generated client-version changes", async () => {
82110
const sharedHeaders = {
83111
"Content-Type": "application/json",

‎extensions/google/memory-embedding-adapter.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ export const geminiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapte
5858
custom_id: String(index),
5959
request: buildGeminiEmbeddingRequest({
6060
input: chunk.embeddingInput ?? { text: chunk.text },
61+
model: client.model,
62+
role: "document",
6163
taskType: "RETRIEVAL_DOCUMENT",
6264
modelPath: client.modelPath,
6365
outputDimensionality: client.outputDimensionality,

0 commit comments

Comments
 (0)