forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopilotRuntimeClient.ts
More file actions
231 lines (207 loc) · 6.85 KB
/
Copy pathCopilotRuntimeClient.ts
File metadata and controls
231 lines (207 loc) · 6.85 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
import { Client, cacheExchange, fetchExchange } from "@urql/core";
import * as packageJson from "../../package.json";
import {
AvailableAgentsQuery,
GenerateCopilotResponseMutation,
GenerateCopilotResponseMutationVariables,
LoadAgentStateQuery,
} from "../graphql/@generated/graphql";
import { generateCopilotResponseMutation } from "../graphql/definitions/mutations";
import {
getAvailableAgentsQuery,
loadAgentStateQuery,
} from "../graphql/definitions/queries";
import { OperationResultSource, OperationResult } from "urql";
import {
ResolvedCopilotKitError,
CopilotKitLowLevelError,
CopilotKitError,
CopilotKitVersionMismatchError,
getPossibleVersionMismatch,
} from "@copilotkit/shared";
const createFetchFn =
(signal?: AbortSignal, handleGQLWarning?: (warning: string) => void) =>
async (...args: Parameters<typeof fetch>) => {
// @ts-expect-error -- since this is our own header, TS will not recognize
const publicApiKey = args[1]?.headers?.["x-copilotcloud-public-api-key"];
try {
const result = await fetch(args[0], { ...args[1], signal });
// No mismatch checking if cloud is being used
const mismatch = publicApiKey
? null
: await getPossibleVersionMismatch({
runtimeVersion: result.headers.get("X-CopilotKit-Runtime-Version")!,
runtimeClientGqlVersion: packageJson.version,
});
if (result.status !== 200) {
if (result.status >= 400 && result.status <= 500) {
if (mismatch) {
throw new CopilotKitVersionMismatchError(mismatch);
}
throw new ResolvedCopilotKitError({ status: result.status });
}
}
if (mismatch && handleGQLWarning) {
handleGQLWarning(mismatch.message);
}
return result;
} catch (error) {
// Let abort error pass through. It will be suppressed later
if (
(error as Error).message.includes("BodyStreamBuffer was aborted") ||
(error as Error).message.includes("signal is aborted without reason")
) {
throw error;
}
if (error instanceof CopilotKitError) {
throw error;
}
throw new CopilotKitLowLevelError({
error: error as Error,
url: args[0] as string,
});
}
};
export interface CopilotRuntimeClientOptions {
url: string;
publicApiKey?: string;
headers?: Record<string, string>;
credentials?: RequestCredentials;
handleGQLErrors?: (error: Error) => void;
handleGQLWarning?: (warning: string) => void;
}
export class CopilotRuntimeClient {
client: Client;
public handleGQLErrors?: (error: Error) => void;
public handleGQLWarning?: (warning: string) => void;
constructor(options: CopilotRuntimeClientOptions) {
const headers: Record<string, string> = {};
this.handleGQLErrors = options.handleGQLErrors;
this.handleGQLWarning = options.handleGQLWarning;
if (options.headers) {
Object.assign(headers, options.headers);
}
if (options.publicApiKey) {
headers["x-copilotcloud-public-api-key"] = options.publicApiKey;
}
this.client = new Client({
url: options.url,
exchanges: [cacheExchange, fetchExchange],
fetchOptions: {
headers: {
...headers,
"X-CopilotKit-Runtime-Client-GQL-Version": packageJson.version,
},
...(options.credentials ? { credentials: options.credentials } : {}),
},
});
}
generateCopilotResponse({
data,
properties,
signal,
}: {
data: GenerateCopilotResponseMutationVariables["data"];
properties?: GenerateCopilotResponseMutationVariables["properties"];
signal?: AbortSignal;
}) {
const fetchFn = createFetchFn(signal, this.handleGQLWarning);
const result = this.client.mutation<
GenerateCopilotResponseMutation,
GenerateCopilotResponseMutationVariables
>(
generateCopilotResponseMutation,
{ data, properties },
{ fetch: fetchFn },
);
return result;
}
public asStream<S, T>(
source: OperationResultSource<OperationResult<S, { data: T }>>,
) {
const handleGQLErrors = this.handleGQLErrors;
return new ReadableStream<S>({
start(controller) {
source.subscribe(({ data, hasNext, error }) => {
if (error) {
if (
error.message.includes("BodyStreamBuffer was aborted") ||
error.message.includes("signal is aborted without reason")
) {
// close the stream if there is no next item
if (!hasNext) controller.close();
//suppress this specific error
console.warn("Abort error suppressed");
return;
}
// Handle structured errors specially - check if it's a CopilotKitError with visibility
if ((error as any).extensions?.visibility) {
// Create a synthetic GraphQL error with the structured error info
const syntheticError = {
...error,
graphQLErrors: [
{
message: error.message,
extensions: (error as any).extensions,
},
],
};
if (handleGQLErrors) {
handleGQLErrors(syntheticError);
}
return; // Don't close the stream for structured errors, let the error handler decide
}
controller.error(error);
if (handleGQLErrors) {
handleGQLErrors(error);
}
} else {
controller.enqueue(data);
if (!hasNext) {
controller.close();
}
}
});
},
});
}
availableAgents() {
const fetchFn = createFetchFn();
return this.client.query<AvailableAgentsQuery>(
getAvailableAgentsQuery,
{},
{ fetch: fetchFn },
);
}
loadAgentState(data: { threadId: string; agentName: string }) {
const fetchFn = createFetchFn();
const result = this.client.query<LoadAgentStateQuery>(
loadAgentStateQuery,
{ data },
{ fetch: fetchFn },
);
// Add error handling for GraphQL errors - similar to generateCopilotResponse
result
.toPromise()
.then(({ error }) => {
if (error && this.handleGQLErrors) {
this.handleGQLErrors(error);
}
})
.catch(() => {}); // Suppress promise rejection warnings
return result;
}
static removeGraphQLTypename(data: any) {
if (Array.isArray(data)) {
data.forEach((item) => CopilotRuntimeClient.removeGraphQLTypename(item));
} else if (typeof data === "object" && data !== null) {
delete data.__typename;
Object.keys(data).forEach((key) => {
if (typeof data[key] === "object" && data[key] !== null) {
CopilotRuntimeClient.removeGraphQLTypename(data[key]);
}
});
}
return data;
}
}