forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract.ts
More file actions
215 lines (177 loc) · 5.76 KB
/
Copy pathextract.ts
File metadata and controls
215 lines (177 loc) · 5.76 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
import {
Action,
COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
MappedParameterTypes,
Parameter,
actionParametersToJsonSchema,
} from "@copilotkit/shared";
import {
ActionExecutionMessage,
Message,
Role,
TextMessage,
convertGqlOutputToMessages,
CopilotRequestType,
ForwardedParametersInput,
} from "@copilotkit/runtime-client-gql";
import { CopilotContextParams, CopilotMessagesContextParams } from "../context";
import { defaultCopilotContextCategories } from "../components";
import { CopilotRuntimeClient } from "@copilotkit/runtime-client-gql";
import {
convertMessagesToGqlInput,
filterAgentStateMessages,
} from "@copilotkit/runtime-client-gql";
interface InitialState<T extends Parameter[] | [] = []> {
status: "initial";
args: Partial<MappedParameterTypes<T>>;
}
interface InProgressState<T extends Parameter[] | [] = []> {
status: "inProgress";
args: Partial<MappedParameterTypes<T>>;
}
interface CompleteState<T extends Parameter[] | [] = []> {
status: "complete";
args: MappedParameterTypes<T>;
}
type StreamHandlerArgs<T extends Parameter[] | [] = []> =
| InitialState<T>
| InProgressState<T>
| CompleteState<T>;
interface ExtractOptions<T extends Parameter[]> {
context: CopilotContextParams & CopilotMessagesContextParams;
instructions: string;
parameters: T;
include?: IncludeOptions;
data?: any;
abortSignal?: AbortSignal;
stream?: (args: StreamHandlerArgs<T>) => void;
requestType?: CopilotRequestType;
forwardedParameters?: ForwardedParametersInput;
}
interface IncludeOptions {
readable?: boolean;
messages?: boolean;
}
export async function extract<const T extends Parameter[]>({
context,
instructions,
parameters,
include,
data,
abortSignal,
stream,
requestType = CopilotRequestType.Task,
forwardedParameters,
}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {
const { messages } = context;
const action: Action<any> = {
name: "extract",
description: instructions,
parameters,
handler: (args: any) => {},
};
const includeReadable = include?.readable ?? false;
const includeMessages = include?.messages ?? false;
let contextString = "";
if (data) {
contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
}
if (includeReadable) {
contextString += context.getContextString([], defaultCopilotContextCategories);
}
const systemMessage: Message = new TextMessage({
content: makeSystemMessage(contextString, instructions),
role: Role.System,
});
const instructionsMessage: Message = new TextMessage({
content: makeInstructionsMessage(instructions),
role: Role.User,
});
const response = context.runtimeClient.asStream(
context.runtimeClient.generateCopilotResponse({
data: {
frontend: {
actions: [
{
name: action.name,
description: action.description || "",
jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),
},
],
url: window.location.href,
},
messages: convertMessagesToGqlInput(
includeMessages
? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]
: [systemMessage, instructionsMessage],
),
metadata: {
requestType: requestType,
},
forwardedParameters: {
...(forwardedParameters ?? {}),
toolChoice: "function",
toolChoiceFunctionName: action.name,
},
},
properties: context.copilotApiConfig.properties,
signal: abortSignal,
}),
);
const reader = response.getReader();
let isInitial = true;
let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
if (abortSignal?.aborted) {
throw new Error("Aborted");
}
actionExecutionMessage = convertGqlOutputToMessages(
value.generateCopilotResponse.messages,
).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;
if (!actionExecutionMessage) {
continue;
}
stream?.({
status: isInitial ? "initial" : "inProgress",
args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,
});
isInitial = false;
}
if (!actionExecutionMessage) {
throw new Error("extract() failed: No function call occurred");
}
stream?.({
status: "complete",
args: actionExecutionMessage.arguments as MappedParameterTypes<T>,
});
return actionExecutionMessage.arguments as MappedParameterTypes<T>;
}
// We need to put this in a user message since some LLMs need
// at least one user message to function
function makeInstructionsMessage(instructions: string): string {
return `
The user has given you the following task to complete:
\`\`\`
${instructions}
\`\`\`
Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
`;
}
function makeSystemMessage(contextString: string, instructions: string): string {
return `
Please act as an efficient, competent, conscientious, and industrious professional assistant.
Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
Always be polite and respectful, and prefer brevity over verbosity.
The user has provided you with the following context:
\`\`\`
${contextString}
\`\`\`
They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
Please assist them as best you can.
This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
`;
}