@livekit/agents 1.0.34 → 1.0.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs.map +1 -1
- package/dist/inference/api_protos.d.cts +4 -4
- package/dist/inference/api_protos.d.ts +4 -4
- package/dist/inference/llm.cjs +30 -3
- package/dist/inference/llm.cjs.map +1 -1
- package/dist/inference/llm.d.cts +3 -1
- package/dist/inference/llm.d.ts +3 -1
- package/dist/inference/llm.d.ts.map +1 -1
- package/dist/inference/llm.js +30 -3
- package/dist/inference/llm.js.map +1 -1
- package/dist/ipc/inference_proc_executor.cjs.map +1 -1
- package/dist/ipc/job_proc_executor.cjs.map +1 -1
- package/dist/ipc/job_proc_lazy_main.cjs +1 -1
- package/dist/ipc/job_proc_lazy_main.cjs.map +1 -1
- package/dist/ipc/job_proc_lazy_main.js +1 -1
- package/dist/ipc/job_proc_lazy_main.js.map +1 -1
- package/dist/llm/chat_context.cjs +20 -2
- package/dist/llm/chat_context.cjs.map +1 -1
- package/dist/llm/chat_context.d.cts +9 -0
- package/dist/llm/chat_context.d.ts +9 -0
- package/dist/llm/chat_context.d.ts.map +1 -1
- package/dist/llm/chat_context.js +20 -2
- package/dist/llm/chat_context.js.map +1 -1
- package/dist/llm/llm.cjs.map +1 -1
- package/dist/llm/llm.d.cts +1 -0
- package/dist/llm/llm.d.ts +1 -0
- package/dist/llm/llm.d.ts.map +1 -1
- package/dist/llm/llm.js.map +1 -1
- package/dist/llm/provider_format/openai.cjs +43 -20
- package/dist/llm/provider_format/openai.cjs.map +1 -1
- package/dist/llm/provider_format/openai.d.ts.map +1 -1
- package/dist/llm/provider_format/openai.js +43 -20
- package/dist/llm/provider_format/openai.js.map +1 -1
- package/dist/llm/provider_format/openai.test.cjs +35 -0
- package/dist/llm/provider_format/openai.test.cjs.map +1 -1
- package/dist/llm/provider_format/openai.test.js +35 -0
- package/dist/llm/provider_format/openai.test.js.map +1 -1
- package/dist/llm/provider_format/utils.cjs +1 -1
- package/dist/llm/provider_format/utils.cjs.map +1 -1
- package/dist/llm/provider_format/utils.d.ts.map +1 -1
- package/dist/llm/provider_format/utils.js +1 -1
- package/dist/llm/provider_format/utils.js.map +1 -1
- package/dist/voice/agent_activity.cjs +19 -19
- package/dist/voice/agent_activity.cjs.map +1 -1
- package/dist/voice/agent_activity.d.ts.map +1 -1
- package/dist/voice/agent_activity.js +19 -19
- package/dist/voice/agent_activity.js.map +1 -1
- package/dist/voice/agent_session.cjs +64 -25
- package/dist/voice/agent_session.cjs.map +1 -1
- package/dist/voice/agent_session.d.cts +25 -1
- package/dist/voice/agent_session.d.ts +25 -1
- package/dist/voice/agent_session.d.ts.map +1 -1
- package/dist/voice/agent_session.js +64 -25
- package/dist/voice/agent_session.js.map +1 -1
- package/dist/voice/background_audio.cjs.map +1 -1
- package/dist/voice/generation.cjs +2 -1
- package/dist/voice/generation.cjs.map +1 -1
- package/dist/voice/generation.d.ts.map +1 -1
- package/dist/voice/generation.js +2 -1
- package/dist/voice/generation.js.map +1 -1
- package/dist/voice/index.cjs +14 -1
- package/dist/voice/index.cjs.map +1 -1
- package/dist/voice/index.d.cts +1 -0
- package/dist/voice/index.d.ts +1 -0
- package/dist/voice/index.d.ts.map +1 -1
- package/dist/voice/index.js +3 -1
- package/dist/voice/index.js.map +1 -1
- package/dist/voice/room_io/room_io.cjs +1 -0
- package/dist/voice/room_io/room_io.cjs.map +1 -1
- package/dist/voice/room_io/room_io.d.ts.map +1 -1
- package/dist/voice/room_io/room_io.js +1 -0
- package/dist/voice/room_io/room_io.js.map +1 -1
- package/dist/voice/speech_handle.cjs +12 -3
- package/dist/voice/speech_handle.cjs.map +1 -1
- package/dist/voice/speech_handle.d.cts +12 -2
- package/dist/voice/speech_handle.d.ts +12 -2
- package/dist/voice/speech_handle.d.ts.map +1 -1
- package/dist/voice/speech_handle.js +10 -2
- package/dist/voice/speech_handle.js.map +1 -1
- package/dist/voice/testing/index.cjs +52 -0
- package/dist/voice/testing/index.cjs.map +1 -0
- package/dist/voice/testing/index.d.cts +20 -0
- package/dist/voice/testing/index.d.ts +20 -0
- package/dist/voice/testing/index.d.ts.map +1 -0
- package/dist/voice/testing/index.js +31 -0
- package/dist/voice/testing/index.js.map +1 -0
- package/dist/voice/testing/run_result.cjs +477 -0
- package/dist/voice/testing/run_result.cjs.map +1 -0
- package/dist/voice/testing/run_result.d.cts +226 -0
- package/dist/voice/testing/run_result.d.ts +226 -0
- package/dist/voice/testing/run_result.d.ts.map +1 -0
- package/dist/voice/testing/run_result.js +451 -0
- package/dist/voice/testing/run_result.js.map +1 -0
- package/dist/voice/testing/types.cjs +46 -0
- package/dist/voice/testing/types.cjs.map +1 -0
- package/dist/voice/testing/types.d.cts +83 -0
- package/dist/voice/testing/types.d.ts +83 -0
- package/dist/voice/testing/types.d.ts.map +1 -0
- package/dist/voice/testing/types.js +19 -0
- package/dist/voice/testing/types.js.map +1 -0
- package/package.json +3 -3
- package/src/inference/llm.ts +42 -3
- package/src/ipc/job_proc_lazy_main.ts +1 -1
- package/src/llm/chat_context.ts +32 -2
- package/src/llm/llm.ts +1 -0
- package/src/llm/provider_format/openai.test.ts +40 -0
- package/src/llm/provider_format/openai.ts +46 -19
- package/src/llm/provider_format/utils.ts +5 -1
- package/src/voice/agent_activity.ts +24 -22
- package/src/voice/agent_session.ts +73 -28
- package/src/voice/generation.ts +1 -0
- package/src/voice/index.ts +1 -0
- package/src/voice/room_io/room_io.ts +1 -0
- package/src/voice/speech_handle.ts +24 -4
- package/src/voice/testing/index.ts +49 -0
- package/src/voice/testing/run_result.ts +576 -0
- package/src/voice/testing/types.ts +118 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/llm/chat_context.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { AudioFrame, VideoFrame } from '@livekit/rtc-node';\nimport { createImmutableArray, shortuuid } from '../utils.js';\nimport { type ProviderFormat, toChatCtx } from './provider_format/index.js';\nimport type { JSONObject, JSONValue, ToolContext } from './tool_context.js';\n\nexport type ChatRole = 'developer' | 'system' | 'user' | 'assistant';\nexport interface ImageContent {\n id: string;\n\n type: 'image_content';\n\n /**\n * Either a string URL or a VideoFrame object.\n */\n image: string | VideoFrame;\n\n inferenceDetail: 'auto' | 'high' | 'low';\n\n inferenceWidth?: number;\n\n inferenceHeight?: number;\n\n mimeType?: string;\n\n _cache: Record<any, any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n}\n\nexport interface AudioContent {\n type: 'audio_content';\n\n frame: AudioFrame[];\n\n transcript?: string;\n}\n\nexport type ChatContent = ImageContent | AudioContent | string;\n\nexport function createImageContent(params: {\n image: string | VideoFrame;\n id?: string;\n inferenceDetail?: 'auto' | 'high' | 'low';\n inferenceWidth?: number;\n inferenceHeight?: number;\n mimeType?: string;\n}): ImageContent {\n const {\n image,\n id = shortuuid('img_'),\n inferenceDetail = 'auto',\n inferenceWidth,\n inferenceHeight,\n mimeType,\n } = params;\n\n return {\n id,\n type: 'image_content',\n image,\n inferenceDetail,\n inferenceWidth,\n inferenceHeight,\n mimeType,\n _cache: {},\n };\n}\n\nexport function createAudioContent(params: {\n frame: AudioFrame[];\n transcript?: string;\n}): AudioContent {\n const { frame, transcript } = params;\n\n return {\n type: 'audio_content',\n frame,\n transcript,\n };\n}\n\nexport class ChatMessage {\n readonly id: string;\n\n readonly type = 'message' as const;\n\n readonly role: ChatRole;\n\n content: ChatContent[];\n\n interrupted: boolean;\n\n hash?: Uint8Array;\n\n createdAt: number;\n\n constructor(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n }) {\n const {\n role,\n content,\n id = shortuuid('item_'),\n interrupted = false,\n createdAt = Date.now(),\n } = params;\n this.id = id;\n this.role = role;\n this.content = Array.isArray(content) ? content : [content];\n this.interrupted = interrupted;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n }) {\n return new ChatMessage(params);\n }\n\n /**\n * Returns a single string with all text parts of the message joined by new\n * lines. If no string content is present, returns `null`.\n */\n get textContent(): string | undefined {\n const parts = this.content.filter((c): c is string => typeof c === 'string');\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n\n toJSONContent(): JSONValue[] {\n return this.content.map((c) => {\n if (typeof c === 'string') {\n return c as JSONValue;\n } else if (c.type === 'image_content') {\n return {\n id: c.id,\n type: c.type,\n image: c.image,\n inferenceDetail: c.inferenceDetail,\n inferenceWidth: c.inferenceWidth,\n inferenceHeight: c.inferenceHeight,\n mimeType: c.mimeType,\n } as JSONObject;\n } else {\n return {\n type: c.type,\n transcript: c.transcript,\n } as JSONObject;\n }\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n role: this.role,\n content: this.toJSONContent(),\n interrupted: this.interrupted,\n };\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class FunctionCall {\n readonly id: string;\n\n readonly type = 'function_call' as const;\n\n callId: string;\n\n args: string;\n\n name: string;\n\n createdAt: number;\n\n /**\n * Opaque signature for Gemini thinking mode.\n * When using Gemini 3+ models with thinking enabled, this signature must be\n * preserved and returned with function responses to maintain thought context.\n */\n thoughtSignature?: string;\n\n constructor(params: {\n callId: string;\n name: string;\n args: string;\n id?: string;\n createdAt?: number;\n thoughtSignature?: string;\n }) {\n const {\n callId,\n name,\n args,\n id = shortuuid('item_'),\n createdAt = Date.now(),\n thoughtSignature,\n } = params;\n this.id = id;\n this.callId = callId;\n this.args = args;\n this.name = name;\n this.createdAt = createdAt;\n this.thoughtSignature = thoughtSignature;\n }\n\n static create(params: {\n callId: string;\n name: string;\n args: string;\n id?: string;\n createdAt?: number;\n thoughtSignature?: string;\n }) {\n return new FunctionCall(params);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n callId: this.callId,\n name: this.name,\n args: this.args,\n };\n\n if (this.thoughtSignature) {\n result.thoughtSignature = this.thoughtSignature;\n }\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class FunctionCallOutput {\n readonly id: string;\n\n readonly type = 'function_call_output' as const;\n\n name = '';\n\n callId: string;\n\n output: string;\n\n isError: boolean;\n\n createdAt: number;\n\n constructor(params: {\n callId: string;\n output: string;\n isError: boolean;\n id?: string;\n createdAt?: number;\n name?: string;\n }) {\n const {\n callId,\n output,\n isError,\n id = shortuuid('item_'),\n createdAt = Date.now(),\n name = '',\n } = params;\n this.id = id;\n this.callId = callId;\n this.output = output;\n this.isError = isError;\n this.name = name;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n callId: string;\n output: string;\n isError: boolean;\n id?: string;\n createdAt?: number;\n name?: string;\n }) {\n return new FunctionCallOutput(params);\n }\n\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n name: this.name,\n callId: this.callId,\n output: this.output,\n isError: this.isError,\n };\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class AgentHandoffItem {\n readonly id: string;\n\n readonly type = 'agent_handoff' as const;\n\n oldAgentId: string | undefined;\n\n newAgentId: string;\n\n createdAt: number;\n\n constructor(params: {\n oldAgentId?: string;\n newAgentId: string;\n id?: string;\n createdAt?: number;\n }) {\n const { oldAgentId, newAgentId, id = shortuuid('item_'), createdAt = Date.now() } = params;\n this.id = id;\n this.oldAgentId = oldAgentId;\n this.newAgentId = newAgentId;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n oldAgentId?: string;\n newAgentId: string;\n id?: string;\n createdAt?: number;\n }) {\n return new AgentHandoffItem(params);\n }\n\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n newAgentId: this.newAgentId,\n };\n\n if (this.oldAgentId !== undefined) {\n result.oldAgentId = this.oldAgentId;\n }\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport type ChatItem = ChatMessage | FunctionCall | FunctionCallOutput | AgentHandoffItem;\n\nexport class ChatContext {\n protected _items: ChatItem[];\n\n constructor(items?: ChatItem[]) {\n this._items = items ? items : [];\n }\n\n static empty(): ChatContext {\n return new ChatContext([]);\n }\n\n get items(): ChatItem[] {\n return this._items;\n }\n\n set items(items: ChatItem[]) {\n this._items = items;\n }\n\n /**\n * Add a new message to the context and return it.\n */\n addMessage(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n }): ChatMessage {\n const msg = new ChatMessage(params);\n if (params.createdAt !== undefined) {\n const idx = this.findInsertionIndex(params.createdAt);\n this._items.splice(idx, 0, msg);\n } else {\n this._items.push(msg);\n }\n return msg;\n }\n\n /**\n * Insert a single item or multiple items based on their `createdAt` field so\n * that the array keeps its chronological order.\n */\n insert(item: ChatItem | ChatItem[]): void {\n const arr = Array.isArray(item) ? item : [item];\n for (const it of arr) {\n const idx = this.findInsertionIndex(it.createdAt);\n this._items.splice(idx, 0, it);\n }\n }\n\n getById(itemId: string): ChatItem | undefined {\n return this._items.find((i) => i.id === itemId);\n }\n\n indexById(itemId: string): number | undefined {\n const idx = this._items.findIndex((i) => i.id === itemId);\n return idx !== -1 ? idx : undefined;\n }\n\n copy(\n options: {\n excludeFunctionCall?: boolean;\n excludeInstructions?: boolean;\n excludeEmptyMessage?: boolean;\n toolCtx?: ToolContext<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n } = {},\n ): ChatContext {\n const {\n excludeFunctionCall = false,\n excludeInstructions = false,\n excludeEmptyMessage = false,\n toolCtx,\n } = options;\n const items: ChatItem[] = [];\n\n const isToolCallOrOutput = (item: ChatItem): item is FunctionCall | FunctionCallOutput =>\n ['function_call', 'function_call_output'].includes(item.type);\n const isChatMessage = (item: ChatItem): item is ChatMessage => item.type === 'message';\n\n for (const item of this._items) {\n if (excludeFunctionCall && isToolCallOrOutput(item)) {\n continue;\n }\n\n if (\n excludeInstructions &&\n isChatMessage(item) &&\n ['system', 'developer'].includes(item.role)\n ) {\n continue;\n }\n\n if (excludeEmptyMessage && isChatMessage(item) && item.content.length === 0) {\n continue;\n }\n\n if (toolCtx !== undefined && isToolCallOrOutput(item) && toolCtx[item.name] === undefined) {\n continue;\n }\n\n items.push(item);\n }\n\n return new ChatContext(items);\n }\n\n truncate(maxItems: number): ChatContext {\n if (maxItems <= 0) return this;\n\n const instructions = this._items.find((i) => i.type === 'message' && i.role === 'system') as\n | ChatMessage\n | undefined;\n\n let newItems = this._items.slice(-maxItems);\n\n // Ensure the first item is not a function-call artefact.\n while (\n newItems.length > 0 &&\n ['function_call', 'function_call_output'].includes(newItems[0]!.type)\n ) {\n newItems.shift();\n }\n\n if (instructions) {\n // At this point `instructions` is defined, so it is safe to pass to `includes`.\n if (!newItems.includes(instructions)) {\n newItems = [instructions, ...newItems];\n }\n }\n\n // replace the items in place to keep the reference\n this._items.splice(0, this._items.length, ...newItems);\n return this;\n }\n\n toJSON(\n options: {\n excludeImage?: boolean;\n excludeAudio?: boolean;\n excludeTimestamp?: boolean;\n excludeFunctionCall?: boolean;\n } = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): JSONObject {\n const {\n excludeImage = true,\n excludeAudio = true,\n excludeTimestamp = true,\n excludeFunctionCall = false,\n } = options;\n\n const items: ChatItem[] = [];\n\n for (const item of this._items) {\n let processedItem = item;\n\n if (excludeFunctionCall && ['function_call', 'function_call_output'].includes(item.type)) {\n continue;\n }\n\n if (item.type === 'message') {\n processedItem = ChatMessage.create({\n role: item.role,\n content: item.content,\n id: item.id,\n interrupted: item.interrupted,\n createdAt: item.createdAt,\n });\n\n // Filter content based on options\n if (excludeImage) {\n processedItem.content = processedItem.content.filter((c) => {\n return !(typeof c === 'object' && c.type === 'image_content');\n });\n }\n\n if (excludeAudio) {\n processedItem.content = processedItem.content.filter((c) => {\n return !(typeof c === 'object' && c.type === 'audio_content');\n });\n }\n }\n\n items.push(processedItem);\n }\n\n return {\n items: items.map((item) => item.toJSON(excludeTimestamp)),\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async toProviderFormat(format: ProviderFormat, injectDummyUserMessage: boolean = true) {\n return await toChatCtx(format, this, injectDummyUserMessage);\n }\n\n /**\n * Internal helper used by `truncate` & `addMessage` to find the correct\n * insertion index for a timestamp so the list remains sorted.\n */\n private findInsertionIndex(createdAt: number): number {\n for (let i = this._items.length - 1; i >= 0; i -= 1) {\n const item = this._items[i];\n if (item!.createdAt <= createdAt) {\n return i + 1;\n }\n }\n return 0;\n }\n\n /**\n * Return true if `other` has the same sequence of items with matching\n * essential fields (IDs, types, and payload) as this context.\n *\n * Comparison rules:\n * - Messages: compares the full `content` list, `role` and `interrupted`.\n * - Function calls: compares `name`, `callId`, and `args`.\n * - Function call outputs: compares `name`, `callId`, `output`, and `isError`.\n *\n * Does not consider timestamps or other metadata.\n */\n isEquivalent(other: ChatContext): boolean {\n if (this === other) {\n return true;\n }\n\n if (this.items.length !== other.items.length) {\n return false;\n }\n\n for (let i = 0; i < this.items.length; i++) {\n const a = this.items[i]!;\n const b = other.items[i]!;\n\n if (a.id !== b.id || a.type !== b.type) {\n return false;\n }\n\n if (a.type === 'message' && b.type === 'message') {\n if (\n a.role !== b.role ||\n a.interrupted !== b.interrupted ||\n !this.compareContent(a.content, b.content)\n ) {\n return false;\n }\n } else if (a.type === 'function_call' && b.type === 'function_call') {\n if (\n a.name !== b.name ||\n a.callId !== b.callId ||\n a.args !== b.args ||\n a.thoughtSignature !== b.thoughtSignature\n ) {\n return false;\n }\n } else if (a.type === 'function_call_output' && b.type === 'function_call_output') {\n if (\n a.name !== b.name ||\n a.callId !== b.callId ||\n a.output !== b.output ||\n a.isError !== b.isError\n ) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Compare two content arrays for equality.\n */\n private compareContent(a: ChatContent[], b: ChatContent[]): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n for (let i = 0; i < a.length; i++) {\n const contentA = a[i]!;\n const contentB = b[i]!;\n\n if (typeof contentA === 'string' && typeof contentB === 'string') {\n if (contentA !== contentB) {\n return false;\n }\n continue;\n }\n\n if (typeof contentA !== typeof contentB) {\n return false;\n }\n\n if (typeof contentA === 'object' && typeof contentB === 'object') {\n if (contentA.type === 'image_content' && contentB.type === 'image_content') {\n if (\n contentA.id !== contentB.id ||\n contentA.image !== contentB.image ||\n contentA.inferenceDetail !== contentB.inferenceDetail ||\n contentA.inferenceWidth !== contentB.inferenceWidth ||\n contentA.inferenceHeight !== contentB.inferenceHeight ||\n contentA.mimeType !== contentB.mimeType\n ) {\n return false;\n }\n } else if (contentA.type === 'audio_content' && contentB.type === 'audio_content') {\n if (contentA.frame.length !== contentB.frame.length) {\n return false;\n }\n if (contentA.transcript !== contentB.transcript) {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Indicates whether the context is read-only\n */\n get readonly(): boolean {\n return false;\n }\n}\n\nexport class ReadonlyChatContext extends ChatContext {\n static readonly errorMsg =\n 'Please use .copy() and agent.update_chat_ctx() to modify the chat context.';\n\n constructor(items: ChatItem[]) {\n super(createImmutableArray(items, ReadonlyChatContext.errorMsg));\n }\n\n get items(): ChatItem[] {\n return this._items;\n }\n\n set items(items: ChatItem[]) {\n throw new Error(\n `Cannot set items on a read-only chat context. ${ReadonlyChatContext.errorMsg}`,\n );\n }\n\n get readonly(): boolean {\n return true;\n }\n}\n"],"mappings":"AAIA,SAAS,sBAAsB,iBAAiB;AAChD,SAA8B,iBAAiB;AAmCxC,SAAS,mBAAmB,QAOlB;AACf,QA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jE;AAAA,EAEA,IAAI,QAAoB;AACtB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,MAAM,OAAmB;AAC3B,UAAM,IAAI;AAAA,MACR,iDAAiD,oBAAoB,QAAQ;AAAA,IAC/E;AAAA,EACF;AAAA,EAEA,IAAI,WAAoB;AACtB,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/llm/chat_context.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { AudioFrame, VideoFrame } from '@livekit/rtc-node';\nimport { createImmutableArray, shortuuid } from '../utils.js';\nimport { type ProviderFormat, toChatCtx } from './provider_format/index.js';\nimport type { JSONObject, JSONValue, ToolContext } from './tool_context.js';\n\nexport type ChatRole = 'developer' | 'system' | 'user' | 'assistant';\nexport interface ImageContent {\n id: string;\n\n type: 'image_content';\n\n /**\n * Either a string URL or a VideoFrame object.\n */\n image: string | VideoFrame;\n\n inferenceDetail: 'auto' | 'high' | 'low';\n\n inferenceWidth?: number;\n\n inferenceHeight?: number;\n\n mimeType?: string;\n\n _cache: Record<any, any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n}\n\nexport interface AudioContent {\n type: 'audio_content';\n\n frame: AudioFrame[];\n\n transcript?: string;\n}\n\nexport type ChatContent = ImageContent | AudioContent | string;\n\nexport function createImageContent(params: {\n image: string | VideoFrame;\n id?: string;\n inferenceDetail?: 'auto' | 'high' | 'low';\n inferenceWidth?: number;\n inferenceHeight?: number;\n mimeType?: string;\n}): ImageContent {\n const {\n image,\n id = shortuuid('img_'),\n inferenceDetail = 'auto',\n inferenceWidth,\n inferenceHeight,\n mimeType,\n } = params;\n\n return {\n id,\n type: 'image_content',\n image,\n inferenceDetail,\n inferenceWidth,\n inferenceHeight,\n mimeType,\n _cache: {},\n };\n}\n\nexport function createAudioContent(params: {\n frame: AudioFrame[];\n transcript?: string;\n}): AudioContent {\n const { frame, transcript } = params;\n\n return {\n type: 'audio_content',\n frame,\n transcript,\n };\n}\n\nexport class ChatMessage {\n readonly id: string;\n\n readonly type = 'message' as const;\n\n readonly role: ChatRole;\n\n content: ChatContent[];\n\n interrupted: boolean;\n\n hash?: Uint8Array;\n\n createdAt: number;\n\n constructor(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n }) {\n const {\n role,\n content,\n id = shortuuid('item_'),\n interrupted = false,\n createdAt = Date.now(),\n } = params;\n this.id = id;\n this.role = role;\n this.content = Array.isArray(content) ? content : [content];\n this.interrupted = interrupted;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n }) {\n return new ChatMessage(params);\n }\n\n /**\n * Returns a single string with all text parts of the message joined by new\n * lines. If no string content is present, returns `null`.\n */\n get textContent(): string | undefined {\n const parts = this.content.filter((c): c is string => typeof c === 'string');\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n\n toJSONContent(): JSONValue[] {\n return this.content.map((c) => {\n if (typeof c === 'string') {\n return c as JSONValue;\n } else if (c.type === 'image_content') {\n return {\n id: c.id,\n type: c.type,\n image: c.image,\n inferenceDetail: c.inferenceDetail,\n inferenceWidth: c.inferenceWidth,\n inferenceHeight: c.inferenceHeight,\n mimeType: c.mimeType,\n } as JSONObject;\n } else {\n return {\n type: c.type,\n transcript: c.transcript,\n } as JSONObject;\n }\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n role: this.role,\n content: this.toJSONContent(),\n interrupted: this.interrupted,\n };\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class FunctionCall {\n readonly id: string;\n\n readonly type = 'function_call' as const;\n\n callId: string;\n\n args: string;\n\n name: string;\n\n createdAt: number;\n\n extra: Record<string, unknown>;\n /**\n * Optional grouping identifier for parallel tool calls.\n */\n groupId?: string;\n\n /**\n * Opaque signature for Gemini thinking mode.\n * When using Gemini 3+ models with thinking enabled, this signature must be\n * preserved and returned with function responses to maintain thought context.\n */\n thoughtSignature?: string;\n\n constructor(params: {\n callId: string;\n name: string;\n args: string;\n id?: string;\n createdAt?: number;\n extra?: Record<string, unknown>;\n groupId?: string;\n thoughtSignature?: string;\n }) {\n const {\n callId,\n name,\n args,\n id = shortuuid('item_'),\n createdAt = Date.now(),\n extra = {},\n groupId,\n thoughtSignature,\n } = params;\n this.id = id;\n this.callId = callId;\n this.args = args;\n this.name = name;\n this.createdAt = createdAt;\n this.extra = { ...extra };\n this.groupId = groupId;\n this.thoughtSignature =\n thoughtSignature ??\n (typeof this.extra.google === 'object' && this.extra.google !== null\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.extra.google as any).thoughtSignature ||\n (this.extra.google as any).thought_signature\n : undefined);\n }\n\n static create(params: {\n callId: string;\n name: string;\n args: string;\n id?: string;\n createdAt?: number;\n extra?: Record<string, unknown>;\n groupId?: string;\n thoughtSignature?: string;\n }) {\n return new FunctionCall(params);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n callId: this.callId,\n name: this.name,\n args: this.args,\n };\n\n if (Object.keys(this.extra).length > 0) {\n result.extra = this.extra as JSONValue;\n }\n\n if (this.groupId) {\n result.groupId = this.groupId;\n }\n\n if (this.thoughtSignature) {\n result.thoughtSignature = this.thoughtSignature;\n }\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class FunctionCallOutput {\n readonly id: string;\n\n readonly type = 'function_call_output' as const;\n\n name = '';\n\n callId: string;\n\n output: string;\n\n isError: boolean;\n\n createdAt: number;\n\n constructor(params: {\n callId: string;\n output: string;\n isError: boolean;\n id?: string;\n createdAt?: number;\n name?: string;\n }) {\n const {\n callId,\n output,\n isError,\n id = shortuuid('item_'),\n createdAt = Date.now(),\n name = '',\n } = params;\n this.id = id;\n this.callId = callId;\n this.output = output;\n this.isError = isError;\n this.name = name;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n callId: string;\n output: string;\n isError: boolean;\n id?: string;\n createdAt?: number;\n name?: string;\n }) {\n return new FunctionCallOutput(params);\n }\n\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n name: this.name,\n callId: this.callId,\n output: this.output,\n isError: this.isError,\n };\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class AgentHandoffItem {\n readonly id: string;\n\n readonly type = 'agent_handoff' as const;\n\n oldAgentId: string | undefined;\n\n newAgentId: string;\n\n createdAt: number;\n\n constructor(params: {\n oldAgentId?: string;\n newAgentId: string;\n id?: string;\n createdAt?: number;\n }) {\n const { oldAgentId, newAgentId, id = shortuuid('item_'), createdAt = Date.now() } = params;\n this.id = id;\n this.oldAgentId = oldAgentId;\n this.newAgentId = newAgentId;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n oldAgentId?: string;\n newAgentId: string;\n id?: string;\n createdAt?: number;\n }) {\n return new AgentHandoffItem(params);\n }\n\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n newAgentId: this.newAgentId,\n };\n\n if (this.oldAgentId !== undefined) {\n result.oldAgentId = this.oldAgentId;\n }\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport type ChatItem = ChatMessage | FunctionCall | FunctionCallOutput | AgentHandoffItem;\n\nexport class ChatContext {\n protected _items: ChatItem[];\n\n constructor(items?: ChatItem[]) {\n this._items = items ? items : [];\n }\n\n static empty(): ChatContext {\n return new ChatContext([]);\n }\n\n get items(): ChatItem[] {\n return this._items;\n }\n\n set items(items: ChatItem[]) {\n this._items = items;\n }\n\n /**\n * Add a new message to the context and return it.\n */\n addMessage(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n }): ChatMessage {\n const msg = new ChatMessage(params);\n if (params.createdAt !== undefined) {\n const idx = this.findInsertionIndex(params.createdAt);\n this._items.splice(idx, 0, msg);\n } else {\n this._items.push(msg);\n }\n return msg;\n }\n\n /**\n * Insert a single item or multiple items based on their `createdAt` field so\n * that the array keeps its chronological order.\n */\n insert(item: ChatItem | ChatItem[]): void {\n const arr = Array.isArray(item) ? item : [item];\n for (const it of arr) {\n const idx = this.findInsertionIndex(it.createdAt);\n this._items.splice(idx, 0, it);\n }\n }\n\n getById(itemId: string): ChatItem | undefined {\n return this._items.find((i) => i.id === itemId);\n }\n\n indexById(itemId: string): number | undefined {\n const idx = this._items.findIndex((i) => i.id === itemId);\n return idx !== -1 ? idx : undefined;\n }\n\n copy(\n options: {\n excludeFunctionCall?: boolean;\n excludeInstructions?: boolean;\n excludeEmptyMessage?: boolean;\n toolCtx?: ToolContext<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n } = {},\n ): ChatContext {\n const {\n excludeFunctionCall = false,\n excludeInstructions = false,\n excludeEmptyMessage = false,\n toolCtx,\n } = options;\n const items: ChatItem[] = [];\n\n const isToolCallOrOutput = (item: ChatItem): item is FunctionCall | FunctionCallOutput =>\n ['function_call', 'function_call_output'].includes(item.type);\n const isChatMessage = (item: ChatItem): item is ChatMessage => item.type === 'message';\n\n for (const item of this._items) {\n if (excludeFunctionCall && isToolCallOrOutput(item)) {\n continue;\n }\n\n if (\n excludeInstructions &&\n isChatMessage(item) &&\n ['system', 'developer'].includes(item.role)\n ) {\n continue;\n }\n\n if (excludeEmptyMessage && isChatMessage(item) && item.content.length === 0) {\n continue;\n }\n\n if (toolCtx !== undefined && isToolCallOrOutput(item) && toolCtx[item.name] === undefined) {\n continue;\n }\n\n items.push(item);\n }\n\n return new ChatContext(items);\n }\n\n truncate(maxItems: number): ChatContext {\n if (maxItems <= 0) return this;\n\n const instructions = this._items.find((i) => i.type === 'message' && i.role === 'system') as\n | ChatMessage\n | undefined;\n\n let newItems = this._items.slice(-maxItems);\n\n // Ensure the first item is not a function-call artefact.\n while (\n newItems.length > 0 &&\n ['function_call', 'function_call_output'].includes(newItems[0]!.type)\n ) {\n newItems.shift();\n }\n\n if (instructions) {\n // At this point `instructions` is defined, so it is safe to pass to `includes`.\n if (!newItems.includes(instructions)) {\n newItems = [instructions, ...newItems];\n }\n }\n\n // replace the items in place to keep the reference\n this._items.splice(0, this._items.length, ...newItems);\n return this;\n }\n\n toJSON(\n options: {\n excludeImage?: boolean;\n excludeAudio?: boolean;\n excludeTimestamp?: boolean;\n excludeFunctionCall?: boolean;\n } = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): JSONObject {\n const {\n excludeImage = true,\n excludeAudio = true,\n excludeTimestamp = true,\n excludeFunctionCall = false,\n } = options;\n\n const items: ChatItem[] = [];\n\n for (const item of this._items) {\n let processedItem = item;\n\n if (excludeFunctionCall && ['function_call', 'function_call_output'].includes(item.type)) {\n continue;\n }\n\n if (item.type === 'message') {\n processedItem = ChatMessage.create({\n role: item.role,\n content: item.content,\n id: item.id,\n interrupted: item.interrupted,\n createdAt: item.createdAt,\n });\n\n // Filter content based on options\n if (excludeImage) {\n processedItem.content = processedItem.content.filter((c) => {\n return !(typeof c === 'object' && c.type === 'image_content');\n });\n }\n\n if (excludeAudio) {\n processedItem.content = processedItem.content.filter((c) => {\n return !(typeof c === 'object' && c.type === 'audio_content');\n });\n }\n }\n\n items.push(processedItem);\n }\n\n return {\n items: items.map((item) => item.toJSON(excludeTimestamp)),\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async toProviderFormat(format: ProviderFormat, injectDummyUserMessage: boolean = true) {\n return await toChatCtx(format, this, injectDummyUserMessage);\n }\n\n /**\n * Internal helper used by `truncate` & `addMessage` to find the correct\n * insertion index for a timestamp so the list remains sorted.\n */\n private findInsertionIndex(createdAt: number): number {\n for (let i = this._items.length - 1; i >= 0; i -= 1) {\n const item = this._items[i];\n if (item!.createdAt <= createdAt) {\n return i + 1;\n }\n }\n return 0;\n }\n\n /**\n * Return true if `other` has the same sequence of items with matching\n * essential fields (IDs, types, and payload) as this context.\n *\n * Comparison rules:\n * - Messages: compares the full `content` list, `role` and `interrupted`.\n * - Function calls: compares `name`, `callId`, and `args`.\n * - Function call outputs: compares `name`, `callId`, `output`, and `isError`.\n *\n * Does not consider timestamps or other metadata.\n */\n isEquivalent(other: ChatContext): boolean {\n if (this === other) {\n return true;\n }\n\n if (this.items.length !== other.items.length) {\n return false;\n }\n\n for (let i = 0; i < this.items.length; i++) {\n const a = this.items[i]!;\n const b = other.items[i]!;\n\n if (a.id !== b.id || a.type !== b.type) {\n return false;\n }\n\n if (a.type === 'message' && b.type === 'message') {\n if (\n a.role !== b.role ||\n a.interrupted !== b.interrupted ||\n !this.compareContent(a.content, b.content)\n ) {\n return false;\n }\n } else if (a.type === 'function_call' && b.type === 'function_call') {\n if (\n a.name !== b.name ||\n a.callId !== b.callId ||\n a.args !== b.args ||\n a.thoughtSignature !== b.thoughtSignature ||\n a.groupId !== b.groupId ||\n JSON.stringify(a.extra) !== JSON.stringify(b.extra)\n ) {\n return false;\n }\n } else if (a.type === 'function_call_output' && b.type === 'function_call_output') {\n if (\n a.name !== b.name ||\n a.callId !== b.callId ||\n a.output !== b.output ||\n a.isError !== b.isError\n ) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Compare two content arrays for equality.\n */\n private compareContent(a: ChatContent[], b: ChatContent[]): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n for (let i = 0; i < a.length; i++) {\n const contentA = a[i]!;\n const contentB = b[i]!;\n\n if (typeof contentA === 'string' && typeof contentB === 'string') {\n if (contentA !== contentB) {\n return false;\n }\n continue;\n }\n\n if (typeof contentA !== typeof contentB) {\n return false;\n }\n\n if (typeof contentA === 'object' && typeof contentB === 'object') {\n if (contentA.type === 'image_content' && contentB.type === 'image_content') {\n if (\n contentA.id !== contentB.id ||\n contentA.image !== contentB.image ||\n contentA.inferenceDetail !== contentB.inferenceDetail ||\n contentA.inferenceWidth !== contentB.inferenceWidth ||\n contentA.inferenceHeight !== contentB.inferenceHeight ||\n contentA.mimeType !== contentB.mimeType\n ) {\n return false;\n }\n } else if (contentA.type === 'audio_content' && contentB.type === 'audio_content') {\n if (contentA.frame.length !== contentB.frame.length) {\n return false;\n }\n if (contentA.transcript !== contentB.transcript) {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Indicates whether the context is read-only\n */\n get readonly(): boolean {\n return false;\n }\n}\n\nexport class ReadonlyChatContext extends ChatContext {\n static readonly errorMsg =\n 'Please use .copy() and agent.update_chat_ctx() to modify the chat context.';\n\n constructor(items: ChatItem[]) {\n super(createImmutableArray(items, ReadonlyChatContext.errorMsg));\n }\n\n get items(): ChatItem[] {\n return this._items;\n }\n\n set items(items: ChatItem[]) {\n throw new Error(\n `Cannot set items on a read-only chat context. ${ReadonlyChatContext.errorMsg}`,\n );\n }\n\n get readonly(): boolean {\n return true;\n }\n}\n"],"mappings":"AAIA,SAAS,sBAAsB,iBAAiB;AAChD,SAA8B,iBAAiB;AAmCxC,SAAS,mBAAmB,QAOlB;AACf,QAAM;AAAA,IACJ;AAAA,IACA,KAAK,UAAU,MAAM;AAAA,IACrB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ,CAAC;AAAA,EACX;AACF;AAEO,SAAS,mBAAmB,QAGlB;AACf,QAAM,EAAE,OAAO,WAAW,IAAI;AAE9B,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA;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AAM,4BAA4B,YAAY;AAAA,EACnD,OAAgB,WACd;AAAA,EAEF,YAAY,OAAmB;AAC7B,UAAM,qBAAqB,OAAO,oBAAoB,QAAQ,CAAC;AAAA,EACjE;AAAA,EAEA,IAAI,QAAoB;AACtB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,MAAM,OAAmB;AAC3B,UAAM,IAAI;AAAA,MACR,iDAAiD,oBAAoB,QAAQ;AAAA,IAC/E;AAAA,EACF;AAAA,EAEA,IAAI,WAAoB;AACtB,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/llm/llm.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/llm/llm.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { TypedEventEmitter as TypedEmitter } from '@livekit/typed-emitter';\nimport type { Span } from '@opentelemetry/api';\nimport { EventEmitter } from 'node:events';\nimport { APIConnectionError, APIError } from '../_exceptions.js';\nimport { log } from '../log.js';\nimport type { LLMMetrics } from '../metrics/base.js';\nimport { recordException, traceTypes, tracer } from '../telemetry/index.js';\nimport { type APIConnectOptions, intervalForRetry } from '../types.js';\nimport { AsyncIterableQueue, delay, startSoon, toError } from '../utils.js';\nimport { type ChatContext, type ChatRole, type FunctionCall } from './chat_context.js';\nimport type { ToolChoice, ToolContext } from './tool_context.js';\n\nexport interface ChoiceDelta {\n role: ChatRole;\n content?: string;\n toolCalls?: FunctionCall[];\n}\n\nexport interface CompletionUsage {\n completionTokens: number;\n promptTokens: number;\n promptCachedTokens: number;\n totalTokens: number;\n}\n\nexport interface ChatChunk {\n id: string;\n delta?: ChoiceDelta;\n usage?: CompletionUsage;\n}\n\nexport interface LLMError {\n type: 'llm_error';\n timestamp: number;\n label: string;\n error: Error;\n recoverable: boolean;\n}\n\nexport type LLMCallbacks = {\n ['metrics_collected']: (metrics: LLMMetrics) => void;\n ['error']: (error: LLMError) => void;\n};\n\nexport abstract class LLM extends (EventEmitter as new () => TypedEmitter<LLMCallbacks>) {\n constructor() {\n super();\n }\n\n abstract label(): string;\n\n /**\n * Get the model name/identifier for this LLM instance.\n *\n * @returns The model name if available, \"unknown\" otherwise.\n *\n * @remarks\n * Plugins should override this property to provide their model information.\n */\n get model(): string {\n return 'unknown';\n }\n\n /**\n * Returns a {@link LLMStream} that can be used to push text and receive LLM responses.\n */\n abstract chat({\n chatCtx,\n toolCtx,\n connOptions,\n parallelToolCalls,\n toolChoice,\n extraKwargs,\n }: {\n chatCtx: ChatContext;\n toolCtx?: ToolContext;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): LLMStream;\n\n /**\n * Pre-warm connection to the LLM service\n */\n prewarm(): void {\n // Default implementation - subclasses can override\n }\n\n async aclose(): Promise<void> {\n // Default implementation - subclasses can override\n }\n}\n\nexport abstract class LLMStream implements AsyncIterableIterator<ChatChunk> {\n protected output = new AsyncIterableQueue<ChatChunk>();\n protected queue = new AsyncIterableQueue<ChatChunk>();\n protected closed = false;\n protected abortController = new AbortController();\n protected _connOptions: APIConnectOptions;\n protected logger = log();\n\n #llm: LLM;\n #chatCtx: ChatContext;\n #toolCtx?: ToolContext;\n #llmRequestSpan?: Span;\n\n constructor(\n llm: LLM,\n {\n chatCtx,\n toolCtx,\n connOptions,\n }: {\n chatCtx: ChatContext;\n toolCtx?: ToolContext;\n connOptions: APIConnectOptions;\n },\n ) {\n this.#llm = llm;\n this.#chatCtx = chatCtx;\n this.#toolCtx = toolCtx;\n this._connOptions = connOptions;\n this.monitorMetrics();\n this.abortController.signal.addEventListener('abort', () => {\n // TODO (AJS-37) clean this up when we refactor with streams\n this.output.close();\n this.closed = true;\n });\n\n // this is a hack to immitate asyncio.create_task so that mainTask\n // is run **after** the constructor has finished. Otherwise we get\n // runtime error when trying to access class variables in the\n // `run` method.\n startSoon(() => this.mainTask().finally(() => this.queue.close()));\n }\n\n private _mainTaskImpl = async (span: Span) => {\n this.#llmRequestSpan = span;\n span.setAttribute(traceTypes.ATTR_GEN_AI_REQUEST_MODEL, this.#llm.model);\n\n for (let i = 0; i < this._connOptions.maxRetry + 1; i++) {\n try {\n return await tracer.startActiveSpan(\n async (attemptSpan) => {\n attemptSpan.setAttribute(traceTypes.ATTR_RETRY_COUNT, i);\n try {\n return await this.run();\n } catch (error) {\n recordException(attemptSpan, toError(error));\n throw error;\n }\n },\n { name: 'llm_request_run' },\n );\n } catch (error) {\n if (error instanceof APIError) {\n const retryInterval = intervalForRetry(this._connOptions, i);\n\n if (this._connOptions.maxRetry === 0 || !error.retryable) {\n this.emitError({ error, recoverable: false });\n throw error;\n } else if (i === this._connOptions.maxRetry) {\n this.emitError({ error, recoverable: false });\n throw new APIConnectionError({\n message: `failed to generate LLM completion after ${this._connOptions.maxRetry + 1} attempts`,\n options: { retryable: false },\n });\n } else {\n this.emitError({ error, recoverable: true });\n this.logger.warn(\n { llm: this.#llm.label(), attempt: i + 1, error },\n `failed to generate LLM completion, retrying in ${retryInterval}s`,\n );\n }\n\n if (retryInterval > 0) {\n await delay(retryInterval);\n }\n } else {\n this.emitError({ error: toError(error), recoverable: false });\n throw error;\n }\n }\n }\n };\n\n private mainTask = async () =>\n tracer.startActiveSpan(async (span) => this._mainTaskImpl(span), {\n name: 'llm_request',\n endOnExit: false,\n });\n\n private emitError({ error, recoverable }: { error: Error; recoverable: boolean }) {\n this.#llm.emit('error', {\n type: 'llm_error',\n timestamp: Date.now(),\n label: this.#llm.label(),\n error,\n recoverable,\n });\n }\n\n protected async monitorMetrics() {\n const startTime = process.hrtime.bigint();\n let ttft: bigint = BigInt(-1);\n let requestId = '';\n let usage: CompletionUsage | undefined;\n let completionStartTime: string | undefined;\n\n for await (const ev of this.queue) {\n if (this.abortController.signal.aborted) {\n break;\n }\n this.output.put(ev);\n requestId = ev.id;\n if (ttft === BigInt(-1)) {\n ttft = process.hrtime.bigint() - startTime;\n completionStartTime = new Date().toISOString();\n }\n if (ev.usage) {\n usage = ev.usage;\n }\n }\n this.output.close();\n\n const duration = process.hrtime.bigint() - startTime;\n const durationMs = Math.trunc(Number(duration / BigInt(1000000)));\n const metrics: LLMMetrics = {\n type: 'llm_metrics',\n timestamp: Date.now(),\n requestId,\n ttftMs: ttft === BigInt(-1) ? -1 : Math.trunc(Number(ttft / BigInt(1000000))),\n durationMs,\n cancelled: this.abortController.signal.aborted,\n label: this.#llm.label(),\n completionTokens: usage?.completionTokens || 0,\n promptTokens: usage?.promptTokens || 0,\n promptCachedTokens: usage?.promptCachedTokens || 0,\n totalTokens: usage?.totalTokens || 0,\n tokensPerSecond: (() => {\n if (durationMs <= 0) {\n return 0;\n }\n return (usage?.completionTokens || 0) / (durationMs / 1000);\n })(),\n };\n\n if (this.#llmRequestSpan) {\n this.#llmRequestSpan.setAttribute(traceTypes.ATTR_LLM_METRICS, JSON.stringify(metrics));\n\n this.#llmRequestSpan.setAttributes({\n [traceTypes.ATTR_GEN_AI_USAGE_INPUT_TOKENS]: metrics.promptTokens,\n [traceTypes.ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: metrics.completionTokens,\n });\n\n if (completionStartTime) {\n this.#llmRequestSpan.setAttribute(\n traceTypes.ATTR_LANGFUSE_COMPLETION_START_TIME,\n completionStartTime,\n );\n }\n\n // End the span now that metrics are collected\n this.#llmRequestSpan.end();\n }\n\n this.#llm.emit('metrics_collected', metrics);\n }\n\n protected abstract run(): Promise<void>;\n\n /** The function context of this stream. */\n get toolCtx(): ToolContext | undefined {\n return this.#toolCtx;\n }\n\n /** The initial chat context of this stream. */\n get chatCtx(): ChatContext {\n return this.#chatCtx;\n }\n\n /** The connection options for this stream. */\n get connOptions(): APIConnectOptions {\n return this._connOptions;\n }\n\n next(): Promise<IteratorResult<ChatChunk>> {\n return this.output.next();\n }\n\n close() {\n this.abortController.abort();\n }\n\n [Symbol.asyncIterator](): LLMStream {\n return this;\n }\n}\n"],"m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AACtB,YAAI,cAAc,GAAG;AACnB,iBAAO;AAAA,QACT;AACA,iBAAQ,+BAAO,qBAAoB,MAAM,aAAa;AAAA,MACxD,GAAG;AAAA,IACL;AAEA,QAAI,KAAK,iBAAiB;AACxB,WAAK,gBAAgB,aAAa,4BAAW,kBAAkB,KAAK,UAAU,OAAO,CAAC;AAEtF,WAAK,gBAAgB,cAAc;AAAA,QACjC,CAAC,4BAAW,8BAA8B,GAAG,QAAQ;AAAA,QACrD,CAAC,4BAAW,+BAA+B,GAAG,QAAQ;AAAA,MACxD,CAAC;AAED,UAAI,qBAAqB;AACvB,aAAK,gBAAgB;AAAA,UACnB,4BAAW;AAAA,UACX;AAAA,QACF;AAAA,MACF;AAGA,WAAK,gBAAgB,IAAI;AAAA,IAC3B;AAEA,SAAK,KAAK,KAAK,qBAAqB,OAAO;AAAA,EAC7C;AAAA;AAAA,EAKA,IAAI,UAAmC;AACrC,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,IAAI,UAAuB;AACzB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,IAAI,cAAiC;AACnC,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,OAA2C;AACzC,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA,EAEA,QAAQ;AACN,SAAK,gBAAgB,MAAM;AAAA,EAC7B;AAAA,EAEA,CAAC,OAAO,aAAa,IAAe;AAClC,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/llm/llm.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { TypedEventEmitter as TypedEmitter } from '@livekit/typed-emitter';\nimport type { Span } from '@opentelemetry/api';\nimport { EventEmitter } from 'node:events';\nimport { APIConnectionError, APIError } from '../_exceptions.js';\nimport { log } from '../log.js';\nimport type { LLMMetrics } from '../metrics/base.js';\nimport { recordException, traceTypes, tracer } from '../telemetry/index.js';\nimport { type APIConnectOptions, intervalForRetry } from '../types.js';\nimport { AsyncIterableQueue, delay, startSoon, toError } from '../utils.js';\nimport { type ChatContext, type ChatRole, type FunctionCall } from './chat_context.js';\nimport type { ToolChoice, ToolContext } from './tool_context.js';\n\nexport interface ChoiceDelta {\n role: ChatRole;\n content?: string;\n toolCalls?: FunctionCall[];\n extra?: Record<string, unknown>;\n}\n\nexport interface CompletionUsage {\n completionTokens: number;\n promptTokens: number;\n promptCachedTokens: number;\n totalTokens: number;\n}\n\nexport interface ChatChunk {\n id: string;\n delta?: ChoiceDelta;\n usage?: CompletionUsage;\n}\n\nexport interface LLMError {\n type: 'llm_error';\n timestamp: number;\n label: string;\n error: Error;\n recoverable: boolean;\n}\n\nexport type LLMCallbacks = {\n ['metrics_collected']: (metrics: LLMMetrics) => void;\n ['error']: (error: LLMError) => void;\n};\n\nexport abstract class LLM extends (EventEmitter as new () => TypedEmitter<LLMCallbacks>) {\n constructor() {\n super();\n }\n\n abstract label(): string;\n\n /**\n * Get the model name/identifier for this LLM instance.\n *\n * @returns The model name if available, \"unknown\" otherwise.\n *\n * @remarks\n * Plugins should override this property to provide their model information.\n */\n get model(): string {\n return 'unknown';\n }\n\n /**\n * Returns a {@link LLMStream} that can be used to push text and receive LLM responses.\n */\n abstract chat({\n chatCtx,\n toolCtx,\n connOptions,\n parallelToolCalls,\n toolChoice,\n extraKwargs,\n }: {\n chatCtx: ChatContext;\n toolCtx?: ToolContext;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): LLMStream;\n\n /**\n * Pre-warm connection to the LLM service\n */\n prewarm(): void {\n // Default implementation - subclasses can override\n }\n\n async aclose(): Promise<void> {\n // Default implementation - subclasses can override\n }\n}\n\nexport abstract class LLMStream implements AsyncIterableIterator<ChatChunk> {\n protected output = new AsyncIterableQueue<ChatChunk>();\n protected queue = new AsyncIterableQueue<ChatChunk>();\n protected closed = false;\n protected abortController = new AbortController();\n protected _connOptions: APIConnectOptions;\n protected logger = log();\n\n #llm: LLM;\n #chatCtx: ChatContext;\n #toolCtx?: ToolContext;\n #llmRequestSpan?: Span;\n\n constructor(\n llm: LLM,\n {\n chatCtx,\n toolCtx,\n connOptions,\n }: {\n chatCtx: ChatContext;\n toolCtx?: ToolContext;\n connOptions: APIConnectOptions;\n },\n ) {\n this.#llm = llm;\n this.#chatCtx = chatCtx;\n this.#toolCtx = toolCtx;\n this._connOptions = connOptions;\n this.monitorMetrics();\n this.abortController.signal.addEventListener('abort', () => {\n // TODO (AJS-37) clean this up when we refactor with streams\n this.output.close();\n this.closed = true;\n });\n\n // this is a hack to immitate asyncio.create_task so that mainTask\n // is run **after** the constructor has finished. Otherwise we get\n // runtime error when trying to access class variables in the\n // `run` method.\n startSoon(() => this.mainTask().finally(() => this.queue.close()));\n }\n\n private _mainTaskImpl = async (span: Span) => {\n this.#llmRequestSpan = span;\n span.setAttribute(traceTypes.ATTR_GEN_AI_REQUEST_MODEL, this.#llm.model);\n\n for (let i = 0; i < this._connOptions.maxRetry + 1; i++) {\n try {\n return await tracer.startActiveSpan(\n async (attemptSpan) => {\n attemptSpan.setAttribute(traceTypes.ATTR_RETRY_COUNT, i);\n try {\n return await this.run();\n } catch (error) {\n recordException(attemptSpan, toError(error));\n throw error;\n }\n },\n { name: 'llm_request_run' },\n );\n } catch (error) {\n if (error instanceof APIError) {\n const retryInterval = intervalForRetry(this._connOptions, i);\n\n if (this._connOptions.maxRetry === 0 || !error.retryable) {\n this.emitError({ error, recoverable: false });\n throw error;\n } else if (i === this._connOptions.maxRetry) {\n this.emitError({ error, recoverable: false });\n throw new APIConnectionError({\n message: `failed to generate LLM completion after ${this._connOptions.maxRetry + 1} attempts`,\n options: { retryable: false },\n });\n } else {\n this.emitError({ error, recoverable: true });\n this.logger.warn(\n { llm: this.#llm.label(), attempt: i + 1, error },\n `failed to generate LLM completion, retrying in ${retryInterval}s`,\n );\n }\n\n if (retryInterval > 0) {\n await delay(retryInterval);\n }\n } else {\n this.emitError({ error: toError(error), recoverable: false });\n throw error;\n }\n }\n }\n };\n\n private mainTask = async () =>\n tracer.startActiveSpan(async (span) => this._mainTaskImpl(span), {\n name: 'llm_request',\n endOnExit: false,\n });\n\n private emitError({ error, recoverable }: { error: Error; recoverable: boolean }) {\n this.#llm.emit('error', {\n type: 'llm_error',\n timestamp: Date.now(),\n label: this.#llm.label(),\n error,\n recoverable,\n });\n }\n\n protected async monitorMetrics() {\n const startTime = process.hrtime.bigint();\n let ttft: bigint = BigInt(-1);\n let requestId = '';\n let usage: CompletionUsage | undefined;\n let completionStartTime: string | undefined;\n\n for await (const ev of this.queue) {\n if (this.abortController.signal.aborted) {\n break;\n }\n this.output.put(ev);\n requestId = ev.id;\n if (ttft === BigInt(-1)) {\n ttft = process.hrtime.bigint() - startTime;\n completionStartTime = new Date().toISOString();\n }\n if (ev.usage) {\n usage = ev.usage;\n }\n }\n this.output.close();\n\n const duration = process.hrtime.bigint() - startTime;\n const durationMs = Math.trunc(Number(duration / BigInt(1000000)));\n const metrics: LLMMetrics = {\n type: 'llm_metrics',\n timestamp: Date.now(),\n requestId,\n ttftMs: ttft === BigInt(-1) ? -1 : Math.trunc(Number(ttft / BigInt(1000000))),\n durationMs,\n cancelled: this.abortController.signal.aborted,\n label: this.#llm.label(),\n completionTokens: usage?.completionTokens || 0,\n promptTokens: usage?.promptTokens || 0,\n promptCachedTokens: usage?.promptCachedTokens || 0,\n totalTokens: usage?.totalTokens || 0,\n tokensPerSecond: (() => {\n if (durationMs <= 0) {\n return 0;\n }\n return (usage?.completionTokens || 0) / (durationMs / 1000);\n })(),\n };\n\n if (this.#llmRequestSpan) {\n this.#llmRequestSpan.setAttribute(traceTypes.ATTR_LLM_METRICS, JSON.stringify(metrics));\n\n this.#llmRequestSpan.setAttributes({\n [traceTypes.ATTR_GEN_AI_USAGE_INPUT_TOKENS]: metrics.promptTokens,\n [traceTypes.ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: metrics.completionTokens,\n });\n\n if (completionStartTime) {\n this.#llmRequestSpan.setAttribute(\n traceTypes.ATTR_LANGFUSE_COMPLETION_START_TIME,\n completionStartTime,\n );\n }\n\n // End the span now that metrics are collected\n this.#llmRequestSpan.end();\n }\n\n this.#llm.emit('metrics_collected', metrics);\n }\n\n protected abstract run(): Promise<void>;\n\n /** The function context of this stream. */\n get toolCtx(): ToolContext | undefined {\n return this.#toolCtx;\n }\n\n /** The initial chat context of this stream. */\n get chatCtx(): ChatContext {\n return this.#chatCtx;\n }\n\n /** The connection options for this stream. */\n get connOptions(): APIConnectOptions {\n return this._connOptions;\n }\n\n next(): Promise<IteratorResult<ChatChunk>> {\n return this.output.next();\n }\n\n close() {\n this.abortController.abort();\n }\n\n [Symbol.asyncIterator](): LLMStream {\n return this;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,yBAA6B;AAC7B,wBAA6C;AAC7C,iBAAoB;AAEpB,uBAAoD;AACpD,mBAAyD;AACzD,mBAA8D;AAC9D,0BAAmE;AAoC5D,MAAe,YAAa,gCAAsD;AAAA,EACvF,cAAc;AACZ,UAAM;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,IAAI,QAAgB;AAClB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAwBA,UAAgB;AAAA,EAEhB;AAAA,EAEA,MAAM,SAAwB;AAAA,EAE9B;AACF;AAEO,MAAe,UAAsD;AAAA,EAChE,SAAS,IAAI,gCAA8B;AAAA,EAC3C,QAAQ,IAAI,gCAA8B;AAAA,EAC1C,SAAS;AAAA,EACT,kBAAkB,IAAI,gBAAgB;AAAA,EACtC;AAAA,EACA,aAAS,gBAAI;AAAA,EAEvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YACE,KACA;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,E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d;AAAA,EAEA,OAA2C;AACzC,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA,EAEA,QAAQ;AACN,SAAK,gBAAgB,MAAM;AAAA,EAC7B;AAAA,EAEA,CAAC,OAAO,aAAa,IAAe;AAClC,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/llm/llm.d.cts
CHANGED
package/dist/llm/llm.d.ts
CHANGED
package/dist/llm/llm.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llm.d.ts","sourceRoot":"","sources":["../../src/llm/llm.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,IAAI,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAKhF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,EAAE,KAAK,iBAAiB,EAAoB,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAA6B,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,QAAQ,EAAE,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACvF,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEjE,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,QAAQ,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,YAAY,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"llm.d.ts","sourceRoot":"","sources":["../../src/llm/llm.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,IAAI,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAKhF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,EAAE,KAAK,iBAAiB,EAAoB,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAA6B,MAAM,aAAa,CAAC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AAc,CAAC,SAAS,CAAC,CAAC;IAI1C,KAAK;IAIL,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,SAAS;CAGpC"}
|
package/dist/llm/llm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/llm/llm.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { TypedEventEmitter as TypedEmitter } from '@livekit/typed-emitter';\nimport type { Span } from '@opentelemetry/api';\nimport { EventEmitter } from 'node:events';\nimport { APIConnectionError, APIError } from '../_exceptions.js';\nimport { log } from '../log.js';\nimport type { LLMMetrics } from '../metrics/base.js';\nimport { recordException, traceTypes, tracer } from '../telemetry/index.js';\nimport { type APIConnectOptions, intervalForRetry } from '../types.js';\nimport { AsyncIterableQueue, delay, startSoon, toError } from '../utils.js';\nimport { type ChatContext, type ChatRole, type FunctionCall } from './chat_context.js';\nimport type { ToolChoice, ToolContext } from './tool_context.js';\n\nexport interface ChoiceDelta {\n role: ChatRole;\n content?: string;\n toolCalls?: FunctionCall[];\n}\n\nexport interface CompletionUsage {\n completionTokens: number;\n promptTokens: number;\n promptCachedTokens: number;\n totalTokens: number;\n}\n\nexport interface ChatChunk {\n id: string;\n delta?: ChoiceDelta;\n usage?: CompletionUsage;\n}\n\nexport interface LLMError {\n type: 'llm_error';\n timestamp: number;\n label: string;\n error: Error;\n recoverable: boolean;\n}\n\nexport type LLMCallbacks = {\n ['metrics_collected']: (metrics: LLMMetrics) => void;\n ['error']: (error: LLMError) => void;\n};\n\nexport abstract class LLM extends (EventEmitter as new () => TypedEmitter<LLMCallbacks>) {\n constructor() {\n super();\n }\n\n abstract label(): string;\n\n /**\n * Get the model name/identifier for this LLM instance.\n *\n * @returns The model name if available, \"unknown\" otherwise.\n *\n * @remarks\n * Plugins should override this property to provide their model information.\n */\n get model(): string {\n return 'unknown';\n }\n\n /**\n * Returns a {@link LLMStream} that can be used to push text and receive LLM responses.\n */\n abstract chat({\n chatCtx,\n toolCtx,\n connOptions,\n parallelToolCalls,\n toolChoice,\n extraKwargs,\n }: {\n chatCtx: ChatContext;\n toolCtx?: ToolContext;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): LLMStream;\n\n /**\n * Pre-warm connection to the LLM service\n */\n prewarm(): void {\n // Default implementation - subclasses can override\n }\n\n async aclose(): Promise<void> {\n // Default implementation - subclasses can override\n }\n}\n\nexport abstract class LLMStream implements AsyncIterableIterator<ChatChunk> {\n protected output = new AsyncIterableQueue<ChatChunk>();\n protected queue = new AsyncIterableQueue<ChatChunk>();\n protected closed = false;\n protected abortController = new AbortController();\n protected _connOptions: APIConnectOptions;\n protected logger = log();\n\n #llm: LLM;\n #chatCtx: ChatContext;\n #toolCtx?: ToolContext;\n #llmRequestSpan?: Span;\n\n constructor(\n llm: LLM,\n {\n chatCtx,\n toolCtx,\n connOptions,\n }: {\n chatCtx: ChatContext;\n toolCtx?: ToolContext;\n connOptions: APIConnectOptions;\n },\n ) {\n this.#llm = llm;\n this.#chatCtx = chatCtx;\n this.#toolCtx = toolCtx;\n this._connOptions = connOptions;\n this.monitorMetrics();\n this.abortController.signal.addEventListener('abort', () => {\n // TODO (AJS-37) clean this up when we refactor with streams\n this.output.close();\n this.closed = true;\n });\n\n // this is a hack to immitate asyncio.create_task so that mainTask\n // is run **after** the constructor has finished. Otherwise we get\n // runtime error when trying to access class variables in the\n // `run` method.\n startSoon(() => this.mainTask().finally(() => this.queue.close()));\n }\n\n private _mainTaskImpl = async (span: Span) => {\n this.#llmRequestSpan = span;\n span.setAttribute(traceTypes.ATTR_GEN_AI_REQUEST_MODEL, this.#llm.model);\n\n for (let i = 0; i < this._connOptions.maxRetry + 1; i++) {\n try {\n return await tracer.startActiveSpan(\n async (attemptSpan) => {\n attemptSpan.setAttribute(traceTypes.ATTR_RETRY_COUNT, i);\n try {\n return await this.run();\n } catch (error) {\n recordException(attemptSpan, toError(error));\n throw error;\n }\n },\n { name: 'llm_request_run' },\n );\n } catch (error) {\n if (error instanceof APIError) {\n const retryInterval = intervalForRetry(this._connOptions, i);\n\n if (this._connOptions.maxRetry === 0 || !error.retryable) {\n this.emitError({ error, recoverable: false });\n throw error;\n } else if (i === this._connOptions.maxRetry) {\n this.emitError({ error, recoverable: false });\n throw new APIConnectionError({\n message: `failed to generate LLM completion after ${this._connOptions.maxRetry + 1} attempts`,\n options: { retryable: false },\n });\n } else {\n this.emitError({ error, recoverable: true });\n this.logger.warn(\n { llm: this.#llm.label(), attempt: i + 1, error },\n `failed to generate LLM completion, retrying in ${retryInterval}s`,\n );\n }\n\n if (retryInterval > 0) {\n await delay(retryInterval);\n }\n } else {\n this.emitError({ error: toError(error), recoverable: false });\n throw error;\n }\n }\n }\n };\n\n private mainTask = async () =>\n tracer.startActiveSpan(async (span) => this._mainTaskImpl(span), {\n name: 'llm_request',\n endOnExit: false,\n });\n\n private emitError({ error, recoverable }: { error: Error; recoverable: boolean }) {\n this.#llm.emit('error', {\n type: 'llm_error',\n timestamp: Date.now(),\n label: this.#llm.label(),\n error,\n recoverable,\n });\n }\n\n protected async monitorMetrics() {\n const startTime = process.hrtime.bigint();\n let ttft: bigint = BigInt(-1);\n let requestId = '';\n let usage: CompletionUsage | undefined;\n let completionStartTime: string | undefined;\n\n for await (const ev of this.queue) {\n if (this.abortController.signal.aborted) {\n break;\n }\n this.output.put(ev);\n requestId = ev.id;\n if (ttft === BigInt(-1)) {\n ttft = process.hrtime.bigint() - startTime;\n completionStartTime = new Date().toISOString();\n }\n if (ev.usage) {\n usage = ev.usage;\n }\n }\n this.output.close();\n\n const duration = process.hrtime.bigint() - startTime;\n const durationMs = Math.trunc(Number(duration / BigInt(1000000)));\n const metrics: LLMMetrics = {\n type: 'llm_metrics',\n timestamp: Date.now(),\n requestId,\n ttftMs: ttft === BigInt(-1) ? -1 : Math.trunc(Number(ttft / BigInt(1000000))),\n durationMs,\n cancelled: this.abortController.signal.aborted,\n label: this.#llm.label(),\n completionTokens: usage?.completionTokens || 0,\n promptTokens: usage?.promptTokens || 0,\n promptCachedTokens: usage?.promptCachedTokens || 0,\n totalTokens: usage?.totalTokens || 0,\n tokensPerSecond: (() => {\n if (durationMs <= 0) {\n return 0;\n }\n return (usage?.completionTokens || 0) / (durationMs / 1000);\n })(),\n };\n\n if (this.#llmRequestSpan) {\n this.#llmRequestSpan.setAttribute(traceTypes.ATTR_LLM_METRICS, JSON.stringify(metrics));\n\n this.#llmRequestSpan.setAttributes({\n [traceTypes.ATTR_GEN_AI_USAGE_INPUT_TOKENS]: metrics.promptTokens,\n [traceTypes.ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: metrics.completionTokens,\n });\n\n if (completionStartTime) {\n this.#llmRequestSpan.setAttribute(\n traceTypes.ATTR_LANGFUSE_COMPLETION_START_TIME,\n completionStartTime,\n );\n }\n\n // End the span now that metrics are collected\n this.#llmRequestSpan.end();\n }\n\n this.#llm.emit('metrics_collected', metrics);\n }\n\n protected abstract run(): Promise<void>;\n\n /** The function context of this stream. */\n get toolCtx(): ToolContext | undefined {\n return this.#toolCtx;\n }\n\n /** The initial chat context of this stream. */\n get chatCtx(): ChatContext {\n return this.#chatCtx;\n }\n\n /** The connection options for this stream. */\n get connOptions(): APIConnectOptions {\n return this._connOptions;\n }\n\n next(): Promise<IteratorResult<ChatChunk>> {\n return this.output.next();\n }\n\n close() {\n this.abortController.abort();\n }\n\n [Symbol.asyncIterator](): LLMStream {\n return this;\n }\n}\n"],"mappings":"AAKA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,gBAAgB;AAC7C,SAAS,WAAW;AAEpB,SAAS,iBAAiB,YAAY,cAAc;AACpD,SAAiC,wBAAwB;AACzD,SAAS,oBAAoB,OAAO,WAAW,eAAe;AAC9D,eAAmE;AAmC5D,MAAe,YAAa,aAAsD;AAAA,EACvF,cAAc;AACZ,UAAM;AAAA,EACR;AAAA;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AAW,8BAA8B,GAAG,QAAQ;AAAA,QACrD,CAAC,WAAW,+BAA+B,GAAG,QAAQ;AAAA,MACxD,CAAC;AAED,UAAI,qBAAqB;AACvB,aAAK,gBAAgB;AAAA,UACnB,WAAW;AAAA,UACX;AAAA,QACF;AAAA,MACF;AAGA,WAAK,gBAAgB,IAAI;AAAA,IAC3B;AAEA,SAAK,KAAK,KAAK,qBAAqB,OAAO;AAAA,EAC7C;AAAA;AAAA,EAKA,IAAI,UAAmC;AACrC,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,IAAI,UAAuB;AACzB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,IAAI,cAAiC;AACnC,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,OAA2C;AACzC,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA,EAEA,QAAQ;AACN,SAAK,gBAAgB,MAAM;AAAA,EAC7B;AAAA,EAEA,CAAC,OAAO,aAAa,IAAe;AAClC,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/llm/llm.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { TypedEventEmitter as TypedEmitter } from '@livekit/typed-emitter';\nimport type { Span } from '@opentelemetry/api';\nimport { EventEmitter } from 'node:events';\nimport { APIConnectionError, APIError } from '../_exceptions.js';\nimport { log } from '../log.js';\nimport type { LLMMetrics } from '../metrics/base.js';\nimport { recordException, traceTypes, tracer } from '../telemetry/index.js';\nimport { type APIConnectOptions, intervalForRetry } from '../types.js';\nimport { AsyncIterableQueue, delay, startSoon, toError } from '../utils.js';\nimport { type ChatContext, type ChatRole, type FunctionCall } from './chat_context.js';\nimport type { ToolChoice, ToolContext } from './tool_context.js';\n\nexport interface ChoiceDelta {\n role: ChatRole;\n content?: string;\n toolCalls?: FunctionCall[];\n extra?: Record<string, unknown>;\n}\n\nexport interface CompletionUsage {\n completionTokens: number;\n promptTokens: number;\n promptCachedTokens: number;\n totalTokens: number;\n}\n\nexport interface ChatChunk {\n id: string;\n delta?: ChoiceDelta;\n usage?: CompletionUsage;\n}\n\nexport interface LLMError {\n type: 'llm_error';\n timestamp: number;\n label: string;\n error: Error;\n recoverable: boolean;\n}\n\nexport type LLMCallbacks = {\n ['metrics_collected']: (metrics: LLMMetrics) => void;\n ['error']: (error: LLMError) => void;\n};\n\nexport abstract class LLM extends (EventEmitter as new () => TypedEmitter<LLMCallbacks>) {\n constructor() {\n super();\n }\n\n abstract label(): string;\n\n /**\n * Get the model name/identifier for this LLM instance.\n *\n * @returns The model name if available, \"unknown\" otherwise.\n *\n * @remarks\n * Plugins should override this property to provide their model information.\n */\n get model(): string {\n return 'unknown';\n }\n\n /**\n * Returns a {@link LLMStream} that can be used to push text and receive LLM responses.\n */\n abstract chat({\n chatCtx,\n toolCtx,\n connOptions,\n parallelToolCalls,\n toolChoice,\n extraKwargs,\n }: {\n chatCtx: ChatContext;\n toolCtx?: ToolContext;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): LLMStream;\n\n /**\n * Pre-warm connection to the LLM service\n */\n prewarm(): void {\n // Default implementation - subclasses can override\n }\n\n async aclose(): Promise<void> {\n // Default implementation - subclasses can override\n }\n}\n\nexport abstract class LLMStream implements AsyncIterableIterator<ChatChunk> {\n protected output = new AsyncIterableQueue<ChatChunk>();\n protected queue = new AsyncIterableQueue<ChatChunk>();\n protected closed = false;\n protected abortController = new AbortController();\n protected _connOptions: APIConnectOptions;\n protected logger = log();\n\n #llm: LLM;\n #chatCtx: ChatContext;\n #toolCtx?: ToolContext;\n #llmRequestSpan?: Span;\n\n constructor(\n llm: LLM,\n {\n chatCtx,\n toolCtx,\n connOptions,\n }: {\n chatCtx: ChatContext;\n toolCtx?: ToolContext;\n connOptions: APIConnectOptions;\n },\n ) {\n this.#llm = llm;\n this.#chatCtx = chatCtx;\n this.#toolCtx = toolCtx;\n this._connOptions = connOptions;\n this.monitorMetrics();\n this.abortController.signal.addEventListener('abort', () => {\n // TODO (AJS-37) clean this up when we refactor with streams\n this.output.close();\n this.closed = true;\n });\n\n // this is a hack to immitate asyncio.create_task so that mainTask\n // is run **after** the constructor has finished. Otherwise we get\n // runtime error when trying to access class variables in the\n // `run` method.\n startSoon(() => this.mainTask().finally(() => this.queue.close()));\n }\n\n private _mainTaskImpl = async (span: Span) => {\n this.#llmRequestSpan = span;\n span.setAttribute(traceTypes.ATTR_GEN_AI_REQUEST_MODEL, this.#llm.model);\n\n for (let i = 0; i < this._connOptions.maxRetry + 1; i++) {\n try {\n return await tracer.startActiveSpan(\n async (attemptSpan) => {\n attemptSpan.setAttribute(traceTypes.ATTR_RETRY_COUNT, i);\n try {\n return await this.run();\n } catch (error) {\n recordException(attemptSpan, toError(error));\n throw error;\n }\n },\n { name: 'llm_request_run' },\n );\n } catch (error) {\n if (error instanceof APIError) {\n const retryInterval = intervalForRetry(this._connOptions, i);\n\n if (this._connOptions.maxRetry === 0 || !error.retryable) {\n this.emitError({ error, recoverable: false });\n throw error;\n } else if (i === this._connOptions.maxRetry) {\n this.emitError({ error, recoverable: false });\n throw new APIConnectionError({\n message: `failed to generate LLM completion after ${this._connOptions.maxRetry + 1} attempts`,\n options: { retryable: false },\n });\n } else {\n this.emitError({ error, recoverable: true });\n this.logger.warn(\n { llm: this.#llm.label(), attempt: i + 1, error },\n `failed to generate LLM completion, retrying in ${retryInterval}s`,\n );\n }\n\n if (retryInterval > 0) {\n await delay(retryInterval);\n }\n } else {\n this.emitError({ error: toError(error), recoverable: false });\n throw error;\n }\n }\n }\n };\n\n private mainTask = async () =>\n tracer.startActiveSpan(async (span) => this._mainTaskImpl(span), {\n name: 'llm_request',\n endOnExit: false,\n });\n\n private emitError({ error, recoverable }: { error: Error; recoverable: boolean }) {\n this.#llm.emit('error', {\n type: 'llm_error',\n timestamp: Date.now(),\n label: this.#llm.label(),\n error,\n recoverable,\n });\n }\n\n protected async monitorMetrics() {\n const startTime = process.hrtime.bigint();\n let ttft: bigint = BigInt(-1);\n let requestId = '';\n let usage: CompletionUsage | undefined;\n let completionStartTime: string | undefined;\n\n for await (const ev of this.queue) {\n if (this.abortController.signal.aborted) {\n break;\n }\n this.output.put(ev);\n requestId = ev.id;\n if (ttft === BigInt(-1)) {\n ttft = process.hrtime.bigint() - startTime;\n completionStartTime = new Date().toISOString();\n }\n if (ev.usage) {\n usage = ev.usage;\n }\n }\n this.output.close();\n\n const duration = process.hrtime.bigint() - startTime;\n const durationMs = Math.trunc(Number(duration / BigInt(1000000)));\n const metrics: LLMMetrics = {\n type: 'llm_metrics',\n timestamp: Date.now(),\n requestId,\n ttftMs: ttft === BigInt(-1) ? -1 : Math.trunc(Number(ttft / BigInt(1000000))),\n durationMs,\n cancelled: this.abortController.signal.aborted,\n label: this.#llm.label(),\n completionTokens: usage?.completionTokens || 0,\n promptTokens: usage?.promptTokens || 0,\n promptCachedTokens: usage?.promptCachedTokens || 0,\n totalTokens: usage?.totalTokens || 0,\n tokensPerSecond: (() => {\n if (durationMs <= 0) {\n return 0;\n }\n return (usage?.completionTokens || 0) / (durationMs / 1000);\n })(),\n };\n\n if (this.#llmRequestSpan) {\n this.#llmRequestSpan.setAttribute(traceTypes.ATTR_LLM_METRICS, JSON.stringify(metrics));\n\n this.#llmRequestSpan.setAttributes({\n [traceTypes.ATTR_GEN_AI_USAGE_INPUT_TOKENS]: metrics.promptTokens,\n [traceTypes.ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: metrics.completionTokens,\n });\n\n if (completionStartTime) {\n this.#llmRequestSpan.setAttribute(\n traceTypes.ATTR_LANGFUSE_COMPLETION_START_TIME,\n completionStartTime,\n );\n }\n\n // End the span now that metrics are collected\n this.#llmRequestSpan.end();\n }\n\n this.#llm.emit('metrics_collected', metrics);\n }\n\n protected abstract run(): Promise<void>;\n\n /** The function context of this stream. */\n get toolCtx(): ToolContext | undefined {\n return this.#toolCtx;\n }\n\n /** The initial chat context of this stream. */\n get chatCtx(): ChatContext {\n return this.#chatCtx;\n }\n\n /** The connection options for this stream. */\n get connOptions(): APIConnectOptions {\n return this._connOptions;\n }\n\n next(): Promise<IteratorResult<ChatChunk>> {\n return this.output.next();\n }\n\n close() {\n this.abortController.abort();\n }\n\n [Symbol.asyncIterator](): LLMStream {\n return this;\n }\n}\n"],"mappings":"AAKA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,gBAAgB;AAC7C,SAAS,WAAW;AAEpB,SAAS,iBAAiB,YAAY,cAAc;AACpD,SAAiC,wBAAwB;AACzD,SAAS,oBAAoB,OAAO,WAAW,eAAe;AAC9D,eAAmE;AAoC5D,MAAe,YAAa,aAAsD;AAAA,EACvF,cAAc;AACZ,UAAM;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,IAAI,QAAgB;AAClB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAwBA,UAAgB;AAAA,EAEhB;AAAA,EAEA,MAAM,SAAwB;AAAA,EAE9B;AACF;AAEO,MAAe,UAAsD;AAAA,EAChE,SAAS,IAAI,mBAA8B;AAAA,EAC3C,QAAQ,IAAI,mBAA8B;AAAA,EAC1C,SAAS;AAAA,EACT,kBAAkB,IAAI,gBAAgB;AAAA,EACtC;AAAA,EACA,SAAS,IAAI;AAAA,EAEvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YACE,KACA;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAKA;AACA,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,WAAW;AAChB,SAAK,eAAe;AACpB,SAAK,eAAe;AACpB,SAAK,gBAAgB,OAAO,iBAAiB,SAAS,MAAM;AAE1D,WAAK,OAAO,MAAM;AAClB,WAAK,SAAS;AAAA,IAChB,CAAC;AAMD,cAAU,MAAM,KAAK,SAAS,EAAE,QAAQ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29
|
for (const group of itemGroups) {
|
|
30
30
|
if (group.isEmpty) continue;
|
|
31
31
|
const message = group.message ? await toChatItem(group.message) : { role: "assistant" };
|
|
32
|
-
const toolCalls = group.toolCalls.map((toolCall) =>
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
32
|
+
const toolCalls = group.toolCalls.map((toolCall) => {
|
|
33
|
+
const tc = {
|
|
34
|
+
type: "function",
|
|
35
|
+
id: toolCall.callId,
|
|
36
|
+
function: { name: toolCall.name, arguments: toolCall.args }
|
|
37
|
+
};
|
|
38
|
+
const googleExtra = getGoogleExtra(toolCall);
|
|
39
|
+
if (googleExtra) {
|
|
40
|
+
tc.extra_content = { google: googleExtra };
|
|
41
|
+
}
|
|
42
|
+
return tc;
|
|
43
|
+
});
|
|
37
44
|
if (toolCalls.length > 0) {
|
|
38
45
|
message["tool_calls"] = toolCalls;
|
|
39
46
|
}
|
|
@@ -48,28 +55,39 @@ async function toChatItem(item) {
|
|
|
48
55
|
if (item.type === "message") {
|
|
49
56
|
const listContent = [];
|
|
50
57
|
let textContent = "";
|
|
51
|
-
for (const
|
|
52
|
-
if (typeof
|
|
58
|
+
for (const content of item.content) {
|
|
59
|
+
if (typeof content === "string") {
|
|
53
60
|
if (textContent) textContent += "\n";
|
|
54
|
-
textContent +=
|
|
55
|
-
} else if (
|
|
56
|
-
listContent.push(await toImageContent(
|
|
61
|
+
textContent += content;
|
|
62
|
+
} else if (content.type === "image_content") {
|
|
63
|
+
listContent.push(await toImageContent(content));
|
|
57
64
|
} else {
|
|
58
|
-
throw new Error(`Unsupported content type: ${
|
|
65
|
+
throw new Error(`Unsupported content type: ${content.type}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const result = { role: item.role };
|
|
69
|
+
if (listContent.length === 0) {
|
|
70
|
+
result.content = textContent;
|
|
71
|
+
} else {
|
|
72
|
+
if (textContent.length > 0) {
|
|
73
|
+
listContent.push({ type: "text", text: textContent });
|
|
59
74
|
}
|
|
75
|
+
result.content = listContent;
|
|
60
76
|
}
|
|
61
|
-
|
|
62
|
-
return { role: item.role, content };
|
|
77
|
+
return result;
|
|
63
78
|
} else if (item.type === "function_call") {
|
|
79
|
+
const tc = {
|
|
80
|
+
id: item.callId,
|
|
81
|
+
type: "function",
|
|
82
|
+
function: { name: item.name, arguments: item.args }
|
|
83
|
+
};
|
|
84
|
+
const googleExtra = getGoogleExtra(item);
|
|
85
|
+
if (googleExtra) {
|
|
86
|
+
tc.extra_content = { google: googleExtra };
|
|
87
|
+
}
|
|
64
88
|
return {
|
|
65
89
|
role: "assistant",
|
|
66
|
-
tool_calls: [
|
|
67
|
-
{
|
|
68
|
-
id: item.callId,
|
|
69
|
-
type: "function",
|
|
70
|
-
function: { name: item.name, arguments: item.args }
|
|
71
|
-
}
|
|
72
|
-
]
|
|
90
|
+
tool_calls: [tc]
|
|
73
91
|
};
|
|
74
92
|
} else if (item.type === "function_call_output") {
|
|
75
93
|
return {
|
|
@@ -80,6 +98,11 @@ async function toChatItem(item) {
|
|
|
80
98
|
}
|
|
81
99
|
throw new Error(`Unsupported item type: ${item["type"]}`);
|
|
82
100
|
}
|
|
101
|
+
function getGoogleExtra(item) {
|
|
102
|
+
var _a;
|
|
103
|
+
const googleExtra = ((_a = item.extra) == null ? void 0 : _a.google) || (item.thoughtSignature ? { thoughtSignature: item.thoughtSignature } : void 0);
|
|
104
|
+
return googleExtra;
|
|
105
|
+
}
|
|
83
106
|
async function toImageContent(content) {
|
|
84
107
|
const cacheKey = "serialized_image";
|
|
85
108
|
let serialized;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/llm/provider_format/openai.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChatContext, ChatItem, ImageContent } from '../chat_context.js';\nimport { type SerializedImage, serializeImage } from '../utils.js';\nimport { groupToolCalls } from './utils.js';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport async function toChatCtx(chatCtx: ChatContext, injectDummyUserMessage: boolean = true) {\n const itemGroups = groupToolCalls(chatCtx);\n const messages: Record<string, any>[] = []; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n for (const group of itemGroups) {\n if (group.isEmpty) continue;\n\n const message: Record<string, any> = group.message // eslint-disable-line @typescript-eslint/no-explicit-any\n ? await toChatItem(group.message)\n : { role: 'assistant' };\n\n const toolCalls = group.toolCalls.map((toolCall) =>
|
|
1
|
+
{"version":3,"sources":["../../../src/llm/provider_format/openai.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChatContext, ChatItem, ImageContent } from '../chat_context.js';\nimport { type SerializedImage, serializeImage } from '../utils.js';\nimport { groupToolCalls } from './utils.js';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport async function toChatCtx(chatCtx: ChatContext, injectDummyUserMessage: boolean = true) {\n const itemGroups = groupToolCalls(chatCtx);\n const messages: Record<string, any>[] = []; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n for (const group of itemGroups) {\n if (group.isEmpty) continue;\n\n const message: Record<string, any> = group.message // eslint-disable-line @typescript-eslint/no-explicit-any\n ? await toChatItem(group.message)\n : { role: 'assistant' };\n\n const toolCalls = group.toolCalls.map((toolCall) => {\n const tc: Record<string, any> = {\n type: 'function',\n id: toolCall.callId,\n function: { name: toolCall.name, arguments: toolCall.args },\n };\n\n // Include provider-specific extra content (e.g., Google thought signatures)\n const googleExtra = getGoogleExtra(toolCall);\n if (googleExtra) {\n tc.extra_content = { google: googleExtra };\n }\n return tc;\n });\n\n if (toolCalls.length > 0) {\n message['tool_calls'] = toolCalls;\n }\n\n messages.push(message);\n\n for (const toolOutput of group.toolOutputs) {\n messages.push(await toChatItem(toolOutput));\n }\n }\n\n return messages;\n}\n\nasync function toChatItem(item: ChatItem) {\n if (item.type === 'message') {\n const listContent: Record<string, any>[] = []; // eslint-disable-line @typescript-eslint/no-explicit-any\n let textContent = '';\n\n for (const content of item.content) {\n if (typeof content === 'string') {\n if (textContent) textContent += '\\n';\n textContent += content;\n } else if (content.type === 'image_content') {\n listContent.push(await toImageContent(content));\n } else {\n throw new Error(`Unsupported content type: ${content.type}`);\n }\n }\n\n const result: Record<string, any> = { role: item.role };\n if (listContent.length === 0) {\n result.content = textContent;\n } else {\n if (textContent.length > 0) {\n listContent.push({ type: 'text', text: textContent });\n }\n result.content = listContent;\n }\n\n return result;\n } else if (item.type === 'function_call') {\n const tc: Record<string, any> = {\n id: item.callId,\n type: 'function',\n function: { name: item.name, arguments: item.args },\n };\n\n // Include provider-specific extra content (e.g., Google thought signatures)\n const googleExtra = getGoogleExtra(item);\n if (googleExtra) {\n tc.extra_content = { google: googleExtra };\n }\n\n return {\n role: 'assistant',\n tool_calls: [tc],\n };\n } else if (item.type === 'function_call_output') {\n return {\n role: 'tool',\n tool_call_id: item.callId,\n content: item.output,\n };\n }\n // Skip other item types (e.g., agent_handoff)\n // These should be filtered by groupToolCalls, but this is a safety net\n throw new Error(`Unsupported item type: ${item['type']}`);\n}\n\nfunction getGoogleExtra(\n item: Partial<{ extra?: Record<string, unknown>; thoughtSignature?: string }>,\n): Record<string, unknown> | undefined {\n const googleExtra =\n (item.extra?.google as Record<string, unknown> | undefined) ||\n (item.thoughtSignature ? { thoughtSignature: item.thoughtSignature } : undefined);\n return googleExtra;\n}\n\nasync function toImageContent(content: ImageContent) {\n const cacheKey = 'serialized_image'; // TODO: use hash of encoding options if available\n let serialized: SerializedImage;\n\n if (content._cache[cacheKey] === undefined) {\n serialized = await serializeImage(content);\n content._cache[cacheKey] = serialized;\n }\n serialized = content._cache[cacheKey];\n\n // Convert SerializedImage to OpenAI format\n if (serialized.externalUrl) {\n return {\n type: 'image_url',\n image_url: {\n url: serialized.externalUrl,\n detail: serialized.inferenceDetail,\n },\n };\n }\n\n if (serialized.base64Data === undefined) {\n throw new Error('Serialized image has no data bytes');\n }\n\n return {\n type: 'image_url',\n image_url: {\n url: `data:${serialized.mimeType};base64,${serialized.base64Data}`,\n detail: serialized.inferenceDetail,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,mBAAqD;AACrD,IAAAA,gBAA+B;AAG/B,eAAsB,UAAU,SAAsB,yBAAkC,MAAM;AAC5F,QAAM,iBAAa,8BAAe,OAAO;AACzC,QAAM,WAAkC,CAAC;AAEzC,aAAW,SAAS,YAAY;AAC9B,QAAI,MAAM,QAAS;AAEnB,UAAM,UAA+B,MAAM,UACvC,MAAM,WAAW,MAAM,OAAO,IAC9B,EAAE,MAAM,YAAY;AAExB,UAAM,YAAY,MAAM,UAAU,IAAI,CAAC,aAAa;AAClD,YAAM,KAA0B;AAAA,QAC9B,MAAM;AAAA,QACN,IAAI,SAAS;AAAA,QACb,UAAU,EAAE,MAAM,SAAS,MAAM,WAAW,SAAS,KAAK;AAAA,MAC5D;AAGA,YAAM,cAAc,eAAe,QAAQ;AAC3C,UAAI,aAAa;AACf,WAAG,gBAAgB,EAAE,QAAQ,YAAY;AAAA,MAC3C;AACA,aAAO;AAAA,IACT,CAAC;AAED,QAAI,UAAU,SAAS,GAAG;AACxB,cAAQ,YAAY,IAAI;AAAA,IAC1B;AAEA,aAAS,KAAK,OAAO;AAErB,eAAW,cAAc,MAAM,aAAa;AAC1C,eAAS,KAAK,MAAM,WAAW,UAAU,CAAC;AAAA,IAC5C;AAAA,EACF;AAEA,SAAO;AACT;AAEA,eAAe,WAAW,MAAgB;AACxC,MAAI,KAAK,SAAS,WAAW;AAC3B,UAAM,cAAqC,CAAC;AAC5C,QAAI,cAAc;AAElB,eAAW,WAAW,KAAK,SAAS;AAClC,UAAI,OAAO,YAAY,UAAU;AAC/B,YAAI,YAAa,gBAAe;AAChC,uBAAe;AAAA,MACjB,WAAW,QAAQ,SAAS,iBAAiB;AAC3C,oBAAY,KAAK,MAAM,eAAe,O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,OAAO,QAAQ;AAGpC,MAAI,WAAW,aAAa;AAC1B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,WAAW;AAAA,QACT,KAAK,WAAW;AAAA,QAChB,QAAQ,WAAW;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AAEA,MAAI,WAAW,eAAe,QAAW;AACvC,UAAM,IAAI,MAAM,oCAAoC;AAAA,EACtD;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,WAAW;AAAA,MACT,KAAK,QAAQ,WAAW,QAAQ,WAAW,WAAW,UAAU;AAAA,MAChE,QAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF;","names":["import_utils"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../../src/llm/provider_format/openai.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAA0B,MAAM,oBAAoB,CAAC;AAK9E,wBAAsB,SAAS,CAAC,OAAO,EAAE,WAAW,EAAE,sBAAsB,GAAE,OAAc,
|
|
1
|
+
{"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../../src/llm/provider_format/openai.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAA0B,MAAM,oBAAoB,CAAC;AAK9E,wBAAsB,SAAS,CAAC,OAAO,EAAE,WAAW,EAAE,sBAAsB,GAAE,OAAc,kCAsC3F"}
|
|
@@ -6,11 +6,18 @@ async function toChatCtx(chatCtx, injectDummyUserMessage = true) {
|
|
|
6
6
|
for (const group of itemGroups) {
|
|
7
7
|
if (group.isEmpty) continue;
|
|
8
8
|
const message = group.message ? await toChatItem(group.message) : { role: "assistant" };
|
|
9
|
-
const toolCalls = group.toolCalls.map((toolCall) =>
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
9
|
+
const toolCalls = group.toolCalls.map((toolCall) => {
|
|
10
|
+
const tc = {
|
|
11
|
+
type: "function",
|
|
12
|
+
id: toolCall.callId,
|
|
13
|
+
function: { name: toolCall.name, arguments: toolCall.args }
|
|
14
|
+
};
|
|
15
|
+
const googleExtra = getGoogleExtra(toolCall);
|
|
16
|
+
if (googleExtra) {
|
|
17
|
+
tc.extra_content = { google: googleExtra };
|
|
18
|
+
}
|
|
19
|
+
return tc;
|
|
20
|
+
});
|
|
14
21
|
if (toolCalls.length > 0) {
|
|
15
22
|
message["tool_calls"] = toolCalls;
|
|
16
23
|
}
|
|
@@ -25,28 +32,39 @@ async function toChatItem(item) {
|
|
|
25
32
|
if (item.type === "message") {
|
|
26
33
|
const listContent = [];
|
|
27
34
|
let textContent = "";
|
|
28
|
-
for (const
|
|
29
|
-
if (typeof
|
|
35
|
+
for (const content of item.content) {
|
|
36
|
+
if (typeof content === "string") {
|
|
30
37
|
if (textContent) textContent += "\n";
|
|
31
|
-
textContent +=
|
|
32
|
-
} else if (
|
|
33
|
-
listContent.push(await toImageContent(
|
|
38
|
+
textContent += content;
|
|
39
|
+
} else if (content.type === "image_content") {
|
|
40
|
+
listContent.push(await toImageContent(content));
|
|
34
41
|
} else {
|
|
35
|
-
throw new Error(`Unsupported content type: ${
|
|
42
|
+
throw new Error(`Unsupported content type: ${content.type}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const result = { role: item.role };
|
|
46
|
+
if (listContent.length === 0) {
|
|
47
|
+
result.content = textContent;
|
|
48
|
+
} else {
|
|
49
|
+
if (textContent.length > 0) {
|
|
50
|
+
listContent.push({ type: "text", text: textContent });
|
|
36
51
|
}
|
|
52
|
+
result.content = listContent;
|
|
37
53
|
}
|
|
38
|
-
|
|
39
|
-
return { role: item.role, content };
|
|
54
|
+
return result;
|
|
40
55
|
} else if (item.type === "function_call") {
|
|
56
|
+
const tc = {
|
|
57
|
+
id: item.callId,
|
|
58
|
+
type: "function",
|
|
59
|
+
function: { name: item.name, arguments: item.args }
|
|
60
|
+
};
|
|
61
|
+
const googleExtra = getGoogleExtra(item);
|
|
62
|
+
if (googleExtra) {
|
|
63
|
+
tc.extra_content = { google: googleExtra };
|
|
64
|
+
}
|
|
41
65
|
return {
|
|
42
66
|
role: "assistant",
|
|
43
|
-
tool_calls: [
|
|
44
|
-
{
|
|
45
|
-
id: item.callId,
|
|
46
|
-
type: "function",
|
|
47
|
-
function: { name: item.name, arguments: item.args }
|
|
48
|
-
}
|
|
49
|
-
]
|
|
67
|
+
tool_calls: [tc]
|
|
50
68
|
};
|
|
51
69
|
} else if (item.type === "function_call_output") {
|
|
52
70
|
return {
|
|
@@ -57,6 +75,11 @@ async function toChatItem(item) {
|
|
|
57
75
|
}
|
|
58
76
|
throw new Error(`Unsupported item type: ${item["type"]}`);
|
|
59
77
|
}
|
|
78
|
+
function getGoogleExtra(item) {
|
|
79
|
+
var _a;
|
|
80
|
+
const googleExtra = ((_a = item.extra) == null ? void 0 : _a.google) || (item.thoughtSignature ? { thoughtSignature: item.thoughtSignature } : void 0);
|
|
81
|
+
return googleExtra;
|
|
82
|
+
}
|
|
60
83
|
async function toImageContent(content) {
|
|
61
84
|
const cacheKey = "serialized_image";
|
|
62
85
|
let serialized;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/llm/provider_format/openai.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChatContext, ChatItem, ImageContent } from '../chat_context.js';\nimport { type SerializedImage, serializeImage } from '../utils.js';\nimport { groupToolCalls } from './utils.js';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport async function toChatCtx(chatCtx: ChatContext, injectDummyUserMessage: boolean = true) {\n const itemGroups = groupToolCalls(chatCtx);\n const messages: Record<string, any>[] = []; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n for (const group of itemGroups) {\n if (group.isEmpty) continue;\n\n const message: Record<string, any> = group.message // eslint-disable-line @typescript-eslint/no-explicit-any\n ? await toChatItem(group.message)\n : { role: 'assistant' };\n\n const toolCalls = group.toolCalls.map((toolCall) =>
|
|
1
|
+
{"version":3,"sources":["../../../src/llm/provider_format/openai.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { ChatContext, ChatItem, ImageContent } from '../chat_context.js';\nimport { type SerializedImage, serializeImage } from '../utils.js';\nimport { groupToolCalls } from './utils.js';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport async function toChatCtx(chatCtx: ChatContext, injectDummyUserMessage: boolean = true) {\n const itemGroups = groupToolCalls(chatCtx);\n const messages: Record<string, any>[] = []; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n for (const group of itemGroups) {\n if (group.isEmpty) continue;\n\n const message: Record<string, any> = group.message // eslint-disable-line @typescript-eslint/no-explicit-any\n ? await toChatItem(group.message)\n : { role: 'assistant' };\n\n const toolCalls = group.toolCalls.map((toolCall) => {\n const tc: Record<string, any> = {\n type: 'function',\n id: toolCall.callId,\n function: { name: toolCall.name, arguments: toolCall.args },\n };\n\n // Include provider-specific extra content (e.g., Google thought signatures)\n const googleExtra = getGoogleExtra(toolCall);\n if (googleExtra) {\n tc.extra_content = { google: googleExtra };\n }\n return tc;\n });\n\n if (toolCalls.length > 0) {\n message['tool_calls'] = toolCalls;\n }\n\n messages.push(message);\n\n for (const toolOutput of group.toolOutputs) {\n messages.push(await toChatItem(toolOutput));\n }\n }\n\n return messages;\n}\n\nasync function toChatItem(item: ChatItem) {\n if (item.type === 'message') {\n const listContent: Record<string, any>[] = []; // eslint-disable-line @typescript-eslint/no-explicit-any\n let textContent = '';\n\n for (const content of item.content) {\n if (typeof content === 'string') {\n if (textContent) textContent += '\\n';\n textContent += content;\n } else if (content.type === 'image_content') {\n listContent.push(await toImageContent(content));\n } else {\n throw new Error(`Unsupported content type: ${content.type}`);\n }\n }\n\n const result: Record<string, any> = { role: item.role };\n if (listContent.length === 0) {\n result.content = textContent;\n } else {\n if (textContent.length > 0) {\n listContent.push({ type: 'text', text: textContent });\n }\n result.content = listContent;\n }\n\n return result;\n } else if (item.type === 'function_call') {\n const tc: Record<string, any> = {\n id: item.callId,\n type: 'function',\n function: { name: item.name, arguments: item.args },\n };\n\n // Include provider-specific extra content (e.g., Google thought signatures)\n const googleExtra = getGoogleExtra(item);\n if (googleExtra) {\n tc.extra_content = { google: googleExtra };\n }\n\n return {\n role: 'assistant',\n tool_calls: [tc],\n };\n } else if (item.type === 'function_call_output') {\n return {\n role: 'tool',\n tool_call_id: item.callId,\n content: item.output,\n };\n }\n // Skip other item types (e.g., agent_handoff)\n // These should be filtered by groupToolCalls, but this is a safety net\n throw new Error(`Unsupported item type: ${item['type']}`);\n}\n\nfunction getGoogleExtra(\n item: Partial<{ extra?: Record<string, unknown>; thoughtSignature?: string }>,\n): Record<string, unknown> | undefined {\n const googleExtra =\n (item.extra?.google as Record<string, unknown> | undefined) ||\n (item.thoughtSignature ? { thoughtSignature: item.thoughtSignature } : undefined);\n return googleExtra;\n}\n\nasync function toImageContent(content: ImageContent) {\n const cacheKey = 'serialized_image'; // TODO: use hash of encoding options if available\n let serialized: SerializedImage;\n\n if (content._cache[cacheKey] === undefined) {\n serialized = await serializeImage(content);\n content._cache[cacheKey] = serialized;\n }\n serialized = content._cache[cacheKey];\n\n // Convert SerializedImage to OpenAI format\n if (serialized.externalUrl) {\n return {\n type: 'image_url',\n image_url: {\n url: serialized.externalUrl,\n detail: serialized.inferenceDetail,\n },\n };\n }\n\n if (serialized.base64Data === undefined) {\n throw new Error('Serialized image has no data bytes');\n }\n\n return {\n type: 'image_url',\n image_url: {\n url: `data:${serialized.mimeType};base64,${serialized.base64Data}`,\n detail: serialized.inferenceDetail,\n },\n };\n}\n"],"mappings":"AAIA,SAA+B,sBAAsB;AACrD,SAAS,sBAAsB;AAG/B,eAAsB,UAAU,SAAsB,yBAAkC,MAAM;AAC5F,QAAM,aAAa,eAAe,OAAO;AACzC,QAAM,WAAkC,CAAC;AAEzC,aAAW,SAAS,Y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AW,WAAW,UAAU;AAAA,MAChE,QAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF;","names":[]}
|
|
@@ -207,6 +207,41 @@ import_vitest.vi.mock("../utils.js", () => ({
|
|
|
207
207
|
}
|
|
208
208
|
]);
|
|
209
209
|
});
|
|
210
|
+
(0, import_vitest.it)("should include provider-specific extra content on tool calls", async () => {
|
|
211
|
+
const ctx = import_chat_context.ChatContext.empty();
|
|
212
|
+
const msg = ctx.addMessage({ role: "assistant", content: "Running tool" });
|
|
213
|
+
const toolCall = import_chat_context.FunctionCall.create({
|
|
214
|
+
id: `${msg.id}/tool_1`,
|
|
215
|
+
callId: "call_789",
|
|
216
|
+
name: "google_call",
|
|
217
|
+
args: "{}",
|
|
218
|
+
extra: { google: { thoughtSignature: "sig-123" } }
|
|
219
|
+
});
|
|
220
|
+
const toolOutput = import_chat_context.FunctionCallOutput.create({
|
|
221
|
+
callId: "call_789",
|
|
222
|
+
output: '{"result": "ok"}',
|
|
223
|
+
isError: false
|
|
224
|
+
});
|
|
225
|
+
ctx.insert([toolCall, toolOutput]);
|
|
226
|
+
const result = await (0, import_openai.toChatCtx)(ctx);
|
|
227
|
+
(0, import_vitest.expect)(result[0]).toEqual({
|
|
228
|
+
role: "assistant",
|
|
229
|
+
content: "Running tool",
|
|
230
|
+
tool_calls: [
|
|
231
|
+
{
|
|
232
|
+
type: "function",
|
|
233
|
+
id: "call_789",
|
|
234
|
+
function: { name: "google_call", arguments: "{}" },
|
|
235
|
+
extra_content: { google: { thoughtSignature: "sig-123" } }
|
|
236
|
+
}
|
|
237
|
+
]
|
|
238
|
+
});
|
|
239
|
+
(0, import_vitest.expect)(result[1]).toEqual({
|
|
240
|
+
role: "tool",
|
|
241
|
+
tool_call_id: "call_789",
|
|
242
|
+
content: '{"result": "ok"}'
|
|
243
|
+
});
|
|
244
|
+
});
|
|
210
245
|
(0, import_vitest.it)("should handle multiple tool calls in one message", async () => {
|
|
211
246
|
const ctx = import_chat_context.ChatContext.empty();
|
|
212
247
|
const msg = ctx.addMessage({ role: "assistant", content: "I'll check both locations." });
|