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
76 lines (66 loc) · 1.97 KB
/
Copy pathCopilotRuntimeClient.ts
File metadata and controls
76 lines (66 loc) · 1.97 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
import { Client, cacheExchange, fetchExchange } from "@urql/core";
import * as packageJson from "../../package.json";
import {
GenerateCopilotResponseMutation,
GenerateCopilotResponseMutationVariables,
} from "../graphql/@generated/graphql";
import { generateCopilotResponseMutation } from "../graphql/definitions/mutations";
import { OperationResultSource, OperationResult } from "urql";
interface CopilotRuntimeClientOptions {
url: string;
publicApiKey?: string;
headers?: Record<string, string>;
}
export class CopilotRuntimeClient {
client: Client;
constructor(options: CopilotRuntimeClientOptions) {
const headers: Record<string, string> = {};
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,
},
},
});
}
generateCopilotResponse({
data,
properties,
signal,
}: {
data: GenerateCopilotResponseMutationVariables["data"];
properties?: GenerateCopilotResponseMutationVariables["properties"];
signal?: AbortSignal;
}) {
const result = this.client.mutation<
GenerateCopilotResponseMutation,
GenerateCopilotResponseMutationVariables
>(
generateCopilotResponseMutation,
{ data, properties },
{ fetch: (url, opts) => fetch(url, { ...opts, signal }) },
);
return result;
}
static asStream<S, T>(source: OperationResultSource<OperationResult<S, { data: T }>>) {
return new ReadableStream<S>({
start(controller) {
source.subscribe(({ data, hasNext }) => {
controller.enqueue(data);
if (!hasNext) {
controller.close();
}
});
},
});
}
}