@copilotkit/runtime 0.0.0-test-custom-tag-prerelease-1-20250108200215

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 (146) hide show
  1. package/.eslintrc.js +7 -0
  2. package/CHANGELOG.md +729 -0
  3. package/README.md +46 -0
  4. package/__snapshots__/schema/schema.graphql +262 -0
  5. package/dist/chunk-2WXVJKUZ.mjs +25 -0
  6. package/dist/chunk-2WXVJKUZ.mjs.map +1 -0
  7. package/dist/chunk-44O2JGUY.mjs +12 -0
  8. package/dist/chunk-44O2JGUY.mjs.map +1 -0
  9. package/dist/chunk-CLGKEUOA.mjs +1408 -0
  10. package/dist/chunk-CLGKEUOA.mjs.map +1 -0
  11. package/dist/chunk-D2WLFQS6.mjs +43 -0
  12. package/dist/chunk-D2WLFQS6.mjs.map +1 -0
  13. package/dist/chunk-DFOKBSIS.mjs +1 -0
  14. package/dist/chunk-DFOKBSIS.mjs.map +1 -0
  15. package/dist/chunk-RFF5IIZJ.mjs +66 -0
  16. package/dist/chunk-RFF5IIZJ.mjs.map +1 -0
  17. package/dist/chunk-U3V2BCGI.mjs +152 -0
  18. package/dist/chunk-U3V2BCGI.mjs.map +1 -0
  19. package/dist/chunk-UYX3NHOI.mjs +25 -0
  20. package/dist/chunk-UYX3NHOI.mjs.map +1 -0
  21. package/dist/chunk-W3GSZTZR.mjs +3281 -0
  22. package/dist/chunk-W3GSZTZR.mjs.map +1 -0
  23. package/dist/chunk-WPNQ4AMN.mjs +80 -0
  24. package/dist/chunk-WPNQ4AMN.mjs.map +1 -0
  25. package/dist/copilot-runtime-6285d897.d.ts +189 -0
  26. package/dist/graphql/types/base/index.d.ts +6 -0
  27. package/dist/graphql/types/base/index.js +63 -0
  28. package/dist/graphql/types/base/index.js.map +1 -0
  29. package/dist/graphql/types/base/index.mjs +8 -0
  30. package/dist/graphql/types/base/index.mjs.map +1 -0
  31. package/dist/graphql/types/converted/index.d.ts +2 -0
  32. package/dist/graphql/types/converted/index.js +124 -0
  33. package/dist/graphql/types/converted/index.js.map +1 -0
  34. package/dist/graphql/types/converted/index.mjs +17 -0
  35. package/dist/graphql/types/converted/index.mjs.map +1 -0
  36. package/dist/groq-adapter-15d41154.d.ts +281 -0
  37. package/dist/index-ff3fbc33.d.ts +87 -0
  38. package/dist/index.d.ts +23 -0
  39. package/dist/index.js +5039 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/index.mjs +76 -0
  42. package/dist/index.mjs.map +1 -0
  43. package/dist/langserve-48e976ac.d.ts +176 -0
  44. package/dist/lib/cloud/index.d.ts +6 -0
  45. package/dist/lib/cloud/index.js +18 -0
  46. package/dist/lib/cloud/index.js.map +1 -0
  47. package/dist/lib/cloud/index.mjs +1 -0
  48. package/dist/lib/cloud/index.mjs.map +1 -0
  49. package/dist/lib/index.d.ts +20 -0
  50. package/dist/lib/index.js +4687 -0
  51. package/dist/lib/index.js.map +1 -0
  52. package/dist/lib/index.mjs +58 -0
  53. package/dist/lib/index.mjs.map +1 -0
  54. package/dist/lib/integrations/index.d.ts +33 -0
  55. package/dist/lib/integrations/index.js +2091 -0
  56. package/dist/lib/integrations/index.js.map +1 -0
  57. package/dist/lib/integrations/index.mjs +34 -0
  58. package/dist/lib/integrations/index.mjs.map +1 -0
  59. package/dist/lib/integrations/nest/index.d.ts +14 -0
  60. package/dist/lib/integrations/nest/index.js +2000 -0
  61. package/dist/lib/integrations/nest/index.js.map +1 -0
  62. package/dist/lib/integrations/nest/index.mjs +13 -0
  63. package/dist/lib/integrations/nest/index.mjs.map +1 -0
  64. package/dist/lib/integrations/node-express/index.d.ts +14 -0
  65. package/dist/lib/integrations/node-express/index.js +2000 -0
  66. package/dist/lib/integrations/node-express/index.js.map +1 -0
  67. package/dist/lib/integrations/node-express/index.mjs +13 -0
  68. package/dist/lib/integrations/node-express/index.mjs.map +1 -0
  69. package/dist/lib/integrations/node-http/index.d.ts +14 -0
  70. package/dist/lib/integrations/node-http/index.js +1986 -0
  71. package/dist/lib/integrations/node-http/index.js.map +1 -0
  72. package/dist/lib/integrations/node-http/index.mjs +12 -0
  73. package/dist/lib/integrations/node-http/index.mjs.map +1 -0
  74. package/dist/service-adapters/index.d.ts +84 -0
  75. package/dist/service-adapters/index.js +1448 -0
  76. package/dist/service-adapters/index.js.map +1 -0
  77. package/dist/service-adapters/index.mjs +26 -0
  78. package/dist/service-adapters/index.mjs.map +1 -0
  79. package/dist/utils/index.d.ts +49 -0
  80. package/dist/utils/index.js +174 -0
  81. package/dist/utils/index.js.map +1 -0
  82. package/dist/utils/index.mjs +12 -0
  83. package/dist/utils/index.mjs.map +1 -0
  84. package/jest.config.js +5 -0
  85. package/package.json +85 -0
  86. package/scripts/generate-gql-schema.ts +13 -0
  87. package/src/agents/langgraph/event-source.ts +287 -0
  88. package/src/agents/langgraph/events.ts +338 -0
  89. package/src/graphql/inputs/action.input.ts +16 -0
  90. package/src/graphql/inputs/agent-session.input.ts +13 -0
  91. package/src/graphql/inputs/agent-state.input.ts +10 -0
  92. package/src/graphql/inputs/cloud-guardrails.input.ts +16 -0
  93. package/src/graphql/inputs/cloud.input.ts +8 -0
  94. package/src/graphql/inputs/context-property.input.ts +10 -0
  95. package/src/graphql/inputs/custom-property.input.ts +15 -0
  96. package/src/graphql/inputs/forwarded-parameters.input.ts +22 -0
  97. package/src/graphql/inputs/frontend.input.ts +14 -0
  98. package/src/graphql/inputs/generate-copilot-response.input.ts +47 -0
  99. package/src/graphql/inputs/message.input.ts +92 -0
  100. package/src/graphql/resolvers/copilot.resolver.ts +540 -0
  101. package/src/graphql/types/base/index.ts +10 -0
  102. package/src/graphql/types/converted/index.ts +70 -0
  103. package/src/graphql/types/copilot-response.type.ts +113 -0
  104. package/src/graphql/types/enums.ts +37 -0
  105. package/src/graphql/types/guardrails-result.type.ts +20 -0
  106. package/src/graphql/types/message-status.type.ts +40 -0
  107. package/src/graphql/types/response-status.type.ts +66 -0
  108. package/src/index.ts +4 -0
  109. package/src/lib/cloud/index.ts +4 -0
  110. package/src/lib/index.ts +8 -0
  111. package/src/lib/integrations/index.ts +6 -0
  112. package/src/lib/integrations/nest/index.ts +17 -0
  113. package/src/lib/integrations/nextjs/app-router.ts +40 -0
  114. package/src/lib/integrations/nextjs/pages-router.ts +49 -0
  115. package/src/lib/integrations/node-express/index.ts +17 -0
  116. package/src/lib/integrations/node-http/index.ts +34 -0
  117. package/src/lib/integrations/shared.ts +109 -0
  118. package/src/lib/logger.ts +28 -0
  119. package/src/lib/runtime/copilot-runtime.ts +412 -0
  120. package/src/lib/runtime/remote-action-constructors.ts +304 -0
  121. package/src/lib/runtime/remote-actions.ts +174 -0
  122. package/src/lib/runtime/remote-lg-action.ts +657 -0
  123. package/src/lib/telemetry-client.ts +52 -0
  124. package/src/service-adapters/anthropic/anthropic-adapter.ts +205 -0
  125. package/src/service-adapters/anthropic/utils.ts +144 -0
  126. package/src/service-adapters/conversion.ts +64 -0
  127. package/src/service-adapters/events.ts +377 -0
  128. package/src/service-adapters/experimental/empty/empty-adapter.ts +33 -0
  129. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +79 -0
  130. package/src/service-adapters/google/google-genai-adapter.ts +39 -0
  131. package/src/service-adapters/groq/groq-adapter.ts +173 -0
  132. package/src/service-adapters/index.ts +16 -0
  133. package/src/service-adapters/langchain/langchain-adapter.ts +99 -0
  134. package/src/service-adapters/langchain/langserve.ts +87 -0
  135. package/src/service-adapters/langchain/types.ts +14 -0
  136. package/src/service-adapters/langchain/utils.ts +306 -0
  137. package/src/service-adapters/openai/openai-adapter.ts +210 -0
  138. package/src/service-adapters/openai/openai-assistant-adapter.ts +304 -0
  139. package/src/service-adapters/openai/utils.ts +161 -0
  140. package/src/service-adapters/service-adapter.ts +30 -0
  141. package/src/service-adapters/unify/unify-adapter.ts +145 -0
  142. package/src/utils/failed-response-status-reasons.ts +48 -0
  143. package/src/utils/index.ts +1 -0
  144. package/tsconfig.json +11 -0
  145. package/tsup.config.ts +16 -0
  146. package/typedoc.json +4 -0
@@ -0,0 +1,377 @@
1
+ import { Action, randomId } from "@copilotkit/shared";
2
+ import {
3
+ of,
4
+ concat,
5
+ map,
6
+ scan,
7
+ concatMap,
8
+ ReplaySubject,
9
+ Subject,
10
+ firstValueFrom,
11
+ from,
12
+ } from "rxjs";
13
+ import { streamLangChainResponse } from "./langchain/utils";
14
+ import { GuardrailsResult } from "../graphql/types/guardrails-result.type";
15
+ import telemetry from "../lib/telemetry-client";
16
+ import { isLangGraphAgentAction } from "../lib/runtime/remote-actions";
17
+ import { ActionInput } from "../graphql/inputs/action.input";
18
+ import { ActionExecutionMessage, ResultMessage } from "../graphql/types/converted";
19
+ import { plainToInstance } from "class-transformer";
20
+
21
+ export enum RuntimeEventTypes {
22
+ TextMessageStart = "TextMessageStart",
23
+ TextMessageContent = "TextMessageContent",
24
+ TextMessageEnd = "TextMessageEnd",
25
+ ActionExecutionStart = "ActionExecutionStart",
26
+ ActionExecutionArgs = "ActionExecutionArgs",
27
+ ActionExecutionEnd = "ActionExecutionEnd",
28
+ ActionExecutionResult = "ActionExecutionResult",
29
+ AgentStateMessage = "AgentStateMessage",
30
+ }
31
+
32
+ export type RuntimeEvent =
33
+ | { type: RuntimeEventTypes.TextMessageStart; messageId: string; parentMessageId?: string }
34
+ | {
35
+ type: RuntimeEventTypes.TextMessageContent;
36
+ messageId: string;
37
+ content: string;
38
+ }
39
+ | { type: RuntimeEventTypes.TextMessageEnd; messageId: string }
40
+ | {
41
+ type: RuntimeEventTypes.ActionExecutionStart;
42
+ actionExecutionId: string;
43
+ actionName: string;
44
+ parentMessageId?: string;
45
+ }
46
+ | { type: RuntimeEventTypes.ActionExecutionArgs; actionExecutionId: string; args: string }
47
+ | { type: RuntimeEventTypes.ActionExecutionEnd; actionExecutionId: string }
48
+ | {
49
+ type: RuntimeEventTypes.ActionExecutionResult;
50
+ actionName: string;
51
+ actionExecutionId: string;
52
+ result: string;
53
+ }
54
+ | {
55
+ type: RuntimeEventTypes.AgentStateMessage;
56
+ threadId: string;
57
+ agentName: string;
58
+ nodeName: string;
59
+ runId: string;
60
+ active: boolean;
61
+ role: string;
62
+ state: string;
63
+ running: boolean;
64
+ };
65
+
66
+ interface RuntimeEventWithState {
67
+ event: RuntimeEvent | null;
68
+ callActionServerSide: boolean;
69
+ action: Action<any> | null;
70
+ actionExecutionId: string | null;
71
+ args: string;
72
+ actionExecutionParentMessageId: string | null;
73
+ }
74
+
75
+ type EventSourceCallback = (eventStream$: RuntimeEventSubject) => Promise<void>;
76
+
77
+ export class RuntimeEventSubject extends ReplaySubject<RuntimeEvent> {
78
+ constructor() {
79
+ super();
80
+ }
81
+
82
+ sendTextMessageStart({
83
+ messageId,
84
+ parentMessageId,
85
+ }: {
86
+ messageId: string;
87
+ parentMessageId?: string;
88
+ }) {
89
+ this.next({ type: RuntimeEventTypes.TextMessageStart, messageId, parentMessageId });
90
+ }
91
+
92
+ sendTextMessageContent({ messageId, content }: { messageId: string; content: string }) {
93
+ this.next({ type: RuntimeEventTypes.TextMessageContent, content, messageId });
94
+ }
95
+
96
+ sendTextMessageEnd({ messageId }: { messageId: string }) {
97
+ this.next({ type: RuntimeEventTypes.TextMessageEnd, messageId });
98
+ }
99
+
100
+ sendTextMessage(messageId: string, content: string) {
101
+ this.sendTextMessageStart({ messageId });
102
+ this.sendTextMessageContent({ messageId, content });
103
+ this.sendTextMessageEnd({ messageId });
104
+ }
105
+
106
+ sendActionExecutionStart({
107
+ actionExecutionId,
108
+ actionName,
109
+ parentMessageId,
110
+ }: {
111
+ actionExecutionId: string;
112
+ actionName: string;
113
+ parentMessageId?: string;
114
+ }) {
115
+ this.next({
116
+ type: RuntimeEventTypes.ActionExecutionStart,
117
+ actionExecutionId,
118
+ actionName,
119
+ parentMessageId,
120
+ });
121
+ }
122
+
123
+ sendActionExecutionArgs({
124
+ actionExecutionId,
125
+ args,
126
+ }: {
127
+ actionExecutionId: string;
128
+ args: string;
129
+ }) {
130
+ this.next({ type: RuntimeEventTypes.ActionExecutionArgs, args, actionExecutionId });
131
+ }
132
+
133
+ sendActionExecutionEnd({ actionExecutionId }: { actionExecutionId: string }) {
134
+ this.next({ type: RuntimeEventTypes.ActionExecutionEnd, actionExecutionId });
135
+ }
136
+
137
+ sendActionExecution({
138
+ actionExecutionId,
139
+ actionName,
140
+ args,
141
+ parentMessageId,
142
+ }: {
143
+ actionExecutionId: string;
144
+ actionName: string;
145
+ args: string;
146
+ parentMessageId?: string;
147
+ }) {
148
+ this.sendActionExecutionStart({ actionExecutionId, actionName, parentMessageId });
149
+ this.sendActionExecutionArgs({ actionExecutionId, args });
150
+ this.sendActionExecutionEnd({ actionExecutionId });
151
+ }
152
+
153
+ sendActionExecutionResult({
154
+ actionExecutionId,
155
+ actionName,
156
+ result,
157
+ }: {
158
+ actionExecutionId: string;
159
+ actionName: string;
160
+ result: string;
161
+ }) {
162
+ this.next({
163
+ type: RuntimeEventTypes.ActionExecutionResult,
164
+ actionName,
165
+ actionExecutionId,
166
+ result,
167
+ });
168
+ }
169
+
170
+ sendAgentStateMessage({
171
+ threadId,
172
+ agentName,
173
+ nodeName,
174
+ runId,
175
+ active,
176
+ role,
177
+ state,
178
+ running,
179
+ }: {
180
+ threadId: string;
181
+ agentName: string;
182
+ nodeName: string;
183
+ runId: string;
184
+ active: boolean;
185
+ role: string;
186
+ state: string;
187
+ running: boolean;
188
+ }) {
189
+ this.next({
190
+ type: RuntimeEventTypes.AgentStateMessage,
191
+ threadId,
192
+ agentName,
193
+ nodeName,
194
+ runId,
195
+ active,
196
+ role,
197
+ state,
198
+ running,
199
+ });
200
+ }
201
+ }
202
+
203
+ export class RuntimeEventSource {
204
+ private eventStream$ = new RuntimeEventSubject();
205
+ private callback!: EventSourceCallback;
206
+
207
+ async stream(callback: EventSourceCallback): Promise<void> {
208
+ this.callback = callback;
209
+ }
210
+
211
+ sendErrorMessageToChat(message = "An error occurred. Please try again.") {
212
+ const errorMessage = `❌ ${message}`;
213
+ if (!this.callback) {
214
+ this.stream(async (eventStream$) => {
215
+ eventStream$.sendTextMessage(randomId(), errorMessage);
216
+ });
217
+ } else {
218
+ this.eventStream$.sendTextMessage(randomId(), errorMessage);
219
+ }
220
+ }
221
+
222
+ processRuntimeEvents({
223
+ serverSideActions,
224
+ guardrailsResult$,
225
+ actionInputsWithoutAgents,
226
+ }: {
227
+ serverSideActions: Action<any>[];
228
+ guardrailsResult$?: Subject<GuardrailsResult>;
229
+ actionInputsWithoutAgents: ActionInput[];
230
+ }) {
231
+ this.callback(this.eventStream$).catch((error) => {
232
+ console.error("Error in event source callback", error);
233
+ this.sendErrorMessageToChat();
234
+ });
235
+ return this.eventStream$.pipe(
236
+ // track state
237
+ scan(
238
+ (acc, event) => {
239
+ // It seems like this is needed so that rxjs recognizes the object has changed
240
+ // This fixes an issue where action were executed multiple times
241
+ // Not investigating further for now (Markus)
242
+ acc = { ...acc };
243
+
244
+ if (event.type === RuntimeEventTypes.ActionExecutionStart) {
245
+ acc.callActionServerSide =
246
+ serverSideActions.find((action) => action.name === event.actionName) !== undefined;
247
+ acc.args = "";
248
+ acc.actionExecutionId = event.actionExecutionId;
249
+ if (acc.callActionServerSide) {
250
+ acc.action = serverSideActions.find((action) => action.name === event.actionName);
251
+ }
252
+ acc.actionExecutionParentMessageId = event.parentMessageId;
253
+ } else if (event.type === RuntimeEventTypes.ActionExecutionArgs) {
254
+ acc.args += event.args;
255
+ }
256
+
257
+ acc.event = event;
258
+
259
+ return acc;
260
+ },
261
+ {
262
+ event: null,
263
+ callActionServerSide: false,
264
+ args: "",
265
+ actionExecutionId: null,
266
+ action: null,
267
+ actionExecutionParentMessageId: null,
268
+ } as RuntimeEventWithState,
269
+ ),
270
+ concatMap((eventWithState) => {
271
+ if (
272
+ eventWithState.event!.type === RuntimeEventTypes.ActionExecutionEnd &&
273
+ eventWithState.callActionServerSide
274
+ ) {
275
+ const toolCallEventStream$ = new RuntimeEventSubject();
276
+ executeAction(
277
+ toolCallEventStream$,
278
+ guardrailsResult$ ? guardrailsResult$ : null,
279
+ eventWithState.action!,
280
+ eventWithState.args,
281
+ eventWithState.actionExecutionParentMessageId,
282
+ eventWithState.actionExecutionId,
283
+ actionInputsWithoutAgents,
284
+ ).catch((error) => {
285
+ console.error(error);
286
+ });
287
+
288
+ telemetry.capture("oss.runtime.server_action_executed", {});
289
+ return concat(of(eventWithState.event!), toolCallEventStream$);
290
+ } else {
291
+ return of(eventWithState.event!);
292
+ }
293
+ }),
294
+ );
295
+ }
296
+ }
297
+
298
+ async function executeAction(
299
+ eventStream$: RuntimeEventSubject,
300
+ guardrailsResult$: Subject<GuardrailsResult> | null,
301
+ action: Action<any>,
302
+ actionArguments: string,
303
+ actionExecutionParentMessageId: string | null,
304
+ actionExecutionId: string,
305
+ actionInputsWithoutAgents: ActionInput[],
306
+ ) {
307
+ if (guardrailsResult$) {
308
+ const { status } = await firstValueFrom(guardrailsResult$);
309
+
310
+ if (status === "denied") {
311
+ eventStream$.complete();
312
+ return;
313
+ }
314
+ }
315
+
316
+ // Prepare arguments for function calling
317
+ let args: Record<string, any>[] = [];
318
+ if (actionArguments) {
319
+ try {
320
+ args = JSON.parse(actionArguments);
321
+ } catch (e) {
322
+ console.warn("Action argument unparsable", { actionArguments });
323
+ }
324
+ }
325
+
326
+ // handle LangGraph agents
327
+ if (isLangGraphAgentAction(action)) {
328
+ const result = `${action.name} agent started`;
329
+
330
+ const agentExecution = plainToInstance(ActionExecutionMessage, {
331
+ id: actionExecutionId,
332
+ createdAt: new Date(),
333
+ name: action.name,
334
+ arguments: JSON.parse(actionArguments),
335
+ parentMessageId: actionExecutionParentMessageId ?? actionExecutionId,
336
+ });
337
+
338
+ const agentExecutionResult = plainToInstance(ResultMessage, {
339
+ id: "result-" + actionExecutionId,
340
+ createdAt: new Date(),
341
+ actionExecutionId,
342
+ actionName: action.name,
343
+ result,
344
+ });
345
+
346
+ eventStream$.sendActionExecutionResult({
347
+ actionExecutionId,
348
+ actionName: action.name,
349
+ result,
350
+ });
351
+
352
+ const stream = await action.langGraphAgentHandler({
353
+ name: action.name,
354
+ actionInputsWithoutAgents,
355
+ additionalMessages: [agentExecution, agentExecutionResult],
356
+ });
357
+
358
+ // forward to eventStream$
359
+ from(stream).subscribe({
360
+ next: (event) => eventStream$.next(event),
361
+ error: (err) => console.error("Error in stream", err),
362
+ complete: () => eventStream$.complete(),
363
+ });
364
+ } else {
365
+ // call the function
366
+ const result = await action.handler?.(args);
367
+
368
+ await streamLangChainResponse({
369
+ result,
370
+ eventStream$,
371
+ actionExecution: {
372
+ name: action.name,
373
+ id: actionExecutionId,
374
+ },
375
+ });
376
+ }
377
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * CopilotKit Empty Adapter
3
+ *
4
+ * This adapter is meant to preserve adherence to runtime requirements, while doing nothing
5
+ * Ideal if you don't want to connect an LLM the to the runtime, and only use your LangGraph agent.
6
+ * Be aware that Copilot Suggestions will not work if you use this adapter
7
+ *
8
+ * ## Example
9
+ *
10
+ * ```ts
11
+ * import { CopilotRuntime, ExperimentalEmptyAdapter } from "@copilotkit/runtime";
12
+ *
13
+ * const copilotKit = new CopilotRuntime();
14
+ *
15
+ * return new ExperimentalEmptyAdapter();
16
+ * ```
17
+ */
18
+ import {
19
+ CopilotServiceAdapter,
20
+ CopilotRuntimeChatCompletionRequest,
21
+ CopilotRuntimeChatCompletionResponse,
22
+ } from "../../service-adapter";
23
+ import { randomId } from "@copilotkit/shared";
24
+
25
+ export class ExperimentalEmptyAdapter implements CopilotServiceAdapter {
26
+ async process(
27
+ request: CopilotRuntimeChatCompletionRequest,
28
+ ): Promise<CopilotRuntimeChatCompletionResponse> {
29
+ return {
30
+ threadId: request.threadId || randomId(),
31
+ };
32
+ }
33
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * CopilotKit Adapter for Ollama
3
+ *
4
+ * <RequestExample>
5
+ * ```jsx CopilotRuntime Example
6
+ * const copilotKit = new CopilotRuntime();
7
+ * return copilotKit.response(req, new OllamaAdapter());
8
+ * ```
9
+ * </RequestExample>
10
+ *
11
+ * You can easily set the model to use by passing it to the constructor.
12
+ * ```jsx
13
+ * const copilotKit = new CopilotRuntime();
14
+ * return copilotKit.response(
15
+ * req,
16
+ * new OllamaAdapter({ model: "llama3-70b-8192" }),
17
+ * );
18
+ * ```
19
+ */
20
+ import { TextMessage } from "../../../graphql/types/converted";
21
+ import {
22
+ CopilotServiceAdapter,
23
+ CopilotRuntimeChatCompletionRequest,
24
+ CopilotRuntimeChatCompletionResponse,
25
+ } from "../../service-adapter";
26
+ import { Ollama } from "@langchain/community/llms/ollama";
27
+ import { randomId } from "@copilotkit/shared";
28
+
29
+ const DEFAULT_MODEL = "llama3:latest";
30
+
31
+ interface OllamaAdapterOptions {
32
+ model?: string;
33
+ }
34
+
35
+ export class ExperimentalOllamaAdapter implements CopilotServiceAdapter {
36
+ private model: string;
37
+
38
+ constructor(options?: OllamaAdapterOptions) {
39
+ if (options?.model) {
40
+ this.model = options.model;
41
+ } else {
42
+ this.model = DEFAULT_MODEL;
43
+ }
44
+ }
45
+
46
+ async process(
47
+ request: CopilotRuntimeChatCompletionRequest,
48
+ ): Promise<CopilotRuntimeChatCompletionResponse> {
49
+ const { messages, actions, eventSource } = request;
50
+ // const messages = this.transformMessages(forwardedProps.messages);
51
+
52
+ const ollama = new Ollama({
53
+ model: this.model,
54
+ });
55
+ const contents = (messages.filter((m) => m.isTextMessage()) as TextMessage[]).map(
56
+ (m) => m.content,
57
+ );
58
+ const _stream = await ollama.stream(contents); // [TODO] role info is dropped...
59
+
60
+ eventSource.stream(async (eventStream$) => {
61
+ const currentMessageId = randomId();
62
+ eventStream$.sendTextMessageStart({ messageId: currentMessageId });
63
+ for await (const chunkText of _stream) {
64
+ eventStream$.sendTextMessageContent({
65
+ messageId: currentMessageId,
66
+ content: chunkText,
67
+ });
68
+ }
69
+ eventStream$.sendTextMessageEnd({ messageId: currentMessageId });
70
+ // we may need to add this later.. [nc]
71
+ // let calls = (await result.response).functionCalls();
72
+
73
+ eventStream$.complete();
74
+ });
75
+ return {
76
+ threadId: request.threadId || randomId(),
77
+ };
78
+ }
79
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Copilot Runtime adapter for Google Generative AI (e.g. Gemini).
3
+ *
4
+ * ## Example
5
+ *
6
+ * ```ts
7
+ * import { CopilotRuntime, GoogleGenerativeAIAdapter } from "@copilotkit/runtime";
8
+ * const { GoogleGenerativeAI } = require("@google/generative-ai");
9
+ *
10
+ * const genAI = new GoogleGenerativeAI(process.env["GOOGLE_API_KEY"]);
11
+ *
12
+ * const copilotKit = new CopilotRuntime();
13
+ *
14
+ * return new GoogleGenerativeAIAdapter({ model: "gemini-1.5-pro" });
15
+ * ```
16
+ */
17
+ import { ChatGoogle } from "@langchain/google-gauth";
18
+ import { LangChainAdapter } from "../langchain/langchain-adapter";
19
+
20
+ interface GoogleGenerativeAIAdapterOptions {
21
+ /**
22
+ * A custom Google Generative AI model to use.
23
+ */
24
+ model?: string;
25
+ }
26
+
27
+ export class GoogleGenerativeAIAdapter extends LangChainAdapter {
28
+ constructor(options?: GoogleGenerativeAIAdapterOptions) {
29
+ super({
30
+ chainFn: async ({ messages, tools, threadId }) => {
31
+ const model = new ChatGoogle({
32
+ modelName: options?.model ?? "gemini-1.5-pro",
33
+ apiVersion: "v1beta",
34
+ }).bindTools(tools);
35
+ return model.stream(messages, { metadata: { conversation_id: threadId } });
36
+ },
37
+ });
38
+ }
39
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Copilot Runtime adapter for Groq.
3
+ *
4
+ * ## Example
5
+ *
6
+ * ```ts
7
+ * import { CopilotRuntime, GroqAdapter } from "@copilotkit/runtime";
8
+ * import { Groq } from "groq-sdk";
9
+ *
10
+ * const groq = new Groq({ apiKey: process.env["GROQ_API_KEY"] });
11
+ *
12
+ * const copilotKit = new CopilotRuntime();
13
+ *
14
+ * return new GroqAdapter({ groq, model: "<model-name>" });
15
+ * ```
16
+ */
17
+ import { Groq } from "groq-sdk";
18
+ import {
19
+ CopilotServiceAdapter,
20
+ CopilotRuntimeChatCompletionRequest,
21
+ CopilotRuntimeChatCompletionResponse,
22
+ } from "../service-adapter";
23
+ import {
24
+ convertActionInputToOpenAITool,
25
+ convertMessageToOpenAIMessage,
26
+ limitMessagesToTokenCount,
27
+ } from "../openai/utils";
28
+ import { randomId } from "@copilotkit/shared";
29
+
30
+ const DEFAULT_MODEL = "llama3-groq-70b-8192-tool-use-preview";
31
+
32
+ export interface GroqAdapterParams {
33
+ /**
34
+ * An optional Groq instance to use.
35
+ */
36
+ groq?: Groq;
37
+
38
+ /**
39
+ * The model to use.
40
+ */
41
+ model?: string;
42
+
43
+ /**
44
+ * Whether to disable parallel tool calls.
45
+ * You can disable parallel tool calls to force the model to execute tool calls sequentially.
46
+ * This is useful if you want to execute tool calls in a specific order so that the state changes
47
+ * introduced by one tool call are visible to the next tool call. (i.e. new actions or readables)
48
+ *
49
+ * @default false
50
+ */
51
+ disableParallelToolCalls?: boolean;
52
+ }
53
+
54
+ export class GroqAdapter implements CopilotServiceAdapter {
55
+ private model: string = DEFAULT_MODEL;
56
+
57
+ private disableParallelToolCalls: boolean = false;
58
+ private _groq: Groq;
59
+ public get groq(): Groq {
60
+ return this._groq;
61
+ }
62
+
63
+ constructor(params?: GroqAdapterParams) {
64
+ this._groq = params?.groq || new Groq({});
65
+ if (params?.model) {
66
+ this.model = params.model;
67
+ }
68
+ this.disableParallelToolCalls = params?.disableParallelToolCalls || false;
69
+ }
70
+
71
+ async process(
72
+ request: CopilotRuntimeChatCompletionRequest,
73
+ ): Promise<CopilotRuntimeChatCompletionResponse> {
74
+ const {
75
+ threadId,
76
+ model = this.model,
77
+ messages,
78
+ actions,
79
+ eventSource,
80
+ forwardedParameters,
81
+ } = request;
82
+ const tools = actions.map(convertActionInputToOpenAITool);
83
+
84
+ let openaiMessages = messages.map(convertMessageToOpenAIMessage);
85
+ openaiMessages = limitMessagesToTokenCount(openaiMessages, tools, model);
86
+
87
+ let toolChoice: any = forwardedParameters?.toolChoice;
88
+ if (forwardedParameters?.toolChoice === "function") {
89
+ toolChoice = {
90
+ type: "function",
91
+ function: { name: forwardedParameters.toolChoiceFunctionName },
92
+ };
93
+ }
94
+ const stream = await this.groq.chat.completions.create({
95
+ model: model,
96
+ stream: true,
97
+ messages: openaiMessages,
98
+ ...(tools.length > 0 && { tools }),
99
+ ...(forwardedParameters?.maxTokens && {
100
+ max_tokens: forwardedParameters.maxTokens,
101
+ }),
102
+ ...(forwardedParameters?.stop && { stop: forwardedParameters.stop }),
103
+ ...(toolChoice && { tool_choice: toolChoice }),
104
+ ...(this.disableParallelToolCalls && { parallel_tool_calls: false }),
105
+ ...(forwardedParameters?.temperature && { temperature: forwardedParameters.temperature }),
106
+ });
107
+
108
+ eventSource.stream(async (eventStream$) => {
109
+ let mode: "function" | "message" | null = null;
110
+ let currentMessageId: string;
111
+ let currentToolCallId: string;
112
+
113
+ for await (const chunk of stream) {
114
+ const toolCall = chunk.choices[0].delta.tool_calls?.[0];
115
+ const content = chunk.choices[0].delta.content;
116
+
117
+ // When switching from message to function or vice versa,
118
+ // send the respective end event.
119
+ // If toolCall?.id is defined, it means a new tool call starts.
120
+ if (mode === "message" && toolCall?.id) {
121
+ mode = null;
122
+ eventStream$.sendTextMessageEnd({ messageId: currentMessageId });
123
+ } else if (mode === "function" && (toolCall === undefined || toolCall?.id)) {
124
+ mode = null;
125
+ eventStream$.sendActionExecutionEnd({ actionExecutionId: currentToolCallId });
126
+ }
127
+
128
+ // If we send a new message type, send the appropriate start event.
129
+ if (mode === null) {
130
+ if (toolCall?.id) {
131
+ mode = "function";
132
+ currentToolCallId = toolCall!.id;
133
+ eventStream$.sendActionExecutionStart({
134
+ actionExecutionId: currentToolCallId,
135
+ actionName: toolCall!.function!.name,
136
+ parentMessageId: chunk.id,
137
+ });
138
+ } else if (content) {
139
+ mode = "message";
140
+ currentMessageId = chunk.id;
141
+ eventStream$.sendTextMessageStart({ messageId: currentMessageId });
142
+ }
143
+ }
144
+
145
+ // send the content events
146
+ if (mode === "message" && content) {
147
+ eventStream$.sendTextMessageContent({
148
+ messageId: currentMessageId,
149
+ content,
150
+ });
151
+ } else if (mode === "function" && toolCall?.function?.arguments) {
152
+ eventStream$.sendActionExecutionArgs({
153
+ actionExecutionId: currentToolCallId,
154
+ args: toolCall.function.arguments,
155
+ });
156
+ }
157
+ }
158
+
159
+ // send the end events
160
+ if (mode === "message") {
161
+ eventStream$.sendTextMessageEnd({ messageId: currentMessageId });
162
+ } else if (mode === "function") {
163
+ eventStream$.sendActionExecutionEnd({ actionExecutionId: currentToolCallId });
164
+ }
165
+
166
+ eventStream$.complete();
167
+ });
168
+
169
+ return {
170
+ threadId: threadId || randomId(),
171
+ };
172
+ }
173
+ }