-
Notifications
You must be signed in to change notification settings - Fork 39
/
sig.ts
288 lines (245 loc) 路 7.85 KB
/
sig.ts
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import JSON5 from 'json5';
import { type FunctionJSONSchema } from '../text/functions.js';
import { parse, type ParsedField, type ParsedSignature } from './parser.js';
export interface Field {
name: string;
title?: string;
description?: string;
type?: {
name: 'string' | 'number' | 'boolean' | 'json'; // extend this as needed
isArray: boolean;
};
isOptional?: boolean;
}
export type IField = Omit<Field, 'title'> & { title: string };
export class Signature {
private sig: ParsedSignature;
private description?: string;
private inputFields: IField[];
private outputFields: IField[];
constructor(signature: Readonly<Signature | string>) {
if (typeof signature === 'string') {
this.sig = parse(signature);
} else if (signature instanceof Signature) {
this.sig = signature.getParsedSignature();
} else {
throw new Error('invalid signature argument');
}
this.description = this.sig.desc;
this.inputFields = this.sig.inputs.map((v) => this.parseParsedField(v));
this.outputFields = this.sig.outputs.map((v) => this.parseParsedField(v));
}
private parseParsedField = (field: Readonly<ParsedField>): IField => {
if (!field.name || field.name.length === 0) {
throw new Error('Field name is required.');
}
const title = this.toTitle(field.name);
return {
name: field.name,
title,
description: field.desc,
isOptional: field.isOptional,
type: field.type ?? { name: 'string', isArray: false }
};
};
private parseField = (field: Readonly<Field>): IField => {
if (!field.name || field.name.length === 0) {
throw new Error('Field name is required.');
}
const title =
!field.title || field.title.length === 0
? this.toTitle(field.name)
: field.title;
if (field.type && (!field.type.name || field.type.name.length === 0)) {
throw new Error('Field type name is required: ' + field.name);
}
return { ...field, title };
};
public setDescription = (desc: string) => (this.description = desc);
public addInputField = (field: Readonly<Field>) =>
this.inputFields.push(this.parseField(field));
public addOutputField = (field: Readonly<Field>) =>
this.outputFields.push(this.parseField(field));
public setInputFields = (fields: readonly Field[]) =>
(this.inputFields = fields.map((v) => this.parseField(v)));
public setOutputFields = (fields: readonly Field[]) =>
(this.outputFields = fields.map((v) => this.parseField(v)));
public getInputFields = () => this.inputFields;
public getOutputFields = () => this.outputFields;
public getDescription = () => this.description;
private toTitle = (name: string) => {
let result = name.replaceAll('_', ' ');
result = result.replace(/([A-Z])/g, ' $1').trim();
return result.charAt(0).toUpperCase() + result.slice(1);
};
public clone = () => {
const sig = new Signature(this);
sig.description = this.description;
sig.inputFields = this.inputFields.map((v) => ({ ...v }));
sig.outputFields = this.outputFields.map((v) => ({ ...v }));
return sig;
};
public getParsedSignature = () => this.sig;
public toJSONSchema = (): FunctionJSONSchema => {
const properties: Record<string, unknown> = {};
const required: Array<string> = [];
for (const f of this.inputFields) {
const type = f.type ? f.type.name : 'string';
if (f.type?.isArray) {
properties[f.name] = {
title: f.title,
description: f.description,
type: 'array' as const,
items: {
type: type,
title: f.title,
description: f.description
}
};
} else {
properties[f.name] = {
title: f.title,
description: f.description,
type: type
};
}
if (!f.isOptional) {
required.push(f.name);
}
}
const schema = {
type: 'object',
properties: properties,
required: required
};
return schema as FunctionJSONSchema;
};
}
export const extractValues = (sig: Readonly<Signature>, result: string) => {
const fields = sig.getOutputFields();
const values: Record<string, unknown> = {};
let s = -1;
let e = -1;
fields.forEach((field, i) => {
const prefix = field.title + ':';
const nextPrefix = fields.at(i + 1)
? fields[i + 1]!.title + ':'
: undefined;
const ps = result.indexOf(prefix, s + 1);
if (ps === -1) {
if (fields.length > 1) {
throw new Error(`Field not found: ${prefix}`);
} else {
s = 0;
e = result.length;
}
} else {
s = ps + prefix.length + 1;
e = nextPrefix ? result.indexOf(nextPrefix, s) : result.length;
}
const val = result.substring(s, e).trim().replace(/---+$/, '').trim();
if (field.type) {
values[field.name] = validateAndParseJson(field, val);
return;
}
values[field.name] = val;
});
return values;
};
function validateAndParseJson(
field: Readonly<NonNullable<Field>>,
jsonString: string
): unknown {
const typeObj = field.type;
if (!typeObj) {
return jsonString;
}
const text = extractBlock(jsonString);
// Attempt to parse the JSON string based on the expected type, if not a string
let value: unknown;
if (typeObj.name !== 'string' || typeObj.isArray) {
try {
value = JSON5.parse(text);
} catch (e) {
const exp = typeObj.isArray ? `array of ${typeObj.name}` : typeObj.name;
const message = `Error '${(e as Error).message}', expected '${exp}' got '${text}'`;
throw new ValidationError({ message, field, value: text });
}
} else {
// If the expected type is a string and not an array, use the jsonString directly
value = text;
}
// Now, validate the parsed value or direct string
const validateSingleValue = (expectedType: string, val: unknown): boolean => {
switch (expectedType) {
case 'string':
return typeof val === 'string';
case 'number':
return typeof val === 'number';
case 'boolean':
return typeof val === 'boolean';
case 'json':
return typeof val === 'object' || Array.isArray(val);
default:
return false; // Unknown type
}
};
if (typeObj.isArray) {
if (!Array.isArray(value)) {
const message = `Expected an array, but got '${typeof value}'.`;
throw new ValidationError({ message, field, value: jsonString });
}
for (const item of value) {
if (!validateSingleValue(typeObj.name, item)) {
const message = `Expected all items in array to be of type '${
typeObj.name
}', but found an item of type '${typeof item}'.`;
throw new ValidationError({ message, field, value: jsonString });
}
}
} else {
if (!validateSingleValue(typeObj.name, value)) {
const message = `Expected value of type '${
typeObj.name
}', but got '${typeof value}'.`;
throw new ValidationError({ message, field, value: jsonString });
}
}
// If validation passes, return null to indicate no error
return value;
}
export class ValidationError extends Error {
private field: Field;
private value: string;
constructor({
message,
field,
value
}: Readonly<{
message: string;
field: Field;
value: string;
}>) {
super(message);
this.field = field;
this.value = value;
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
public getField = () => this.field;
public getValue = () => this.value;
}
export const extractBlock = (input: string): string => {
const jsonBlockPattern = /```([A-Za-z]+)?\s*([\s\S]*?)\s*```/g;
const match = jsonBlockPattern.exec(input);
if (!match) {
return input;
}
if (match.length === 3) {
return match[2] as string;
}
if (match.length === 2) {
return match[1] as string;
}
return input;
};