-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
log_to_message.ts
35 lines (32 loc) · 1.02 KB
/
log_to_message.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
import type { AgentStep } from "@langchain/core/agents";
import {
type BaseMessage,
AIMessage,
HumanMessage,
} from "@langchain/core/messages";
import { renderTemplate } from "@langchain/core/prompts";
export function formatLogToMessage(
intermediateSteps: AgentStep[],
templateToolResponse = "{observation}"
): BaseMessage[] {
// Get all input variables, if there is more than one, throw an error.
const matches = [...templateToolResponse.matchAll(/{([^}]*)}/g)];
const stringsInsideBrackets = matches.map((match) => match[1]);
if (stringsInsideBrackets.length > 1) {
throw new Error(
`templateToolResponse must contain one input variable: ${templateToolResponse}`
);
}
const thoughts: BaseMessage[] = [];
for (const step of intermediateSteps) {
thoughts.push(new AIMessage(step.action.log));
thoughts.push(
new HumanMessage(
renderTemplate(templateToolResponse, "f-string", {
[stringsInsideBrackets[0]]: step.observation,
})
)
);
}
return thoughts;
}