Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add auto aspect ratio and image search support for Nano Banana 2 (#12537)

sxjeru1c1af1771679
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index b5809daa6c9..b2ad3d0488f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -195,6 +195,7 @@
"messages.tokenDetails.inputCitation": "Input citation",
"messages.tokenDetails.inputText": "Text Input",
"messages.tokenDetails.inputTitle": "Input Details",
+ "messages.tokenDetails.inputTool": "Tool Use Input",
"messages.tokenDetails.inputUncached": "Uncached Input",
"messages.tokenDetails.inputWriteCached": "Input cache write",
"messages.tokenDetails.output": "Output",
@@ -240,6 +241,8 @@
"rag.userQuery.actions.regenerate": "Regenerate Query",
"regenerate": "Regenerate",
"roleAndArchive": "Agent Profile & History",
+ "search.grounding.imageSearchQueries": "Image Search Keywords",
+ "search.grounding.imageTitle": "Found {{count}} images",
"search.grounding.searchQueries": "Search Keywords",
"search.grounding.title": "Found {{count}} results",
"search.mode.auto.desc": "Search the web automatically when needed.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 3325accc6ed..d570287599d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -195,6 +195,7 @@
"messages.tokenDetails.inputCitation": "引用输入",
"messages.tokenDetails.inputText": "文本输入",
"messages.tokenDetails.inputTitle": "输入明细",
+ "messages.tokenDetails.inputTool": "工具调用",
"messages.tokenDetails.inputUncached": "未缓存输入",
"messages.tokenDetails.inputWriteCached": "缓存写入",
"messages.tokenDetails.output": "输出",
@@ -240,6 +241,8 @@
"rag.userQuery.actions.regenerate": "重新生成 Query",
"regenerate": "重新生成",
"roleAndArchive": "助理档案与记录",
+ "search.grounding.imageSearchQueries": "图片搜索关键词",
+ "search.grounding.imageTitle": "找到 {{count}} 张图片",
"search.grounding.searchQueries": "搜索关键词",
"search.grounding.title": "找到 {{count}} 条结果",
"search.mode.auto.desc": "在需要时自动搜索网络。",
diff --git a/packages/agent-runtime/src/core/UsageCounter.ts b/packages/agent-runtime/src/core/UsageCounter.ts
index efaf4bdc10a..117135e3810 100644
--- a/packages/agent-runtime/src/core/UsageCounter.ts
+++ b/packages/agent-runtime/src/core/UsageCounter.ts
@@ -80,6 +80,7 @@ export class UsageCounter {
'inputImageTokens',
'inputAudioTokens',
'inputCitationTokens',
+ 'inputToolTokens',
'outputTextTokens',
'outputImageTokens',
'outputAudioTokens',
diff --git a/packages/conversation-flow/src/parse.ts b/packages/conversation-flow/src/parse.ts
index 7d9f5755645..d669e52655f 100644
--- a/packages/conversation-flow/src/parse.ts
+++ b/packages/conversation-flow/src/parse.ts
@@ -63,6 +63,7 @@ export function parse(messages: Message[], messageGroups?: MessageGroupMetadata[
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputToolTokens',
'inputWriteCacheTokens',
'latency',
'outputAudioTokens',
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 6d8e36460c5..d77b506de54 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -21,7 +21,7 @@ export class FlatListBuilder {
private branchResolver: BranchResolver,
private messageCollector: MessageCollector,
private messageTransformer: MessageTransformer,
- ) {}
+ ) { }
/**
* Generate flatList from messages array
@@ -805,6 +805,7 @@ export class FlatListBuilder {
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputToolTokens',
'inputWriteCacheTokens',
'latency',
'outputAudioTokens',
@@ -947,6 +948,7 @@ export class FlatListBuilder {
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputToolTokens',
'inputWriteCacheTokens',
'latency',
'outputAudioTokens',
diff --git a/packages/conversation-flow/src/transformation/MessageTransformer.ts b/packages/conversation-flow/src/transformation/MessageTransformer.ts
index 89297869614..b6eb6ad1a2e 100644
--- a/packages/conversation-flow/src/transformation/MessageTransformer.ts
+++ b/packages/conversation-flow/src/transformation/MessageTransformer.ts
@@ -51,6 +51,7 @@ export class MessageTransformer {
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputToolTokens',
'inputWriteCacheTokens',
'outputAudioTokens',
'outputImageTokens',
@@ -113,6 +114,7 @@ export class MessageTransformer {
'inputCitationTokens',
'inputImageTokens',
'inputTextTokens',
+ 'inputToolTokens',
'inputWriteCacheTokens',
'outputAudioTokens',
'outputImageTokens',
diff --git a/packages/model-bank/src/aiModels/google.ts b/packages/model-bank/src/aiModels/google.ts
index 7cf228f3165..5e36092a285 100644
--- a/packages/model-bank/src/aiModels/google.ts
+++ b/packages/model-bank/src/aiModels/google.ts
@@ -871,6 +871,7 @@ export const imagenGenParameters: ModelParamsSchema = {
};
const NANO_BANANA_ASPECT_RATIOS = [
+ 'auto',
'1:1', // 1024x1024 / 2048x2048 / 4096x4096
'2:3', // 848x1264 / 1696x2528 / 3392x5056
'3:2', // 1264x848 / 2528x1696 / 5056x3392
@@ -887,7 +888,7 @@ const NANO_BANANA_2_ASPECT_RATIOS = [...NANO_BANANA_ASPECT_RATIOS, '1:4', '4:1',
export const nanoBananaParameters: ModelParamsSchema = {
aspectRatio: {
- default: '1:1',
+ default: 'auto',
enum: NANO_BANANA_ASPECT_RATIOS,
},
imageUrls: {
@@ -898,7 +899,7 @@ export const nanoBananaParameters: ModelParamsSchema = {
export const nanoBananaProParameters: ModelParamsSchema = {
aspectRatio: {
- default: '1:1',
+ default: 'auto',
enum: NANO_BANANA_ASPECT_RATIOS,
},
imageUrls: {
@@ -913,7 +914,7 @@ export const nanoBananaProParameters: ModelParamsSchema = {
export const nanoBanana2Parameters: ModelParamsSchema = {
aspectRatio: {
- default: '1:1',
+ default: 'auto',
enum: NANO_BANANA_2_ASPECT_RATIOS,
},
imageUrls: {
diff --git a/packages/model-bank/src/aiModels/lobehub/utils.ts b/packages/model-bank/src/aiModels/lobehub/utils.ts
index 4f8132d83d7..48610d8732c 100644
--- a/packages/model-bank/src/aiModels/lobehub/utils.ts
+++ b/packages/model-bank/src/aiModels/lobehub/utils.ts
@@ -10,6 +10,7 @@ export const imagenBaseParameters: ModelParamsSchema = {
};
export const NANO_BANANA_ASPECT_RATIOS = [
+ 'auto',
'1:1', // 1024x1024 / 2048x2048 / 4096x4096
'2:3', // 848x1264 / 1696x2528 / 3392x5056
'3:2', // 1264x848 / 2528x1696 / 5056x3392
@@ -24,7 +25,7 @@ export const NANO_BANANA_ASPECT_RATIOS = [
export const nanoBananaParameters: ModelParamsSchema = {
aspectRatio: {
- default: '1:1',
+ default: 'auto',
enum: NANO_BANANA_ASPECT_RATIOS,
},
imageUrls: {
@@ -35,7 +36,7 @@ export const nanoBananaParameters: ModelParamsSchema = {
export const nanoBananaProParameters: ModelParamsSchema = {
aspectRatio: {
- default: '1:1',
+ default: 'auto',
enum: NANO_BANANA_ASPECT_RATIOS,
},
imageUrls: {
@@ -58,7 +59,7 @@ export const NANO_BANANA_2_ASPECT_RATIOS = [
export const nanoBanana2Parameters: ModelParamsSchema = {
aspectRatio: {
- default: '1:1',
+ default: 'auto',
enum: NANO_BANANA_2_ASPECT_RATIOS,
},
imageUrls: {
diff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.json
index 5c908f99270..aa44ef83bb8 100644
--- a/packages/model-runtime/package.json
+++ b/packages/model-runtime/package.json
@@ -17,7 +17,7 @@
"@azure-rest/ai-inference": "1.0.0-beta.5",
"@azure/core-auth": "^1.10.1",
"@fal-ai/client": "^1.7.2",
- "@google/genai": "^1.29.0",
+ "@google/genai": "^1.43.0",
"@huggingface/inference": "^4.13.4",
"@lobechat/business-model-runtime": "workspace:*",
"@lobechat/const": "workspace:*",
diff --git a/packages/model-runtime/src/core/streams/google/google-ai.test.ts b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
index 964aa214f99..90a4e9978de 100644
--- a/packages/model-runtime/src/core/streams/google/google-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
@@ -852,6 +852,269 @@ describe('GoogleGenerativeAIStream', () => {
].map((i) => i + '\n'),
);
});
+
+ it('should handle groundingMetadata with image search results', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const data = [
+ {
+ text: 'Here are some images',
+ candidates: [
+ {
+ content: {
+ parts: [{ text: 'Here are some images' }],
+ role: 'model',
+ },
+ finishReason: 'STOP',
+ index: 0,
+ groundingMetadata: {
+ groundingChunks: [
+ {
+ web: {
+ uri: 'https://example.com/article',
+ title: 'example.com',
+ },
+ },
+ {
+ image: {
+ imageUri: 'https://example.com/photo.jpg',
+ sourceUri: 'https://example.com/page',
+ title: 'Example Photo',
+ domain: 'example.com',
+ },
+ },
+ {
+ image: {
+ imageUri: 'https://another.com/img.png',
+ sourceUri: 'https://another.com/gallery',
+ title: 'Another Image',
+ domain: 'another.com',
+ },
+ },
+ ],
+ webSearchQueries: ['example images'],
+ imageSearchQueries: ['example photo search'],
+ },
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 5,
+ candidatesTokenCount: 10,
+ totalTokenCount: 15,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 5 }],
+ },
+ modelVersion: 'gemini-3.1-flash-image-preview',
+ },
+ ];
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ data.forEach((item) => controller.enqueue(item));
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+ const chunks = await decodeStreamChunks(protocolStream);
+
+ expect(chunks).toEqual(
+ [
+ 'id: chat_1',
+ 'event: text',
+ 'data: "Here are some images"\n',
+
+ 'id: chat_1',
+ 'event: grounding',
+ `data: ${JSON.stringify({
+ citations: [
+ {
+ favicon: 'example.com',
+ title: 'example.com',
+ url: 'https://example.com/article',
+ },
+ ],
+ imageResults: [
+ {
+ domain: 'example.com',
+ imageUri: 'https://example.com/photo.jpg',
+ sourceUri: 'https://example.com/page',
+ title: 'Example Photo',
+ },
+ {
+ domain: 'another.com',
+ imageUri: 'https://another.com/img.png',
+ sourceUri: 'https://another.com/gallery',
+ title: 'Another Image',
+ },
+ ],
+ imageSearchQueries: ['example photo search'],
+ searchQueries: ['example images'],
+ })}\n`,
+
+ 'id: chat_1',
+ 'event: stop',
+ `data: "STOP"\n`,
+
+ 'id: chat_1',
+ 'event: usage',
+ `data: {"inputTextTokens":5,"outputImageTokens":0,"outputTextTokens":10,"totalInputTokens":5,"totalOutputTokens":10,"totalTokens":15}\n`,
+ ].map((i) => i + '\n'),
+ );
+ });
+
+ it('should handle groundingMetadata with only image search results (no web)', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const data = [
+ {
+ text: 'Image only results',
+ candidates: [
+ {
+ content: {
+ parts: [{ text: 'Image only results' }],
+ role: 'model',
+ },
+ finishReason: 'STOP',
+ index: 0,
+ groundingMetadata: {
+ groundingChunks: [
+ {
+ image: {
+ imageUri: 'https://img.example.com/cat.jpg',
+ sourceUri: 'https://example.com/cats',
+ title: 'Cat Photo',
+ domain: 'example.com',
+ },
+ },
+ ],
+ imageSearchQueries: ['cute cats'],
+ },
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 3,
+ candidatesTokenCount: 5,
+ totalTokenCount: 8,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 3 }],
+ },
+ modelVersion: 'gemini-3.1-flash-image-preview',
+ },
+ ];
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ data.forEach((item) => controller.enqueue(item));
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+ const chunks = await decodeStreamChunks(protocolStream);
+
+ expect(chunks).toEqual(
+ [
+ 'id: chat_1',
+ 'event: text',
+ 'data: "Image only results"\n',
+
+ 'id: chat_1',
+ 'event: grounding',
+ `data: ${JSON.stringify({
+ imageResults: [
+ {
+ domain: 'example.com',
+ imageUri: 'https://img.example.com/cat.jpg',
+ sourceUri: 'https://example.com/cats',
+ title: 'Cat Photo',
+ },
+ ],
+ imageSearchQueries: ['cute cats'],
+ })}\n`,
+
+ 'id: chat_1',
+ 'event: stop',
+ `data: "STOP"\n`,
+
+ 'id: chat_1',
+ 'event: usage',
+ `data: {"inputTextTokens":3,"outputImageTokens":0,"outputTextTokens":5,"totalInputTokens":3,"totalOutputTokens":5,"totalTokens":8}\n`,
+ ].map((i) => i + '\n'),
+ );
+ });
+
+ it('should filter empty strings from searchQueries in groundingMetadata', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const data = [
+ {
+ text: 'result',
+ candidates: [
+ {
+ content: { parts: [{ text: 'result' }], role: 'model' },
+ finishReason: 'STOP',
+ index: 0,
+ groundingMetadata: {
+ groundingChunks: [
+ {
+ web: {
+ uri: 'https://vertexaisearch.cloud.google.com/grounding-api-redirect/abc',
+ title: 'example.com',
+ },
+ },
+ ],
+ webSearchQueries: ['', '杭州天气', 'Hangzhou weather'],
+ },
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 5,
+ candidatesTokenCount: 3,
+ totalTokenCount: 8,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 5 }],
+ },
+ modelVersion: 'gemini-3.1-flash-image-preview',
+ },
+ ];
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ data.forEach((item) => controller.enqueue(item));
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+ const chunks = await decodeStreamChunks(protocolStream);
+
+ expect(chunks).toEqual(
+ [
+ 'id: chat_1',
+ 'event: text',
+ 'data: "result"\n',
+
+ 'id: chat_1',
+ 'event: grounding',
+ `data: ${JSON.stringify({
+ citations: [
+ {
+ favicon: 'example.com',
+ title: 'example.com',
+ url: 'https://vertexaisearch.cloud.google.com/grounding-api-redirect/abc',
+ },
+ ],
+ searchQueries: ['杭州天气', 'Hangzhou weather'],
+ })}\n`,
+
+ 'id: chat_1',
+ 'event: stop',
+ `data: "STOP"\n`,
+
+ 'id: chat_1',
+ 'event: usage',
+ `data: {"inputTextTokens":5,"outputImageTokens":0,"outputTextTokens":3,"totalInputTokens":5,"totalOutputTokens":3,"totalTokens":8}\n`,
+ ].map((i) => i + '\n'),
+ );
+ });
});
describe('Tool calls', () => {
diff --git a/packages/model-runtime/src/core/streams/google/index.ts b/packages/model-runtime/src/core/streams/google/index.ts
index 9741ccdb5da..67697be3c1a 100644
--- a/packages/model-runtime/src/core/streams/google/index.ts
+++ b/packages/model-runtime/src/core/streams/google/index.ts
@@ -233,26 +233,55 @@ const transformGoogleGenerativeAIStream = (
}
// return the grounding
- const { groundingChunks, webSearchQueries } = candidate.groundingMetadata ?? {};
+ const { groundingChunks, imageSearchQueries, webSearchQueries } =
+ candidate.groundingMetadata ?? {};
if (groundingChunks) {
+ const webChunks = groundingChunks.filter((chunk) => chunk.web);
+ const imageChunks = groundingChunks.filter((chunk) => chunk.image);
+
return [
- { data: text, id: context.id, type: 'text' },
+ ...(text ? [{ data: text, id: context.id, type: 'text' as const }] : []),
{
data: {
- citations: groundingChunks?.map((chunk) => ({
- // Google returns a uri processed by Google itself, so it cannot display the real favicon
- // Need to use title as a replacement
- favicon: chunk.web?.title,
- title: chunk.web?.title,
- url: chunk.web?.uri,
- })),
- searchQueries: webSearchQueries,
+ citations:
+ webChunks.length > 0
+ ? webChunks.map((chunk) => {
+ // Fall back to hostname when title is empty
+ let displayTitle = chunk.web?.title?.replaceAll(/<[^>]*>/g, '');
+ if (!displayTitle) {
+ try {
+ displayTitle = new URL(chunk.web?.uri || '').hostname.replace('www.', '');
+ } catch {
+ displayTitle = chunk.web?.uri;
+ }
+ }
+ return {
+ // Google returns a uri processed by Google itself, so it cannot display the real favicon
+ // Need to use title (or derived hostname) as a replacement
+ favicon: displayTitle,
+ title: displayTitle,
+ url: chunk.web?.uri,
+ };
+ })
+ : undefined,
+ imageResults:
+ imageChunks.length > 0
+ ? imageChunks.map((chunk) => ({
+ domain: chunk.image?.domain,
+ imageUri: chunk.image?.imageUri,
+ sourceUri: chunk.image?.sourceUri,
+ title: chunk.image?.title,
+ }))
+ : undefined,
+ imageSearchQueries:
+ imageSearchQueries && imageSearchQueries.length > 0 ? imageSearchQueries : undefined,
+ searchQueries: webSearchQueries?.filter(Boolean),
} as GroundingSearch,
id: context.id,
type: 'grounding',
},
...usageChunks,
- ];
+ ].filter(Boolean) as StreamProtocolChunk[];
}
// Check for image data before handling finishReason
diff --git a/packages/model-runtime/src/core/streams/vertex-ai.test.ts b/packages/model-runtime/src/core/streams/vertex-ai.test.ts
index 5f8195e5323..28905f870b9 100644
--- a/packages/model-runtime/src/core/streams/vertex-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/vertex-ai.test.ts
@@ -747,4 +747,277 @@ describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
].map((i) => i + '\n'),
);
});
+
+ it('should handle groundingMetadata with image search results', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const rawChunks = [
+ {
+ candidates: [
+ {
+ content: {
+ role: 'model',
+ parts: [{ text: 'Here are images and web results' }],
+ },
+ finishReason: 'STOP',
+ index: 0,
+ groundingMetadata: {
+ groundingChunks: [
+ {
+ web: {
+ uri: 'https://example.com/article',
+ title: 'example.com',
+ },
+ },
+ {
+ image: {
+ imageUri: 'https://example.com/photo.jpg',
+ sourceUri: 'https://example.com/page',
+ title: 'Example Photo',
+ domain: 'example.com',
+ },
+ },
+ ],
+ webSearchQueries: ['example query'],
+ imageSearchQueries: ['example image query'],
+ },
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 5,
+ candidatesTokenCount: 10,
+ totalTokenCount: 15,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 5 }],
+ candidatesTokensDetails: [{ modality: 'TEXT', tokenCount: 10 }],
+ },
+ modelVersion: 'gemini-3.1-flash-image-preview',
+ },
+ ];
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ rawChunks.forEach((chunk) => controller.enqueue(chunk));
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+
+ const decoder = new TextDecoder();
+ const chunks: string[] = [];
+
+ // @ts-ignore
+ for await (const chunk of protocolStream) {
+ chunks.push(decoder.decode(chunk, { stream: true }));
+ }
+
+ expect(chunks).toEqual(
+ [
+ 'id: chat_1',
+ 'event: text',
+ 'data: "Here are images and web results"\n',
+
+ 'id: chat_1',
+ 'event: grounding',
+ `data: ${JSON.stringify({
+ citations: [
+ {
+ favicon: 'example.com',
+ title: 'example.com',
+ url: 'https://example.com/article',
+ },
+ ],
+ imageResults: [
+ {
+ domain: 'example.com',
+ imageUri: 'https://example.com/photo.jpg',
+ sourceUri: 'https://example.com/page',
+ title: 'Example Photo',
+ },
+ ],
+ imageSearchQueries: ['example image query'],
+ searchQueries: ['example query'],
+ })}\n`,
+
+ 'id: chat_1',
+ 'event: stop',
+ `data: "STOP"\n`,
+
+ 'id: chat_1',
+ 'event: usage',
+ `data: {"inputTextTokens":5,"outputImageTokens":0,"outputTextTokens":10,"totalInputTokens":5,"totalOutputTokens":10,"totalTokens":15}\n`,
+ ].map((i) => i + '\n'),
+ );
+ });
+
+ it('should handle groundingMetadata with only image chunks (no web chunks)', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const rawChunks = [
+ {
+ candidates: [
+ {
+ content: {
+ role: 'model',
+ parts: [{ text: 'Image results only' }],
+ },
+ finishReason: 'STOP',
+ index: 0,
+ groundingMetadata: {
+ groundingChunks: [
+ {
+ image: {
+ imageUri: 'https://img.example.com/cat.jpg',
+ sourceUri: 'https://example.com/cats',
+ title: 'Cat Photo',
+ domain: 'example.com',
+ },
+ },
+ ],
+ imageSearchQueries: ['cute cats'],
+ },
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 3,
+ candidatesTokenCount: 5,
+ totalTokenCount: 8,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 3 }],
+ candidatesTokensDetails: [{ modality: 'TEXT', tokenCount: 5 }],
+ },
+ modelVersion: 'gemini-3.1-flash-image-preview',
+ },
+ ];
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ rawChunks.forEach((chunk) => controller.enqueue(chunk));
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+
+ const decoder = new TextDecoder();
+ const chunks: string[] = [];
+
+ // @ts-ignore
+ for await (const chunk of protocolStream) {
+ chunks.push(decoder.decode(chunk, { stream: true }));
+ }
+
+ expect(chunks).toEqual(
+ [
+ 'id: chat_1',
+ 'event: text',
+ 'data: "Image results only"\n',
+
+ 'id: chat_1',
+ 'event: grounding',
+ `data: ${JSON.stringify({
+ imageResults: [
+ {
+ domain: 'example.com',
+ imageUri: 'https://img.example.com/cat.jpg',
+ sourceUri: 'https://example.com/cats',
+ title: 'Cat Photo',
+ },
+ ],
+ imageSearchQueries: ['cute cats'],
+ })}\n`,
+
+ 'id: chat_1',
+ 'event: stop',
+ `data: "STOP"\n`,
+
+ 'id: chat_1',
+ 'event: usage',
+ `data: {"inputTextTokens":3,"outputImageTokens":0,"outputTextTokens":5,"totalInputTokens":3,"totalOutputTokens":5,"totalTokens":8}\n`,
+ ].map((i) => i + '\n'),
+ );
+ });
+
+ it('should filter empty strings from searchQueries in groundingMetadata', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const rawChunks = [
+ {
+ candidates: [
+ {
+ content: {
+ role: 'model',
+ parts: [{ text: 'result' }],
+ },
+ finishReason: 'STOP',
+ index: 0,
+ groundingMetadata: {
+ groundingChunks: [
+ {
+ web: {
+ uri: 'https://vertexaisearch.cloud.google.com/grounding-api-redirect/abc',
+ title: 'example.com',
+ },
+ },
+ ],
+ webSearchQueries: ['', '杭州天气', 'Hangzhou weather'],
+ },
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 5,
+ candidatesTokenCount: 3,
+ totalTokenCount: 8,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 5 }],
+ candidatesTokensDetails: [{ modality: 'TEXT', tokenCount: 3 }],
+ },
+ modelVersion: 'gemini-3.1-flash-image-preview',
+ },
+ ];
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ rawChunks.forEach((chunk) => controller.enqueue(chunk));
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+
+ const decoder = new TextDecoder();
+ const chunks: string[] = [];
+
+ // @ts-ignore
+ for await (const chunk of protocolStream) {
+ chunks.push(decoder.decode(chunk, { stream: true }));
+ }
+
+ expect(chunks).toEqual(
+ [
+ 'id: chat_1',
+ 'event: text',
+ 'data: "result"\n',
+
+ 'id: chat_1',
+ 'event: grounding',
+ `data: ${JSON.stringify({
+ citations: [
+ {
+ favicon: 'example.com',
+ title: 'example.com',
+ url: 'https://vertexaisearch.cloud.google.com/grounding-api-redirect/abc',
+ },
+ ],
+ searchQueries: ['杭州天气', 'Hangzhou weather'],
+ })}\n`,
+
+ 'id: chat_1',
+ 'event: stop',
+ `data: "STOP"\n`,
+
+ 'id: chat_1',
+ 'event: usage',
+ `data: {"inputTextTokens":5,"outputImageTokens":0,"outputTextTokens":3,"totalInputTokens":5,"totalOutputTokens":3,"totalTokens":8}\n`,
+ ].map((i) => i + '\n'),
+ );
+ });
});
diff --git a/packages/model-runtime/src/core/usageConverters/google-ai.test.ts b/packages/model-runtime/src/core/usageConverters/google-ai.test.ts
index 2625fc0466f..446a88075de 100644
--- a/packages/model-runtime/src/core/usageConverters/google-ai.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/google-ai.test.ts
@@ -86,4 +86,43 @@ describe('convertGoogleAIUsage', () => {
expect(result.cost).toBeCloseTo(0.4, 10);
});
+
+ it('should handle toolUsePromptTokenCount (e.g. grounding/search tool return tokens)', () => {
+ const usage: GenerateContentResponseUsageMetadata = {
+ candidatesTokenCount: 367,
+ promptTokenCount: 50,
+ toolUsePromptTokenCount: 7596,
+ totalTokenCount: 8013,
+ };
+
+ const result = convertGoogleAIUsage(usage);
+
+ expect(result).toEqual({
+ inputAudioTokens: undefined,
+ inputCacheMissTokens: undefined,
+ inputCachedTokens: undefined,
+ inputImageTokens: undefined,
+ inputTextTokens: undefined,
+ inputToolTokens: 7596,
+ outputImageTokens: 0,
+ outputReasoningTokens: undefined,
+ outputTextTokens: 367,
+ totalInputTokens: 7646, // promptTokenCount (50) + toolUsePromptTokenCount (7596)
+ totalOutputTokens: 367,
+ totalTokens: 8013,
+ });
+ });
+
+ it('should not set inputToolTokens when toolUsePromptTokenCount is absent', () => {
+ const usage: GenerateContentResponseUsageMetadata = {
+ candidatesTokenCount: 367,
+ promptTokenCount: 7646,
+ totalTokenCount: 8013,
+ };
+
+ const result = convertGoogleAIUsage(usage);
+
+ expect(result.inputToolTokens).toBeUndefined();
+ expect(result.totalInputTokens).toBe(7646);
+ });
});
diff --git a/packages/model-runtime/src/core/usageConverters/google-ai.ts b/packages/model-runtime/src/core/usageConverters/google-ai.ts
index 1791f263076..9f3f088263d 100644
--- a/packages/model-runtime/src/core/usageConverters/google-ai.ts
+++ b/packages/model-runtime/src/core/usageConverters/google-ai.ts
@@ -25,6 +25,9 @@ export const convertGoogleAIUsage = (
candidatesDetails?.reduce((sum, detail) => sum + (detail?.tokenCount ?? 0), 0) ??
0;
+ // toolUsePromptTokenCount represents tokens consumed for tool call prompts (input side)
+ const toolUseTokens = usage.toolUsePromptTokenCount;
+
const outputImageTokens = getTokenCount(candidatesDetails, MediaModality.IMAGE) ?? 0;
const textTokensFromDetails = getTokenCount(candidatesDetails, MediaModality.TEXT);
const outputTextTokens =
@@ -39,10 +42,13 @@ export const convertGoogleAIUsage = (
inputCachedTokens: usage.cachedContentTokenCount,
inputImageTokens: getTokenCount(usage.promptTokensDetails, MediaModality.IMAGE),
inputTextTokens: getTokenCount(usage.promptTokensDetails, MediaModality.TEXT),
+ inputToolTokens: toolUseTokens,
outputImageTokens,
outputReasoningTokens: reasoningTokens,
outputTextTokens,
- totalInputTokens: usage.promptTokenCount,
+ totalInputTokens: toolUseTokens
+ ? (usage.promptTokenCount ?? 0) + toolUseTokens
+ : usage.promptTokenCount,
totalOutputTokens,
totalTokens: usage.totalTokenCount,
} satisfies ModelUsage;
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
index e200bf69b6c..2c6bc6e252a 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
@@ -292,6 +292,75 @@ describe('computeChatPricing', () => {
expect(totalCredits).toBe(184_919); // 161222 + 6257 + 17440 = 184919
expect(totalCost).toBeCloseTo(0.184919, 6); // 184919 credits = $0.184919
});
+
+ it('bills tool-use (grounding) tokens at textInput rate when no explicit cache', () => {
+ // Simulates Google Search grounding: promptTokenCount=50 (user text),
+ // toolUsePromptTokenCount=7596 (search results fed back to model).
+ // The converter sets inputToolTokens=7596 and totalInputTokens=7646.
+ // inputTextTokens=50 represents ONLY the text modality from promptTokensDetails.
+ // textInput billing must use totalInputTokens (7646), not inputTextTokens (50).
+ const pricing: Pricing = {
+ units: [
+ { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 4, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ };
+
+ const usage: ModelTokensUsage = {
+ inputTextTokens: 50, // Text modality from promptTokensDetails (user text only)
+ inputToolTokens: 7596, // toolUsePromptTokenCount from Google API (grounding results)
+ totalInputTokens: 7646, // promptTokenCount(50) + toolUsePromptTokenCount(7596)
+ outputTextTokens: 367,
+ totalOutputTokens: 367,
+ totalTokens: 8013,
+ };
+
+ const result = computeChatCost(pricing, usage);
+ expect(result).toBeDefined();
+ expect(result?.issues).toHaveLength(0);
+
+ const textInput = result?.breakdown.find((item) => item.unit.name === 'textInput');
+ // Must bill on totalInputTokens (7646) NOT inputTextTokens (50)
+ expect(textInput?.quantity).toBe(7646);
+ // rate=1 credit/token (representing $1/million tokens * millionTokens unit),
+ // ceil(7646 * 1) = 7646 credits
+ expect(textInput?.credits).toBe(7646);
+ });
+
+ it('bills tool-use tokens correctly when also using cache', () => {
+ // Simulates a scenario where both caching AND grounding are active.
+ // inputCacheMissTokens=50 (uncached user text),
+ // inputCachedTokens=7596 (cached grounding context),
+ // inputToolTokens=200 (explicit function call results)
+ const pricing: Pricing = {
+ units: [
+ { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput_cacheRead', rate: 0.1, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 4, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ };
+
+ const usage: ModelTokensUsage = {
+ inputCacheMissTokens: 50,
+ inputCachedTokens: 7596,
+ inputToolTokens: 200,
+ totalInputTokens: 7846,
+ outputTextTokens: 100,
+ totalOutputTokens: 100,
+ totalTokens: 7946,
+ };
+
+ const result = computeChatCost(pricing, usage);
+ expect(result).toBeDefined();
+ expect(result?.issues).toHaveLength(0);
+
+ const textInput = result?.breakdown.find((item) => item.unit.name === 'textInput');
+ // inputCacheMissTokens(50) + inputToolTokens(200) = 250
+ expect(textInput?.quantity).toBe(250);
+
+ const cached = result?.breakdown.find((item) => item.unit.name === 'textInput_cacheRead');
+ expect(cached?.quantity).toBe(7596);
+ });
});
describe('Anthropic', () => {
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
index 0daf9d01e1b..8dfe4bbbbc0 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts
@@ -56,8 +56,13 @@ type UnitQuantityResolver = (usage: ModelTokensUsage) => number | undefined;
const UNIT_QUANTITY_RESOLVERS: Partial<Record<PricingUnitName, UnitQuantityResolver>> = {
textInput: (usage) => {
+ const toolTokens = usage.inputToolTokens ?? 0;
+
if (usage.inputCacheMissTokens !== undefined) {
- return usage.inputCacheMissTokens;
+ // inputCacheMissTokens only covers non-cached prompt tokens;
+ // tool-use tokens (e.g. grounding results) are billed at the same input rate
+ // and must be added here because there is no separate toolInput pricing unit.
+ return usage.inputCacheMissTokens + toolTokens;
}
if (typeof usage.inputCachedTokens === 'number' && typeof usage.totalInputTokens === 'number') {
@@ -66,6 +71,13 @@ const UNIT_QUANTITY_RESOLVERS: Partial<Record<PricingUnitName, UnitQuantityResol
);
}
+ // When tool tokens are present, totalInputTokens already includes them
+ // (set by the converter as promptTokenCount + toolUsePromptTokenCount).
+ // Prefer totalInputTokens over inputTextTokens to avoid underbilling.
+ if (toolTokens > 0) {
+ return usage.totalInputTokens;
+ }
+
return usage.inputTextTokens ?? usage.totalInputTokens;
},
textInput_cacheRead: (usage) => usage.inputCachedTokens,
diff --git a/packages/model-runtime/src/providers/google/createImage.test.ts b/packages/model-runtime/src/providers/google/createImage.test.ts
index d89119a37b4..b1d8c655fe9 100644
--- a/packages/model-runtime/src/providers/google/createImage.test.ts
+++ b/packages/model-runtime/src/providers/google/createImage.test.ts
@@ -388,6 +388,54 @@ describe('createGoogleImage', () => {
});
});
+ it('should not include imageConfig when aspectRatio is auto', async () => {
+ // Arrange
+ const realBase64ImageData =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
+ const mockContentResponse = {
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ inlineData: {
+ data: realBase64ImageData,
+ mimeType: 'image/png',
+ },
+ },
+ ],
+ },
+ },
+ ],
+ };
+ vi.spyOn(mockClient.models, 'generateContent').mockResolvedValue(mockContentResponse as any);
+
+ const payload: CreateImagePayload = {
+ model: 'gemini-2.5-flash-image:image',
+ params: {
+ prompt: 'Create a beautiful sunset landscape',
+ aspectRatio: 'auto',
+ },
+ };
+
+ // Act
+ await createGoogleImage(mockClient, provider, payload);
+
+ // Assert - imageConfig should NOT be included when aspectRatio is 'auto'
+ expect(mockClient.models.generateContent).toHaveBeenCalledWith({
+ contents: [
+ {
+ role: 'user',
+ parts: [{ text: 'Create a beautiful sunset landscape' }],
+ },
+ ],
+ model: 'gemini-2.5-flash-image',
+ config: {
+ responseModalities: ['Image'],
+ },
+ });
+ });
+
it('should support image editing with base64 imageUrl', async () => {
// Arrange
const inputImageBase64 =
diff --git a/packages/model-runtime/src/providers/google/createImage.ts b/packages/model-runtime/src/providers/google/createImage.ts
index b7dac5f1d64..e732441781d 100644
--- a/packages/model-runtime/src/providers/google/createImage.ts
+++ b/packages/model-runtime/src/providers/google/createImage.ts
@@ -143,7 +143,7 @@ async function generateImageByChatModel(
const config: GenerateContentConfig = {
responseModalities: ['Image'],
- ...(params.aspectRatio
+ ...(params.aspectRatio && params.aspectRatio !== 'auto'
? {
imageConfig: {
aspectRatio: params.aspectRatio,
diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.ts
index 5f08799f841..44155223365 100644
--- a/packages/model-runtime/src/providers/google/index.test.ts
+++ b/packages/model-runtime/src/providers/google/index.test.ts
@@ -681,6 +681,78 @@ describe('thinkingConfig includeThoughts logic', () => {
});
});
+describe('buildGoogleToolsWithSearch', () => {
+ it('should include imageSearch searchTypes for models in modelsWithImageSearch when search is enabled', async () => {
+ const mockStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue({
+ text: 'test',
+ candidates: [
+ {
+ content: { parts: [{ text: 'test' }], role: 'model' },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
+ modelVersion: 'gemini-3.1-flash-image-preview',
+ });
+ controller.close();
+ },
+ });
+ vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
+ mockStream as any,
+ );
+
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gemini-3.1-flash-image-preview',
+ temperature: 0,
+ enabledSearch: true,
+ });
+
+ const callArgs = (instance['client'].models.generateContentStream as any).mock.calls[0];
+ const config = callArgs[0].config as any;
+ expect(config.tools).toEqual([
+ { googleSearch: { searchTypes: { imageSearch: {}, webSearch: {} } } },
+ ]);
+ });
+
+ it('should use plain googleSearch for non-imageSearch models when search is enabled', async () => {
+ const mockStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue({
+ text: 'test',
+ candidates: [
+ {
+ content: { parts: [{ text: 'test' }], role: 'model' },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
+ modelVersion: 'gemini-2.0-flash',
+ });
+ controller.close();
+ },
+ });
+ vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
+ mockStream as any,
+ );
+
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gemini-2.0-flash',
+ temperature: 0,
+ enabledSearch: true,
+ });
+
+ const callArgs = (instance['client'].models.generateContentStream as any).mock.calls[0];
+ const config = callArgs[0].config as any;
+ expect(config.tools).toEqual([{ googleSearch: {} }]);
+ });
+});
+
describe('models', () => {
it('should pass API Key via x-goog-api-key header instead of URL parameter', async () => {
const mockFetch = vi.fn().mockResolvedValue({
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index 48e00daabb9..fe1b855e17b 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -44,6 +44,10 @@ const modelsWithModalities = new Set([
'nano-banana-pro-preview',
]);
+const modelsWithImageSearch = new Set([
+ 'gemini-3.1-flash-image-preview',
+]);
+
const modelsDisableInstuction = new Set([
'gemini-2.0-flash-exp',
'gemini-2.0-flash-exp-image-generation',
@@ -167,7 +171,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {
const config: GenerateContentConfig = {
abortSignal: originalSignal,
imageConfig:
- modelsWithModalities.has(model) && imageAspectRatio
+ modelsWithModalities.has(model) && imageAspectRatio && imageAspectRatio !== 'auto'
? {
aspectRatio: imageAspectRatio,
imageSize: imageResolution,
@@ -463,15 +467,24 @@ export class LobeGoogleAI implements LobeRuntimeAI {
return buildGoogleTools(tools);
}
+ // Build GoogleSearch tool config with optional image search support
+ const googleSearchTool = hasSearch
+ ? {
+ googleSearch: modelsWithImageSearch.has(payload?.model ?? '')
+ ? { searchTypes: { imageSearch: {}, webSearch: {} } }
+ : {},
+ }
+ : undefined;
+
// Build and return search-related tools (search tools cannot be used with FunctionCall simultaneously)
if (hasUrlContext && hasSearch) {
- return [{ urlContext: {} }, { googleSearch: {} }];
+ return [{ urlContext: {} }, googleSearchTool!];
}
if (hasUrlContext) {
return [{ urlContext: {} }];
}
if (hasSearch) {
- return [{ googleSearch: {} }];
+ return [googleSearchTool!];
}
// Finally consider function declarations
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index 55080387bfb..a5a1f9aa776 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -1,6 +1,6 @@
import { z } from 'zod';
-import type { PageSelection} from './pageSelection';
+import type { PageSelection } from './pageSelection';
import { PageSelectionSchema } from './pageSelection';
export interface ModelTokensUsage {
@@ -25,6 +25,10 @@ export interface ModelTokensUsage {
inputImageTokens?: number;
inputTextTokens?: number;
+ /**
+ * tool use prompt tokens (Google AI / Vertex AI)
+ */
+ inputToolTokens?: number;
inputWriteCacheTokens?: number;
outputAudioTokens?: number;
outputImageTokens?: number;
@@ -50,6 +54,7 @@ export const ModelUsageSchema = z.object({
inputImageTokens: z.number().optional(),
inputAudioTokens: z.number().optional(),
inputCitationTokens: z.number().optional(),
+ inputToolTokens: z.number().optional(),
// Output tokens breakdown
outputTextTokens: z.number().optional(),
diff --git a/packages/types/src/search.ts b/packages/types/src/search.ts
index 5cfd945087a..a4bcffef0f1 100644
--- a/packages/types/src/search.ts
+++ b/packages/types/src/search.ts
@@ -25,11 +25,27 @@ export interface CitationItem {
url: string;
}
+export interface ImageCitationItem {
+ domain?: string;
+ imageUri?: string;
+ sourceUri?: string;
+ title?: string;
+}
+
export interface GroundingSearch {
citations?: CitationItem[];
+ imageResults?: ImageCitationItem[];
+ imageSearchQueries?: string[];
searchQueries?: string[];
}
+export const ImageCitationItemSchema = z.object({
+ domain: z.string().optional(),
+ imageUri: z.string().optional(),
+ sourceUri: z.string().optional(),
+ title: z.string().optional(),
+});
+
export const GroundingSearchSchema = z.object({
citations: z
.array(
@@ -41,5 +57,7 @@ export const GroundingSearchSchema = z.object({
}),
)
.optional(),
+ imageResults: z.array(ImageCitationItemSchema).optional(),
+ imageSearchQueries: z.array(z.string()).optional(),
searchQueries: z.array(z.string()).optional(),
});
diff --git a/src/features/Conversation/Markdown/plugins/ImageSearchRef/Render.test.tsx b/src/features/Conversation/Markdown/plugins/ImageSearchRef/Render.test.tsx
new file mode 100644
index 00000000000..6a2a3bef6db
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ImageSearchRef/Render.test.tsx
@@ -0,0 +1,85 @@
+import { render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import * as storeModule from '../../../store';
+import Render from './Render';
+
+vi.mock('../../../store', async (importOriginal) => {
+ const original = await importOriginal<typeof storeModule>();
+ return { ...original, useConversationStore: vi.fn() };
+});
+
+const mockUseConversationStore = vi.mocked(storeModule.useConversationStore);
+
+const MESSAGE_ID = 'msg-test-1';
+
+const makeProps = (imageIndex: number, originalText: string) => ({
+ children: null,
+ id: MESSAGE_ID,
+ node: { properties: { imageIndex, originalText } },
+ tagName: 'image-search-ref',
+ type: 'element',
+});
+
+describe('ImageSearchRef Render', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('fallback: no image results', () => {
+ it('should render plain text when imageResults is undefined', () => {
+ mockUseConversationStore.mockReturnValue(undefined);
+ render(<Render {...(makeProps(0, 'image_0.png') as any)} />);
+ expect(screen.getByText('image_0.png')).toBeInTheDocument();
+ expect(screen.queryByRole('link')).toBeNull();
+ });
+
+ it('should render plain text when imageResults is an empty array', () => {
+ mockUseConversationStore.mockReturnValue([]);
+ render(<Render {...(makeProps(0, 'image_0.png') as any)} />);
+ expect(screen.getByText('image_0.png')).toBeInTheDocument();
+ expect(screen.queryByRole('link')).toBeNull();
+ });
+
+ it('should render plain text when imageIndex is out of bounds', () => {
+ mockUseConversationStore.mockReturnValue([
+ {
+ domain: 'example.com',
+ imageUri: 'https://img.example.com/0.jpg',
+ sourceUri: 'https://example.com',
+ title: 'Photo',
+ },
+ ]);
+ render(<Render {...(makeProps(5, 'image_5.png') as any)} />);
+ expect(screen.getByText('image_5.png')).toBeInTheDocument();
+ expect(screen.queryByRole('link')).toBeNull();
+ });
+ });
+
+ describe('chip: with image results', () => {
+ const imageResult = {
+ domain: 'example.com',
+ imageUri: 'https://img.example.com/0.jpg',
+ sourceUri: 'https://example.com/photo',
+ title: 'A Sample Photo',
+ };
+
+ beforeEach(() => {
+ mockUseConversationStore.mockReturnValue([imageResult]);
+ });
+
+ it('should render an anchor chip linking to imageUri', () => {
+ render(<Render {...(makeProps(0, 'image_0.png') as any)} />);
+ // Popover wraps the trigger <a> and adds role="button" via base-ui,
+ // so query by role "button" (the chip) and verify href/target attributes.
+ const chip = screen.getByRole('button', { name: 'image_0.png' });
+ expect(chip).toHaveAttribute('href', imageResult.imageUri);
+ expect(chip).toHaveAttribute('target', '_blank');
+ });
+
+ it('should show originalText inside the chip', () => {
+ render(<Render {...(makeProps(0, 'image_0.png') as any)} />);
+ expect(screen.getByText('image_0.png')).toBeInTheDocument();
+ });
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/ImageSearchRef/Render.tsx b/src/features/Conversation/Markdown/plugins/ImageSearchRef/Render.tsx
new file mode 100644
index 00000000000..8c44948a105
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ImageSearchRef/Render.tsx
@@ -0,0 +1,178 @@
+'use client';
+
+import { Flexbox, Popover } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+
+import Image from '@/libs/next/Image';
+
+import { dataSelectors, useConversationStore } from '../../../store';
+import { type MarkdownElementProps } from '../type';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ imageCardLink: css`
+ color: inherit;
+ text-decoration: none;
+ transition: opacity 0.2s;
+
+ &:hover {
+ opacity: 0.75;
+ }
+ `,
+ imageDomain: css`
+ overflow: hidden;
+
+ font-size: 0.8em;
+ line-height: 1;
+ color: ${cssVar.colorTextQuaternary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ imageThumb: css`
+ display: block;
+
+ width: 100%;
+ height: 160px;
+ border-radius: 6px;
+
+ object-fit: cover;
+ `,
+ imageTitle: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+
+ font-size: 0.95em;
+ line-height: 1.4;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ `,
+ refChip: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+
+ padding-block: 1px;
+ padding-inline: 6px;
+ border-radius: 4px;
+
+ font-size: 0.8em;
+ color: ${cssVar.colorTextSecondary};
+ text-decoration: none;
+ vertical-align: -1px;
+
+ background: ${cssVar.colorFillSecondary};
+
+ transition: background 0.15s;
+
+ &:hover {
+ background: ${cssVar.colorFill};
+ }
+ `,
+ thumbWrap: css`
+ overflow: hidden;
+ display: inline-flex;
+ flex-shrink: 0;
+
+ width: 16px;
+ height: 16px;
+ border-radius: 3px;
+ `,
+}));
+
+interface ImageSearchRefProperties {
+ imageIndex: number;
+ originalText: string;
+}
+
+const stripHtml = (html: string) => html.replaceAll(/<[^>]*>/g, '');
+
+const Render = memo<MarkdownElementProps<ImageSearchRefProperties>>(({ node, id }) => {
+ const { imageIndex, originalText } = node?.properties || {};
+
+ const imageResults = useConversationStore(
+ (s) => dataSelectors.getDbMessageById(id)(s)?.search?.imageResults,
+ isEqual,
+ );
+
+ // Fallback: no image results on this message (e.g. non-image-search model)
+ const image = imageResults?.[imageIndex];
+ if (!image) return <span>{originalText}</span>;
+
+ const popoverContent = (
+ <Flexbox gap={4} style={{ maxWidth: 240 }}>
+ {image.imageUri && (
+ <a
+ className={styles.imageCardLink}
+ href={image.imageUri}
+ rel="noopener noreferrer"
+ target="_blank"
+ >
+ <img
+ alt={image.title ? stripHtml(image.title) : ''}
+ className={styles.imageThumb}
+ src={image.imageUri}
+ />
+ </a>
+ )}
+ <a
+ className={styles.imageCardLink}
+ href={image.sourceUri || image.imageUri}
+ rel="noopener noreferrer"
+ target="_blank"
+ title={image.title ? stripHtml(image.title) : undefined}
+ >
+ <Flexbox gap={2}>
+ {image.title && (
+ <div className={styles.imageTitle} dangerouslySetInnerHTML={{ __html: image.title }} />
+ )}
+ {image.domain && (
+ <Flexbox horizontal align="center" gap={4}>
+ <Image
+ unoptimized
+ alt={image.domain}
+ height={12}
+ src={`https://icons.duckduckgo.com/ip3/${image.domain}.ico`}
+ style={{ borderRadius: 2, flexShrink: 0 }}
+ width={12}
+ />
+ <div className={styles.imageDomain}>{image.domain}</div>
+ </Flexbox>
+ )}
+ </Flexbox>
+ </a>
+ </Flexbox>
+ );
+
+ return (
+ <Popover content={popoverContent} trigger="hover">
+ <a
+ href={image.imageUri}
+ rel="noopener noreferrer"
+ style={{ color: 'inherit', textDecoration: 'none' }}
+ target="_blank"
+ >
+ <span className={styles.refChip}>
+ {image.imageUri && (
+ <span className={styles.thumbWrap}>
+ <img
+ alt=""
+ src={image.imageUri}
+ style={{ height: '100%', objectFit: 'cover', width: '100%' }}
+ />
+ </span>
+ )}
+ {originalText}
+ </span>
+ </a>
+ </Popover>
+ );
+});
+
+Render.displayName = 'ImageSearchRefRender';
+
+export default Render;
diff --git a/src/features/Conversation/Markdown/plugins/ImageSearchRef/index.ts b/src/features/Conversation/Markdown/plugins/ImageSearchRef/index.ts
new file mode 100644
index 00000000000..e15cc9c9b64
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ImageSearchRef/index.ts
@@ -0,0 +1,14 @@
+import { type FC } from 'react';
+
+import { type MarkdownElement, type MarkdownElementProps } from '../type';
+import { IMAGE_SEARCH_REF_TAG, rehypeImageSearchRef } from './rehypePlugin';
+import Render from './Render';
+
+const ImageSearchRefElement: MarkdownElement = {
+ Component: Render as FC<MarkdownElementProps>,
+ rehypePlugin: rehypeImageSearchRef,
+ scope: 'assistant',
+ tag: IMAGE_SEARCH_REF_TAG,
+};
+
+export default ImageSearchRefElement;
diff --git a/src/features/Conversation/Markdown/plugins/ImageSearchRef/rehypePlugin.test.ts b/src/features/Conversation/Markdown/plugins/ImageSearchRef/rehypePlugin.test.ts
new file mode 100644
index 00000000000..0c3d2f7c829
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ImageSearchRef/rehypePlugin.test.ts
@@ -0,0 +1,191 @@
+import { describe, expect, it } from 'vitest';
+
+import { IMAGE_SEARCH_REF_TAG, rehypeImageSearchRef } from './rehypePlugin';
+
+const run = (tree: any) => rehypeImageSearchRef()(tree);
+
+describe('rehypeImageSearchRef', () => {
+ describe('basic replacement', () => {
+ it('should replace a lone image_0.png text node with a custom element', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'p',
+ children: [{ type: 'text', value: 'image_0.png' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ const p = (tree as any).children[0];
+ expect(p.children).toHaveLength(1);
+ expect(p.children[0]).toMatchObject({
+ type: 'element',
+ tagName: IMAGE_SEARCH_REF_TAG,
+ properties: { imageIndex: 0, originalText: 'image_0.png' },
+ children: [{ type: 'text', value: 'image_0.png' }],
+ });
+ });
+
+ it('should preserve text before and after the reference', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'p',
+ children: [{ type: 'text', value: 'See image_3.jpg for details.' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ const children = (tree as any).children[0].children;
+ expect(children).toHaveLength(3);
+ expect(children[0]).toEqual({ type: 'text', value: 'See ' });
+ expect(children[1]).toMatchObject({
+ type: 'element',
+ tagName: IMAGE_SEARCH_REF_TAG,
+ properties: { imageIndex: 3, originalText: 'image_3.jpg' },
+ });
+ expect(children[2]).toEqual({ type: 'text', value: ' for details.' });
+ });
+
+ it('should handle multiple references in a single text node', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'p',
+ children: [{ type: 'text', value: 'image_0.png and image_1.webp' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ const children = (tree as any).children[0].children;
+ expect(children).toHaveLength(3);
+ expect(children[0]).toMatchObject({
+ tagName: IMAGE_SEARCH_REF_TAG,
+ properties: { imageIndex: 0, originalText: 'image_0.png' },
+ });
+ expect(children[1]).toEqual({ type: 'text', value: ' and ' });
+ expect(children[2]).toMatchObject({
+ tagName: IMAGE_SEARCH_REF_TAG,
+ properties: { imageIndex: 1, originalText: 'image_1.webp' },
+ });
+ });
+ });
+
+ describe('supported extensions', () => {
+ it.each(['png', 'jpg', 'jpeg', 'gif', 'webp'])('should match image_0.%s', (ext) => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'p',
+ children: [{ type: 'text', value: `image_0.${ext}` }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ const children = (tree as any).children[0].children;
+ expect(children[0]).toMatchObject({
+ type: 'element',
+ tagName: IMAGE_SEARCH_REF_TAG,
+ properties: { imageIndex: 0, originalText: `image_0.${ext}` },
+ });
+ });
+ });
+
+ describe('word boundary enforcement', () => {
+ it('should NOT match when prefix is attached (myimage_0.png)', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'p',
+ children: [{ type: 'text', value: 'myimage_0.png' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ // No replacement — original text node stays
+ const children = (tree as any).children[0].children;
+ expect(children).toHaveLength(1);
+ expect(children[0]).toEqual({ type: 'text', value: 'myimage_0.png' });
+ });
+
+ it('should NOT match when suffix is attached (image_0.pngfile)', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'p',
+ children: [{ type: 'text', value: 'image_0.pngfile' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ const children = (tree as any).children[0].children;
+ expect(children).toHaveLength(1);
+ expect(children[0]).toEqual({ type: 'text', value: 'image_0.pngfile' });
+ });
+ });
+
+ describe('no-op cases', () => {
+ it('should leave text nodes without image references unchanged', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'p',
+ children: [{ type: 'text', value: 'No references here.' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ const children = (tree as any).children[0].children;
+ expect(children).toHaveLength(1);
+ expect(children[0]).toEqual({ type: 'text', value: 'No references here.' });
+ });
+
+ it('should handle multi-digit indices correctly', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'p',
+ children: [{ type: 'text', value: 'image_42.gif' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ const children = (tree as any).children[0].children;
+ expect(children[0]).toMatchObject({
+ properties: { imageIndex: 42, originalText: 'image_42.gif' },
+ });
+ });
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/ImageSearchRef/rehypePlugin.ts b/src/features/Conversation/Markdown/plugins/ImageSearchRef/rehypePlugin.ts
new file mode 100644
index 00000000000..81b2e2e3ce9
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/ImageSearchRef/rehypePlugin.ts
@@ -0,0 +1,59 @@
+import { SKIP, visit } from 'unist-util-visit';
+
+export const IMAGE_SEARCH_REF_TAG = 'image-search-ref';
+
+/** Matches filenames like image_0.png, image_12.jpg produced by Gemini image search */
+const IMAGE_REF_REGEX = /\bimage_(\d+)\.(?:png|jpe?g|gif|webp)\b/gi;
+
+/**
+ * Rehype plugin that transforms plain-text Gemini image references (e.g. `image_0.png`)
+ * appearing in message content into custom `<image-search-ref>` HAST elements.
+ *
+ * The transformation only rewrites text nodes – markdown image syntax is untouched.
+ */
+export const rehypeImageSearchRef = () => (tree: any) => {
+ visit(tree, 'text', (node: any, index: number | undefined, parent: any) => {
+ if (index === undefined || !parent) return;
+
+ const value = String(node.value);
+
+ // Quick check to avoid expensive processing for most nodes
+ IMAGE_REF_REGEX.lastIndex = 0;
+ if (!IMAGE_REF_REGEX.test(value)) return;
+
+ IMAGE_REF_REGEX.lastIndex = 0;
+ const segments: any[] = [];
+ let lastIndex = 0;
+ let match: RegExpExecArray | null;
+
+ while ((match = IMAGE_REF_REGEX.exec(value)) !== null) {
+ // Preserve preceding text
+ if (match.index > lastIndex) {
+ segments.push({ type: 'text', value: value.slice(lastIndex, match.index) });
+ }
+
+ segments.push({
+ children: [{ type: 'text', value: match[0] }],
+ properties: {
+ imageIndex: Number(match[1]),
+ originalText: match[0],
+ },
+ tagName: IMAGE_SEARCH_REF_TAG,
+ type: 'element',
+ });
+
+ lastIndex = match.index + match[0].length;
+ }
+
+ // Preserve trailing text
+ if (lastIndex < value.length) {
+ segments.push({ type: 'text', value: value.slice(lastIndex) });
+ }
+
+ // No actual replacements – exit early (shouldn't happen given test above)
+ if (segments.length === 0) return;
+
+ parent.children.splice(index, 1, ...segments);
+ return [SKIP, index + segments.length];
+ });
+};
diff --git a/src/features/Conversation/Markdown/plugins/index.ts b/src/features/Conversation/Markdown/plugins/index.ts
index e3c62b93ffe..ecfcdc8421a 100644
--- a/src/features/Conversation/Markdown/plugins/index.ts
+++ b/src/features/Conversation/Markdown/plugins/index.ts
@@ -1,3 +1,4 @@
+import ImageSearchRef from './ImageSearchRef';
import LobeArtifact from './LobeArtifact';
import LobeThinking from './LobeThinking';
import LocalFile from './LocalFile';
@@ -13,4 +14,5 @@ export const markdownElements: MarkdownElement[] = [
LobeThinking,
LocalFile,
Mention,
+ ImageSearchRef,
];
diff --git a/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx b/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx
index b2672f3014c..81471911977 100644
--- a/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx
+++ b/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx
@@ -29,7 +29,7 @@ const MessageContent = memo<UIChatMessage>(
const isToolCallGenerating = generating && (content === LOADING_FLAT || !content) && !!tools;
- const showSearch = !!search && !!search.citations?.length;
+ const showSearch = !!search && (!!search.citations?.length || !!search.imageResults?.length);
const showImageItems = !!imageList && imageList.length > 0;
// remove \n to avoid empty content
@@ -67,7 +67,12 @@ const MessageContent = memo<UIChatMessage>(
return (
<Flexbox gap={8} id={id}>
{showSearch && (
- <SearchGrounding citations={search?.citations} searchQueries={search?.searchQueries} />
+ <SearchGrounding
+ citations={search?.citations}
+ imageResults={search?.imageResults}
+ imageSearchQueries={search?.imageSearchQueries}
+ searchQueries={search?.searchQueries}
+ />
)}
{showFileChunks && <FileChunks data={chunksList} />}
{showReasoning && <Reasoning {...props.reasoning} id={id} />}
diff --git a/src/features/Conversation/Messages/Task/components/MessageContent.tsx b/src/features/Conversation/Messages/Task/components/MessageContent.tsx
index 797b8df38b7..6a40dfea80d 100644
--- a/src/features/Conversation/Messages/Task/components/MessageContent.tsx
+++ b/src/features/Conversation/Messages/Task/components/MessageContent.tsx
@@ -26,7 +26,7 @@ const MessageContent = memo<UIChatMessage>(
// TODO: Need to implement isIntentUnderstanding selector in ConversationStore if needed
const isIntentUnderstanding = false;
- const showSearch = !!search && !!search.citations?.length;
+ const showSearch = !!search && (!!search.citations?.length || !!search.imageResults?.length);
const showImageItems = !!imageList && imageList.length > 0;
// remove \n to avoid empty content
@@ -42,7 +42,12 @@ const MessageContent = memo<UIChatMessage>(
return (
<Flexbox gap={8} id={id}>
{showSearch && (
- <SearchGrounding citations={search?.citations} searchQueries={search?.searchQueries} />
+ <SearchGrounding
+ citations={search?.citations}
+ imageResults={search?.imageResults}
+ imageSearchQueries={search?.imageSearchQueries}
+ searchQueries={search?.searchQueries}
+ />
)}
{showFileChunks && <FileChunks data={chunksList} />}
{showReasoning && <Reasoning {...props.reasoning} id={id} />}
diff --git a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx
index 08c16f88a95..1c2bc04c538 100644
--- a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx
+++ b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx
@@ -108,6 +108,12 @@ const TokenDetail = memo<TokenDetailProps>(({ usage, performance, model, provide
? detailTokens.inputCachedWrite.credit
: detailTokens.inputCachedWrite.token,
},
+ !!detailTokens.inputTool && {
+ color: cssVar.geekblue,
+ id: 'inputTool',
+ title: t('messages.tokenDetails.inputTool'),
+ value: isShowCredit ? detailTokens.inputTool.credit : detailTokens.inputTool.token,
+ },
!!detailTokens.totalOutput && {
color: cssVar.colorSuccess,
id: 'output',
diff --git a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/tokens.ts b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/tokens.ts
index 930b88e2bda..ec74b769b36 100644
--- a/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/tokens.ts
+++ b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/tokens.ts
@@ -21,23 +21,25 @@ export const getDetailsToken = (usage: ModelUsage, modelCard?: LobeDefaultAiMode
const outputImageTokens = usage.outputImageTokens || (usage as any).imageTokens || 0;
+ const inputToolTokens = usage.inputToolTokens || 0;
+
const outputTextTokens =
typeof usage.outputTextTokens === 'number'
? usage.outputTextTokens
: Math.max(
- 0,
- totalOutputTokens -
- outputReasoningTokens -
- (usage.outputAudioTokens || 0) -
- outputImageTokens,
- );
+ 0,
+ totalOutputTokens -
+ outputReasoningTokens -
+ (usage.outputAudioTokens || 0) -
+ outputImageTokens,
+ );
const inputWriteCacheTokens = usage.inputWriteCacheTokens || 0;
const inputCacheTokens = usage.inputCachedTokens || (usage as any).cachedTokens || 0;
const inputCacheMissTokens = usage?.inputCacheMissTokens
? usage?.inputCacheMissTokens
- : totalInputTokens - (inputCacheTokens || 0);
+ : totalInputTokens - (inputCacheTokens || 0) - inputToolTokens;
// Pricing
const formatPrice = getPrice(modelCard?.pricing || { units: [] });
@@ -60,16 +62,23 @@ export const getDetailsToken = (usage: ModelUsage, modelCard?: LobeDefaultAiMode
const totalInputCredit = (
!!totalInputTokens ? calcCredit(totalInputTokens, formatPrice.input) : 0
) as number;
+ const inputToolCredit = (
+ !!inputToolTokens ? calcCredit(inputToolTokens, formatPrice.input) : 0
+ ) as number;
const totalCredit =
- inputCacheMissCredit + inputCachedCredit + inputWriteCachedCredit + totalOutputCredit;
+ inputCacheMissCredit +
+ inputCachedCredit +
+ inputWriteCachedCredit +
+ inputToolCredit +
+ totalOutputCredit;
return {
inputAudio: !!usage.inputAudioTokens
? {
- credit: calcCredit(usage.inputAudioTokens, getAudioInputUnitRate(modelCard?.pricing)),
- token: usage.inputAudioTokens,
- }
+ credit: calcCredit(usage.inputAudioTokens, getAudioInputUnitRate(modelCard?.pricing)),
+ token: usage.inputAudioTokens,
+ }
: undefined,
inputCacheMiss: !!inputCacheMissTokens
? { credit: inputCacheMissCredit, token: inputCacheMissTokens }
@@ -82,42 +91,48 @@ export const getDetailsToken = (usage: ModelUsage, modelCard?: LobeDefaultAiMode
: undefined,
inputCitation: !!usage.inputCitationTokens
? {
- credit: calcCredit(usage.inputCitationTokens, formatPrice.input),
- token: usage.inputCitationTokens,
- }
+ credit: calcCredit(usage.inputCitationTokens, formatPrice.input),
+ token: usage.inputCitationTokens,
+ }
: undefined,
inputText: !!inputTextTokens
? {
- credit: calcCredit(inputTextTokens, formatPrice.input),
- token: inputTextTokens,
- }
+ credit: calcCredit(inputTextTokens, formatPrice.input),
+ token: inputTextTokens,
+ }
+ : undefined,
+ inputTool: !!inputToolTokens
+ ? {
+ credit: inputToolCredit,
+ token: inputToolTokens,
+ }
: undefined,
outputAudio: !!usage.outputAudioTokens
? {
- credit: calcCredit(usage.outputAudioTokens, getAudioOutputUnitRate(modelCard?.pricing)),
- id: 'outputAudio',
- token: usage.outputAudioTokens,
- }
+ credit: calcCredit(usage.outputAudioTokens, getAudioOutputUnitRate(modelCard?.pricing)),
+ id: 'outputAudio',
+ token: usage.outputAudioTokens,
+ }
: undefined,
outputImage: !!outputImageTokens
? {
- credit: calcCredit(outputImageTokens, formatPrice.output),
- id: 'outputImage',
- token: outputImageTokens,
- }
+ credit: calcCredit(outputImageTokens, formatPrice.output),
+ id: 'outputImage',
+ token: outputImageTokens,
+ }
: undefined,
outputReasoning: !!outputReasoningTokens
? {
- credit: calcCredit(outputReasoningTokens, formatPrice.output),
- token: outputReasoningTokens,
- }
+ credit: calcCredit(outputReasoningTokens, formatPrice.output),
+ token: outputReasoningTokens,
+ }
: undefined,
outputText: !!outputTextTokens
? {
- credit: calcCredit(outputTextTokens, formatPrice.output),
- token: outputTextTokens,
- }
+ credit: calcCredit(outputTextTokens, formatPrice.output),
+ token: outputTextTokens,
+ }
: undefined,
totalInput: !!totalInputTokens
diff --git a/src/features/Conversation/Messages/components/SearchGrounding.tsx b/src/features/Conversation/Messages/components/SearchGrounding.tsx
index afba157be6a..c2de978607f 100644
--- a/src/features/Conversation/Messages/components/SearchGrounding.tsx
+++ b/src/features/Conversation/Messages/components/SearchGrounding.tsx
@@ -1,6 +1,6 @@
import { Flexbox, Icon, SearchResultCards, Tag } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { ChevronDown, ChevronRight, Globe } from 'lucide-react';
+import { ChevronDown, ChevronRight, Globe, Images } from 'lucide-react';
import { AnimatePresence, m as motion } from 'motion/react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,6 +9,16 @@ import { useIsDark } from '@/hooks/useIsDark';
import Image from '@/libs/next/Image';
import { type GroundingSearch } from '@/types/search';
+const stripHtml = (html: string) =>
+ html
+ .replaceAll(/<[^>]*>/g, '')
+ .replaceAll('&amp;', '&')
+ .replaceAll('&lt;', '<')
+ .replaceAll('&gt;', '>')
+ .replaceAll('&quot;', '"')
+ .replaceAll('&#39;', "'")
+ .replaceAll('&nbsp;', ' ');
+
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
width: fit-content;
@@ -34,6 +44,58 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
expandLight: css`
background: ${cssVar.colorFillTertiary} !important;
`,
+ imageCard: css`
+ overflow: hidden;
+ border-radius: 8px;
+ `,
+ imageCardLink: css`
+ color: inherit;
+ text-decoration: none;
+ transition: opacity 0.2s;
+
+ &:hover {
+ opacity: 0.75;
+ }
+ `,
+ imageDomain: css`
+ overflow: hidden;
+
+ font-size: 11px;
+ line-height: 1;
+ color: ${cssVar.colorTextQuaternary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ imageGrid: css`
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 8px;
+ `,
+ imageThumb: css`
+ display: block;
+ width: 100%;
+ height: 80px;
+ object-fit: cover;
+ `,
+ imageThumbWrap: css`
+ overflow: hidden;
+ display: block;
+ flex-shrink: 0;
+
+ height: 80px;
+ border-radius: 6px;
+ `,
+ imageTitle: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+
+ font-size: 11px;
+ line-height: 1.4;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ `,
title: css`
overflow: hidden;
display: -webkit-box;
@@ -45,97 +107,200 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const SearchGrounding = memo<GroundingSearch>(({ searchQueries, citations }) => {
- const { t } = useTranslation('chat');
- const isDarkMode = useIsDark();
-
- const [showDetail, setShowDetail] = useState(false);
-
- return (
- <Flexbox
- gap={16}
- style={{ width: showDetail ? '100%' : undefined }}
- className={cx(
- styles.container,
- isDarkMode ? styles.containerDark : styles.containerLight,
- showDetail && (isDarkMode ? styles.expandDark : styles.expandLight),
- )}
- >
+const SearchGrounding = memo<GroundingSearch>(
+ ({ searchQueries, citations, imageResults, imageSearchQueries }) => {
+ const { t } = useTranslation('chat');
+ const isDarkMode = useIsDark();
+
+ const [showDetail, setShowDetail] = useState(false);
+
+ const hasWebResults = !!citations?.length;
+ const hasImageResults = !!imageResults?.length;
+ const titleIcon = !hasWebResults && hasImageResults ? Images : Globe;
+ const titleText = hasWebResults
+ ? t('search.grounding.title', { count: citations?.length })
+ : t('search.grounding.imageTitle', { count: imageResults?.length });
+
+ return (
<Flexbox
- horizontal
- distribution={'space-between'}
- flex={1}
- gap={8}
- style={{ cursor: 'pointer' }}
- onClick={() => {
- setShowDetail(!showDetail);
- }}
+ gap={16}
+ style={{ width: showDetail ? '100%' : undefined }}
+ className={cx(
+ styles.container,
+ isDarkMode ? styles.containerDark : styles.containerLight,
+ showDetail && (isDarkMode ? styles.expandDark : styles.expandLight),
+ )}
>
- <Flexbox horizontal align={'center'} gap={8}>
- <Icon icon={Globe} />
- <Flexbox horizontal>{t('search.grounding.title', { count: citations?.length })}</Flexbox>
- {!showDetail && (
- <Flexbox horizontal>
- {citations?.slice(0, 8).map((item, index) => (
- <Image
- unoptimized
- alt={item.title || item.url}
- height={16}
- key={`${item.url}-${index}`}
- src={`https://icons.duckduckgo.com/ip3/${new URL(item.url).host}.ico`}
- width={16}
- style={{
- background: cssVar.colorBgContainer,
- borderRadius: 8,
- marginInline: -2,
- padding: 2,
- zIndex: 100 - index,
- }}
- />
- ))}
- </Flexbox>
- )}
- </Flexbox>
+ <Flexbox
+ horizontal
+ distribution={'space-between'}
+ flex={1}
+ gap={8}
+ style={{ cursor: 'pointer' }}
+ onClick={() => {
+ setShowDetail(!showDetail);
+ }}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon icon={titleIcon} />
+ <Flexbox horizontal>{titleText}</Flexbox>
+ {!showDetail && hasWebResults && (
+ <Flexbox horizontal>
+ {citations?.slice(0, 8).map((item, index) => (
+ <Image
+ unoptimized
+ alt={item.title || item.url}
+ height={16}
+ key={`${item.url}-${index}`}
+ src={`https://icons.duckduckgo.com/ip3/${item.favicon || new URL(item.url).host}.ico`}
+ width={16}
+ style={{
+ background: cssVar.colorBgContainer,
+ borderRadius: 8,
+ marginInline: -2,
+ padding: 2,
+ zIndex: 100 - index,
+ }}
+ />
+ ))}
+ </Flexbox>
+ )}
+ {!showDetail && !hasWebResults && hasImageResults && (
+ <Flexbox horizontal>
+ {imageResults?.slice(0, 8).map((item, index) => (
+ <Image
+ unoptimized
+ alt={item.domain || ''}
+ height={16}
+ key={`${item.domain}-${index}`}
+ src={`https://icons.duckduckgo.com/ip3/${item.domain || ''}.ico`}
+ width={16}
+ style={{
+ background: cssVar.colorBgContainer,
+ borderRadius: 8,
+ marginInline: -2,
+ padding: 2,
+ zIndex: 100 - index,
+ }}
+ />
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
- <Flexbox horizontal gap={4}>
- <Icon icon={showDetail ? ChevronDown : ChevronRight} />
+ <Flexbox horizontal gap={4}>
+ <Icon icon={showDetail ? ChevronDown : ChevronRight} />
+ </Flexbox>
</Flexbox>
- </Flexbox>
- <AnimatePresence initial={false}>
- {showDetail && (
- <motion.div
- animate="open"
- exit="collapsed"
- initial="collapsed"
- style={{ overflow: 'hidden', width: '100%' }}
- transition={{
- duration: 0.2,
- ease: [0.4, 0, 0.2, 1], // Using ease-out easing function
- }}
- variants={{
- collapsed: { height: 0, opacity: 0, width: 'auto' },
- open: { height: 'auto', opacity: 1, width: 'auto' },
- }}
- >
- <Flexbox gap={12}>
- {searchQueries && (
- <Flexbox horizontal gap={4}>
- {t('search.grounding.searchQueries')}
- <Flexbox horizontal gap={8}>
- {searchQueries.map((query, index) => (
- <Tag key={index}>{query}</Tag>
- ))}
+ <AnimatePresence initial={false}>
+ {showDetail && (
+ <motion.div
+ animate="open"
+ exit="collapsed"
+ initial="collapsed"
+ style={{ overflow: 'hidden', width: '100%' }}
+ transition={{
+ duration: 0.2,
+ ease: [0.4, 0, 0.2, 1], // Using ease-out easing function
+ }}
+ variants={{
+ collapsed: { height: 0, opacity: 0, width: 'auto' },
+ open: { height: 'auto', opacity: 1, width: 'auto' },
+ }}
+ >
+ <Flexbox gap={12}>
+ {searchQueries && (
+ <Flexbox horizontal gap={4}>
+ {t('search.grounding.searchQueries')}
+ <Flexbox horizontal gap={8}>
+ {searchQueries.map((query, index) => (
+ <Tag key={index}>{query}</Tag>
+ ))}
+ </Flexbox>
</Flexbox>
- </Flexbox>
- )}
- {citations && <SearchResultCards dataSource={citations} />}
- </Flexbox>
- </motion.div>
- )}
- </AnimatePresence>
- </Flexbox>
- );
-});
+ )}
+ {citations && (
+ <SearchResultCards
+ dataSource={citations.map((c) => ({
+ ...c,
+ // Pass the original redirect URL as href to preserve the actual link
+ href: c.url,
+ // Override url with favicon domain so SearchResultCard derives the correct favicon host
+ url: c.favicon ? `https://${c.favicon}` : c.url,
+ }))}
+ />
+ )}
+ {imageSearchQueries && imageSearchQueries.length > 0 && (
+ <Flexbox horizontal gap={4}>
+ {t('search.grounding.imageSearchQueries')}
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {imageSearchQueries.map((query, index) => (
+ <Tag key={index}>{query}</Tag>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ )}
+ {imageResults && imageResults.length > 0 && (
+ <div className={styles.imageGrid}>
+ {imageResults.map((item, index) => (
+ <div className={styles.imageCard} key={`${item.imageUri}-${index}`}>
+ <Flexbox gap={4}>
+ <a
+ className={styles.imageCardLink}
+ href={item.imageUri}
+ rel="noopener noreferrer"
+ target="_blank"
+ >
+ <div className={styles.imageThumbWrap}>
+ <img
+ alt={item.title ? stripHtml(item.title) : ''}
+ className={styles.imageThumb}
+ src={item.imageUri || ''}
+ />
+ </div>
+ </a>
+ <a
+ className={styles.imageCardLink}
+ href={item.sourceUri}
+ rel="noopener noreferrer"
+ target="_blank"
+ title={item.title ? stripHtml(item.title) : undefined}
+ >
+ <Flexbox gap={2}>
+ {item.title && (
+ <div
+ className={styles.imageTitle}
+ dangerouslySetInnerHTML={{ __html: item.title }}
+ />
+ )}
+ {item.domain && (
+ <Flexbox horizontal align="center" gap={4}>
+ <Image
+ unoptimized
+ alt={item.domain}
+ height={12}
+ src={`https://icons.duckduckgo.com/ip3/${item.domain}.ico`}
+ style={{ borderRadius: 2, flexShrink: 0 }}
+ width={12}
+ />
+ <div className={styles.imageDomain}>{item.domain}</div>
+ </Flexbox>
+ )}
+ </Flexbox>
+ </a>
+ </Flexbox>
+ </div>
+ ))}
+ </div>
+ )}
+ </Flexbox>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </Flexbox>
+ );
+ },
+);
export default SearchGrounding;
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ImageAspectRatio2Select.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ImageAspectRatio2Select.tsx
index 041fe21607d..4d6e3f791c8 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/ImageAspectRatio2Select.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ImageAspectRatio2Select.tsx
@@ -7,6 +7,7 @@ import { useAgentStore } from '@/store/agent';
import { chatConfigByIdSelectors } from '@/store/agent/selectors';
const NANO_BANANA_2_ASPECT_RATIOS = [
+ 'auto',
'1:1', // 1024x1024 / 2048x2048 / 4096x4096
'2:3', // 848x1264 / 1696x2528 / 3392x5056
'3:2', // 1264x848 / 2528x1696 / 5056x3392
@@ -74,7 +75,7 @@ const ImageAspectRatio2SelectWithStore = memo<{ defaultValue: AspectRatio2 }>(
// Main exported component - chooses between controlled and store mode
const ImageAspectRatio2Select = memo<ImageAspectRatio2SelectProps>(
- ({ value: controlledValue, onChange: controlledOnChange, defaultValue = '1:1' }) => {
+ ({ value: controlledValue, onChange: controlledOnChange, defaultValue = 'auto' }) => {
const isControlled = controlledValue !== undefined || controlledOnChange !== undefined;
if (isControlled) {
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ImageAspectRatioSelect.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ImageAspectRatioSelect.tsx
index c9526407e17..3ec930dda18 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/ImageAspectRatioSelect.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ImageAspectRatioSelect.tsx
@@ -7,6 +7,7 @@ import { useAgentStore } from '@/store/agent';
import { chatConfigByIdSelectors } from '@/store/agent/selectors';
const NANO_BANANA_ASPECT_RATIOS = [
+ 'auto',
'1:1', // 1024x1024 / 2048x2048 / 4096x4096
'2:3', // 848x1264 / 1696x2528 / 3392x5056
'3:2', // 1264x848 / 2528x1696 / 5056x3392
@@ -68,7 +69,7 @@ const ImageAspectRatioSelectWithStore = memo<{ defaultValue: AspectRatio }>(({ d
// Main exported component - chooses between controlled and store mode
const ImageAspectRatioSelect = memo<ImageAspectRatioSelectProps>(
- ({ value: controlledValue, onChange: controlledOnChange, defaultValue = '1:1' }) => {
+ ({ value: controlledValue, onChange: controlledOnChange, defaultValue = 'auto' }) => {
const isControlled = controlledValue !== undefined || controlledOnChange !== undefined;
if (isControlled) {
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 61e47b17e88..8f160636f59 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -214,6 +214,7 @@ export default {
'messages.tokenDetails.inputTitle': 'Input Details',
'messages.tokenDetails.inputUncached': 'Uncached Input',
'messages.tokenDetails.inputWriteCached': 'Input cache write',
+ 'messages.tokenDetails.inputTool': 'Tool Use Input',
'messages.tokenDetails.output': 'Output',
'messages.tokenDetails.outputAudio': 'Audio Output',
'messages.tokenDetails.outputImage': 'Image Output',
@@ -270,6 +271,8 @@ export default {
'memory.on.desc': 'Allow AI to actively search and manage your memories during conversation.',
'memory.on.title': 'Enable Memory Tool',
'memory.title': 'Memory',
+ 'search.grounding.imageSearchQueries': 'Image Search Keywords',
+ 'search.grounding.imageTitle': 'Found {{count}} images',
'search.grounding.searchQueries': 'Search Keywords',
'search.grounding.title': 'Found {{count}} results',
'search.mode.auto.desc': 'Search the web automatically when needed.',
diff --git a/src/store/chat/agents/StreamingHandler.ts b/src/store/chat/agents/StreamingHandler.ts
index 321ac3f1916..679d4cf2e87 100644
--- a/src/store/chat/agents/StreamingHandler.ts
+++ b/src/store/chat/agents/StreamingHandler.ts
@@ -287,12 +287,10 @@ export class StreamingHandler {
}
private handleGroundingChunk(chunk: { grounding?: GroundingData; type: 'grounding' }): void {
- if (!chunk.grounding?.citations?.length) return;
+ const { grounding } = chunk;
+ if (!grounding?.citations?.length && !grounding?.imageResults?.length) return;
- this.callbacks.onGroundingUpdate({
- citations: chunk.grounding.citations,
- searchQueries: chunk.grounding.searchQueries,
- });
+ this.callbacks.onGroundingUpdate(grounding);
}
private handleBase64ImageChunk(chunk: {
@@ -526,7 +524,10 @@ export class StreamingHandler {
isMultimodal: hasContentImages || undefined,
performance: finishData.speed,
reasoning: finalReasoning,
- search: finishData.grounding?.citations ? finishData.grounding : undefined,
+ search:
+ finishData.grounding?.citations?.length || finishData.grounding?.imageResults?.length
+ ? finishData.grounding
+ : undefined,
usage: finishData.usage,
},
toolCalls: finishData.toolCalls,