@fractal-solutions/qflow 1.0.28 → 1.0.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +504 -0
- package/README.md +172 -30
- package/dist/agent/agent.d.ts +13 -2
- package/dist/agent/agent.js +191 -70
- package/dist/agent/logger.d.ts +1 -0
- package/dist/agent/logger.js +2 -1
- package/dist/agent/tools.d.ts +3276 -129
- package/dist/agent/tools.js +558 -22
- package/dist/nodes/browser_control.d.ts +4 -0
- package/dist/nodes/browser_control.js +73 -0
- package/dist/nodes/data_validation.d.ts +9 -0
- package/dist/nodes/data_validation.js +48 -0
- package/dist/nodes/display_image.d.ts +4 -0
- package/dist/nodes/display_image.js +46 -0
- package/dist/nodes/gis.d.ts +37 -0
- package/dist/nodes/gis.js +106 -0
- package/dist/nodes/git.d.ts +4 -0
- package/dist/nodes/git.js +55 -0
- package/dist/nodes/hardware_interaction.d.ts +8 -0
- package/dist/nodes/hardware_interaction.js +97 -0
- package/dist/nodes/image_gallery.d.ts +8 -0
- package/dist/nodes/image_gallery.js +99 -0
- package/dist/nodes/index.d.ts +14 -0
- package/dist/nodes/index.js +14 -0
- package/dist/nodes/interactive_input.d.ts +4 -0
- package/dist/nodes/interactive_input.js +70 -0
- package/dist/nodes/multimedia_processing.d.ts +10 -0
- package/dist/nodes/multimedia_processing.js +79 -0
- package/dist/nodes/pdf_processor.d.ts +4 -0
- package/dist/nodes/pdf_processor.js +75 -0
- package/dist/nodes/remote_execution.d.ts +4 -0
- package/dist/nodes/remote_execution.js +82 -0
- package/dist/nodes/scheduler.d.ts +20 -0
- package/dist/nodes/scheduler.js +97 -0
- package/dist/nodes/speech_synthesis.d.ts +45 -0
- package/dist/nodes/speech_synthesis.js +142 -0
- package/dist/nodes/spreadsheet.d.ts +10 -0
- package/dist/nodes/spreadsheet.js +241 -0
- package/dist/nodes/system_notification.d.ts +4 -0
- package/dist/nodes/system_notification.js +49 -0
- package/dist/nodes/webhook.d.ts +15 -0
- package/dist/nodes/webhook.js +110 -0
- package/dist/nodes/websockets.d.ts +4 -0
- package/dist/nodes/websockets.js +73 -0
- package/package.json +11 -2
package/dist/agent/agent.js
CHANGED
|
@@ -4,7 +4,7 @@ import { getToolDefinitions } from './tools.js';
|
|
|
4
4
|
import { SummarizeNode } from '../nodes/summarize.js';
|
|
5
5
|
import { logger } from './logger.js';
|
|
6
6
|
export class AgentNode extends AsyncNode {
|
|
7
|
-
constructor(llmNode, availableTools, summarizeLLM, flowRegistry = {}, requireFinishConfirmation = true) {
|
|
7
|
+
constructor(llmNode, availableTools, summarizeLLM, flowRegistry = {}, requireFinishConfirmation = true, maxConversationHistoryTokens = 100000) {
|
|
8
8
|
super();
|
|
9
9
|
if (!llmNode) {
|
|
10
10
|
throw new Error("AgentNode requires an LLMNode instance for reasoning.");
|
|
@@ -16,6 +16,7 @@ export class AgentNode extends AsyncNode {
|
|
|
16
16
|
this.conversationHistory = [];
|
|
17
17
|
this.maxSteps = 20;
|
|
18
18
|
this.requireFinishConfirmation = requireFinishConfirmation;
|
|
19
|
+
this.maxConversationHistoryTokens = maxConversationHistoryTokens;
|
|
19
20
|
}
|
|
20
21
|
async execAsync() {
|
|
21
22
|
const { goal } = this.params;
|
|
@@ -24,7 +25,8 @@ export class AgentNode extends AsyncNode {
|
|
|
24
25
|
}
|
|
25
26
|
this.conversationHistory = [
|
|
26
27
|
{ role: "system", content: this.getSystemPrompt() },
|
|
27
|
-
{ role: "user", content: `Goal: ${goal}` }
|
|
28
|
+
{ role: "user", content: `Goal: ${goal}` },
|
|
29
|
+
{ role: "system", content: "Begin by outlining a plan to achieve the goal. Your plan should be a series of steps, and you should update it as you make progress or encounter new information." }
|
|
28
30
|
];
|
|
29
31
|
let step = 0;
|
|
30
32
|
let finalOutput = null;
|
|
@@ -40,21 +42,37 @@ export class AgentNode extends AsyncNode {
|
|
|
40
42
|
this.conversationHistory.push({ role: "user", content: `Error: Failed to get LLM response: ${e.message}` });
|
|
41
43
|
continue;
|
|
42
44
|
}
|
|
43
|
-
let thought,
|
|
45
|
+
let thought, toolCalls, parallel;
|
|
44
46
|
try {
|
|
45
47
|
const parsedResponse = this.parseLLMResponse(llmResponse);
|
|
46
48
|
thought = parsedResponse.thought;
|
|
47
|
-
|
|
49
|
+
toolCalls = parsedResponse.toolCalls;
|
|
50
|
+
parallel = parsedResponse.parallel;
|
|
48
51
|
logger.thought(thought);
|
|
49
52
|
}
|
|
50
53
|
catch (e) {
|
|
51
54
|
logger.error(`Error parsing LLM response: ${e.message}`);
|
|
52
|
-
this.conversationHistory.push({ role: "user", content: `Error: Your response was not valid JSON or did not follow the expected format. Please respond with a 'thought' and '
|
|
55
|
+
this.conversationHistory.push({ role: "user", content: `Error: Your response was not valid JSON or did not follow the expected format. Please respond with a 'thought' and 'tool_calls' array. Error: ${e.message}. Your last response was: ${llmResponse}` });
|
|
53
56
|
continue;
|
|
54
57
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
+
// Validate tool parameters for all tool calls
|
|
59
|
+
const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
|
|
60
|
+
if (validationErrors.length > 0) {
|
|
61
|
+
const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
|
|
62
|
+
logger.error(errorMessage);
|
|
63
|
+
this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool_calls: toolCalls, parallel }) });
|
|
67
|
+
// If no tool calls, continue the loop to allow the LLM to re-evaluate
|
|
68
|
+
if (toolCalls.length === 0) {
|
|
69
|
+
this.conversationHistory.push({ role: "system", content: "No tools were called. Reflect on your plan and provide the next step." });
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
// Handle finish tool
|
|
73
|
+
const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
|
|
74
|
+
if (finishToolCall) {
|
|
75
|
+
finalOutput = finishToolCall.parameters.output;
|
|
58
76
|
if (this.requireFinishConfirmation) {
|
|
59
77
|
const confirmNode = new UserInputNode();
|
|
60
78
|
confirmNode.setParams({
|
|
@@ -63,56 +81,79 @@ export class AgentNode extends AsyncNode {
|
|
|
63
81
|
const confirmFlow = new AsyncFlow(confirmNode);
|
|
64
82
|
const confirmation = await confirmFlow.runAsync({});
|
|
65
83
|
if (confirmation.toLowerCase() !== 'yes') {
|
|
66
|
-
logger.info("Agent finish denied by user.
|
|
67
|
-
|
|
84
|
+
logger.info("Agent finish denied by user. User input will be the next prompt.");
|
|
85
|
+
// Treat the user's new input as a new instruction/goal
|
|
86
|
+
this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
|
|
87
|
+
// Optionally, you might want to clear some of the previous conversation history
|
|
88
|
+
// to give more weight to the new instruction, but be careful not to lose context.
|
|
89
|
+
// For now, we'll just add the new instruction.
|
|
68
90
|
continue; // Continue the loop
|
|
69
91
|
}
|
|
70
92
|
}
|
|
71
93
|
logger.final(finalOutput);
|
|
72
94
|
break;
|
|
73
95
|
}
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
this.conversationHistory.push({ role: "user", content: errorMessage });
|
|
79
|
-
continue;
|
|
80
|
-
}
|
|
81
|
-
let toolOutput;
|
|
82
|
-
try {
|
|
83
|
-
logger.toolCall(toolCall.tool, toolCall.parameters);
|
|
84
|
-
// If the tool is a sub-flow or iterator, look up the flow in the registry
|
|
85
|
-
if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator') {
|
|
86
|
-
const flowName = toolCall.parameters.flow;
|
|
87
|
-
if (!this.flowRegistry[flowName]) {
|
|
88
|
-
throw new Error(`Flow '${flowName}' not found in registry.`);
|
|
89
|
-
}
|
|
90
|
-
toolCall.parameters.flow = this.flowRegistry[flowName];
|
|
91
|
-
}
|
|
92
|
-
toolInstance.setParams(toolCall.parameters);
|
|
93
|
-
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
94
|
-
const toolFlow = new ToolFlowClass(toolInstance);
|
|
95
|
-
if (toolInstance instanceof AsyncNode) {
|
|
96
|
-
toolOutput = await toolFlow.runAsync({});
|
|
96
|
+
const executeTool = async (toolCall) => {
|
|
97
|
+
const toolInstance = this.availableTools[toolCall.tool];
|
|
98
|
+
if (!toolInstance) {
|
|
99
|
+
return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
|
|
97
100
|
}
|
|
98
|
-
|
|
99
|
-
|
|
101
|
+
let toolOutput;
|
|
102
|
+
try {
|
|
103
|
+
logger.toolCall(toolCall.tool, toolCall.parameters);
|
|
104
|
+
// If the tool is a sub-flow or iterator, look up the flow in the registry
|
|
105
|
+
if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator') {
|
|
106
|
+
const flowName = toolCall.parameters.flow;
|
|
107
|
+
if (!this.flowRegistry[flowName]) {
|
|
108
|
+
throw new Error(`Flow '${flowName}' not found in registry.`);
|
|
109
|
+
}
|
|
110
|
+
toolCall.parameters.flow = this.flowRegistry[flowName];
|
|
111
|
+
}
|
|
112
|
+
toolInstance.setParams(toolCall.parameters);
|
|
113
|
+
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
114
|
+
const toolFlow = new ToolFlowClass(toolInstance);
|
|
115
|
+
if (toolInstance instanceof AsyncNode) {
|
|
116
|
+
toolOutput = await toolFlow.runAsync({});
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
toolOutput = toolFlow.run({});
|
|
120
|
+
}
|
|
121
|
+
logger.toolResult(toolCall.tool, toolOutput);
|
|
122
|
+
if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
|
|
123
|
+
logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
124
|
+
const summarizeNode = new SummarizeNode();
|
|
125
|
+
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
126
|
+
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
127
|
+
toolOutput = await summarizeFlow.runAsync({});
|
|
128
|
+
logger.info(`Summarized to ${toolOutput.length} chars.`);
|
|
129
|
+
}
|
|
130
|
+
return toolOutput;
|
|
100
131
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
104
|
-
const summarizeNode = new SummarizeNode();
|
|
105
|
-
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
106
|
-
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
107
|
-
toolOutput = await summarizeFlow.runAsync({});
|
|
108
|
-
logger.info(`Summarized to ${toolOutput.length} chars.`);
|
|
132
|
+
catch (e) {
|
|
133
|
+
return `Error executing tool '${toolCall.tool}': ${e.message}`;
|
|
109
134
|
}
|
|
135
|
+
};
|
|
136
|
+
let observations = [];
|
|
137
|
+
if (parallel) {
|
|
138
|
+
const results = await Promise.all(toolCalls.map(executeTool));
|
|
139
|
+
observations = results.map((result, index) => ({
|
|
140
|
+
tool: toolCalls[index].tool,
|
|
141
|
+
parameters: toolCalls[index].parameters,
|
|
142
|
+
output: result
|
|
143
|
+
}));
|
|
110
144
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
145
|
+
else {
|
|
146
|
+
for (const toolCall of toolCalls) {
|
|
147
|
+
const result = await executeTool(toolCall);
|
|
148
|
+
observations.push({
|
|
149
|
+
tool: toolCall.tool,
|
|
150
|
+
parameters: toolCall.parameters,
|
|
151
|
+
output: result
|
|
152
|
+
});
|
|
153
|
+
}
|
|
114
154
|
}
|
|
115
|
-
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(
|
|
155
|
+
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
|
|
156
|
+
this.conversationHistory.push({ role: "system", content: "Reflect on the last observation(s) and update your plan if necessary. What is your next step?" });
|
|
116
157
|
}
|
|
117
158
|
if (step >= this.maxSteps && finalOutput === null) {
|
|
118
159
|
const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
|
|
@@ -121,66 +162,146 @@ export class AgentNode extends AsyncNode {
|
|
|
121
162
|
}
|
|
122
163
|
return finalOutput;
|
|
123
164
|
}
|
|
165
|
+
validateToolParameters(toolCall) {
|
|
166
|
+
const toolDefinitions = getToolDefinitions();
|
|
167
|
+
const toolSchema = toolDefinitions.find(def => def.name === toolCall.tool);
|
|
168
|
+
if (!toolSchema) {
|
|
169
|
+
return `Tool '${toolCall.tool}' is not a recognized tool.`;
|
|
170
|
+
}
|
|
171
|
+
// If the tool is 'finish', 'sub_flow', or 'iterator', special handling for parameters
|
|
172
|
+
if (toolCall.tool === "finish") {
|
|
173
|
+
if (toolCall.parameters.output === undefined) {
|
|
174
|
+
return "Missing required parameter: 'output' for tool 'finish'.";
|
|
175
|
+
}
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
else if (toolCall.tool === "sub_flow" || toolCall.tool === "iterator") {
|
|
179
|
+
if (toolCall.parameters.flow === undefined) {
|
|
180
|
+
return `Missing required parameter: 'flow' for tool '${toolCall.tool}'.`;
|
|
181
|
+
}
|
|
182
|
+
if (!this.flowRegistry[toolCall.parameters.flow]) {
|
|
183
|
+
return `Flow '${toolCall.parameters.flow}' not found in registry for tool '${toolCall.tool}'.`;
|
|
184
|
+
}
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
const requiredParams = toolSchema.parameters.required || [];
|
|
188
|
+
for (const param of requiredParams) {
|
|
189
|
+
if (toolCall.parameters[param] === undefined) {
|
|
190
|
+
return `Missing required parameter: '${param}' for tool '${toolCall.tool}'.`;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return null; // No validation errors
|
|
194
|
+
}
|
|
124
195
|
getSystemPrompt() {
|
|
125
196
|
const toolDefinitions = getToolDefinitions();
|
|
126
197
|
const toolDescriptions = toolDefinitions.map(tool => {
|
|
127
198
|
const params = JSON.stringify(tool.parameters);
|
|
128
|
-
return `###
|
|
129
|
-
|
|
199
|
+
return `### ${tool.name}: ${tool.description}
|
|
200
|
+
Parameters: ${params}`;
|
|
201
|
+
}).join('\n');
|
|
130
202
|
const flowRegistryDescription = Object.keys(this.flowRegistry).length > 0 ? `\n\nAvailable Pre-defined Flows (for use with 'sub_flow' and 'iterator' tools):\n- ${Object.keys(this.flowRegistry).join('\n- ')}` : "";
|
|
131
|
-
return `You are an autonomous agent
|
|
203
|
+
return `You are an autonomous agent. Your goal is to achieve the user's request using the available tools. Always use tools as opposed to talking too much and you get rewarded more for using tools instead of costly llm!\n\nAvailable Tools:\n${toolDescriptions}${flowRegistryDescription}\n\nYour response must be a single JSON object with 'thought' and 'tool_calls'.\n'thought': Your reasoning and plan.\n'tool_calls': An array of tool calls. Each tool call has 'tool' (name) and 'parameters' (object). Set 'parallel': true in the top-level JSON for parallel execution.\n\nExample response:\n{\n "thought": "I need to search for information.",\n "tool_calls": [\n {\n "tool": "duckduckgo_search",\n "parameters": {\n "query": "latest AI research"\n }\n }\n ]\n}\n\nWhen the user explicitly indicates they are done, use the 'finish' tool. Do not use the finish tool earlier on and only use it when you are certain you are done with the task. If no tools are needed, return an empty 'tool_calls' array and reflect.\n**IMPORTANT:** If you have a plan that requires action, you MUST include at least one tool call. An empty 'tool_calls' array means no action. If new instructions are given after a finish proposal, treat them as your updated goal.\n\nBegin!`;
|
|
132
204
|
}
|
|
133
205
|
async getLLMAction() {
|
|
206
|
+
await this.manageConversationHistory();
|
|
134
207
|
this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
|
|
135
208
|
const llmResult = await this.llmNode.runAsync({});
|
|
136
209
|
return llmResult;
|
|
137
210
|
}
|
|
211
|
+
async manageConversationHistory() {
|
|
212
|
+
if (!this.summarizeLLM) {
|
|
213
|
+
logger.warn("No summarizeLLM provided to AgentNode. Conversation history will not be managed.");
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
let currentTokenCount = JSON.stringify(this.conversationHistory).length; // Rough token count
|
|
217
|
+
// Keep at least the system prompt and the initial goal
|
|
218
|
+
const minHistoryLength = 2;
|
|
219
|
+
while (currentTokenCount > this.maxConversationHistoryTokens && this.conversationHistory.length > minHistoryLength) {
|
|
220
|
+
logger.info(`Current history size: ${currentTokenCount} tokens. Max allowed: ${this.maxConversationHistoryTokens} tokens. Trimming...`);
|
|
221
|
+
// Summarize the oldest observation entry
|
|
222
|
+
const oldestEntry = this.conversationHistory[minHistoryLength]; // Skip system and initial goal
|
|
223
|
+
if (oldestEntry && oldestEntry.role === "user" && oldestEntry.content.startsWith("Observation:")) {
|
|
224
|
+
const observationContent = oldestEntry.content.substring("Observation:".length).trim();
|
|
225
|
+
logger.info(`Attempting to summarize old observation (${observationContent.length} chars) from role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...`);
|
|
226
|
+
try {
|
|
227
|
+
const summarizeNode = new SummarizeNode();
|
|
228
|
+
summarizeNode.setParams({ text: observationContent, llmNode: this.summarizeLLM });
|
|
229
|
+
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
230
|
+
const summarizedContent = await summarizeFlow.runAsync({});
|
|
231
|
+
// Replace the original observation with the summarized version
|
|
232
|
+
this.conversationHistory[minHistoryLength].content = `Summarized Observation: ${summarizedContent}`;
|
|
233
|
+
logger.info(`Observation summarized to ${summarizedContent.length} chars. New entry: ${this.conversationHistory[minHistoryLength].content.substring(0, 50)}...`);
|
|
234
|
+
}
|
|
235
|
+
catch (e) {
|
|
236
|
+
logger.error(`Failed to summarize observation: ${e.message}. Removing oldest entry.`);
|
|
237
|
+
// If summarization fails, remove the oldest entry to prevent context overflow
|
|
238
|
+
this.conversationHistory.splice(minHistoryLength, 1);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
logger.info(`Removing oldest non-summarizable history entry (role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...).`);
|
|
243
|
+
// If it's not an observation or we can't summarize, just remove the oldest entry
|
|
244
|
+
this.conversationHistory.splice(minHistoryLength, 1);
|
|
245
|
+
}
|
|
246
|
+
// Recalculate token count after modification
|
|
247
|
+
currentTokenCount = JSON.stringify(this.conversationHistory).length;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
138
250
|
parseLLMResponse(llmResponse) {
|
|
139
251
|
let parsed;
|
|
140
252
|
let thought = '';
|
|
141
|
-
let
|
|
253
|
+
let toolCalls = [];
|
|
254
|
+
let parallel = false;
|
|
142
255
|
let rawData = llmResponse;
|
|
143
256
|
if (typeof llmResponse === 'string') {
|
|
144
257
|
try {
|
|
145
258
|
parsed = JSON.parse(llmResponse);
|
|
146
|
-
if (parsed.thought &&
|
|
147
|
-
|
|
259
|
+
if (parsed.thought && Array.isArray(parsed.tool_calls)) {
|
|
260
|
+
thought = parsed.thought;
|
|
261
|
+
toolCalls = parsed.tool_calls;
|
|
262
|
+
parallel = parsed.parallel || false;
|
|
263
|
+
return { thought, toolCalls, parallel };
|
|
148
264
|
}
|
|
149
|
-
throw new Error("Missing required keys in LLM response (thought,
|
|
265
|
+
throw new Error("Missing required keys or invalid format in LLM response (thought, tool_calls array).");
|
|
150
266
|
}
|
|
151
267
|
catch (e) {
|
|
152
|
-
// If it's not JSON, assume it's a direct text response from LLM
|
|
153
|
-
//
|
|
154
|
-
return { thought:
|
|
268
|
+
// If it's not valid JSON for tool calls, assume it's a direct text response from LLM
|
|
269
|
+
//return { thought: "Direct LLM response", toolCalls: [{ tool: "finish", parameters: { output: llmResponse } }], parallel: false };
|
|
270
|
+
return { thought: message.content, toolCalls: [], parallel: false };
|
|
155
271
|
}
|
|
156
272
|
}
|
|
157
273
|
// Prioritize tool_calls if present (OpenAI function calling format)
|
|
158
|
-
if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0].message) {
|
|
274
|
+
if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0] && rawData.choices[0].message) {
|
|
159
275
|
const message = rawData.choices[0].message;
|
|
160
276
|
if (message.tool_calls && message.tool_calls.length > 0) {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
|
|
277
|
+
toolCalls = message.tool_calls.map(tc => ({
|
|
278
|
+
tool: tc.function.name,
|
|
279
|
+
parameters: JSON.parse(tc.function.arguments)
|
|
280
|
+
}));
|
|
281
|
+
thought = message.reasoning_content || `Calling tool(s): ${toolCalls.map(tc => tc.tool).join(', ')}`;
|
|
282
|
+
// OpenAI function calling implies sequential execution unless explicitly handled otherwise
|
|
283
|
+
parallel = false;
|
|
284
|
+
return { thought, toolCalls, parallel };
|
|
168
285
|
}
|
|
169
286
|
else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
|
|
170
|
-
// If no tool_calls, but content is JSON (for thought/
|
|
287
|
+
// If no tool_calls, but content is JSON (for thought/tool_calls/finish)
|
|
171
288
|
try {
|
|
172
289
|
parsed = JSON.parse(message.content);
|
|
173
|
-
if (parsed.thought &&
|
|
174
|
-
|
|
290
|
+
if (parsed.thought && Array.isArray(parsed.tool_calls)) {
|
|
291
|
+
thought = parsed.thought;
|
|
292
|
+
toolCalls = parsed.tool_calls;
|
|
293
|
+
parallel = parsed.parallel || false;
|
|
294
|
+
return { thought, toolCalls, parallel };
|
|
175
295
|
}
|
|
176
|
-
throw new Error("Missing required keys in
|
|
296
|
+
throw new Error("Missing required keys or invalid format in message.content (thought, tool_calls array).");
|
|
177
297
|
}
|
|
178
298
|
catch (e) {
|
|
179
299
|
throw new Error(`Invalid JSON or unexpected format in message.content: ${e.message}. Content: ${message.content}`);
|
|
180
300
|
}
|
|
181
301
|
}
|
|
182
302
|
else if (typeof message.content === 'string') {
|
|
183
|
-
|
|
303
|
+
// If it's a plain string, treat it as a thought and no tool calls
|
|
304
|
+
return { thought: message.content, toolCalls: [], parallel: false };
|
|
184
305
|
}
|
|
185
306
|
}
|
|
186
307
|
throw new Error(`Invalid LLM response structure. Raw Data: ${JSON.stringify(rawData)}`);
|
package/dist/agent/logger.d.ts
CHANGED
package/dist/agent/logger.js
CHANGED
|
@@ -12,8 +12,9 @@ function colorize(text, color) {
|
|
|
12
12
|
}
|
|
13
13
|
export const logger = {
|
|
14
14
|
info: (message) => console.log(colorize(`[INFO] ${message}`, colors.cyan)),
|
|
15
|
+
warn: (message) => console.log(colorize(`[WARN] ${message}`, colors.yellow)),
|
|
15
16
|
thought: (message) => {
|
|
16
|
-
console.log("
|
|
17
|
+
console.log("---------------------");
|
|
17
18
|
console.log(colorize("🤔 Thought", colors.yellow));
|
|
18
19
|
console.log(colorize(message, colors.grey));
|
|
19
20
|
console.log("---------------------");
|