-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmessage-builder.ts
More file actions
65 lines (55 loc) · 1.5 KB
/
message-builder.ts
File metadata and controls
65 lines (55 loc) · 1.5 KB
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
import { AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
import { AIToolCall } from '../interfaces/ai-provider.interface.js';
export class MessageBuilder {
private messages: BaseMessage[] = [];
public system(content: string): MessageBuilder {
this.messages.push(new SystemMessage(content));
return this;
}
public human(content: string): MessageBuilder {
this.messages.push(new HumanMessage(content));
return this;
}
public ai(content: string, toolCalls?: AIToolCall[]): MessageBuilder {
const message = new AIMessage({
content,
tool_calls: toolCalls?.map((tc) => ({
id: tc.id,
name: tc.name,
args: tc.arguments,
})),
});
this.messages.push(message);
return this;
}
public toolResult(toolCallId: string, result: string): MessageBuilder {
this.messages.push(
new ToolMessage({
tool_call_id: toolCallId,
content: result,
}),
);
return this;
}
public toolResults(results: Array<{ toolCallId: string; result: string }>): MessageBuilder {
for (const result of results) {
this.toolResult(result.toolCallId, result.result);
}
return this;
}
public build(): BaseMessage[] {
return this.messages;
}
public clear(): MessageBuilder {
this.messages = [];
return this;
}
public get length(): number {
return this.messages.length;
}
public static fromMessages(messages: BaseMessage[]): MessageBuilder {
const builder = new MessageBuilder();
builder.messages = [...messages];
return builder;
}
}