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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
|
# Dash Agent Tool Development Guide
**Table of Contents**
1. [Introduction: The Role and Potential of Tools](#1-introduction-the-role-and-potential-of-tools)
- Beyond Information Retrieval: Action and Creation
- The Agent as an Extension of the User within Dash
2. [Core Agent Architecture Deep Dive](#2-core-agent-architecture-deep-dive)
- The ReAct-Inspired Interaction Loop: Rationale and Flow
- XML Structure: Why XML? Parsing and LLM Guidance
- Stages (`<stage>`) and Roles (`role="..."`): Enforcing Order
- Message Management (`messages`, `interMessages`): Building Context
- State Handling: Agent's Internal State vs. Tool Statelessness
- Key Components Revisited (`Agent.ts`, `prompts.ts`, `BaseTool.ts`, Parsers)
- Role of `prompts.ts`: Template and Dynamic Content Injection
- Limits and Safeguards (`maxTurns`)
3. [Anatomy of a Dash Agent Tool (Detailed Breakdown)](#3-anatomy-of-a-dash-agent-tool-detailed-breakdown)
- The `BaseTool` Abstract Class: Foundation and Contract
- `ToolInfo`: Defining Identity and LLM Instructions
- `name`: Uniqueness and LLM Invocation Trigger
- `description`: The LLM's Primary Guide - _Dynamically Injected into Prompt_
- `parameterRules`: The Input Contract (In Depth)
- `citationRules`: Controlling Grounding in the Final Answer
- The `execute` Method: Heart of the Tool
- Asynchronous Nature (`async/await`)
- Receiving Arguments (`args: ParametersType<P>`)
- Performing the Core Logic (API calls, Dash functions)
- Returning `Observation[]`: The Output Contract (In Depth)
- The `inputValidator` Method: Handling Edge Cases
4. [The Agent-Tool Interaction Flow (Annotated XML Trace)](#4-the-agent-tool-interaction-flow-annotated-xml-trace)
- Detailed Step-by-Step with `Agent.ts` actions highlighted
5. [Step-by-Step Guide: Creating a New Tool](#5-step-by-step-guide-creating-a-new-tool)
- Step 1: Define Goal, Scope, Inputs, Outputs, Dash Interactions, Side Effects
- Step 2: Create the Tool Class File (Directory Structure)
- Step 3: Define Parameters (`parameterRules`) - Type Handling, Arrays
- Step 4: Define Tool Information (`ToolInfo`) - Crafting the _Crucial_ `description`
- Step 5: Implement `execute` - Defensive Coding, Using Injected Functions, Error Handling Pattern
- Step 6: Format Output (`Observation[]`) - Chunk Structure, `chunk_type`, IDs
- Step 7: Register Tool in `Agent.ts` - _This makes the tool available to the prompt_
- Step 8: Verify Prompt Integration (No Manual Editing Needed)
- Step 9: Testing Your Tool - Strategies and What to Look For
6. [Deep Dive: Advanced Concepts & Patterns](#6-deep-dive-advanced-concepts--patterns)
- Handling Complex Data Types (Arrays, Objects) in Parameters/Observations
- Binary Data Handling (e.g., Base64 in Chunks)
- Managing Long-Running Tasks (Beyond simple `await`)
- Tools Needing Dash Context (Passing `this` vs. specific functions)
- The Role of `chunk_id` and `chunk_type`
7. [Best Practices and Advanced Considerations](#7-best-practices-and-advanced-considerations)
- Error Handling & Reporting (Specific Error Chunks)
- Security Considerations (Input Sanitization, API Key Management, Output Filtering)
- Performance Optimization (Minimize `execute` workload)
- Idempotency: Designing for Retries
- Tool Granularity: Single Responsibility Principle
- Context Window Management (Concise Descriptions are Key)
- User Experience (Tool output clarity)
- Maintainability and Code Comments
8. [Debugging Strategies](#8-debugging-strategies)
- Console Logging within `execute`
- Inspecting `interMessages` in `Agent.ts`
- Testing Tool Logic Standalone
- Analyzing LLM Failures (Incorrect tool choice -> Check `description`, bad parameters)
9. [Example: `CreateDashNoteTool`](#9-example-createdashnotetool)
10. [Glossary of Key Terms](#10-glossary-of-key-terms)
11. [Conclusion](#11-conclusion)
---
## 1. Introduction: The Role and Potential of Tools
Welcome, Dash team member! This guide will walk you through creating new tools for the Dash Agent. The Agent is designed to interact with users, understand their queries, and leverage specialized **Tools** to perform actions or retrieve information that the core Large Language Model (LLM) cannot do on its own.
Tools extend the Agent's capabilities beyond simple conversation. They allow the Agent to:
- Interact with external APIs (e.g., web search, calculators, image generation).
- Access and process data specific to the user's Dash environment (e.g., querying document metadata, analyzing linked CSVs).
- Perform actions within Dash (e.g., creating new documents, adding links, modifying metadata).
By building new tools, you directly enhance the Agent's utility and integration within the Dash ecosystem.
### Beyond Information Retrieval: Action and Creation
While tools like `RAGTool` and `SearchTool` retrieve information, others _act_. `CalculateTool` performs computations, `ImageCreationTool` generates content, and importantly, tools like `DocumentMetadataTool` and your custom tools can **modify the Dash environment**, creating documents, adding links, or changing properties.
### The Agent as an Extension of the User within Dash
Think of the Agent, equipped with tools, as an intelligent assistant that can perform tasks _on behalf of the user_ directly within their Dash workspace. This deep integration is a key differentiator.
---
## 2. Core Agent Architecture Deep Dive
Understanding the "why" behind the architecture helps in tool development.
### The ReAct-Inspired Interaction Loop: Rationale and Flow
The Agent operates based on a loop inspired by the ReAct (Reason + Act) framework. The LLM alternates between:
- **Reasoning (`<thought>`):** Analyzing the query and deciding the next step.
- **Acting (`<action>`, `<action_input>`):** Selecting and preparing to use a tool, or formulating a final answer (`<answer>`).
- **Observing (`<observation>`):** Receiving the results from a tool execution.
This structure (Reason -> Act -> Observe -> Reason...) forces the LLM to break down complex tasks into manageable steps, making the process more reliable and auditable than letting the LLM generate a monolithic plan upfront.
### XML Structure: Why XML? Parsing and LLM Guidance
- **Why XML?** LLMs are generally adept at generating well-formed XML. XML's explicit start/end tags make parsing by `Agent.ts` (using libraries like `fast-xml-parser`) more robust and less prone to LLM "hallucinations" breaking the structure compared to formats like JSON in some complex scenarios.
- **LLM Guidance:** The strict XML schema defined in the system prompt provides clear guardrails for the LLM's output, constraining it to valid actions and formats.
### Stages (`<stage>`) and Roles (`role="..."`): Enforcing Order
The `<stage number="...">` ensures sequential processing. The `role` attribute indicates the source (e.g., `user`, `assistant`) and dictates control flow. `Agent.ts` _waits_ for a `user` (or `system-error-reporter`) stage after sending an `assistant` stage, enforcing the turn-based nature. The LLM is explicitly told only to generate `assistant` stages.
### Message Management (`messages`, `interMessages`): Building Context
- `messages`: The user-facing chat history (persisted in the Dash Doc `data` field).
- `interMessages`: The **internal, complete context** sent to the LLM for each turn. It includes the system prompt, user queries, _all intermediate thoughts, actions, rules, inputs, and observations_. This ensures the LLM has the full history of the current reasoning chain. It grows with each step in the loop.
### State Handling: Agent's Internal State vs. Tool Statelessness
- `Agent.ts` manages the conversational state (`interMessages`, current turn number, `processingInfo`, etc.).
- **Tools should be designed to be stateless.** They receive inputs via `args`, perform their action, and return results. Any persistent state relevant to the user's work should reside within Dash Docs/Fobs, accessible perhaps via tools like `DocumentMetadataTool` or specific functions passed to the tool.
### Key Components Revisited (`Agent.ts`, `prompts.ts`, `BaseTool.ts`, Parsers)
- `Agent.ts`: The central controller. Parses XML, validates actions, manages the loop, calls `tool.execute`, formats `Observation`s. Handles the streaming updates for the _final_ answer via `StreamedAnswerParser`. Holds the registry of available tools (`this.tools`).
- `prompts.ts` (`getReactPrompt`): Generates the system prompt for the LLM. It acts as a **template** defining the Agent's overall task, rules, and the required XML structure. Crucially, it **dynamically injects the list of available tools** (including their names and descriptions) based on the tools registered in the `Agent.ts` instance at runtime. **_You do not manually add tool descriptions here._**
- `BaseTool.ts`: The abstract class defining the _interface_ all tools must adhere to. Contains properties like `name` and `description` used by `getReactPrompt`.
- Parsers (`AnswerParser`, `StreamedAnswerParser`): Handle the final `<answer>` tag, extracting structured content, citations, etc., for UI display (`ChatBox.tsx`).
### Limits and Safeguards (`maxTurns`)
`Agent.ts` includes a `maxTurns` limit (default 30) to prevent infinite loops if the LLM gets stuck or fails to reach an `<answer>` stage.
---
## 3. Anatomy of a Dash Agent Tool (Detailed Breakdown)
All tools inherit from the abstract class `BaseTool`.
### The `BaseTool` Abstract Class: Foundation and Contract
- Located in `src/components/views/nodes/chatbot/agentsystem/tools/BaseTool.ts`.
- Generic `BaseTool<P extends ReadonlyArray<Parameter>>`: `P` represents the specific, readonly array of `Parameter` definitions for _your_ tool, ensuring type safety for the `args` in `execute`.
- Defines the public properties (`name`, `description`, `parameterRules`, `citationRules`) and the abstract `execute` method that all tools must implement.
### `ToolInfo`: Defining Identity and LLM Instructions
- A configuration object (`{ name: string; description: string; parameterRules: P; citationRules: string; }`) passed to the `BaseTool` constructor.
- `name: string`:
- The **unique identifier** for your tool (e.g., `dictionaryLookup`, `createDashNote`).
- Must match the key used when registering the tool in `Agent.ts`'s `this.tools` map.
- This is the string the LLM will output in the `<action>` tag to invoke your tool.
- Keep it concise and descriptive (camelCase recommended).
- `description: string`: The LLM's Primary Guide - _Dynamically Injected into Prompt_.
- This text is extracted from your `ToolInfo` object when `getReactPrompt` is called.
- It's **the text the LLM sees** to understand your tool's purpose and when to use it.
- **Crafting this is critical.** Make it extremely clear, concise, and accurate. Explicitly state:
- What the tool _does_.
- What _inputs_ it needs (briefly).
- What _output_ it provides.
- _Crucially_, under what circumstances the Agent should _choose_ this tool over others. (e.g., "Use this tool to create _new_ Dash notes, not for editing existing ones.")
- `parameterRules: P` (where `P extends ReadonlyArray<Parameter>`):
- The readonly array defining the **exact inputs** your `execute` method expects.
- Each element is a `Parameter` object (`{ name: string; type: 'string' | ... ; required: boolean; description: string; max_inputs?: number }`):
- `name`: Name of the parameter (e.g., `wordToDefine`, `noteContent`). Used as the key in the `args` object passed to `execute`.
- `type`: `'string' | 'number' | 'boolean' | 'string[]' | 'number[]' | 'boolean[]'`. `Agent.ts` uses this for basic validation and parsing (specifically for arrays).
- `required`: `true` if the LLM _must_ provide this parameter for the tool to function. `Agent.ts` checks this before calling `execute` (unless `inputValidator` overrides).
- `description`: Explanation of the parameter _for the LLM_. Guides the LLM on _what value_ to provide. Be specific (e.g., "The exact URL to scrape", "A search query suitable for web search").
- `max_inputs?`: Optional. For array types (`string[]`, etc.), suggests a limit to the LLM on the number of items to provide.
- `citationRules: string`:
- Instructions for the LLM on how to construct the `<citations>` block within the final `<answer>` tag _when information obtained from this specific tool is used_.
- Directly influences the grounding and verifiability of the Agent's final response.
- Be explicit about the format: "Cite using `<citation index="..." chunk_id="..." type="your_chunk_type">Optional text snippet</citation>`".
- Specify what goes into `chunk_id` (e.g., "Use the ID provided in the observation chunk"), `type` (a constant string representing your tool's output type), and whether the text snippet should be included (often empty for URLs, calculations).
- If no citation is appropriate (e.g., calculator, ephemeral action), state clearly: "No citation needed for this tool's output."
### The `execute` Method: Heart of the Tool
- `abstract execute(args: ParametersType<P>): Promise<Observation[]>;`
- **Asynchronous Nature (`async/await`):** Must be `async` because tool actions often involve I/O (network requests, database access via Dash functions, filesystem). Must return a `Promise`.
- **Receiving Arguments (`args: ParametersType<P>`):**
- Receives a single argument `args`. This object's keys are your defined parameter names (from `parameterRules`), and the values are those provided by the LLM in the `<action_input><inputs>` block.
- The type `ParametersType<P>` infers the structure of `args` based on your specific `parameterRules` definition (`P`), providing TypeScript type safety.
- `Agent.ts` performs basic validation (required fields) and type coercion (for arrays) before calling `execute`. However, **always perform defensive checks** within `execute` (e.g., check if required args are truly present and not empty strings, check types if crucial).
- **Performing the Core Logic:** This is where your tool does its work. Examples:
- Call external APIs (using `axios`, `fetch`, or specific SDKs).
- Call Dash functions passed via the constructor (e.g., `this._createDocInDash(...)`, `this._addLinkedUrlDoc(...)`).
- Perform calculations or data transformations.
- Interact with other backend systems if necessary.
- **Returning `Observation[]`: The Output Contract (In Depth)**
- The method **must** resolve to an array of `Observation` objects. Even if there's only one piece of output, return it in an array: `[observation]`.
- Each `Observation` object usually has the structure `{ type: 'text', text: string }`. Other types might be possible but `text` is standard for LLM interaction.
- The `text` string **must** contain the tool's output formatted within one or more `<chunk>` tags. This is how the Agent passes structured results back to the LLM.
- Format: `<chunk chunk_id="UNIQUE_ID" chunk_type="YOUR_TYPE">OUTPUT_DATA</chunk>`
- `chunk_id`: A unique identifier for this specific piece of output (use `uuidv4()`). Essential for linking citations back to observations.
- `chunk_type`: A string literal describing the _semantic type_ of the data (e.g., `'search_result_url'`, `'calculation_result'`, `'note_creation_status'`, `'error'`, `'metadata_info'`). Helps the LLM interpret the result. Choose consistent and descriptive names.
- `OUTPUT_DATA`: The actual result from your tool. Can be simple text, JSON stringified data, etc. Keep it concise if possible for the LLM context.
- **Return errors** using the same format, but with `chunk_type="error"` and a descriptive error message inside the chunk tag. This allows the Agent loop to continue gracefully and potentially inform the LLM or user.
### The `inputValidator` Method: Handling Edge Cases
- `inputValidator(inputParam: ParametersType<readonly Parameter[]>) { return false; }` (Default implementation in `BaseTool`).
- Override this method _only_ if your tool needs complex input validation logic beyond simple `required` checks (e.g., dependencies between parameters).
- If you override it to return `true`, `Agent.ts` will skip its standard check for missing _required_ parameters. Your `execute` method becomes fully responsible for validating the `args` object.
- Use case example: `DocumentMetadataTool` uses it to allow either `fieldName`/`fieldValue` OR `fieldEdits` to be provided for the "edit" action.
---
## 4. The Agent-Tool Interaction Flow (Annotated XML Trace)
Let's trace the `dictionaryLookup` example with `Agent.ts` actions:
1. **User Input:** User types "What is hypermedia?" and submits.
- `// ChatBox.tsx calls agent.askAgent("What is hypermedia?")`
- `// Agent.ts adds stage 1 to interMessages:`
```xml
<stage number="1" role="user">
<query>What is hypermedia?</query>
</stage>
```
- `// Agent.ts calls LLM with interMessages.`
2. **LLM Thought & Action:** LLM processes the query and system prompt (which includes the dynamically generated description for `dictionaryLookup`).
- `// LLM responds with stage 2:`
```xml
<stage number="2" role="assistant">
<thought>The user is asking for a definition. The dictionaryLookup tool is appropriate for this.</thought>
<action>dictionaryLookup</action>
</stage>
```
- `// Agent.ts parses stage 2. Finds <action>dictionaryLookup</action>.`
- `// Agent.ts retrieves the dictionaryTool instance: tool = this.tools['dictionaryLookup'].`
- `// Agent.ts gets parameter rules: rules = tool.getActionRule().`
3. **Agent Provides Rules:** `Agent.ts` formats the rules into XML.
- `// Agent.ts adds stage 3 to interMessages:`
```xml
<stage number="3" role="user">
<action_rules>
<tool>dictionaryLookup</tool>
<description>Looks up the definition of a given English word.</description>
<citationRules>Cite the definition using the provided chunk_id and type="dictionary_definition". Leave citation content empty.</citationRules>
<parameters>
<word>
<type>string</type>
<description>The word to define.</description>
<required>true</required>
</word>
</parameters>
</action_rules>
</stage>
```
- `// Agent.ts calls LLM with updated interMessages.`
4. **LLM Provides Inputs:** LLM uses the rules to formulate the required inputs.
- `// LLM responds with stage 4:`
```xml
<stage number="4" role="assistant">
<action_input>
<action_input_description>Looking up the definition for the word 'hypermedia'.</action_input_description>
<inputs>
<word>hypermedia</word>
</inputs>
</action_input>
</stage>
```
- `// Agent.ts parses stage 4. Finds <action_input>. Extracts inputs: { word: 'hypermedia' }.`
- `// Agent.ts validates required params (finds 'word'). Checks tool.inputValidator (returns false). OK.`
- `// Agent.ts calls: const observations = await dictionaryTool.execute({ word: 'hypermedia' });`
5. **Tool Execution -> Observation:** The `dictionaryTool.execute` method runs, calls an API, gets the definition, and formats the `Observation`.
- `// dictionaryTool.execute resolves Promise with:`
```javascript
[{ type: 'text', text: '<chunk chunk_id="dict-abc-123" chunk_type="dictionary_definition">Hypermedia is an extension of hypertext allowing...</chunk>' }];
```
- `// Agent.ts receives the resolved Observation[].`
6. **Agent Provides Observation:** `Agent.ts` formats the observation(s) into the next stage.
- `// Agent.ts adds stage 5 to interMessages:`
```xml
<stage number="5" role="user">
<observation>
<chunk chunk_id="dict-abc-123" chunk_type="dictionary_definition">Hypermedia is an extension of hypertext allowing...</chunk>
</observation>
</stage>
```
- `// Agent.ts calls LLM with updated interMessages.`
7. **LLM Generates Final Answer:** LLM uses the full context (query, thoughts, actions, observation) and the `citationRules` from the `dictionaryLookup` tool.
- `// LLM responds with stage 6:`
```xml
<stage number="6" role="assistant">
<thought>I have received the definition from the dictionary tool. I will now format the final answer according to the specified structure, including the citation.</thought>
<answer>
<grounded_text citation_index="1">Hypermedia is an extension of hypertext allowing graphics, audio, video, plain text and hyperlinks to intertwine to create a generally non-linear medium of information.</grounded_text>
<citations>
<citation index="1" chunk_id="dict-abc-123" type="dictionary_definition"></citation>
</citations>
<follow_up_questions>
<question>Can you give an example of a hypermedia system?</question>
<question>How does hypermedia differ from multimedia?</question>
<question>Who coined the term hypermedia?</question>
</follow_up_questions>
<loop_summary>Used dictionaryLookup tool to define 'hypermedia'.</loop_summary>
</answer>
</stage>
```
- `// Agent.ts parses stage 6. Finds <answer>. Calls AnswerParser.`
- `// Agent.ts updates ChatBox UI (`\_history.push(...)`). Loop ends.`
---
## 5. Step-by-Step Guide: Creating a New Tool
Let's use the example of creating a `CreateDashNoteTool`.
### Step 1: Define Goal, Scope, Inputs, Outputs, Dash Interactions, Side Effects
- **Goal:** Allow Agent to create a new text note (`DocumentType.TEXT` or equivalent) in Dash.
- **Scope:** Creates a _simple_ note with title and text content. Does not handle complex formatting, linking (beyond default linking to ChatBox if handled by the creation function), or specific placement beyond a potential default offset.
- **Inputs:** `noteTitle` (string, required), `noteContent` (string, required).
- **Outputs (Observation):** Confirmation message with new note's Dash Document ID, or an error message.
- **Dash Interactions:** Calls a function capable of creating Dash documents (e.g., `createDocInDash` passed via constructor).
- **Side Effects:** A new Dash text document is created in the user's space and potentially linked to the ChatBox.
### Step 2: Create the Tool Class File (Directory Structure)
- Create file: `src/components/views/nodes/chatbot/agentsystem/tools/CreateDashNoteTool.ts`
- Ensure it's within the `tools` subdirectory.
### Step 3: Define Parameters (`parameterRules`) - Type Handling, Arrays
- Use `as const` for the array to allow TypeScript to infer literal types, which aids `ParametersType`.
- Define `noteTitle` and `noteContent` as required strings.
```typescript
import { Parameter } from '../types/tool_types';
const createDashNoteToolParams = [
{
name: 'noteTitle',
type: 'string',
required: true,
description: 'The title for the new Dash note document. Cannot be empty.',
},
{
name: 'noteContent',
type: 'string',
required: true,
description: 'The text content for the new Dash note. Can be an empty string.', // Specify if empty content is allowed
},
] as const; // Use 'as const' for precise typing
// Infer the type for args object in execute
type CreateDashNoteToolParamsType = typeof createDashNoteToolParams;
```
### Step 4: Define Tool Information (`ToolInfo`) - Crafting the _Crucial_ `description`
- This object's `description` is key for the LLM.
```typescript
import { ToolInfo, ParametersType } from '../types/tool_types';
// Assuming createDashNoteToolParams and CreateDashNoteToolParamsType are defined above
const createDashNoteToolInfo: ToolInfo<CreateDashNoteToolParamsType> = {
name: 'createDashNote', // Must match registration key in Agent.ts
description:
'Creates a *new*, simple text note document within the current Dash view. Requires a title and text content. The note will be linked to the ChatBox and placed nearby with default dimensions. Use this when the user asks to create a new note, save information, or write something down persistently in Dash.',
parameterRules: createDashNoteToolParams,
citationRules: 'This tool creates a document. The observation confirms success and provides the new document ID. No citation is typically needed in the final answer unless confirming the action.',
};
```
### Step 5: Implement `execute` - Defensive Coding, Using Injected Functions, Error Handling Pattern
- Implement the `execute` method within your class.
- Wrap logic in `try...catch`.
- Validate inputs defensively.
- Check injected dependencies (`this._createDocInDash`).
- Call the Dash function.
- Handle the return value.
- Format success or error `Observation`.
```typescript
import { BaseTool } from './BaseTool';
import { Observation } from '../types/types';
import { supportedDocTypes } from '../types/tool_types';
import { parsedDoc } from '../chatboxcomponents/ChatBox'; // May need adjustment based on actual path
import { Doc } from '../../../../../../fields/Doc'; // Adjust path as needed
import { v4 as uuidv4 } from 'uuid';
import { RTFCast } from '../../../../../../fields/Types'; // Adjust path as needed
// Assuming createDashNoteToolParams, CreateDashNoteToolParamsType, createDashNoteToolInfo are defined above
export class CreateDashNoteTool extends BaseTool<CreateDashNoteToolParamsType> {
// Dependency: Function to create a document in Dash
private _createDocInDash: (doc: parsedDoc) => Doc | undefined;
// Constructor to inject dependencies
constructor(createDocInDash: (doc: parsedDoc) => Doc | undefined) {
super(createDashNoteToolInfo);
if (typeof createDocInDash !== 'function') {
console.error('CreateDashNoteTool Error: createDocInDash function dependency not provided during instantiation!');
// Consider throwing an error or setting a flag to prevent execution
}
this._createDocInDash = createDocInDash;
}
async execute(args: ParametersType<CreateDashNoteToolParamsType>): Promise<Observation[]> {
const chunkId = uuidv4(); // Unique ID for this observation
const { noteTitle, noteContent } = args;
// --- Input Validation ---
if (typeof noteTitle !== 'string' || !noteTitle.trim()) {
return [{ type: 'text', text: `<chunk chunk_id="${chunkId}" chunk_type="error">Invalid input: Note title must be a non-empty string.</chunk>` }];
}
if (typeof noteContent !== 'string') {
// Assuming empty content IS allowed based on description
// If not allowed, return error here.
return [{ type: 'text', text: `<chunk chunk_id="${chunkId}" chunk_type="error">Invalid input: Note content must be a string.</chunk>` }];
}
if (!this._createDocInDash) {
return [{ type: 'text', text: `<chunk chunk_id="${chunkId}" chunk_type="error">Tool Configuration Error: Document creation function not available.</chunk>` }];
}
// --- End Validation ---
try {
const trimmedTitle = noteTitle.trim();
// Prepare the document object for the creation function
const noteDoc: parsedDoc = {
doc_type: supportedDocTypes.note, // Use the correct type for a text note
title: trimmedTitle,
data: RTFCast(noteContent) as unknown as string, // Ensure data is correctly formatted if needed
// Example default properties:
_width: 300,
_layout_fitWidth: false,
_layout_autoHeight: true,
backgroundColor: '#FFFFE0', // Light yellow background
// Add x, y coordinates if desired, potentially relative to ChatBox if context is available
};
console.log(`CreateDashNoteTool: Attempting to create doc:`, { title: noteDoc.title, type: noteDoc.doc_type }); // Avoid logging full content
// Call the injected Dash function
const createdDoc = this._createDocInDash(noteDoc);
// Check the result
if (createdDoc && createdDoc.id) {
const successMessage = `Successfully created note titled "${trimmedTitle}" with ID: ${createdDoc.id}. It has been added to your current view.`;
console.log(`CreateDashNoteTool: Success - ${successMessage}`);
// Return observation confirming success
return [{ type: 'text', text: `<chunk chunk_id="${chunkId}" chunk_type="note_creation_status">${successMessage}</chunk>` }];
} else {
console.error('CreateDashNoteTool Error: _createDocInDash returned undefined or document without an ID.');
throw new Error('Dash document creation failed or did not return a valid document ID.');
}
} catch (error) {
console.error(`CreateDashNoteTool: Error creating note titled "${noteTitle.trim()}":`, error);
const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred during note creation.';
// Return observation indicating error
return [{ type: 'text', text: `<chunk chunk_id="${chunkId}" chunk_type="error">Error creating note: ${errorMessage}</chunk>` }];
}
}
}
```
### Step 6: Format Output (`Observation[]`) - Chunk Structure, `chunk_type`, IDs
- Ensure the `text` field within the returned `Observation` contains `<chunk chunk_id="..." chunk_type="...">...</chunk>`.
- Use a specific `chunk_type` (e.g., `note_creation_status`, `error`).
- Generate a unique `chunk_id` using `uuidv4()`.
- The text inside the chunk should be informative for the LLM and potentially for debugging.
### Step 7: Register Tool in `Agent.ts` - _This makes the tool available to the prompt_
- Import your tool class at the top of `Agent.ts`:
```typescript
import { CreateDashNoteTool } from '../tools/CreateDashNoteTool';
```
- In the `Agent` constructor, instantiate your tool within the `this.tools = { ... };` block. Ensure the key matches `ToolInfo.name` and pass any required dependencies (like the `createDocInDash` function).
```typescript
constructor(
_vectorstore: Vectorstore,
summaries: () => string,
history: () => string,
csvData: () => { filename: string; id: string; text: string }[],
addLinkedUrlDoc: (url: string, id: string) => void,
createImage: (result: any, options: any) => void, // Use specific types if known
createDocInDashFunc: (doc: parsedDoc) => Doc | undefined, // Renamed for clarity
createCSVInDash: (url: string, title: string, id: string, data: string) => void
) {
// ... existing initializations (OpenAI client, vectorstore, etc.) ...
this.vectorstore = _vectorstore;
this._summaries = summaries;
this._history = history;
this._csvData = csvData;
this.tools = {
calculate: new CalculateTool(),
rag: new RAGTool(this.vectorstore),
dataAnalysis: new DataAnalysisTool(csvData),
websiteInfoScraper: new WebsiteInfoScraperTool(addLinkedUrlDoc),
searchTool: new SearchTool(addLinkedUrlDoc),
noTool: new NoTool(),
imageCreationTool: new ImageCreationTool(createImage),
documentMetadata: new DocumentMetadataTool(this), // Pass ChatBox instance if needed by tool
// Register the new tool here:
createDashNote: new CreateDashNoteTool(createDocInDashFunc), // Pass the required function
};
// ... rest of constructor
}
```
- **Verify Dependencies:** Ensure that the `createDocInDashFunc` parameter (or however you name it) is actually being passed into the `Agent` constructor when it's instantiated (likely within `ChatBox.tsx`). Trace the dependency chain.
### Step 8: Verify Prompt Integration (No Manual Editing Needed)
- **No manual changes are needed in `prompts.ts`**. The `getReactPrompt` function dynamically builds the `<tools>` section from `this.tools`.
- **Verify (Recommended):** Temporarily add `console.log(systemPrompt)` in `Agent.ts` right after `const systemPrompt = getReactPrompt(...)` within the `askAgent` method. Run a query. Examine the console output to confirm the system prompt includes your tool's `<title>` and `<description>` within the `<tools>` block. Remove the log afterward.
### Step 9: Testing Your Tool - Strategies and What to Look For
- **Functional Tests:** Use specific prompts like "Create a note called 'Ideas' with content 'Test 1'." Check the Dash UI for the note and the chat for the success message/ID.
- **Edge Case Tests:** Test empty titles (should fail validation), empty content (should succeed if allowed), titles/content with special characters or excessive length.
- **LLM Interaction Tests:** Use less direct prompts like "Save this thought: Remember to buy milk." Does the LLM correctly identify the need for your tool and extract/request the title and content?
- **Failure Tests:** If possible, simulate failure in the dependency (`createDocInDash`) to ensure the `error` chunk is returned correctly.
- **Console/Debugging:** Use `console.log` within `execute` and inspect `interMessages` in `Agent.ts` to trace the flow and identify issues.
---
## 6. Deep Dive: Advanced Concepts & Patterns
### Handling Complex Data Types (Arrays, Objects) in Parameters/Observations
- **Parameters:** For complex inputs, define the parameter `type` as `string` in `parameterRules`. In the `description`, instruct the LLM to provide a **valid JSON string**. Inside your `execute` method, use `JSON.parse()` within a `try...catch` block to parse this string. Handle potential parsing errors gracefully (return an `error` chunk).
- **Observations:** To return structured data, `JSON.stringify` your object/array and embed this string _inside_ the `<chunk>` tag. Use a specific `chunk_type` (e.g., `json_data_analysis`). The LLM might need guidance (via prompt engineering) on how to interpret and use this JSON data effectively in its final response.
### Binary Data Handling (e.g., Base64 in Chunks)
- **Avoid large binary data in observations.** Context windows are limited.
- **Preferred:** Save binary data server-side (e.g., using `DashUploadUtils` or similar) or reference existing Dash media docs. Return a **reference** (URL, Doc ID, file path accessible by Dash) within the `<chunk>`.
- **If absolutely necessary:** For small images/data needed _directly_ by the LLM, Base64 encode it inside the chunk: `<chunk chunk_id="..." chunk_type="base64_image_png">BASE64_STRING</chunk>`.
### Managing Long-Running Tasks (Beyond simple `await`)
- The agent's `askAgent` loop `await`s `tool.execute()`. Tasks taking more than ~5-10 seconds degrade user experience. Very long tasks risk timeouts.
- **Limitation:** The current architecture doesn't have built-in support for asynchronous background jobs with status polling.
- **Possible (Complex) Workaround:**
1. Tool `execute` initiates a long-running _external_ process (like the Python PDF chunker) or backend job.
2. `execute` _immediately_ returns an `Observation` like `<chunk chunk_type="task_initiated" job_id="JOB123">Processing started. Use status check tool with ID JOB123.</chunk>`.
3. Requires a _separate_ `StatusCheckTool` that takes a `job_id` and queries the external process/backend for status.
4. This adds significant complexity to the agent's reasoning flow. Use only if absolutely necessary.
### Tools Needing Dash Context (Passing `this` vs. specific functions)
- **Specific Functions (Preferred):** Pass only necessary functions from `ChatBox`/Dash utilities. Promotes modularity and testability. Requires updating constructors if needs change.
- **`ChatBox` Instance (`this`) (As in `DocumentMetadataTool`):** Provides broad access to `ChatBox` state (`Document`, `layoutDoc`, computed properties) and methods. Easier for tools with complex Dash interactions but increases coupling and makes testing harder.
- **Decision:** Start with specific functions. Escalate to passing `this` only if the tool's requirements become extensive and unmanageable via individual function injection.
### The Role of `chunk_id` and `chunk_type`
- `chunk_id` (e.g., `uuidv4()`): **Traceability & Citation.** Uniquely identifies a piece of data returned by a tool. Allows the final `<answer>`'s `<citation>` tag to precisely reference the source observation via this ID. Essential for debugging and grounding.
- `chunk_type`: **Semantic Meaning.** Tells the LLM _what kind_ of information the chunk contains (e.g., `url`, `calculation_result`, `error`, `note_creation_status`). Guides the LLM in processing the observation and formatting the final answer appropriately. Use consistent and descriptive type names.
---
## 7. Best Practices and Advanced Considerations
- **Error Handling & Reporting:** Return errors in structured `<chunk chunk_type="error">...</chunk>` format. Include context in the message (e.g., "API call failed for URL: [url]", "Invalid value for parameter: [param_name]").
- **Security:**
- **Input Sanitization:** **Crucial.** If tool inputs influence API calls, file paths, database queries, etc., validate and sanitize them rigorously. Do not trust LLM output implicitly.
- **API Keys:** Use server-side environment variables (`process.env`) for keys used in backend routes called by tools. Avoid exposing keys directly in client-side tool code if possible.
- **Output Filtering:** Be mindful of sensitive data. Don't leak PII or internal details in observations or error messages.
- **Performance Optimization:** Keep `execute` logic efficient. Minimize blocking operations. Use asynchronous patterns correctly.
- **Idempotency:** Design tools (especially those causing side effects like creation/modification) to be safe if run multiple times with the same input, if possible.
- **Tool Granularity (SRP):** Aim for tools that do one thing well. Complex workflows can be achieved by the LLM chaining multiple focused tools.
- **Context Window Management:** Write concise but clear tool `description`s. Keep `Observation` data relevant and succinct.
- **User Experience:** Tool output (via observations) influences the final answer. Ensure returned data is clear and `citationRules` guide the LLM to produce understandable results.
- **Maintainability:** Use clear code, comments for complex logic, TypeScript types, and follow project conventions.
---
## 8. Debugging Strategies
1. **`console.log`:** Liberally use `console.log` inside your tool's `execute` method to inspect `args`, intermediate variables, API responses, and the `Observation[]` object just before returning.
2. **Inspect `interMessages`:** Temporarily modify `Agent.ts` (e.g., in the `askAgent` `while` loop) to `console.log(JSON.stringify(this.interMessages, null, 2))` before each LLM call. This shows the exact XML context the LLM sees and its raw XML response. Pinpoint where the conversation deviates or breaks.
3. **Test Standalone:** Create a simple test script (`.ts` file run with `ts-node` or similar). Import your tool. Create mock objects/functions for its dependencies (e.g., `const mockCreateDoc = (doc) => ({ id: 'mock-doc-123', ...doc });`). Instantiate your tool with mocks: `const tool = new YourTool(mockCreateDoc);`. Call `await tool.execute(testArgs);` and assert the output. This isolates tool logic.
4. **Analyzing LLM Failures:** Use the `interMessages` log:
- **Wrong Tool Chosen:** LLM's `<thought>` selects the wrong tool, or uses `<action>noTool</action>` inappropriately. -> **Refine your tool's `description`** in `ToolInfo` for clarity and better differentiation.
- **Missing/Incorrect Parameters:** LLM fails to provide required parameters in `<inputs>`, or provides wrong values. -> **Refine parameter `description`s** in `parameterRules`. Check the `<action_input>` stage in the log.
- **Ignoring Observation/Bad Answer:** LLM gets the correct `<observation>` but generates a poor `<answer>` (ignores data, bad citation). -> Check `chunk_type`, data format inside the chunk, and **clarify `citationRules`**. Simplify observation data if needed.
- **XML Formatting Errors:** LLM returns malformed XML. -> This might require adjusting the system prompt's structure rules or adding more robust parsing/error handling in `Agent.ts`.
---
## 9. Example: `CreateDashNoteTool`
The code provided in Step 5 serves as a practical example, demonstrating dependency injection, input validation, calling a Dash function, and formatting success/error observations within the required `<chunk>` structure. Ensure the dependency (`createDocInDashFunc`) is correctly passed during `Agent` instantiation in `ChatBox.tsx`.
---
## 10. Glossary of Key Terms
- **Agent (`Agent.ts`):** The orchestrator class managing the LLM interaction loop and tool usage.
- **Tool (`BaseTool.ts`):** A class extending `BaseTool` to provide specific functionality (API calls, Dash actions).
- **LLM (Large Language Model):** The AI model providing reasoning and text generation (e.g., GPT-4o).
- **ReAct Loop:** The core interaction pattern: Reason -> Act -> Observe.
- **XML Structure:** The tag-based format (`<stage>`, `<thought>`, etc.) for LLM communication.
- **`interMessages`:** The internal, complete conversational context sent to the LLM.
- **`ToolInfo`:** Configuration object (`name`, `description`, `parameterRules`, `citationRules`) defining a tool. **Source of dynamic prompt content for the tool list.**
- **`parameterRules`:** Array defining a tool's expected input parameters.
- **`citationRules`:** Instructions for the LLM on citing a tool's output.
- **`execute`:** The primary asynchronous method within a tool containing its core logic.
- **`Observation`:** The structured object (`{ type: 'text', text: '<chunk>...' }`) returned by `execute`.
- **`<chunk>`:** The required XML-like wrapper within an Observation's `text`, containing `chunk_id` and `chunk_type`.
- **`chunk_type`:** Semantic identifier for the data type within a `<chunk>`.
- **System Prompt (`getReactPrompt`):** The foundational instructions for the LLM, acting as a **template dynamically populated** with registered tool descriptions.
- **Dash Functions:** Capabilities from the Dash environment (e.g., `createDocInDash`) injected into tools.
- **Stateless Tool:** A tool whose output depends solely on current inputs, not past interactions.
---
## 11. Conclusion
This guide provides a detailed framework for extending the Dash Agent with custom tools. By adhering to the `BaseTool` structure, understanding the agent's interaction flow, crafting clear `ToolInfo` descriptions, implementing robust `execute` methods, and correctly registering your tool in `Agent.ts`, you can build powerful integrations that leverage both AI and the unique capabilities of the Dash hypermedia environment. Remember that testing and careful consideration of dependencies, errors, and security are crucial for creating reliable tools.
|