@onereach/step-create-chat-completion 0.0.7-rc.5 → 0.0.7-rc.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,14 +1,14 @@
1
- import Step from '@onereach/flow-sdk/step';
2
- import { CONFIG, IThread, IThreadId, IActionEvent, ACTION, IEvent } from '@onereach/flow-sdk/types';
1
+ import { CONFIG, IThreadId, RESULT, LOCAL, IEvent, IThread, IStepId, STATE, IActionEvent, ACTION } from '@onereach/flow-sdk/types/index.js';
2
+ import { ChatCompletion, ChatCompletionToolMessageParam, ChatCompletionMessageFunctionToolCall, ChatCompletionChunk as ChatCompletionChunk$1, ChatCompletionMessageParam } from 'openai/resources';
3
3
  import { z } from 'zod/v4-mini';
4
- import { ChatCompletionChunk, ChatCompletionMessageToolCall, ChatCompletion, ChatCompletionToolMessageParam, ChatCompletionMessageParam } from 'openai/resources';
4
+ import Step from '@onereach/flow-sdk/step.js';
5
+ import { ChatCompletionMessageFunctionToolCall as ChatCompletionMessageFunctionToolCall$1, ChatCompletionMessageParam as ChatCompletionMessageParam$1, ChatCompletionToolMessageParam as ChatCompletionToolMessageParam$2 } from 'openai/resources.js';
6
+ import { ChatCompletion as ChatCompletion$1, ChatCompletionToolMessageParam as ChatCompletionToolMessageParam$1, ChatCompletionChunk } from 'openai/resources.mjs';
5
7
 
6
8
  declare const dataInSchema: z.ZodMiniObject<{
7
9
  provider: z.ZodMiniString<string>;
8
10
  model: z.ZodMiniString<string>;
9
- tokenName: z.ZodMiniOptional<z.ZodMiniString<string>>;
10
- tokenNameHeader: z.ZodMiniDefault<z.ZodMiniString<string>>;
11
- sessionIdHeader: z.ZodMiniDefault<z.ZodMiniString<string>>;
11
+ accountKey: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
12
12
  typeOfStep: z.ZodMiniEnum<{
13
13
  chat: "chat";
14
14
  completion: "completion";
@@ -17,24 +17,22 @@ declare const dataInSchema: z.ZodMiniObject<{
17
17
  userMessage: z.ZodMiniOptional<z.ZodMiniString<string>>;
18
18
  switchAssistantsMessage: z.ZodMiniDefault<z.ZodMiniBoolean<boolean>>;
19
19
  assistantsFirstMessage: z.ZodMiniOptional<z.ZodMiniString<string>>;
20
- userSettings: z.ZodMiniObject<{
21
- temperature: z.ZodMiniPromise<z.ZodMiniDefault<z.ZodMiniNumber<unknown>>>;
22
- topP: z.ZodMiniPromise<z.ZodMiniOptional<z.ZodMiniNumber<unknown>>>;
23
- maxTokens: z.ZodMiniPromise<z.ZodMiniOptional<z.ZodMiniNumber<unknown>>>;
24
- presencePenalty: z.ZodMiniPromise<z.ZodMiniOptional<z.ZodMiniNumber<unknown>>>;
25
- frequencyPenalty: z.ZodMiniPromise<z.ZodMiniOptional<z.ZodMiniNumber<unknown>>>;
26
- stop: z.ZodMiniPromise<z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniObject<{
27
- token: z.ZodMiniString<string>;
28
- }, z.core.$strip>>>>;
29
- }, z.core.$strip>;
30
- n: z.ZodMiniDefault<z.ZodMiniNumber<unknown>>;
20
+ temperature: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniNumber<unknown>]>, z.ZodMiniTransform<number | undefined, number | "" | undefined>>;
21
+ topP: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniNumber<unknown>]>, z.ZodMiniTransform<number | undefined, number | "" | undefined>>;
22
+ maxTokens: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniNumber<unknown>]>, z.ZodMiniTransform<number | undefined, number | "" | undefined>>;
23
+ presencePenalty: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniNumber<unknown>]>, z.ZodMiniTransform<number | undefined, number | "" | undefined>>;
24
+ frequencyPenalty: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniNumber<unknown>]>, z.ZodMiniTransform<number | undefined, number | "" | undefined>>;
25
+ n: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniNumber<unknown>]>, z.ZodMiniTransform<number | undefined, number | "" | undefined>>;
26
+ stop: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniObject<{
27
+ token: z.ZodMiniString<string>;
28
+ }, z.core.$strip>>>;
31
29
  streamResponse: z.ZodMiniDefault<z.ZodMiniBoolean<boolean>>;
32
30
  streamSettings: z.ZodMiniOptional<z.ZodMiniObject<{
33
- maxBufferLength: z.ZodMiniPromise<z.ZodMiniNumber<unknown>>;
34
- debounceDuration: z.ZodMiniPromise<z.ZodMiniNumber<unknown>>;
31
+ maxBufferLength: z.ZodMiniNumber<unknown>;
32
+ debounceDuration: z.ZodMiniNumber<unknown>;
35
33
  }, z.core.$strip>>;
36
34
  customHistory: z.ZodMiniDefault<z.ZodMiniBoolean<boolean>>;
37
- historyRange: z.ZodMiniDefault<z.ZodMiniNumber<unknown>>;
35
+ historyLength: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniNumber<unknown>]>, z.ZodMiniTransform<number | undefined, number | "" | undefined>>;
38
36
  historyMode: z.ZodMiniOptional<z.ZodMiniEnum<{
39
37
  mergefield: "mergefield";
40
38
  codeHistory: "codeHistory";
@@ -62,7 +60,7 @@ declare const dataInSchema: z.ZodMiniObject<{
62
60
  content: z.ZodMiniString<string>;
63
61
  name: z.ZodMiniOptional<z.ZodMiniString<string>>;
64
62
  tool_call_id: z.ZodMiniString<string>;
65
- }, z.core.$strip>]>>>;
63
+ }, z.core.$strip>], "role">>>;
66
64
  historyCode: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniDiscriminatedUnion<[z.ZodMiniObject<{
67
65
  role: z.ZodMiniLiteral<"system">;
68
66
  content: z.ZodMiniString<string>;
@@ -86,240 +84,162 @@ declare const dataInSchema: z.ZodMiniObject<{
86
84
  content: z.ZodMiniString<string>;
87
85
  name: z.ZodMiniOptional<z.ZodMiniString<string>>;
88
86
  tool_call_id: z.ZodMiniString<string>;
89
- }, z.core.$strip>]>>>;
87
+ }, z.core.$strip>], "role">>>;
88
+ functionsList: z.ZodMiniArray<z.ZodMiniObject<{
89
+ name: z.ZodMiniString<string>;
90
+ description: z.ZodMiniOptional<z.ZodMiniString<string>>;
91
+ parameters: z.ZodMiniOptional<z.ZodMiniPipe<z.ZodMiniObject<{
92
+ type: z.ZodMiniLiteral<"object">;
93
+ properties: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniObject<{
94
+ type: z.ZodMiniEnum<{
95
+ string: "string";
96
+ number: "number";
97
+ boolean: "boolean";
98
+ object: "object";
99
+ array: "array";
100
+ }>;
101
+ description: z.ZodMiniOptional<z.ZodMiniString<string>>;
102
+ items: z.ZodMiniOptional<z.ZodMiniObject<{
103
+ type: z.ZodMiniEnum<{
104
+ string: "string";
105
+ number: "number";
106
+ boolean: "boolean";
107
+ object: "object";
108
+ }>;
109
+ description: z.ZodMiniOptional<z.ZodMiniString<string>>;
110
+ }, z.core.$strip>>;
111
+ }, z.core.$strip>>;
112
+ }, z.core.$strip>, z.ZodMiniTransform<{
113
+ type: "object";
114
+ properties: Record<string, {
115
+ type: "string" | "number" | "boolean" | "object" | "array";
116
+ description?: string | undefined;
117
+ items?: {
118
+ type: "string" | "number" | "boolean" | "object";
119
+ description?: string | undefined;
120
+ } | undefined;
121
+ }>;
122
+ } & {
123
+ additionalProperties: false;
124
+ required: string[];
125
+ }, {
126
+ type: "object";
127
+ properties: Record<string, {
128
+ type: "string" | "number" | "boolean" | "object" | "array";
129
+ description?: string | undefined;
130
+ items?: {
131
+ type: "string" | "number" | "boolean" | "object";
132
+ description?: string | undefined;
133
+ } | undefined;
134
+ }>;
135
+ } & {
136
+ additionalProperties: false;
137
+ required: string[];
138
+ }>>>;
139
+ strict: z.ZodMiniBoolean<boolean>;
140
+ }, z.core.$strip>>;
90
141
  processError: z.ZodMiniBoolean<boolean>;
91
142
  processTimeout: z.ZodMiniBoolean<boolean>;
92
143
  timeoutDuration: z.ZodMiniString<string>;
93
144
  }, z.core.$strip>;
94
145
  type DataIn = z.infer<typeof dataInSchema>;
95
146
 
96
- declare class StreamWorker extends Step<StreamWorkerConfig> {
97
- static readonly class = "str_wrk";
98
- static start(step: Step<StreamControllerConfig>, event: ContentChunk): Promise<void>;
99
- static isBusy(step: Step<StreamControllerConfig>): boolean;
100
- static getThread(step: Step<StreamControllerConfig>): IThread<StreamWorkerConfig> | undefined;
101
- static getThreadId(step: Step<StreamControllerConfig>): IThreadId;
102
- runStep(): void;
103
- }
104
- type ContentChunk = {
105
- content: string;
106
- index: number;
107
- ts: number;
108
- };
109
- type StreamWorkerOut = {
110
- chunk: ContentChunk;
111
- };
112
- type StreamWorkerState = {
113
- class: typeof StreamWorker.class;
114
- event: ContentChunk;
115
- };
116
- interface StreamWorkerConfig extends CONFIG {
147
+ interface BaseConfig extends CONFIG {
117
148
  dataIn: DataIn;
118
- dataOut: StreamWorkerOut;
119
- state: StreamWorkerState;
120
149
  }
121
150
 
122
- declare class StreamController extends Step<StreamControllerConfig> {
123
- static readonly class = "str_ctrl";
124
- static start(step: Step<ChatCompletionConfig>): Promise<void>;
125
- static handleChunk(step: Step<ChatCompletionConfig>, chunk: ChatCompletionChunk): Promise<void>;
126
- static lastChunkReceived(step: Step<ChatCompletionConfig>): Promise<void>;
127
- static getThreadId(step: Step): IThreadId;
128
- runStep(): void;
129
- /**
130
- * Handler of the worker thread end event.
131
- */
132
- onWorkerThreadEnd(event: IActionEvent<StreamWorkerConfig, ACTION.end>): void;
133
- /**
134
- * Handles a single chunk of the streaming response from the OpenAI API.
135
- */
136
- onStreamChunk(event: IEvent<StreamChunkParams, EventName$2.handleChunk>): void;
137
- protected handleMultipleChoices(choice: ChatCompletionChunk.Choice): void;
138
- protected handleLengthFinishReason(choice: ChatCompletionChunk.Choice): void;
139
- protected onToolCall(toolCall: ChatCompletionMessageToolCall): void;
140
- /**
141
- * Tries to flush the queue of response chunks to the controller thread.
142
- * If the first event in the queue is not full, it waits for a debounce duration before flushing.
143
- * If the first event is full, it flushes it immediately.
144
- */
145
- private scheduleNextContentEvent;
146
- /**
147
- * Compacts the content into the controller thread's events queue.
148
- * If the content is too long, it splits it into multiple events.
149
- * If the last event is not full, it extends it with the new content.
150
- */
151
- private addContentToQueue;
152
- /**
153
- * Processes the next event in the controller thread's queue.
154
- * If the worker thread is busy, it skips processing.
155
- * If the event is the termination marker, it notifies the end of the controller thread.
156
- * If the event is ready for processing, it starts the worker thread to handle it.
157
- */
158
- tryRunWorker(): void;
159
- private isEventReady;
160
- private getEventToProcess;
161
- /**
162
- * Handles the notification that all response chunks were received from the OpenAI API.
163
- */
164
- onLastStreamChunkReceived(): Promise<void>;
165
- protected get maxChunkContentLength(): number;
166
- protected get debounceDuration(): number;
167
- }
168
- declare enum EventName$2 {
169
- handleChunk = "add_chunk",
170
- lastStreamChunkReceived = "llm_rsp_end"
171
- }
172
- type ContentChunkEvent = {
173
- content: string;
174
- index: number;
175
- ts: number;
151
+ type ManagedThreadLocal = {
152
+ active: boolean;
153
+ parent: IThreadId;
176
154
  };
177
- type ContentEndEvent = {
178
- lastChunkReceived: true;
179
- };
180
- type ContentEvent = ContentChunkEvent | ContentEndEvent;
181
- type StreamChunkParams = {
182
- chunk: ChatCompletionChunk;
183
- };
184
- type StreamControllerEvents = IEvent<StreamChunkParams, 'add_chunk'> | IEvent<unknown, 'llm_rsp_end'>;
185
- type StreamControllerState = {
186
- class: typeof StreamController.class;
187
- completionResult: Partial<ChatCompletion>;
188
- events: ContentEvent[];
189
- index: number;
190
- lastChunkReceived: boolean;
191
- debounceId?: NodeJS.Timeout;
192
- skipIndexWarning: boolean;
193
- };
194
- type StreamControllerResult = {
195
- status: 'ok';
196
- completion: ChatCompletion;
155
+
156
+ type BaseChildResultCancel = {
157
+ status: 'cancel';
197
158
  };
198
- interface StreamControllerConfig extends CONFIG {
199
- dataIn: DataIn;
200
- state: StreamControllerState;
201
- result: StreamControllerResult;
202
- events: StreamControllerEvents;
159
+ type BaseChildResult = BaseChildResultCancel | Error;
160
+ type BaseChildLocal = ManagedThreadLocal;
161
+ interface BaseChildConfig<TResult extends RESULT<CONFIG> = BaseChildResult, TLocal extends LOCAL<CONFIG> = BaseChildLocal> extends BaseConfig {
162
+ result: TResult;
163
+ local: TLocal;
203
164
  }
204
165
 
205
- declare class ToolsWorker<TArgs extends ParsedArguments, TResult> extends Step<ToolsWorkerConfig<TArgs, TResult>> {
206
- static readonly class = "tl_wrk";
207
- static start<TArgs extends ParsedArguments, TResult>(step: Step<ToolsControllerConfig<TResult>>, toolCall: ChatCompletionMessageToolCall): Promise<void>;
208
- static getThreadId(toolCall: ChatCompletionMessageToolCall): IThreadId;
209
- /**
210
- * Initializes the tool worker thread to handle processing of repackaged content chunks.
211
- */
212
- runStep(): void;
213
- protected getExitName(toolCall: ChatCompletionMessageToolCall): string;
214
- }
215
- type ParsedArguments<TArgs extends Record<string, unknown> = Record<string, unknown>> = TArgs;
216
- type ToolCallWithParsedArgs<TArgs extends ParsedArguments> = {
217
- id: string;
218
- type: 'function';
219
- function: {
220
- name: string;
221
- arguments: TArgs;
222
- };
223
- };
224
- type ToolsWorkerMergeField<TArgs extends ParsedArguments> = {
225
- toolCall: ToolCallWithParsedArgs<TArgs>;
226
- };
227
- type ToolsWorkerOut<TArgs extends ParsedArguments> = ToolsWorkerMergeField<TArgs>;
228
- type ToolsWorkerState = {
229
- class: typeof ToolsWorker.class;
166
+ declare const cancelContextClassId = "cncl_ctrl";
167
+ declare const parentEvents: {
168
+ readonly cancel: "st_cancel";
230
169
  };
231
- type ToolsWorkerLocal<TArgs extends ParsedArguments> = {
232
- toolCall: ChatCompletionMessageToolCall;
233
- parsedArguments: TArgs;
170
+ type ParentEventName = typeof parentEvents;
171
+ declare const cancelContentEvents: {
172
+ readonly cancel: "cnl_cancel";
234
173
  };
235
- type ThreadWorkerResult<TResult> = {
236
- toolCallId: string;
237
- data: TResult;
174
+ type CancelContentEventName = typeof cancelContentEvents;
175
+ type CancelContextEvents = IEvent<unknown, CancelContentEventName['cancel']>;
176
+ type CancelContextState = {
177
+ class: typeof cancelContextClassId;
238
178
  };
239
- interface ToolsWorkerConfig<TArgs extends ParsedArguments, TResult> extends CONFIG {
240
- dataIn: DataIn;
241
- dataOut: ToolsWorkerOut<TArgs>;
242
- state: ToolsWorkerState;
243
- result: ThreadWorkerResult<TResult>;
244
- local: ToolsWorkerLocal<TArgs>;
179
+ interface CancelContextConfig extends BaseChildConfig {
180
+ state: CancelContextState;
181
+ events: CancelContextEvents;
245
182
  }
246
183
 
247
- declare class ToolsController<TArgs extends ParsedArguments, TResult> extends Step<ToolsControllerConfig<TResult>> {
248
- static readonly class = "tl_ctrl";
249
- static start<TResult>(step: Step<ChatCompletionConfig>): Promise<void>;
250
- static callTool<T extends ChatCompletionConfig | StreamControllerConfig>(step: Step<T>, toolCall: ChatCompletionMessageToolCall): Promise<void>;
251
- static lastToolCallReceived<T extends ChatCompletionConfig | StreamControllerConfig>(step: Step<T>): Promise<void>;
252
- static getThreadId<T extends CONFIG>(step: Step<T>): IThreadId;
253
- runStep(): void;
254
- onCallTool(event: IEvent<CallToolParams, EventName$1.callTool>): void;
255
- onLastToolCallReceived(): void;
256
- /**
257
- * Starts the tool worker thread to process the tool call.
258
- */
259
- protected startToolWorkerThread(toolCall: ChatCompletionMessageToolCall): void;
260
- onToolWorkerThreadEnd(event: IActionEvent<ToolsWorkerConfig<TArgs, TResult>, ACTION.end>): void;
261
- protected setToolCallResult(toolCallId: string, result: TResult): void;
262
- protected tryEndToolsControllerThread(): void;
263
- protected get messages(): ChatCompletionToolMessageParam[];
264
- }
265
- declare enum EventName$1 {
266
- callTool = "tl_run_call",
267
- lastToolCallReceived = "tl_rsp_end"
268
- }
269
- type ToolCallTask<TResult> = {
270
- status: 'pending' | 'completed' | 'failed';
271
- call: ChatCompletionMessageToolCall;
272
- result?: TResult;
273
- };
274
- type TasksMap<TResult> = Record<ChatCompletionMessageToolCall['id'], ToolCallTask<TResult>>;
275
- type ToolsControllerResult = {
276
- status: 'ok';
277
- messages: ChatCompletionToolMessageParam[];
278
- };
279
- type CallToolParams = {
280
- toolCall: ChatCompletionMessageToolCall;
281
- };
282
- type ToolsControllerEvents = IEvent<CallToolParams, EventName$1.callTool> | IEvent<never, EventName$1.lastToolCallReceived>;
283
- type ToolsControllerState<TResult> = {
284
- tasks: TasksMap<TResult>;
285
- expectMoreTasks: boolean;
184
+ type ChatCompletionOut = ChatCompletion;
185
+ type ChatCompletionState = {
186
+ cancelled: boolean;
187
+ contentReady: boolean;
188
+ chatCompletion?: ChatCompletion;
189
+ toolsResults: ChatCompletionToolMessageParam[];
286
190
  };
287
- interface ToolsControllerConfig<TResult> extends CONFIG {
288
- dataIn: DataIn;
289
- state: ToolsControllerState<TResult>;
290
- result: ToolsControllerResult;
291
- events: ToolsControllerEvents;
191
+ type ChatCompletionCancelEvent = IEvent<unknown, ParentEventName['cancel']>;
192
+ type ChatCompletionEvent = ChatCompletionCancelEvent;
193
+ interface ChatCompletionConfig extends BaseConfig {
194
+ dataOut: ChatCompletionOut;
195
+ state: ChatCompletionState;
196
+ events: ChatCompletionEvent;
292
197
  }
293
198
 
294
- declare class CreateChatCompletionStep<TResult> extends Step<ChatCompletionConfig> {
199
+ declare class BaseStep<T extends BaseConfig> extends Step<T> {
295
200
  resolveDataIn(): Promise<{
296
201
  provider: string;
297
202
  model: string;
298
- tokenNameHeader: string;
299
- sessionIdHeader: string;
203
+ accountKey: string | undefined;
300
204
  typeOfStep: "chat" | "completion";
301
205
  switchAssistantsMessage: boolean;
302
- userSettings: {
303
- temperature: number;
304
- topP: number | undefined;
305
- maxTokens: number | undefined;
306
- presencePenalty: number | undefined;
307
- frequencyPenalty: number | undefined;
308
- stop: {
309
- token: string;
310
- }[] | undefined;
311
- };
312
- n: number;
206
+ temperature: number | undefined;
207
+ topP: number | undefined;
208
+ maxTokens: number | undefined;
209
+ presencePenalty: number | undefined;
210
+ frequencyPenalty: number | undefined;
211
+ n: number | undefined;
313
212
  streamResponse: boolean;
314
213
  customHistory: boolean;
315
- historyRange: number;
214
+ historyLength: number | undefined;
215
+ functionsList: {
216
+ name: string;
217
+ strict: boolean;
218
+ description?: string | undefined;
219
+ parameters?: ({
220
+ type: "object";
221
+ properties: Record<string, {
222
+ type: "string" | "number" | "boolean" | "object" | "array";
223
+ description?: string | undefined;
224
+ items?: {
225
+ type: "string" | "number" | "boolean" | "object";
226
+ description?: string | undefined;
227
+ } | undefined;
228
+ }>;
229
+ } & {
230
+ additionalProperties: false;
231
+ required: string[];
232
+ }) | undefined;
233
+ }[];
316
234
  processError: boolean;
317
235
  processTimeout: boolean;
318
236
  timeoutDuration: string;
319
- tokenName?: string | undefined;
320
237
  systemMessage?: string | undefined;
321
238
  userMessage?: string | undefined;
322
239
  assistantsFirstMessage?: string | undefined;
240
+ stop?: {
241
+ token: string;
242
+ }[] | undefined;
323
243
  streamSettings?: {
324
244
  maxBufferLength: number;
325
245
  debounceDuration: number;
@@ -374,73 +294,382 @@ declare class CreateChatCompletionStep<TResult> extends Step<ChatCompletionConfi
374
294
  name?: string | undefined;
375
295
  })[] | undefined;
376
296
  }>;
297
+ }
298
+
299
+ declare class CancelContext extends BaseStep<CancelContextConfig> {
300
+ static readonly class = "cncl_ctrl";
301
+ static start(thread: IThread<ChatCompletionConfig>): Promise<void>;
302
+ static stop(thread: IThread<ChatCompletionConfig>): Promise<void>;
303
+ static getThreadId(stepId: IStepId): IThreadId;
377
304
  runStep(): void;
378
- initRequest(): Promise<void>;
379
- private handleResponse;
380
- private handleStreamResponse;
381
- onToolsControllerEnd(event: IActionEvent<ToolsControllerConfig<TResult>, ACTION.end>): Promise<void>;
382
- onStreamControllerThreadEnd(event: IActionEvent<StreamControllerConfig, ACTION.end>): Promise<void>;
383
- private tryToExitStep;
384
- private get history();
385
- private get openAiService();
305
+ initialize(): void;
306
+ onCancel(): void;
386
307
  }
387
- type ChatCompletionOut = ChatCompletion & {
388
- _history: ChatCompletionMessageParam[];
308
+
309
+ declare const requestContextClassId = "rqst_ctx";
310
+ type RequestContextState = {
311
+ class: typeof requestContextClassId;
389
312
  };
390
- type ChatCompletionState = {
391
- toolsReady: boolean;
392
- contentReady: boolean;
393
- chatCompletion?: ChatCompletion;
394
- toolsResults: ChatCompletionToolMessageParam[];
313
+ type RequestContextResultOk = {
314
+ status: 'ok';
395
315
  };
396
- interface ChatCompletionConfig extends CONFIG {
397
- dataIn: DataIn;
398
- dataOut: ChatCompletionOut;
399
- state: ChatCompletionState;
316
+ type RequestContextResult = RequestContextResultOk | RESULT<BaseChildConfig>;
317
+ interface RequestContextConfig extends BaseChildConfig<RequestContextResult> {
318
+ state: RequestContextState;
319
+ result: RequestContextResult;
400
320
  }
401
321
 
402
- declare class HistoryController extends Step<HistoryControllerConfig> {
403
- static readonly class = "hst_ctrl";
404
- static start(step: Step<ChatCompletionConfig>): Promise<void>;
405
- static appendToHistory(step: Step, message: ChatCompletionMessageParam | ChatCompletionMessageParam[]): Promise<void>;
406
- static getHistory(step: Step): ChatCompletionMessageParam[];
407
- static getThreadId(step: Step): IThreadId;
408
- runStep(): void;
322
+ declare const toolsContextClassId = "tl_ctrl";
323
+ declare const toolContextEvents: {
324
+ readonly callTool: "tl_run_call";
325
+ readonly lastToolCallReceived: "tl_rsp_end";
326
+ };
327
+ type ToolContextEventName = typeof toolContextEvents;
328
+ type ToolCallTask = {
329
+ status: 'pending' | 'completed' | 'failed';
330
+ call: ChatCompletionMessageFunctionToolCall;
331
+ /** result of the tool call, if completed */
332
+ result?: unknown;
333
+ };
334
+ type TasksMap = Record<ChatCompletionMessageFunctionToolCall['id'], ToolCallTask>;
335
+ type ToolsContextResultOk = {
336
+ status: 'ok';
337
+ messages: ChatCompletionToolMessageParam[];
338
+ };
339
+ type ToolsContextResult = ToolsContextResultOk | RESULT<BaseChildConfig>;
340
+ type CallToolParameters = {
341
+ toolCall: ChatCompletionMessageFunctionToolCall;
342
+ };
343
+ type ToolsContextEventCallTool = IEvent<CallToolParameters, ToolContextEventName['callTool']>;
344
+ type ToolsContextEventLastToolReceived = IEvent<unknown, ToolContextEventName['lastToolCallReceived']>;
345
+ type ToolsContextEvent = ToolsContextEventCallTool | ToolsContextEventLastToolReceived;
346
+ type ToolsContextState = {
347
+ class: typeof toolsContextClassId;
348
+ /** tool calls from LLM response */
349
+ tasks: TasksMap;
350
+ /** flag to indicate if there are more tasks to process */
351
+ expectMoreTasks: boolean;
352
+ };
353
+ interface ToolsContextConfig extends BaseChildConfig<ToolsContextResult> {
354
+ state: ToolsContextState;
355
+ events: ToolsContextEvent;
356
+ }
357
+
358
+ declare const contentContextEvents: {
359
+ readonly handleContent: "hnd_cnt";
360
+ };
361
+ type ContentContentEventName = typeof contentContextEvents;
362
+ type ContentContextHandleContentEvent = IEvent<{
363
+ content: ChatCompletionChunk | ChatCompletion$1;
364
+ }, ContentContentEventName['handleContent']>;
365
+ type ContentContextEvent = ContentContextHandleContentEvent;
366
+ type ContentContextState = {
367
+ requestComplete: boolean;
368
+ chatCompletion?: ChatCompletion$1;
369
+ /**
370
+ * Are tool calls ready?
371
+ * - `undefined` - no tools to wait for
372
+ * - `false` - tools are processing
373
+ * - `true` - tools finished processing
374
+ */
375
+ toolsReady?: boolean;
376
+ toolsResults?: ChatCompletionToolMessageParam$1[];
377
+ };
378
+ type ContentContextOkResult = {
379
+ status: 'ok';
380
+ chatCompletion: ChatCompletion$1;
381
+ toolsResults: ChatCompletionToolMessageParam$1[];
382
+ };
383
+ type ContentContextResult = ContentContextOkResult | RESULT<BaseChildConfig>;
384
+ interface ContentContextConfig extends BaseChildConfig<ContentContextResult> {
385
+ state: ContentContextState;
386
+ result: ContentContextResult;
387
+ events: ContentContextEvent;
388
+ }
389
+
390
+ declare abstract class AbstractContentContext<T extends ContentContextConfig> extends BaseStep<T> {
391
+ static get class(): string;
392
+ static getInitialState<T extends ContentContextConfig>(): STATE<T>;
393
+ runStep(): void | Promise<void>;
409
394
  initialize(): void;
410
- onAppendToHistory(event: IEvent<HistoryControllerAppendParams, EventName.appendToHistory>): void;
395
+ abstract onHandleContent(event: ContentContextHandleContentEvent): void | Promise<void>;
396
+ protected abstract onAllContentReceived(): void | Promise<void>;
397
+ protected abstract tryToComplete(): void | Promise<void>;
398
+ onRequestContextEnd(event: IActionEvent<RequestContextConfig, ACTION.end>): Promise<void>;
399
+ onToolsContextEnd(event: IActionEvent<ToolsContextConfig, ACTION.end>): Promise<void>;
400
+ protected callFunction(toolCall: ChatCompletionMessageFunctionToolCall$1): Promise<void>;
401
+ protected handleMultipleChoices(): void;
402
+ protected initToolsContextThread(): Promise<void>;
403
+ protected cancel(): void;
404
+ protected complete(): void;
405
+ }
406
+
407
+ type SimpleContentContextHandleContentEvent = IEvent<{
408
+ content: ChatCompletion;
409
+ }, ContentContentEventName['handleContent']>;
410
+ type SimpleContentContextEvent = SimpleContentContextHandleContentEvent;
411
+ interface SimpleContentContextConfig extends ContentContextConfig {
412
+ events: SimpleContentContextEvent;
413
+ }
414
+
415
+ declare class SimpleContentContext extends AbstractContentContext<SimpleContentContextConfig> {
416
+ static readonly class = "cnt_cxt_smp";
417
+ static getInitialState(): STATE<SimpleContentContextConfig>;
418
+ onHandleContent(event: SimpleContentContextHandleContentEvent): Promise<void>;
419
+ onAllContentReceived(): void;
420
+ protected tryToComplete(): void;
421
+ }
422
+
423
+ declare const streamContentContextClassId = "cnt_cxt_str";
424
+ type StreamContentContextHandleContentEvent = IEvent<{
425
+ content: ChatCompletionChunk$1;
426
+ }, ContentContentEventName['handleContent']>;
427
+ type StreamContentContextEvent = StreamContentContextHandleContentEvent;
428
+ type ContentChunkEvent = {
429
+ content: string;
430
+ index: number;
431
+ ts: number;
432
+ };
433
+ type ContentEndEvent = {
434
+ lastChunkReceived: true;
435
+ };
436
+ type ContentEvent = ContentChunkEvent | ContentEndEvent;
437
+ type StreamContentContextState = Omit<ContentContextState, 'class'> & {
438
+ class: typeof streamContentContextClassId;
439
+ /** aggregated result of the LLM response */
440
+ partialChatCompletion: Partial<ChatCompletion>;
441
+ /** queue of response chunks */
442
+ events: ContentEvent[];
443
+ /** last index for a chunk to be processed by worker */
444
+ index: number;
445
+ /** marker for end of response stream */
446
+ lastChunkReceived: boolean;
447
+ /** When `true` means worker finished the processing the queue */
448
+ workerComplete: boolean;
449
+ };
450
+ interface StreamContentContextConfig extends ContentContextConfig {
451
+ events: StreamContentContextEvent;
452
+ state: StreamContentContextState;
453
+ }
454
+
455
+ declare const streamContentContextWorkerClassId = "str_wrk";
456
+ declare const streamWorkerExits: {
457
+ readonly chunk: "chunk";
458
+ };
459
+ type ContentChunk = {
460
+ content: string;
461
+ index: number;
462
+ ts: number;
463
+ };
464
+ type StreamContentContextWorkerOut = {
465
+ chunk: ContentChunk;
466
+ };
467
+ type StreamContentContextWorkerState = {
468
+ class: typeof streamContentContextWorkerClassId;
469
+ event: ContentChunk;
470
+ };
471
+ type StreamContentContextWorkerResult = undefined | RESULT<BaseChildConfig>;
472
+ interface StreamContentContextWorkerConfig extends BaseChildConfig<StreamContentContextWorkerResult> {
473
+ dataOut: StreamContentContextWorkerOut;
474
+ state: StreamContentContextWorkerState;
475
+ }
476
+
477
+ declare class StreamContentContextWorker extends BaseStep<StreamContentContextWorkerConfig> {
478
+ static readonly class = "str_wrk";
479
+ static start(thread: IThread<StreamContentContextConfig>, event: ContentChunk): Promise<void>;
480
+ static isBusy(thread: IThread<StreamContentContextConfig>): boolean;
481
+ static getThreadId(stepId: IStepId): IThreadId;
482
+ runStep(): void;
483
+ }
484
+
485
+ declare class StreamContentContext extends AbstractContentContext<StreamContentContextConfig> {
486
+ static readonly class = "cnt_cxt_str";
487
+ static getInitialState(): STATE<StreamContentContextConfig>;
488
+ runStep(): Promise<void>;
489
+ /**
490
+ * Handler of the worker thread end event.
491
+ */
492
+ onWorkerThreadEnd(event: IActionEvent<StreamContentContextWorkerConfig, ACTION.end>): void;
411
493
  /**
412
- * Adds a message to the managed history of this step
494
+ * Handles a single chunk of the streaming response from the OpenAI API.
413
495
  */
414
- protected appendToManagedHistory(messages: ChatCompletionMessageParam[]): void;
496
+ onHandleContent(event: StreamContentContextHandleContentEvent): void;
415
497
  /**
416
- * Returns the messages to be sent to the OpenAI API.
498
+ * Handles the notification that all response chunks were received from the OpenAI API.
417
499
  */
418
- protected get initialMessages(): ChatCompletionMessageParam[];
419
- }
420
- declare enum EventName {
421
- appendToHistory = "hst_append"
500
+ protected onAllContentReceived(): void;
501
+ private onToolCall;
502
+ /**
503
+ * Tries to flush the queue of response chunks to the controller thread.
504
+ * If the first event in the queue is not full, it waits for a debounce duration before flushing.
505
+ * If the first event is full, it flushes it immediately.
506
+ */
507
+ private scheduleNextContentEvent;
508
+ /**
509
+ * Compacts the content into the controller thread's events queue.
510
+ * If the content is too long, it splits it into multiple events.
511
+ * If the last event is not full, it extends it with the new content.
512
+ */
513
+ private addContentToQueue;
514
+ /**
515
+ * Processes the next event in the controller thread's queue.
516
+ * If the worker thread is busy, it skips processing.
517
+ * If the event is the termination marker, it notifies the end of the controller thread.
518
+ * If the event is ready for processing, it starts the worker thread to handle it.
519
+ */
520
+ private tryRunWorker;
521
+ private isEventReady;
522
+ private getEventToProcess;
523
+ protected tryToComplete(): void;
524
+ protected get maxChunkContentLength(): number;
525
+ protected get debounceDuration(): number;
422
526
  }
423
- type HistoryControllerAppendParams = {
527
+
528
+ declare const historyContextClassId = "hst_ctrl";
529
+ declare const historyContextEvents: {
530
+ readonly appendToHistory: "hst_append";
531
+ readonly prepareHistory: "hst_prepare";
532
+ readonly adjustOnCancel: "hst_cncl";
533
+ };
534
+ type HistoryContextEventName = typeof historyContextEvents;
535
+ type HistoryContextAppendParameters = {
424
536
  message: ChatCompletionMessageParam | ChatCompletionMessageParam[];
425
537
  };
426
- type HistoryControllerEvents = IEvent<HistoryControllerAppendParams, EventName.appendToHistory>;
427
- type HistoryControllerState = {
428
- class: typeof HistoryController.class;
538
+ type HistoryContextEventAppendToHistory = IEvent<HistoryContextAppendParameters, HistoryContextEventName['appendToHistory']>;
539
+ type HistoryContextEventPrepareHistory = IEvent<unknown, HistoryContextEventName['prepareHistory']>;
540
+ type HistoryContextEventAdjustOnCancel = IEvent<unknown, HistoryContextEventName['adjustOnCancel']>;
541
+ type HistoryContextEvent = HistoryContextEventAppendToHistory | HistoryContextEventPrepareHistory | HistoryContextEventAdjustOnCancel;
542
+ type HistoryContextState = {
543
+ class: typeof historyContextClassId;
544
+ /** messages to send to OpenAI API */
429
545
  messages: ChatCompletionMessageParam[];
430
546
  };
431
- interface HistoryControllerConfig extends CONFIG {
432
- dataIn: DataIn;
433
- state: HistoryControllerState;
434
- events: HistoryControllerEvents;
547
+ interface HistoryContextConfig extends BaseConfig {
548
+ state: HistoryContextState;
549
+ events: HistoryContextEvent;
550
+ }
551
+
552
+ declare class HistoryContext extends BaseStep<HistoryContextConfig> {
553
+ static readonly class = "hst_ctrl";
554
+ static start(thread: IThread<ChatCompletionConfig>): Promise<void>;
555
+ static prepareHistory<T extends ChatCompletionConfig>(thread: IThread<T>): Promise<void>;
556
+ static appendToHistory<T extends ChatCompletionConfig>(thread: IThread<T>, message: ChatCompletionMessageParam$1 | ChatCompletionMessageParam$1[]): Promise<void>;
557
+ static adjustOnCancel<T extends ChatCompletionConfig>(thread: IThread<T>): Promise<void>;
558
+ static getHistory<T extends CONFIG>(thread: IThread<T>): ChatCompletionMessageParam$1[];
559
+ static getThreadId(stepId: IStepId): IThreadId;
560
+ runStep(): void;
561
+ initialize(): void;
562
+ onAdjustOnCancel(): void;
563
+ onPrepareHistory(): void;
564
+ onAppendToHistory(event: HistoryContextEventAppendToHistory): void;
565
+ }
566
+
567
+ declare class RequestContext extends BaseStep<RequestContextConfig> {
568
+ static readonly class = "rqst_ctx";
569
+ static start<T extends ContentContextConfig>(thread: IThread<T>): Promise<RequestContextResult>;
570
+ static getThreadId(stepId: IStepId): IThreadId;
571
+ runStep(): Promise<void>;
572
+ private cancel;
573
+ private complete;
574
+ private get history();
575
+ private get openAiService();
576
+ private get responseHandler();
577
+ }
578
+
579
+ declare const toolsContextWorkerClassId = "tl_wrk";
580
+ type ToolsContextParsedArguments = Record<string, unknown>;
581
+ type ToolsContextWorkerMergeField = {
582
+ function: {
583
+ name: string;
584
+ arguments: ToolsContextParsedArguments;
585
+ };
586
+ };
587
+ type ToolsContextWorkerOut = ToolsContextWorkerMergeField;
588
+ type ToolsContextWorkerState = {
589
+ class: typeof toolsContextWorkerClassId;
590
+ };
591
+ type ToolsContextWorkerLocal = {
592
+ toolCall: ChatCompletionMessageFunctionToolCall;
593
+ parsedArguments: ToolsContextParsedArguments;
594
+ } & LOCAL<BaseChildConfig>;
595
+ type ThreadWorkerResultOk = {
596
+ status: 'ok';
597
+ /** id of the tool call that was processed */
598
+ toolCallId: string;
599
+ /** result of the tool call */
600
+ data: unknown;
601
+ };
602
+ type ThreadWorkerResult = ThreadWorkerResultOk | RESULT<BaseChildConfig>;
603
+ interface ToolsContextWorkerConfig extends BaseChildConfig<ThreadWorkerResult, ToolsContextWorkerLocal> {
604
+ dataOut: ToolsContextWorkerOut;
605
+ state: ToolsContextWorkerState;
606
+ }
607
+
608
+ declare class ToolsContextWorker extends BaseStep<ToolsContextWorkerConfig> {
609
+ static readonly class = "tl_wrk";
610
+ static start(thread: IThread<ToolsContextConfig>, toolCall: ChatCompletionMessageFunctionToolCall$1): Promise<void>;
611
+ static getThreadId(toolCall: ChatCompletionMessageFunctionToolCall$1): IThreadId;
612
+ /**
613
+ * Initializes the tool worker thread to handle processing of repackaged content chunks.
614
+ */
615
+ runStep(): void;
616
+ protected getExitName(): string;
617
+ }
618
+
619
+ declare class ToolsContext extends BaseStep<ToolsContextConfig> {
620
+ static readonly class = "tl_ctrl";
621
+ static start<T extends ContentContextConfig>(thread: IThread<T>): Promise<void>;
622
+ static callTool<T extends ContentContextConfig>(thread: IThread<T>, toolCall: ChatCompletionMessageFunctionToolCall$1): Promise<void>;
623
+ /**
624
+ * Notify tools context thread that no more tool calls are expected
625
+ */
626
+ static lastToolCallReceived<T extends ContentContextConfig>(thread: IThread<T>): Promise<void>;
627
+ static getThreadId(stepId: IStepId): IThreadId;
628
+ runStep(): void;
629
+ initialize(): void;
630
+ onCallTool(event: ToolsContextEventCallTool): void;
631
+ onLastToolCallReceived(): void;
632
+ onWorkerThreadEnd(event: IActionEvent<ToolsContextWorkerConfig, ACTION.end>): void;
633
+ /**
634
+ * Starts the tool worker thread to process the tool call.
635
+ */
636
+ protected startToolWorkerThread(toolCall: ChatCompletionMessageFunctionToolCall$1): void;
637
+ protected setToolCallResult(toolCallId: string, result: unknown): void;
638
+ protected tryEndToolsContextThread(): void;
639
+ protected get messages(): ChatCompletionToolMessageParam$2[];
640
+ }
641
+
642
+ declare class CreateChatCompletionStep extends BaseStep<ChatCompletionConfig> {
643
+ runStep(): void;
644
+ initialize(): Promise<void>;
645
+ onContentContextEnd(event: IActionEvent<ContentContextConfig, ACTION.end>): Promise<void>;
646
+ onHistoryContextEnd(event: IActionEvent<HistoryContextConfig, ACTION.end>): Promise<void>;
647
+ onCancel(): Promise<void>;
648
+ private tryToExitStep;
649
+ /**
650
+ * Reset the step so it can handle new request
651
+ *
652
+ * - Reset state of initial thread (e.g. main) to original state;
653
+ * - End CancelContext thread;
654
+ * - End ContentController (with child thread);
655
+ *
656
+ * @throws if there any issues with stopping threads
657
+ */
658
+ private resetStep;
659
+ private resetState;
660
+ private validateMergeFieldType;
661
+ private get contentContext();
435
662
  }
436
663
 
437
- declare const step: typeof CreateChatCompletionStep;
438
664
  declare const states: {
439
- hst_ctrl: typeof HistoryController;
440
- tl_ctrl: typeof ToolsController;
441
- tl_wrk: typeof ToolsWorker;
442
- str_ctrl: typeof StreamController;
443
- str_wrk: typeof StreamWorker;
665
+ hst_ctrl: typeof HistoryContext;
666
+ rqst_ctx: typeof RequestContext;
667
+ tl_ctrl: typeof ToolsContext;
668
+ tl_wrk: typeof ToolsContextWorker;
669
+ cnt_cxt_smp: typeof SimpleContentContext;
670
+ cnt_cxt_str: typeof StreamContentContext;
671
+ str_wrk: typeof StreamContentContextWorker;
672
+ cncl_ctrl: typeof CancelContext;
444
673
  };
445
674
 
446
- export { states, step };
675
+ export { type CallToolParameters, type CancelContentEventName, type CancelContextConfig, type CancelContextEvents, type CancelContextState, type ChatCompletionCancelEvent, type ChatCompletionConfig, type ChatCompletionEvent, type ChatCompletionOut, type ChatCompletionState, type ContentChunk, type ContentChunkEvent, type ContentContentEventName, type ContentContextConfig, type ContentContextEvent, type ContentContextHandleContentEvent, type ContentContextOkResult, type ContentContextResult, type ContentContextState, type ContentEndEvent, type ContentEvent, type HistoryContextAppendParameters, type HistoryContextConfig, type HistoryContextEvent, type HistoryContextEventAdjustOnCancel, type HistoryContextEventAppendToHistory, type HistoryContextEventName, type HistoryContextEventPrepareHistory, type HistoryContextState, type ParentEventName, type RequestContextConfig, type RequestContextResult, type RequestContextResultOk, type RequestContextState, type SimpleContentContextConfig, type SimpleContentContextEvent, type SimpleContentContextHandleContentEvent, type StreamContentContextConfig, type StreamContentContextEvent, type StreamContentContextHandleContentEvent, type StreamContentContextState, type StreamContentContextWorkerConfig, type StreamContentContextWorkerOut, type StreamContentContextWorkerResult, type StreamContentContextWorkerState, type TasksMap, type ThreadWorkerResult, type ThreadWorkerResultOk, type ToolCallTask, type ToolContextEventName, type ToolsContextConfig, type ToolsContextEvent, type ToolsContextEventCallTool, type ToolsContextEventLastToolReceived, type ToolsContextParsedArguments, type ToolsContextResult, type ToolsContextResultOk, type ToolsContextState, type ToolsContextWorkerConfig, type ToolsContextWorkerLocal, type ToolsContextWorkerMergeField, type ToolsContextWorkerOut, type ToolsContextWorkerState, cancelContentEvents, cancelContextClassId, contentContextEvents, historyContextClassId, historyContextEvents, parentEvents, requestContextClassId, states, CreateChatCompletionStep as step, streamContentContextClassId, streamContentContextWorkerClassId, streamWorkerExits, toolContextEvents, toolsContextClassId, toolsContextWorkerClassId };