-
Notifications
You must be signed in to change notification settings - Fork 2k
/
openai_functions.ts
54 lines (52 loc) · 1.66 KB
/
openai_functions.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
import {
AIMessage,
type BaseMessage,
HumanMessage,
FunctionMessage,
} from "@langchain/core/messages";
import type { AgentStep } from "@langchain/core/agents";
import { renderTemplate } from "@langchain/core/prompts";
import { TEMPLATE_TOOL_RESPONSE } from "../chat_convo/prompt.js";
/**
* Format a list of AgentSteps into a list of BaseMessage instances for
* agents that use OpenAI's API. Helpful for passing in previous agent
* step context into new iterations.
*
* @deprecated Use formatToOpenAIFunctionMessages instead.
* @param steps A list of AgentSteps to format.
* @returns A list of BaseMessages.
*/
export function formatForOpenAIFunctions(steps: AgentStep[]): BaseMessage[] {
const thoughts: BaseMessage[] = [];
for (const step of steps) {
thoughts.push(new AIMessage(step.action.log));
thoughts.push(
new HumanMessage(
renderTemplate(TEMPLATE_TOOL_RESPONSE, "f-string", {
observation: step.observation,
})
)
);
}
return thoughts;
}
/**
* Format a list of AgentSteps into a list of BaseMessage instances for
* agents that use OpenAI's API. Helpful for passing in previous agent
* step context into new iterations.
*
* @param steps A list of AgentSteps to format.
* @returns A list of BaseMessages.
*/
export function formatToOpenAIFunctionMessages(
steps: AgentStep[]
): BaseMessage[] {
return steps.flatMap(({ action, observation }) => {
if ("messageLog" in action && action.messageLog !== undefined) {
const log = action.messageLog as BaseMessage[];
return log.concat(new FunctionMessage(observation, action.tool));
} else {
return [new AIMessage(action.log)];
}
});
}