-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathchat-message-controller.ts
358 lines (310 loc) · 10.7 KB
/
chat-message-controller.ts
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import { type ChatMessage, ChatMessageRole } from '@/api/chats';
import { AppChatStreamState, type BaseAnnotation, type ChatMessageAnnotation, type StackVMState, type StackVMStateAnnotation } from '@/components/chat/chat-stream-state';
import { StackVM } from '@/lib/stackvm';
import EventEmitter from 'eventemitter3';
export interface OngoingState<State = AppChatStreamState> {
finished: boolean;
state: State;
display: string;
message?: string;
}
export interface OngoingStateHistoryItem<State = AppChatStreamState> {
state: OngoingState<State>;
time: Date;
}
export interface ChatMessageControllerEventsMap<State = AppChatStreamState> {
'update': [assistant_message: ChatMessage];
'stream-update': [ongoing_message: ChatMessage, ongoing: OngoingState<State>, delta: string];
'stream-history-update': [ongoing_message: ChatMessage, history: { state: OngoingState<State>, time: Date }[]];
'stream-finished': [ongoing_message: ChatMessage];
'stream-error': [ongoing_message: ChatMessage, ongoing: OngoingState<State>];
'stream-tool-call': [id: string, name: string, args: any];
'stream-tool-result': [id: string, result: any];
'stream-state-change': [];
}
export abstract class BaseChatMessageController<
State,
Annotation extends BaseAnnotation<any>,
> extends EventEmitter<ChatMessageControllerEventsMap<State>> {
protected _message: ChatMessage;
protected _ongoing: OngoingState<State> | undefined;
protected _ongoingHistory: OngoingStateHistoryItem<Annotation['state']>[] | undefined;
public readonly role: ChatMessageRole;
public readonly id: number;
constructor (message: ChatMessage, ongoing: OngoingState<State> | true | undefined) {
super();
this._message = message;
this._ongoing = ongoing === true ? this.createInitialOngoingState() : ongoing;
this._ongoingHistory = ongoing ? [] : undefined;
this.role = message.role;
this.id = message.id;
if (this._message.finished_at == null && !ongoing) {
this._ongoing = this.createUnknownOngoingState();
}
}
// dynamic, usage in react component needs subscription.
get content () {
return this.message?.content ?? '';
}
update (message: ChatMessage) {
this._message = { ...this._message, ...message };
this.emit('update', this._message);
}
applyStreamAnnotation (annotation: Annotation) {
if (!this._ongoing || this._ongoing.finished) {
console.warn('message already finished');
return;
}
const stateChanged = annotation.state !== this._ongoing.state;
let message = this._message;
const ongoing: OngoingState<State> = { ...this._ongoing };
ongoing.state = annotation.state;
ongoing.display = annotation.display || (stateChanged ? '' : ongoing.display);
ongoing.message = stateChanged ? undefined : ongoing.message;
message = this._polishMessage(message, ongoing, annotation);
const lastOngoing = this._ongoing;
this._ongoing = ongoing;
this._message = message;
if (annotation.state === AppChatStreamState.FINISHED) {
this._ongoing.finished = true;
}
this.emit('stream-update', this._message, this._ongoing, '');
if (stateChanged && this._ongoingHistory != null) {
const lastState = this._ongoingHistory[this._ongoingHistory.length - 1];
if (lastOngoing && lastOngoing.display && lastOngoing.state !== lastState?.state.state) {
// Insert new state
this._ongoingHistory = [
...this._ongoingHistory,
{
state: lastOngoing,
time: new Date(),
},
];
this.emit('stream-history-update', this._message, this._ongoingHistory);
}
}
}
applyDelta (delta: string) {
if (!this._ongoing || this._ongoing.finished) {
console.warn('message already finished');
return;
}
this._message = {
...this._message,
content: this._message.content + delta,
};
this.emit('stream-update', this._message, this._ongoing, delta);
}
applyError (error: string) {
if (!this._ongoing || this._ongoing.finished) {
console.warn('message already finished');
console.error('Error in ChatMessageController (on finished message):', error);
return;
}
this._ongoing = {
...this._ongoing,
finished: true,
};
this._message = {
...this._message,
error,
};
this.emit('stream-error', this._message, this._ongoing);
}
applyToolCall ({ toolCallId, toolName, args }: { toolCallId: string, toolName: string, args: any }) {
this.emit('stream-tool-call', toolCallId, toolName, args);
}
applyToolResult ({ toolCallId, result }: { toolCallId: string, result: any }) {
this.emit('stream-tool-result', toolCallId, result);
}
applyFinishMessage (_: unknown) {
}
finish () {
this._ongoing = undefined;
this.emit('stream-finished', this._message);
return this._message;
}
get message (): ChatMessage {
return this._message;
}
get ongoing () {
return this._ongoing;
}
get ongoingHistory () {
return this._ongoingHistory;
}
abstract parseAnnotation (raw: unknown): Annotation | null;
abstract createInitialOngoingState (): OngoingState<State>;
abstract createUnknownOngoingState (): OngoingState<State>;
protected abstract _polishMessage (message: ChatMessage, ongoing: OngoingState<State>, annotation: Annotation): ChatMessage
}
export type ChatMessageController = LegacyChatMessageController | ExternalChatMessageController;
export type ChatMessageControllerAnnotationState<C extends ChatMessageController> = C extends BaseChatMessageController<infer State, any> ? State : never;
export class LegacyChatMessageController extends BaseChatMessageController<AppChatStreamState, ChatMessageAnnotation> {
readonly version = 'Legacy';
parseAnnotation (raw: unknown): ChatMessageAnnotation {
return raw as ChatMessageAnnotation;
}
createInitialOngoingState (): OngoingState {
return {
state: AppChatStreamState.CONNECTING,
display: 'Connecting to server...',
finished: false,
};
}
createUnknownOngoingState (): OngoingState {
return {
state: AppChatStreamState.UNKNOWN,
display: 'Unknown',
finished: false,
};
}
_polishMessage (message: ChatMessage, ongoing: OngoingState, annotation: ChatMessageAnnotation) {
switch (annotation.state) {
case AppChatStreamState.TRACE:
message = { ...message };
message.trace_url = annotation.context.langfuse_url;
break;
case AppChatStreamState.SOURCE_NODES:
message = { ...message };
message.sources = annotation.context;
break;
case AppChatStreamState.REFINE_QUESTION:
ongoing.message = annotation.message || ongoing.message;
break;
}
return message;
}
}
export class ExternalChatMessageController extends BaseChatMessageController<StackVMState, StackVMStateAnnotation> {
readonly version = 'StackVM';
private externalStreamStart = false;
applyToolCall (payload: { toolCallId: string; toolName: string; args: any }) {
super.applyToolCall(payload);
if (this._ongoing) {
this._ongoing = {
...this._ongoing,
state: {
plan_id: this._ongoing.state.plan_id,
state: this._ongoing.state.state,
toolCalls: [...this._ongoing.state.toolCalls, payload],
},
};
this.emit('stream-update', this._message, this._ongoing, '');
}
}
applyToolResult (payload: { toolCallId: string; result: any }) {
super.applyToolResult(payload);
if (this._ongoing) {
const idx = this._ongoing.state.toolCalls.findIndex(toolCall => toolCall.toolCallId === payload.toolCallId);
if (idx >= 0) {
this._ongoing.state.toolCalls[idx] = {
...this._ongoing.state.toolCalls[idx],
result: payload.result,
};
this._ongoing.state = { ...this._ongoing.state };
this._ongoing = { ...this._ongoing };
this.emit('stream-update', this._message, this._ongoing, '');
}
}
}
applyFinishMessage (_: unknown) {
this.externalStreamStart = false;
this.emit('stream-state-change');
}
parseAnnotation (raw: unknown): StackVMStateAnnotation | null {
if (this.externalStreamStart) {
const { state: rawState, plan_id } = raw as { state: StackVM.State, plan_id: string };
const state = StackVM.model.parseState(rawState);
return {
state: { plan_id, state, toolCalls: [] },
display: '[deprecated]',
};
} else {
const { state, display } = raw as ChatMessageAnnotation;
if (state === AppChatStreamState.EXTERNAL_STREAM_START) {
this.externalStreamStart = true;
this.emit('stream-state-change');
return null;
} else {
return {
state: null,
display: display ?? state,
};
}
}
}
createInitialOngoingState (): OngoingState<StackVMState> {
return {
state: {
plan_id: '',
state: {
variables_refs: {},
variables: {},
errors: [],
current_plan: [],
program_counter: -1,
goal_completed: false,
goal: '',
msgs: [],
plan: {
steps: [],
vars: [],
},
},
toolCalls: [],
},
display: 'Thinking...',
finished: false,
};
}
createUnknownOngoingState (): OngoingState<StackVMState> {
return {
state: {
plan_id: '',
state: {
variables_refs: {},
variables: {},
errors: ['Unknown state'],
current_plan: [],
program_counter: -1,
goal_completed: false,
goal: '',
msgs: [],
plan: {
steps: [],
vars: [],
},
},
toolCalls: [],
},
display: 'Unknown',
finished: false,
};
}
_polishMessage (message: ChatMessage, ongoing: OngoingState<StackVMState>, annotation: StackVMStateAnnotation): ChatMessage {
// FIX Initial state
// First step reasoning finished with PC = 1, we need to insert a PC = 0 state first.
if (annotation.state && annotation.state.state.program_counter === 1) {
if (!this._ongoingHistory?.find(item => item.state.state?.state.program_counter === 0)) {
const lastState = {
state: {
state: {
...ongoing.state,
state: { ...ongoing.state.state, program_counter: 0, variables: {}, variables_refs: {} },
},
finished: false,
display: '[deprecated]',
},
time: new Date(),
};
this._ongoing = lastState.state;
this._ongoingHistory = [
...this._ongoingHistory ?? [],
lastState,
];
}
}
return message;
}
}