-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.ts
192 lines (176 loc) Β· 5.14 KB
/
index.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
import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
import { z } from "zod";
import {
Example,
interpolateFString,
FewShotPromptTemplate,
} from "@langchain/core/prompts";
import { InputValues } from "@langchain/core/utils/types";
import { QueryTransformer, TraverseType } from "./parser.js";
import {
Comparator,
Comparators,
Operator,
Operators,
StructuredQuery,
} from "./ir.js";
import {
DEFAULT_EXAMPLES,
DEFAULT_PREFIX,
DEFAULT_SCHEMA,
DEFAULT_SUFFIX,
EXAMPLE_PROMPT,
} from "./prompt.js";
import { LLMChain } from "../llm_chain.js";
import { AsymmetricStructuredOutputParser } from "../../output_parsers/structured.js";
import { AttributeInfo } from "../../schema/query_constructor.js";
export { QueryTransformer, type TraverseType };
export {
DEFAULT_EXAMPLES,
DEFAULT_PREFIX,
DEFAULT_SCHEMA,
DEFAULT_SUFFIX,
EXAMPLE_PROMPT,
};
const queryInputSchema = /* #__PURE__ */ z.object({
query: /* #__PURE__ */ z
.string()
.describe("text string to compare to document contents"),
filter: /* #__PURE__ */ z
.string()
.optional()
.describe("logical condition statement for filtering documents"),
});
/**
* A class that extends AsymmetricStructuredOutputParser to parse
* structured query output.
*/
export class StructuredQueryOutputParser extends AsymmetricStructuredOutputParser<
typeof queryInputSchema,
StructuredQuery
> {
lc_namespace = ["langchain", "chains", "query_constructor"];
queryTransformer: QueryTransformer;
constructor(fields: {
allowedComparators: Comparator[];
allowedOperators: Operator[];
}) {
super({ ...fields, inputSchema: queryInputSchema });
const { allowedComparators, allowedOperators } = fields;
this.queryTransformer = new QueryTransformer(
allowedComparators,
allowedOperators
);
}
/**
* Processes the output of a structured query.
* @param query The query string.
* @param filter The filter condition.
* @returns A Promise that resolves to a StructuredQuery instance.
*/
async outputProcessor({
query,
filter,
}: z.infer<typeof queryInputSchema>): Promise<StructuredQuery> {
let myQuery = query;
if (myQuery.length === 0) {
myQuery = " ";
}
if (filter === "NO_FILTER" || filter === undefined) {
return new StructuredQuery(query);
} else {
const parsedFilter = await this.queryTransformer.parse(filter);
return new StructuredQuery(query, parsedFilter);
}
}
/**
* Creates a new StructuredQueryOutputParser instance from the provided
* components.
* @param allowedComparators An array of allowed Comparator instances.
* @param allowedOperators An array of allowed Operator instances.
* @returns A new StructuredQueryOutputParser instance.
*/
static fromComponents(
allowedComparators: Comparator[] = [],
allowedOperators: Operator[] = []
) {
return new StructuredQueryOutputParser({
allowedComparators,
allowedOperators,
});
}
}
export function formatAttributeInfo(info: AttributeInfo[]) {
const infoObj = info.reduce((acc, attr) => {
acc[attr.name] = {
type: attr.type,
description: attr.description,
};
return acc;
}, {} as { [name: string]: { type: string; description: string } });
return JSON.stringify(infoObj, null, 2)
.replaceAll("{", "{{")
.replaceAll("}", "}}");
}
const defaultExample = DEFAULT_EXAMPLES.map((EXAMPLE) => EXAMPLE as Example);
function _getPrompt(
documentContents: string,
attributeInfo: AttributeInfo[],
allowedComparators?: Comparator[],
allowedOperators?: Operator[],
examples: InputValues[] = defaultExample
) {
const myAllowedComparators: Comparator[] =
allowedComparators ?? Object.values(Comparators);
const myAllowedOperators: Operator[] =
allowedOperators ?? Object.values(Operators);
const attributeJSON = formatAttributeInfo(attributeInfo);
const schema = interpolateFString(DEFAULT_SCHEMA, {
allowed_comparators: myAllowedComparators.join(" | "),
allowed_operators: myAllowedOperators.join(" | "),
});
const prefix = interpolateFString(DEFAULT_PREFIX, {
schema,
});
const suffix = interpolateFString(DEFAULT_SUFFIX, {
i: examples.length + 1,
content: documentContents,
attributes: attributeJSON,
});
const outputParser = StructuredQueryOutputParser.fromComponents(
allowedComparators,
allowedOperators
);
return new FewShotPromptTemplate({
examples,
examplePrompt: EXAMPLE_PROMPT,
inputVariables: ["query"],
suffix,
prefix,
outputParser,
});
}
/**
* A type that represents options for the query constructor chain.
*/
export type QueryConstructorChainOptions = {
llm: BaseLanguageModelInterface;
documentContents: string;
attributeInfo: AttributeInfo[];
examples?: InputValues[];
allowedComparators?: Comparator[];
allowedOperators?: Operator[];
};
export function loadQueryConstructorChain(opts: QueryConstructorChainOptions) {
const prompt = _getPrompt(
opts.documentContents,
opts.attributeInfo,
opts.allowedComparators,
opts.allowedOperators,
opts.examples
);
return new LLMChain({
llm: opts.llm,
prompt,
});
}