-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm_tool.ts
More file actions
388 lines (368 loc) · 11.2 KB
/
Copy pathllm_tool.ts
File metadata and controls
388 lines (368 loc) · 11.2 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/**
* Core LLM Tool implementation module for the BB Tools Framework.
* Provides the base class and types for creating tools that can be used
* by Language Learning Models (LLMs) to interact with projects and conversations.
*
* @module
*/
import type { JSX } from 'preact';
import type { JSONSchema4 } from 'json-schema';
import { Ajv } from 'ajv';
import { TOOL_STYLES_BROWSER, TOOL_STYLES_CONSOLE, TOOL_TAGS_BROWSER } from './llm_tool_tags.tsx';
import type { IConversationInteraction } from './interaction.ts';
import type { IProjectEditor } from './project_editor.ts';
import type { LLMAnswerToolUse, LLMMessageContentPart, LLMMessageContentParts } from './message.ts';
/**
* JSON Schema definition for tool input validation.
* Used to ensure tool inputs match expected format.
*
* @example
* ```ts
* const schema: LLMToolInputSchema = {
* type: 'object',
* properties: {
* query: { type: 'string' },
* limit: { type: 'number' }
* },
* required: ['query']
* };
* ```
*/
export type LLMToolInputSchema = JSONSchema4;
/**
* Valid content types that can be returned as tool results.
* Can be plain text, a single content part, or multiple content parts.
*
* @example
* ```ts
* const result: LLMToolRunResultContent = [
* { type: 'text', text: 'Operation completed' },
* { type: 'image', source: { type: 'base64', media_type: 'image/png', data: '...' } }
* ];
* ```
*/
export type LLMToolRunResultContent =
| string
| LLMMessageContentPart
| LLMMessageContentParts;
export type LLMToolRunToolResponse = string;
export interface LLMToolRunBbResponseData {
data: unknown;
}
export type LLMToolRunBbResponse = LLMToolRunBbResponseData | string;
/**
* Complete result of a tool execution.
* Includes tool-specific results, response text, and optional callback.
*
* @example
* ```ts
* const result: LLMToolRunResult = {
* toolResults: { type: 'text', text: 'Found 3 files' },
* toolResponse: 'Successfully searched files',
* bbResponse: { data: { fileCount: 3 } }
* };
* ```
*/
export interface LLMToolRunResult {
toolResults: LLMToolRunResultContent;
toolResponse: LLMToolRunToolResponse;
bbResponse: LLMToolRunBbResponse;
finalizeCallback?: (messageId: string) => void;
}
/**
* Feature flags describing a tool's capabilities and requirements.
* Used to inform the LLM about how the tool operates.
*
* @example
* ```ts
* const features: LLMToolFeatures = {
* mutates: true, // Tool modifies resources
* stateful: false, // Tool doesn't maintain state
* async: true, // Tool runs asynchronously
* idempotent: true, // Multiple runs produce same result
* resourceIntensive: false, // Tool is lightweight
* requiresNetwork: false // Tool works offline
* };
* ```
*/
export interface LLMToolFeatures {
mutates?: boolean; // Whether tool modifies resources
stateful?: boolean; // Whether tool maintains state
async?: boolean; // Whether tool runs asynchronously
idempotent?: boolean; // Whether multiple runs produce same result
resourceIntensive?: boolean; // Whether tool needs significant resources
requiresNetwork?: boolean; // Whether tool needs internet access
}
export type LLMToolConfig = Record<string, unknown>;
export type LLMToolFormatterDestination = 'console' | 'browser';
export type LLMToolUseInputFormatter = (
toolInput: LLMToolInputSchema,
format: LLMToolFormatterDestination,
) => string;
export type LLMToolRunResultFormatter = (
resultContent: unknown,
format: LLMToolFormatterDestination,
) => string;
/**
* Formatted result structure for destination-specific output.
* Used by both browser and console formatters to provide consistent structure.
*
* @example
* ```ts
* // Browser destination result
* const browserResult: LLMToolLogEntryFormattedResult = {
* title: <h2>Search Results</h2>,
* subtitle: <h3>Found 3 matches</h3>,
* content: <div>...</div>,
* preview: <span>3 matches found</span>
* };
*
* // Console destination result
* const consoleResult: LLMToolLogEntryFormattedResult = {
* title: 'Search Results',
* subtitle: 'Found 3 matches',
* content: '...',
* preview: '3 matches found'
* };
* ```
*/
export interface LLMToolLogEntryFormattedResult {
title: string | JSX.Element;
subtitle?: string | JSX.Element;
content: string | JSX.Element;
preview: string | JSX.Element;
}
export interface LLMToolMetadata {
toolId: string;
name: string;
version: string;
protocolType: 'bb' | 'mcp';
loadedFrom: 'builtin' | 'plugin' | 'mcp';
author: string;
license: string;
description: string;
purpose: string;
path?: string; // is set by code, not part of manifest
toolSets?: string | string[]; //defaults to 'core'
category?: string | string[];
capabilities?: string | string[];
enabled?: boolean; //defaults to true
mutates?: boolean; //defaults to true
deprecated?: boolean; //defaults to false
replacedBy?: string; //when deprecated is true
error?: string;
config?: unknown;
mcpData?: Record<string, unknown>; //LLMToolMCPConfig
pluginData?: {
pluginName: string;
version: string;
author: string;
description: string;
license: string;
bbVersion: string;
};
examples?: Array<{ description: string; input: unknown }>;
}
/**
* Base class for all LLM tools in the BB Tools Framework.
* Provides core functionality for input validation, execution, and result formatting.
*
* @example
* ```ts
* class SearchTool extends LLMTool {
* get inputSchema() {
* return {
* type: 'object',
* properties: {
* query: { type: 'string' }
* },
* required: ['query']
* };
* }
*
* async runTool(interaction, toolUse, projectEditor) {
* // Tool implementation
* return {
* toolResults: { type: 'text', text: 'Results...' },
* toolResponse: 'Search completed',
* bbResponse: { data: { matches: [] } }
* };
* }
*
* formatLogEntryToolUse(toolInput, format) {
* return {
* title: 'Search',
* content: `Searching for: ${toolInput.query}`,
* preview: 'Search operation'
* };
* }
*
* formatLogEntryToolResult(resultContent, format) {
* return {
* title: 'Search Results',
* content: resultContent,
* preview: 'Found matches'
* };
* }
* }
* ```
*/
abstract class LLMTool {
public toolId: string;
public features: LLMToolFeatures = {};
constructor(
public name: string,
public description: string,
public toolConfig: LLMToolConfig,
public metadata: LLMToolMetadata,
) {
this.toolId = metadata.toolId || `${metadata.loadedFrom || 'builtin'}:${metadata.name}`;
this.features = { mutates: metadata.mutates || false };
//logger.info(`LLMTool: Constructing tool ${name}`);
}
// deno-lint-ignore require-await
public async init(): Promise<LLMTool> {
return this;
}
/**
* JSON Schema defining the expected input format for the tool.
* Must be implemented by each tool to enable input validation.
*
* @example
* ```ts
* get inputSchema() {
* return {
* type: 'object',
* properties: {
* query: { type: 'string', description: 'Search query' }
* },
* required: ['query']
* };
* }
* ```
*/
abstract get inputSchema(): LLMToolInputSchema;
/**
* Validates tool input against the defined schema.
* Uses AJV for JSON Schema validation.
*
* @param input - The input to validate
* @returns True if input matches schema, false otherwise
*
* @example
* ```ts
* const isValid = tool.validateInput({ query: 'search term' });
* if (!isValid) {
* throw new Error('Invalid input');
* }
* ```
*/
validateInput(input: unknown): boolean {
const ajv = new Ajv({ code: { esm: true } });
const validate = ajv.compile(this.inputSchema);
return validate(input) as boolean;
}
/**
* Executes the tool's main functionality.
* Must be implemented by each tool to define its behavior.
*
* @param interaction - Conversation interaction context
* @param toolUse - Information about the current tool use
* @param projectEditor - Project editing capabilities
* @returns Promise resolving to the tool's execution results
*
* @example
* ```ts
* async runTool(interaction, toolUse, projectEditor) {
* const results = await performOperation(toolUse.toolInput);
* return {
* toolResults: { type: 'text', text: results },
* toolResponse: 'Operation completed',
* bbResponse: { data: results }
* };
* }
* ```
*/
abstract runTool(
interaction: IConversationInteraction,
toolUse: LLMAnswerToolUse,
projectEditor: IProjectEditor,
): Promise<LLMToolRunResult>;
/**
* Formats tool input for a specific destination (browser/console).
* Creates formatted representation of tool input parameters.
*
* @param toolInput - The validated input provided to the tool
* @param format - Target destination (console or browser)
* @returns Formatted structure for the destination
*
* @example Browser Destination
* ```tsx
* formatLogEntryToolUse(toolInput, 'browser') {
* return {
* title: <h2>Search Files</h2>,
* subtitle: <h3>Query: {toolInput.query}</h3>,
* content: <div>Searching project files...</div>,
* preview: <span>Search operation</span>
* };
* }
* ```
*
* @example Console Destination
* ```ts
* formatLogEntryToolUse(toolInput, 'console') {
* return {
* title: 'Search Files',
* subtitle: `Query: ${toolInput.query}`,
* content: 'Searching project files...',
* preview: 'Search operation'
* };
* }
* ```
*/
abstract formatLogEntryToolUse(
toolInput: LLMToolInputSchema,
format: LLMToolFormatterDestination,
): LLMToolLogEntryFormattedResult;
/**
* Formats tool results for a specific destination (browser/console).
* Creates formatted representation of operation outcomes.
*
* @param resultContent - The content returned by the tool
* @param format - Target destination (console or browser)
* @returns Formatted structure for the destination
*
* @example Browser Destination
* ```tsx
* formatLogEntryToolResult(resultContent, 'browser') {
* return {
* title: <h2>Search Results</h2>,
* subtitle: <h3>Found {resultContent.matches.length} matches</h3>,
* content: <div>{resultContent.matches.map(m => <div>{m}</div>)}</div>,
* preview: <span>Search completed</span>
* };
* }
* ```
*
* @example Console Destination
* ```ts
* formatLogEntryToolResult(resultContent, 'console') {
* return {
* title: 'Search Results',
* subtitle: `Found ${resultContent.matches.length} matches`,
* content: resultContent.matches.join('\n'),
* preview: 'Search completed'
* };
* }
* ```
*/
abstract formatLogEntryToolResult(
resultContent: unknown,
format: LLMToolFormatterDestination,
): LLMToolLogEntryFormattedResult;
// Style constants for tool output formatting
static readonly TOOL_TAGS_BROWSER = TOOL_TAGS_BROWSER;
static readonly TOOL_STYLES_BROWSER = TOOL_STYLES_BROWSER;
static readonly TOOL_STYLES_CONSOLE = TOOL_STYLES_CONSOLE;
}
export default LLMTool;