forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopilot-runtime.ts
More file actions
307 lines (278 loc) · 8.5 KB
/
Copy pathcopilot-runtime.ts
File metadata and controls
307 lines (278 loc) · 8.5 KB
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
/**
* Handles requests from frontend, provides function calling and various LLM backends.
*
* <img
* referrerPolicy="no-referrer-when-downgrade"
* src="https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be"
* />
*
* <RequestExample>
* ```jsx CopilotRuntime Example
* import {
* CopilotRuntime,
* OpenAIAdapter
* } from "@copilotkit/runtime";
*
* export async function POST(req: Request) {
* const copilotKit = new CopilotRuntime();
* return copilotKit.response(req, new OpenAIAdapter());
* }
*
* ```
* </RequestExample>
*
* This class is the main entry point for the runtime. It handles requests from the frontend, provides function calling and various LLM backends.
*
* For example, to use OpenAI as a backend (check the [OpenAI Adapter](./OpenAIAdapter) docs for more info):
* ```typescript
* const copilotKit = new CopilotRuntime();
* return copilotKit.response(req, new OpenAIAdapter());
* ```
*
* Currently we support:
*
* - [OpenAI](./OpenAIAdapter)
* - [LangChain](./LangChainAdapter)
* - [OpenAI Assistant API](./OpenAIAssistantAdapter)
* - [Google Gemini](./GoogleGenerativeAIAdapter)
*
* ## Server Side Actions
*
* CopilotKit supports actions that can be executed on the server side. You can define server side actions by passing the `actions` parameter:
*
* ```typescript
* const copilotKit = new CopilotRuntime({
* actions: [
* {
* name: "sayHello",
* description: "Says hello to someone.",
* argumentAnnotations: [
* {
* name: "arg",
* type: "string",
* description: "The name of the person to say hello to.",
* required: true,
* },
* ],
* implementation: async (arg) => {
* console.log("Hello from the server", arg, "!");
* },
* },
* ],
* });
* ```
*
* Server side actions can also return a result which becomes part of the message history.
*
* This is useful because it gives the LLM context about what happened on the server side. In addition,
* it can be used to look up information from a vector or relational database and other sources.
*
* In addition to that, server side actions can also come from LangChain, including support for streaming responses.
*
* Returned results can be of the following type:
*
* - anything serializable to JSON
* - `string`
* - LangChain types:
* - `IterableReadableStream`
* - `BaseMessageChunk`
* - `AIMessage`
*
* ## LangServe
*
* The backend also supports LangServe, enabling you to connect to existing chains, for example python based chains.
* Use the `langserve` parameter to specify URLs for LangServe.
*
* ```typescript
* const copilotKit = new CopilotRuntime({
* langserve: [
* {
* chainUrl: "http://my-langserve.chain",
* name: "performResearch",
* description: "Performs research on a given topic.",
* },
* ],
* });
* ```
*
* When left out, arguments are automatically inferred from the schema provided by LangServe.
*/
import { Action, actionParametersToJsonSchema, Parameter } from "@copilotkit/shared";
import { RemoteChain, RemoteChainParameters, CopilotServiceAdapter } from "../service-adapters";
import { MessageInput } from "../graphql/inputs/message.input";
import { ActionInput } from "../graphql/inputs/action.input";
import { RuntimeEventSource } from "../service-adapters/events";
import { convertGqlInputToMessages } from "../service-adapters/conversion";
import { Message } from "../graphql/types/converted";
interface CopilotRuntimeRequest {
serviceAdapter: CopilotServiceAdapter;
messages: MessageInput[];
actions: ActionInput[];
outputMessagesPromise: Promise<Message[]>;
properties: any;
threadId?: string;
runId?: string;
publicApiKey?: string;
}
interface CopilotRuntimeResponse {
threadId: string;
runId?: string;
eventSource: RuntimeEventSource;
actions: Action<any>[];
}
type ActionsConfiguration<T extends Parameter[] | [] = []> =
| Action<T>[]
| ((ctx: { properties: any }) => Action<T>[]);
interface OnBeforeRequestOptions {
threadId?: string;
runId?: string;
inputMessages: Message[];
properties: any;
}
type OnBeforeRequestHandler = (options: OnBeforeRequestOptions) => void | Promise<void>;
interface OnAfterRequestOptions {
threadId: string;
runId?: string;
inputMessages: Message[];
outputMessages: Message[];
properties: any;
}
type OnAfterRequestHandler = (options: OnAfterRequestOptions) => void | Promise<void>;
interface Middleware {
/**
* A function that is called before the request is processed.
*/
onBeforeRequest?: OnBeforeRequestHandler;
/**
* A function that is called after the request is processed.
*/
onAfterRequest?: OnAfterRequestHandler;
}
export interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> {
/**
* Middleware to be used by the runtime.
*
* ```ts
* onBeforeRequest: (options: {
* threadId?: string;
* runId?: string;
* inputMessages: Message[];
* properties: any;
* }) => void | Promise<void>;
* ```
*
* ```ts
* onAfterRequest: (options: {
* threadId?: string;
* runId?: string;
* inputMessages: Message[];
* outputMessages: Message[];
* properties: any;
* }) => void | Promise<void>;
* ```
*/
middleware?: Middleware;
/*
* A list of server side actions that can be executed.
*/
actions?: ActionsConfiguration<T>;
/*
* An array of LangServer URLs.
*/
langserve?: RemoteChainParameters[];
}
export class CopilotRuntime<const T extends Parameter[] | [] = []> {
public actions: ActionsConfiguration<T>;
private langserve: Promise<Action<any>>[] = [];
private onBeforeRequest?: OnBeforeRequestHandler;
private onAfterRequest?: OnAfterRequestHandler;
constructor(params?: CopilotRuntimeConstructorParams<T>) {
this.actions = params?.actions || [];
for (const chain of params?.langserve || []) {
const remoteChain = new RemoteChain(chain);
this.langserve.push(remoteChain.toAction());
}
this.onBeforeRequest = params?.middleware?.onBeforeRequest;
this.onAfterRequest = params?.middleware?.onAfterRequest;
}
async process(request: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {
const {
serviceAdapter,
messages,
actions: clientSideActionsInput,
threadId,
runId,
properties,
outputMessagesPromise,
} = request;
const langserveFunctions: Action<any>[] = [];
for (const chainPromise of this.langserve) {
try {
const chain = await chainPromise;
langserveFunctions.push(chain);
} catch (error) {
console.error("Error loading langserve chain:", error);
}
}
const configuredActions =
typeof this.actions === "function" ? this.actions({ properties }) : this.actions;
const actions = [...configuredActions, ...langserveFunctions];
const serverSideActionsInput: ActionInput[] = actions.map((action) => ({
name: action.name,
description: action.description,
jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),
}));
const actionInputs = flattenToolCallsNoDuplicates([
...serverSideActionsInput,
...clientSideActionsInput,
]);
const inputMessages = convertGqlInputToMessages(messages);
await this.onBeforeRequest?.({
threadId,
runId,
inputMessages,
properties,
});
try {
const eventSource = new RuntimeEventSource();
const result = await serviceAdapter.process({
messages: inputMessages,
actions: actionInputs,
threadId,
runId,
eventSource,
});
outputMessagesPromise
.then((outputMessages) => {
this.onAfterRequest?.({
threadId: result.threadId,
runId: result.runId,
inputMessages,
outputMessages,
properties,
});
})
.catch((_error) => {});
return {
threadId: result.threadId,
runId: result.runId,
eventSource,
actions: actions,
};
} catch (error) {
console.error("Error getting response:", error);
throw error;
}
}
}
export function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): ActionInput[] {
let allTools: ActionInput[] = [];
const allToolNames: string[] = [];
for (const tool of toolsByPriority) {
if (!allToolNames.includes(tool.name)) {
allTools.push(tool);
allToolNames.push(tool.name);
}
}
return allTools;
}