-
Notifications
You must be signed in to change notification settings - Fork 295
/
CallbackManager.ts
229 lines (210 loc) · 6.04 KB
/
CallbackManager.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
import type { Anthropic } from "@anthropic-ai/sdk";
import { CustomEvent } from "@llamaindex/env";
import type { NodeWithScore } from "../Node.js";
import type { AgentEndEvent, AgentStartEvent } from "../agent/types.js";
import {
EventCaller,
getEventCaller,
} from "../internal/context/EventCaller.js";
import type {
LLMEndEvent,
LLMStartEvent,
LLMStreamEvent,
LLMToolCallEvent,
LLMToolResultEvent,
RetrievalEndEvent,
RetrievalStartEvent,
} from "../llm/types.js";
export class LlamaIndexCustomEvent<T = any> extends CustomEvent<T> {
reason: EventCaller | null;
private constructor(
event: string,
options?: CustomEventInit & {
reason?: EventCaller | null;
},
) {
super(event, options);
this.reason = options?.reason ?? null;
}
static fromEvent<Type extends keyof LlamaIndexEventMaps>(
type: Type,
detail: LlamaIndexEventMaps[Type]["detail"],
) {
return new LlamaIndexCustomEvent(type, {
detail: detail,
reason: getEventCaller(),
});
}
}
/**
* This type is used to define the event maps.
*/
export interface LlamaIndexEventMaps {
/**
* @deprecated
*/
retrieve: CustomEvent<RetrievalCallbackResponse>;
"retrieve-start": RetrievalStartEvent;
"retrieve-end": RetrievalEndEvent;
/**
* @deprecated
*/
stream: CustomEvent<StreamCallbackResponse>;
// llm events
"llm-start": LLMStartEvent;
"llm-end": LLMEndEvent;
"llm-tool-call": LLMToolCallEvent;
"llm-tool-result": LLMToolResultEvent;
"llm-stream": LLMStreamEvent;
// agent events
"agent-start": AgentStartEvent;
"agent-end": AgentEndEvent;
}
//#region @deprecated remove in the next major version
//Specify StreamToken per mainstream LLM
export interface DefaultStreamToken {
id: string;
object: string;
created: number;
model: string;
choices: {
index: number;
delta: {
content?: string | null;
role?: "user" | "assistant" | "system" | "function" | "tool";
};
finish_reason: string | null;
}[];
}
//OpenAI stream token schema is the default.
//Note: Anthropic and Replicate also use similar token schemas.
export type OpenAIStreamToken = DefaultStreamToken;
export type AnthropicStreamToken = Anthropic.Completion;
//
//Callback Responses
//
//TODO: Write Embedding Callbacks
//StreamCallbackResponse should let practitioners implement callbacks out of the box...
//When custom streaming LLMs are involved, people are expected to write their own StreamCallbackResponses
export interface StreamCallbackResponse {
index: number;
isDone?: boolean;
token?: DefaultStreamToken;
}
export interface RetrievalCallbackResponse {
query: string;
nodes: NodeWithScore[];
}
interface CallbackManagerMethods {
/**
* onLLMStream is called when a token is streamed from the LLM. Defining this
* callback auto sets the stream = True flag on the openAI createChatCompletion request.
* @deprecated will be removed in the next major version
*/
onLLMStream: (params: StreamCallbackResponse) => Promise<void> | void;
/**
* onRetrieve is called as soon as the retriever finishes fetching relevant nodes.
* This callback allows you to handle the retrieved nodes even if the synthesizer
* is still running.
* @deprecated will be removed in the next major version
*/
onRetrieve: (params: RetrievalCallbackResponse) => Promise<void> | void;
}
//#endregion
const noop: (...args: any[]) => any = () => void 0;
type EventHandler<Event extends CustomEvent> = (
event: Event & {
reason: EventCaller | null;
},
) => void;
export class CallbackManager implements CallbackManagerMethods {
/**
* @deprecated will be removed in the next major version
*/
get onLLMStream(): CallbackManagerMethods["onLLMStream"] {
return async (response) => {
await Promise.all(
this.#handlers
.get("stream")!
.map((handler) =>
handler(LlamaIndexCustomEvent.fromEvent("stream", response)),
),
);
};
}
/**
* @deprecated will be removed in the next major version
*/
get onRetrieve(): CallbackManagerMethods["onRetrieve"] {
return async (response) => {
await Promise.all(
this.#handlers
.get("retrieve")!
.map((handler) =>
handler(LlamaIndexCustomEvent.fromEvent("retrieve", response)),
),
);
};
}
/**
* @deprecated will be removed in the next major version
*/
set onLLMStream(_: never) {
throw new Error("onLLMStream is deprecated. Use on('stream') instead");
}
/**
* @deprecated will be removed in the next major version
*/
set onRetrieve(_: never) {
throw new Error("onRetrieve is deprecated. Use `on('retrieve')` instead");
}
#handlers = new Map<keyof LlamaIndexEventMaps, EventHandler<CustomEvent>[]>();
constructor(handlers?: Partial<CallbackManagerMethods>) {
const onLLMStream = handlers?.onLLMStream ?? noop;
this.on("stream", (event) => onLLMStream(event.detail));
const onRetrieve = handlers?.onRetrieve ?? noop;
this.on("retrieve", (event) => onRetrieve(event.detail));
}
on<
K extends keyof LlamaIndexEventMaps,
H extends EventHandler<LlamaIndexEventMaps[K]>,
>(event: K, handler: H) {
if (!this.#handlers.has(event)) {
this.#handlers.set(event, []);
}
this.#handlers.get(event)!.push(handler);
return this;
}
off<
K extends keyof LlamaIndexEventMaps,
H extends EventHandler<LlamaIndexEventMaps[K]>,
>(event: K, handler: H) {
if (!this.#handlers.has(event)) {
return;
}
const handlers = this.#handlers.get(event)!;
const index = handlers.indexOf(handler);
if (index > -1) {
handlers.splice(index, 1);
}
return this;
}
dispatchEvent<K extends keyof LlamaIndexEventMaps>(
event: K,
detail: LlamaIndexEventMaps[K]["detail"],
) {
const handlers = this.#handlers.get(event);
if (!handlers) {
return;
}
queueMicrotask(() => {
handlers.forEach((handler) =>
handler(
LlamaIndexCustomEvent.fromEvent(event, {
...detail,
}),
),
);
});
}
}