@langchain/core 1.2.18 → 1.2.20
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/CHANGELOG.md +15 -0
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/language_models/event.cjs.map +1 -1
- package/dist/language_models/event.d.cts +27 -2
- package/dist/language_models/event.d.cts.map +1 -1
- package/dist/language_models/event.d.ts +27 -2
- package/dist/language_models/event.d.ts.map +1 -1
- package/dist/language_models/event.js.map +1 -1
- package/dist/language_models/profile.cjs.map +1 -1
- package/dist/language_models/profile.d.cts +21 -0
- package/dist/language_models/profile.d.cts.map +1 -1
- package/dist/language_models/profile.d.ts +21 -0
- package/dist/language_models/profile.d.ts.map +1 -1
- package/dist/language_models/profile.js.map +1 -1
- package/dist/language_models/stream.cjs +8 -1
- package/dist/language_models/stream.cjs.map +1 -1
- package/dist/language_models/stream.d.cts.map +1 -1
- package/dist/language_models/stream.d.ts.map +1 -1
- package/dist/language_models/stream.js +8 -1
- package/dist/language_models/stream.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# @langchain/core
|
|
2
2
|
|
|
3
|
+
## 1.2.20
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#11922](https://github.com/langchain-ai/langchainjs/pull/11922) [`d71c542`](https://github.com/langchain-ai/langchainjs/commit/d71c542fb1d9cd1ceb310a4759591c024cf0d57d) Thanks [@richardscarrott](https://github.com/richardscarrott)! - feat(core): add `midConversationSystemMessages` and `midConversationTools` to `ModelProfile`. They say whether a chat model sends a system message after the first turn in place, and whether it can add a tool through a message rather than the request's tool list. Either way the prompt prefix before it stays unchanged.
|
|
8
|
+
|
|
9
|
+
## 1.2.19
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- [#11982](https://github.com/langchain-ai/langchainjs/pull/11982) [`5af4684`](https://github.com/langchain-ai/langchainjs/commit/5af4684bd19a16bb59950801da92245733482fb3) Thanks [@richardscarrott](https://github.com/richardscarrott)! - feat(core): read `tool-call-delta` in `ChatModelStream`
|
|
14
|
+
|
|
15
|
+
- `ChatModelStream` appends `tool-call-delta` slices to a tool call's args, and still replaces them on `block-delta`
|
|
16
|
+
- It ignores delta types it doesn't recognize instead of throwing `Unknown delta type`
|
|
17
|
+
|
|
3
18
|
## 1.2.18
|
|
4
19
|
|
|
5
20
|
### Patch Changes
|
|
@@ -139,7 +139,7 @@ var BaseLangChain = class extends require_base.Runnable {
|
|
|
139
139
|
this.callbacks = params.callbacks;
|
|
140
140
|
this.tags = params.tags ?? [];
|
|
141
141
|
this.metadata = params.metadata ?? {};
|
|
142
|
-
this._addVersion("@langchain/core", "1.2.
|
|
142
|
+
this._addVersion("@langchain/core", "1.2.20");
|
|
143
143
|
}
|
|
144
144
|
_addVersion(pkg, version) {
|
|
145
145
|
const existing = this.metadata?.versions;
|
|
@@ -138,7 +138,7 @@ var BaseLangChain = class extends Runnable {
|
|
|
138
138
|
this.callbacks = params.callbacks;
|
|
139
139
|
this.tags = params.tags ?? [];
|
|
140
140
|
this.metadata = params.metadata ?? {};
|
|
141
|
-
this._addVersion("@langchain/core", "1.2.
|
|
141
|
+
this._addVersion("@langchain/core", "1.2.20");
|
|
142
142
|
}
|
|
143
143
|
_addVersion(pkg, version) {
|
|
144
144
|
const existing = this.metadata?.versions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.cjs","names":[],"sources":["../../src/language_models/event.ts"],"sourcesContent":["/**\n * Chat model streaming event protocol.\n *\n * Defines a content-block-centric event model for streaming chat model responses.\n * Events carry LangChain {@link ContentBlock} types on lifecycle boundaries\n * and explicit delta variants for incremental updates during streaming.\n *\n * ## Design Principles\n *\n * 1. **Content-block deltas have explicit merge semantics.** Text,\n * reasoning, and data deltas append to named fields. Generic block deltas\n * shallow-merge fields onto the active content block.\n *\n * 2. **Lifecycle completeness.** Every streamable entity has explicit start and finish\n * events. Consumers never need to infer boundaries from absence of events.\n *\n * 3. **Interleaving allowed.** Content blocks may interleave (e.g., parallel tool calls).\n * The only invariant: a block's start precedes its deltas, and its deltas precede\n * its finish. No ordering constraint between different blocks.\n *\n * 4. **Provider passthrough.** Native provider events that don't map to standard types\n * are forwarded as {@link ProviderEvent} rather than silently dropped.\n *\n * ## Lifecycle Contract\n *\n * ```\n * MessageStart\n * -> ContentBlockStart(index=0, content=...)\n * -> ContentBlockDelta(index=0, delta={ type: \"text-delta\", text: \"Hello\" })\n * -> ContentBlockDelta(index=0, delta={ type: \"text-delta\", text: \" world\" })\n * -> ContentBlockFinish(index=0, content=...)\n * -> UsageUpdate(...)\n * -> MessageFinish(reason, usage?)\n * ```\n *\n * @module\n */\n\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\n\n// ─── Message Lifecycle ──────────────────────────────────────────\n\n/**\n * Emitted once at the start of a model response.\n */\nexport interface MessageStartEvent {\n event: \"message-start\";\n /** Optional message ID assigned by the provider. */\n id?: string;\n /**\n * Initial usage snapshot, if the provider reports input token counts\n * before content begins streaming (e.g., Anthropic's `message_start`).\n */\n usage?: Partial<UsageMetadata>;\n}\n\n/**\n * Finish reason for a model response.\n *\n * - `\"stop\"`: Natural end of generation.\n * - `\"length\"`: Hit max token limit.\n * - `\"tool_use\"`: Model is requesting tool execution.\n * - `\"content_filter\"`: Content was filtered by safety systems.\n */\nexport type FinishReason = \"stop\" | \"length\" | \"tool_use\" | \"content_filter\";\n\n/**\n * Emitted once when the model response is complete.\n */\nexport interface MessageFinishEvent {\n event: \"message-finish\";\n /** Why the model stopped generating. */\n reason?: FinishReason;\n /** Final usage snapshot. */\n usage?: Partial<UsageMetadata>;\n /** Provider-specific response metadata (model name, response ID, headers, etc.). */\n responseMetadata?: Record<string, unknown>;\n}\n\n// ─── Content Block Lifecycle ────────────────────────────────────\n// See https://github.com/langchain-ai/agent-protocol/blob/main/streaming/protocol.cddl\n\n/**\n * Emitted when a new content block begins streaming.\n *\n * @example\n * ```ts\n * { event: \"content-block-start\", index: 0,\n * content: { type: \"text\", text: \"\" } }\n * ```\n */\nexport interface ContentBlockStartEvent {\n event: \"content-block-start\";\n /** Positional index of this block within the message. */\n index: number;\n /** Initial state of the content block. */\n content: ContentBlock;\n}\n\n// ─── Content Block Deltas ───────────────────────────────────────\n\n/**\n * Incremental text content. Append `text` to the active block's `text` field.\n */\nexport interface TextDelta {\n type: \"text-delta\";\n /** The new text to append. */\n text: string;\n}\n\n/**\n * Incremental reasoning content. Append `reasoning` to the active block's\n * `reasoning` field.\n */\nexport interface ReasoningDelta {\n type: \"reasoning-delta\";\n /** The new reasoning text to append. */\n reasoning: string;\n}\n\n/**\n * Incremental encoded data. Append `data` to the active multimodal block's\n * data field.\n */\nexport interface DataDelta {\n type: \"data-delta\";\n /** Encoded data chunk to append. */\n data: string;\n /** Encoding for the data chunk. Defaults to `\"base64\"` when omitted. */\n encoding?: \"base64\";\n}\n\n/**\n * Generic content block field update. Shallow-merge `fields` onto the active\n * content block.\n */\nexport interface BlockDelta {\n type: \"block-delta\";\n /** Fields to shallow-merge onto the active content block. */\n fields: { type: string } & Record<string, unknown>;\n}\n\n/**\n * Union of all content block delta types.\n */\nexport type ContentBlockDelta =\n | TextDelta\n | ReasoningDelta\n | DataDelta\n | BlockDelta;\n\n/**\n * Emitted for each incremental update within a content block.\n *\n * The `delta` field carries the incremental content block update.\n * Accumulation rules:\n * - `text-delta` → append `text` to the active block's text field\n * - `reasoning-delta` → append `reasoning` to the active block's reasoning field\n * - `data-delta` → append `data` to the active block's data field\n * - `block-delta` → shallow-merge `fields` onto the active block\n *\n * @example\n * ```ts\n * // Text token\n * { event: \"content-block-delta\", index: 0,\n * delta: { type: \"text-delta\", text: \" world\" } }\n *\n * // Tool call args snapshot\n * { event: \"content-block-delta\", index: 1,\n * delta: { type: \"block-delta\",\n * fields: { type: \"tool_call_chunk\", args: '{\"q\":\"wea' } } }
|
|
1
|
+
{"version":3,"file":"event.cjs","names":[],"sources":["../../src/language_models/event.ts"],"sourcesContent":["/**\n * Chat model streaming event protocol.\n *\n * Defines a content-block-centric event model for streaming chat model responses.\n * Events carry LangChain {@link ContentBlock} types on lifecycle boundaries\n * and explicit delta variants for incremental updates during streaming.\n *\n * ## Design Principles\n *\n * 1. **Content-block deltas have explicit merge semantics.** Text,\n * reasoning, and data deltas append to named fields. Generic block deltas\n * shallow-merge fields onto the active content block.\n *\n * 2. **Lifecycle completeness.** Every streamable entity has explicit start and finish\n * events. Consumers never need to infer boundaries from absence of events.\n *\n * 3. **Interleaving allowed.** Content blocks may interleave (e.g., parallel tool calls).\n * The only invariant: a block's start precedes its deltas, and its deltas precede\n * its finish. No ordering constraint between different blocks.\n *\n * 4. **Provider passthrough.** Native provider events that don't map to standard types\n * are forwarded as {@link ProviderEvent} rather than silently dropped.\n *\n * ## Lifecycle Contract\n *\n * ```\n * MessageStart\n * -> ContentBlockStart(index=0, content=...)\n * -> ContentBlockDelta(index=0, delta={ type: \"text-delta\", text: \"Hello\" })\n * -> ContentBlockDelta(index=0, delta={ type: \"text-delta\", text: \" world\" })\n * -> ContentBlockFinish(index=0, content=...)\n * -> UsageUpdate(...)\n * -> MessageFinish(reason, usage?)\n * ```\n *\n * @module\n */\n\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\n\n// ─── Message Lifecycle ──────────────────────────────────────────\n\n/**\n * Emitted once at the start of a model response.\n */\nexport interface MessageStartEvent {\n event: \"message-start\";\n /** Optional message ID assigned by the provider. */\n id?: string;\n /**\n * Initial usage snapshot, if the provider reports input token counts\n * before content begins streaming (e.g., Anthropic's `message_start`).\n */\n usage?: Partial<UsageMetadata>;\n}\n\n/**\n * Finish reason for a model response.\n *\n * - `\"stop\"`: Natural end of generation.\n * - `\"length\"`: Hit max token limit.\n * - `\"tool_use\"`: Model is requesting tool execution.\n * - `\"content_filter\"`: Content was filtered by safety systems.\n */\nexport type FinishReason = \"stop\" | \"length\" | \"tool_use\" | \"content_filter\";\n\n/**\n * Emitted once when the model response is complete.\n */\nexport interface MessageFinishEvent {\n event: \"message-finish\";\n /** Why the model stopped generating. */\n reason?: FinishReason;\n /** Final usage snapshot. */\n usage?: Partial<UsageMetadata>;\n /** Provider-specific response metadata (model name, response ID, headers, etc.). */\n responseMetadata?: Record<string, unknown>;\n}\n\n// ─── Content Block Lifecycle ────────────────────────────────────\n// See https://github.com/langchain-ai/agent-protocol/blob/main/streaming/protocol.cddl\n\n/**\n * Emitted when a new content block begins streaming.\n *\n * @example\n * ```ts\n * { event: \"content-block-start\", index: 0,\n * content: { type: \"text\", text: \"\" } }\n * ```\n */\nexport interface ContentBlockStartEvent {\n event: \"content-block-start\";\n /** Positional index of this block within the message. */\n index: number;\n /** Initial state of the content block. */\n content: ContentBlock;\n}\n\n// ─── Content Block Deltas ───────────────────────────────────────\n\n/**\n * Incremental text content. Append `text` to the active block's `text` field.\n */\nexport interface TextDelta {\n type: \"text-delta\";\n /** The new text to append. */\n text: string;\n}\n\n/**\n * Incremental reasoning content. Append `reasoning` to the active block's\n * `reasoning` field.\n */\nexport interface ReasoningDelta {\n type: \"reasoning-delta\";\n /** The new reasoning text to append. */\n reasoning: string;\n}\n\n/**\n * Incremental encoded data. Append `data` to the active multimodal block's\n * data field.\n */\nexport interface DataDelta {\n type: \"data-delta\";\n /** Encoded data chunk to append. */\n data: string;\n /** Encoding for the data chunk. Defaults to `\"base64\"` when omitted. */\n encoding?: \"base64\";\n}\n\n/**\n * Incremental tool-call arguments. Append `args` to the active\n * `tool_call_chunk` or `server_tool_call_chunk` block's `args` field, treating\n * missing args as an empty string.\n *\n * A slice need not be valid JSON on its own. The call's `id` and `name` arrive\n * on `content-block-start`, and `content-block-finish` carries the parsed call.\n */\nexport interface ToolCallDelta {\n type: \"tool-call-delta\";\n /** The new slice of the call's arguments string to append. */\n args: string;\n}\n\n/**\n * Generic content block field update. Shallow-merge `fields` onto the active\n * content block.\n */\nexport interface BlockDelta {\n type: \"block-delta\";\n /** Fields to shallow-merge onto the active content block. */\n fields: { type: string } & Record<string, unknown>;\n}\n\n/**\n * Union of all content block delta types.\n */\nexport type ContentBlockDelta =\n | TextDelta\n | ReasoningDelta\n | DataDelta\n | ToolCallDelta\n | BlockDelta;\n\n/**\n * Emitted for each incremental update within a content block.\n *\n * The `delta` field carries the incremental content block update.\n * Accumulation rules:\n * - `text-delta` → append `text` to the active block's text field\n * - `reasoning-delta` → append `reasoning` to the active block's reasoning field\n * - `data-delta` → append `data` to the active block's data field\n * - `tool-call-delta` → append `args` to the active tool-call block's args field\n * - `block-delta` → shallow-merge `fields` onto the active block\n *\n * Consumers ignore delta types they don't recognize.\n * `content-block-finish` carries the complete block.\n *\n * A tool call's args stream in one of two forms, never both in one block:\n * `tool-call-delta` slices, which append, or `block-delta` snapshots of the\n * args so far, which replace.\n *\n * @example\n * ```ts\n * // Text token\n * { event: \"content-block-delta\", index: 0,\n * delta: { type: \"text-delta\", text: \" world\" } }\n *\n * // Tool call args slice\n * { event: \"content-block-delta\", index: 1,\n * delta: { type: \"tool-call-delta\", args: '\"wea' } }\n *\n * // Tool call args snapshot\n * { event: \"content-block-delta\", index: 1,\n * delta: { type: \"block-delta\",\n * fields: { type: \"tool_call_chunk\", args: '{\"q\":\"wea' } } }\n *\n * // Provider-specific field (e.g., signature)\n * { event: \"content-block-delta\", index: 0,\n * delta: { type: \"block-delta\",\n * fields: { type: \"reasoning\", signature: \"sig_abc\" } } }\n * ```\n */\nexport interface ContentBlockDeltaEvent {\n event: \"content-block-delta\";\n /** Positional index of the block being updated. */\n index: number;\n /** Incremental content block delta. */\n delta: ContentBlockDelta;\n}\n\n/**\n * Emitted when a content block is complete.\n *\n * @example\n * ```ts\n * { event: \"content-block-finish\", index: 0,\n * content: { type: \"text\", text: \"Hello world\" } }\n * ```\n */\nexport interface ContentBlockFinishEvent {\n event: \"content-block-finish\";\n /** Positional index of the completed block. */\n index: number;\n /** Finalized content block. */\n content: ContentBlock;\n}\n\n// ─── Usage ──────────────────────────────────────────────────────\n\n/**\n * Emitted whenever the provider reports updated usage information.\n * Each event carries a **running snapshot** (not an additive delta).\n */\nexport interface UsageUpdateEvent {\n event: \"usage\";\n /** Current usage snapshot. */\n usage: Partial<UsageMetadata>;\n}\n\n// ─── Provider Passthrough ───────────────────────────────────────\n\n/**\n * Passthrough for native provider events that don't map to standard types.\n */\nexport interface ProviderEvent {\n event: \"provider\";\n /** Provider identifier (e.g., `\"openai\"`, `\"anthropic\"`, `\"google\"`). */\n provider: string;\n /** Raw event type name from the provider SDK. */\n name: string;\n /** Raw event payload from the provider SDK. */\n payload: unknown;\n}\n\n// ─── Error ──────────────────────────────────────────────────────\n\n/**\n * Emitted on unrecoverable stream errors.\n */\nexport interface StreamErrorEvent {\n event: \"error\";\n /** Human-readable error message. */\n message: string;\n /** Optional error code for programmatic handling. */\n code?: string;\n}\n\n// ─── Union ──────────────────────────────────────────────────────\n\n/**\n * Union of all chat model stream event types.\n */\nexport type ChatModelStreamEvent =\n | MessageStartEvent\n | MessageFinishEvent\n | ContentBlockStartEvent\n | ContentBlockDeltaEvent\n | ContentBlockFinishEvent\n | UsageUpdateEvent\n | ProviderEvent\n | StreamErrorEvent;\n"],"mappings":""}
|
|
@@ -79,6 +79,19 @@ export interface DataDelta {
|
|
|
79
79
|
/** Encoding for the data chunk. Defaults to `"base64"` when omitted. */
|
|
80
80
|
encoding?: "base64";
|
|
81
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* Incremental tool-call arguments. Append `args` to the active
|
|
84
|
+
* `tool_call_chunk` or `server_tool_call_chunk` block's `args` field, treating
|
|
85
|
+
* missing args as an empty string.
|
|
86
|
+
*
|
|
87
|
+
* A slice need not be valid JSON on its own. The call's `id` and `name` arrive
|
|
88
|
+
* on `content-block-start`, and `content-block-finish` carries the parsed call.
|
|
89
|
+
*/
|
|
90
|
+
export interface ToolCallDelta {
|
|
91
|
+
type: "tool-call-delta";
|
|
92
|
+
/** The new slice of the call's arguments string to append. */
|
|
93
|
+
args: string;
|
|
94
|
+
}
|
|
82
95
|
/**
|
|
83
96
|
* Generic content block field update. Shallow-merge `fields` onto the active
|
|
84
97
|
* content block.
|
|
@@ -93,7 +106,7 @@ export interface BlockDelta {
|
|
|
93
106
|
/**
|
|
94
107
|
* Union of all content block delta types.
|
|
95
108
|
*/
|
|
96
|
-
export type ContentBlockDelta = TextDelta | ReasoningDelta | DataDelta | BlockDelta;
|
|
109
|
+
export type ContentBlockDelta = TextDelta | ReasoningDelta | DataDelta | ToolCallDelta | BlockDelta;
|
|
97
110
|
/**
|
|
98
111
|
* Emitted for each incremental update within a content block.
|
|
99
112
|
*
|
|
@@ -102,18 +115,30 @@ export type ContentBlockDelta = TextDelta | ReasoningDelta | DataDelta | BlockDe
|
|
|
102
115
|
* - `text-delta` → append `text` to the active block's text field
|
|
103
116
|
* - `reasoning-delta` → append `reasoning` to the active block's reasoning field
|
|
104
117
|
* - `data-delta` → append `data` to the active block's data field
|
|
118
|
+
* - `tool-call-delta` → append `args` to the active tool-call block's args field
|
|
105
119
|
* - `block-delta` → shallow-merge `fields` onto the active block
|
|
106
120
|
*
|
|
121
|
+
* Consumers ignore delta types they don't recognize.
|
|
122
|
+
* `content-block-finish` carries the complete block.
|
|
123
|
+
*
|
|
124
|
+
* A tool call's args stream in one of two forms, never both in one block:
|
|
125
|
+
* `tool-call-delta` slices, which append, or `block-delta` snapshots of the
|
|
126
|
+
* args so far, which replace.
|
|
127
|
+
*
|
|
107
128
|
* @example
|
|
108
129
|
* ```ts
|
|
109
130
|
* // Text token
|
|
110
131
|
* { event: "content-block-delta", index: 0,
|
|
111
132
|
* delta: { type: "text-delta", text: " world" } }
|
|
112
133
|
*
|
|
134
|
+
* // Tool call args slice
|
|
135
|
+
* { event: "content-block-delta", index: 1,
|
|
136
|
+
* delta: { type: "tool-call-delta", args: '"wea' } }
|
|
137
|
+
*
|
|
113
138
|
* // Tool call args snapshot
|
|
114
139
|
* { event: "content-block-delta", index: 1,
|
|
115
140
|
* delta: { type: "block-delta",
|
|
116
|
-
* fields: { type: "tool_call_chunk", args: '{"q":"wea' } } }
|
|
141
|
+
* fields: { type: "tool_call_chunk", args: '{"q":"wea' } } }
|
|
117
142
|
*
|
|
118
143
|
* // Provider-specific field (e.g., signature)
|
|
119
144
|
* { event: "content-block-delta", index: 0,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.d.cts","names":[],"sources":["../../src/language_models/event.ts"],"mappings":";;;;;;iBA8CiB;EACf;;EAEA;;;;;EAKA,QAAQ,QAAQ;;;;;;;;;;YAWN;;;;iBAKK;EACf;;EAEA,SAAS;;EAET,QAAQ,QAAQ;;EAEhB,mBAAmB;;;;;;;;;;;iBAeJ;EACf;;EAEA;;EAEA,SAAS;;;;;iBAQM;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;;EAEA;;;;;;iBAOe;EACf;;EAEA;IAAU;MAAiB;;;;;YAMjB,oBACR,YACA,iBACA,YACA
|
|
1
|
+
{"version":3,"file":"event.d.cts","names":[],"sources":["../../src/language_models/event.ts"],"mappings":";;;;;;iBA8CiB;EACf;;EAEA;;;;;EAKA,QAAQ,QAAQ;;;;;;;;;;YAWN;;;;iBAKK;EACf;;EAEA,SAAS;;EAET,QAAQ,QAAQ;;EAEhB,mBAAmB;;;;;;;;;;;iBAeJ;EACf;;EAEA;;EAEA,SAAS;;;;;iBAQM;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;;EAEA;;;;;;;;;;iBAWe;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;IAAU;MAAiB;;;;;YAMjB,oBACR,YACA,iBACA,YACA,gBACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyCa;EACf;;EAEA;;EAEA,OAAO;;;;;;;;;;;iBAYQ;EACf;;EAEA;;EAEA,SAAS;;;;;;iBASM;EACf;;EAEA,OAAO,QAAQ;;;;;iBAQA;EACf;;EAEA;;EAEA;;EAEA;;;;;iBAQe;EACf;;EAEA;;EAEA;;;;;YAQU,uBACR,oBACA,qBACA,yBACA,yBACA,0BACA,mBACA,gBACA"}
|
|
@@ -79,6 +79,19 @@ export interface DataDelta {
|
|
|
79
79
|
/** Encoding for the data chunk. Defaults to `"base64"` when omitted. */
|
|
80
80
|
encoding?: "base64";
|
|
81
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* Incremental tool-call arguments. Append `args` to the active
|
|
84
|
+
* `tool_call_chunk` or `server_tool_call_chunk` block's `args` field, treating
|
|
85
|
+
* missing args as an empty string.
|
|
86
|
+
*
|
|
87
|
+
* A slice need not be valid JSON on its own. The call's `id` and `name` arrive
|
|
88
|
+
* on `content-block-start`, and `content-block-finish` carries the parsed call.
|
|
89
|
+
*/
|
|
90
|
+
export interface ToolCallDelta {
|
|
91
|
+
type: "tool-call-delta";
|
|
92
|
+
/** The new slice of the call's arguments string to append. */
|
|
93
|
+
args: string;
|
|
94
|
+
}
|
|
82
95
|
/**
|
|
83
96
|
* Generic content block field update. Shallow-merge `fields` onto the active
|
|
84
97
|
* content block.
|
|
@@ -93,7 +106,7 @@ export interface BlockDelta {
|
|
|
93
106
|
/**
|
|
94
107
|
* Union of all content block delta types.
|
|
95
108
|
*/
|
|
96
|
-
export type ContentBlockDelta = TextDelta | ReasoningDelta | DataDelta | BlockDelta;
|
|
109
|
+
export type ContentBlockDelta = TextDelta | ReasoningDelta | DataDelta | ToolCallDelta | BlockDelta;
|
|
97
110
|
/**
|
|
98
111
|
* Emitted for each incremental update within a content block.
|
|
99
112
|
*
|
|
@@ -102,18 +115,30 @@ export type ContentBlockDelta = TextDelta | ReasoningDelta | DataDelta | BlockDe
|
|
|
102
115
|
* - `text-delta` → append `text` to the active block's text field
|
|
103
116
|
* - `reasoning-delta` → append `reasoning` to the active block's reasoning field
|
|
104
117
|
* - `data-delta` → append `data` to the active block's data field
|
|
118
|
+
* - `tool-call-delta` → append `args` to the active tool-call block's args field
|
|
105
119
|
* - `block-delta` → shallow-merge `fields` onto the active block
|
|
106
120
|
*
|
|
121
|
+
* Consumers ignore delta types they don't recognize.
|
|
122
|
+
* `content-block-finish` carries the complete block.
|
|
123
|
+
*
|
|
124
|
+
* A tool call's args stream in one of two forms, never both in one block:
|
|
125
|
+
* `tool-call-delta` slices, which append, or `block-delta` snapshots of the
|
|
126
|
+
* args so far, which replace.
|
|
127
|
+
*
|
|
107
128
|
* @example
|
|
108
129
|
* ```ts
|
|
109
130
|
* // Text token
|
|
110
131
|
* { event: "content-block-delta", index: 0,
|
|
111
132
|
* delta: { type: "text-delta", text: " world" } }
|
|
112
133
|
*
|
|
134
|
+
* // Tool call args slice
|
|
135
|
+
* { event: "content-block-delta", index: 1,
|
|
136
|
+
* delta: { type: "tool-call-delta", args: '"wea' } }
|
|
137
|
+
*
|
|
113
138
|
* // Tool call args snapshot
|
|
114
139
|
* { event: "content-block-delta", index: 1,
|
|
115
140
|
* delta: { type: "block-delta",
|
|
116
|
-
* fields: { type: "tool_call_chunk", args: '{"q":"wea' } } }
|
|
141
|
+
* fields: { type: "tool_call_chunk", args: '{"q":"wea' } } }
|
|
117
142
|
*
|
|
118
143
|
* // Provider-specific field (e.g., signature)
|
|
119
144
|
* { event: "content-block-delta", index: 0,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.d.ts","names":[],"sources":["../../src/language_models/event.ts"],"mappings":";;;;;;iBA8CiB;EACf;;EAEA;;;;;EAKA,QAAQ,QAAQ;;;;;;;;;;YAWN;;;;iBAKK;EACf;;EAEA,SAAS;;EAET,QAAQ,QAAQ;;EAEhB,mBAAmB;;;;;;;;;;;iBAeJ;EACf;;EAEA;;EAEA,SAAS;;;;;iBAQM;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;;EAEA;;;;;;iBAOe;EACf;;EAEA;IAAU;MAAiB;;;;;YAMjB,oBACR,YACA,iBACA,YACA
|
|
1
|
+
{"version":3,"file":"event.d.ts","names":[],"sources":["../../src/language_models/event.ts"],"mappings":";;;;;;iBA8CiB;EACf;;EAEA;;;;;EAKA,QAAQ,QAAQ;;;;;;;;;;YAWN;;;;iBAKK;EACf;;EAEA,SAAS;;EAET,QAAQ,QAAQ;;EAEhB,mBAAmB;;;;;;;;;;;iBAeJ;EACf;;EAEA;;EAEA,SAAS;;;;;iBAQM;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;;EAEA;;;;;;;;;;iBAWe;EACf;;EAEA;;;;;;iBAOe;EACf;;EAEA;IAAU;MAAiB;;;;;YAMjB,oBACR,YACA,iBACA,YACA,gBACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyCa;EACf;;EAEA;;EAEA,OAAO;;;;;;;;;;;iBAYQ;EACf;;EAEA;;EAEA,SAAS;;;;;;iBASM;EACf;;EAEA,OAAO,QAAQ;;;;;iBAQA;EACf;;EAEA;;EAEA;;EAEA;;;;;iBAQe;EACf;;EAEA;;EAEA;;;;;YAQU,uBACR,oBACA,qBACA,yBACA,yBACA,0BACA,mBACA,gBACA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.js","names":[],"sources":["../../src/language_models/event.ts"],"sourcesContent":["/**\n * Chat model streaming event protocol.\n *\n * Defines a content-block-centric event model for streaming chat model responses.\n * Events carry LangChain {@link ContentBlock} types on lifecycle boundaries\n * and explicit delta variants for incremental updates during streaming.\n *\n * ## Design Principles\n *\n * 1. **Content-block deltas have explicit merge semantics.** Text,\n * reasoning, and data deltas append to named fields. Generic block deltas\n * shallow-merge fields onto the active content block.\n *\n * 2. **Lifecycle completeness.** Every streamable entity has explicit start and finish\n * events. Consumers never need to infer boundaries from absence of events.\n *\n * 3. **Interleaving allowed.** Content blocks may interleave (e.g., parallel tool calls).\n * The only invariant: a block's start precedes its deltas, and its deltas precede\n * its finish. No ordering constraint between different blocks.\n *\n * 4. **Provider passthrough.** Native provider events that don't map to standard types\n * are forwarded as {@link ProviderEvent} rather than silently dropped.\n *\n * ## Lifecycle Contract\n *\n * ```\n * MessageStart\n * -> ContentBlockStart(index=0, content=...)\n * -> ContentBlockDelta(index=0, delta={ type: \"text-delta\", text: \"Hello\" })\n * -> ContentBlockDelta(index=0, delta={ type: \"text-delta\", text: \" world\" })\n * -> ContentBlockFinish(index=0, content=...)\n * -> UsageUpdate(...)\n * -> MessageFinish(reason, usage?)\n * ```\n *\n * @module\n */\n\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\n\n// ─── Message Lifecycle ──────────────────────────────────────────\n\n/**\n * Emitted once at the start of a model response.\n */\nexport interface MessageStartEvent {\n event: \"message-start\";\n /** Optional message ID assigned by the provider. */\n id?: string;\n /**\n * Initial usage snapshot, if the provider reports input token counts\n * before content begins streaming (e.g., Anthropic's `message_start`).\n */\n usage?: Partial<UsageMetadata>;\n}\n\n/**\n * Finish reason for a model response.\n *\n * - `\"stop\"`: Natural end of generation.\n * - `\"length\"`: Hit max token limit.\n * - `\"tool_use\"`: Model is requesting tool execution.\n * - `\"content_filter\"`: Content was filtered by safety systems.\n */\nexport type FinishReason = \"stop\" | \"length\" | \"tool_use\" | \"content_filter\";\n\n/**\n * Emitted once when the model response is complete.\n */\nexport interface MessageFinishEvent {\n event: \"message-finish\";\n /** Why the model stopped generating. */\n reason?: FinishReason;\n /** Final usage snapshot. */\n usage?: Partial<UsageMetadata>;\n /** Provider-specific response metadata (model name, response ID, headers, etc.). */\n responseMetadata?: Record<string, unknown>;\n}\n\n// ─── Content Block Lifecycle ────────────────────────────────────\n// See https://github.com/langchain-ai/agent-protocol/blob/main/streaming/protocol.cddl\n\n/**\n * Emitted when a new content block begins streaming.\n *\n * @example\n * ```ts\n * { event: \"content-block-start\", index: 0,\n * content: { type: \"text\", text: \"\" } }\n * ```\n */\nexport interface ContentBlockStartEvent {\n event: \"content-block-start\";\n /** Positional index of this block within the message. */\n index: number;\n /** Initial state of the content block. */\n content: ContentBlock;\n}\n\n// ─── Content Block Deltas ───────────────────────────────────────\n\n/**\n * Incremental text content. Append `text` to the active block's `text` field.\n */\nexport interface TextDelta {\n type: \"text-delta\";\n /** The new text to append. */\n text: string;\n}\n\n/**\n * Incremental reasoning content. Append `reasoning` to the active block's\n * `reasoning` field.\n */\nexport interface ReasoningDelta {\n type: \"reasoning-delta\";\n /** The new reasoning text to append. */\n reasoning: string;\n}\n\n/**\n * Incremental encoded data. Append `data` to the active multimodal block's\n * data field.\n */\nexport interface DataDelta {\n type: \"data-delta\";\n /** Encoded data chunk to append. */\n data: string;\n /** Encoding for the data chunk. Defaults to `\"base64\"` when omitted. */\n encoding?: \"base64\";\n}\n\n/**\n * Generic content block field update. Shallow-merge `fields` onto the active\n * content block.\n */\nexport interface BlockDelta {\n type: \"block-delta\";\n /** Fields to shallow-merge onto the active content block. */\n fields: { type: string } & Record<string, unknown>;\n}\n\n/**\n * Union of all content block delta types.\n */\nexport type ContentBlockDelta =\n | TextDelta\n | ReasoningDelta\n | DataDelta\n | BlockDelta;\n\n/**\n * Emitted for each incremental update within a content block.\n *\n * The `delta` field carries the incremental content block update.\n * Accumulation rules:\n * - `text-delta` → append `text` to the active block's text field\n * - `reasoning-delta` → append `reasoning` to the active block's reasoning field\n * - `data-delta` → append `data` to the active block's data field\n * - `block-delta` → shallow-merge `fields` onto the active block\n *\n * @example\n * ```ts\n * // Text token\n * { event: \"content-block-delta\", index: 0,\n * delta: { type: \"text-delta\", text: \" world\" } }\n *\n * // Tool call args snapshot\n * { event: \"content-block-delta\", index: 1,\n * delta: { type: \"block-delta\",\n * fields: { type: \"tool_call_chunk\", args: '{\"q\":\"wea' } } }
|
|
1
|
+
{"version":3,"file":"event.js","names":[],"sources":["../../src/language_models/event.ts"],"sourcesContent":["/**\n * Chat model streaming event protocol.\n *\n * Defines a content-block-centric event model for streaming chat model responses.\n * Events carry LangChain {@link ContentBlock} types on lifecycle boundaries\n * and explicit delta variants for incremental updates during streaming.\n *\n * ## Design Principles\n *\n * 1. **Content-block deltas have explicit merge semantics.** Text,\n * reasoning, and data deltas append to named fields. Generic block deltas\n * shallow-merge fields onto the active content block.\n *\n * 2. **Lifecycle completeness.** Every streamable entity has explicit start and finish\n * events. Consumers never need to infer boundaries from absence of events.\n *\n * 3. **Interleaving allowed.** Content blocks may interleave (e.g., parallel tool calls).\n * The only invariant: a block's start precedes its deltas, and its deltas precede\n * its finish. No ordering constraint between different blocks.\n *\n * 4. **Provider passthrough.** Native provider events that don't map to standard types\n * are forwarded as {@link ProviderEvent} rather than silently dropped.\n *\n * ## Lifecycle Contract\n *\n * ```\n * MessageStart\n * -> ContentBlockStart(index=0, content=...)\n * -> ContentBlockDelta(index=0, delta={ type: \"text-delta\", text: \"Hello\" })\n * -> ContentBlockDelta(index=0, delta={ type: \"text-delta\", text: \" world\" })\n * -> ContentBlockFinish(index=0, content=...)\n * -> UsageUpdate(...)\n * -> MessageFinish(reason, usage?)\n * ```\n *\n * @module\n */\n\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\n\n// ─── Message Lifecycle ──────────────────────────────────────────\n\n/**\n * Emitted once at the start of a model response.\n */\nexport interface MessageStartEvent {\n event: \"message-start\";\n /** Optional message ID assigned by the provider. */\n id?: string;\n /**\n * Initial usage snapshot, if the provider reports input token counts\n * before content begins streaming (e.g., Anthropic's `message_start`).\n */\n usage?: Partial<UsageMetadata>;\n}\n\n/**\n * Finish reason for a model response.\n *\n * - `\"stop\"`: Natural end of generation.\n * - `\"length\"`: Hit max token limit.\n * - `\"tool_use\"`: Model is requesting tool execution.\n * - `\"content_filter\"`: Content was filtered by safety systems.\n */\nexport type FinishReason = \"stop\" | \"length\" | \"tool_use\" | \"content_filter\";\n\n/**\n * Emitted once when the model response is complete.\n */\nexport interface MessageFinishEvent {\n event: \"message-finish\";\n /** Why the model stopped generating. */\n reason?: FinishReason;\n /** Final usage snapshot. */\n usage?: Partial<UsageMetadata>;\n /** Provider-specific response metadata (model name, response ID, headers, etc.). */\n responseMetadata?: Record<string, unknown>;\n}\n\n// ─── Content Block Lifecycle ────────────────────────────────────\n// See https://github.com/langchain-ai/agent-protocol/blob/main/streaming/protocol.cddl\n\n/**\n * Emitted when a new content block begins streaming.\n *\n * @example\n * ```ts\n * { event: \"content-block-start\", index: 0,\n * content: { type: \"text\", text: \"\" } }\n * ```\n */\nexport interface ContentBlockStartEvent {\n event: \"content-block-start\";\n /** Positional index of this block within the message. */\n index: number;\n /** Initial state of the content block. */\n content: ContentBlock;\n}\n\n// ─── Content Block Deltas ───────────────────────────────────────\n\n/**\n * Incremental text content. Append `text` to the active block's `text` field.\n */\nexport interface TextDelta {\n type: \"text-delta\";\n /** The new text to append. */\n text: string;\n}\n\n/**\n * Incremental reasoning content. Append `reasoning` to the active block's\n * `reasoning` field.\n */\nexport interface ReasoningDelta {\n type: \"reasoning-delta\";\n /** The new reasoning text to append. */\n reasoning: string;\n}\n\n/**\n * Incremental encoded data. Append `data` to the active multimodal block's\n * data field.\n */\nexport interface DataDelta {\n type: \"data-delta\";\n /** Encoded data chunk to append. */\n data: string;\n /** Encoding for the data chunk. Defaults to `\"base64\"` when omitted. */\n encoding?: \"base64\";\n}\n\n/**\n * Incremental tool-call arguments. Append `args` to the active\n * `tool_call_chunk` or `server_tool_call_chunk` block's `args` field, treating\n * missing args as an empty string.\n *\n * A slice need not be valid JSON on its own. The call's `id` and `name` arrive\n * on `content-block-start`, and `content-block-finish` carries the parsed call.\n */\nexport interface ToolCallDelta {\n type: \"tool-call-delta\";\n /** The new slice of the call's arguments string to append. */\n args: string;\n}\n\n/**\n * Generic content block field update. Shallow-merge `fields` onto the active\n * content block.\n */\nexport interface BlockDelta {\n type: \"block-delta\";\n /** Fields to shallow-merge onto the active content block. */\n fields: { type: string } & Record<string, unknown>;\n}\n\n/**\n * Union of all content block delta types.\n */\nexport type ContentBlockDelta =\n | TextDelta\n | ReasoningDelta\n | DataDelta\n | ToolCallDelta\n | BlockDelta;\n\n/**\n * Emitted for each incremental update within a content block.\n *\n * The `delta` field carries the incremental content block update.\n * Accumulation rules:\n * - `text-delta` → append `text` to the active block's text field\n * - `reasoning-delta` → append `reasoning` to the active block's reasoning field\n * - `data-delta` → append `data` to the active block's data field\n * - `tool-call-delta` → append `args` to the active tool-call block's args field\n * - `block-delta` → shallow-merge `fields` onto the active block\n *\n * Consumers ignore delta types they don't recognize.\n * `content-block-finish` carries the complete block.\n *\n * A tool call's args stream in one of two forms, never both in one block:\n * `tool-call-delta` slices, which append, or `block-delta` snapshots of the\n * args so far, which replace.\n *\n * @example\n * ```ts\n * // Text token\n * { event: \"content-block-delta\", index: 0,\n * delta: { type: \"text-delta\", text: \" world\" } }\n *\n * // Tool call args slice\n * { event: \"content-block-delta\", index: 1,\n * delta: { type: \"tool-call-delta\", args: '\"wea' } }\n *\n * // Tool call args snapshot\n * { event: \"content-block-delta\", index: 1,\n * delta: { type: \"block-delta\",\n * fields: { type: \"tool_call_chunk\", args: '{\"q\":\"wea' } } }\n *\n * // Provider-specific field (e.g., signature)\n * { event: \"content-block-delta\", index: 0,\n * delta: { type: \"block-delta\",\n * fields: { type: \"reasoning\", signature: \"sig_abc\" } } }\n * ```\n */\nexport interface ContentBlockDeltaEvent {\n event: \"content-block-delta\";\n /** Positional index of the block being updated. */\n index: number;\n /** Incremental content block delta. */\n delta: ContentBlockDelta;\n}\n\n/**\n * Emitted when a content block is complete.\n *\n * @example\n * ```ts\n * { event: \"content-block-finish\", index: 0,\n * content: { type: \"text\", text: \"Hello world\" } }\n * ```\n */\nexport interface ContentBlockFinishEvent {\n event: \"content-block-finish\";\n /** Positional index of the completed block. */\n index: number;\n /** Finalized content block. */\n content: ContentBlock;\n}\n\n// ─── Usage ──────────────────────────────────────────────────────\n\n/**\n * Emitted whenever the provider reports updated usage information.\n * Each event carries a **running snapshot** (not an additive delta).\n */\nexport interface UsageUpdateEvent {\n event: \"usage\";\n /** Current usage snapshot. */\n usage: Partial<UsageMetadata>;\n}\n\n// ─── Provider Passthrough ───────────────────────────────────────\n\n/**\n * Passthrough for native provider events that don't map to standard types.\n */\nexport interface ProviderEvent {\n event: \"provider\";\n /** Provider identifier (e.g., `\"openai\"`, `\"anthropic\"`, `\"google\"`). */\n provider: string;\n /** Raw event type name from the provider SDK. */\n name: string;\n /** Raw event payload from the provider SDK. */\n payload: unknown;\n}\n\n// ─── Error ──────────────────────────────────────────────────────\n\n/**\n * Emitted on unrecoverable stream errors.\n */\nexport interface StreamErrorEvent {\n event: \"error\";\n /** Human-readable error message. */\n message: string;\n /** Optional error code for programmatic handling. */\n code?: string;\n}\n\n// ─── Union ──────────────────────────────────────────────────────\n\n/**\n * Union of all chat model stream event types.\n */\nexport type ChatModelStreamEvent =\n | MessageStartEvent\n | MessageFinishEvent\n | ContentBlockStartEvent\n | ContentBlockDeltaEvent\n | ContentBlockFinishEvent\n | UsageUpdateEvent\n | ProviderEvent\n | StreamErrorEvent;\n"],"mappings":""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"profile.cjs","names":[],"sources":["../../src/language_models/profile.ts"],"sourcesContent":["/**\n * Represents the capabilities and constraints of a language model.\n *\n * This interface defines the various features and limitations that a model may have,\n * including input/output constraints, multimodal support, and advanced capabilities\n * like tool calling and structured output.\n */\nexport interface ModelProfile {\n /**\n * Maximum number of tokens that can be included in the input context window.\n *\n * This represents the total token budget for the model's input, including\n * the prompt, system messages, conversation history, and any other context.\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxInputTokens: 128000 // Model supports up to 128k tokens\n * };\n * ```\n */\n maxInputTokens?: number;\n\n /**\n * Whether the model supports image inputs.\n *\n * When `true`, the model can process images as part of its input, enabling\n * multimodal interactions where visual content can be analyzed alongside text.\n *\n * @see {@link imageUrlInputs} for URL-based image input support\n */\n imageInputs?: boolean;\n\n /**\n * Whether the model supports image URL inputs.\n *\n * When `true`, the model can accept URLs pointing to images rather than\n * requiring the image data to be embedded directly in the request. This can\n * be more efficient for large images or when images are already hosted.\n *\n * @see {@link imageInputs} for direct image input support\n */\n imageUrlInputs?: boolean;\n\n /**\n * Whether the model supports PDF document inputs.\n *\n * When `true`, the model can process PDF files as input, allowing it to\n * analyze document content, extract information, or answer questions about\n * PDF documents.\n */\n pdfInputs?: boolean;\n\n /**\n * Whether the model supports audio inputs.\n *\n * When `true`, the model can process audio data as input, enabling\n * capabilities like speech recognition, audio analysis, or multimodal\n * interactions involving sound.\n */\n audioInputs?: boolean;\n\n /**\n * Whether the model supports video inputs.\n *\n * When `true`, the model can process video data as input, enabling\n * capabilities like video analysis, scene understanding, or multimodal\n * interactions involving moving images.\n */\n videoInputs?: boolean;\n\n /**\n * MIME types the model accepts as generic file inputs.\n *\n * Covers file types beyond those with dedicated flags (e.g. {@link pdfInputs}),\n * such as office documents, source code, or plain text. When undefined, the\n * model's support for generic file inputs is unknown.\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * fileMimeTypes: [\"text/plain\", \"text/csv\", \"application/json\"]\n * };\n * ```\n */\n fileMimeTypes?: readonly string[];\n\n /**\n * Whether the model supports image content in tool messages.\n *\n * When `true`, tool responses can include images that the model can process\n * and reason about. This enables workflows where tools return visual data\n * that the model needs to interpret.\n */\n imageToolMessage?: boolean;\n\n /**\n * Whether the model supports PDF content in tool messages.\n *\n * When `true`, tool responses can include PDF documents that the model can\n * process and reason about. This enables workflows where tools return\n * document data that the model needs to interpret.\n */\n pdfToolMessage?: boolean;\n\n /**\n * Maximum number of tokens the model can generate in its output.\n *\n * This represents the upper limit on the length of the model's response.\n * The actual output may be shorter depending on the completion criteria\n * (e.g., natural stopping point, stop sequences).\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxOutputTokens: 4096 // Model can generate up to 4k tokens\n * };\n * ```\n */\n maxOutputTokens?: number;\n\n /**\n * Whether the model supports reasoning or chain-of-thought output.\n *\n * When `true`, the model can produce explicit reasoning steps or\n * chain-of-thought explanations as part of its output. This is useful\n * for understanding the model's decision-making process and improving\n * transparency in complex reasoning tasks.\n */\n reasoningOutput?: boolean;\n\n /**\n * Whether the model can generate image outputs.\n *\n * When `true`, the model can produce images as part of its response,\n * enabling capabilities like image generation, editing, or visual\n * content creation.\n */\n imageOutputs?: boolean;\n\n /**\n * Whether the model can generate audio outputs.\n *\n * When `true`, the model can produce audio data as part of its response,\n * enabling capabilities like text-to-speech, audio generation, or\n * sound synthesis.\n */\n audioOutputs?: boolean;\n\n /**\n * Whether the model can generate video outputs.\n *\n * When `true`, the model can produce video data as part of its response,\n * enabling capabilities like video generation, editing, or visual\n * content creation with motion.\n */\n videoOutputs?: boolean;\n\n /**\n * Whether the model supports tool calling (function calling).\n *\n * When `true`, the model can invoke external tools or functions during\n * its reasoning process. The model can decide which tools to call,\n * with what arguments, and can incorporate the tool results into its\n * final response.\n *\n * @see {@link toolChoice} for controlling tool selection behavior\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/models#tool-calling}\n */\n toolCalling?: boolean;\n\n /**\n * Whether the model supports tool choice control.\n *\n * When `true`, the caller can specify how the model should select tools,\n * such as forcing the use of a specific tool, allowing any tool, or\n * preventing tool use entirely. This provides fine-grained control over\n * the model's tool-calling behavior.\n *\n * @see {@link toolCalling} for basic tool calling support\n */\n toolChoice?: boolean;\n\n /**\n * Whether the model supports structured output generation.\n *\n * When `true`, the model can generate responses that conform to a\n * specified schema or structure (e.g., JSON with a particular format).\n * This is useful for ensuring the model's output can be reliably parsed\n * and processed programmatically.\n *\n * @example\n * ```typescript\n * // Model can be instructed to return JSON matching a schema\n * const profile: ModelProfile = {\n * structuredOutput: true\n * };\n * ```\n */\n structuredOutput?: boolean;\n}\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"profile.cjs","names":[],"sources":["../../src/language_models/profile.ts"],"sourcesContent":["/**\n * Represents the capabilities and constraints of a language model.\n *\n * This interface defines the various features and limitations that a model may have,\n * including input/output constraints, multimodal support, and advanced capabilities\n * like tool calling and structured output.\n */\nexport interface ModelProfile {\n /**\n * Maximum number of tokens that can be included in the input context window.\n *\n * This represents the total token budget for the model's input, including\n * the prompt, system messages, conversation history, and any other context.\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxInputTokens: 128000 // Model supports up to 128k tokens\n * };\n * ```\n */\n maxInputTokens?: number;\n\n /**\n * Whether the model supports image inputs.\n *\n * When `true`, the model can process images as part of its input, enabling\n * multimodal interactions where visual content can be analyzed alongside text.\n *\n * @see {@link imageUrlInputs} for URL-based image input support\n */\n imageInputs?: boolean;\n\n /**\n * Whether the model supports image URL inputs.\n *\n * When `true`, the model can accept URLs pointing to images rather than\n * requiring the image data to be embedded directly in the request. This can\n * be more efficient for large images or when images are already hosted.\n *\n * @see {@link imageInputs} for direct image input support\n */\n imageUrlInputs?: boolean;\n\n /**\n * Whether the model supports PDF document inputs.\n *\n * When `true`, the model can process PDF files as input, allowing it to\n * analyze document content, extract information, or answer questions about\n * PDF documents.\n */\n pdfInputs?: boolean;\n\n /**\n * Whether the model supports audio inputs.\n *\n * When `true`, the model can process audio data as input, enabling\n * capabilities like speech recognition, audio analysis, or multimodal\n * interactions involving sound.\n */\n audioInputs?: boolean;\n\n /**\n * Whether the model supports video inputs.\n *\n * When `true`, the model can process video data as input, enabling\n * capabilities like video analysis, scene understanding, or multimodal\n * interactions involving moving images.\n */\n videoInputs?: boolean;\n\n /**\n * MIME types the model accepts as generic file inputs.\n *\n * Covers file types beyond those with dedicated flags (e.g. {@link pdfInputs}),\n * such as office documents, source code, or plain text. When undefined, the\n * model's support for generic file inputs is unknown.\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * fileMimeTypes: [\"text/plain\", \"text/csv\", \"application/json\"]\n * };\n * ```\n */\n fileMimeTypes?: readonly string[];\n\n /**\n * Whether the model supports image content in tool messages.\n *\n * When `true`, tool responses can include images that the model can process\n * and reason about. This enables workflows where tools return visual data\n * that the model needs to interpret.\n */\n imageToolMessage?: boolean;\n\n /**\n * Whether the model supports PDF content in tool messages.\n *\n * When `true`, tool responses can include PDF documents that the model can\n * process and reason about. This enables workflows where tools return\n * document data that the model needs to interpret.\n */\n pdfToolMessage?: boolean;\n\n /**\n * Maximum number of tokens the model can generate in its output.\n *\n * This represents the upper limit on the length of the model's response.\n * The actual output may be shorter depending on the completion criteria\n * (e.g., natural stopping point, stop sequences).\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxOutputTokens: 4096 // Model can generate up to 4k tokens\n * };\n * ```\n */\n maxOutputTokens?: number;\n\n /**\n * Whether the model supports reasoning or chain-of-thought output.\n *\n * When `true`, the model can produce explicit reasoning steps or\n * chain-of-thought explanations as part of its output. This is useful\n * for understanding the model's decision-making process and improving\n * transparency in complex reasoning tasks.\n */\n reasoningOutput?: boolean;\n\n /**\n * Whether the model can generate image outputs.\n *\n * When `true`, the model can produce images as part of its response,\n * enabling capabilities like image generation, editing, or visual\n * content creation.\n */\n imageOutputs?: boolean;\n\n /**\n * Whether the model can generate audio outputs.\n *\n * When `true`, the model can produce audio data as part of its response,\n * enabling capabilities like text-to-speech, audio generation, or\n * sound synthesis.\n */\n audioOutputs?: boolean;\n\n /**\n * Whether the model can generate video outputs.\n *\n * When `true`, the model can produce video data as part of its response,\n * enabling capabilities like video generation, editing, or visual\n * content creation with motion.\n */\n videoOutputs?: boolean;\n\n /**\n * Whether the model supports tool calling (function calling).\n *\n * When `true`, the model can invoke external tools or functions during\n * its reasoning process. The model can decide which tools to call,\n * with what arguments, and can incorporate the tool results into its\n * final response.\n *\n * @see {@link toolChoice} for controlling tool selection behavior\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/models#tool-calling}\n */\n toolCalling?: boolean;\n\n /**\n * Whether the model supports tool choice control.\n *\n * When `true`, the caller can specify how the model should select tools,\n * such as forcing the use of a specific tool, allowing any tool, or\n * preventing tool use entirely. This provides fine-grained control over\n * the model's tool-calling behavior.\n *\n * @see {@link toolCalling} for basic tool calling support\n */\n toolChoice?: boolean;\n\n /**\n * Whether a system message after the first turn is sent where it sits.\n *\n * When `true`, the instruction applies from its position onwards, and the\n * prompt prefix before it stays unchanged. Absent or `false` means the chat\n * model may move it into the leading system prompt, or the provider may\n * reject it.\n */\n midConversationSystemMessages?: boolean;\n\n /**\n * Whether tools can be added mid-conversation.\n *\n * The tool is added through a message rather than the request's tool list,\n * so the prompt prefix before it stays unchanged. Implies\n * {@link midConversationSystemMessages}.\n *\n * The message format is provider-specific. Every provider that sets this\n * accepts a tool's full definition; some also accept a reference to a tool\n * already in the request, or can remove a tool.\n */\n midConversationTools?: boolean;\n\n /**\n * Whether the model supports structured output generation.\n *\n * When `true`, the model can generate responses that conform to a\n * specified schema or structure (e.g., JSON with a particular format).\n * This is useful for ensuring the model's output can be reliably parsed\n * and processed programmatically.\n *\n * @example\n * ```typescript\n * // Model can be instructed to return JSON matching a schema\n * const profile: ModelProfile = {\n * structuredOutput: true\n * };\n * ```\n */\n structuredOutput?: boolean;\n}\n"],"mappings":""}
|
|
@@ -166,6 +166,27 @@ export interface ModelProfile {
|
|
|
166
166
|
* @see {@link toolCalling} for basic tool calling support
|
|
167
167
|
*/
|
|
168
168
|
toolChoice?: boolean;
|
|
169
|
+
/**
|
|
170
|
+
* Whether a system message after the first turn is sent where it sits.
|
|
171
|
+
*
|
|
172
|
+
* When `true`, the instruction applies from its position onwards, and the
|
|
173
|
+
* prompt prefix before it stays unchanged. Absent or `false` means the chat
|
|
174
|
+
* model may move it into the leading system prompt, or the provider may
|
|
175
|
+
* reject it.
|
|
176
|
+
*/
|
|
177
|
+
midConversationSystemMessages?: boolean;
|
|
178
|
+
/**
|
|
179
|
+
* Whether tools can be added mid-conversation.
|
|
180
|
+
*
|
|
181
|
+
* The tool is added through a message rather than the request's tool list,
|
|
182
|
+
* so the prompt prefix before it stays unchanged. Implies
|
|
183
|
+
* {@link midConversationSystemMessages}.
|
|
184
|
+
*
|
|
185
|
+
* The message format is provider-specific. Every provider that sets this
|
|
186
|
+
* accepts a tool's full definition; some also accept a reference to a tool
|
|
187
|
+
* already in the request, or can remove a tool.
|
|
188
|
+
*/
|
|
189
|
+
midConversationTools?: boolean;
|
|
169
190
|
/**
|
|
170
191
|
* Whether the model supports structured output generation.
|
|
171
192
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"profile.d.cts","names":[],"sources":["../../src/language_models/profile.ts"],"mappings":";;;;;;;;iBAOiB;;;;;;;;;;;;;;EAcf;;;;;;;;;EAUA;;;;;;;;;;EAWA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;;;;EAgBA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;;;;EAgBA;;;;;;;;;EAUA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;EAaA;;;;;;;;;;;EAYA;;;;;;;;;;;;;;;;;EAkBA"}
|
|
1
|
+
{"version":3,"file":"profile.d.cts","names":[],"sources":["../../src/language_models/profile.ts"],"mappings":";;;;;;;;iBAOiB;;;;;;;;;;;;;;EAcf;;;;;;;;;EAUA;;;;;;;;;;EAWA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;;;;EAgBA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;;;;EAgBA;;;;;;;;;EAUA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;EAaA;;;;;;;;;;;EAYA;;;;;;;;;EAUA;;;;;;;;;;;;EAaA;;;;;;;;;;;;;;;;;EAkBA"}
|
|
@@ -166,6 +166,27 @@ export interface ModelProfile {
|
|
|
166
166
|
* @see {@link toolCalling} for basic tool calling support
|
|
167
167
|
*/
|
|
168
168
|
toolChoice?: boolean;
|
|
169
|
+
/**
|
|
170
|
+
* Whether a system message after the first turn is sent where it sits.
|
|
171
|
+
*
|
|
172
|
+
* When `true`, the instruction applies from its position onwards, and the
|
|
173
|
+
* prompt prefix before it stays unchanged. Absent or `false` means the chat
|
|
174
|
+
* model may move it into the leading system prompt, or the provider may
|
|
175
|
+
* reject it.
|
|
176
|
+
*/
|
|
177
|
+
midConversationSystemMessages?: boolean;
|
|
178
|
+
/**
|
|
179
|
+
* Whether tools can be added mid-conversation.
|
|
180
|
+
*
|
|
181
|
+
* The tool is added through a message rather than the request's tool list,
|
|
182
|
+
* so the prompt prefix before it stays unchanged. Implies
|
|
183
|
+
* {@link midConversationSystemMessages}.
|
|
184
|
+
*
|
|
185
|
+
* The message format is provider-specific. Every provider that sets this
|
|
186
|
+
* accepts a tool's full definition; some also accept a reference to a tool
|
|
187
|
+
* already in the request, or can remove a tool.
|
|
188
|
+
*/
|
|
189
|
+
midConversationTools?: boolean;
|
|
169
190
|
/**
|
|
170
191
|
* Whether the model supports structured output generation.
|
|
171
192
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"profile.d.ts","names":[],"sources":["../../src/language_models/profile.ts"],"mappings":";;;;;;;;iBAOiB;;;;;;;;;;;;;;EAcf;;;;;;;;;EAUA;;;;;;;;;;EAWA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;;;;EAgBA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;;;;EAgBA;;;;;;;;;EAUA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;EAaA;;;;;;;;;;;EAYA;;;;;;;;;;;;;;;;;EAkBA"}
|
|
1
|
+
{"version":3,"file":"profile.d.ts","names":[],"sources":["../../src/language_models/profile.ts"],"mappings":";;;;;;;;iBAOiB;;;;;;;;;;;;;;EAcf;;;;;;;;;EAUA;;;;;;;;;;EAWA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;;;;EAgBA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;;;;EAgBA;;;;;;;;;EAUA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;EASA;;;;;;;;;;;;EAaA;;;;;;;;;;;EAYA;;;;;;;;;EAUA;;;;;;;;;;;;EAaA;;;;;;;;;;;;;;;;;EAkBA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"profile.js","names":[],"sources":["../../src/language_models/profile.ts"],"sourcesContent":["/**\n * Represents the capabilities and constraints of a language model.\n *\n * This interface defines the various features and limitations that a model may have,\n * including input/output constraints, multimodal support, and advanced capabilities\n * like tool calling and structured output.\n */\nexport interface ModelProfile {\n /**\n * Maximum number of tokens that can be included in the input context window.\n *\n * This represents the total token budget for the model's input, including\n * the prompt, system messages, conversation history, and any other context.\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxInputTokens: 128000 // Model supports up to 128k tokens\n * };\n * ```\n */\n maxInputTokens?: number;\n\n /**\n * Whether the model supports image inputs.\n *\n * When `true`, the model can process images as part of its input, enabling\n * multimodal interactions where visual content can be analyzed alongside text.\n *\n * @see {@link imageUrlInputs} for URL-based image input support\n */\n imageInputs?: boolean;\n\n /**\n * Whether the model supports image URL inputs.\n *\n * When `true`, the model can accept URLs pointing to images rather than\n * requiring the image data to be embedded directly in the request. This can\n * be more efficient for large images or when images are already hosted.\n *\n * @see {@link imageInputs} for direct image input support\n */\n imageUrlInputs?: boolean;\n\n /**\n * Whether the model supports PDF document inputs.\n *\n * When `true`, the model can process PDF files as input, allowing it to\n * analyze document content, extract information, or answer questions about\n * PDF documents.\n */\n pdfInputs?: boolean;\n\n /**\n * Whether the model supports audio inputs.\n *\n * When `true`, the model can process audio data as input, enabling\n * capabilities like speech recognition, audio analysis, or multimodal\n * interactions involving sound.\n */\n audioInputs?: boolean;\n\n /**\n * Whether the model supports video inputs.\n *\n * When `true`, the model can process video data as input, enabling\n * capabilities like video analysis, scene understanding, or multimodal\n * interactions involving moving images.\n */\n videoInputs?: boolean;\n\n /**\n * MIME types the model accepts as generic file inputs.\n *\n * Covers file types beyond those with dedicated flags (e.g. {@link pdfInputs}),\n * such as office documents, source code, or plain text. When undefined, the\n * model's support for generic file inputs is unknown.\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * fileMimeTypes: [\"text/plain\", \"text/csv\", \"application/json\"]\n * };\n * ```\n */\n fileMimeTypes?: readonly string[];\n\n /**\n * Whether the model supports image content in tool messages.\n *\n * When `true`, tool responses can include images that the model can process\n * and reason about. This enables workflows where tools return visual data\n * that the model needs to interpret.\n */\n imageToolMessage?: boolean;\n\n /**\n * Whether the model supports PDF content in tool messages.\n *\n * When `true`, tool responses can include PDF documents that the model can\n * process and reason about. This enables workflows where tools return\n * document data that the model needs to interpret.\n */\n pdfToolMessage?: boolean;\n\n /**\n * Maximum number of tokens the model can generate in its output.\n *\n * This represents the upper limit on the length of the model's response.\n * The actual output may be shorter depending on the completion criteria\n * (e.g., natural stopping point, stop sequences).\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxOutputTokens: 4096 // Model can generate up to 4k tokens\n * };\n * ```\n */\n maxOutputTokens?: number;\n\n /**\n * Whether the model supports reasoning or chain-of-thought output.\n *\n * When `true`, the model can produce explicit reasoning steps or\n * chain-of-thought explanations as part of its output. This is useful\n * for understanding the model's decision-making process and improving\n * transparency in complex reasoning tasks.\n */\n reasoningOutput?: boolean;\n\n /**\n * Whether the model can generate image outputs.\n *\n * When `true`, the model can produce images as part of its response,\n * enabling capabilities like image generation, editing, or visual\n * content creation.\n */\n imageOutputs?: boolean;\n\n /**\n * Whether the model can generate audio outputs.\n *\n * When `true`, the model can produce audio data as part of its response,\n * enabling capabilities like text-to-speech, audio generation, or\n * sound synthesis.\n */\n audioOutputs?: boolean;\n\n /**\n * Whether the model can generate video outputs.\n *\n * When `true`, the model can produce video data as part of its response,\n * enabling capabilities like video generation, editing, or visual\n * content creation with motion.\n */\n videoOutputs?: boolean;\n\n /**\n * Whether the model supports tool calling (function calling).\n *\n * When `true`, the model can invoke external tools or functions during\n * its reasoning process. The model can decide which tools to call,\n * with what arguments, and can incorporate the tool results into its\n * final response.\n *\n * @see {@link toolChoice} for controlling tool selection behavior\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/models#tool-calling}\n */\n toolCalling?: boolean;\n\n /**\n * Whether the model supports tool choice control.\n *\n * When `true`, the caller can specify how the model should select tools,\n * such as forcing the use of a specific tool, allowing any tool, or\n * preventing tool use entirely. This provides fine-grained control over\n * the model's tool-calling behavior.\n *\n * @see {@link toolCalling} for basic tool calling support\n */\n toolChoice?: boolean;\n\n /**\n * Whether the model supports structured output generation.\n *\n * When `true`, the model can generate responses that conform to a\n * specified schema or structure (e.g., JSON with a particular format).\n * This is useful for ensuring the model's output can be reliably parsed\n * and processed programmatically.\n *\n * @example\n * ```typescript\n * // Model can be instructed to return JSON matching a schema\n * const profile: ModelProfile = {\n * structuredOutput: true\n * };\n * ```\n */\n structuredOutput?: boolean;\n}\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"profile.js","names":[],"sources":["../../src/language_models/profile.ts"],"sourcesContent":["/**\n * Represents the capabilities and constraints of a language model.\n *\n * This interface defines the various features and limitations that a model may have,\n * including input/output constraints, multimodal support, and advanced capabilities\n * like tool calling and structured output.\n */\nexport interface ModelProfile {\n /**\n * Maximum number of tokens that can be included in the input context window.\n *\n * This represents the total token budget for the model's input, including\n * the prompt, system messages, conversation history, and any other context.\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxInputTokens: 128000 // Model supports up to 128k tokens\n * };\n * ```\n */\n maxInputTokens?: number;\n\n /**\n * Whether the model supports image inputs.\n *\n * When `true`, the model can process images as part of its input, enabling\n * multimodal interactions where visual content can be analyzed alongside text.\n *\n * @see {@link imageUrlInputs} for URL-based image input support\n */\n imageInputs?: boolean;\n\n /**\n * Whether the model supports image URL inputs.\n *\n * When `true`, the model can accept URLs pointing to images rather than\n * requiring the image data to be embedded directly in the request. This can\n * be more efficient for large images or when images are already hosted.\n *\n * @see {@link imageInputs} for direct image input support\n */\n imageUrlInputs?: boolean;\n\n /**\n * Whether the model supports PDF document inputs.\n *\n * When `true`, the model can process PDF files as input, allowing it to\n * analyze document content, extract information, or answer questions about\n * PDF documents.\n */\n pdfInputs?: boolean;\n\n /**\n * Whether the model supports audio inputs.\n *\n * When `true`, the model can process audio data as input, enabling\n * capabilities like speech recognition, audio analysis, or multimodal\n * interactions involving sound.\n */\n audioInputs?: boolean;\n\n /**\n * Whether the model supports video inputs.\n *\n * When `true`, the model can process video data as input, enabling\n * capabilities like video analysis, scene understanding, or multimodal\n * interactions involving moving images.\n */\n videoInputs?: boolean;\n\n /**\n * MIME types the model accepts as generic file inputs.\n *\n * Covers file types beyond those with dedicated flags (e.g. {@link pdfInputs}),\n * such as office documents, source code, or plain text. When undefined, the\n * model's support for generic file inputs is unknown.\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * fileMimeTypes: [\"text/plain\", \"text/csv\", \"application/json\"]\n * };\n * ```\n */\n fileMimeTypes?: readonly string[];\n\n /**\n * Whether the model supports image content in tool messages.\n *\n * When `true`, tool responses can include images that the model can process\n * and reason about. This enables workflows where tools return visual data\n * that the model needs to interpret.\n */\n imageToolMessage?: boolean;\n\n /**\n * Whether the model supports PDF content in tool messages.\n *\n * When `true`, tool responses can include PDF documents that the model can\n * process and reason about. This enables workflows where tools return\n * document data that the model needs to interpret.\n */\n pdfToolMessage?: boolean;\n\n /**\n * Maximum number of tokens the model can generate in its output.\n *\n * This represents the upper limit on the length of the model's response.\n * The actual output may be shorter depending on the completion criteria\n * (e.g., natural stopping point, stop sequences).\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxOutputTokens: 4096 // Model can generate up to 4k tokens\n * };\n * ```\n */\n maxOutputTokens?: number;\n\n /**\n * Whether the model supports reasoning or chain-of-thought output.\n *\n * When `true`, the model can produce explicit reasoning steps or\n * chain-of-thought explanations as part of its output. This is useful\n * for understanding the model's decision-making process and improving\n * transparency in complex reasoning tasks.\n */\n reasoningOutput?: boolean;\n\n /**\n * Whether the model can generate image outputs.\n *\n * When `true`, the model can produce images as part of its response,\n * enabling capabilities like image generation, editing, or visual\n * content creation.\n */\n imageOutputs?: boolean;\n\n /**\n * Whether the model can generate audio outputs.\n *\n * When `true`, the model can produce audio data as part of its response,\n * enabling capabilities like text-to-speech, audio generation, or\n * sound synthesis.\n */\n audioOutputs?: boolean;\n\n /**\n * Whether the model can generate video outputs.\n *\n * When `true`, the model can produce video data as part of its response,\n * enabling capabilities like video generation, editing, or visual\n * content creation with motion.\n */\n videoOutputs?: boolean;\n\n /**\n * Whether the model supports tool calling (function calling).\n *\n * When `true`, the model can invoke external tools or functions during\n * its reasoning process. The model can decide which tools to call,\n * with what arguments, and can incorporate the tool results into its\n * final response.\n *\n * @see {@link toolChoice} for controlling tool selection behavior\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/models#tool-calling}\n */\n toolCalling?: boolean;\n\n /**\n * Whether the model supports tool choice control.\n *\n * When `true`, the caller can specify how the model should select tools,\n * such as forcing the use of a specific tool, allowing any tool, or\n * preventing tool use entirely. This provides fine-grained control over\n * the model's tool-calling behavior.\n *\n * @see {@link toolCalling} for basic tool calling support\n */\n toolChoice?: boolean;\n\n /**\n * Whether a system message after the first turn is sent where it sits.\n *\n * When `true`, the instruction applies from its position onwards, and the\n * prompt prefix before it stays unchanged. Absent or `false` means the chat\n * model may move it into the leading system prompt, or the provider may\n * reject it.\n */\n midConversationSystemMessages?: boolean;\n\n /**\n * Whether tools can be added mid-conversation.\n *\n * The tool is added through a message rather than the request's tool list,\n * so the prompt prefix before it stays unchanged. Implies\n * {@link midConversationSystemMessages}.\n *\n * The message format is provider-specific. Every provider that sets this\n * accepts a tool's full definition; some also accept a reference to a tool\n * already in the request, or can remove a tool.\n */\n midConversationTools?: boolean;\n\n /**\n * Whether the model supports structured output generation.\n *\n * When `true`, the model can generate responses that conform to a\n * specified schema or structure (e.g., JSON with a particular format).\n * This is useful for ensuring the model's output can be reliably parsed\n * and processed programmatically.\n *\n * @example\n * ```typescript\n * // Model can be instructed to return JSON matching a schema\n * const profile: ModelProfile = {\n * structuredOutput: true\n * };\n * ```\n */\n structuredOutput?: boolean;\n}\n"],"mappings":""}
|
|
@@ -75,6 +75,7 @@ var ReplayBuffer = class {
|
|
|
75
75
|
* - `text-delta` → append text
|
|
76
76
|
* - `reasoning-delta` → append reasoning text
|
|
77
77
|
* - `data-delta` → append encoded data to `data`
|
|
78
|
+
* - `tool-call-delta` → append tool-call args
|
|
78
79
|
* - `block-delta` → shallow merge fields
|
|
79
80
|
*
|
|
80
81
|
* @internal
|
|
@@ -101,11 +102,17 @@ function applyDelta(block, delta) {
|
|
|
101
102
|
...block,
|
|
102
103
|
data: (block.data ?? "") + delta.data
|
|
103
104
|
};
|
|
105
|
+
case "tool-call-delta":
|
|
106
|
+
if (block.type === "tool_call_chunk" || block.type === "server_tool_call_chunk") return {
|
|
107
|
+
...block,
|
|
108
|
+
args: (block.args ?? "") + delta.args
|
|
109
|
+
};
|
|
110
|
+
return block;
|
|
104
111
|
case "block-delta": return {
|
|
105
112
|
...block,
|
|
106
113
|
...delta.fields
|
|
107
114
|
};
|
|
108
|
-
default:
|
|
115
|
+
default: return block;
|
|
109
116
|
}
|
|
110
117
|
}
|
|
111
118
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.cjs","names":["AIMessage"],"sources":["../../src/language_models/stream.ts"],"sourcesContent":["/**\n * Typed stream classes for chat model streaming.\n *\n * @module\n */\n\nimport { AIMessage } from \"../messages/ai.js\";\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\nimport type { ChatModelStreamEvent, ContentBlockDelta } from \"./event.js\";\n\ntype UsageMetadataLike = Partial<UsageMetadata>;\n\n/**\n * A buffer that caches emitted events for replay.\n *\n * Multiple consumers can independently iterate the same buffer —\n * each gets its own cursor. Events are never consumed or removed.\n *\n * @internal\n */\nclass ReplayBuffer {\n private events: ChatModelStreamEvent[] = [];\n private finished = false;\n private waiters: Array<() => void> = [];\n private error: Error | null = null;\n\n push(event: ChatModelStreamEvent): void {\n this.events.push(event);\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n finish(): void {\n this.finished = true;\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n setError(err: Error): void {\n this.error = err;\n this.finished = true;\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n async *iterate(): AsyncGenerator<ChatModelStreamEvent> {\n if (this.finished) {\n if (this.error) throw this.error;\n yield* this.events;\n return;\n }\n\n let cursor = 0;\n while (true) {\n while (cursor < this.events.length) {\n yield this.events[cursor]!;\n cursor++;\n }\n if (this.finished) {\n if (this.error) throw this.error;\n return;\n }\n await new Promise<void>((resolve) => {\n if (cursor < this.events.length || this.finished) {\n resolve();\n return;\n }\n this.waiters.push(resolve);\n });\n }\n }\n}\n\n/**\n * Apply a typed delta to an accumulated content block.\n *\n * - `text-delta` → append text\n * - `reasoning-delta` → append reasoning text\n * - `data-delta` → append encoded data to `data`\n * - `block-delta` → shallow merge fields\n *\n * @internal\n */\nfunction applyDelta(\n block: ContentBlock,\n delta: ContentBlockDelta\n): ContentBlock {\n switch (delta.type) {\n case \"text-delta\":\n if (block.type === \"text\") {\n return {\n ...block,\n text: (block.text ?? \"\") + delta.text,\n };\n }\n return block;\n case \"reasoning-delta\":\n if (block.type === \"thinking\") {\n return {\n ...block,\n thinking: (block.thinking ?? \"\") + delta.reasoning,\n };\n }\n if (block.type === \"reasoning\") {\n return {\n ...block,\n reasoning: (block.reasoning ?? \"\") + delta.reasoning,\n };\n }\n return block;\n case \"data-delta\":\n return {\n ...block,\n data: (block.data ?? \"\") + delta.data,\n };\n case \"block-delta\":\n return { ...block, ...delta.fields } as ContentBlock;\n default:\n throw new Error(`Unknown delta type: ${JSON.stringify(delta)}`);\n }\n}\n\n/**\n * Returns the typed delta carried by a content-block delta event.\n *\n * Stream protocol compliant language models store incremental updates in\n * `event.delta`, e.g. `{ type: \"text-delta\", text: \"hello\" }`. Some models and\n * adapters still emit the older content-shaped form on `event.content`, e.g.\n * `{ type: \"text\", text: \"hello\" }`, which predates explicit delta event\n * variants.\n *\n * Keep accepting that content-shaped form here so {@link ChatModelStream}\n * remains a tolerant consumer while producers migrate to protocol compliant\n * typed deltas.\n *\n * @internal\n */\nfunction getEventDelta(\n event: ChatModelStreamEvent\n): ContentBlockDelta | undefined {\n if (event.event !== \"content-block-delta\") return undefined;\n if (\"delta\" in event && event.delta) return event.delta;\n\n const content = (event as { content?: unknown }).content;\n if (content == null || typeof content !== \"object\") return undefined;\n const block = content as { type?: string } & Record<string, unknown>;\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { type: \"text-delta\", text: block.text };\n }\n if (block.type === \"reasoning\" && typeof block.reasoning === \"string\") {\n return { type: \"reasoning-delta\", reasoning: block.reasoning };\n }\n if (block.type === \"thinking\" && typeof block.thinking === \"string\") {\n return { type: \"reasoning-delta\", reasoning: block.thinking };\n }\n if (typeof block.data === \"string\") {\n return { type: \"data-delta\", data: block.data, encoding: \"base64\" };\n }\n if (typeof block.type === \"string\") {\n return { type: \"block-delta\", fields: { ...block, type: block.type } };\n }\n return undefined;\n}\n\nfunction getReasoningDelta(content: unknown): string | undefined {\n if (content == null || typeof content !== \"object\") return undefined;\n const block = content as {\n type?: string;\n reasoning?: unknown;\n thinking?: unknown;\n };\n if (block.type === \"reasoning\" && typeof block.reasoning === \"string\") {\n return block.reasoning;\n }\n if (block.type === \"thinking\" && typeof block.thinking === \"string\") {\n return block.thinking;\n }\n return undefined;\n}\n\nfunction isReasoningContent(content: unknown): boolean {\n if (content == null || typeof content !== \"object\") return false;\n const type = (content as { type?: unknown }).type;\n return type === \"reasoning\" || type === \"thinking\";\n}\n\n/**\n * Normalize protocol-compatible partial usage into Core's concrete usage shape.\n *\n * Some stream sources emit usage snapshots without every aggregate token field.\n * Keep the stream event input permissive, then normalize at read time so\n * high-level Core consumers always receive a complete {@link UsageMetadata}.\n */\nfunction normalizeUsage(\n usage: UsageMetadataLike | undefined\n): UsageMetadata | undefined {\n if (!usage) return undefined;\n return {\n ...usage,\n input_tokens: usage.input_tokens ?? 0,\n output_tokens: usage.output_tokens ?? 0,\n total_tokens: usage.total_tokens ?? 0,\n };\n}\n\nfunction parseToolArgs(value: unknown): Record<string, unknown> {\n if (value != null && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n if (typeof value !== \"string\" || value.length === 0) return {};\n try {\n const parsed = JSON.parse(value);\n return parsed != null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction standardizeToolBlock(block: ContentBlock): ContentBlock {\n const record = block as Record<string, unknown>;\n if (block.type === \"tool_call\") return block;\n if (\n block.type !== \"tool_call_chunk\" &&\n block.type !== \"tool_use\" &&\n block.type !== \"input_json_delta\"\n ) {\n return block;\n }\n\n const name = typeof record.name === \"string\" ? record.name : undefined;\n if (name == null) return block;\n\n const args = record.args ?? record.input;\n return {\n ...record,\n type: \"tool_call\",\n name,\n args: parseToolArgs(args),\n } as ContentBlock;\n}\n\n// ─── Sub-Stream: Text ───────────────────────────────────────────\n\n/**\n * Typed stream for text content.\n *\n * - **Iterate**: yields incremental text deltas.\n * - **Await**: resolves to the complete concatenated text.\n * - **`.full`**: yields the running accumulated text after each delta.\n */\nexport class TextContentStream\n implements AsyncIterable<string>, PromiseLike<string>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n /** Yields the accumulated text so far after each delta. */\n get full(): AsyncIterable<string> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n let accumulated = \"\";\n for await (const event of buffer.iterate()) {\n const delta = getEventDelta(event);\n if (delta?.type === \"text-delta\") {\n accumulated += delta.text;\n yield accumulated;\n }\n }\n },\n };\n }\n\n /** Yields incremental text deltas. */\n [Symbol.asyncIterator](): AsyncIterator<string> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n const delta = getEventDelta(event);\n if (delta?.type === \"text-delta\") {\n yield delta.text;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = string, TResult2 = never>(\n onfulfilled?: ((value: string) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let text = \"\";\n for await (const delta of this) {\n text += delta;\n }\n return text;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Tool Calls ─────────────────────────────────────\n\n/**\n * Typed stream for tool calls.\n *\n * - **Iterate**: yields individual `ToolCall` objects as each completes.\n * - **Await**: resolves to the full array.\n * - **`.full`**: yields the accumulated array after each new tool call.\n */\nexport class ToolCallsStream\n implements\n AsyncIterable<ContentBlock.Tools.ToolCall>,\n PromiseLike<Array<ContentBlock.Tools.ToolCall>>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n get full(): AsyncIterable<Array<ContentBlock.Tools.ToolCall>> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n const calls: Array<ContentBlock.Tools.ToolCall> = [];\n for await (const event of buffer.iterate()) {\n if (\n event.event === \"content-block-finish\" &&\n event.content.type === \"tool_call\"\n ) {\n calls.push(event.content as ContentBlock.Tools.ToolCall);\n yield [...calls];\n }\n }\n },\n };\n }\n\n [Symbol.asyncIterator](): AsyncIterator<ContentBlock.Tools.ToolCall> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n if (\n event.event === \"content-block-finish\" &&\n event.content.type === \"tool_call\"\n ) {\n yield event.content as ContentBlock.Tools.ToolCall;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = Array<ContentBlock.Tools.ToolCall>, TResult2 = never>(\n onfulfilled?:\n | ((\n value: Array<ContentBlock.Tools.ToolCall>\n ) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n const calls: Array<ContentBlock.Tools.ToolCall> = [];\n for await (const call of this) {\n calls.push(call);\n }\n return calls;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Reasoning ──────────────────────────────────────\n\n/**\n * Typed stream for reasoning content (chain-of-thought).\n * Same interface as {@link TextContentStream} but for reasoning blocks.\n */\nexport class ReasoningContentStream\n implements AsyncIterable<string>, PromiseLike<string>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n get full(): AsyncIterable<string> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n let accumulated = \"\";\n let seenReasoning = false;\n for await (const event of buffer.iterate()) {\n if (event.event === \"content-block-start\") {\n if (!isReasoningContent(event.content)) {\n if (seenReasoning) return;\n continue;\n }\n seenReasoning = true;\n const delta = getReasoningDelta(event.content);\n if (delta == null || delta.length === 0) continue;\n accumulated += delta;\n yield accumulated;\n } else if (event.event === \"content-block-delta\") {\n const eventDelta = getEventDelta(event);\n if (eventDelta?.type !== \"reasoning-delta\") continue;\n seenReasoning = true;\n const delta = eventDelta.reasoning;\n if (delta == null || delta.length === 0) continue;\n accumulated += delta;\n yield accumulated;\n } else if (\n event.event === \"content-block-finish\" &&\n isReasoningContent(event.content)\n ) {\n return;\n } else if (event.event === \"message-finish\") {\n return;\n }\n }\n },\n };\n }\n\n [Symbol.asyncIterator](): AsyncIterator<string> {\n const buffer = this._buffer;\n async function* gen() {\n let seenReasoning = false;\n for await (const event of buffer.iterate()) {\n if (event.event === \"content-block-start\") {\n if (!isReasoningContent(event.content)) {\n if (seenReasoning) return;\n continue;\n }\n seenReasoning = true;\n const delta = getReasoningDelta(event.content);\n if (delta != null && delta.length > 0) yield delta;\n } else if (event.event === \"content-block-delta\") {\n const eventDelta = getEventDelta(event);\n if (eventDelta?.type !== \"reasoning-delta\") continue;\n seenReasoning = true;\n const delta = eventDelta.reasoning;\n if (delta != null && delta.length > 0) yield delta;\n } else if (\n event.event === \"content-block-finish\" &&\n isReasoningContent(event.content)\n ) {\n return;\n } else if (event.event === \"message-finish\") {\n return;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = string, TResult2 = never>(\n onfulfilled?: ((value: string) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let text = \"\";\n for await (const delta of this) {\n text += delta;\n }\n return text;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Usage ──────────────────────────────────────────\n\n/**\n * Typed stream for usage metadata.\n */\nexport class UsageMetadataStream\n implements\n AsyncIterable<UsageMetadata>,\n PromiseLike<UsageMetadata | undefined>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<UsageMetadata> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n if (event.event === \"usage\") {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n } else if (event.event === \"message-start\" && event.usage) {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n } else if (event.event === \"message-finish\" && event.usage) {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = UsageMetadata | undefined, TResult2 = never>(\n onfulfilled?:\n | ((value: UsageMetadata | undefined) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let latest: UsageMetadata | undefined;\n for await (const usage of this) {\n latest = usage;\n }\n return latest;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── ChatModelStream ────────────────────────────────────────────\n\n/**\n * The main stream object returned by chat model streaming.\n *\n * Implements `AsyncIterable<ChatModelStreamEvent>` for raw event access\n * and `PromiseLike<AIMessage>` for simple `await` usage.\n */\nexport class ChatModelStream\n implements AsyncIterable<ChatModelStreamEvent>, PromiseLike<AIMessage>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(source: AsyncIterable<ChatModelStreamEvent>) {\n this._buffer = new ReplayBuffer();\n this._consume(source);\n }\n\n /** @internal */\n private async _consume(\n source: AsyncIterable<ChatModelStreamEvent>\n ): Promise<void> {\n try {\n for await (const event of source) {\n this._buffer.push(event);\n }\n this._buffer.finish();\n } catch (err) {\n this._buffer.setError(\n err instanceof Error ? err : new Error(String(err))\n );\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<ChatModelStreamEvent> {\n return this._buffer.iterate();\n }\n\n get text(): TextContentStream {\n return new TextContentStream(this._buffer);\n }\n\n get toolCalls(): ToolCallsStream {\n return new ToolCallsStream(this._buffer);\n }\n\n get reasoning(): ReasoningContentStream {\n return new ReasoningContentStream(this._buffer);\n }\n\n get usage(): UsageMetadataStream {\n return new UsageMetadataStream(this._buffer);\n }\n\n get output(): PromiseLike<AIMessage> {\n return this._assembleMessage();\n }\n\n then<TResult1 = AIMessage, TResult2 = never>(\n onfulfilled?:\n | ((value: AIMessage) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n return this._assembleMessage().then(onfulfilled, onrejected);\n }\n\n /** @internal */\n private async _assembleMessage(): Promise<AIMessage> {\n const contentBlocks: Array<ContentBlock | undefined> = [];\n let id: string | undefined;\n let usage: UsageMetadata | undefined;\n let metadata: Record<string, unknown> = {};\n let finishReason: string | undefined;\n\n for await (const event of this._buffer.iterate()) {\n switch (event.event) {\n case \"message-start\":\n id = event.id ?? id;\n if (event.usage) usage = normalizeUsage(event.usage);\n break;\n\n case \"content-block-start\":\n contentBlocks[event.index] = event.content;\n break;\n\n case \"content-block-delta\": {\n const current = contentBlocks[event.index];\n const delta = getEventDelta(event);\n if (current) {\n if (delta) contentBlocks[event.index] = applyDelta(current, delta);\n }\n break;\n }\n\n case \"content-block-finish\":\n contentBlocks[event.index] = event.content;\n break;\n\n case \"usage\":\n usage = normalizeUsage(event.usage);\n break;\n\n case \"message-finish\":\n finishReason = event.reason;\n if (event.usage) usage = normalizeUsage(event.usage);\n if (event.responseMetadata) {\n metadata = {\n ...metadata,\n ...event.responseMetadata,\n };\n }\n break;\n\n default:\n break;\n }\n }\n\n const filteredBlocks = contentBlocks\n .filter((b): b is ContentBlock => b != null)\n .map(standardizeToolBlock);\n\n return new AIMessage({\n id,\n content: filteredBlocks,\n usage_metadata: usage,\n response_metadata: {\n ...metadata,\n ...(finishReason ? { finish_reason: finishReason } : {}),\n output_version: \"v1\" as const,\n },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,eAAN,MAAmB;CACjB,SAAyC,CAAC;CAC1C,WAAmB;CACnB,UAAqC,CAAC;CACtC,QAA8B;CAE9B,KAAK,OAAmC;EACtC,KAAK,OAAO,KAAK,KAAK;EACtB,MAAM,SAAS,KAAK,QAAQ,OAAO,CAAC;EACpC,KAAK,MAAM,UAAU,QACnB,OAAO;CAEX;CAEA,SAAe;EACb,KAAK,WAAW;EAChB,MAAM,SAAS,KAAK,QAAQ,OAAO,CAAC;EACpC,KAAK,MAAM,UAAU,QACnB,OAAO;CAEX;CAEA,SAAS,KAAkB;EACzB,KAAK,QAAQ;EACb,KAAK,WAAW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jB,GAAG;IACH,GAAI,eAAe,EAAE,eAAe,aAAa,IAAI,CAAC;IACtD,gBAAgB;GAClB;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"stream.cjs","names":["AIMessage"],"sources":["../../src/language_models/stream.ts"],"sourcesContent":["/**\n * Typed stream classes for chat model streaming.\n *\n * @module\n */\n\nimport { AIMessage } from \"../messages/ai.js\";\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\nimport type { ChatModelStreamEvent, ContentBlockDelta } from \"./event.js\";\n\ntype UsageMetadataLike = Partial<UsageMetadata>;\n\n/**\n * A buffer that caches emitted events for replay.\n *\n * Multiple consumers can independently iterate the same buffer —\n * each gets its own cursor. Events are never consumed or removed.\n *\n * @internal\n */\nclass ReplayBuffer {\n private events: ChatModelStreamEvent[] = [];\n private finished = false;\n private waiters: Array<() => void> = [];\n private error: Error | null = null;\n\n push(event: ChatModelStreamEvent): void {\n this.events.push(event);\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n finish(): void {\n this.finished = true;\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n setError(err: Error): void {\n this.error = err;\n this.finished = true;\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n async *iterate(): AsyncGenerator<ChatModelStreamEvent> {\n if (this.finished) {\n if (this.error) throw this.error;\n yield* this.events;\n return;\n }\n\n let cursor = 0;\n while (true) {\n while (cursor < this.events.length) {\n yield this.events[cursor]!;\n cursor++;\n }\n if (this.finished) {\n if (this.error) throw this.error;\n return;\n }\n await new Promise<void>((resolve) => {\n if (cursor < this.events.length || this.finished) {\n resolve();\n return;\n }\n this.waiters.push(resolve);\n });\n }\n }\n}\n\n/**\n * Apply a typed delta to an accumulated content block.\n *\n * - `text-delta` → append text\n * - `reasoning-delta` → append reasoning text\n * - `data-delta` → append encoded data to `data`\n * - `tool-call-delta` → append tool-call args\n * - `block-delta` → shallow merge fields\n *\n * @internal\n */\nfunction applyDelta(\n block: ContentBlock,\n delta: ContentBlockDelta\n): ContentBlock {\n switch (delta.type) {\n case \"text-delta\":\n if (block.type === \"text\") {\n return {\n ...block,\n text: (block.text ?? \"\") + delta.text,\n };\n }\n return block;\n case \"reasoning-delta\":\n if (block.type === \"thinking\") {\n return {\n ...block,\n thinking: (block.thinking ?? \"\") + delta.reasoning,\n };\n }\n if (block.type === \"reasoning\") {\n return {\n ...block,\n reasoning: (block.reasoning ?? \"\") + delta.reasoning,\n };\n }\n return block;\n case \"data-delta\":\n return {\n ...block,\n data: (block.data ?? \"\") + delta.data,\n };\n case \"tool-call-delta\":\n if (\n block.type === \"tool_call_chunk\" ||\n block.type === \"server_tool_call_chunk\"\n ) {\n return {\n ...block,\n args: (block.args ?? \"\") + delta.args,\n };\n }\n return block;\n case \"block-delta\":\n return { ...block, ...delta.fields } as ContentBlock;\n default:\n // The agent protocol adds delta variants over time, so skip ones this\n // version doesn't know. `content-block-finish` carries the full block.\n return block;\n }\n}\n\n/**\n * Returns the typed delta carried by a content-block delta event.\n *\n * Stream protocol compliant language models store incremental updates in\n * `event.delta`, e.g. `{ type: \"text-delta\", text: \"hello\" }`. Some models and\n * adapters still emit the older content-shaped form on `event.content`, e.g.\n * `{ type: \"text\", text: \"hello\" }`, which predates explicit delta event\n * variants.\n *\n * Keep accepting that content-shaped form here so {@link ChatModelStream}\n * remains a tolerant consumer while producers migrate to protocol compliant\n * typed deltas.\n *\n * @internal\n */\nfunction getEventDelta(\n event: ChatModelStreamEvent\n): ContentBlockDelta | undefined {\n if (event.event !== \"content-block-delta\") return undefined;\n if (\"delta\" in event && event.delta) return event.delta;\n\n const content = (event as { content?: unknown }).content;\n if (content == null || typeof content !== \"object\") return undefined;\n const block = content as { type?: string } & Record<string, unknown>;\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { type: \"text-delta\", text: block.text };\n }\n if (block.type === \"reasoning\" && typeof block.reasoning === \"string\") {\n return { type: \"reasoning-delta\", reasoning: block.reasoning };\n }\n if (block.type === \"thinking\" && typeof block.thinking === \"string\") {\n return { type: \"reasoning-delta\", reasoning: block.thinking };\n }\n if (typeof block.data === \"string\") {\n return { type: \"data-delta\", data: block.data, encoding: \"base64\" };\n }\n if (typeof block.type === \"string\") {\n return { type: \"block-delta\", fields: { ...block, type: block.type } };\n }\n return undefined;\n}\n\nfunction getReasoningDelta(content: unknown): string | undefined {\n if (content == null || typeof content !== \"object\") return undefined;\n const block = content as {\n type?: string;\n reasoning?: unknown;\n thinking?: unknown;\n };\n if (block.type === \"reasoning\" && typeof block.reasoning === \"string\") {\n return block.reasoning;\n }\n if (block.type === \"thinking\" && typeof block.thinking === \"string\") {\n return block.thinking;\n }\n return undefined;\n}\n\nfunction isReasoningContent(content: unknown): boolean {\n if (content == null || typeof content !== \"object\") return false;\n const type = (content as { type?: unknown }).type;\n return type === \"reasoning\" || type === \"thinking\";\n}\n\n/**\n * Normalize protocol-compatible partial usage into Core's concrete usage shape.\n *\n * Some stream sources emit usage snapshots without every aggregate token field.\n * Keep the stream event input permissive, then normalize at read time so\n * high-level Core consumers always receive a complete {@link UsageMetadata}.\n */\nfunction normalizeUsage(\n usage: UsageMetadataLike | undefined\n): UsageMetadata | undefined {\n if (!usage) return undefined;\n return {\n ...usage,\n input_tokens: usage.input_tokens ?? 0,\n output_tokens: usage.output_tokens ?? 0,\n total_tokens: usage.total_tokens ?? 0,\n };\n}\n\nfunction parseToolArgs(value: unknown): Record<string, unknown> {\n if (value != null && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n if (typeof value !== \"string\" || value.length === 0) return {};\n try {\n const parsed = JSON.parse(value);\n return parsed != null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction standardizeToolBlock(block: ContentBlock): ContentBlock {\n const record = block as Record<string, unknown>;\n if (block.type === \"tool_call\") return block;\n if (\n block.type !== \"tool_call_chunk\" &&\n block.type !== \"tool_use\" &&\n block.type !== \"input_json_delta\"\n ) {\n return block;\n }\n\n const name = typeof record.name === \"string\" ? record.name : undefined;\n if (name == null) return block;\n\n const args = record.args ?? record.input;\n return {\n ...record,\n type: \"tool_call\",\n name,\n args: parseToolArgs(args),\n } as ContentBlock;\n}\n\n// ─── Sub-Stream: Text ───────────────────────────────────────────\n\n/**\n * Typed stream for text content.\n *\n * - **Iterate**: yields incremental text deltas.\n * - **Await**: resolves to the complete concatenated text.\n * - **`.full`**: yields the running accumulated text after each delta.\n */\nexport class TextContentStream\n implements AsyncIterable<string>, PromiseLike<string>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n /** Yields the accumulated text so far after each delta. */\n get full(): AsyncIterable<string> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n let accumulated = \"\";\n for await (const event of buffer.iterate()) {\n const delta = getEventDelta(event);\n if (delta?.type === \"text-delta\") {\n accumulated += delta.text;\n yield accumulated;\n }\n }\n },\n };\n }\n\n /** Yields incremental text deltas. */\n [Symbol.asyncIterator](): AsyncIterator<string> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n const delta = getEventDelta(event);\n if (delta?.type === \"text-delta\") {\n yield delta.text;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = string, TResult2 = never>(\n onfulfilled?: ((value: string) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let text = \"\";\n for await (const delta of this) {\n text += delta;\n }\n return text;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Tool Calls ─────────────────────────────────────\n\n/**\n * Typed stream for tool calls.\n *\n * - **Iterate**: yields individual `ToolCall` objects as each completes.\n * - **Await**: resolves to the full array.\n * - **`.full`**: yields the accumulated array after each new tool call.\n */\nexport class ToolCallsStream\n implements\n AsyncIterable<ContentBlock.Tools.ToolCall>,\n PromiseLike<Array<ContentBlock.Tools.ToolCall>>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n get full(): AsyncIterable<Array<ContentBlock.Tools.ToolCall>> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n const calls: Array<ContentBlock.Tools.ToolCall> = [];\n for await (const event of buffer.iterate()) {\n if (\n event.event === \"content-block-finish\" &&\n event.content.type === \"tool_call\"\n ) {\n calls.push(event.content as ContentBlock.Tools.ToolCall);\n yield [...calls];\n }\n }\n },\n };\n }\n\n [Symbol.asyncIterator](): AsyncIterator<ContentBlock.Tools.ToolCall> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n if (\n event.event === \"content-block-finish\" &&\n event.content.type === \"tool_call\"\n ) {\n yield event.content as ContentBlock.Tools.ToolCall;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = Array<ContentBlock.Tools.ToolCall>, TResult2 = never>(\n onfulfilled?:\n | ((\n value: Array<ContentBlock.Tools.ToolCall>\n ) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n const calls: Array<ContentBlock.Tools.ToolCall> = [];\n for await (const call of this) {\n calls.push(call);\n }\n return calls;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Reasoning ──────────────────────────────────────\n\n/**\n * Typed stream for reasoning content (chain-of-thought).\n * Same interface as {@link TextContentStream} but for reasoning blocks.\n */\nexport class ReasoningContentStream\n implements AsyncIterable<string>, PromiseLike<string>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n get full(): AsyncIterable<string> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n let accumulated = \"\";\n let seenReasoning = false;\n for await (const event of buffer.iterate()) {\n if (event.event === \"content-block-start\") {\n if (!isReasoningContent(event.content)) {\n if (seenReasoning) return;\n continue;\n }\n seenReasoning = true;\n const delta = getReasoningDelta(event.content);\n if (delta == null || delta.length === 0) continue;\n accumulated += delta;\n yield accumulated;\n } else if (event.event === \"content-block-delta\") {\n const eventDelta = getEventDelta(event);\n if (eventDelta?.type !== \"reasoning-delta\") continue;\n seenReasoning = true;\n const delta = eventDelta.reasoning;\n if (delta == null || delta.length === 0) continue;\n accumulated += delta;\n yield accumulated;\n } else if (\n event.event === \"content-block-finish\" &&\n isReasoningContent(event.content)\n ) {\n return;\n } else if (event.event === \"message-finish\") {\n return;\n }\n }\n },\n };\n }\n\n [Symbol.asyncIterator](): AsyncIterator<string> {\n const buffer = this._buffer;\n async function* gen() {\n let seenReasoning = false;\n for await (const event of buffer.iterate()) {\n if (event.event === \"content-block-start\") {\n if (!isReasoningContent(event.content)) {\n if (seenReasoning) return;\n continue;\n }\n seenReasoning = true;\n const delta = getReasoningDelta(event.content);\n if (delta != null && delta.length > 0) yield delta;\n } else if (event.event === \"content-block-delta\") {\n const eventDelta = getEventDelta(event);\n if (eventDelta?.type !== \"reasoning-delta\") continue;\n seenReasoning = true;\n const delta = eventDelta.reasoning;\n if (delta != null && delta.length > 0) yield delta;\n } else if (\n event.event === \"content-block-finish\" &&\n isReasoningContent(event.content)\n ) {\n return;\n } else if (event.event === \"message-finish\") {\n return;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = string, TResult2 = never>(\n onfulfilled?: ((value: string) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let text = \"\";\n for await (const delta of this) {\n text += delta;\n }\n return text;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Usage ──────────────────────────────────────────\n\n/**\n * Typed stream for usage metadata.\n */\nexport class UsageMetadataStream\n implements\n AsyncIterable<UsageMetadata>,\n PromiseLike<UsageMetadata | undefined>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<UsageMetadata> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n if (event.event === \"usage\") {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n } else if (event.event === \"message-start\" && event.usage) {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n } else if (event.event === \"message-finish\" && event.usage) {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = UsageMetadata | undefined, TResult2 = never>(\n onfulfilled?:\n | ((value: UsageMetadata | undefined) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let latest: UsageMetadata | undefined;\n for await (const usage of this) {\n latest = usage;\n }\n return latest;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── ChatModelStream ────────────────────────────────────────────\n\n/**\n * The main stream object returned by chat model streaming.\n *\n * Implements `AsyncIterable<ChatModelStreamEvent>` for raw event access\n * and `PromiseLike<AIMessage>` for simple `await` usage.\n */\nexport class ChatModelStream\n implements AsyncIterable<ChatModelStreamEvent>, PromiseLike<AIMessage>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(source: AsyncIterable<ChatModelStreamEvent>) {\n this._buffer = new ReplayBuffer();\n this._consume(source);\n }\n\n /** @internal */\n private async _consume(\n source: AsyncIterable<ChatModelStreamEvent>\n ): Promise<void> {\n try {\n for await (const event of source) {\n this._buffer.push(event);\n }\n this._buffer.finish();\n } catch (err) {\n this._buffer.setError(\n err instanceof Error ? err : new Error(String(err))\n );\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<ChatModelStreamEvent> {\n return this._buffer.iterate();\n }\n\n get text(): TextContentStream {\n return new TextContentStream(this._buffer);\n }\n\n get toolCalls(): ToolCallsStream {\n return new ToolCallsStream(this._buffer);\n }\n\n get reasoning(): ReasoningContentStream {\n return new ReasoningContentStream(this._buffer);\n }\n\n get usage(): UsageMetadataStream {\n return new UsageMetadataStream(this._buffer);\n }\n\n get output(): PromiseLike<AIMessage> {\n return this._assembleMessage();\n }\n\n then<TResult1 = AIMessage, TResult2 = never>(\n onfulfilled?:\n | ((value: AIMessage) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n return this._assembleMessage().then(onfulfilled, onrejected);\n }\n\n /** @internal */\n private async _assembleMessage(): Promise<AIMessage> {\n const contentBlocks: Array<ContentBlock | undefined> = [];\n let id: string | undefined;\n let usage: UsageMetadata | undefined;\n let metadata: Record<string, unknown> = {};\n let finishReason: string | undefined;\n\n for await (const event of this._buffer.iterate()) {\n switch (event.event) {\n case \"message-start\":\n id = event.id ?? id;\n if (event.usage) usage = normalizeUsage(event.usage);\n break;\n\n case \"content-block-start\":\n contentBlocks[event.index] = event.content;\n break;\n\n case \"content-block-delta\": {\n const current = contentBlocks[event.index];\n const delta = getEventDelta(event);\n if (current) {\n if (delta) contentBlocks[event.index] = applyDelta(current, delta);\n }\n break;\n }\n\n case \"content-block-finish\":\n contentBlocks[event.index] = event.content;\n break;\n\n case \"usage\":\n usage = normalizeUsage(event.usage);\n break;\n\n case \"message-finish\":\n finishReason = event.reason;\n if (event.usage) usage = normalizeUsage(event.usage);\n if (event.responseMetadata) {\n metadata = {\n ...metadata,\n ...event.responseMetadata,\n };\n }\n break;\n\n default:\n break;\n }\n }\n\n const filteredBlocks = contentBlocks\n .filter((b): b is ContentBlock => b != null)\n .map(standardizeToolBlock);\n\n return new AIMessage({\n id,\n content: filteredBlocks,\n usage_metadata: usage,\n response_metadata: {\n ...metadata,\n ...(finishReason ? { finish_reason: finishReason } : {}),\n output_version: \"v1\" as const,\n },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,eAAN,MAAmB;CACjB,SAAyC,CAAC;CAC1C,WAAmB;CACnB,UAAqC,CAAC;CACtC,QAA8B;CAE9B,KAAK,OAAmC;EACtC,KAAK,OAAO,KAAK,KAAK;EACtB,MAAM,SAAS,KAAK,QAAQ,OAAO,CAAC;EACpC,KAAK,MAAM,UAAU,QACnB,OAAO;CAEX;CAEA,SAAe;EACb,KAAK,WAAW;EAChB,MAAM,SAAS,KAAK,QAAQ,OAAO,CAAC;EACpC,KAAK,MAAM,UAAU,QACnB,OAAO;CAEX;CAEA,SAAS,KAAkB;EACzB,KAAK,QAAQ;EACb,KAAK,WAAW;EAChB,MAAM,SAAS,KAAK,QAAQ,OAAO,CAAC;EACpC,KAAK,MAAM,UAAU,QACnB,OAAO;CAEX;CAEA,OAAO,UAAgD;EACrD,IAAI,KAAK,UAAU;GACjB,IAAI,KAAK,OAAO,MAAM,KAAK;GAC3B,OAAO,KAAK;GACZ;EACF;EAEA,IAAI,SAAS;EACb,OAAO,MAAM;GACX,OAAO,SAAS,KAAK,OAAO,QAAQ;IAClC,MAAM,KAAK,OAAO;IAClB;GACF;GACA,IAAI,KAAK,UAAU;IACjB,IAAI,KAAK,OAAO,MAAM,KAAK;IAC3B;GACF;GACA,MAAM,IAAI,SAAe,YAAY;IACnC,IAAI,SAAS,KAAK,OAAO,UAAU,KAAK,UAAU;KAChD,QAAQ;KACR;IACF;IACA,KAAK,QAAQ,KAAK,OAAO;GAC3B,CAAC;EACH;CACF;AACF;;;;;;;;;;;;A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,WAAW,MAAM,SAAS,KAAK,QAAQ,QAAQ,GAC7C,QAAQ,MAAM,OAAd;GACE,KAAK;IACH,KAAK,MAAM,MAAM;IACjB,IAAI,MAAM,OAAO,QAAQ,eAAe,MAAM,KAAK;IACnD;GAEF,KAAK;IACH,cAAc,MAAM,SAAS,MAAM;IACnC;GAEF,KAAK,uBAAuB;IAC1B,MAAM,UAAU,cAAc,MAAM;IACpC,MAAM,QAAQ,cAAc,KAAK;IACjC,IAAI,SACE;SAAA,OAAO,cAAc,MAAM,SAAS,WAAW,SAAS,KAAK;IAAA;IAEnE;GACF;GAEA,KAAK;IACH,cAAc,MAAM,SAAS,MAAM;IACnC;GAEF,KAAK;IACH,QAAQ,eAAe,MAAM,KAAK;IAClC;GAEF,KAAK;IACH,eAAe,MAAM;IACrB,IAAI,MAAM,OAAO,QAAQ,eAAe,MAAM,KAAK;IACnD,IAAI,MAAM,kBACR,WAAW;KACT,GAAG;KACH,GAAG,MAAM;IACX;EAMN;EAGF,MAAM,iBAAiB,cACpB,QAAQ,MAAyB,KAAK,IAAI,CAAC,CAC3C,IAAI,oBAAoB;EAE3B,OAAO,IAAIA,WAAAA,UAAU;GACnB;GACA,SAAS;GACT,gBAAgB;GAChB,mBAAmB;IACjB,GAAG;IACH,GAAI,eAAe,EAAE,eAAe,aAAa,IAAI,CAAC;IACtD,gBAAgB;GAClB;EACF,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.d.cts","names":[],"sources":["../../src/language_models/stream.ts"],"mappings":";;;;;;;;;;;;;cAqBM;UACI;UACA;UACA;UACA;EAER,KAAK,OAAO;EAQZ;EAQA,SAAS,KAAK;EASP,WAAW,eAAe;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"stream.d.cts","names":[],"sources":["../../src/language_models/stream.ts"],"mappings":";;;;;;;;;;;;;cAqBM;UACI;UACA;UACA;UACA;EAER,KAAK,OAAO;EAQZ;EAQA,SAAS,KAAK;EASP,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Ae,oBAAoB,WAAW,YAAY,oBACzD,YAAY,WAAW;;UAKZ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.d.ts","names":[],"sources":["../../src/language_models/stream.ts"],"mappings":";;;;;;;;;;;;;cAqBM;UACI;UACA;UACA;UACA;EAER,KAAK,OAAO;EAQZ;EAQA,SAAS,KAAK;EASP,WAAW,eAAe;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"stream.d.ts","names":[],"sources":["../../src/language_models/stream.ts"],"mappings":";;;;;;;;;;;;;cAqBM;UACI;UACA;UACA;UACA;EAER,KAAK,OAAO;EAQZ;EAQA,SAAS,KAAK;EASP,WAAW,eAAe;;;;;;;;;qBA+NtB,6BACA,uBAAuB;;UAG1B;;EAGR,YAAY,QAAQ;;MAKhB,QAAQ;;GAiBX,OAAO,kBAAkB;EAa1B,KAAK,mBAAmB,kBACtB,gBAAgB,kBAAkB,WAAW,YAAY,mBACzD,eAAe,oBAAoB,WAAW,YAAY,oBACzD,YAAY,WAAW;;;;;;;;;qBAqBf,2BAET,cAAc,aAAa,MAAM,WACjC,YAAY,MAAM,aAAa,MAAM;;UAG/B;;EAGR,YAAY,QAAQ;MAIhB,QAAQ,cAAc,MAAM,aAAa,MAAM;GAkBlD,OAAO,kBAAkB,cAAc,aAAa,MAAM;EAe3D,KAAK,WAAW,MAAM,aAAa,MAAM,WAAW,kBAClD,gBAEM,OAAO,MAAM,aAAa,MAAM,cAC7B,WAAW,YAAY,mBAEhC,eAAe,oBAAoB,WAAW,YAAY,oBACzD,YAAY,WAAW;;;;;;qBAkBf,kCACA,uBAAuB;;UAG1B;;EAGR,YAAY,QAAQ;MAIhB,QAAQ;GAsCX,OAAO,kBAAkB;EAgC1B,KAAK,mBAAmB,kBACtB,gBAAgB,kBAAkB,WAAW,YAAY,mBACzD,eAAe,oBAAoB,WAAW,YAAY,oBACzD,YAAY,WAAW;;;;;qBAiBf,+BAET,cAAc,gBACd,YAAY;;UAGN;;EAGR,YAAY,QAAQ;GAInB,OAAO,kBAAkB,cAAc;EAmBxC,KAAK,WAAW,2BAA2B,kBACzC,gBACM,OAAO,8BAA8B,WAAW,YAAY,mBAElE,eAAe,oBAAoB,WAAW,YAAY,oBACzD,YAAY,WAAW;;;;;;;;qBAoBf,2BACA,cAAc,uBAAuB,YAAY;;UAGpD;;EAGR,YAAY,QAAQ,cAAc;;UAMpB;GAeb,OAAO,kBAAkB,cAAc;MAIpC,QAAQ;MAIR,aAAa;MAIb,aAAa;MAIb,SAAS;MAIT,UAAU,YAAY;EAI1B,KAAK,WAAW,WAAW,kBACzB,gBACM,OAAO,cAAc,WAAW,YAAY,mBAElD,eAAe,oBAAoB,WAAW,YAAY,oBACzD,YAAY,WAAW;;UAKZ"}
|
|
@@ -74,6 +74,7 @@ var ReplayBuffer = class {
|
|
|
74
74
|
* - `text-delta` → append text
|
|
75
75
|
* - `reasoning-delta` → append reasoning text
|
|
76
76
|
* - `data-delta` → append encoded data to `data`
|
|
77
|
+
* - `tool-call-delta` → append tool-call args
|
|
77
78
|
* - `block-delta` → shallow merge fields
|
|
78
79
|
*
|
|
79
80
|
* @internal
|
|
@@ -100,11 +101,17 @@ function applyDelta(block, delta) {
|
|
|
100
101
|
...block,
|
|
101
102
|
data: (block.data ?? "") + delta.data
|
|
102
103
|
};
|
|
104
|
+
case "tool-call-delta":
|
|
105
|
+
if (block.type === "tool_call_chunk" || block.type === "server_tool_call_chunk") return {
|
|
106
|
+
...block,
|
|
107
|
+
args: (block.args ?? "") + delta.args
|
|
108
|
+
};
|
|
109
|
+
return block;
|
|
103
110
|
case "block-delta": return {
|
|
104
111
|
...block,
|
|
105
112
|
...delta.fields
|
|
106
113
|
};
|
|
107
|
-
default:
|
|
114
|
+
default: return block;
|
|
108
115
|
}
|
|
109
116
|
}
|
|
110
117
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.js","names":[],"sources":["../../src/language_models/stream.ts"],"sourcesContent":["/**\n * Typed stream classes for chat model streaming.\n *\n * @module\n */\n\nimport { AIMessage } from \"../messages/ai.js\";\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\nimport type { ChatModelStreamEvent, ContentBlockDelta } from \"./event.js\";\n\ntype UsageMetadataLike = Partial<UsageMetadata>;\n\n/**\n * A buffer that caches emitted events for replay.\n *\n * Multiple consumers can independently iterate the same buffer —\n * each gets its own cursor. Events are never consumed or removed.\n *\n * @internal\n */\nclass ReplayBuffer {\n private events: ChatModelStreamEvent[] = [];\n private finished = false;\n private waiters: Array<() => void> = [];\n private error: Error | null = null;\n\n push(event: ChatModelStreamEvent): void {\n this.events.push(event);\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n finish(): void {\n this.finished = true;\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n setError(err: Error): void {\n this.error = err;\n this.finished = true;\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n async *iterate(): AsyncGenerator<ChatModelStreamEvent> {\n if (this.finished) {\n if (this.error) throw this.error;\n yield* this.events;\n return;\n }\n\n let cursor = 0;\n while (true) {\n while (cursor < this.events.length) {\n yield this.events[cursor]!;\n cursor++;\n }\n if (this.finished) {\n if (this.error) throw this.error;\n return;\n }\n await new Promise<void>((resolve) => {\n if (cursor < this.events.length || this.finished) {\n resolve();\n return;\n }\n this.waiters.push(resolve);\n });\n }\n }\n}\n\n/**\n * Apply a typed delta to an accumulated content block.\n *\n * - `text-delta` → append text\n * - `reasoning-delta` → append reasoning text\n * - `data-delta` → append encoded data to `data`\n * - `block-delta` → shallow merge fields\n *\n * @internal\n */\nfunction applyDelta(\n block: ContentBlock,\n delta: ContentBlockDelta\n): ContentBlock {\n switch (delta.type) {\n case \"text-delta\":\n if (block.type === \"text\") {\n return {\n ...block,\n text: (block.text ?? \"\") + delta.text,\n };\n }\n return block;\n case \"reasoning-delta\":\n if (block.type === \"thinking\") {\n return {\n ...block,\n thinking: (block.thinking ?? \"\") + delta.reasoning,\n };\n }\n if (block.type === \"reasoning\") {\n return {\n ...block,\n reasoning: (block.reasoning ?? \"\") + delta.reasoning,\n };\n }\n return block;\n case \"data-delta\":\n return {\n ...block,\n data: (block.data ?? \"\") + delta.data,\n };\n case \"block-delta\":\n return { ...block, ...delta.fields } as ContentBlock;\n default:\n throw new Error(`Unknown delta type: ${JSON.stringify(delta)}`);\n }\n}\n\n/**\n * Returns the typed delta carried by a content-block delta event.\n *\n * Stream protocol compliant language models store incremental updates in\n * `event.delta`, e.g. `{ type: \"text-delta\", text: \"hello\" }`. Some models and\n * adapters still emit the older content-shaped form on `event.content`, e.g.\n * `{ type: \"text\", text: \"hello\" }`, which predates explicit delta event\n * variants.\n *\n * Keep accepting that content-shaped form here so {@link ChatModelStream}\n * remains a tolerant consumer while producers migrate to protocol compliant\n * typed deltas.\n *\n * @internal\n */\nfunction getEventDelta(\n event: ChatModelStreamEvent\n): ContentBlockDelta | undefined {\n if (event.event !== \"content-block-delta\") return undefined;\n if (\"delta\" in event && event.delta) return event.delta;\n\n const content = (event as { content?: unknown }).content;\n if (content == null || typeof content !== \"object\") return undefined;\n const block = content as { type?: string } & Record<string, unknown>;\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { type: \"text-delta\", text: block.text };\n }\n if (block.type === \"reasoning\" && typeof block.reasoning === \"string\") {\n return { type: \"reasoning-delta\", reasoning: block.reasoning };\n }\n if (block.type === \"thinking\" && typeof block.thinking === \"string\") {\n return { type: \"reasoning-delta\", reasoning: block.thinking };\n }\n if (typeof block.data === \"string\") {\n return { type: \"data-delta\", data: block.data, encoding: \"base64\" };\n }\n if (typeof block.type === \"string\") {\n return { type: \"block-delta\", fields: { ...block, type: block.type } };\n }\n return undefined;\n}\n\nfunction getReasoningDelta(content: unknown): string | undefined {\n if (content == null || typeof content !== \"object\") return undefined;\n const block = content as {\n type?: string;\n reasoning?: unknown;\n thinking?: unknown;\n };\n if (block.type === \"reasoning\" && typeof block.reasoning === \"string\") {\n return block.reasoning;\n }\n if (block.type === \"thinking\" && typeof block.thinking === \"string\") {\n return block.thinking;\n }\n return undefined;\n}\n\nfunction isReasoningContent(content: unknown): boolean {\n if (content == null || typeof content !== \"object\") return false;\n const type = (content as { type?: unknown }).type;\n return type === \"reasoning\" || type === \"thinking\";\n}\n\n/**\n * Normalize protocol-compatible partial usage into Core's concrete usage shape.\n *\n * Some stream sources emit usage snapshots without every aggregate token field.\n * Keep the stream event input permissive, then normalize at read time so\n * high-level Core consumers always receive a complete {@link UsageMetadata}.\n */\nfunction normalizeUsage(\n usage: UsageMetadataLike | undefined\n): UsageMetadata | undefined {\n if (!usage) return undefined;\n return {\n ...usage,\n input_tokens: usage.input_tokens ?? 0,\n output_tokens: usage.output_tokens ?? 0,\n total_tokens: usage.total_tokens ?? 0,\n };\n}\n\nfunction parseToolArgs(value: unknown): Record<string, unknown> {\n if (value != null && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n if (typeof value !== \"string\" || value.length === 0) return {};\n try {\n const parsed = JSON.parse(value);\n return parsed != null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction standardizeToolBlock(block: ContentBlock): ContentBlock {\n const record = block as Record<string, unknown>;\n if (block.type === \"tool_call\") return block;\n if (\n block.type !== \"tool_call_chunk\" &&\n block.type !== \"tool_use\" &&\n block.type !== \"input_json_delta\"\n ) {\n return block;\n }\n\n const name = typeof record.name === \"string\" ? record.name : undefined;\n if (name == null) return block;\n\n const args = record.args ?? record.input;\n return {\n ...record,\n type: \"tool_call\",\n name,\n args: parseToolArgs(args),\n } as ContentBlock;\n}\n\n// ─── Sub-Stream: Text ───────────────────────────────────────────\n\n/**\n * Typed stream for text content.\n *\n * - **Iterate**: yields incremental text deltas.\n * - **Await**: resolves to the complete concatenated text.\n * - **`.full`**: yields the running accumulated text after each delta.\n */\nexport class TextContentStream\n implements AsyncIterable<string>, PromiseLike<string>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n /** Yields the accumulated text so far after each delta. */\n get full(): AsyncIterable<string> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n let accumulated = \"\";\n for await (const event of buffer.iterate()) {\n const delta = getEventDelta(event);\n if (delta?.type === \"text-delta\") {\n accumulated += delta.text;\n yield accumulated;\n }\n }\n },\n };\n }\n\n /** Yields incremental text deltas. */\n [Symbol.asyncIterator](): AsyncIterator<string> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n const delta = getEventDelta(event);\n if (delta?.type === \"text-delta\") {\n yield delta.text;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = string, TResult2 = never>(\n onfulfilled?: ((value: string) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let text = \"\";\n for await (const delta of this) {\n text += delta;\n }\n return text;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Tool Calls ─────────────────────────────────────\n\n/**\n * Typed stream for tool calls.\n *\n * - **Iterate**: yields individual `ToolCall` objects as each completes.\n * - **Await**: resolves to the full array.\n * - **`.full`**: yields the accumulated array after each new tool call.\n */\nexport class ToolCallsStream\n implements\n AsyncIterable<ContentBlock.Tools.ToolCall>,\n PromiseLike<Array<ContentBlock.Tools.ToolCall>>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n get full(): AsyncIterable<Array<ContentBlock.Tools.ToolCall>> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n const calls: Array<ContentBlock.Tools.ToolCall> = [];\n for await (const event of buffer.iterate()) {\n if (\n event.event === \"content-block-finish\" &&\n event.content.type === \"tool_call\"\n ) {\n calls.push(event.content as ContentBlock.Tools.ToolCall);\n yield [...calls];\n }\n }\n },\n };\n }\n\n [Symbol.asyncIterator](): AsyncIterator<ContentBlock.Tools.ToolCall> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n if (\n event.event === \"content-block-finish\" &&\n event.content.type === \"tool_call\"\n ) {\n yield event.content as ContentBlock.Tools.ToolCall;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = Array<ContentBlock.Tools.ToolCall>, TResult2 = never>(\n onfulfilled?:\n | ((\n value: Array<ContentBlock.Tools.ToolCall>\n ) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n const calls: Array<ContentBlock.Tools.ToolCall> = [];\n for await (const call of this) {\n calls.push(call);\n }\n return calls;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Reasoning ──────────────────────────────────────\n\n/**\n * Typed stream for reasoning content (chain-of-thought).\n * Same interface as {@link TextContentStream} but for reasoning blocks.\n */\nexport class ReasoningContentStream\n implements AsyncIterable<string>, PromiseLike<string>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n get full(): AsyncIterable<string> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n let accumulated = \"\";\n let seenReasoning = false;\n for await (const event of buffer.iterate()) {\n if (event.event === \"content-block-start\") {\n if (!isReasoningContent(event.content)) {\n if (seenReasoning) return;\n continue;\n }\n seenReasoning = true;\n const delta = getReasoningDelta(event.content);\n if (delta == null || delta.length === 0) continue;\n accumulated += delta;\n yield accumulated;\n } else if (event.event === \"content-block-delta\") {\n const eventDelta = getEventDelta(event);\n if (eventDelta?.type !== \"reasoning-delta\") continue;\n seenReasoning = true;\n const delta = eventDelta.reasoning;\n if (delta == null || delta.length === 0) continue;\n accumulated += delta;\n yield accumulated;\n } else if (\n event.event === \"content-block-finish\" &&\n isReasoningContent(event.content)\n ) {\n return;\n } else if (event.event === \"message-finish\") {\n return;\n }\n }\n },\n };\n }\n\n [Symbol.asyncIterator](): AsyncIterator<string> {\n const buffer = this._buffer;\n async function* gen() {\n let seenReasoning = false;\n for await (const event of buffer.iterate()) {\n if (event.event === \"content-block-start\") {\n if (!isReasoningContent(event.content)) {\n if (seenReasoning) return;\n continue;\n }\n seenReasoning = true;\n const delta = getReasoningDelta(event.content);\n if (delta != null && delta.length > 0) yield delta;\n } else if (event.event === \"content-block-delta\") {\n const eventDelta = getEventDelta(event);\n if (eventDelta?.type !== \"reasoning-delta\") continue;\n seenReasoning = true;\n const delta = eventDelta.reasoning;\n if (delta != null && delta.length > 0) yield delta;\n } else if (\n event.event === \"content-block-finish\" &&\n isReasoningContent(event.content)\n ) {\n return;\n } else if (event.event === \"message-finish\") {\n return;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = string, TResult2 = never>(\n onfulfilled?: ((value: string) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let text = \"\";\n for await (const delta of this) {\n text += delta;\n }\n return text;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Usage ──────────────────────────────────────────\n\n/**\n * Typed stream for usage metadata.\n */\nexport class UsageMetadataStream\n implements\n AsyncIterable<UsageMetadata>,\n PromiseLike<UsageMetadata | undefined>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<UsageMetadata> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n if (event.event === \"usage\") {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n } else if (event.event === \"message-start\" && event.usage) {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n } else if (event.event === \"message-finish\" && event.usage) {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = UsageMetadata | undefined, TResult2 = never>(\n onfulfilled?:\n | ((value: UsageMetadata | undefined) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let latest: UsageMetadata | undefined;\n for await (const usage of this) {\n latest = usage;\n }\n return latest;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── ChatModelStream ────────────────────────────────────────────\n\n/**\n * The main stream object returned by chat model streaming.\n *\n * Implements `AsyncIterable<ChatModelStreamEvent>` for raw event access\n * and `PromiseLike<AIMessage>` for simple `await` usage.\n */\nexport class ChatModelStream\n implements AsyncIterable<ChatModelStreamEvent>, PromiseLike<AIMessage>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(source: AsyncIterable<ChatModelStreamEvent>) {\n this._buffer = new ReplayBuffer();\n this._consume(source);\n }\n\n /** @internal */\n private async _consume(\n source: AsyncIterable<ChatModelStreamEvent>\n ): Promise<void> {\n try {\n for await (const event of source) {\n this._buffer.push(event);\n }\n this._buffer.finish();\n } catch (err) {\n this._buffer.setError(\n err instanceof Error ? err : new Error(String(err))\n );\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<ChatModelStreamEvent> {\n return this._buffer.iterate();\n }\n\n get text(): TextContentStream {\n return new TextContentStream(this._buffer);\n }\n\n get toolCalls(): ToolCallsStream {\n return new ToolCallsStream(this._buffer);\n }\n\n get reasoning(): ReasoningContentStream {\n return new ReasoningContentStream(this._buffer);\n }\n\n get usage(): UsageMetadataStream {\n return new UsageMetadataStream(this._buffer);\n }\n\n get output(): PromiseLike<AIMessage> {\n return this._assembleMessage();\n }\n\n then<TResult1 = AIMessage, TResult2 = never>(\n onfulfilled?:\n | ((value: AIMessage) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n return this._assembleMessage().then(onfulfilled, onrejected);\n }\n\n /** @internal */\n private async _assembleMessage(): Promise<AIMessage> {\n const contentBlocks: Array<ContentBlock | undefined> = [];\n let id: string | undefined;\n let usage: UsageMetadata | undefined;\n let metadata: Record<string, unknown> = {};\n let finishReason: string | undefined;\n\n for await (const event of this._buffer.iterate()) {\n switch (event.event) {\n case \"message-start\":\n id = event.id ?? id;\n if (event.usage) usage = normalizeUsage(event.usage);\n break;\n\n case \"content-block-start\":\n contentBlocks[event.index] = event.content;\n break;\n\n case \"content-block-delta\": {\n const current = contentBlocks[event.index];\n const delta = getEventDelta(event);\n if (current) {\n if (delta) contentBlocks[event.index] = applyDelta(current, delta);\n }\n break;\n }\n\n case \"content-block-finish\":\n contentBlocks[event.index] = event.content;\n break;\n\n case \"usage\":\n usage = normalizeUsage(event.usage);\n break;\n\n case \"message-finish\":\n finishReason = event.reason;\n if (event.usage) usage = normalizeUsage(event.usage);\n if (event.responseMetadata) {\n metadata = {\n ...metadata,\n ...event.responseMetadata,\n };\n }\n break;\n\n default:\n break;\n }\n }\n\n const filteredBlocks = contentBlocks\n .filter((b): b is ContentBlock => b != null)\n .map(standardizeToolBlock);\n\n return new AIMessage({\n id,\n content: filteredBlocks,\n usage_metadata: usage,\n response_metadata: {\n ...metadata,\n ...(finishReason ? { finish_reason: finishReason } : {}),\n output_version: \"v1\" as const,\n },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,eAAN,MAAmB;CACjB,SAAyC,CAAC;CAC1C,WAAmB;CACnB,UAAqC,CA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,KAAK;IAClC;GAEF,KAAK;IACH,eAAe,MAAM;IACrB,IAAI,MAAM,OAAO,QAAQ,eAAe,MAAM,KAAK;IACnD,IAAI,MAAM,kBACR,WAAW;KACT,GAAG;KACH,GAAG,MAAM;IACX;EAMN;EAGF,MAAM,iBAAiB,cACpB,QAAQ,MAAyB,KAAK,IAAI,CAAC,CAC3C,IAAI,oBAAoB;EAE3B,OAAO,IAAI,UAAU;GACnB;GACA,SAAS;GACT,gBAAgB;GAChB,mBAAmB;IACjB,GAAG;IACH,GAAI,eAAe,EAAE,eAAe,aAAa,IAAI,CAAC;IACtD,gBAAgB;GAClB;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"stream.js","names":[],"sources":["../../src/language_models/stream.ts"],"sourcesContent":["/**\n * Typed stream classes for chat model streaming.\n *\n * @module\n */\n\nimport { AIMessage } from \"../messages/ai.js\";\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\nimport type { ChatModelStreamEvent, ContentBlockDelta } from \"./event.js\";\n\ntype UsageMetadataLike = Partial<UsageMetadata>;\n\n/**\n * A buffer that caches emitted events for replay.\n *\n * Multiple consumers can independently iterate the same buffer —\n * each gets its own cursor. Events are never consumed or removed.\n *\n * @internal\n */\nclass ReplayBuffer {\n private events: ChatModelStreamEvent[] = [];\n private finished = false;\n private waiters: Array<() => void> = [];\n private error: Error | null = null;\n\n push(event: ChatModelStreamEvent): void {\n this.events.push(event);\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n finish(): void {\n this.finished = true;\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n setError(err: Error): void {\n this.error = err;\n this.finished = true;\n const toWake = this.waiters.splice(0);\n for (const waiter of toWake) {\n waiter();\n }\n }\n\n async *iterate(): AsyncGenerator<ChatModelStreamEvent> {\n if (this.finished) {\n if (this.error) throw this.error;\n yield* this.events;\n return;\n }\n\n let cursor = 0;\n while (true) {\n while (cursor < this.events.length) {\n yield this.events[cursor]!;\n cursor++;\n }\n if (this.finished) {\n if (this.error) throw this.error;\n return;\n }\n await new Promise<void>((resolve) => {\n if (cursor < this.events.length || this.finished) {\n resolve();\n return;\n }\n this.waiters.push(resolve);\n });\n }\n }\n}\n\n/**\n * Apply a typed delta to an accumulated content block.\n *\n * - `text-delta` → append text\n * - `reasoning-delta` → append reasoning text\n * - `data-delta` → append encoded data to `data`\n * - `tool-call-delta` → append tool-call args\n * - `block-delta` → shallow merge fields\n *\n * @internal\n */\nfunction applyDelta(\n block: ContentBlock,\n delta: ContentBlockDelta\n): ContentBlock {\n switch (delta.type) {\n case \"text-delta\":\n if (block.type === \"text\") {\n return {\n ...block,\n text: (block.text ?? \"\") + delta.text,\n };\n }\n return block;\n case \"reasoning-delta\":\n if (block.type === \"thinking\") {\n return {\n ...block,\n thinking: (block.thinking ?? \"\") + delta.reasoning,\n };\n }\n if (block.type === \"reasoning\") {\n return {\n ...block,\n reasoning: (block.reasoning ?? \"\") + delta.reasoning,\n };\n }\n return block;\n case \"data-delta\":\n return {\n ...block,\n data: (block.data ?? \"\") + delta.data,\n };\n case \"tool-call-delta\":\n if (\n block.type === \"tool_call_chunk\" ||\n block.type === \"server_tool_call_chunk\"\n ) {\n return {\n ...block,\n args: (block.args ?? \"\") + delta.args,\n };\n }\n return block;\n case \"block-delta\":\n return { ...block, ...delta.fields } as ContentBlock;\n default:\n // The agent protocol adds delta variants over time, so skip ones this\n // version doesn't know. `content-block-finish` carries the full block.\n return block;\n }\n}\n\n/**\n * Returns the typed delta carried by a content-block delta event.\n *\n * Stream protocol compliant language models store incremental updates in\n * `event.delta`, e.g. `{ type: \"text-delta\", text: \"hello\" }`. Some models and\n * adapters still emit the older content-shaped form on `event.content`, e.g.\n * `{ type: \"text\", text: \"hello\" }`, which predates explicit delta event\n * variants.\n *\n * Keep accepting that content-shaped form here so {@link ChatModelStream}\n * remains a tolerant consumer while producers migrate to protocol compliant\n * typed deltas.\n *\n * @internal\n */\nfunction getEventDelta(\n event: ChatModelStreamEvent\n): ContentBlockDelta | undefined {\n if (event.event !== \"content-block-delta\") return undefined;\n if (\"delta\" in event && event.delta) return event.delta;\n\n const content = (event as { content?: unknown }).content;\n if (content == null || typeof content !== \"object\") return undefined;\n const block = content as { type?: string } & Record<string, unknown>;\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { type: \"text-delta\", text: block.text };\n }\n if (block.type === \"reasoning\" && typeof block.reasoning === \"string\") {\n return { type: \"reasoning-delta\", reasoning: block.reasoning };\n }\n if (block.type === \"thinking\" && typeof block.thinking === \"string\") {\n return { type: \"reasoning-delta\", reasoning: block.thinking };\n }\n if (typeof block.data === \"string\") {\n return { type: \"data-delta\", data: block.data, encoding: \"base64\" };\n }\n if (typeof block.type === \"string\") {\n return { type: \"block-delta\", fields: { ...block, type: block.type } };\n }\n return undefined;\n}\n\nfunction getReasoningDelta(content: unknown): string | undefined {\n if (content == null || typeof content !== \"object\") return undefined;\n const block = content as {\n type?: string;\n reasoning?: unknown;\n thinking?: unknown;\n };\n if (block.type === \"reasoning\" && typeof block.reasoning === \"string\") {\n return block.reasoning;\n }\n if (block.type === \"thinking\" && typeof block.thinking === \"string\") {\n return block.thinking;\n }\n return undefined;\n}\n\nfunction isReasoningContent(content: unknown): boolean {\n if (content == null || typeof content !== \"object\") return false;\n const type = (content as { type?: unknown }).type;\n return type === \"reasoning\" || type === \"thinking\";\n}\n\n/**\n * Normalize protocol-compatible partial usage into Core's concrete usage shape.\n *\n * Some stream sources emit usage snapshots without every aggregate token field.\n * Keep the stream event input permissive, then normalize at read time so\n * high-level Core consumers always receive a complete {@link UsageMetadata}.\n */\nfunction normalizeUsage(\n usage: UsageMetadataLike | undefined\n): UsageMetadata | undefined {\n if (!usage) return undefined;\n return {\n ...usage,\n input_tokens: usage.input_tokens ?? 0,\n output_tokens: usage.output_tokens ?? 0,\n total_tokens: usage.total_tokens ?? 0,\n };\n}\n\nfunction parseToolArgs(value: unknown): Record<string, unknown> {\n if (value != null && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n if (typeof value !== \"string\" || value.length === 0) return {};\n try {\n const parsed = JSON.parse(value);\n return parsed != null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction standardizeToolBlock(block: ContentBlock): ContentBlock {\n const record = block as Record<string, unknown>;\n if (block.type === \"tool_call\") return block;\n if (\n block.type !== \"tool_call_chunk\" &&\n block.type !== \"tool_use\" &&\n block.type !== \"input_json_delta\"\n ) {\n return block;\n }\n\n const name = typeof record.name === \"string\" ? record.name : undefined;\n if (name == null) return block;\n\n const args = record.args ?? record.input;\n return {\n ...record,\n type: \"tool_call\",\n name,\n args: parseToolArgs(args),\n } as ContentBlock;\n}\n\n// ─── Sub-Stream: Text ───────────────────────────────────────────\n\n/**\n * Typed stream for text content.\n *\n * - **Iterate**: yields incremental text deltas.\n * - **Await**: resolves to the complete concatenated text.\n * - **`.full`**: yields the running accumulated text after each delta.\n */\nexport class TextContentStream\n implements AsyncIterable<string>, PromiseLike<string>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n /** Yields the accumulated text so far after each delta. */\n get full(): AsyncIterable<string> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n let accumulated = \"\";\n for await (const event of buffer.iterate()) {\n const delta = getEventDelta(event);\n if (delta?.type === \"text-delta\") {\n accumulated += delta.text;\n yield accumulated;\n }\n }\n },\n };\n }\n\n /** Yields incremental text deltas. */\n [Symbol.asyncIterator](): AsyncIterator<string> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n const delta = getEventDelta(event);\n if (delta?.type === \"text-delta\") {\n yield delta.text;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = string, TResult2 = never>(\n onfulfilled?: ((value: string) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let text = \"\";\n for await (const delta of this) {\n text += delta;\n }\n return text;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Tool Calls ─────────────────────────────────────\n\n/**\n * Typed stream for tool calls.\n *\n * - **Iterate**: yields individual `ToolCall` objects as each completes.\n * - **Await**: resolves to the full array.\n * - **`.full`**: yields the accumulated array after each new tool call.\n */\nexport class ToolCallsStream\n implements\n AsyncIterable<ContentBlock.Tools.ToolCall>,\n PromiseLike<Array<ContentBlock.Tools.ToolCall>>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n get full(): AsyncIterable<Array<ContentBlock.Tools.ToolCall>> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n const calls: Array<ContentBlock.Tools.ToolCall> = [];\n for await (const event of buffer.iterate()) {\n if (\n event.event === \"content-block-finish\" &&\n event.content.type === \"tool_call\"\n ) {\n calls.push(event.content as ContentBlock.Tools.ToolCall);\n yield [...calls];\n }\n }\n },\n };\n }\n\n [Symbol.asyncIterator](): AsyncIterator<ContentBlock.Tools.ToolCall> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n if (\n event.event === \"content-block-finish\" &&\n event.content.type === \"tool_call\"\n ) {\n yield event.content as ContentBlock.Tools.ToolCall;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = Array<ContentBlock.Tools.ToolCall>, TResult2 = never>(\n onfulfilled?:\n | ((\n value: Array<ContentBlock.Tools.ToolCall>\n ) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n const calls: Array<ContentBlock.Tools.ToolCall> = [];\n for await (const call of this) {\n calls.push(call);\n }\n return calls;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Reasoning ──────────────────────────────────────\n\n/**\n * Typed stream for reasoning content (chain-of-thought).\n * Same interface as {@link TextContentStream} but for reasoning blocks.\n */\nexport class ReasoningContentStream\n implements AsyncIterable<string>, PromiseLike<string>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n get full(): AsyncIterable<string> {\n const buffer = this._buffer;\n return {\n async *[Symbol.asyncIterator]() {\n let accumulated = \"\";\n let seenReasoning = false;\n for await (const event of buffer.iterate()) {\n if (event.event === \"content-block-start\") {\n if (!isReasoningContent(event.content)) {\n if (seenReasoning) return;\n continue;\n }\n seenReasoning = true;\n const delta = getReasoningDelta(event.content);\n if (delta == null || delta.length === 0) continue;\n accumulated += delta;\n yield accumulated;\n } else if (event.event === \"content-block-delta\") {\n const eventDelta = getEventDelta(event);\n if (eventDelta?.type !== \"reasoning-delta\") continue;\n seenReasoning = true;\n const delta = eventDelta.reasoning;\n if (delta == null || delta.length === 0) continue;\n accumulated += delta;\n yield accumulated;\n } else if (\n event.event === \"content-block-finish\" &&\n isReasoningContent(event.content)\n ) {\n return;\n } else if (event.event === \"message-finish\") {\n return;\n }\n }\n },\n };\n }\n\n [Symbol.asyncIterator](): AsyncIterator<string> {\n const buffer = this._buffer;\n async function* gen() {\n let seenReasoning = false;\n for await (const event of buffer.iterate()) {\n if (event.event === \"content-block-start\") {\n if (!isReasoningContent(event.content)) {\n if (seenReasoning) return;\n continue;\n }\n seenReasoning = true;\n const delta = getReasoningDelta(event.content);\n if (delta != null && delta.length > 0) yield delta;\n } else if (event.event === \"content-block-delta\") {\n const eventDelta = getEventDelta(event);\n if (eventDelta?.type !== \"reasoning-delta\") continue;\n seenReasoning = true;\n const delta = eventDelta.reasoning;\n if (delta != null && delta.length > 0) yield delta;\n } else if (\n event.event === \"content-block-finish\" &&\n isReasoningContent(event.content)\n ) {\n return;\n } else if (event.event === \"message-finish\") {\n return;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = string, TResult2 = never>(\n onfulfilled?: ((value: string) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let text = \"\";\n for await (const delta of this) {\n text += delta;\n }\n return text;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── Sub-Stream: Usage ──────────────────────────────────────────\n\n/**\n * Typed stream for usage metadata.\n */\nexport class UsageMetadataStream\n implements\n AsyncIterable<UsageMetadata>,\n PromiseLike<UsageMetadata | undefined>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(buffer: ReplayBuffer) {\n this._buffer = buffer;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<UsageMetadata> {\n const buffer = this._buffer;\n async function* gen() {\n for await (const event of buffer.iterate()) {\n if (event.event === \"usage\") {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n } else if (event.event === \"message-start\" && event.usage) {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n } else if (event.event === \"message-finish\" && event.usage) {\n const usage = normalizeUsage(event.usage);\n if (usage) yield usage;\n }\n }\n }\n return gen();\n }\n\n then<TResult1 = UsageMetadata | undefined, TResult2 = never>(\n onfulfilled?:\n | ((value: UsageMetadata | undefined) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n const promise = (async () => {\n let latest: UsageMetadata | undefined;\n for await (const usage of this) {\n latest = usage;\n }\n return latest;\n })();\n return promise.then(onfulfilled, onrejected);\n }\n}\n\n// ─── ChatModelStream ────────────────────────────────────────────\n\n/**\n * The main stream object returned by chat model streaming.\n *\n * Implements `AsyncIterable<ChatModelStreamEvent>` for raw event access\n * and `PromiseLike<AIMessage>` for simple `await` usage.\n */\nexport class ChatModelStream\n implements AsyncIterable<ChatModelStreamEvent>, PromiseLike<AIMessage>\n{\n /** @internal */\n private _buffer: ReplayBuffer;\n\n /** @internal */\n constructor(source: AsyncIterable<ChatModelStreamEvent>) {\n this._buffer = new ReplayBuffer();\n this._consume(source);\n }\n\n /** @internal */\n private async _consume(\n source: AsyncIterable<ChatModelStreamEvent>\n ): Promise<void> {\n try {\n for await (const event of source) {\n this._buffer.push(event);\n }\n this._buffer.finish();\n } catch (err) {\n this._buffer.setError(\n err instanceof Error ? err : new Error(String(err))\n );\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<ChatModelStreamEvent> {\n return this._buffer.iterate();\n }\n\n get text(): TextContentStream {\n return new TextContentStream(this._buffer);\n }\n\n get toolCalls(): ToolCallsStream {\n return new ToolCallsStream(this._buffer);\n }\n\n get reasoning(): ReasoningContentStream {\n return new ReasoningContentStream(this._buffer);\n }\n\n get usage(): UsageMetadataStream {\n return new UsageMetadataStream(this._buffer);\n }\n\n get output(): PromiseLike<AIMessage> {\n return this._assembleMessage();\n }\n\n then<TResult1 = AIMessage, TResult2 = never>(\n onfulfilled?:\n | ((value: AIMessage) => TResult1 | PromiseLike<TResult1>)\n | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): PromiseLike<TResult1 | TResult2> {\n return this._assembleMessage().then(onfulfilled, onrejected);\n }\n\n /** @internal */\n private async _assembleMessage(): Promise<AIMessage> {\n const contentBlocks: Array<ContentBlock | undefined> = [];\n let id: string | undefined;\n let usage: UsageMetadata | undefined;\n let metadata: Record<string, unknown> = {};\n let finishReason: string | undefined;\n\n for await (const event of this._buffer.iterate()) {\n switch (event.event) {\n case \"message-start\":\n id = event.id ?? id;\n if (event.usage) usage = normalizeUsage(event.usage);\n break;\n\n case \"content-block-start\":\n contentBlocks[event.index] = event.content;\n break;\n\n case \"content-block-delta\": {\n const current = contentBlocks[event.index];\n const delta = getEventDelta(event);\n if (current) {\n if (delta) contentBlocks[event.index] = applyDelta(current, delta);\n }\n break;\n }\n\n case \"content-block-finish\":\n contentBlocks[event.index] = event.content;\n break;\n\n case \"usage\":\n usage = normalizeUsage(event.usage);\n break;\n\n case \"message-finish\":\n finishReason = event.reason;\n if (event.usage) usage = normalizeUsage(event.usage);\n if (event.responseMetadata) {\n metadata = {\n ...metadata,\n ...event.responseMetadata,\n };\n }\n break;\n\n default:\n break;\n }\n }\n\n const filteredBlocks = contentBlocks\n .filter((b): b is ContentBlock => b != null)\n .map(standardizeToolBlock);\n\n return new AIMessage({\n id,\n content: filteredBlocks,\n usage_metadata: usage,\n response_metadata: {\n ...metadata,\n ...(finishReason ? { finish_reason: finishReason } : {}),\n output_version: \"v1\" as const,\n },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,eAAN,MAAmB;CACjB,SAAyC,CAAC;CAC1C,WAAmB;CACnB,UAAqC,CAAC;CACtC,QAA8B;CAE9B,KAAK,OAAmC;EACtC,KAAK,OAAO,KAAK,KAAK;EACtB,MAAM,SAAS,KAAK,QAAQ,OAAO,CAAC;EACpC,KAAK,MAAM,UAAU,QACnB,OAAO;CAEX;CAEA,SAAe;EACb,KAAK,WAAW;EAChB,MAAM,SAAS,KAAK,QAAQ,OAAO,CAAC;EACpC,KAAK,MAAM,UAAU,QACnB,OAAO;CAEX;CAEA,SAAS,KAAkB;EACzB,KAAK,QAAQ;EACb,KAAK,WAAW;EAChB,MAAM,SAAS,KAAK,QAAQ,OAAO,CAAC;EACpC,KAAK,MAAM,UAAU,QACnB,OAAO;CAEX;CAEA,OAAO,UAAgD;EACrD,IAAI,KAAK,UAAU;GACjB,IAAI,KAAK,OAAO,MAAM,KAAK;GAC3B,OAAO,KAAK;GACZ;EACF;EAEA,IAAI,SAAS;EACb,OAAO,MAAM;GACX,OAAO,S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