Skip to content

Commit 574615a

Browse files
committed
Integrate OpenAI inside ToolChain conditional
The OpenAI conditionality was moved inside the ToolChain declaration to streamline and simplify the code. This simple restructuring ensures that the OpenAI API key and instance of OpenAI are only created if there are tool messages present.
1 parent 48804de commit 574615a

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

src/agents/GraphRunner.ts

+17-17
Original file line numberDiff line numberDiff line change
@@ -62,28 +62,28 @@ export class GraphRunner extends RunnableChain<GraphRunnerInput, GraphRunnerOutp
6262
// Signals calling a new agent,
6363
logger(`Calling agent: ${node.name}`);
6464

65-
const converted: ChatCompletionMessageParam[] = state.messages.map((message) => {
66-
const content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
67-
if (message instanceof AIMessage) {
68-
return {content, role: "assistant"};
69-
} else if (message instanceof HumanMessage) {
70-
return {content, role: "user"};
71-
} else if (message instanceof SystemMessage) {
72-
return {content, role: "system"};
73-
} else if (message instanceof ToolMessage) {
74-
return {content, role: "tool", tool_call_id: message.tool_call_id};
75-
} else {
76-
throw new Error("Unknown message type.");
77-
}
78-
});
79-
80-
if (node.instructions) converted.push({content: node.instructions, role: "user"});
81-
8265
let message: BaseMessage;
8366
if (tools.length > 0) {
8467
const openAiApiKey = process.env.OPENAI_API_KEY;
8568
const openai = new OpenAI({apiKey: openAiApiKey});
8669

70+
const converted: ChatCompletionMessageParam[] = state.messages.map((message) => {
71+
const content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
72+
if (message instanceof AIMessage) {
73+
return {content, role: "assistant"};
74+
} else if (message instanceof HumanMessage) {
75+
return {content, role: "user"};
76+
} else if (message instanceof SystemMessage) {
77+
return {content, role: "system"};
78+
} else if (message instanceof ToolMessage) {
79+
return {content, role: "tool", tool_call_id: message.tool_call_id};
80+
} else {
81+
throw new Error("Unknown message type.");
82+
}
83+
});
84+
85+
if (node.instructions) converted.push({content: node.instructions, role: "user"});
86+
8787
const runner = new ToolChain({
8888
openai: openai,
8989
model: GPT4_TEXT,

0 commit comments

Comments
 (0)