-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
router.ts
58 lines (53 loc) · 1.82 KB
/
router.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
import { z } from "zod";
import { OutputParserException } from "@langchain/core/output_parsers";
import { JsonMarkdownStructuredOutputParser } from "./structured.js";
/**
* Defines the input parameters for the RouterOutputParser class. It can
* include a default destination and an interpolation depth.
*/
export type RouterOutputParserInput = {
defaultDestination?: string;
interpolationDepth?: number;
};
/**
* A type of output parser that extends the
* JsonMarkdownStructuredOutputParser. It is used to parse the output of a
* router in LangChain. The class takes a schema and an optional
* RouterOutputParserInput object as parameters.
*/
export class RouterOutputParser<
Y extends z.ZodTypeAny
> extends JsonMarkdownStructuredOutputParser<Y> {
defaultDestination = "DEFAULT";
constructor(schema: Y, options?: RouterOutputParserInput) {
super(schema);
this.defaultDestination =
options?.defaultDestination ?? this.defaultDestination;
}
/**
* Overrides the parse method from JsonMarkdownStructuredOutputParser.
* This method takes a string as input, attempts to parse it, and returns
* the parsed text. If the destination of the parsed text matches the
* defaultDestination, the destination is set to null. If the parsing
* fails, an OutputParserException is thrown.
* @param text The text to be parsed.
* @returns The parsed text as a Promise.
*/
async parse(text: string): Promise<z.infer<Y>> {
try {
const parsedText = await super.parse(text);
if (
parsedText.destination?.toLowerCase() ===
this.defaultDestination.toLowerCase()
) {
parsedText.destination = null;
}
return parsedText;
} catch (e) {
throw new OutputParserException(
`Failed to parse. Text: "${text}". Error: ${e}`,
text
);
}
}
}