TypeScriptADK-TS

Built-in Tools

Ready-to-use tools for common tasks like search, file operations, and user interaction

Overview

ADK-TS provides a comprehensive collection of pre-built tools that handle common agent tasks. These tools are production-ready, thoroughly tested, and optimized for reliability. Simply import the tool you need and add it to your agent's configuration—no custom development required.

Quick Start

Here's how to use built-in tools with your agent:

import { LlmAgent, GoogleSearchTool, HttpRequestTool } from "@iqai/adk";

const agent = new LlmAgent({
  name: "research_agent",
  description:
    "An agent that helps users research topics using web search and HTTP requests",
  instruction: "Help users research topics using web search and HTTP requests",
  tools: [new GoogleSearchTool(), new HttpRequestTool()],
});

That's it! Your agent can now search the web and make HTTP requests.

Available Tools

ToolPurposeEnvironment Variables
GoogleSearchToolSearch the web for information (uses Google Custom Search API)GOOGLE_API_KEY, GOOGLE_CSE_ID
WebSearchToolSearch the web for information (uses Tavily API)TAVILY_API_KEY
WebFetchToolFetch and parse web page content
HttpRequestToolMake HTTP requests to APIs
ReadToolRead file contents
WriteToolCreate new files
EditToolEdit existing files
GlobToolFind files by pattern
GrepToolSearch file contents
FileOperationsToolComprehensive file management
BashToolExecute terminal commands
UserInteractionToolPrompt users for input
GetUserChoiceToolPresent multiple choice options
LoadMemoryToolSearch conversation history
LoadArtifactsToolAccess uploaded files
TransferToAgentToolHand off to another agent
ExitLoopToolExit workflow loops

Understanding Tool Configuration:

  • Configuration Options: Optional parameters passed when creating a tool instance (e.g., new BashTool({ maxTimeout: 60000 })). These customize the tool behavior but are not required—the default settings work for most use cases.
  • Tool Parameters: Arguments that the agent passes to the tool during execution (e.g., { query: "search term" } for GoogleSearchTool). These are specified by the agent based on the task at hand.
  • Environment Variables: External values like API keys that must be set in your environment before using certain tools.

Web & API Tools

GoogleSearchTool

Search the web for real-time information using Google's search engine.

Import:

import { GoogleSearchTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "research_agent",
  description: "A research assistant that searches the web for information",
  tools: [new GoogleSearchTool()],
});

Environment Variables:

GOOGLE_API_KEY=your_api_key_here
GOOGLE_CSE_ID=your_search_engine_id

Tool Parameters:

ParameterTypeRequiredDescription
querystringYesThe search query to execute
numResultsintegerOptionalNumber of results to return (default: 5, max: 10)
startintegerOptionalStart index for pagination (default: 1)
safestringOptionalSafe search filter: "active" or "off" (default: "off")
siteSearchstringOptionalRestrict results to a specific site
siteSearchFilterstringOptionalInclude ("i") or exclude ("e") specific site
lrstringOptionalLanguage restriction (e.g., "lang_en")
crstringOptionalCountry restriction (e.g., "countryUS")
fieldsstringOptionalPartial response fields to reduce payload

How It's Triggered:

// User: "What are the latest updates about AI in 2024?"
// Agent automatically calls:
// google_search({ query: "latest AI updates 2024", numResults: 5 })
// Agent receives search results and summarizes them

Response Format:

{
  success: boolean;
  results?: Array<{
    title: string;
    link: string;
    snippet: string;
  }>;
  error?: string;
}

Capabilities:

  • Full control over search parameters including language and country restrictions
  • Pagination support for accessing more results
  • Safe search filtering
  • Site-specific search with include/exclude options
  • Partial field responses to optimize bandwidth

Use Cases:

  • Real-time web research
  • Finding current information and news
  • Verifying facts with multiple sources
  • Domain-specific searches

WebSearchTool

Search the web for current information using Tavily API with advanced search capabilities.

Import:

import { WebSearchTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "research_agent",
  description: "A research assistant with advanced web search",
  tools: [new WebSearchTool()],
});

Environment Variables:

TAVILY_API_KEY=your_tavily_api_key_here

Tool Parameters:

ParameterTypeRequiredDescription
querystringYesSearch terms
searchDepthstringOptional"basic", "advanced", "fast", "ultra-fast" (default: basic)
chunksPerSourcenumberOptionalMaximum chunks per source (default: 3, max: 3)
maxResultsnumberOptionalMaximum search results (default: 5, max: 20)
topicstringOptional"general", "news", "finance" (default: general)
timeRangestringOptional"day", "week", "month", "year" (or "d", "w", "m", "y")
startDatestringOptionalResults after this date (YYYY-MM-DD)
endDatestringOptionalResults before this date (YYYY-MM-DD)
includeAnswerstringOptionalInclude LLM-generated answer ("true", "basic", "advanced")
includeRawContentstringOptionalInclude raw content ("true", "markdown", "text")
includeImagesbooleanOptionalInclude image search results
includeImageDescriptionsbooleanOptionalInclude descriptive text for images
includeFaviconbooleanOptionalInclude favicon URL for results
includeDomainsarrayOptionalDomains to include in search
excludeDomainsarrayOptionalDomains to exclude from search
countrystringOptionalCountry to prioritize results from
autoParametersbooleanOptionalAutomatically configure based on query
includeUsagebooleanOptionalInclude credit usage information

How It's Triggered:

// User: "Find recent news about renewable energy"
// Agent calls:
// web_search({
//   query: "renewable energy news",
//   topic: "news",
//   timeRange: "week",
//   maxResults: 10
// })

Response Format:

{
  success: boolean;
  data?: {
    query: string;
    results: Array<{
      title: string;
      url: string;
      content: string;
      raw_content?: string;
      favicon?: string;
      score?: number;
    }>;
    answer?: string;
    images?: Array<{
      url: string;
      description?: string;
    }>;
    response_time: number;
    usage?: Record<string, string>;
    request_id?: string;
  };
  error?: string;
}

Capabilities:

  • Advanced search depth options balancing speed and relevance
  • Topic-specific searches (general, news, finance)
  • Time-based filtering with flexible date ranges
  • Optional AI-generated answers with different detail levels
  • Raw content extraction in multiple formats

Use Cases:

  • News monitoring and research
  • Financial market analysis
  • Topic-specific deep research
  • Time-sensitive information gathering

WebFetchTool

Fetch and parse content from web pages with automatic HTML cleaning.

Import:

import { WebFetchTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "web_reader_agent",
  description: "An agent that fetches and analyzes web page content",
  tools: [new WebFetchTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
urlstringYesWeb page URL to fetch

How It's Triggered:

// User: "What's on the React documentation homepage?"
// Agent calls:
// web_fetch({ url: "https://react.dev" })
// Returns parsed content with title and cleaned text

Response Format:

{
  success: boolean;
  data?: {
    title: string;
    content: string;
    metadata: {
      contentType: string;
      url: string;
    };
  };
  error?: string;
}

Supported Content Types:

  • HTML: Extracts title and clean text with scripts and styles removed
  • JSON: Returns formatted JSON string
  • Plain text: Returns raw content
  • PDF: Returns error (not supported without additional libraries)

Capabilities:

  • Automatic content type detection (HTML, JSON, text)
  • Clean text extraction with HTML tag, script, and style removal
  • HTTP redirect handling (max 5 redirects)
  • 30-second timeout protection
  • Content length limiting (20,000 chars for HTML)

Use Cases:

  • Reading documentation pages
  • Extracting article content
  • Processing API responses
  • Content verification

HttpRequestTool

Make HTTP requests to APIs and web services with full control over methods, headers, and parameters.

Import:

import { HttpRequestTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "api_agent",
  description: "An agent that integrates with external APIs and services",
  tools: [new HttpRequestTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
urlstringYesThe URL to request
methodstringOptionalHTTP method: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
headersobjectOptionalCustom headers (e.g., { "Authorization": "Bearer token" })
bodystringOptionalRequest body (for POST, PUT, PATCH)
paramsobjectOptionalURL query parameters to include
timeoutnumberOptionalRequest timeout in milliseconds (default: 10000)

How It's Triggered:

// User: "Get the weather from the API"
// Agent calls:
// http_request({
//   url: "https://api.weather.com/forecast",
//   method: "GET",
//   params: { city: "london" },
//   headers: { "Authorization": "Bearer YOUR_API_KEY" }
// })

Capabilities:

  • Support for all HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)
  • Custom headers for authentication and API integration
  • JSON and form data support
  • Query parameter handling
  • Configurable request timeouts

Use Cases:

  • Integrating with REST APIs
  • Fetching data from external services
  • Posting data to webhooks
  • Testing API endpoints

File System Tools

ReadTool

Read contents of text files in the working directory.

Import:

import { ReadTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "file_reader_agent",
  description: "An agent that reads and analyzes file contents",
  tools: [new ReadTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
pathstringYesRelative or absolute file path

How It's Triggered:

// User: "Read the contents of config.json"
// Agent calls:
// read_file({ path: "config.json" })
// Agent receives file contents and can analyze or respond

Response Format:

{
  success: boolean;
  data?: string; // File contents
  error?: string;
}

Capabilities:

  • UTF-8 encoding for text files
  • Automatic binary file detection and rejection
  • Support for both relative and absolute paths
  • Clear error messages for missing or inaccessible files

Use Cases:

  • Reading configuration files
  • Analyzing source code
  • Processing logs
  • Extracting data from text files

WriteTool

Create new files with specified content, preventing accidental overwrites.

Import:

import { WriteTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "file_writer_agent",
  description: "An agent that creates new files",
  tools: [new WriteTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
pathstringYesTarget file path
contentstringYesContent to write

How It's Triggered:

// User: "Create a README.md file with project description"
// Agent calls:
// write_file({
//   path: "README.md",
//   content: "# My Project\n\nDescription here..."
// })

Response Format:

{
  success: boolean;
  data?: string; // Success message
  error?: string;
}

Capabilities:

  • Safe file creation with overwrite protection
  • Automatic parent directory creation
  • UTF-8 encoding
  • Clear success/error messages

Use Cases:

  • Creating new source files
  • Generating documentation
  • Saving analysis results
  • Creating configuration files

Overwrite Protection

WriteTool will not overwrite existing files. To modify existing files, use EditTool instead.

EditTool

Make precise edits to existing files using search and replace.

Import:

import { EditTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "file_editor_agent",
  description: "An agent that edits existing files precisely",
  tools: [new EditTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
pathstringYesFile to edit
old_strstringYesExact text to find (must be unique)
new_strstringYesReplacement text

How It's Triggered:

// User: "Change the port from 3000 to 8080 in server.js"
// Agent calls:
// edit_file({
//   path: "server.js",
//   old_str: "const PORT = 3000;",
//   new_str: "const PORT = 8080;"
// })

Response Format:

{
  success: boolean;
  data?: string; // Preview of changes
  error?: string;
}

Preview Format:

<<<<<< OLD
const PORT = 3000;
======
const PORT = 8080;
>>>>>> NEW

Capabilities:

  • Validates search string exists in the file
  • Ensures search string is unique to prevent ambiguous edits
  • Shows before/after preview of changes
  • Preserves file encoding

Use Cases:

  • Updating configuration values
  • Modifying code precisely
  • Fixing typos in documentation
  • Changing variable names

GlobTool

Find files matching glob patterns for flexible file discovery.

Import:

import { GlobTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "file_finder_agent",
  description: "An agent that finds files matching patterns",
  tools: [new GlobTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
patternstringYesGlob pattern to search for

How It's Triggered:

// User: "Find all TypeScript files in the src directory"
// Agent calls:
// glob({ pattern: "src/**/*.ts" })
// Returns: ["src/index.ts", "src/utils/helper.ts", ...]

Response Format:

{
  success: boolean;
  data?: string[]; // Array of matching file paths
  error?: string;
}

Glob Pattern Examples:

PatternMatches
*.pyAll Python files in current directory
**/*.tsAll TypeScript files recursively
src/**/*.test.jsAll test files in src directory
*.{js,ts}All JavaScript and TypeScript files
docs/**/*.mdAll Markdown files in docs

Capabilities:

  • Standard glob pattern support with wildcards and path matching
  • Automatic exclusion of node_modules and .git directories
  • Cross-platform compatible path handling
  • Support for nested directory structures

Use Cases:

  • Finding all files of a certain type
  • Locating test files
  • Discovering configuration files
  • Building file lists for processing

GrepTool

Search for patterns in files using regular expressions with advanced filtering and context.

Import:

import { GrepTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "code_search_agent",
  description: "An agent that searches through code for patterns",
  tools: [new GrepTool()],
});

// With custom configuration:
const customAgent = new LlmAgent({
  name: "custom_search_agent",
  description: "Custom search configuration",
  tools: [
    new GrepTool({
      maxMatches: 1000,
      maxFileSize: 5 * 1024 * 1024, // 5MB
      contextLines: 3,
      excludePatterns: ["**/custom-exclude/**"],
      includePatterns: ["**/*.custom"],
    }),
  ],
});

Configuration Options:

OptionTypeDefaultDescription
maxMatchesnumber500Maximum matches to return
maxFileSizenumber10485760Maximum file size to search (10MB in bytes)
contextLinesnumber2Number of context lines before/after each match
excludePatternsstring[]See belowGlob patterns for files to exclude
includePatternsstring[][]Glob patterns for files to include

Default Exclusion Patterns:

Automatically excludes node_modules, .git, .next, dist, build, .cache, coverage, .vscode, .idea, and minified/bundled JavaScript files (.min.js, .bundle.js, .map).

Tool Parameters:

ParameterTypeRequiredDescription
patternstringYesRegex pattern to search for
filesstringYesFile path or glob pattern
caseInsensitivebooleanOptionalCase-insensitive search (default: false)
contextLinesnumberOptionalContext lines before/after match (max: 10)
maxMatchesnumberOptionalMaximum matches to return (max: 1000)
wholeWordbooleanOptionalMatch whole words only (default: false)
invertMatchbooleanOptionalShow non-matching lines (default: false)
excludestringOptionalAdditional exclude patterns (comma-separated)
includestringOptionalAdditional include patterns (comma-separated)

How It's Triggered:

// User: "Find all TODO comments in TypeScript files"
// Agent calls:
// grep({
//   pattern: "TODO:",
//   files: "**/*.ts",
//   caseInsensitive: true,
//   contextLines: 2
// })

Response Format:

{
  success: boolean;
  matches: Array<{
    file: string;
    line: number;
    column: number;
    content: string;
    context?: {
      before: string[];
      after: string[];
    };
  }>;
  stats: {
    filesSearched: number;
    filesMatched: number;
    totalMatches: number;
    limitReached: boolean;
    duration: number; // milliseconds
  };
  error?: string;
  warnings?: string[];
}

Capabilities:

  • Regular expression pattern matching with multiple search options
  • Context lines display for better result understanding
  • Configurable exclusion/inclusion patterns for targeted searches
  • Parallel file processing (5 concurrent files)
  • Performance statistics and warnings for skipped files

Use Cases:

  • Finding specific code patterns
  • Locating TODO/FIXME comments
  • Searching for function definitions
  • Security audits

FileOperationsTool

Comprehensive file operations tool for reading, writing, and managing files with security restrictions.

Import:

import { FileOperationsTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "file_agent",
  description: "An agent that manages file operations on the local filesystem",
  tools: [new FileOperationsTool()],
});

// With custom base path for security:
const restrictedAgent = new LlmAgent({
  name: "restricted_file_agent",
  description: "An agent with restricted file access",
  tools: [
    new FileOperationsTool({
      basePath: "/safe/directory",
    }),
  ],
});

Configuration Options:

OptionTypeDefaultDescription
basePathstringprocess.cwd()Base directory for all file operations (for security)

Tool Parameters:

ParameterTypeRequiredDescription
operationstringYesOperation type (see Supported Operations)
filepathstringYesFile or directory path (relative to basePath)
contentstringOptionalContent to write (required for write and append)
encodingstringOptionalFile encoding (default: utf8)

Supported Operations:

  • read: Read file contents
  • write: Write or overwrite files
  • append: Add content to existing files
  • delete: Remove files
  • exists: Check if file exists
  • list: List directory contents with metadata (name, size, timestamps)
  • mkdir: Create directories recursively

How It's Triggered:

// User: "Read config.json"
// file_operations({ operation: "read", filepath: "config.json" })

// User: "Save data to output.txt"
// file_operations({ operation: "write", filepath: "output.txt", content: "data" })

// User: "What's in the data folder?"
// file_operations({ operation: "list", filepath: "data" })

Response Format:

{
  success: boolean;
  data?: any; // Varies by operation
  error?: string;
}

Security Features:

  • Limited to specified basePath directory to prevent unauthorized access
  • Path traversal attack prevention (../ protection)
  • Validates all file operations before execution
  • Safe error handling without exposing system details

Use Cases:

  • All-in-one file management in sandboxed environments
  • Restricted file access for untrusted operations
  • Multi-operation file workflows
  • Directory management

System Tools

BashTool

Execute terminal commands with configurable security restrictions and timeouts.

Import:

import { BashTool } from "@iqai/adk";

Setup:

// Whitelist mode (safest for production):
const agent = new LlmAgent({
  name: "command_executor_agent",
  description: "An agent that executes safe terminal commands",
  tools: [
    new BashTool({
      enabled: true,
      mode: "whitelist",
      allowedCommands: ["ls", "pwd", "cat", "node --version"],
      maxTimeout: 30000,
    }),
  ],
});

// Sandboxed mode (Docker-based isolation):
const sandboxedAgent = new LlmAgent({
  name: "sandboxed_agent",
  description: "An agent with Docker-sandboxed command execution",
  tools: [
    new BashTool({
      enabled: true,
      mode: "sandboxed",
      dockerImage: "alpine:latest",
    }),
  ],
});

Configuration Options:

OptionTypeDefaultDescription
enabledbooleanfalseMust be true to use tool (disabled by default for security)
modestring"disabled""whitelist", "sandboxed", "unrestricted" (dev only)
allowedCommandsstring[]Default listAllowed commands for whitelist mode
dockerImagestringalpine:latestDocker image for sandboxed mode
maxTimeoutnumber30000Maximum command execution time in milliseconds
requireConfirmationbooleanfalseRequire user confirmation before executing
enableLoggingbooleantrueLog all command executions

Tool Parameters:

ParameterTypeRequiredDescription
commandstringYesShell command to execute

How It's Triggered:

// User: "What files are in the current directory?"
// Agent calls:
// bash({ command: "ls -la" })

// User: "Check the Node.js version"
// Agent calls:
// bash({ command: "node --version" })

Response Format:

{
  exit_code: number | null;
  stdout: string;
  stderr: string;
  blocked?: boolean;
  reason?: string;
}

Safety Features:

  • Disabled by default for maximum security
  • Three security modes: whitelist, sandboxed, and unrestricted
  • Blocks dangerous patterns (fork bombs, disk operations, privilege escalation) - view blocked patterns
  • Configurable timeout protection (default: 30 seconds)
  • Command execution logging

Capabilities:

  • Multiple security modes for different trust levels
  • Command whitelisting for production environments
  • Docker-based sandboxing for isolation
  • Timeout protection and exit code tracking
  • Separate stdout and stderr capture

Use Cases:

  • Package installation (npm, pip, yarn)
  • Git operations
  • System information queries
  • Development workflows

Security Warning

BashTool is disabled by default and requires explicit configuration due to security risks. Only enable in trusted environments with appropriate security mode (whitelist or sandboxed). The unrestricted mode should only be used in isolated development environments.

User Interaction Tools

UserInteractionTool

Prompt users for input during agent execution, enabling confirmations and multi-step workflows.

Import:

import { UserInteractionTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "approval_agent",
  description: "An agent that handles user approvals and confirmations",
  tools: [new UserInteractionTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
promptstringYesThe question or message to display to the user
optionsarrayOptionalMultiple choice options to present
defaultValuestringOptionalDefault value if user provides no input

How It's Triggered:

// User: "I want to delete my account"
// Agent internally decides it needs confirmation:
// user_interaction({
//   prompt: "Are you absolutely sure you want to delete your account? This cannot be undone.",
//   options: ["Yes, delete it", "No, keep it"]
// })

// User sees numbered options and selects one
// Agent receives the user's choice and proceeds

Response Format:

{
  success: boolean;
  userInput?: string;
  error?: string;
}

Capabilities:

  • Pause agent execution to collect user input
  • Present multiple choice options
  • Support for default values
  • Long-running operation that waits for user response

Use Cases:

  • Confirmation dialogs for critical actions
  • Multi-step wizards
  • Collecting user preferences
  • Interactive workflows

Long-Running Operation

This tool is marked as isLongRunning: true because it waits for user input. The agent will pause execution until the user responds.

GetUserChoiceTool

Present users with multiple options and collect their selection.

Import:

import { GetUserChoiceTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "choice_agent",
  description: "An agent that presents options and collects user selections",
  tools: [new GetUserChoiceTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
optionsarrayYesList of options for the user to choose from
questionstringOptionalThe question or prompt to show before presenting options

How It's Triggered:

// User: "I want to choose a subscription plan"
// Agent calls:
// get_user_choice({
//   question: "Which plan would you like?",
//   options: ["Basic - $9/month", "Pro - $29/month", "Enterprise - $99/month"]
// })

// User sees numbered options and selects one
// Agent receives the selected option and proceeds

Capabilities:

  • Present numbered multiple choice options to users
  • Optional question/prompt text
  • Long-running operation that waits for user selection

Use Cases:

  • Subscription selection
  • Configuration choices
  • Menu navigation
  • Preference collection

Long-Running Operation

This tool is marked as isLongRunning: true because it waits for user input. The agent will pause execution until the user selects an option.

Memory & Context Tools

LoadMemoryTool

Search conversation history and past interactions to maintain context across sessions.

Import:

import { LoadMemoryTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "context_agent",
  description: "An agent that maintains context across conversations",
  tools: [new LoadMemoryTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
querystringYesWhat to search for in memory (e.g., "previous purchases")

How It's Triggered:

// User: "What did I ask you about last time?"
// Agent calls:
// load_memory({ query: "previous conversation topics" })
// Agent retrieves relevant memories and responds

// User: "I have that preference set, right?"
// Agent calls:
// load_memory({ query: "user preferences" })
// Agent confirms based on retrieved memory

Capabilities:

  • Search past conversations
  • Retrieve user preferences
  • Reference previous decisions
  • Maintain context across sessions

Use Cases:

  • Remembering user preferences
  • Recalling previous discussions
  • Maintaining conversation continuity
  • Building on past interactions

LoadArtifactsTool

Access and process uploaded files, enabling document analysis and file-based workflows.

Import:

import { LoadArtifactsTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "document_analyzer_agent",
  description: "An agent that analyzes and processes uploaded documents",
  tools: [new LoadArtifactsTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
artifact_namesarrayNoList of artifact names to load

How It's Triggered:

// User uploads files and asks: "Analyze my resume"
// Agent calls:
// load_artifacts({ artifact_names: ["resume.pdf"] })
// Agent retrieves and analyzes the resume

// User: "What's in the contract?"
// Agent calls:
// load_artifacts({ artifact_names: ["contract.pdf"] })
// Agent reads and analyzes the contract

Capabilities:

  • Load specific artifacts by name
  • Access file contents
  • Automatic format detection
  • Support for various file types (PDF, images, text, etc.)
  • List all available artifacts

Use Cases:

  • Document analysis
  • File processing workflows
  • Data extraction from uploads
  • Multi-file comparisons

Agent Orchestration Tools

TransferToAgentTool

Hand off work to another specialized agent, enabling complex multi-agent workflows.

Import:

import { TransferToAgentTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "router_agent",
  description: "An agent that routes requests to specialized agents",
  tools: [new TransferToAgentTool()],
});

Tool Parameters:

ParameterTypeRequiredDescription
agent_namestringYesThe name of the agent to transfer control to

How It's Triggered:

// User: "I need help with my payment"
// Router agent recognizes this is a payment issue:
// transfer_to_agent({ agent_name: "payment_specialist_agent" })
// Control transfers to the payment specialist

// User: "Can you check my order status?"
// Router agent calls:
// transfer_to_agent({ agent_name: "order_tracking_agent" })
// Control transfers to the order tracking agent

Capabilities:

  • Transfer control to specialized agents
  • Enable agent orchestration
  • Route requests based on expertise
  • Maintain conversation context during transfer

Use Cases:

  • Multi-agent systems
  • Specialized task routing
  • Domain-specific expertise
  • Complex workflow orchestration

ExitLoopTool

Exit from workflow loops when completion criteria are met.

Import:

import { ExitLoopTool } from "@iqai/adk";

Setup:

const agent = new LlmAgent({
  name: "loop_agent",
  description: "An agent that processes items in loops with exit control",
  tools: [new ExitLoopTool()],
});

Tool Parameters:

This tool takes no parameters.

How It's Triggered:

// Agent is processing items in a loop
// When instructed to exit, agent calls:
// exit_loop()
// Loop execution terminates and control returns to parent workflow

// Example workflow:
// Agent: Processing item 1... done
// Agent: Processing item 2... done
// Agent: Processing item 3... done
// Agent: All items processed, calling exit_loop()
// Workflow exits loop successfully

Capabilities:

  • Exit from execution loops
  • Controlled loop termination
  • Signal completion to parent workflow
  • Prevent infinite loops

Use Cases:

  • Batch processing workflows
  • Iterative tasks with completion criteria
  • Loop-based automation
  • Multi-step processes

Tool Combinations

Combine multiple built-in tools to create powerful agent capabilities. Here are some proven patterns:

Information Gathering

Combine search and memory tools for comprehensive research that builds on previous conversations:

const researchAgent = new LlmAgent({
  name: "researcher_agent",
  description:
    "A research assistant that searches the web for current information and recalls relevant details from previous conversations",
  instruction:
    "Use web search to find current information, then check memory for related previous discussions",
  tools: [new GoogleSearchTool(), new LoadMemoryTool()],
});

Document Processing

Process uploaded documents and save analysis results to files:

const documentAgent = new LlmAgent({
  name: "document_processor_agent",
  description:
    "An agent that analyzes uploaded documents and saves processed results",
  instruction:
    "Load and analyze uploaded documents, then save findings and summaries to files",
  tools: [
    new LoadArtifactsTool(),
    new FileOperationsTool({ basePath: "/output" }),
  ],
});

API Integration

Call external APIs and save response data for analysis or caching:

const apiAgent = new LlmAgent({
  name: "api_integration_agent",
  description: "An agent that calls external APIs and processes responses",
  instruction:
    "Make API calls to retrieve data, process responses, and save relevant information",
  tools: [new HttpRequestTool(), new FileOperationsTool()],
});

Interactive Workflows

Collect user input and confirmations while managing file operations:

const interactiveAgent = new LlmAgent({
  name: "interactive_workflow_agent",
  description: "An agent that guides users through multi-step processes",
  instruction:
    "Interact with users to gather requirements and approvals, then perform file operations based on their input",
  tools: [new UserInteractionTool(), new FileOperationsTool()],
});

Code Analysis & Modification

Search through code and make precise edits:

const codeAgent = new LlmAgent({
  name: "code_assistant_agent",
  description: "An agent that analyzes and modifies code files",
  instruction:
    "Search for code patterns, analyze files, and make precise edits as requested",
  tools: [new GrepTool(), new ReadTool(), new EditTool()],
});

Best Practices

To effectively use built-in tools in your agents:

Tool Selection

  • Choose Relevant Tools: Only add tools that match your agent's purpose. Too many tools can confuse the LLM and degrade performance.
  • Start Simple: Begin with essential tools and add more as needed.
  • Consider Dependencies: Some tool combinations work better together (e.g., GrepTool + EditTool for code modifications).

Security & Safety

  • Configure Safely: Set restrictive basePath for FileOperationsTool to prevent unauthorized access.
  • Validate Inputs: Use BashTool with caution and consider command whitelisting.
  • Secure Authentication: Be cautious with authentication headers in logs when using HttpRequestTool.
  • Protect Sensitive Data: Don't expose sensitive information in UserInteractionTool prompts.

Error Handling

  • Handle External Failures: Tools that call external services (e.g. GoogleSearchTool, HttpRequestTool) depend on network availability. Design agents to handle failures gracefully.
  • Trust Built-in Error Handling: Built-in tools handle common errors automatically (network failures, invalid files, user cancellations).
  • Provide Context: When errors occur, ensure your agent instructions guide the LLM on how to respond.

Performance

  • Set Appropriate Timeouts: Configure timeouts for HTTP requests and command executions based on expected response times.
  • Limit Search Results: Use numResults and maxMatches parameters to prevent overwhelming the LLM with data.
  • Monitor Long-Running Operations: Be aware that user interaction tools will pause agent execution.