Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 14x 14x 14x 14x 14x 14x 14x 2x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 15x 187x 14x 14x 187x 57x 57x 187x 127x 127x 187x 128x 128x 128x 1x 128x 1x 128x 187x 2x 187x 15x 15x 1x 1x 1x 15x 15x 13x 2x 13x 2x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x | import { Message } from "./Message.js";
import {
ContentPart,
isBinaryContent,
formatMultimodalContent,
MessageContent
} from "./Content.js";
import { ChatOptions } from "./ChatOptions.js";
import { Provider, ChatChunk, Usage, ThinkingResult } from "../providers/Provider.js";
import { ChatResponseString } from "./ChatResponse.js";
import { Stream } from "../streaming/Stream.js";
import { config } from "../config.js";
import { ToolExecutionMode } from "../constants.js";
import { AskOptions } from "./Chat.js";
import { FileLoader } from "../utils/FileLoader.js";
import { toJsonSchema } from "../schema/to-json-schema.js";
import { ToolDefinition, ToolCall } from "./Tool.js";
import { ChatValidator } from "./Validation.js";
import { ToolHandler } from "./ToolHandler.js";
import { logger } from "../utils/logger.js";
import { ResponseFormat } from "../providers/Provider.js";
/**
* Internal handler for chat streaming logic.
* Wraps the provider's stream with side effects like history updates and events.
*/
export class ChatStream {
private messages: Message[];
private systemMessages: Message[];
constructor(
private readonly provider: Provider,
private readonly model: string,
private readonly options: ChatOptions = {},
messages?: Message[],
systemMessages?: Message[]
) {
this.messages = messages ?? [];
this.systemMessages = systemMessages ?? [];
Eif (this.messages.length === 0 && this.systemMessages.length === 0) {
Iif (options.systemPrompt) {
this.systemMessages.push({
role: "system",
content: options.systemPrompt
});
}
Iif (options.messages) {
for (const msg of options.messages) {
if (msg.role === "system" || msg.role === "developer") {
this.systemMessages.push(msg);
} else {
this.messages.push(msg);
}
}
}
}
if (!this.options.toolExecution) {
this.options.toolExecution = config.toolExecution || ToolExecutionMode.AUTO;
}
}
get history(): readonly Message[] {
return [...this.systemMessages, ...this.messages];
}
create(content: string | ContentPart[], options: AskOptions = {}): Stream<ChatChunk> {
const controller = new AbortController();
const sideEffectGenerator = async function* (
self: ChatStream,
provider: Provider,
model: string,
messages: Message[],
systemMessages: Message[],
baseOptions: ChatOptions,
abortController: AbortController,
content: string | ContentPart[],
requestOptions: AskOptions
) {
const options = {
...baseOptions,
...requestOptions,
headers: { ...baseOptions.headers, ...requestOptions.headers }
};
// Process Multimodal Content
let messageContent: MessageContent = content;
const files = [...(requestOptions.images ?? []), ...(requestOptions.files ?? [])];
Iif (files.length > 0) {
const processedFiles = await Promise.all(files.map((f: string) => FileLoader.load(f)));
const hasBinary = processedFiles.some(isBinaryContent);
ChatValidator.validateVision(provider, model, hasBinary, options);
messageContent = formatMultimodalContent(content, processedFiles);
}
if (options.tools && options.tools.length > 0) {
ChatValidator.validateTools(provider, model, true, options);
}
messages.push({ role: "user", content: messageContent });
Iif (!provider.stream) {
throw new Error("Streaming not supported by provider");
}
// Process Schema/Structured Output
let responseFormat: ResponseFormat | undefined = options.responseFormat;
Iif (!responseFormat && options.schema) {
ChatValidator.validateStructuredOutput(provider, model, true, options);
const jsonSchema = toJsonSchema(options.schema.definition.schema);
responseFormat = {
type: "json_schema",
json_schema: {
name: options.schema.definition.name,
description: options.schema.definition.description,
strict: options.schema.definition.strict ?? true,
schema: jsonSchema
}
};
}
Iif (!provider.stream) {
throw new Error("Streaming not supported by provider");
}
let isFirst = true;
const maxToolCalls = options.maxToolCalls ?? 5;
let stepCount = 0;
const totalUsage: Usage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 };
const trackUsage = (u?: Usage) => {
if (u) {
totalUsage.input_tokens += u.input_tokens;
totalUsage.output_tokens += u.output_tokens;
totalUsage.total_tokens += u.total_tokens;
if (u.cached_tokens) {
totalUsage.cached_tokens = (totalUsage.cached_tokens ?? 0) + u.cached_tokens;
}
}
};
while (true) {
stepCount++;
Iif (stepCount > maxToolCalls) {
throw new Error(
`[NodeLLM] Maximum tool execution calls (${maxToolCalls}) exceeded during streaming.`
);
}
let fullContent = "";
let fullReasoning = "";
const thinking: ThinkingResult = { text: "" };
let toolCalls: ToolCall[] | undefined;
let currentTurnUsage: Usage | undefined;
try {
let requestMessages = [...systemMessages, ...messages];
if (options.onBeforeRequest) {
const result = await options.onBeforeRequest(requestMessages);
Eif (result) {
requestMessages = result;
}
}
for await (const chunk of provider.stream({
model,
messages: requestMessages,
tools: options.tools as ToolDefinition[],
temperature: options.temperature,
max_tokens: options.maxTokens ?? config.maxTokens,
response_format: responseFormat,
headers: options.headers,
requestTimeout: options.requestTimeout ?? config.requestTimeout,
thinking: options.thinking,
signal: abortController.signal,
...options.params
})) {
if (isFirst) {
if (options.onNewMessage) options.onNewMessage();
isFirst = false;
}
if (chunk.content) {
fullContent += chunk.content;
yield chunk;
}
if (chunk.reasoning) {
fullReasoning += chunk.reasoning;
yield { content: "", reasoning: chunk.reasoning };
}
if (chunk.thinking) {
Eif (chunk.thinking.text) {
thinking.text += chunk.thinking.text;
}
if (chunk.thinking.signature) {
thinking.signature = chunk.thinking.signature;
}
if (chunk.thinking.tokens) {
thinking.tokens = (thinking.tokens ?? 0) + chunk.thinking.tokens;
}
yield chunk;
}
if (chunk.tool_calls) {
toolCalls = chunk.tool_calls;
}
Iif ((chunk as { usage?: Usage }).usage) {
currentTurnUsage = (chunk as { usage: Usage }).usage;
trackUsage(currentTurnUsage);
}
}
let assistantResponse = new ChatResponseString(
fullContent || "",
currentTurnUsage || { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
model,
provider.id,
thinking.text || thinking.signature ? thinking : undefined,
fullReasoning || undefined
);
if (options.onAfterResponse) {
const result = await options.onAfterResponse(assistantResponse);
Eif (result) {
assistantResponse = result;
}
}
messages.push({
role: "assistant",
content: assistantResponse || null,
tool_calls: toolCalls,
reasoning: fullReasoning || undefined,
usage: currentTurnUsage
});
if (!toolCalls || toolCalls.length === 0) {
if (options.onEndMessage) {
options.onEndMessage(assistantResponse);
}
break;
}
if (!ToolHandler.shouldExecuteTools(toolCalls, options.toolExecution)) {
break;
}
for (const toolCall of toolCalls) {
Eif (options.toolExecution === ToolExecutionMode.CONFIRM) {
const approved = await ToolHandler.requestToolConfirmation(
toolCall,
options.onConfirmToolCall
);
Iif (!approved) {
messages.push(
provider.formatToolResultMessage(toolCall.id, "Action cancelled by user.")
);
continue;
}
}
try {
const toolResult = await ToolHandler.execute(
toolCall,
options.tools as unknown as ToolDefinition[],
options.onToolCallStart,
options.onToolCallEnd
);
messages.push(
provider.formatToolResultMessage(toolResult.tool_call_id, toolResult.content)
);
} catch (error: unknown) {
const err = error as Error & { fatal?: boolean; status?: number };
const directive = await options.onToolCallError?.(toolCall, err);
if (directive === "STOP") {
throw error;
}
messages.push(
provider.formatToolResultMessage(
toolCall.id,
`Fatal error executing tool '${toolCall.function.name}': ${err.message}`,
{ isError: true }
)
);
if (directive === "CONTINUE") {
continue;
}
const isFatal = err.fatal === true || err.status === 401 || err.status === 403;
if (isFatal) {
throw err;
}
logger.error(
`Tool execution failed for '${toolCall.function.name}':`,
error as Error
);
}
}
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
// Aborted
}
throw error;
}
}
};
return new Stream(
() =>
sideEffectGenerator(
this,
this.provider,
this.model,
this.messages,
this.systemMessages,
this.options,
controller,
content,
options
),
controller
);
}
}
|