An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
fix(citation): give fetch results citation labels (#1045)
Yoshiki Miura25d572a110c3
diff --git a/evals/tasks/fixture-tools.ts b/evals/tasks/fixture-tools.tsindex c3532092..472a3d62 100644--- a/evals/tasks/fixture-tools.ts+++ b/evals/tasks/fixture-tools.ts@@ -15,11 +15,14 @@ export function createFixtureFetchTool(results: SearchFixture[]) {description: fetchTool.description,inputSchema: fetchTool.inputSchema,async execute({ url }: { url: string }) {- const match = results.find(result => result.url === url)+ // Carries the label the fixture search gave the same document, so a+ // citation of the fetched page resolves like it does in production.+ const labelledResults = assignCitationLabels(results, 1)+ const match = labelledResults.find(result => result.url === url)return {state: 'complete' as const,query: url,- results: match ? [match] : results,+ results: match ? [match] : labelledResults,images: [],number_of_results: match ? 1 : results.length}diff --git a/lib/agents/__tests__/researcher.test.ts b/lib/agents/__tests__/researcher.test.tsindex 1b1d169b..a678d337 100644--- a/lib/agents/__tests__/researcher.test.ts+++ b/lib/agents/__tests__/researcher.test.ts@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest'+import { createFetchTool } from '@/lib/tools/fetch'import { createSearchTool } from '@/lib/tools/search'import type { Model } from '@/lib/types/models'@@ -20,7 +21,7 @@ vi.mock('ai', () => ({}))vi.mock('@/lib/tools/fetch', () => ({- fetchTool: {}+ createFetchTool: vi.fn(() => ({}))}))vi.mock('@/lib/tools/question', () => ({@@ -116,14 +117,16 @@ describe('createResearcher', () => {})})- it('passes the citation label seed to the search tool', () => {+ it('shares a seeded citation label allocator between search and fetch', () => {createResearcher({model: 'openai:model-id',citationLabelSeed: 9})- expect(createSearchTool).toHaveBeenCalledWith('openai:model-id', {- labelSeed: 9- })+ const searchOptions = vi.mocked(createSearchTool).mock.calls[0][1]+ const fetchOptions = vi.mocked(createFetchTool).mock.calls[0][0]++ expect(searchOptions?.labelAllocator).toBe(fetchOptions?.labelAllocator)+ expect(searchOptions?.labelAllocator?.reserve(1)).toBe(9)})})diff --git a/lib/agents/prompts/search-mode-prompts.ts b/lib/agents/prompts/search-mode-prompts.tsindex a2f15a0e..acfae6bc 100644--- a/lib/agents/prompts/search-mode-prompts.ts+++ b/lib/agents/prompts/search-mode-prompts.ts@@ -81,7 +81,7 @@ Search requirement (MANDATORY):- Do NOT answer informational questions based only on internal knowledge; verify with current sources via search and cite- Prefer recent sources when recency matters; mention dates when relevant- For informational questions without URLs, your FIRST action in this turn MUST be the \`search\` tool. Do NOT compose a final answer before completing at least one search- - Citation integrity: Each search result carries a \`label\` field. Cite that label exactly as it appears on the result you used and never invent one+ - Citation integrity: Each search or fetch result carries a \`label\` field. Cite that label exactly as it appears on the result you used and never invent one- If initial results are insufficient or stale, state the limitation or ask a clarifying question; do not run a second searchFetch tool usage:@@ -93,7 +93,7 @@ Fetch tool usage:Citation Format (MANDATORY):[number](#label) - Always use this EXACT format-- Each search result carries a \`label\` field. Use the label exactly as it appears on the result you used+- Each search or fetch result carries a \`label\` field. Use the label exactly as it appears on the result you used- Never invent a label or cite a label from a different result- The number in brackets carries no meaning. Always write \`1\`- Examples of valid citations: [1](#S3), [1](#S7), [1](#S12)@@ -187,7 +187,7 @@ Mandatory search for questions:- Do NOT answer informational questions based only on internal knowledge; verify with current sources and include citations- Prioritize recency when relevant and reference dates- Your FIRST action for informational questions without URLs MUST be the \`search\` tool. Do not produce the final answer until at least one search has completed in this turn- - Citation integrity: Each search result carries a \`label\` field. Cite that label exactly as it appears on the result you used and never invent one+ - Citation integrity: Each search or fetch result carries a \`label\` field. Cite that label exactly as it appears on the result you used and never invent one- If results are weak, refine your query and perform one additional search (or ask a clarifying question) before answeringTool preamble (adaptive):@@ -201,7 +201,7 @@ Rule precedence:4. **If the query is ambiguous, use ask_question tool for clarification**-5. **CRITICAL: You MUST cite sources inline using the [number](#label) format**. **CITATION PLACEMENT**: Follow this pattern: sentence. [citation] - Write the complete sentence, add a period, then add citations after the period. Do NOT add period or punctuation after citations. If a sentence uses multiple sources, place ALL citations together after the period (e.g., "AI adoption has increased. [1](#S3) [1](#S7)"). Each search result carries a \`label\` field. Cite the label exactly as it appears on the result you used and never invent one. The number in brackets carries no meaning; always write \`1\`. Every sentence with information from search results MUST have citations at its end.+5. **CRITICAL: You MUST cite sources inline using the [number](#label) format**. **CITATION PLACEMENT**: Follow this pattern: sentence. [citation] - Write the complete sentence, add a period, then add citations after the period. Do NOT add period or punctuation after citations. If a sentence uses multiple sources, place ALL citations together after the period (e.g., "AI adoption has increased. [1](#S3) [1](#S7)"). Each search or fetch result carries a \`label\` field. Cite the label exactly as it appears on the result you used and never invent one. The number in brackets carries no meaning; always write \`1\`. Every sentence with information from search results MUST have citations at its end.6. If results are not relevant or helpful, you may rely on your general knowledge ONLY AFTER at least one search attempt (do not add citations for general knowledge)@@ -263,7 +263,7 @@ When using the ask_question tool:Citation Format:[number](#label) - Always use this EXACT format, e.g., [1](#S3), [1](#S7), [1](#S12)-- Each search result carries a \`label\` field. Use the label exactly as it appears on the result you used+- Each search or fetch result carries a \`label\` field. Use the label exactly as it appears on the result you used- Never invent a label or cite a label from a different result- The number in brackets carries no meaning. Always write \`1\`- **CRITICAL CITATION PLACEMENT RULES**:diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.tsindex 135818f3..8cf6f8a4 100644--- a/lib/agents/researcher.ts+++ b/lib/agents/researcher.ts@@ -6,11 +6,12 @@ import type {} from '@/lib/types/agent'import { type Model } from '@/lib/types/models'-import { fetchTool } from '../tools/fetch'+import { createFetchTool } from '../tools/fetch'import { createQuestionTool } from '../tools/question'import { createSearchTool } from '../tools/search'import { createTodoTools } from '../tools/todo'import { SearchMode } from '../types/search'+import { createCitationLabelAllocator } from '../utils/citation'import { getModel } from '../utils/registry'import { isTracingEnabled } from '../utils/telemetry'@@ -89,9 +90,11 @@ export function createResearcher({const currentDate = new Date().toLocaleDateString()// Create model-specific tools with proper typing+ const labelAllocator = createCitationLabelAllocator(citationLabelSeed)const originalSearchTool = createSearchTool(model, {- labelSeed: citationLabelSeed+ labelAllocator})+ const fetchTool = createFetchTool({ labelAllocator })const askQuestionTool = createQuestionTool(model)const todoTools = createTodoTools()diff --git a/lib/render/__tests__/prompt.test.ts b/lib/render/__tests__/prompt.test.tsindex 944cea6e..4212fca4 100644--- a/lib/render/__tests__/prompt.test.ts+++ b/lib/render/__tests__/prompt.test.ts@@ -48,7 +48,9 @@ describe('render prompts', () => {const prompt = getPrompt()expect(prompt).toContain('[number](#label)')- expect(prompt).toContain('Each search result carries a `label` field')+ expect(prompt).toContain(+ 'Each search or fetch result carries a `label` field'+ )expect(prompt).toContain('number in brackets carries no meaning')expect(prompt).toContain('[1](#S3)')expect(prompt).toContain('[1](#S7)')diff --git a/lib/tools/__tests__/fetch.test.ts b/lib/tools/__tests__/fetch.test.tsindex f953e921..8ee10402 100644--- a/lib/tools/__tests__/fetch.test.ts+++ b/lib/tools/__tests__/fetch.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { fetchTool } from '@/lib/tools/fetch'+import { createFetchTool, fetchTool } from '@/lib/tools/fetch'+import { createCitationLabelAllocator } from '@/lib/utils/citation'const url = 'https://example.com/resource'@@ -63,6 +64,34 @@ describe('regular fetch content types', () => {})})+ it('labels results from the allocator seed', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(+ async () =>+ new Response('Fetched body', {+ headers: { 'content-type': 'text/plain' }+ })+ )+ )+ const tool = createFetchTool({+ labelAllocator: createCitationLabelAllocator(7)+ })+ const result = tool.execute?.(+ { url, type: 'regular' },+ { toolCallId: 'fetch', messages: [], context: {} }+ )+ const iterator = (result as AsyncIterable<unknown>)[Symbol.asyncIterator]()++ await iterator.next()+ const complete = await iterator.next()++ expect(complete.value).toMatchObject({+ results: [{ label: 'S7', url }],+ state: 'complete'+ })+ })+it('rejects unsupported content types', async () => {vi.spyOn(console, 'error').mockImplementation(() => {})const result = fetchRegular('PDF', 'application/pdf')diff --git a/lib/tools/__tests__/search-fallback.test.ts b/lib/tools/__tests__/search-fallback.test.tsindex ab88761c..d31347ee 100644--- a/lib/tools/__tests__/search-fallback.test.ts+++ b/lib/tools/__tests__/search-fallback.test.ts@@ -11,8 +11,10 @@ vi.mock('@/lib/tools/search/providers', () => ({DEFAULT_PROVIDER: 'tavily'}))+import { createFetchTool } from '@/lib/tools/fetch'import { createSearchTool } from '@/lib/tools/search'import type { SearchResultItem } from '@/lib/types'+import { createCitationLabelAllocator } from '@/lib/utils/citation'const fallbackResult = {results: [@@ -47,6 +49,15 @@ function executeGeneralSearch(return (result as AsyncIterable<unknown>)[Symbol.asyncIterator]()}+function executeFetch(fetchTool: ReturnType<typeof createFetchTool>) {+ const result = fetchTool.execute?.(+ { url: 'https://example.com/fetched', type: 'regular' },+ { toolCallId: 'fetch-call', messages: [], context: {} }+ )++ return (result as AsyncIterable<unknown>)[Symbol.asyncIterator]()+}+describe('general search provider fallback', () => {beforeEach(() => {vi.stubEnv('BRAVE_SEARCH_API_KEY', 'test-key')@@ -125,6 +136,62 @@ describe('general search provider fallback', () => {expect(secondLabels).toEqual(['S7', 'S8'])})+ it.each(['search-first', 'fetch-first'] as const)(+ 'shares non-overlapping labels when %s',+ async order => {+ const labelAllocator = createCitationLabelAllocator(5)+ const searchTool = createSearchTool('openai:gpt-4o-mini', {+ labelAllocator+ })+ const fetchTool = createFetchTool({ labelAllocator })+ mocks.braveSearch.mockResolvedValue({+ ...fallbackResult,+ results: [+ ...fallbackResult.results,+ {+ title: 'Second result',+ content: 'More content',+ url: 'https://example.com/second'+ }+ ]+ })+ vi.stubGlobal(+ 'fetch',+ vi.fn(+ async () =>+ new Response('Fetched content', {+ headers: { 'content-type': 'text/plain' }+ })+ )+ )++ const search = executeGeneralSearch('basic', searchTool)+ const fetch = executeFetch(fetchTool)+ const first = order === 'search-first' ? search : fetch+ const second = order === 'search-first' ? fetch : search++ await first.next()+ const firstComplete = await first.next()+ await second.next()+ const secondComplete = await second.next()+ const searchComplete =+ order === 'search-first' ? firstComplete : secondComplete+ const fetchComplete =+ order === 'search-first' ? secondComplete : firstComplete+ const searchLabels = (+ searchComplete.value as { results: SearchResultItem[] }+ ).results.map(result => result.label)+ const fetchLabels = (+ fetchComplete.value as { results: SearchResultItem[] }+ ).results.map(result => result.label)++ expect(searchLabels).toEqual(+ order === 'search-first' ? ['S5', 'S6'] : ['S6', 'S7']+ )+ expect(fetchLabels).toEqual(order === 'search-first' ? ['S7'] : ['S5'])+ }+ )+it('uses the optimized provider after a transport failure', async () => {mocks.braveSearch.mockRejectedValue(new TypeError('fetch failed'))vi.spyOn(console, 'warn').mockImplementation(() => undefined)diff --git a/lib/tools/fetch.ts b/lib/tools/fetch.tsindex 0fb8190b..1ae0dbcc 100644--- a/lib/tools/fetch.ts+++ b/lib/tools/fetch.ts@@ -3,6 +3,11 @@ import { tool, UIToolInvocation } from 'ai'import { INVALID_URL_SENTINEL, ToolFailureError } from '@/lib/errors/tool-error'import { fetchSchema } from '@/lib/schema/fetch'import { SearchResults as SearchResultsType } from '@/lib/types'+import {+ assignCitationLabels,+ type CitationLabelAllocator,+ createCitationLabelAllocator+} from '@/lib/utils/citation'import {assertPublicUrl,assertResolvedPublicUrl,@@ -182,60 +187,76 @@ async function fetchTavilyExtractData(url: string): Promise<SearchResultsType> {}}-export const fetchTool = tool({- description:- 'Fetch content from any URL. By default uses "regular" type which performs fast, direct HTML fetching without external APIs - ideal for most websites. IMPORTANT: "regular" type does NOT support PDFs and will fail on PDF URLs. Use "api" type when you need: 1) PDF content extraction (required for .pdf URLs), 2) Complex JavaScript-rendered pages, 3) Better markdown formatting, 4) Table extraction. The "api" type requires Jina or Tavily API keys and uses Jina Reader if available, otherwise falls back to Tavily Extract.',- inputSchema: fetchSchema,- async *execute({ url, type = 'regular' }) {- assertFetchableUrl(url)- // Ahead of the branch below, so an address the server must not reach is- // refused whether it would be read here or handed to an extraction service.- try {- assertPublicUrl(url)- } catch (error) {- throw new ToolFailureError('fetch', error)- }+export function createFetchTool(options?: {+ labelAllocator?: CitationLabelAllocator+}) {+ const labelAllocator =+ options?.labelAllocator ?? createCitationLabelAllocator()- // Yield initial fetching state- yield {- state: 'fetching' as const,- url- }+ return tool({+ description:+ 'Fetch content from any URL. By default uses "regular" type which performs fast, direct HTML fetching without external APIs - ideal for most websites. IMPORTANT: "regular" type does NOT support PDFs and will fail on PDF URLs. Use "api" type when you need: 1) PDF content extraction (required for .pdf URLs), 2) Complex JavaScript-rendered pages, 3) Better markdown formatting, 4) Table extraction. The "api" type requires Jina or Tavily API keys and uses Jina Reader if available, otherwise falls back to Tavily Extract.',+ inputSchema: fetchSchema,+ async *execute({ url, type = 'regular' }) {+ assertFetchableUrl(url)+ // Ahead of the branch below, so an address the server must not reach is+ // refused whether it would be read here or handed to an extraction service.+ try {+ assertPublicUrl(url)+ } catch (error) {+ throw new ToolFailureError('fetch', error)+ }- let results: SearchResultsType-- // Only the retrieval is wrapped: a yield rejects when the consumer stops- // reading, and an aborted stream is not a failure of the page.- try {- if (type === 'regular') {- // Use regular fetch for direct HTML retrieval- results = await fetchRegularData(url)- } else {- // The extraction service does the requesting here, so the name has to- // be settled before it is handed over rather than at connect time.- await assertResolvedPublicUrl(url)-- // Use API-based extraction (Jina or Tavily)- const useJina = process.env.JINA_API_KEY- if (useJina) {- results = await fetchJinaReaderData(url)+ // Yield initial fetching state+ yield {+ state: 'fetching' as const,+ url+ }++ let results: SearchResultsType++ // Only the retrieval is wrapped: a yield rejects when the consumer stops+ // reading, and an aborted stream is not a failure of the page.+ try {+ if (type === 'regular') {+ // Use regular fetch for direct HTML retrieval+ results = await fetchRegularData(url)} else {- results = await fetchTavilyExtractData(url)+ // The extraction service does the requesting here, so the name has to+ // be settled before it is handed over rather than at connect time.+ await assertResolvedPublicUrl(url)++ // Use API-based extraction (Jina or Tavily)+ const useJina = process.env.JINA_API_KEY+ if (useJina) {+ results = await fetchJinaReaderData(url)+ } else {+ results = await fetchTavilyExtractData(url)+ }}+ } catch (error) {+ throw new ToolFailureError('fetch', error)+ }++ if (Array.isArray(results.results)) {+ results.results = assignCitationLabels(+ results.results,+ labelAllocator.reserve(results.results.length)+ )}- } catch (error) {- throw new ToolFailureError('fetch', error)- }- logToolPayload('fetch', url, { results: results.results })+ logToolPayload('fetch', url, { results: results.results })- // Yield final results with complete state- yield {- state: 'complete' as const,- ...results+ // Yield final results with complete state+ yield {+ state: 'complete' as const,+ ...results+ }}- }-})+ })+}++export const fetchTool = createFetchTool()// Export type for UI tool invocationexport type FetchUIToolInvocation = UIToolInvocation<typeof fetchTool>diff --git a/lib/tools/search.ts b/lib/tools/search.tsindex f58a60b5..c2370fd2 100644--- a/lib/tools/search.ts+++ b/lib/tools/search.ts@@ -4,7 +4,11 @@ import { ToolFailureError } from '@/lib/errors/tool-error'import { getSearchSchemaForModel } from '@/lib/schema/search'import { sliceWithoutSplittingSurrogatePair } from '@/lib/streaming/helpers/slice-without-splitting-surrogate-pair'import { SearchResults } from '@/lib/types'-import { assignCitationLabels } from '@/lib/utils/citation'+import {+ assignCitationLabels,+ type CitationLabelAllocator,+ createCitationLabelAllocator+} from '@/lib/utils/citation'import {getGeneralSearchProviderType,getSearchToolDescription@@ -55,9 +59,14 @@ function describeRecoverableSearchFailure(*/export function createSearchTool(fullModel: string,- options?: { labelSeed?: number }+ options?: {+ labelAllocator?: CitationLabelAllocator+ labelSeed?: number+ }) {- let nextLabelNumber = options?.labelSeed ?? 1+ const labelAllocator =+ options?.labelAllocator ??+ createCitationLabelAllocator(options?.labelSeed ?? 1)return tool({description: getSearchToolDescription(),@@ -225,8 +234,9 @@ export function createSearchTool(// Reserve the block synchronously so searches running in parallel within// the same step cannot be handed overlapping labels.if (Array.isArray(searchResult.results)) {- const labelBlockStart = nextLabelNumber- nextLabelNumber += searchResult.results.length+ const labelBlockStart = labelAllocator.reserve(+ searchResult.results.length+ )searchResult.results = assignCitationLabels(searchResult.results,labelBlockStartdiff --git a/lib/utils/__tests__/citation.test.ts b/lib/utils/__tests__/citation.test.tsindex d41699b4..92bae272 100644--- a/lib/utils/__tests__/citation.test.ts+++ b/lib/utils/__tests__/citation.test.ts@@ -48,6 +48,34 @@ function labelledAssistantMessage({} as unknown as UIMessage}+function labelledFetchMessage({+ id,+ label,+ url+}: {+ id: string+ label: string+ url: string+}): UIMessage {+ return {+ id,+ role: 'assistant',+ parts: [+ {+ type: 'tool-fetch',+ state: 'output-available',+ toolCallId: `fetch-${id}`,+ input: { url },+ output: {+ query: '',+ images: [],+ results: [{ label, title: id, url, content: `${id} evidence` }]+ }+ }+ ]+ } as unknown as UIMessage+}+describe('processCitations', () => {const mockCitationMaps = {toolCall1: {@@ -382,6 +410,20 @@ describe('processCitations', () => {expect(maps).not.toHaveProperty('invalid')expect(maps.toolCall1[2]).toEqual(labelledResults[1])})++ it('maps fetch labels without adding a tool-call map', () => {+ const message = labelledFetchMessage({+ id: 'fetched',+ label: 'S3',+ url: 'https://fetched.test/source'+ })+ const maps = extractCitationMaps(message)++ expect(maps).not.toHaveProperty('fetch-fetched')+ expect(processCitations('[1](#S3)', maps)).toBe(+ '[fetched](https://fetched.test/source)'+ )+ })})describe('derived citation labels', () => {@@ -459,6 +501,47 @@ describe('processCitations', () => {expect(nextCitationLabelNumber([message])).toBe(13)})+ it('advances past labels from fetch outputs', () => {+ const message = labelledFetchMessage({+ id: 'fetch-history',+ label: 'S8',+ url: 'https://fetched.test/history'+ })++ expect(nextCitationLabelNumber([message])).toBe(9)+ })++ it('resolves fetch labels through the combined conversation map', () => {+ const message = labelledFetchMessage({+ id: 'fetch-turn',+ label: 'S3',+ url: 'https://fetched.test/combined'+ })+ const maps = extractCitationMapsFromMessages([message])++ expect(processCitations('[1](#S3)', maps)).toBe(+ '[fetched](https://fetched.test/combined)'+ )+ })++ it('treats a label shared by search and fetch turns as ambiguous', () => {+ const search = labelledAssistantMessage({+ id: 'search-turn',+ toolCallId: 'search-call',+ labels: ['S3'],+ urls: ['https://search.test/source']+ })+ const fetch = labelledFetchMessage({+ id: 'fetch-turn',+ label: 'S3',+ url: 'https://fetch.test/source'+ })+ const maps = extractCitationMapsFromMessages([search, fetch])++ expect(maps).not.toHaveProperty('S3')+ expect(processCitations('[1](#S3)', maps)).toBe('')+ })+it('refuses to resolve a label two turns both claim', () => {const first = labelledAssistantMessage({id: 'concurrent-one',diff --git a/lib/utils/citation.ts b/lib/utils/citation.tsindex ce7745c9..ab95d349 100644--- a/lib/utils/citation.ts+++ b/lib/utils/citation.ts@@ -20,6 +20,22 @@ export function isCitationLabel(label: string): boolean {const DERIVED_LABEL_PATTERN = /^S\d+$/+export type CitationLabelAllocator = {+ reserve(count: number): number+}++export function createCitationLabelAllocator(seed = 1): CitationLabelAllocator {+ let nextLabelNumber = seed++ return {+ reserve(count) {+ const blockStart = nextLabelNumber+ nextLabelNumber += count+ return blockStart+ }+ }+}+export function createCitationPattern(): RegExp {// A global RegExp carries lastIndex state, so each consumer needs a fresh one.// The id excludes brackets, parens and whitespace so a citation the model@@ -71,7 +87,7 @@ export function nextCitationLabelNumber(messages: UIMessage[]): number {for (const message of messages) {for (const part of message.parts ?? []) {if (- part.type !== 'tool-search' ||+ (part.type !== 'tool-search' && part.type !== 'tool-fetch') ||part.state !== 'output-available' ||!part.output) {@@ -105,29 +121,31 @@ export function extractCitationMaps(if (!message.parts) return citationMapsmessage.parts.forEach((part: any) => {- // Check for search tool output+ const isSearchOutput = part.type === 'tool-search'+ const isFetchOutput = part.type === 'tool-fetch'if (- part.type === 'tool-search' &&+ (isSearchOutput || isFetchOutput) &&part.state === 'output-available' &&- part.output &&- part.toolCallId+ part.output) {const searchResults = part.output as SearchResults// Prefer citationMap when present (older persisted messages still carry// it). Newer search outputs omit the redundant citationMap, so derive it// from results by index (citation N -> results[N-1]).- let citationMap = searchResults.citationMap- if (!citationMap && Array.isArray(searchResults.results)) {- citationMap = {}- searchResults.results.forEach((result, index) => {- citationMap![index + 1] = result // Citation numbers start at 1- })- }+ if (isSearchOutput && part.toolCallId) {+ let citationMap = searchResults.citationMap+ if (!citationMap && Array.isArray(searchResults.results)) {+ citationMap = {}+ searchResults.results.forEach((result, index) => {+ citationMap![index + 1] = result // Citation numbers start at 1+ })+ }- if (citationMap && Object.keys(citationMap).length > 0) {- // Store citation map with toolCallId as key- citationMaps[part.toolCallId] = citationMap+ if (citationMap && Object.keys(citationMap).length > 0) {+ // Store citation map with toolCallId as key+ citationMaps[part.toolCallId] = citationMap+ }}for (const result of searchResults.results ?? []) {