-
Notifications
You must be signed in to change notification settings - Fork 139
/
template.ts
182 lines (158 loc) · 5.43 KB
/
template.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
/**
* Copyright 2024 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FrameworkError } from "@/errors.js";
import { ObjectLike, PlainObject } from "@/internals/types.js";
import * as R from "remeda";
import Mustache from "mustache";
import { Serializable } from "@/internals/serializable.js";
import { z, ZodType } from "zod";
import { createSchemaValidator, toJsonSchema } from "@/internals/helpers/schema.js";
import type { SchemaObject, ValidateFunction } from "ajv";
import { shallowCopy } from "@/serializer/utils.js";
import { pickBy } from "remeda";
import { getProp } from "@/internals/helpers/object.js";
type PostInfer<T> = T extends PlainObject
? {
[K in keyof T]: T[K] extends Date ? string : T[K];
}
: T;
type InferValue<T> = T extends ZodType<infer A> ? PostInfer<A> : never;
export type PromptTemplateRenderFn<K extends ZodType> = (this: InferValue<K>) => any;
export type PromptTemplateRenderInput<T extends ZodType, T2 extends z.input<T> = z.input<T>> = {
[K in Extract<keyof T2, string>]: T2[K] | PromptTemplateRenderFn<T> | undefined;
};
export interface PromptTemplateInput<T extends ZodType> {
template: string;
customTags?: [string, string];
escape?: boolean;
schema: SchemaObject;
defaults?: Partial<InferValue<T>>;
functions?: Record<string, PromptTemplateRenderFn<T>>;
}
type PromptTemplateConstructor<T extends ZodType, N> = N extends ZodType
? Omit<PromptTemplateInput<N>, "schema" | "functions" | "defaults"> & {
schema: N;
functions?: Record<string, PromptTemplateRenderFn<N | T>>;
defaults?: Partial<InferValue<N | T>>;
}
: Omit<PromptTemplateInput<T>, "schema"> & { schema: T | SchemaObject };
type Customizer<T extends ZodType, N> = (
config: Required<PromptTemplateInput<T>>,
) => PromptTemplateConstructor<T, N>;
export class PromptTemplateError<T extends ZodType> extends FrameworkError {
template: PromptTemplate<T>;
constructor(message: string, template: PromptTemplate<T>, context?: ObjectLike) {
super(message, [], {
context,
});
this.template = template;
}
}
export class ValidationPromptTemplateError<T extends ZodType> extends PromptTemplateError<T> {}
export class PromptTemplate<T extends ZodType> extends Serializable {
protected config: Required<PromptTemplateInput<T>>;
public static functions = {
trim: () => (text: string, render: (value: string) => string) => {
return render(text).replace(/(,\s*$)/g, "");
},
};
constructor(config: Omit<PromptTemplateInput<T>, "schema"> & { schema: T | SchemaObject }) {
super();
this.config = {
...config,
defaults: (config.defaults ?? {}) as Partial<InferValue<T>>,
schema: toJsonSchema(config.schema),
escape: Boolean(config.escape),
customTags: config.customTags ?? ["{{", "}}"],
functions: {
...PromptTemplate.functions,
...config.functions,
},
};
}
static {
this.register();
}
validateInput(input: unknown): asserts input is T {
const validator = createSchemaValidator(this.config.schema, {
coerceTypes: false,
}) as ValidateFunction<T>;
const success = validator(input);
if (!success) {
throw new ValidationPromptTemplateError(
`Template cannot be rendered because input does not adhere to the template schema.`,
this,
{
errors: validator.errors,
},
);
}
}
fork(customizer: Customizer<T, SchemaObject>): PromptTemplate<T>;
fork<R extends ZodType>(customizer: Customizer<T, R>): PromptTemplate<R>;
fork<R extends ZodType>(
customizer: Customizer<T, SchemaObject> | Customizer<T, R>,
): PromptTemplate<T | R> {
const config = shallowCopy(this.config);
const newConfig = customizer?.(config) ?? config;
return new PromptTemplate(newConfig);
}
render(input: PromptTemplateRenderInput<T>): string {
const updatedInput: typeof input = { ...input };
Object.assign(
updatedInput,
pickBy(this.config.defaults, (_, k) => getProp(updatedInput, [k]) === undefined),
);
this.validateInput(updatedInput);
const view: Record<string, any> = {
...this.config.functions,
...updatedInput,
};
const output = Mustache.render(
this.config.template,
view,
{},
{
tags: this.config.customTags,
...(!this.config.escape && {
escape: R.identity(),
}),
},
);
if (output.match(/\[object (.+)]/)) {
throw new ValidationPromptTemplateError(
"Rendered template contains incorrectly serialized value!",
this,
{
output,
},
);
}
return output;
}
loadSnapshot(data: ReturnType<typeof this.createSnapshot>) {
this.config = data.config;
}
createSnapshot() {
return {
config: this.config,
};
}
}
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace PromptTemplate {
export type infer<T> = PromptTemplate<ZodType<T>>;
}