-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
expression.ts
85 lines (74 loc) · 2.63 KB
/
expression.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
import { BaseOutputParser } from "@langchain/core/output_parsers";
import { MasterHandler } from "./expression_type_handlers/factory.js";
import { ParsedType } from "./expression_type_handlers/types.js";
import { ASTParser } from "./expression_type_handlers/base.js";
/**
* We need to be able to handle the following cases:
* ExpressionStatement
* CallExpression
* Identifier | MemberExpression
* ExpressionLiterals: [
* CallExpression
* StringLiteral
* NumericLiteral
* ArrayLiteralExpression
* ExpressionLiterals
* ObjectLiteralExpression
* PropertyAssignment
* Identifier
* ExpressionLiterals
* ]
*/
export class ExpressionParser extends BaseOutputParser<ParsedType> {
lc_namespace = ["langchain", "output_parsers", "expression"];
parser: ParseFunction;
/**
* We should separate loading the parser into its own function
* because loading the grammar takes some time. If there are
* multiple concurrent parse calls, it's faster to just wait
* for building the parser once and then use it for all
* subsequent calls. See expression.test.ts for an example.
*/
async ensureParser() {
if (!this.parser) {
this.parser = await ASTParser.importASTParser();
}
}
/**
* Parses the given text. It first ensures the parser is loaded, then
* tries to parse the text. If the parsing fails, it throws an error. If
* the parsing is successful, it returns the parsed expression.
* @param text The text to be parsed.
* @returns The parsed expression
*/
async parse(text: string) {
await this.ensureParser();
try {
const program = this.parser(text);
const node = program.body;
if (!ASTParser.isExpressionStatement(node)) {
throw new Error(
`Expected ExpressionStatement, got ${(node as ExpressionNode).type}`
);
}
const { expression: expressionStatement } = node;
if (!ASTParser.isCallExpression(expressionStatement)) {
throw new Error("Expected CallExpression");
}
const masterHandler = MasterHandler.createMasterHandler();
return await masterHandler.handle(expressionStatement);
} catch (err) {
throw new Error(`Error parsing ${err}: ${text}`);
}
}
/**
* This method is currently empty, but it could be used to provide
* instructions on the format of the input text.
* @returns string
*/
getFormatInstructions(): string {
return "";
}
}
export * from "./expression_type_handlers/types.js";
export { MasterHandler } from "./expression_type_handlers/factory.js";