@copilotkit/runtime 0.37.0

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 (105) hide show
  1. package/.eslintrc.js +7 -0
  2. package/.turbo/turbo-build.log +70 -0
  3. package/CHANGELOG.md +1 -0
  4. package/__snapshots__/schema/schema.graphql +178 -0
  5. package/dist/chunk-2CCVVJDU.mjs +56 -0
  6. package/dist/chunk-2CCVVJDU.mjs.map +1 -0
  7. package/dist/chunk-4UA4RB4C.mjs +185 -0
  8. package/dist/chunk-4UA4RB4C.mjs.map +1 -0
  9. package/dist/chunk-5HGYI6EG.mjs +678 -0
  10. package/dist/chunk-5HGYI6EG.mjs.map +1 -0
  11. package/dist/chunk-7IFP53C6.mjs +169 -0
  12. package/dist/chunk-7IFP53C6.mjs.map +1 -0
  13. package/dist/chunk-BLTAUVRP.mjs +30 -0
  14. package/dist/chunk-BLTAUVRP.mjs.map +1 -0
  15. package/dist/chunk-NFCPM5AM.mjs +43 -0
  16. package/dist/chunk-NFCPM5AM.mjs.map +1 -0
  17. package/dist/chunk-XPAUPJMW.mjs +1051 -0
  18. package/dist/chunk-XPAUPJMW.mjs.map +1 -0
  19. package/dist/graphql/types/base/index.d.ts +6 -0
  20. package/dist/graphql/types/base/index.js +63 -0
  21. package/dist/graphql/types/base/index.js.map +1 -0
  22. package/dist/graphql/types/base/index.mjs +7 -0
  23. package/dist/graphql/types/base/index.mjs.map +1 -0
  24. package/dist/graphql/types/converted/index.d.ts +2 -0
  25. package/dist/graphql/types/converted/index.js +88 -0
  26. package/dist/graphql/types/converted/index.js.map +1 -0
  27. package/dist/graphql/types/converted/index.mjs +12 -0
  28. package/dist/graphql/types/converted/index.mjs.map +1 -0
  29. package/dist/index-aa091e3c.d.ts +49 -0
  30. package/dist/index-f0875df3.d.ts +197 -0
  31. package/dist/index.d.ts +15 -0
  32. package/dist/index.js +2171 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/index.mjs +49 -0
  35. package/dist/index.mjs.map +1 -0
  36. package/dist/langchain-adapter-9ce103f3.d.ts +200 -0
  37. package/dist/langserve-fd5066ee.d.ts +96 -0
  38. package/dist/lib/index.d.ts +15 -0
  39. package/dist/lib/index.js +2170 -0
  40. package/dist/lib/index.js.map +1 -0
  41. package/dist/lib/index.mjs +46 -0
  42. package/dist/lib/index.mjs.map +1 -0
  43. package/dist/lib/integrations/index.d.ts +9 -0
  44. package/dist/lib/integrations/index.js +1024 -0
  45. package/dist/lib/integrations/index.js.map +1 -0
  46. package/dist/lib/integrations/index.mjs +24 -0
  47. package/dist/lib/integrations/index.mjs.map +1 -0
  48. package/dist/lib/integrations/node-http/index.d.ts +8 -0
  49. package/dist/lib/integrations/node-http/index.js +969 -0
  50. package/dist/lib/integrations/node-http/index.js.map +1 -0
  51. package/dist/lib/integrations/node-http/index.mjs +10 -0
  52. package/dist/lib/integrations/node-http/index.mjs.map +1 -0
  53. package/dist/pages-router-b6bc6c60.d.ts +30 -0
  54. package/dist/service-adapters/index.d.ts +11 -0
  55. package/dist/service-adapters/index.js +912 -0
  56. package/dist/service-adapters/index.js.map +1 -0
  57. package/dist/service-adapters/index.mjs +18 -0
  58. package/dist/service-adapters/index.mjs.map +1 -0
  59. package/jest.config.js +5 -0
  60. package/package.json +63 -0
  61. package/scripts/generate-gql-schema.ts +13 -0
  62. package/src/graphql/inputs/action.input.ts +13 -0
  63. package/src/graphql/inputs/cloud-guardrails.input.ts +19 -0
  64. package/src/graphql/inputs/cloud.input.ts +8 -0
  65. package/src/graphql/inputs/context-property.input.ts +10 -0
  66. package/src/graphql/inputs/custom-property.input.ts +15 -0
  67. package/src/graphql/inputs/frontend.input.ts +11 -0
  68. package/src/graphql/inputs/generate-copilot-response.input.ts +22 -0
  69. package/src/graphql/inputs/message.input.ts +50 -0
  70. package/src/graphql/resolvers/copilot.resolver.ts +147 -0
  71. package/src/graphql/types/base/index.ts +10 -0
  72. package/src/graphql/types/converted/index.ts +29 -0
  73. package/src/graphql/types/copilot-response.type.ts +75 -0
  74. package/src/graphql/types/enums.ts +22 -0
  75. package/src/graphql/types/guardrails-result.type.ts +20 -0
  76. package/src/graphql/types/message-status.type.ts +40 -0
  77. package/src/graphql/types/response-status.type.ts +52 -0
  78. package/src/index.ts +2 -0
  79. package/src/lib/copilot-cloud.ts +63 -0
  80. package/src/lib/copilot-runtime.ts +261 -0
  81. package/src/lib/guardrails.ts +3 -0
  82. package/src/lib/index.ts +7 -0
  83. package/src/lib/integrations/index.ts +4 -0
  84. package/src/lib/integrations/nextjs/app-router.ts +29 -0
  85. package/src/lib/integrations/nextjs/pages-router.ts +36 -0
  86. package/src/lib/integrations/node-http/index.ts +23 -0
  87. package/src/lib/integrations/shared.ts +68 -0
  88. package/src/service-adapters/conversion.ts +47 -0
  89. package/src/service-adapters/events.ts +197 -0
  90. package/src/service-adapters/experimental/groq/groq-adapter.ts +124 -0
  91. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +75 -0
  92. package/src/service-adapters/google/google-genai-adapter.ts +149 -0
  93. package/src/service-adapters/google/utils.ts +94 -0
  94. package/src/service-adapters/index.ts +6 -0
  95. package/src/service-adapters/langchain/langchain-adapter.ts +82 -0
  96. package/src/service-adapters/langchain/langserve.ts +81 -0
  97. package/src/service-adapters/langchain/types.ts +14 -0
  98. package/src/service-adapters/langchain/utils.ts +235 -0
  99. package/src/service-adapters/openai/openai-adapter.ts +142 -0
  100. package/src/service-adapters/openai/openai-assistant-adapter.ts +260 -0
  101. package/src/service-adapters/openai/utils.ts +164 -0
  102. package/src/service-adapters/service-adapter.ts +29 -0
  103. package/tsconfig.json +11 -0
  104. package/tsup.config.ts +17 -0
  105. package/typedoc.json +4 -0
@@ -0,0 +1,75 @@
1
+ import { Field, InterfaceType, ObjectType } from "type-graphql";
2
+ import { MessageRole, ActionExecutionScope } from "./enums";
3
+ import { MessageStatusUnion } from "./message-status.type";
4
+ import { ResponseStatusUnion } from "./response-status.type";
5
+
6
+ @InterfaceType({
7
+ resolveType(value) {
8
+ if (value.hasOwnProperty("content")) {
9
+ return TextMessageOutput;
10
+ } else if (value.hasOwnProperty("name")) {
11
+ return ActionExecutionMessageOutput;
12
+ } else if (value.hasOwnProperty("result")) {
13
+ return ResultMessageOutput;
14
+ }
15
+ return undefined;
16
+ },
17
+ })
18
+ abstract class BaseMessageOutput {
19
+ @Field(() => String)
20
+ id: string;
21
+
22
+ @Field(() => Date)
23
+ createdAt: Date;
24
+
25
+ @Field(() => MessageStatusUnion)
26
+ status: typeof MessageStatusUnion;
27
+ }
28
+
29
+ @ObjectType({ implements: BaseMessageOutput })
30
+ export class TextMessageOutput {
31
+ @Field(() => MessageRole)
32
+ role: MessageRole;
33
+
34
+ @Field(() => [String])
35
+ content: string[];
36
+ }
37
+
38
+ @ObjectType({ implements: BaseMessageOutput })
39
+ export class ActionExecutionMessageOutput {
40
+ @Field(() => String)
41
+ name: string;
42
+
43
+ @Field(() => ActionExecutionScope)
44
+ scope: ActionExecutionScope;
45
+
46
+ @Field(() => [String])
47
+ arguments: string[];
48
+ }
49
+
50
+ @ObjectType({ implements: BaseMessageOutput })
51
+ export class ResultMessageOutput {
52
+ @Field(() => String)
53
+ actionExecutionId: string;
54
+
55
+ @Field(() => String)
56
+ actionName: string;
57
+
58
+ @Field(() => String)
59
+ result: string;
60
+ }
61
+
62
+ @ObjectType()
63
+ export class CopilotResponse {
64
+ @Field(() => String)
65
+ threadId!: string;
66
+
67
+ @Field(() => ResponseStatusUnion)
68
+ status: typeof ResponseStatusUnion;
69
+
70
+ @Field({ nullable: true })
71
+ runId?: string;
72
+
73
+ @Field(() => [BaseMessageOutput])
74
+ messages: (typeof BaseMessageOutput)[];
75
+ }
@@ -0,0 +1,22 @@
1
+ import { registerEnumType } from "type-graphql";
2
+
3
+ export enum MessageRole {
4
+ user = "user",
5
+ assistant = "assistant",
6
+ system = "system",
7
+ }
8
+
9
+ export enum ActionExecutionScope {
10
+ server = "server",
11
+ client = "client",
12
+ }
13
+
14
+ registerEnumType(MessageRole, {
15
+ name: "MessageRole",
16
+ description: "The role of the message",
17
+ });
18
+
19
+ registerEnumType(ActionExecutionScope, {
20
+ name: "ActionExecutionScope",
21
+ description: "The scope of the action",
22
+ });
@@ -0,0 +1,20 @@
1
+ import { Field, ObjectType, registerEnumType } from "type-graphql";
2
+
3
+ export enum GuardrailsResultStatus {
4
+ ALLOWED = "allowed",
5
+ DENIED = "denied",
6
+ }
7
+
8
+ registerEnumType(GuardrailsResultStatus, {
9
+ name: "GuardrailsResultStatus",
10
+ description: "The status of the guardrails check",
11
+ });
12
+
13
+ @ObjectType()
14
+ export class GuardrailsResult {
15
+ @Field(() => GuardrailsResultStatus)
16
+ status: GuardrailsResultStatus;
17
+
18
+ @Field(() => String, { nullable: true })
19
+ reason?: string;
20
+ }
@@ -0,0 +1,40 @@
1
+ import { Field, ObjectType, createUnionType, registerEnumType } from "type-graphql";
2
+
3
+ export enum MessageStatusCode {
4
+ Pending = "pending",
5
+ Success = "success",
6
+ Failed = "failed",
7
+ }
8
+
9
+ registerEnumType(MessageStatusCode, {
10
+ name: "MessageStatusCode",
11
+ });
12
+
13
+ @ObjectType()
14
+ class BaseMessageStatus {
15
+ @Field(() => MessageStatusCode)
16
+ code: MessageStatusCode;
17
+ }
18
+
19
+ @ObjectType()
20
+ export class PendingMessageStatus extends BaseMessageStatus {
21
+ code: MessageStatusCode = MessageStatusCode.Pending;
22
+ }
23
+
24
+ @ObjectType()
25
+ export class SuccessMessageStatus extends BaseMessageStatus {
26
+ code: MessageStatusCode = MessageStatusCode.Success;
27
+ }
28
+
29
+ @ObjectType()
30
+ export class FailedMessageStatus extends BaseMessageStatus {
31
+ code: MessageStatusCode = MessageStatusCode.Failed;
32
+
33
+ @Field(() => String)
34
+ reason: string;
35
+ }
36
+
37
+ export const MessageStatusUnion = createUnionType({
38
+ name: "MessageStatus",
39
+ types: () => [PendingMessageStatus, SuccessMessageStatus, FailedMessageStatus] as const,
40
+ });
@@ -0,0 +1,52 @@
1
+ import { Field, InterfaceType, ObjectType, createUnionType, registerEnumType } from "type-graphql";
2
+
3
+ export enum ResponseStatusCode {
4
+ Pending = "pending",
5
+ Success = "success",
6
+ Failed = "failed",
7
+ }
8
+
9
+ registerEnumType(ResponseStatusCode, {
10
+ name: "ResponseStatusCode",
11
+ });
12
+
13
+ @InterfaceType({
14
+ resolveType(value) {
15
+ if (value.code === ResponseStatusCode.Success) {
16
+ return SuccessResponseStatus;
17
+ } else if (value.code === ResponseStatusCode.Failed) {
18
+ return FailedResponseStatus;
19
+ } else if (value.code === ResponseStatusCode.Pending) {
20
+ return PendingResponseStatus;
21
+ }
22
+ return undefined;
23
+ },
24
+ })
25
+ @ObjectType()
26
+ abstract class BaseResponseStatus {
27
+ @Field(() => ResponseStatusCode)
28
+ code: ResponseStatusCode;
29
+ }
30
+
31
+ @ObjectType({ implements: BaseResponseStatus })
32
+ export class PendingResponseStatus extends BaseResponseStatus {
33
+ code: ResponseStatusCode = ResponseStatusCode.Pending;
34
+ }
35
+
36
+ @ObjectType({ implements: BaseResponseStatus })
37
+ export class SuccessResponseStatus extends BaseResponseStatus {
38
+ code: ResponseStatusCode = ResponseStatusCode.Success;
39
+ }
40
+
41
+ @ObjectType({ implements: BaseResponseStatus })
42
+ export class FailedResponseStatus extends BaseResponseStatus {
43
+ code: ResponseStatusCode = ResponseStatusCode.Failed;
44
+
45
+ @Field(() => String)
46
+ reason: string;
47
+ }
48
+
49
+ export const ResponseStatusUnion = createUnionType({
50
+ name: "ResponseStatus",
51
+ types: () => [PendingResponseStatus, SuccessResponseStatus, FailedResponseStatus] as const,
52
+ });
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ import "reflect-metadata";
2
+ export * from "./lib";
@@ -0,0 +1,63 @@
1
+ import {
2
+ COPILOT_CLOUD_API_URL,
3
+ COPILOT_CLOUD_VERSION,
4
+ COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
5
+ CopilotCloudConfig,
6
+ } from "@copilotkit/shared";
7
+
8
+ export interface CloudCheckGuardrailsInputParams {
9
+ cloud: CopilotCloudConfig;
10
+ publicApiKey: string;
11
+ // TODO-PROTOCOL: switch to graphql
12
+ messages: any[];
13
+ }
14
+
15
+ export interface CloudCheckGuardrailsInputResponse {
16
+ status: "allowed" | "denied";
17
+ reason: string;
18
+ }
19
+
20
+ export abstract class CopilotCloud {
21
+ abstract checkGuardrailsInput(
22
+ params: CloudCheckGuardrailsInputParams,
23
+ ): Promise<CloudCheckGuardrailsInputResponse>;
24
+ }
25
+
26
+ export class RemoteCopilotCloud extends CopilotCloud {
27
+ constructor(private readonly cloudApiUrl: string = COPILOT_CLOUD_API_URL) {
28
+ super();
29
+ }
30
+
31
+ async checkGuardrailsInput({
32
+ cloud,
33
+ publicApiKey,
34
+ messages,
35
+ }: CloudCheckGuardrailsInputParams): Promise<CloudCheckGuardrailsInputResponse> {
36
+ const url = `${this.cloudApiUrl}/${COPILOT_CLOUD_VERSION}/copilotkit/guardrails/input`;
37
+
38
+ const response = await fetch(url, {
39
+ method: "PUT",
40
+ headers: {
41
+ "Content-Type": "application/json",
42
+ [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey,
43
+ },
44
+ body: JSON.stringify({ messages, cloud }),
45
+ });
46
+
47
+ if (!response.ok) {
48
+ let message = response.statusText;
49
+
50
+ // try to parse the response body for a more detailed error message
51
+ try {
52
+ const json = await response.json();
53
+ if (json.message) {
54
+ message = json.message;
55
+ }
56
+ } catch (error) {}
57
+
58
+ throw new Error("Failed to check input guardrails: " + message);
59
+ }
60
+ const json = await response.json();
61
+ return { status: json.status, reason: json.reason };
62
+ }
63
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Handles requests from frontend, provides function calling and various LLM backends.
3
+ *
4
+ * <img
5
+ * referrerPolicy="no-referrer-when-downgrade"
6
+ * src="https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be"
7
+ * />
8
+ *
9
+ * <RequestExample>
10
+ * ```jsx CopilotRuntime Example
11
+ * import {
12
+ * CopilotRuntime,
13
+ * OpenAIAdapter
14
+ * } from "@copilotkit/runtime";
15
+ *
16
+ * export async function POST(req: Request) {
17
+ * const copilotKit = new CopilotRuntime();
18
+ * return copilotKit.response(req, new OpenAIAdapter());
19
+ * }
20
+ *
21
+ * ```
22
+ * </RequestExample>
23
+ *
24
+ * This class is the main entry point for the runtime. It handles requests from the frontend, provides function calling and various LLM backends.
25
+ *
26
+ * For example, to use OpenAI as a backend (check the [OpenAI Adapter](./OpenAIAdapter) docs for more info):
27
+ * ```typescript
28
+ * const copilotKit = new CopilotRuntime();
29
+ * return copilotKit.response(req, new OpenAIAdapter());
30
+ * ```
31
+ *
32
+ * Currently we support:
33
+ *
34
+ * - [OpenAI](./OpenAIAdapter)
35
+ * - [LangChain](./LangChainAdapter)
36
+ * - [OpenAI Assistant API](./OpenAIAssistantAdapter)
37
+ * - [Google Gemini](./GoogleGenerativeAIAdapter)
38
+ *
39
+ * ## Server Side Actions
40
+ *
41
+ * CopilotKit supports actions that can be executed on the server side. You can define server side actions by passing the `actions` parameter:
42
+ *
43
+ * ```typescript
44
+ * const copilotKit = new CopilotRuntime({
45
+ * actions: [
46
+ * {
47
+ * name: "sayHello",
48
+ * description: "Says hello to someone.",
49
+ * argumentAnnotations: [
50
+ * {
51
+ * name: "arg",
52
+ * type: "string",
53
+ * description: "The name of the person to say hello to.",
54
+ * required: true,
55
+ * },
56
+ * ],
57
+ * implementation: async (arg) => {
58
+ * console.log("Hello from the server", arg, "!");
59
+ * },
60
+ * },
61
+ * ],
62
+ * });
63
+ * ```
64
+ *
65
+ * Server side actions can also return a result which becomes part of the message history.
66
+ *
67
+ * This is useful because it gives the LLM context about what happened on the server side. In addition,
68
+ * it can be used to look up information from a vector or relational database and other sources.
69
+ *
70
+ * In addition to that, server side actions can also come from LangChain, including support for streaming responses.
71
+ *
72
+ * Returned results can be of the following type:
73
+ *
74
+ * - anything serializable to JSON
75
+ * - `string`
76
+ * - LangChain types:
77
+ * - `IterableReadableStream`
78
+ * - `BaseMessageChunk`
79
+ * - `AIMessage`
80
+ *
81
+ * ## LangServe
82
+ *
83
+ * The backend also supports LangServe, enabling you to connect to existing chains, for example python based chains.
84
+ * Use the `langserve` parameter to specify URLs for LangServe.
85
+ *
86
+ * ```typescript
87
+ * const copilotKit = new CopilotRuntime({
88
+ * langserve: [
89
+ * {
90
+ * chainUrl: "http://my-langserve.chain",
91
+ * name: "performResearch",
92
+ * description: "Performs research on a given topic.",
93
+ * },
94
+ * ],
95
+ * });
96
+ * ```
97
+ *
98
+ * When left out, arguments are automatically inferred from the schema provided by LangServe.
99
+ */
100
+
101
+ import { Action, actionParametersToJsonSchema, Parameter } from "@copilotkit/shared";
102
+ import { RemoteChain, CopilotServiceAdapter } from "../service-adapters";
103
+ import { CopilotCloud, RemoteCopilotCloud } from "./copilot-cloud";
104
+ import { MessageInput } from "../graphql/inputs/message.input";
105
+ import { ActionInput } from "../graphql/inputs/action.input";
106
+ import { RuntimeEventSource } from "../service-adapters/events";
107
+ import { convertGqlInputToMessages } from "../service-adapters/conversion";
108
+
109
+ interface CopilotRuntimeRequest {
110
+ serviceAdapter: CopilotServiceAdapter;
111
+ messages: MessageInput[];
112
+ actions: ActionInput[];
113
+ threadId?: string;
114
+ runId?: string;
115
+ publicApiKey?: string;
116
+ }
117
+
118
+ interface CopilotRuntimeResponse {
119
+ threadId?: string;
120
+ runId?: string;
121
+ eventSource: RuntimeEventSource;
122
+ }
123
+
124
+ export interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> {
125
+ /*
126
+ * A list of server side actions that can be executed.
127
+ */
128
+ actions?: Action<T>[];
129
+
130
+ /*
131
+ * An array of LangServer URLs.
132
+ */
133
+ langserve?: RemoteChain[];
134
+
135
+ debug?: boolean;
136
+ copilotCloud?: CopilotCloud;
137
+ }
138
+
139
+ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
140
+ public actions: Action<any>[] = [];
141
+ private langserve: Promise<Action<any>>[] = [];
142
+ private debug: boolean = false;
143
+ private copilotCloud: CopilotCloud;
144
+
145
+ constructor(params?: CopilotRuntimeConstructorParams<T>) {
146
+ this.actions = params?.actions || [];
147
+
148
+ for (const chain of params?.langserve || []) {
149
+ const remoteChain = new RemoteChain(chain);
150
+ this.langserve.push(remoteChain.toAction());
151
+ }
152
+ this.debug = params?.debug || false;
153
+ this.copilotCloud = params?.copilotCloud || new RemoteCopilotCloud();
154
+ }
155
+
156
+ addAction<const T extends Parameter[] | [] = []>(action: Action<T>): void {
157
+ this.removeAction(action.name);
158
+ this.actions.push(action);
159
+ }
160
+
161
+ removeAction(actionName: string): void {
162
+ this.actions = this.actions.filter((f) => f.name !== actionName);
163
+ }
164
+
165
+ async process({
166
+ serviceAdapter,
167
+ messages,
168
+ actions: clientSideActionsInput,
169
+ threadId,
170
+ runId,
171
+ publicApiKey,
172
+ }: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {
173
+ // TODO-PROTOCOL: cloud configuration
174
+ // const cloud: CopilotCloudConfig = forwardedProps.cloud;
175
+
176
+ const langserveFunctions: Action<any>[] = [];
177
+
178
+ for (const chainPromise of this.langserve) {
179
+ try {
180
+ const chain = await chainPromise;
181
+ langserveFunctions.push(chain);
182
+ } catch (error) {
183
+ console.error("Error loading langserve chain:", error);
184
+ }
185
+ }
186
+
187
+ const serverSideActionsInput: ActionInput[] = [...this.actions, ...langserveFunctions].map(
188
+ (action) => ({
189
+ name: action.name,
190
+ description: action.description,
191
+ jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),
192
+ }),
193
+ );
194
+
195
+ const actions = flattenToolCallsNoDuplicates([
196
+ ...serverSideActionsInput,
197
+ ...clientSideActionsInput,
198
+ ]);
199
+
200
+ try {
201
+ const eventSource = new RuntimeEventSource();
202
+ // TODO-PROTOCOL: type this and support function calls
203
+ const result = await serviceAdapter.process({
204
+ messages: convertGqlInputToMessages(messages),
205
+ actions,
206
+ threadId,
207
+ runId,
208
+ eventSource,
209
+ });
210
+
211
+ // TODO-PROTOCOL add guardrails
212
+ //
213
+ // if (publicApiKey !== undefined) {
214
+ // // wait for the cloud log chat to finish before streaming back the response
215
+ // try {
216
+ // const checkGuardrailsInputResult = await this.copilotCloud.checkGuardrailsInput({
217
+ // cloud,
218
+ // publicApiKey,
219
+ // messages: forwardedProps.messages || [],
220
+ // });
221
+
222
+ // if (checkGuardrailsInputResult.status === "denied") {
223
+ // // the chat was denied. instead of streaming back the response,
224
+ // // we let the client know...
225
+ // return {
226
+ // stream: new SingleChunkReadableStream(checkGuardrailsInputResult.reason),
227
+ // // headers: result.headers,
228
+ // };
229
+ // }
230
+ // } catch (error) {
231
+ // console.error("Error checking guardrails:", error);
232
+ // }
233
+ // }
234
+ return {
235
+ threadId: result.threadId,
236
+ runId: result.runId,
237
+ eventSource,
238
+ };
239
+ } catch (error) {
240
+ console.error("Error getting response:", error);
241
+ throw error;
242
+ }
243
+ }
244
+ }
245
+
246
+ export function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): ActionInput[] {
247
+ let allTools: ActionInput[] = [];
248
+ const allToolNames: string[] = [];
249
+ for (const tool of toolsByPriority) {
250
+ if (!allToolNames.includes(tool.name)) {
251
+ allTools.push(tool);
252
+ allToolNames.push(tool.name);
253
+ }
254
+ }
255
+ return allTools;
256
+ }
257
+
258
+ /**
259
+ * @deprecated use CopilotRuntime instead
260
+ */
261
+ export class CopilotBackend extends CopilotRuntime {}
@@ -0,0 +1,3 @@
1
+ export interface GuardrailsOptions {
2
+ baseUrl: string;
3
+ }
@@ -0,0 +1,7 @@
1
+ export * from "./copilot-runtime";
2
+ export * from "../service-adapters/openai/openai-adapter";
3
+ export * from "../service-adapters/langchain/langchain-adapter";
4
+ export * from "../service-adapters/google/google-genai-adapter";
5
+ export * from "../service-adapters/openai/openai-assistant-adapter";
6
+ export * from "./copilot-cloud";
7
+ export * from "./integrations";
@@ -0,0 +1,4 @@
1
+ export * from "./shared";
2
+ export * from "./nextjs/app-router";
3
+ export * from "./nextjs/pages-router";
4
+ export * from "./node-http";
@@ -0,0 +1,29 @@
1
+ import { createYoga } from "graphql-yoga";
2
+ import { getCommonConfig } from "../shared";
3
+ import { CopilotRuntime } from "../../copilot-runtime";
4
+ import { CopilotServiceAdapter } from "../../../service-adapters";
5
+
6
+ export function copilotRuntimeNextJSAppRouterEndpoint({
7
+ runtime,
8
+ endpoint,
9
+ serviceAdapter,
10
+ }: {
11
+ runtime: CopilotRuntime;
12
+ serviceAdapter: CopilotServiceAdapter;
13
+ endpoint: string;
14
+ }) {
15
+ const commonConfig = getCommonConfig({ runtime, serviceAdapter });
16
+
17
+ const yoga = createYoga({
18
+ ...commonConfig,
19
+ graphqlEndpoint: endpoint,
20
+ fetchAPI: { Response: globalThis.Response },
21
+ });
22
+
23
+ return {
24
+ handleRequest: yoga,
25
+ GET: yoga,
26
+ POST: yoga,
27
+ OPTIONS: yoga,
28
+ };
29
+ }
@@ -0,0 +1,36 @@
1
+ import { YogaServerInstance, createYoga } from "graphql-yoga";
2
+ import { GraphQLContext, getCommonConfig } from "../shared";
3
+ import { CopilotRuntime } from "../../copilot-runtime";
4
+ import { CopilotServiceAdapter } from "../../../service-adapters";
5
+
6
+ export const config = {
7
+ api: {
8
+ bodyParser: false,
9
+ },
10
+ };
11
+
12
+ export type CopilotRuntimeServerInstance<T> = YogaServerInstance<T, Partial<GraphQLContext>>;
13
+
14
+ // Theis import is needed to fix the type error
15
+ // Fix is currently in TypeScript 5.5 beta, waiting for stable version
16
+ // https://github.com/microsoft/TypeScript/issues/42873#issuecomment-2066874644
17
+ export type {} from "@whatwg-node/server";
18
+
19
+ export function copilotRuntimeNextJSPagesRouterEndpoint({
20
+ runtime,
21
+ endpoint,
22
+ serviceAdapter,
23
+ }: {
24
+ runtime: CopilotRuntime;
25
+ serviceAdapter: CopilotServiceAdapter;
26
+ endpoint: string;
27
+ }): CopilotRuntimeServerInstance<GraphQLContext> {
28
+ const commonConfig = getCommonConfig({ runtime, serviceAdapter });
29
+
30
+ const yoga = createYoga({
31
+ ...commonConfig,
32
+ graphqlEndpoint: endpoint,
33
+ });
34
+
35
+ return yoga;
36
+ }
@@ -0,0 +1,23 @@
1
+ import { createYoga } from "graphql-yoga";
2
+ import { getCommonConfig } from "../shared";
3
+ import { CopilotRuntime } from "../../copilot-runtime";
4
+ import { CopilotServiceAdapter } from "../../../service-adapters";
5
+
6
+ export function copilotRuntimeNodeHttpEndpoint({
7
+ runtime,
8
+ endpoint,
9
+ serviceAdapter,
10
+ }: {
11
+ runtime: CopilotRuntime;
12
+ serviceAdapter: CopilotServiceAdapter;
13
+ endpoint: string;
14
+ }) {
15
+ const commonConfig = getCommonConfig({ runtime, serviceAdapter });
16
+
17
+ const yoga = createYoga({
18
+ ...commonConfig,
19
+ graphqlEndpoint: endpoint,
20
+ });
21
+
22
+ return yoga;
23
+ }