@codebolt/codeboltjs 2.0.16 → 2.0.17

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.
@@ -1,805 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.InitialPromptBuilder = void 0;
7
- const systemprompt_1 = require("./systemprompt");
8
- const js_yaml_1 = __importDefault(require("js-yaml"));
9
- const fs_1 = __importDefault(require("fs"));
10
- const path_1 = __importDefault(require("path"));
11
- // All interfaces moved to appropriate type files
12
- /**
13
- * PromptBuilder class for constructing prompts using a fluent interface.
14
- * Allows chaining methods to build complex prompts from user messages.
15
- */
16
- class InitialPromptBuilder {
17
- /**
18
- * Creates a new PromptBuilder instance.
19
- *
20
- * @param userMessage - The initial user message containing text and mentioned entities
21
- * @param codebolt - Optional codebolt API instance for automatic tool and environment loading
22
- */
23
- constructor(userMessage, codebolt) {
24
- var _a;
25
- /** System prompt text */
26
- this.systemPromptText = "";
27
- /** Task instruction text */
28
- this.taskInstructionText = "";
29
- /** Available tools */
30
- this.tools = [];
31
- /** Conversation history */
32
- this.conversationHistory = [];
33
- /** Environment details */
34
- this.environmentDetails = "";
35
- /** File contents cache */
36
- this.fileContents = new Map();
37
- // Flags for what needs to be loaded during build
38
- this.shouldLoadMCPTools = false;
39
- this.mcpAdditionalServers = ["codebolt"];
40
- this.shouldLoadAgentTools = false;
41
- this.shouldLoadEnvironmentDetails = false;
42
- this.shouldLoadAll = false;
43
- // Handle both InitialUserMessage and CLIUserMessage types
44
- if ('message' in userMessage && typeof userMessage.message === 'object') {
45
- // This is a CLIUserMessage with nested message structure
46
- this.message = userMessage.message.userMessage || ((_a = userMessage.data) === null || _a === void 0 ? void 0 : _a.text.trim()) || "";
47
- this.mentionedFiles = userMessage.message.mentionedFiles || [];
48
- // Convert string array to MCPTool array for CLIUserMessage
49
- this.mentionedMCPs = (userMessage.message.mentionedMCPs || []).map((name) => ({ name }));
50
- this.mentionedAgents = userMessage.message.mentionedAgents || [];
51
- }
52
- else {
53
- // This is an InitialUserMessage
54
- this.message = userMessage.messageText || userMessage.userMessage || "";
55
- this.mentionedFiles = userMessage.mentionedFiles || [];
56
- this.mentionedMCPs = userMessage.mentionedMCPs || [];
57
- this.mentionedAgents = userMessage.mentionedAgents || [];
58
- }
59
- this.promptParts = [this.message];
60
- this.codebolt = codebolt;
61
- }
62
- /**
63
- * Sets the codebolt API instance for automatic operations.
64
- *
65
- * @param codebolt - The codebolt API instance
66
- * @returns The PromptBuilder instance for chaining
67
- */
68
- setCodeboltAPI(codebolt) {
69
- this.codebolt = codebolt;
70
- return this;
71
- }
72
- /**
73
- * Marks MCP tools to be loaded during build from the mentioned MCPs and additional servers.
74
- *
75
- * @param additionalServers - Additional MCP servers to load tools from
76
- * @returns The PromptBuilder instance for chaining
77
- */
78
- addMCPTools(additionalServers = ["codebolt"]) {
79
- this.shouldLoadMCPTools = true;
80
- this.mcpAdditionalServers = additionalServers;
81
- return this;
82
- }
83
- /**
84
- * Marks mentioned agents to be converted to OpenAI tool format during build.
85
- *
86
- * @returns The PromptBuilder instance for chaining
87
- */
88
- addAgentTools() {
89
- this.shouldLoadAgentTools = true;
90
- return this;
91
- }
92
- /**
93
- * Marks environment details to be loaded during build.
94
- *
95
- * @returns The PromptBuilder instance for chaining
96
- */
97
- addEnvironmentDetails() {
98
- this.shouldLoadEnvironmentDetails = true;
99
- return this;
100
- }
101
- /**
102
- * Convenience method to mark all tools and environment details to be loaded during build.
103
- * Equivalent to calling addMCPTools(), addAgentTools(), and addEnvironmentDetails().
104
- *
105
- * @param additionalServers - Additional MCP servers to load tools from
106
- * @returns The PromptBuilder instance for chaining
107
- */
108
- addAllAutomatic(additionalServers = ["codebolt"]) {
109
- this.shouldLoadAll = true;
110
- this.mcpAdditionalServers = additionalServers;
111
- return this;
112
- }
113
- /**
114
- * Loads MCP tools from the codebolt API.
115
- * Internal method called during build.
116
- */
117
- async loadMCPTools() {
118
- if (!this.codebolt) {
119
- console.warn("Codebolt API not available. Cannot load MCP tools automatically.");
120
- return;
121
- }
122
- try {
123
- // Get default tools from specified servers
124
- const { data: defaultTools } = await this.codebolt.mcp.listMcpFromServers(this.mcpAdditionalServers);
125
- this.tools = [...this.tools, ...defaultTools];
126
- // Get tools from mentioned MCPs
127
- if (this.mentionedMCPs && this.mentionedMCPs.length > 0) {
128
- const { data: mcpTools } = await this.codebolt.mcp.getTools(this.mentionedMCPs);
129
- this.tools = [...this.tools, ...mcpTools];
130
- }
131
- }
132
- catch (error) {
133
- console.error(`Error loading MCP tools: ${error}`);
134
- }
135
- }
136
- /**
137
- * Converts mentioned agents to OpenAI tool format.
138
- * Internal method called during build.
139
- */
140
- loadAgentTools() {
141
- if (this.mentionedAgents && this.mentionedAgents.length > 0) {
142
- const agentTools = this.mentionedAgents.map(agent => ({
143
- type: "function",
144
- function: {
145
- name: `subagent--${agent.unique_id}`,
146
- description: agent.longDescription || agent.description || "Agent tool",
147
- parameters: {
148
- type: "object",
149
- properties: {
150
- task: {
151
- type: "string",
152
- description: "The task to be executed by the tool."
153
- }
154
- },
155
- required: ["task"]
156
- }
157
- }
158
- }));
159
- this.tools = [...this.tools, ...agentTools];
160
- }
161
- }
162
- /**
163
- * Loads file contents and environment details from the codebolt API.
164
- * Internal method called during build.
165
- */
166
- async loadEnvironmentDetails() {
167
- if (!this.codebolt) {
168
- console.warn("Codebolt API not available. Cannot load environment details automatically.");
169
- return;
170
- }
171
- try {
172
- // Load mentioned file contents
173
- if (this.mentionedFiles && this.mentionedFiles.length > 0) {
174
- for (const file of this.mentionedFiles) {
175
- try {
176
- const fileData = await this.codebolt.fs.readFile(file);
177
- this.fileContents.set(file, fileData);
178
- }
179
- catch (error) {
180
- console.error(`Error reading file ${file}: ${error}`);
181
- this.fileContents.set(file, "[File could not be read]");
182
- }
183
- }
184
- }
185
- // Get project path and file listing
186
- const { projectPath } = await this.codebolt.project.getProjectPath();
187
- if (projectPath) {
188
- const { success, result } = await this.codebolt.fs.listFile(projectPath, true);
189
- if (success) {
190
- this.environmentDetails = `\n\n<environment_details>\n\n# Current Working Directory (${projectPath}) Files\n${result}\n</environment_details>`;
191
- }
192
- }
193
- }
194
- catch (error) {
195
- console.error(`Error loading environment details: ${error}`);
196
- }
197
- }
198
- /**
199
- * Adds system prompt from a YAML file.
200
- *
201
- * @param filepath - Path to the YAML file containing system prompts
202
- * @param key - Key identifier for the specific prompt
203
- * @param exampleFilePath - Optional path to example file to append
204
- * @returns The PromptBuilder instance for chaining
205
- */
206
- addSystemPrompt(filepath, key, exampleFilePath) {
207
- try {
208
- const systemPrompt = new systemprompt_1.SystemPrompt(filepath, key);
209
- this.systemPromptText = systemPrompt.toPromptText();
210
- // Add example file if provided
211
- if (exampleFilePath) {
212
- try {
213
- const example = fs_1.default.readFileSync(path_1.default.resolve(exampleFilePath), 'utf8');
214
- this.systemPromptText += `\n\n<example_agent>\n\`\`\`\n${example}\n\`\`\`\n</example_agent>`;
215
- }
216
- catch (error) {
217
- console.error(`Error loading example file: ${error}`);
218
- }
219
- }
220
- }
221
- catch (error) {
222
- console.error(`Error loading system prompt: ${error}`);
223
- }
224
- return this;
225
- }
226
- /**
227
- * Adds task instruction from a YAML file.
228
- *
229
- * @param filepath - Path to the YAML file containing task instructions
230
- * @param refsection - Section name within the YAML file
231
- * @returns The PromptBuilder instance for chaining
232
- */
233
- addTaskInstruction(filepath, refsection) {
234
- try {
235
- const fileContents = fs_1.default.readFileSync(path_1.default.resolve(filepath), 'utf8');
236
- const data = js_yaml_1.default.load(fileContents);
237
- const task = data[refsection];
238
- if (task) {
239
- this.taskInstructionText = `Task Description: ${task.description}\nExpected Output: ${task.expected_output}`;
240
- }
241
- }
242
- catch (error) {
243
- console.error(`Error loading task instruction: ${error}`);
244
- }
245
- return this;
246
- }
247
- /**
248
- * Manually adds environment details with file listing.
249
- * Use addEnvironmentDetails() for automatic loading instead.
250
- *
251
- * @param projectPath - The project path
252
- * @param fileListResult - The file listing result
253
- * @returns The PromptBuilder instance for chaining
254
- */
255
- setEnvironmentDetails(projectPath, fileListResult) {
256
- if (projectPath && fileListResult) {
257
- this.environmentDetails = `\n\n<environment_details>\n\n# Current Working Directory (${projectPath}) Files\n${fileListResult}\n</environment_details>`;
258
- }
259
- return this;
260
- }
261
- /**
262
- * Adds MCP tools information to the prompt.
263
- * Only adds content if there are mentioned MCPs.
264
- *
265
- * @returns The PromptBuilder instance for chaining
266
- */
267
- addMCPToolsToPrompt() {
268
- if (this.mentionedMCPs.length > 0) {
269
- const mcpTools = this.mentionedMCPs.map(mcp => {
270
- const name = mcp.name || mcp.toolbox || "Unknown";
271
- const toolName = mcp.toolName || "";
272
- const tools = mcp.tools ? JSON.stringify(mcp.tools) : "[]";
273
- let mcpInfo = `MCP: ${name}`;
274
- if (toolName) {
275
- mcpInfo += `, Tool: ${toolName}`;
276
- }
277
- mcpInfo += `, Tools: ${tools}`;
278
- return mcpInfo;
279
- }).join("\n");
280
- this.promptParts.push(`[MCP Tools]\n${mcpTools}`);
281
- }
282
- return this;
283
- }
284
- /**
285
- * Adds agent information to the prompt.
286
- * Only adds content if there are mentioned agents.
287
- *
288
- * @returns The PromptBuilder instance for chaining
289
- */
290
- addAgentsToPrompt() {
291
- if (this.mentionedAgents.length > 0) {
292
- const agentList = this.mentionedAgents.map(agent => {
293
- const identifier = agent.name || agent.title || agent.id || agent.agent_id || "Unknown";
294
- let agentInfo = `Agent: ${identifier}`;
295
- if (agent.description) {
296
- agentInfo += ` - ${agent.description}`;
297
- }
298
- return agentInfo;
299
- }).join("\n");
300
- this.promptParts.push(`[Agents]\n${agentList}`);
301
- }
302
- return this;
303
- }
304
- /**
305
- * Manually sets the available tools for the conversation.
306
- * Use addMCPTools() and addAgentTools() for automatic loading instead.
307
- *
308
- * @param tools - Array of OpenAI tools
309
- * @returns The PromptBuilder instance for chaining
310
- */
311
- setTools(tools) {
312
- this.tools = [...tools];
313
- return this;
314
- }
315
- /**
316
- * Adds additional tools to the existing tool list.
317
- *
318
- * @param tools - Array of OpenAI tools to add
319
- * @returns The PromptBuilder instance for chaining
320
- */
321
- addTools(tools) {
322
- this.tools = [...this.tools, ...tools];
323
- return this;
324
- }
325
- /**
326
- * Builds the user message content with files (without environment details).
327
- *
328
- * @returns Array of content blocks
329
- */
330
- buildUserMessageContent() {
331
- let finalPrompt = `
332
- The user has sent the following query:
333
- <user_query> ${this.message} </user_query>.
334
- `;
335
- // Attach files if mentioned
336
- if (this.mentionedFiles && this.mentionedFiles.length > 0) {
337
- finalPrompt += `The Attached files are:`;
338
- for (const file of this.mentionedFiles) {
339
- const fileData = this.fileContents.get(file) || "[File content not available]";
340
- finalPrompt += `File Name: ${file}, File Path: ${file}, Filedata: ${fileData}`;
341
- }
342
- }
343
- const content = [
344
- { type: "text", text: finalPrompt }
345
- ];
346
- // Add environment details
347
- if (this.environmentDetails) {
348
- content.push({ type: "text", text: this.environmentDetails });
349
- }
350
- // Add task instruction if available
351
- if (this.taskInstructionText) {
352
- content.push({
353
- type: "text",
354
- text: this.taskInstructionText
355
- });
356
- }
357
- return content;
358
- }
359
- /**
360
- * Builds the OpenAI conversation format.
361
- *
362
- * @returns Array of OpenAI messages
363
- */
364
- buildOpenAIMessages() {
365
- const messages = [];
366
- // Add system message if available
367
- if (this.systemPromptText) {
368
- messages.push({
369
- role: "system",
370
- content: this.systemPromptText
371
- });
372
- }
373
- // Add user message
374
- const userContent = this.buildUserMessageContent();
375
- messages.push({
376
- role: "user",
377
- content: userContent
378
- });
379
- // Add any existing conversation history
380
- messages.push(...this.conversationHistory);
381
- return messages;
382
- }
383
- /**
384
- * Gets the available tools in OpenAI format.
385
- *
386
- * @returns Array of OpenAI tools
387
- */
388
- getTools() {
389
- return this.tools;
390
- }
391
- /**
392
- * Gets the loaded file contents.
393
- *
394
- * @returns Map of file paths to their contents
395
- */
396
- getFileContents() {
397
- return new Map(this.fileContents);
398
- }
399
- /**
400
- * Adds a message to the conversation history.
401
- *
402
- * @param role - The role of the message sender
403
- * @param content - The content of the message
404
- * @param toolCallId - Optional tool call ID for tool messages
405
- * @param toolCalls - Optional tool calls for assistant messages
406
- * @returns The PromptBuilder instance for chaining
407
- */
408
- addToConversationHistory(role, content, toolCallId, toolCalls) {
409
- const message = { role, content };
410
- if (toolCallId) {
411
- message.tool_call_id = toolCallId;
412
- }
413
- if (toolCalls) {
414
- message.tool_calls = toolCalls;
415
- }
416
- this.conversationHistory.push(message);
417
- return this;
418
- }
419
- /**
420
- * Gets the current conversation history.
421
- *
422
- * @returns Array of conversation entries
423
- */
424
- getConversationHistory() {
425
- return [...this.conversationHistory];
426
- }
427
- /**
428
- * Adds an LLM response to the conversation history.
429
- * This method processes the LLM response and adds the assistant's message to the conversation.
430
- * It handles both resolved responses and promises that resolve to responses.
431
- *
432
- * @param llmResponse - The LLM response (can be a promise or resolved response)
433
- * @returns The PromptBuilder instance for chaining
434
- *
435
- * @example
436
- * ```typescript
437
- * // Example of using addLLMResponse in an agent workflow loop
438
- * import { PromptBuilder } from './promptbuilder';
439
- * import llm from '../modules/llm';
440
- *
441
- * async function agentWorkflowWithLLMResponse(userMessage: any, codebolt: CodeboltAPI) {
442
- * // Step 1: Build initial prompt
443
- * const promptBuilder = new PromptBuilder(userMessage, codebolt);
444
- * let currentPrompt = await promptBuilder
445
- * .addMCPTools()
446
- * .addAgentTools()
447
- * .addEnvironmentDetails()
448
- * .buildInferenceParams();
449
- *
450
- * let completed = false;
451
- * let maxTurns = 20;
452
- * let turn = 0;
453
- *
454
- * // Step 2: Main conversation loop (similar to agent.ts while loop)
455
- * while (!completed && turn < maxTurns) {
456
- * // Get LLM response
457
- * const llmResponse = llm.inference(currentPrompt);
458
- *
459
- * // Add LLM response to conversation history
460
- * await promptBuilder.addLLMResponse(llmResponse);
461
- *
462
- * // Process the response using LLMOutputHandler
463
- * const outputHandler = new LLMOutputHandler(llmResponse, codebolt);
464
- * await outputHandler.sendMessageToUser();
465
- *
466
- * // Check if task is completed
467
- * if (outputHandler.isCompleted()) {
468
- * completed = true;
469
- * break;
470
- * }
471
- *
472
- * // Execute tools and get results
473
- * const toolResults = await outputHandler.runTools();
474
- *
475
- * // Add tool results to conversation
476
- * if (toolResults.length > 0) {
477
- * promptBuilder.addToolResults(toolResults);
478
- * } else {
479
- * // Add default continuation message when no tools executed
480
- * promptBuilder.addDefaultContinuationMessage();
481
- * }
482
- *
483
- * // Build next prompt for the loop
484
- * currentPrompt = await promptBuilder.buildInferenceParams();
485
- * turn++;
486
- * }
487
- * }
488
- * ```
489
- */
490
- async addLLMResponse(llmResponse) {
491
- try {
492
- // Resolve the response if it's a promise
493
- const resolvedResponse = await Promise.resolve(llmResponse);
494
- if (!resolvedResponse || !resolvedResponse.completion) {
495
- console.warn("Invalid LLM response provided");
496
- return this;
497
- }
498
- const completion = resolvedResponse.completion;
499
- let assistantMessage = null;
500
- // Handle different response formats
501
- if (completion.choices && completion.choices.length > 0) {
502
- // OpenAI-style response with choices
503
- const choice = completion.choices[0];
504
- if (choice.message) {
505
- assistantMessage = {
506
- role: "assistant",
507
- content: choice.message.content || "",
508
- tool_calls: choice.message.tool_calls || undefined
509
- };
510
- }
511
- }
512
- else if (completion.content) {
513
- // Direct content response
514
- assistantMessage = {
515
- role: "assistant",
516
- content: completion.content
517
- };
518
- }
519
- else if (completion.message) {
520
- // Message format response
521
- assistantMessage = {
522
- role: "assistant",
523
- content: completion.message.content || "",
524
- tool_calls: completion.message.tool_calls || undefined
525
- };
526
- }
527
- // Add the assistant message to conversation history
528
- if (assistantMessage) {
529
- this.conversationHistory.push(assistantMessage);
530
- }
531
- else {
532
- // Fallback for cases where no valid message is found
533
- this.conversationHistory.push({
534
- role: "assistant",
535
- content: "I apologize, but I was unable to provide a proper response."
536
- });
537
- }
538
- }
539
- catch (error) {
540
- console.error("Error adding LLM response to conversation:", error);
541
- // Add error message to conversation history
542
- this.conversationHistory.push({
543
- role: "assistant",
544
- content: "An error occurred while processing my response."
545
- });
546
- }
547
- return this;
548
- }
549
- /**
550
- * Adds tool results to the conversation history.
551
- * This method is typically used after executing tools from an LLM response.
552
- *
553
- * @param toolResults - Array of tool results to add to the conversation
554
- * @returns The PromptBuilder instance for chaining
555
- */
556
- addToolResults(toolResults) {
557
- if (toolResults && toolResults.length > 0) {
558
- // Add each tool result as a separate message
559
- toolResults.forEach(toolResult => {
560
- this.conversationHistory.push({
561
- role: "tool",
562
- content: toolResult.content,
563
- tool_call_id: toolResult.tool_call_id
564
- });
565
- });
566
- }
567
- return this;
568
- }
569
- /**
570
- * Adds a user message to the conversation history.
571
- * Useful for adding follow-up questions or additional context during the conversation.
572
- *
573
- * @param message - The user message to add
574
- * @returns The PromptBuilder instance for chaining
575
- */
576
- addUserMessage(message) {
577
- const userMessage = {
578
- role: "user",
579
- content: message
580
- };
581
- this.conversationHistory.push(userMessage);
582
- return this;
583
- }
584
- /**
585
- * Adds a default continuation message when no tools were executed.
586
- * This is used in the agent workflow to prompt the LLM to either complete the task
587
- * or ask for more information.
588
- *
589
- * @returns The PromptBuilder instance for chaining
590
- */
591
- addDefaultContinuationMessage() {
592
- const defaultMessage = "If you have completed the user's task, use the attempt_completion tool. If you require additional information from the user, use the ask_followup_question tool. Otherwise, if you have not completed the task and do not need additional information, then proceed with the next step of the task. (This is an automated message, so do not respond to it conversationally.)";
593
- this.addUserMessage([{
594
- type: "text",
595
- text: defaultMessage
596
- }]);
597
- return this;
598
- }
599
- /**
600
- * Adds a custom text section to the prompt.
601
- *
602
- * @param title - Optional title for the section
603
- * @param content - The content to add
604
- * @returns The PromptBuilder instance for chaining
605
- */
606
- addCustomSection(title, content) {
607
- if (content.trim()) {
608
- const section = title ? `[${title}]\n${content}` : content;
609
- this.promptParts.push(section);
610
- }
611
- return this;
612
- }
613
- /**
614
- * Adds a system instruction to the prompt.
615
- *
616
- * @param instruction - The system instruction to add
617
- * @returns The PromptBuilder instance for chaining
618
- */
619
- addSystemInstruction(instruction) {
620
- if (instruction.trim()) {
621
- this.promptParts.push(`[System Instruction]\n${instruction}`);
622
- }
623
- return this;
624
- }
625
- /**
626
- * Adds context information to the prompt.
627
- *
628
- * @param context - The context information to add
629
- * @returns The PromptBuilder instance for chaining
630
- */
631
- addContext(context) {
632
- const userMessage = {
633
- role: "user",
634
- content: context
635
- };
636
- this.conversationHistory.push(userMessage);
637
- return this;
638
- }
639
- /**
640
- * Builds and returns the OpenAI message format with tools.
641
- * This method performs all async operations that were marked during setup.
642
- *
643
- * @returns Object with messages, tools, and other LLM parameters
644
- */
645
- async build() {
646
- // Perform all async operations based on what was requested
647
- if (this.shouldLoadAll) {
648
- await this.loadMCPTools();
649
- this.loadAgentTools();
650
- await this.loadEnvironmentDetails();
651
- }
652
- else {
653
- if (this.shouldLoadMCPTools) {
654
- await this.loadMCPTools();
655
- }
656
- if (this.shouldLoadAgentTools) {
657
- this.loadAgentTools();
658
- }
659
- if (this.shouldLoadEnvironmentDetails) {
660
- await this.loadEnvironmentDetails();
661
- }
662
- }
663
- return {
664
- messages: this.buildOpenAIMessages(),
665
- tools: this.getTools(),
666
- full: true,
667
- max_tokens: 8192,
668
- tool_choice: "auto",
669
- };
670
- }
671
- /**
672
- * Gets the current prompt parts without building the final string.
673
- * Useful for debugging or inspection.
674
- *
675
- * @returns Array of current prompt parts
676
- */
677
- getPromptParts() {
678
- return [...this.promptParts];
679
- }
680
- /**
681
- * Clears all prompt parts except the initial message.
682
- * Useful for starting over with the same message.
683
- *
684
- * @returns The PromptBuilder instance for chaining
685
- */
686
- reset() {
687
- this.promptParts = [this.message];
688
- this.conversationHistory = [];
689
- this.systemPromptText = "";
690
- this.taskInstructionText = "";
691
- this.tools = [];
692
- this.environmentDetails = "";
693
- this.fileContents.clear();
694
- // Reset async loading flags
695
- this.shouldLoadMCPTools = false;
696
- this.shouldLoadAgentTools = false;
697
- this.shouldLoadEnvironmentDetails = false;
698
- this.shouldLoadAll = false;
699
- this.mcpAdditionalServers = ["codebolt"];
700
- return this;
701
- }
702
- /**
703
- * Creates an LLM inference parameters object in the format expected by the sample code.
704
- * This method performs all async operations that were marked during setup.
705
- *
706
- * @returns Object with messages, tools, and other LLM parameters
707
- */
708
- async buildInferenceParams() {
709
- // Perform all async operations based on what was requested
710
- if (this.shouldLoadAll) {
711
- await this.loadMCPTools();
712
- this.loadAgentTools();
713
- await this.loadEnvironmentDetails();
714
- }
715
- else {
716
- if (this.shouldLoadMCPTools) {
717
- await this.loadMCPTools();
718
- }
719
- if (this.shouldLoadAgentTools) {
720
- this.loadAgentTools();
721
- }
722
- if (this.shouldLoadEnvironmentDetails) {
723
- await this.loadEnvironmentDetails();
724
- }
725
- }
726
- return {
727
- full: true,
728
- messages: this.buildOpenAIMessages(),
729
- tools: this.getTools(),
730
- tool_choice: "auto",
731
- };
732
- }
733
- /**
734
- * Creates a minimal LLM inference parameters object with only the user message.
735
- * This is useful for simple completions or when no tools/context are needed.
736
- *
737
- * @returns Object with messages (user only), no tools, and default tool_choice
738
- */
739
- //TODO: implement this
740
- buildDefaultInferenceParams() {
741
- return {
742
- full: false,
743
- messages: [this.message],
744
- tools: [],
745
- tool_choice: "auto",
746
- };
747
- }
748
- /**
749
- * Checks if the last LLM response indicates task completion.
750
- * This method examines the conversation history for completion signals.
751
- *
752
- * @returns Boolean indicating if the task appears to be completed
753
- */
754
- isTaskCompleted() {
755
- if (this.conversationHistory.length === 0) {
756
- return false;
757
- }
758
- // Get the last assistant message
759
- const lastAssistantMessage = this.conversationHistory
760
- .slice()
761
- .reverse()
762
- .find(msg => msg.role === 'assistant');
763
- if (!lastAssistantMessage) {
764
- return false;
765
- }
766
- // Check if the message has tool calls with completion tools
767
- if (lastAssistantMessage.tool_calls) {
768
- const hasCompletionTool = lastAssistantMessage.tool_calls.some(toolCall => toolCall.function && toolCall.function.name.includes('attempt_completion'));
769
- if (hasCompletionTool) {
770
- return true;
771
- }
772
- }
773
- // Check for completion keywords in the message content
774
- const content = typeof lastAssistantMessage.content === 'string'
775
- ? lastAssistantMessage.content
776
- : '';
777
- const completionKeywords = [
778
- 'task completed',
779
- 'task is completed',
780
- 'successfully completed',
781
- 'finished the task',
782
- 'task has been completed'
783
- ];
784
- return completionKeywords.some(keyword => content.toLowerCase().includes(keyword.toLowerCase()));
785
- }
786
- /**
787
- * Gets the current conversation length (number of messages).
788
- * Useful for determining when to summarize the conversation.
789
- *
790
- * @returns Number of messages in the conversation history
791
- */
792
- getConversationLength() {
793
- return this.conversationHistory.length;
794
- }
795
- /**
796
- * Checks if the conversation should be summarized based on length.
797
- *
798
- * @param maxLength - Maximum conversation length before summarization (default: 50)
799
- * @returns Boolean indicating if summarization is needed
800
- */
801
- shouldSummarizeConversation(maxLength = 50) {
802
- return this.getConversationLength() > maxLength;
803
- }
804
- }
805
- exports.InitialPromptBuilder = InitialPromptBuilder;