@codebolt/agent 1.0.0
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/README.md +120 -0
- package/dist/agent.d.ts +86 -0
- package/dist/agent.js +324 -0
- package/dist/followupquestionbuilder.d.ts +75 -0
- package/dist/followupquestionbuilder.js +197 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +23 -0
- package/dist/llmoutputhandler.d.ts +102 -0
- package/dist/llmoutputhandler.js +452 -0
- package/dist/promptbuilder.d.ts +382 -0
- package/dist/promptbuilder.js +805 -0
- package/dist/systemprompt.d.ts +20 -0
- package/dist/systemprompt.js +48 -0
- package/dist/taskInstruction.d.ts +37 -0
- package/dist/taskInstruction.js +57 -0
- package/dist/types/InternalTypes.d.ts +499 -0
- package/dist/types/InternalTypes.js +30 -0
- package/dist/types/commonTypes.d.ts +369 -0
- package/dist/types/commonTypes.js +37 -0
- package/dist/types/libFunctionTypes.d.ts +695 -0
- package/dist/types/libFunctionTypes.js +11 -0
- package/dist/types/socketMessageTypes.d.ts +952 -0
- package/dist/types/socketMessageTypes.js +50 -0
- package/dist/usermessage.d.ts +70 -0
- package/dist/usermessage.js +123 -0
- package/package.json +49 -0
package/README.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# CodeBolt Agent Utils
|
|
2
|
+
|
|
3
|
+
A TypeScript library providing utilities for building and managing AI agents with CodeBolt. This package extracts the agent functionality from the main CodeBolt library into a focused, reusable package.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Agent Class**: Core agent functionality for managing conversations with LLMs
|
|
8
|
+
- **Message Builders**: Utilities for building user messages, system prompts, and task instructions
|
|
9
|
+
- **Prompt Management**: Advanced prompt building and management capabilities
|
|
10
|
+
- **LLM Output Handling**: Processing and managing LLM responses and tool executions
|
|
11
|
+
- **Follow-up Questions**: Generate contextual follow-up questions for conversations
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @codebolt/agent-utils
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
### Basic Agent Setup
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import { Agent, SystemPrompt, TaskInstruction } from '@codebolt/agent-utils';
|
|
25
|
+
|
|
26
|
+
// Create a system prompt
|
|
27
|
+
const systemPrompt = new SystemPrompt();
|
|
28
|
+
await systemPrompt.loadPrompt('./prompts/system.yaml');
|
|
29
|
+
|
|
30
|
+
// Create a task instruction
|
|
31
|
+
const taskInstruction = new TaskInstruction();
|
|
32
|
+
await taskInstruction.loadInstruction('./tasks/coding-task.yaml');
|
|
33
|
+
|
|
34
|
+
// Initialize agent
|
|
35
|
+
const agent = new Agent([], systemPrompt);
|
|
36
|
+
|
|
37
|
+
// Run the agent on a task
|
|
38
|
+
const result = await agent.runAgent(taskInstruction);
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Building User Messages
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
44
|
+
import { UserMessage } from '@codebolt/agent-utils';
|
|
45
|
+
|
|
46
|
+
const userMessage = new UserMessage();
|
|
47
|
+
await userMessage.addMessage("Please help me with my code");
|
|
48
|
+
await userMessage.addFileContent("./src/main.ts");
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Advanced Prompt Building
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
import { InitialPromptBuilder } from '@codebolt/agent-utils';
|
|
55
|
+
|
|
56
|
+
const promptBuilder = new InitialPromptBuilder("Fix the bug in my application");
|
|
57
|
+
promptBuilder
|
|
58
|
+
.addSystemInstructions("You are a helpful coding assistant")
|
|
59
|
+
.addFile("./src/problematic-file.ts")
|
|
60
|
+
.addTaskDetails("Find and fix the TypeScript compilation errors");
|
|
61
|
+
|
|
62
|
+
const prompt = await promptBuilder.build();
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### LLM Output Handling
|
|
66
|
+
|
|
67
|
+
```typescript
|
|
68
|
+
import { LLMOutputHandler } from '@codebolt/agent-utils';
|
|
69
|
+
|
|
70
|
+
const outputHandler = new LLMOutputHandler();
|
|
71
|
+
const result = await outputHandler.processLLMResponse(llmResponse, tools);
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## API Reference
|
|
75
|
+
|
|
76
|
+
### Classes
|
|
77
|
+
|
|
78
|
+
- `Agent` - Core agent for managing LLM conversations and tool executions
|
|
79
|
+
- `UserMessage` - Builder for user messages with file content support
|
|
80
|
+
- `SystemPrompt` - Management of system prompts from YAML files
|
|
81
|
+
- `TaskInstruction` - Handling of task instructions and metadata
|
|
82
|
+
- `InitialPromptBuilder` - Fluent interface for building complex prompts
|
|
83
|
+
- `FollowUpPromptBuilder` - Generate follow-up questions for conversations
|
|
84
|
+
- `LLMOutputHandler` - Process LLM responses and handle tool executions
|
|
85
|
+
|
|
86
|
+
### Types
|
|
87
|
+
|
|
88
|
+
The package exports comprehensive TypeScript types for all interfaces, including:
|
|
89
|
+
- `Message`, `ToolResult`, `ToolDetails`
|
|
90
|
+
- `OpenAIMessage`, `OpenAITool`, `ConversationEntry`
|
|
91
|
+
- `UserMessageContent`, `CodeboltAPI`
|
|
92
|
+
- `MCPTool`, `InitialUserMessage`
|
|
93
|
+
|
|
94
|
+
## Dependencies
|
|
95
|
+
|
|
96
|
+
This package depends on `@codebolt/codeboltjs` for core functionality like file system operations, LLM communication, and tool execution.
|
|
97
|
+
|
|
98
|
+
## Development
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
# Install dependencies
|
|
102
|
+
npm install
|
|
103
|
+
|
|
104
|
+
# Build the project
|
|
105
|
+
npm run build
|
|
106
|
+
|
|
107
|
+
# Run in development mode
|
|
108
|
+
npm run dev
|
|
109
|
+
|
|
110
|
+
# Clean build artifacts
|
|
111
|
+
npm run clean
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
MIT
|
|
117
|
+
|
|
118
|
+
## Contributing
|
|
119
|
+
|
|
120
|
+
Please see the main CodeBolt repository for contribution guidelines.
|
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { SystemPrompt } from "./systemprompt";
|
|
2
|
+
import { TaskInstruction } from "./taskInstruction";
|
|
3
|
+
/**
|
|
4
|
+
* Agent class that manages conversations with LLMs and tool executions.
|
|
5
|
+
* Handles the conversation flow, tool calls, and task completions.
|
|
6
|
+
*/
|
|
7
|
+
declare class Agent {
|
|
8
|
+
/** Available tools for the agent to use */
|
|
9
|
+
private tools;
|
|
10
|
+
/** Full conversation history for API calls */
|
|
11
|
+
private apiConversationHistory;
|
|
12
|
+
/** Maximum number of conversation turns (0 means unlimited) */
|
|
13
|
+
private maxRun;
|
|
14
|
+
/** System prompt that provides instructions to the model */
|
|
15
|
+
private systemPrompt;
|
|
16
|
+
/** Messages from the user */
|
|
17
|
+
private userMessage;
|
|
18
|
+
/** The next user message to be added to the conversation */
|
|
19
|
+
private nextUserMessage;
|
|
20
|
+
/**
|
|
21
|
+
* Creates a new Agent instance.
|
|
22
|
+
*
|
|
23
|
+
* @param tools - The tools available to the agent
|
|
24
|
+
* @param systemPrompt - The system prompt providing instructions to the LLM
|
|
25
|
+
* @param maxRun - Maximum number of conversation turns (0 means unlimited)
|
|
26
|
+
*/
|
|
27
|
+
constructor(tools: any | undefined, systemPrompt: SystemPrompt, maxRun?: number);
|
|
28
|
+
/**
|
|
29
|
+
* Runs the agent on a specific task until completion or max runs reached.
|
|
30
|
+
*
|
|
31
|
+
* @param task - The task instruction to be executed
|
|
32
|
+
* @param successCondition - Optional function to determine if the task is successful
|
|
33
|
+
* @returns Promise with success status, error (if any), and the last assistant message
|
|
34
|
+
*/
|
|
35
|
+
run(task: TaskInstruction, successCondition?: () => boolean): Promise<{
|
|
36
|
+
success: boolean;
|
|
37
|
+
error: string | null;
|
|
38
|
+
message: string | null;
|
|
39
|
+
}>;
|
|
40
|
+
/**
|
|
41
|
+
* Attempts to make a request to the LLM with conversation history and tools.
|
|
42
|
+
*
|
|
43
|
+
* @param apiConversationHistory - The current conversation history
|
|
44
|
+
* @param tools - The tools available to the LLM
|
|
45
|
+
* @returns Promise with the LLM response
|
|
46
|
+
*/
|
|
47
|
+
private attemptLlmRequest;
|
|
48
|
+
/**
|
|
49
|
+
* Executes a tool with given name and input.
|
|
50
|
+
*
|
|
51
|
+
* @param toolName - The name of the tool to execute
|
|
52
|
+
* @param toolInput - The input parameters for the tool
|
|
53
|
+
* @returns Promise with tuple [userRejected, result]
|
|
54
|
+
*/
|
|
55
|
+
private executeTool;
|
|
56
|
+
/**
|
|
57
|
+
* Starts a sub-agent to handle a specific task.
|
|
58
|
+
*
|
|
59
|
+
* @param agentName - The name of the sub-agent to start
|
|
60
|
+
* @param params - Parameters for the sub-agent
|
|
61
|
+
* @returns Promise with tuple [userRejected, result]
|
|
62
|
+
*/
|
|
63
|
+
private startSubAgent;
|
|
64
|
+
/**
|
|
65
|
+
* Extracts tool details from a tool call object.
|
|
66
|
+
*
|
|
67
|
+
* @param tool - The tool call object from the LLM response
|
|
68
|
+
* @returns ToolDetails object with name, input, and ID
|
|
69
|
+
*/
|
|
70
|
+
private getToolDetail;
|
|
71
|
+
/**
|
|
72
|
+
* Creates a tool result object from the tool execution response.
|
|
73
|
+
*
|
|
74
|
+
* @param tool_call_id - The ID of the tool call
|
|
75
|
+
* @param content - The content returned by the tool
|
|
76
|
+
* @returns ToolResult object
|
|
77
|
+
*/
|
|
78
|
+
private getToolResult;
|
|
79
|
+
/**
|
|
80
|
+
* Fallback method for API requests in case of failures.
|
|
81
|
+
*
|
|
82
|
+
* @throws Error API request fallback not implemented
|
|
83
|
+
*/
|
|
84
|
+
private attemptApiRequest;
|
|
85
|
+
}
|
|
86
|
+
export { Agent };
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
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.Agent = void 0;
|
|
7
|
+
const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
|
|
8
|
+
const { chat, mcp, llm, agent: codeboltAgent } = codeboltjs_1.default;
|
|
9
|
+
// All interfaces moved to libFunctionTypes.ts
|
|
10
|
+
/**
|
|
11
|
+
* Agent class that manages conversations with LLMs and tool executions.
|
|
12
|
+
* Handles the conversation flow, tool calls, and task completions.
|
|
13
|
+
*/
|
|
14
|
+
class Agent {
|
|
15
|
+
/**
|
|
16
|
+
* Creates a new Agent instance.
|
|
17
|
+
*
|
|
18
|
+
* @param tools - The tools available to the agent
|
|
19
|
+
* @param systemPrompt - The system prompt providing instructions to the LLM
|
|
20
|
+
* @param maxRun - Maximum number of conversation turns (0 means unlimited)
|
|
21
|
+
*/
|
|
22
|
+
constructor(tools = [], systemPrompt, maxRun = 0) {
|
|
23
|
+
this.tools = tools;
|
|
24
|
+
this.userMessage = [];
|
|
25
|
+
this.apiConversationHistory = [];
|
|
26
|
+
this.maxRun = maxRun;
|
|
27
|
+
this.systemPrompt = systemPrompt;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Runs the agent on a specific task until completion or max runs reached.
|
|
31
|
+
*
|
|
32
|
+
* @param task - The task instruction to be executed
|
|
33
|
+
* @param successCondition - Optional function to determine if the task is successful
|
|
34
|
+
* @returns Promise with success status, error (if any), and the last assistant message
|
|
35
|
+
*/
|
|
36
|
+
async run(task, successCondition = () => true) {
|
|
37
|
+
var _a, _b;
|
|
38
|
+
let mentaionedMCPSTool = await task.userMessage.getMentionedMcpsTools();
|
|
39
|
+
this.tools = [
|
|
40
|
+
...this.tools,
|
|
41
|
+
...mentaionedMCPSTool || [],
|
|
42
|
+
];
|
|
43
|
+
let mentionedAgents = await task.userMessage.getMentionedAgents();
|
|
44
|
+
// Transform agents into tool format
|
|
45
|
+
const agentTools = mentionedAgents.map(agent => {
|
|
46
|
+
return {
|
|
47
|
+
type: "function",
|
|
48
|
+
function: {
|
|
49
|
+
name: `subagent--${agent.unique_id}`,
|
|
50
|
+
description: agent.longDescription || agent.description,
|
|
51
|
+
parameters: {
|
|
52
|
+
type: "object",
|
|
53
|
+
properties: {
|
|
54
|
+
task: {
|
|
55
|
+
type: "string",
|
|
56
|
+
description: "The task to be executed by the tool."
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
required: ["task"]
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
this.tools = this.tools.concat(agentTools);
|
|
65
|
+
let completed = false;
|
|
66
|
+
let userMessages = await task.toPrompt();
|
|
67
|
+
this.apiConversationHistory.push({ role: "user", content: userMessages });
|
|
68
|
+
let runcomplete = 0;
|
|
69
|
+
while (!completed && (runcomplete <= this.maxRun || this.maxRun === 0)) {
|
|
70
|
+
try {
|
|
71
|
+
runcomplete++;
|
|
72
|
+
const response = await this.attemptLlmRequest(this.apiConversationHistory, this.tools);
|
|
73
|
+
let isMessagePresentinReply = false;
|
|
74
|
+
for (const contentBlock of response.choices) {
|
|
75
|
+
if (contentBlock.message) {
|
|
76
|
+
isMessagePresentinReply = true;
|
|
77
|
+
this.apiConversationHistory.push(contentBlock.message);
|
|
78
|
+
if (contentBlock.message.content != null) {
|
|
79
|
+
await chat.sendMessage(contentBlock.message.content, {});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (!isMessagePresentinReply) {
|
|
84
|
+
this.apiConversationHistory.push({
|
|
85
|
+
role: "assistant",
|
|
86
|
+
content: [{ type: "text", text: "Failure: I did not provide a response." }],
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
let toolResults = [];
|
|
91
|
+
let taskCompletedBlock;
|
|
92
|
+
let userRejectedToolUse = false;
|
|
93
|
+
const contentBlock = response.choices[0];
|
|
94
|
+
if ((_a = contentBlock.message) === null || _a === void 0 ? void 0 : _a.tool_calls) {
|
|
95
|
+
for (const tool of contentBlock.message.tool_calls) {
|
|
96
|
+
try {
|
|
97
|
+
const { toolInput, toolName, toolUseId } = this.getToolDetail(tool);
|
|
98
|
+
if (!userRejectedToolUse) {
|
|
99
|
+
if (toolName.includes("attempt_completion")) {
|
|
100
|
+
taskCompletedBlock = tool;
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
let [serverName] = toolName.replace('--', ':').split(':');
|
|
104
|
+
if (serverName == 'subagent') {
|
|
105
|
+
const agentResponse = await codeboltAgent.startAgent(toolName.replace("subagent--", ''), toolInput.task);
|
|
106
|
+
const [didUserReject, result] = [false, "tool result is successful"];
|
|
107
|
+
let toolResult = this.getToolResult(toolUseId, result);
|
|
108
|
+
toolResults.push({
|
|
109
|
+
role: "tool",
|
|
110
|
+
tool_call_id: toolResult.tool_call_id,
|
|
111
|
+
content: toolResult.content,
|
|
112
|
+
});
|
|
113
|
+
if (toolResult.userMessage) {
|
|
114
|
+
this.nextUserMessage = {
|
|
115
|
+
role: "user",
|
|
116
|
+
content: toolResult.userMessage
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
if (didUserReject) {
|
|
120
|
+
userRejectedToolUse = true;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
const [didUserReject, result] = await this.executeTool(toolName, toolInput);
|
|
125
|
+
// toolResults.push(this.getToolResult(toolUseId, result));
|
|
126
|
+
let toolResult = this.getToolResult(toolUseId, result);
|
|
127
|
+
toolResults.push({
|
|
128
|
+
role: "tool",
|
|
129
|
+
tool_call_id: toolResult.tool_call_id,
|
|
130
|
+
content: toolResult.content,
|
|
131
|
+
});
|
|
132
|
+
if (toolResult.userMessage) {
|
|
133
|
+
this.nextUserMessage = {
|
|
134
|
+
role: "user",
|
|
135
|
+
content: toolResult.userMessage
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
if (didUserReject) {
|
|
139
|
+
userRejectedToolUse = true;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
let toolResult = this.getToolResult(toolUseId, "Skipping tool execution due to previous tool user rejection.");
|
|
146
|
+
toolResults.push({
|
|
147
|
+
role: "tool",
|
|
148
|
+
tool_call_id: toolResult.tool_call_id,
|
|
149
|
+
content: toolResult.content,
|
|
150
|
+
});
|
|
151
|
+
if (toolResult.userMessage) {
|
|
152
|
+
this.nextUserMessage = {
|
|
153
|
+
role: "user",
|
|
154
|
+
content: toolResult.userMessage
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
toolResults.push({
|
|
161
|
+
role: "tool",
|
|
162
|
+
tool_call_id: tool.id,
|
|
163
|
+
content: `please provide valid json string for tool.function.arguments String(error)`,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (taskCompletedBlock) {
|
|
169
|
+
let [_, result] = await this.executeTool(taskCompletedBlock.function.name, JSON.parse(taskCompletedBlock.function.arguments || "{}"));
|
|
170
|
+
if (result === "") {
|
|
171
|
+
completed = true;
|
|
172
|
+
result = "The user is satisfied with the result.";
|
|
173
|
+
}
|
|
174
|
+
let toolResult = this.getToolResult(taskCompletedBlock.id, result);
|
|
175
|
+
toolResults.push({
|
|
176
|
+
role: "tool",
|
|
177
|
+
tool_call_id: toolResult.tool_call_id,
|
|
178
|
+
content: toolResult.content,
|
|
179
|
+
});
|
|
180
|
+
if (toolResult.userMessage) {
|
|
181
|
+
this.nextUserMessage = {
|
|
182
|
+
role: "user",
|
|
183
|
+
content: toolResult.userMessage
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
this.apiConversationHistory.push(...toolResults);
|
|
188
|
+
if (this.nextUserMessage) {
|
|
189
|
+
this.apiConversationHistory.push(this.nextUserMessage);
|
|
190
|
+
}
|
|
191
|
+
let nextUserMessage = toolResults;
|
|
192
|
+
if (toolResults.length === 0) {
|
|
193
|
+
nextUserMessage = [{
|
|
194
|
+
role: "user",
|
|
195
|
+
content: [{
|
|
196
|
+
type: "text",
|
|
197
|
+
text: "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.)"
|
|
198
|
+
}]
|
|
199
|
+
}];
|
|
200
|
+
if (nextUserMessage) {
|
|
201
|
+
this.apiConversationHistory.push(nextUserMessage[0]);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
console.error("Error in agent tool call:", error);
|
|
207
|
+
return { success: false, error: error instanceof Error ? error.message : String(error), message: null };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
console.error("Error in agent tool call:", error);
|
|
212
|
+
return { success: false, error: error instanceof Error ? error.message : String(error), message: null };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
success: completed,
|
|
217
|
+
error: null,
|
|
218
|
+
message: ((_b = this.apiConversationHistory
|
|
219
|
+
.filter(msg => msg.role === 'assistant')
|
|
220
|
+
.pop()) === null || _b === void 0 ? void 0 : _b.content) || ''
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Attempts to make a request to the LLM with conversation history and tools.
|
|
225
|
+
*
|
|
226
|
+
* @param apiConversationHistory - The current conversation history
|
|
227
|
+
* @param tools - The tools available to the LLM
|
|
228
|
+
* @returns Promise with the LLM response
|
|
229
|
+
*/
|
|
230
|
+
async attemptLlmRequest(apiConversationHistory, tools) {
|
|
231
|
+
try {
|
|
232
|
+
let systemPrompt = await this.systemPrompt.toPromptText();
|
|
233
|
+
const aiMessages = [
|
|
234
|
+
{ role: "system", content: systemPrompt },
|
|
235
|
+
...apiConversationHistory,
|
|
236
|
+
];
|
|
237
|
+
const createParams = {
|
|
238
|
+
full: true,
|
|
239
|
+
messages: aiMessages,
|
|
240
|
+
tools: tools,
|
|
241
|
+
tool_choice: "auto",
|
|
242
|
+
};
|
|
243
|
+
//@ts-ignore
|
|
244
|
+
const { completion } = await llm.inference(createParams);
|
|
245
|
+
return completion;
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
return this.attemptApiRequest();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Executes a tool with given name and input.
|
|
253
|
+
*
|
|
254
|
+
* @param toolName - The name of the tool to execute
|
|
255
|
+
* @param toolInput - The input parameters for the tool
|
|
256
|
+
* @returns Promise with tuple [userRejected, result]
|
|
257
|
+
*/
|
|
258
|
+
async executeTool(toolName, toolInput) {
|
|
259
|
+
//codebolttools--readfile
|
|
260
|
+
const [toolboxName, actualToolName] = toolName.split('--');
|
|
261
|
+
console.log("Toolbox name: ", toolboxName, "Actual tool name: ", actualToolName);
|
|
262
|
+
const { data } = await mcp.executeTool(toolboxName, actualToolName, toolInput);
|
|
263
|
+
console.log("Tool result: ", data);
|
|
264
|
+
return data;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Starts a sub-agent to handle a specific task.
|
|
268
|
+
*
|
|
269
|
+
* @param agentName - The name of the sub-agent to start
|
|
270
|
+
* @param params - Parameters for the sub-agent
|
|
271
|
+
* @returns Promise with tuple [userRejected, result]
|
|
272
|
+
*/
|
|
273
|
+
async startSubAgent(agentName, params) {
|
|
274
|
+
return [false, await codeboltAgent.startAgent(agentName, params.task)];
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Extracts tool details from a tool call object.
|
|
278
|
+
*
|
|
279
|
+
* @param tool - The tool call object from the LLM response
|
|
280
|
+
* @returns ToolDetails object with name, input, and ID
|
|
281
|
+
*/
|
|
282
|
+
getToolDetail(tool) {
|
|
283
|
+
return {
|
|
284
|
+
toolName: tool.function.name,
|
|
285
|
+
toolInput: JSON.parse(tool.function.arguments || "{}"),
|
|
286
|
+
toolUseId: tool.id
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Creates a tool result object from the tool execution response.
|
|
291
|
+
*
|
|
292
|
+
* @param tool_call_id - The ID of the tool call
|
|
293
|
+
* @param content - The content returned by the tool
|
|
294
|
+
* @returns ToolResult object
|
|
295
|
+
*/
|
|
296
|
+
getToolResult(tool_call_id, content) {
|
|
297
|
+
let userMessage = undefined;
|
|
298
|
+
try {
|
|
299
|
+
let parsed = JSON.parse(content);
|
|
300
|
+
if (parsed.payload && parsed.payload.content) {
|
|
301
|
+
content = `The browser action has been executed. The screenshot have been captured for your analysis. The tool response is provided in the next user message`;
|
|
302
|
+
// this.apiConversationHistory.push()
|
|
303
|
+
userMessage = parsed.payload.content;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
role: "tool",
|
|
310
|
+
tool_call_id,
|
|
311
|
+
content,
|
|
312
|
+
userMessage
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Fallback method for API requests in case of failures.
|
|
317
|
+
*
|
|
318
|
+
* @throws Error API request fallback not implemented
|
|
319
|
+
*/
|
|
320
|
+
attemptApiRequest() {
|
|
321
|
+
throw new Error("API request fallback not implemented");
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
exports.Agent = Agent;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { OpenAIMessage, OpenAITool, ToolResult, CodeboltAPI } from "./types/libFunctionTypes";
|
|
2
|
+
/**
|
|
3
|
+
* Builds follow-up prompts for continuing conversations with tool results.
|
|
4
|
+
* Manages conversation history and summarization when conversations get too long.
|
|
5
|
+
*/
|
|
6
|
+
declare class FollowUpPromptBuilder {
|
|
7
|
+
/** Previous conversation messages */
|
|
8
|
+
private previousConversation;
|
|
9
|
+
/** Tool results to add to the conversation */
|
|
10
|
+
private toolResults;
|
|
11
|
+
/** Available tools for the conversation */
|
|
12
|
+
private tools;
|
|
13
|
+
/** The last LLM response, if available */
|
|
14
|
+
private llmResponse?;
|
|
15
|
+
/** Maximum conversation length before summarization */
|
|
16
|
+
private maxConversationLength;
|
|
17
|
+
/** Whether to force summarization */
|
|
18
|
+
private forceSummarization;
|
|
19
|
+
/** Codebolt API instance */
|
|
20
|
+
private codebolt?;
|
|
21
|
+
/**
|
|
22
|
+
* Creates a new FollowUpQuestionBuilder instance.
|
|
23
|
+
*
|
|
24
|
+
* @param codebolt - Optional codebolt API instance
|
|
25
|
+
*/
|
|
26
|
+
constructor(codebolt?: CodeboltAPI);
|
|
27
|
+
/**
|
|
28
|
+
* Adds the previous conversation to the builder.
|
|
29
|
+
*
|
|
30
|
+
* @param previousPrompt - The previous prompt object containing messages and tools
|
|
31
|
+
* @returns The FollowUpQuestionBuilder instance for chaining
|
|
32
|
+
*/
|
|
33
|
+
addPreviousConversation(previousPrompt: {
|
|
34
|
+
messages: OpenAIMessage[];
|
|
35
|
+
tools: OpenAITool[];
|
|
36
|
+
tool_choice?: string;
|
|
37
|
+
}, llmResponse: {
|
|
38
|
+
completion: any;
|
|
39
|
+
}): this;
|
|
40
|
+
addLLMResponseToConverstaion(llmResponse: {
|
|
41
|
+
completion: any;
|
|
42
|
+
}): this;
|
|
43
|
+
/**
|
|
44
|
+
* Adds tool execution results to the conversation.
|
|
45
|
+
*
|
|
46
|
+
* @param toolResults - Array of tool execution results
|
|
47
|
+
* @returns The FollowUpQuestionBuilder instance for chaining
|
|
48
|
+
*/
|
|
49
|
+
addToolResult(toolResults: ToolResult[]): this;
|
|
50
|
+
/**
|
|
51
|
+
* Checks if the conversation is too long and sets up summarization with custom max length.
|
|
52
|
+
*
|
|
53
|
+
* @param maxLength - Maximum number of messages before summarization
|
|
54
|
+
* @returns The FollowUpQuestionBuilder instance for chaining
|
|
55
|
+
*/
|
|
56
|
+
checkAndSummarizeConversationIfLong(maxLength: number): this;
|
|
57
|
+
/**
|
|
58
|
+
* Performs conversation summarization if needed.
|
|
59
|
+
*
|
|
60
|
+
* @returns Promise that resolves to the summarized messages
|
|
61
|
+
*/
|
|
62
|
+
private performSummarization;
|
|
63
|
+
/**
|
|
64
|
+
* Builds the follow-up conversation prompt with tool results.
|
|
65
|
+
*
|
|
66
|
+
* @returns Promise that resolves to the conversation prompt object
|
|
67
|
+
*/
|
|
68
|
+
build(): Promise<{
|
|
69
|
+
messages: OpenAIMessage[];
|
|
70
|
+
tools: OpenAITool[];
|
|
71
|
+
tool_choice: "auto";
|
|
72
|
+
full: boolean;
|
|
73
|
+
}>;
|
|
74
|
+
}
|
|
75
|
+
export { FollowUpPromptBuilder };
|