-
Notifications
You must be signed in to change notification settings - Fork 2k
/
json_output_functions_parsers.ts
213 lines (186 loc) Β· 5.92 KB
/
json_output_functions_parsers.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
import { JsonSchema7ObjectType } from "zod-to-json-schema";
import { Optional } from "../../types/type-utils.js";
import { Generation, ChatGeneration } from "../../outputs.js";
import { BaseLLMOutputParser } from "../base.js";
import { parsePartialJson } from "../json.js";
import {
BaseCumulativeTransformOutputParser,
BaseCumulativeTransformOutputParserInput,
} from "../transform.js";
import {
compare,
type Operation as JSONPatchOperation,
} from "../../utils/json_patch.js";
/**
* Represents optional parameters for a function in a JSON Schema.
*/
export type FunctionParameters = Optional<
JsonSchema7ObjectType,
"additionalProperties"
>;
/**
* Class for parsing the output of an LLM. Can be configured to return
* only the arguments of the function call in the output.
*/
export class OutputFunctionsParser extends BaseLLMOutputParser<string> {
static lc_name() {
return "OutputFunctionsParser";
}
lc_namespace = ["langchain", "output_parsers", "openai_functions"];
lc_serializable = true;
argsOnly = true;
constructor(config?: { argsOnly?: boolean }) {
super();
this.argsOnly = config?.argsOnly ?? this.argsOnly;
}
/**
* Parses the output and returns a string representation of the function
* call or its arguments.
* @param generations The output of the LLM to parse.
* @returns A string representation of the function call or its arguments.
*/
async parseResult(
generations: Generation[] | ChatGeneration[]
): Promise<string> {
if ("message" in generations[0]) {
const gen = generations[0] as ChatGeneration;
const functionCall = gen.message.additional_kwargs.function_call;
if (!functionCall) {
throw new Error(
`No function_call in message ${JSON.stringify(generations)}`
);
}
if (!functionCall.arguments) {
throw new Error(
`No arguments in function_call ${JSON.stringify(generations)}`
);
}
if (this.argsOnly) {
return functionCall.arguments;
}
return JSON.stringify(functionCall);
} else {
throw new Error(
`No message in generations ${JSON.stringify(generations)}`
);
}
}
}
/**
* Class for parsing the output of an LLM into a JSON object. Uses an
* instance of `OutputFunctionsParser` to parse the output.
*/
export class JsonOutputFunctionsParser<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Output extends Record<string, any> = Record<string, any>
> extends BaseCumulativeTransformOutputParser<Output> {
static lc_name() {
return "JsonOutputFunctionsParser";
}
lc_namespace = ["langchain", "output_parsers", "openai_functions"];
lc_serializable = true;
outputParser: OutputFunctionsParser;
argsOnly = true;
constructor(
config?: { argsOnly?: boolean } & BaseCumulativeTransformOutputParserInput
) {
super(config);
this.argsOnly = config?.argsOnly ?? this.argsOnly;
this.outputParser = new OutputFunctionsParser(config);
}
protected _diff(
prev: unknown | undefined,
next: unknown
): JSONPatchOperation[] | undefined {
if (!next) {
return undefined;
}
const ops = compare(prev ?? {}, next);
return ops;
}
async parsePartialResult(
generations: ChatGeneration[]
): Promise<Output | undefined> {
const generation = generations[0];
if (!generation.message) {
return undefined;
}
const { message } = generation;
const functionCall = message.additional_kwargs.function_call;
if (!functionCall) {
return undefined;
}
if (this.argsOnly) {
return parsePartialJson(functionCall.arguments);
}
return {
...functionCall,
arguments: parsePartialJson(functionCall.arguments),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as Record<string, any> as Output;
}
/**
* Parses the output and returns a JSON object. If `argsOnly` is true,
* only the arguments of the function call are returned.
* @param generations The output of the LLM to parse.
* @returns A JSON object representation of the function call or its arguments.
*/
async parseResult(
generations: Generation[] | ChatGeneration[]
): Promise<Output> {
const result = await this.outputParser.parseResult(generations);
if (!result) {
throw new Error(
`No result from "OutputFunctionsParser" ${JSON.stringify(generations)}`
);
}
return this.parse(result);
}
async parse(text: string): Promise<Output> {
const parsedResult = JSON.parse(text);
if (this.argsOnly) {
return parsedResult;
}
parsedResult.arguments = JSON.parse(parsedResult.arguments);
return parsedResult;
}
getFormatInstructions(): string {
return "";
}
}
/**
* Class for parsing the output of an LLM into a JSON object and returning
* a specific attribute. Uses an instance of `JsonOutputFunctionsParser`
* to parse the output.
*/
export class JsonKeyOutputFunctionsParser<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
T extends Record<string, any> = Record<string, any>
> extends BaseLLMOutputParser<T> {
static lc_name() {
return "JsonKeyOutputFunctionsParser";
}
lc_namespace = ["langchain", "output_parsers", "openai_functions"];
lc_serializable = true;
outputParser = new JsonOutputFunctionsParser();
attrName: string;
get lc_aliases() {
return {
attrName: "key_name",
};
}
constructor(fields: { attrName: string }) {
super(fields);
this.attrName = fields.attrName;
}
/**
* Parses the output and returns a specific attribute of the parsed JSON
* object.
* @param generations The output of the LLM to parse.
* @returns The value of a specific attribute of the parsed JSON object.
*/
async parseResult(generations: Generation[] | ChatGeneration[]): Promise<T> {
const result = await this.outputParser.parseResult(generations);
return result[this.attrName as keyof typeof result] as T;
}
}