@copilotkit/runtime 0.38.0-mme-alpha.1 → 1.0.0-beta.1

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.
Files changed (89) hide show
  1. package/.turbo/turbo-build.log +81 -67
  2. package/CHANGELOG.md +13 -10
  3. package/__snapshots__/schema/schema.graphql +15 -1
  4. package/dist/chunk-44O2JGUY.mjs +12 -0
  5. package/dist/chunk-5U6S5EGT.mjs +24 -0
  6. package/dist/chunk-5U6S5EGT.mjs.map +1 -0
  7. package/dist/{chunk-XI3HBDMA.mjs → chunk-7QCEK4DP.mjs} +25 -14
  8. package/dist/chunk-7QCEK4DP.mjs.map +1 -0
  9. package/dist/{chunk-DX2KAJBF.mjs → chunk-DL2QQEOR.mjs} +204 -19
  10. package/dist/chunk-DL2QQEOR.mjs.map +1 -0
  11. package/dist/{chunk-FRK6BXXV.mjs → chunk-DVDKD6F5.mjs} +3 -3
  12. package/dist/{chunk-NXFMYCNF.mjs → chunk-F5K2JKGM.mjs} +38 -23
  13. package/dist/chunk-F5K2JKGM.mjs.map +1 -0
  14. package/dist/{chunk-OZMCHYYR.mjs → chunk-GEIBJJQ4.mjs} +3 -3
  15. package/dist/{chunk-4RGXTUS4.mjs → chunk-R25IOQB5.mjs} +17 -4
  16. package/dist/chunk-R25IOQB5.mjs.map +1 -0
  17. package/dist/{chunk-6NZ4UMOD.mjs → chunk-RMZWGQ46.mjs} +2 -2
  18. package/dist/{chunk-BYB2LNMK.mjs → chunk-U3V2BCGI.mjs} +2 -2
  19. package/dist/chunk-ZTEJCDMJ.mjs +24 -0
  20. package/dist/chunk-ZTEJCDMJ.mjs.map +1 -0
  21. package/dist/graphql/types/base/index.mjs +2 -2
  22. package/dist/graphql/types/converted/index.mjs +3 -3
  23. package/dist/index.d.ts +8 -5
  24. package/dist/index.js +297 -53
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +17 -11
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{langchain-adapter-54784d29.d.ts → langchain-adapter-a02d1d38.d.ts} +4 -4
  29. package/dist/{langserve-63794237.d.ts → langserve-75ebbc38.d.ts} +1 -2
  30. package/dist/lib/index.d.ts +8 -5
  31. package/dist/lib/index.js +297 -53
  32. package/dist/lib/index.js.map +1 -1
  33. package/dist/lib/index.mjs +17 -11
  34. package/dist/lib/integrations/index.d.ts +7 -4
  35. package/dist/lib/integrations/index.js +254 -14
  36. package/dist/lib/integrations/index.js.map +1 -1
  37. package/dist/lib/integrations/index.mjs +15 -7
  38. package/dist/lib/integrations/nest/index.d.ts +14 -0
  39. package/dist/lib/integrations/nest/index.js +1481 -0
  40. package/dist/lib/integrations/nest/index.js.map +1 -0
  41. package/dist/lib/integrations/nest/index.mjs +13 -0
  42. package/dist/lib/integrations/nest/index.mjs.map +1 -0
  43. package/dist/lib/integrations/node-express/index.d.ts +14 -0
  44. package/dist/lib/integrations/node-express/index.js +1481 -0
  45. package/dist/lib/integrations/node-express/index.js.map +1 -0
  46. package/dist/lib/integrations/node-express/index.mjs +13 -0
  47. package/dist/lib/integrations/node-express/index.mjs.map +1 -0
  48. package/dist/lib/integrations/node-http/index.d.ts +7 -3
  49. package/dist/lib/integrations/node-http/index.js +214 -14
  50. package/dist/lib/integrations/node-http/index.js.map +1 -1
  51. package/dist/lib/integrations/node-http/index.mjs +6 -6
  52. package/dist/{pages-router-b88114e9.d.ts → pages-router-24897543.d.ts} +1 -1
  53. package/dist/service-adapters/index.d.ts +2 -2
  54. package/dist/service-adapters/index.js +28 -17
  55. package/dist/service-adapters/index.js.map +1 -1
  56. package/dist/service-adapters/index.mjs +5 -5
  57. package/dist/{index-1eb2e9b1.d.ts → shared-48c0f7b8.d.ts} +64 -21
  58. package/dist/utils/index.mjs +2 -2
  59. package/package.json +4 -4
  60. package/src/graphql/inputs/cloud-guardrails.input.ts +2 -2
  61. package/src/graphql/inputs/generate-copilot-response.input.ts +10 -0
  62. package/src/graphql/resolvers/copilot.resolver.ts +79 -3
  63. package/src/graphql/types/enums.ts +13 -0
  64. package/src/lib/copilot-runtime.ts +106 -32
  65. package/src/lib/integrations/index.ts +2 -0
  66. package/src/lib/integrations/nest/index.ts +14 -0
  67. package/src/lib/integrations/nextjs/app-router.ts +10 -0
  68. package/src/lib/integrations/nextjs/pages-router.ts +10 -0
  69. package/src/lib/integrations/node-express/index.ts +14 -0
  70. package/src/lib/integrations/node-http/index.ts +10 -0
  71. package/src/lib/integrations/shared.ts +15 -2
  72. package/src/lib/telemetry-client.ts +9 -0
  73. package/src/service-adapters/experimental/groq/groq-adapter.ts +3 -1
  74. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +3 -1
  75. package/src/service-adapters/google/google-genai-adapter.ts +3 -1
  76. package/src/service-adapters/langchain/langchain-adapter.ts +8 -9
  77. package/src/service-adapters/openai/openai-adapter.ts +8 -7
  78. package/src/service-adapters/openai/openai-assistant-adapter.ts +6 -8
  79. package/src/service-adapters/service-adapter.ts +1 -2
  80. package/dist/chunk-4RGXTUS4.mjs.map +0 -1
  81. package/dist/chunk-DX2KAJBF.mjs.map +0 -1
  82. package/dist/chunk-NXFMYCNF.mjs.map +0 -1
  83. package/dist/chunk-RHQLCJGG.mjs +0 -7
  84. package/dist/chunk-XI3HBDMA.mjs.map +0 -1
  85. /package/dist/{chunk-RHQLCJGG.mjs.map → chunk-44O2JGUY.mjs.map} +0 -0
  86. /package/dist/{chunk-FRK6BXXV.mjs.map → chunk-DVDKD6F5.mjs.map} +0 -0
  87. /package/dist/{chunk-OZMCHYYR.mjs.map → chunk-GEIBJJQ4.mjs.map} +0 -0
  88. /package/dist/{chunk-6NZ4UMOD.mjs.map → chunk-RMZWGQ46.mjs.map} +0 -0
  89. /package/dist/{chunk-BYB2LNMK.mjs.map → chunk-U3V2BCGI.mjs.map} +0 -0
@@ -26,13 +26,15 @@ import {
26
26
  import { ResponseStatusUnion, SuccessResponseStatus } from "../types/response-status.type";
27
27
  import { GraphQLJSONObject } from "graphql-scalars";
28
28
  import { plainToInstance } from "class-transformer";
29
- import { GuardrailsResult, GuardrailsResultStatus } from "../types/guardrails-result.type";
29
+ import { GuardrailsResult } from "../types/guardrails-result.type";
30
30
  import { GraphQLError } from "graphql";
31
31
  import {
32
32
  GuardrailsValidationFailureResponse,
33
33
  MessageStreamInterruptedResponse,
34
34
  UnknownErrorResponse,
35
35
  } from "../../utils";
36
+ import { ActionExecutionMessage, Message, ResultMessage, TextMessage } from "../types/converted";
37
+ import telemetry from "../../lib/telemetry-client";
36
38
 
37
39
  const invokeGuardrails = async ({
38
40
  baseUrl,
@@ -47,6 +49,8 @@ const invokeGuardrails = async ({
47
49
  onResult: (result: GuardrailsResult) => void;
48
50
  onError: (err: Error) => void;
49
51
  }) => {
52
+ console.log("invokeGuardrails.baseUrl", baseUrl);
53
+
50
54
  if (
51
55
  data.messages.length &&
52
56
  data.messages[data.messages.length - 1].textMessage?.role === MessageRole.user
@@ -104,6 +108,11 @@ export class CopilotResolver {
104
108
  @Arg("properties", () => GraphQLJSONObject, { nullable: true })
105
109
  properties?: CopilotRequestContextProperties,
106
110
  ) {
111
+ telemetry.capture("oss.runtime.copilot_request_created", {
112
+ "cloud.guardrails.enabled": data.cloud?.guardrails !== undefined,
113
+ requestType: data.metadata.requestType,
114
+ });
115
+
107
116
  let logger = ctx.logger.child({ component: "CopilotResolver.generateCopilotResponse" });
108
117
  logger.debug({ data }, "Generating Copilot response");
109
118
 
@@ -132,19 +141,29 @@ export class CopilotResolver {
132
141
 
133
142
  if (process.env.COPILOT_CLOUD_BASE_URL) {
134
143
  copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;
135
- } else if (ctx._copilotkit.baseUrl) {
136
- copilotCloudBaseUrl = ctx._copilotkit.baseUrl;
144
+ } else if (ctx._copilotkit.cloud?.baseUrl) {
145
+ copilotCloudBaseUrl = ctx._copilotkit.cloud?.baseUrl;
137
146
  } else {
138
147
  copilotCloudBaseUrl = "https://api.cloud.copilotkit.ai";
139
148
  }
140
149
 
141
150
  logger = logger.child({ copilotCloudBaseUrl });
142
151
  }
152
+
143
153
  logger.debug("Setting up subjects");
144
154
  const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();
145
155
  const interruptStreaming$ = new ReplaySubject<{ reason: string; messageId?: string }>();
146
156
  const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();
147
157
 
158
+ let outputMessages: Message[] = [];
159
+ let resolveOutputMessagesPromise: (messages: Message[]) => void;
160
+ let rejectOutputMessagesPromise: (err: Error) => void;
161
+
162
+ const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {
163
+ resolveOutputMessagesPromise = resolve;
164
+ rejectOutputMessagesPromise = reject;
165
+ });
166
+
148
167
  logger.debug("Processing");
149
168
  const {
150
169
  eventSource,
@@ -158,6 +177,8 @@ export class CopilotResolver {
158
177
  threadId: data.threadId,
159
178
  runId: data.runId,
160
179
  publicApiKey: undefined,
180
+ properties: ctx.properties || {},
181
+ outputMessagesPromise,
161
182
  });
162
183
 
163
184
  logger.debug("Event source created, creating response");
@@ -180,13 +201,27 @@ export class CopilotResolver {
180
201
  onResult: (result) => {
181
202
  logger.debug({ status: result.status }, "Guardrails validation done");
182
203
  guardrailsResult$.next(result);
204
+
205
+ // Guardrails validation failed
183
206
  if (result.status === "denied") {
207
+ // send the reason to the client and interrupt streaming
184
208
  responseStatus$.next(
185
209
  new GuardrailsValidationFailureResponse({ guardrailsReason: result.reason }),
186
210
  );
187
211
  interruptStreaming$.next({
188
212
  reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,
189
213
  });
214
+
215
+ // resolve messages promise to the middleware
216
+ outputMessages = [
217
+ plainToInstance(TextMessage, {
218
+ id: nanoid(),
219
+ createdAt: new Date(),
220
+ content: result.reason,
221
+ role: MessageRole.assistant,
222
+ }),
223
+ ];
224
+ resolveOutputMessagesPromise(outputMessages);
190
225
  }
191
226
  },
192
227
  onError: (err) => {
@@ -199,6 +234,9 @@ export class CopilotResolver {
199
234
  interruptStreaming$.next({
200
235
  reason: `Interrupted due to unknown error in guardrails validation`,
201
236
  });
237
+
238
+ // reject the middleware promise
239
+ rejectOutputMessagesPromise(err);
202
240
  },
203
241
  });
204
242
  }
@@ -251,6 +289,7 @@ export class CopilotResolver {
251
289
  content: new Repeater(async (pushTextChunk, stopStreamingText) => {
252
290
  logger.debug("Text message content repeater created");
253
291
 
292
+ const textChunks: string[] = [];
254
293
  let textSubscription: Subscription;
255
294
 
256
295
  interruptStreaming$
@@ -277,6 +316,7 @@ export class CopilotResolver {
277
316
  next: async (e: RuntimeEvent) => {
278
317
  if (e.type == RuntimeEventTypes.TextMessageContent) {
279
318
  await pushTextChunk(e.content);
319
+ textChunks.push(e.content);
280
320
  }
281
321
  },
282
322
  error: (err) => {
@@ -293,6 +333,15 @@ export class CopilotResolver {
293
333
  streamingTextStatus.next(new SuccessMessageStatus());
294
334
  stopStreamingText();
295
335
  textSubscription?.unsubscribe();
336
+
337
+ outputMessages.push(
338
+ plainToInstance(TextMessage, {
339
+ id: messageId,
340
+ createdAt: new Date(),
341
+ content: textChunks.join(""),
342
+ role: MessageRole.assistant,
343
+ }),
344
+ );
296
345
  },
297
346
  });
298
347
  }),
@@ -317,11 +366,14 @@ export class CopilotResolver {
317
366
  arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {
318
367
  logger.debug("Action execution argument stream created");
319
368
 
369
+ const argumentChunks: string[] = [];
320
370
  let actionExecutionArgumentSubscription: Subscription;
371
+
321
372
  actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({
322
373
  next: async (e: RuntimeEvent) => {
323
374
  if (e.type == RuntimeEventTypes.ActionExecutionArgs) {
324
375
  await pushArgumentsChunk(e.args);
376
+ argumentChunks.push(e.args);
325
377
  }
326
378
  },
327
379
  error: (err) => {
@@ -340,6 +392,16 @@ export class CopilotResolver {
340
392
  streamingArgumentsStatus.next(new SuccessMessageStatus());
341
393
  stopStreamingArguments();
342
394
  actionExecutionArgumentSubscription?.unsubscribe();
395
+
396
+ outputMessages.push(
397
+ plainToInstance(ActionExecutionMessage, {
398
+ id: event.actionExecutionId,
399
+ createdAt: new Date(),
400
+ name: event.actionName,
401
+ scope: event.scope!,
402
+ arguments: argumentChunks.join(""),
403
+ }),
404
+ );
343
405
  },
344
406
  });
345
407
  }),
@@ -358,6 +420,16 @@ export class CopilotResolver {
358
420
  actionName: event.actionName,
359
421
  result: event.result,
360
422
  });
423
+
424
+ outputMessages.push(
425
+ plainToInstance(ResultMessage, {
426
+ id: nanoid(),
427
+ createdAt: new Date(),
428
+ actionExecutionId: event.actionExecutionId,
429
+ actionName: event.actionName,
430
+ result: event.result,
431
+ }),
432
+ );
361
433
  break;
362
434
  }
363
435
  },
@@ -370,6 +442,8 @@ export class CopilotResolver {
370
442
  );
371
443
  eventStreamSubscription?.unsubscribe();
372
444
  stopStreamingMessages();
445
+
446
+ rejectOutputMessagesPromise(err);
373
447
  },
374
448
  complete: async () => {
375
449
  logger.debug("Event stream completed");
@@ -380,6 +454,8 @@ export class CopilotResolver {
380
454
  responseStatus$.next(new SuccessResponseStatus());
381
455
  eventStreamSubscription?.unsubscribe();
382
456
  stopStreamingMessages();
457
+
458
+ resolveOutputMessagesPromise(outputMessages);
383
459
  },
384
460
  });
385
461
  }),
@@ -11,6 +11,14 @@ export enum ActionExecutionScope {
11
11
  client = "client",
12
12
  }
13
13
 
14
+ export enum CopilotRequestType {
15
+ Chat = "Chat",
16
+ Task = "Task",
17
+ TextareaCompletion = "TextareaCompletion",
18
+ TextareaPopover = "TextareaPopover",
19
+ Suggestion = "Suggestion",
20
+ }
21
+
14
22
  registerEnumType(MessageRole, {
15
23
  name: "MessageRole",
16
24
  description: "The role of the message",
@@ -20,3 +28,8 @@ registerEnumType(ActionExecutionScope, {
20
28
  name: "ActionExecutionScope",
21
29
  description: "The scope of the action",
22
30
  });
31
+
32
+ registerEnumType(CopilotRequestType, {
33
+ name: "CopilotRequestType",
34
+ description: "The type of Copilot request",
35
+ });
@@ -104,41 +104,102 @@ import { MessageInput } from "../graphql/inputs/message.input";
104
104
  import { ActionInput } from "../graphql/inputs/action.input";
105
105
  import { RuntimeEventSource } from "../service-adapters/events";
106
106
  import { convertGqlInputToMessages } from "../service-adapters/conversion";
107
+ import { Message } from "../graphql/types/converted";
107
108
 
108
109
  interface CopilotRuntimeRequest {
109
110
  serviceAdapter: CopilotServiceAdapter;
110
111
  messages: MessageInput[];
111
112
  actions: ActionInput[];
113
+ outputMessagesPromise: Promise<Message[]>;
114
+ properties: any;
112
115
  threadId?: string;
113
116
  runId?: string;
114
117
  publicApiKey?: string;
115
118
  }
116
119
 
117
120
  interface CopilotRuntimeResponse {
118
- threadId?: string;
121
+ threadId: string;
119
122
  runId?: string;
120
123
  eventSource: RuntimeEventSource;
121
124
  actions: Action<any>[];
122
125
  }
123
126
 
127
+ type ActionsConfiguration<T extends Parameter[] | [] = []> =
128
+ | Action<T>[]
129
+ | ((ctx: { properties: any }) => Action<T>[]);
130
+
131
+ interface OnBeforeRequestOptions {
132
+ threadId?: string;
133
+ runId?: string;
134
+ inputMessages: Message[];
135
+ properties: any;
136
+ }
137
+
138
+ type OnBeforeRequestHandler = (options: OnBeforeRequestOptions) => void | Promise<void>;
139
+
140
+ interface OnAfterRequestOptions {
141
+ threadId: string;
142
+ runId?: string;
143
+ inputMessages: Message[];
144
+ outputMessages: Message[];
145
+ properties: any;
146
+ }
147
+
148
+ type OnAfterRequestHandler = (options: OnAfterRequestOptions) => void | Promise<void>;
149
+
150
+ interface Middleware {
151
+ /**
152
+ * A function that is called before the request is processed.
153
+ */
154
+ onBeforeRequest?: OnBeforeRequestHandler;
155
+
156
+ /**
157
+ * A function that is called after the request is processed.
158
+ */
159
+ onAfterRequest?: OnAfterRequestHandler;
160
+ }
161
+
124
162
  export interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> {
163
+ /**
164
+ * Middleware to be used by the runtime.
165
+ *
166
+ * ```ts
167
+ * onBeforeRequest: (options: {
168
+ * threadId?: string;
169
+ * runId?: string;
170
+ * inputMessages: Message[];
171
+ * properties: any;
172
+ * }) => void | Promise<void>;
173
+ * ```
174
+ *
175
+ * ```ts
176
+ * onAfterRequest: (options: {
177
+ * threadId?: string;
178
+ * runId?: string;
179
+ * inputMessages: Message[];
180
+ * outputMessages: Message[];
181
+ * properties: any;
182
+ * }) => void | Promise<void>;
183
+ * ```
184
+ */
185
+ middleware?: Middleware;
186
+
125
187
  /*
126
188
  * A list of server side actions that can be executed.
127
189
  */
128
- actions?: Action<T>[];
190
+ actions?: ActionsConfiguration<T>;
129
191
 
130
192
  /*
131
193
  * An array of LangServer URLs.
132
194
  */
133
195
  langserve?: RemoteChainParameters[];
134
-
135
- debug?: boolean;
136
196
  }
137
197
 
138
198
  export class CopilotRuntime<const T extends Parameter[] | [] = []> {
139
- public actions: Action<any>[] = [];
199
+ public actions: ActionsConfiguration<T>;
140
200
  private langserve: Promise<Action<any>>[] = [];
141
- private debug: boolean = false;
201
+ private onBeforeRequest?: OnBeforeRequestHandler;
202
+ private onAfterRequest?: OnAfterRequestHandler;
142
203
 
143
204
  constructor(params?: CopilotRuntimeConstructorParams<T>) {
144
205
  this.actions = params?.actions || [];
@@ -147,26 +208,21 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
147
208
  const remoteChain = new RemoteChain(chain);
148
209
  this.langserve.push(remoteChain.toAction());
149
210
  }
150
- this.debug = params?.debug || false;
151
- }
152
-
153
- addAction<const T extends Parameter[] | [] = []>(action: Action<T>): void {
154
- this.removeAction(action.name);
155
- this.actions.push(action);
156
- }
157
211
 
158
- removeAction(actionName: string): void {
159
- this.actions = this.actions.filter((f) => f.name !== actionName);
212
+ this.onBeforeRequest = params?.middleware?.onBeforeRequest;
213
+ this.onAfterRequest = params?.middleware?.onAfterRequest;
160
214
  }
161
215
 
162
- async process({
163
- serviceAdapter,
164
- messages,
165
- actions: clientSideActionsInput,
166
- threadId,
167
- runId,
168
- publicApiKey,
169
- }: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {
216
+ async process(request: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {
217
+ const {
218
+ serviceAdapter,
219
+ messages,
220
+ actions: clientSideActionsInput,
221
+ threadId,
222
+ runId,
223
+ properties,
224
+ outputMessagesPromise,
225
+ } = request;
170
226
  const langserveFunctions: Action<any>[] = [];
171
227
 
172
228
  for (const chainPromise of this.langserve) {
@@ -178,7 +234,10 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
178
234
  }
179
235
  }
180
236
 
181
- const actions = [...this.actions, ...langserveFunctions];
237
+ const configuredActions =
238
+ typeof this.actions === "function" ? this.actions({ properties }) : this.actions;
239
+
240
+ const actions = [...configuredActions, ...langserveFunctions];
182
241
 
183
242
  const serverSideActionsInput: ActionInput[] = actions.map((action) => ({
184
243
  name: action.name,
@@ -190,23 +249,43 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
190
249
  ...serverSideActionsInput,
191
250
  ...clientSideActionsInput,
192
251
  ]);
252
+ const inputMessages = convertGqlInputToMessages(messages);
253
+
254
+ await this.onBeforeRequest?.({
255
+ threadId,
256
+ runId,
257
+ inputMessages,
258
+ properties,
259
+ });
193
260
 
194
261
  try {
195
262
  const eventSource = new RuntimeEventSource();
196
- // TODO-PROTOCOL: type this and support function calls
263
+
197
264
  const result = await serviceAdapter.process({
198
- messages: convertGqlInputToMessages(messages),
265
+ messages: inputMessages,
199
266
  actions: actionInputs,
200
267
  threadId,
201
268
  runId,
202
269
  eventSource,
203
270
  });
204
271
 
272
+ outputMessagesPromise
273
+ .then((outputMessages) => {
274
+ this.onAfterRequest?.({
275
+ threadId: result.threadId,
276
+ runId: result.runId,
277
+ inputMessages,
278
+ outputMessages,
279
+ properties,
280
+ });
281
+ })
282
+ .catch((_error) => {});
283
+
205
284
  return {
206
285
  threadId: result.threadId,
207
286
  runId: result.runId,
208
287
  eventSource,
209
- actions,
288
+ actions: actions,
210
289
  };
211
290
  } catch (error) {
212
291
  console.error("Error getting response:", error);
@@ -226,8 +305,3 @@ export function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): Ac
226
305
  }
227
306
  return allTools;
228
307
  }
229
-
230
- /**
231
- * @deprecated use CopilotRuntime instead
232
- */
233
- export class CopilotBackend extends CopilotRuntime {}
@@ -2,3 +2,5 @@ export * from "./shared";
2
2
  export * from "./nextjs/app-router";
3
3
  export * from "./nextjs/pages-router";
4
4
  export * from "./node-http";
5
+ export * from "./node-express";
6
+ export * from "./nest";
@@ -0,0 +1,14 @@
1
+ import { CreateCopilotRuntimeServerOptions } from "../shared";
2
+ import { copilotRuntimeNodeHttpEndpoint } from "../node-http";
3
+ import telemetry from "../../telemetry-client";
4
+
5
+ export function copilotRuntimeNestEndpoint(options: CreateCopilotRuntimeServerOptions) {
6
+ telemetry.setGlobalProperties({
7
+ runtime: {
8
+ framework: "nest",
9
+ },
10
+ });
11
+
12
+ telemetry.capture("oss.runtime.instance_created", {});
13
+ return copilotRuntimeNodeHttpEndpoint(options);
14
+ }
@@ -1,8 +1,18 @@
1
1
  import { createYoga } from "graphql-yoga";
2
2
  import { CreateCopilotRuntimeServerOptions, getCommonConfig } from "../shared";
3
+ import telemetry from "../../telemetry-client";
3
4
 
4
5
  export function copilotRuntimeNextJSAppRouterEndpoint(options: CreateCopilotRuntimeServerOptions) {
5
6
  const commonConfig = getCommonConfig(options);
7
+
8
+ telemetry.setGlobalProperties({
9
+ runtime: {
10
+ framework: "nextjs-app-router",
11
+ },
12
+ });
13
+
14
+ telemetry.capture("oss.runtime.instance_created", {});
15
+
6
16
  const logger = commonConfig.logging;
7
17
  logger.debug("Creating NextJS App Router endpoint");
8
18
 
@@ -1,5 +1,6 @@
1
1
  import { YogaServerInstance, createYoga } from "graphql-yoga";
2
2
  import { CreateCopilotRuntimeServerOptions, GraphQLContext, getCommonConfig } from "../shared";
3
+ import telemetry from "../../telemetry-client";
3
4
 
4
5
  export const config = {
5
6
  api: {
@@ -18,6 +19,15 @@ export function copilotRuntimeNextJSPagesRouterEndpoint(
18
19
  options: CreateCopilotRuntimeServerOptions,
19
20
  ): CopilotRuntimeServerInstance<GraphQLContext> {
20
21
  const commonConfig = getCommonConfig(options);
22
+
23
+ telemetry.setGlobalProperties({
24
+ runtime: {
25
+ framework: "nextjs-pages-router",
26
+ },
27
+ });
28
+
29
+ telemetry.capture("oss.runtime.instance_created", {});
30
+
21
31
  const logger = commonConfig.logging;
22
32
  logger.debug("Creating NextJS Pages Router endpoint");
23
33
 
@@ -0,0 +1,14 @@
1
+ import { CreateCopilotRuntimeServerOptions } from "../shared";
2
+ import { copilotRuntimeNodeHttpEndpoint } from "../node-http";
3
+ import telemetry from "../../telemetry-client";
4
+
5
+ export function copilotRuntimeNodeExpressEndpoint(options: CreateCopilotRuntimeServerOptions) {
6
+ telemetry.setGlobalProperties({
7
+ runtime: {
8
+ framework: "node-express",
9
+ },
10
+ });
11
+
12
+ telemetry.capture("oss.runtime.instance_created", {});
13
+ return copilotRuntimeNodeHttpEndpoint(options);
14
+ }
@@ -1,8 +1,18 @@
1
1
  import { createYoga } from "graphql-yoga";
2
2
  import { CreateCopilotRuntimeServerOptions, getCommonConfig } from "../shared";
3
+ import telemetry from "../../telemetry-client";
3
4
 
4
5
  export function copilotRuntimeNodeHttpEndpoint(options: CreateCopilotRuntimeServerOptions) {
5
6
  const commonConfig = getCommonConfig(options);
7
+
8
+ telemetry.setGlobalProperties({
9
+ runtime: {
10
+ framework: "node-http",
11
+ },
12
+ });
13
+
14
+ telemetry.capture("oss.runtime.instance_created", {});
15
+
6
16
  const logger = commonConfig.logging;
7
17
  logger.debug("Creating Node HTTP endpoint");
8
18
 
@@ -7,6 +7,7 @@ import { CopilotServiceAdapter } from "../../service-adapters";
7
7
  import { CopilotCloudOptions } from "../cloud";
8
8
  import { LogLevel, createLogger } from "../../lib/logger";
9
9
  import { createYoga } from "graphql-yoga";
10
+ import telemetry from "../telemetry-client";
10
11
 
11
12
  const logger = createLogger();
12
13
 
@@ -23,7 +24,7 @@ export type GraphQLContext = YogaInitialContext & {
23
24
  };
24
25
 
25
26
  export interface CreateCopilotRuntimeServerOptions {
26
- runtime: CopilotRuntime;
27
+ runtime: CopilotRuntime<any>;
27
28
  serviceAdapter: CopilotServiceAdapter;
28
29
  endpoint: string;
29
30
  baseUrl?: string;
@@ -74,10 +75,22 @@ export type CommonConfig = {
74
75
  export function getCommonConfig(options: CreateCopilotRuntimeServerOptions): CommonConfig {
75
76
  const logLevel = (process.env.LOG_LEVEL as LogLevel) || (options.logLevel as LogLevel) || "error";
76
77
  const logger = createLogger({ level: logLevel, component: "getCommonConfig" });
77
- logger.debug("Getting common config");
78
78
 
79
79
  const contextLogger = createLogger({ level: logLevel });
80
80
 
81
+ if (options.cloud) {
82
+ telemetry.setCloudConfiguration({
83
+ publicApiKey: options.cloud.publicApiKey,
84
+ baseUrl: options.cloud.baseUrl,
85
+ });
86
+ }
87
+
88
+ telemetry.setGlobalProperties({
89
+ runtime: {
90
+ serviceAdapter: options.serviceAdapter.constructor.name,
91
+ },
92
+ });
93
+
81
94
  return {
82
95
  logging: createLogger({ component: "Yoga GraphQL", level: logLevel }),
83
96
  schema: buildSchema(),
@@ -0,0 +1,9 @@
1
+ import { TelemetryClient } from "@copilotkit/shared";
2
+ const packageJson = require("../../package.json");
3
+
4
+ const telemetryClient = new TelemetryClient({
5
+ packageName: packageJson.name,
6
+ packageVersion: packageJson.version,
7
+ });
8
+
9
+ export default telemetryClient;
@@ -107,7 +107,9 @@ export class ExperimentalGroqAdapter implements CopilotServiceAdapter {
107
107
 
108
108
  eventStream$.complete();
109
109
  });
110
- return {};
110
+ return {
111
+ threadId: request.threadId || nanoid(),
112
+ };
111
113
  }
112
114
  }
113
115
 
@@ -70,6 +70,8 @@ export class ExperimentalOllamaAdapter implements CopilotServiceAdapter {
70
70
 
71
71
  eventStream$.complete();
72
72
  });
73
- return {};
73
+ return {
74
+ threadId: request.threadId || nanoid(),
75
+ };
74
76
  }
75
77
  }
@@ -130,7 +130,9 @@ export class GoogleGenerativeAIAdapter implements CopilotServiceAdapter {
130
130
  eventStream$.complete();
131
131
  });
132
132
 
133
- return {};
133
+ return {
134
+ threadId: request.threadId || nanoid(),
135
+ };
134
136
  }
135
137
  }
136
138
 
@@ -35,6 +35,7 @@ import {
35
35
  } from "./utils";
36
36
  import { DynamicStructuredTool } from "@langchain/core/tools";
37
37
  import { LangChainReturnType } from "./types";
38
+ import { nanoid } from "nanoid";
38
39
 
39
40
  interface ChainFnParameters {
40
41
  model: string;
@@ -54,14 +55,10 @@ export class LangChainAdapter implements CopilotServiceAdapter {
54
55
  */
55
56
  constructor(private options: LangChainAdapterOptions) {}
56
57
 
57
- async process({
58
- eventSource,
59
- model,
60
- actions,
61
- messages,
62
- threadId,
63
- runId,
64
- }: CopilotRuntimeChatCompletionRequest): Promise<CopilotRuntimeChatCompletionResponse> {
58
+ async process(
59
+ request: CopilotRuntimeChatCompletionRequest,
60
+ ): Promise<CopilotRuntimeChatCompletionResponse> {
61
+ const { eventSource, model, actions, messages, threadId, runId } = request;
65
62
  const result = await this.options.chainFn({
66
63
  messages: messages.map(convertMessageToLangChainMessage),
67
64
  tools: actions.map(convertActionInputToLangChainTool),
@@ -77,6 +74,8 @@ export class LangChainAdapter implements CopilotServiceAdapter {
77
74
  });
78
75
  });
79
76
 
80
- return {};
77
+ return {
78
+ threadId: threadId || nanoid(),
79
+ };
81
80
  }
82
81
  }