-
Notifications
You must be signed in to change notification settings - Fork 2k
/
string.ts
96 lines (87 loc) 路 2.57 KB
/
string.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
import { BaseTransformOutputParser } from "./transform.js";
import {
MessageContentComplex,
MessageContentImageUrl,
MessageContentText,
} from "../messages/index.js";
/**
* OutputParser that parses LLMResult into the top likely string.
* @example
* ```typescript
* const promptTemplate = PromptTemplate.fromTemplate(
* "Tell me a joke about {topic}",
* );
*
* const chain = RunnableSequence.from([
* promptTemplate,
* new ChatOpenAI({}),
* new StringOutputParser(),
* ]);
*
* const result = await chain.invoke({ topic: "bears" });
* console.log("What do you call a bear with no teeth? A gummy bear!");
* ```
*/
export class StringOutputParser extends BaseTransformOutputParser<string> {
static lc_name() {
return "StrOutputParser";
}
lc_namespace = ["langchain_core", "output_parsers", "string"];
lc_serializable = true;
/**
* Parses a string output from an LLM call. This method is meant to be
* implemented by subclasses to define how a string output from an LLM
* should be parsed.
* @param text The string output from an LLM call.
* @param callbacks Optional callbacks.
* @returns A promise of the parsed output.
*/
parse(text: string): Promise<string> {
return Promise.resolve(text);
}
getFormatInstructions(): string {
return "";
}
protected _textContentToString(content: MessageContentText): string {
return content.text;
}
protected _imageUrlContentToString(_content: MessageContentImageUrl): string {
throw new Error(
`Cannot coerce a multimodal "image_url" message part into a string.`
);
}
protected _messageContentComplexToString(
content: MessageContentComplex
): string {
switch (content.type) {
case "text":
if ("text" in content) {
// Type guard for MessageContentText
return this._textContentToString(content as MessageContentText);
}
break;
case "image_url":
if ("image_url" in content) {
// Type guard for MessageContentImageUrl
return this._imageUrlContentToString(
content as MessageContentImageUrl
);
}
break;
default:
throw new Error(
`Cannot coerce "${content.type}" message part into a string.`
);
}
throw new Error(`Invalid content type: ${content.type}`);
}
protected _baseMessageContentToString(
content: MessageContentComplex[]
): string {
return content.reduce(
(acc: string, item: MessageContentComplex) =>
acc + this._messageContentComplexToString(item),
""
);
}
}