WebInfer

Tools

Extend AI capabilities with tools for web search, web crawling, and custom functions

Tools allow LLMs to perform actions and access external data. WebInfer supports both custom tools you define and built-in stock tools like web search.

How Tools Work

1

You define tools with descriptions and schemas

The LLM uses descriptions to decide when to call each tool

2

LLM generates structured input matching your schema

The AI extracts parameters from the conversation context

3

Your execute function runs with the input

Executes in the browser - can access DOM, APIs, local storage

4

Tool result is sent back to the LLM

The AI can use the result to continue the conversation

Building UI-Capable Agents

Because tools run in the browser, you can build AI companions that understand user intent and directly manipulate your UI. Here's an example of a theme-switching assistant:

theme-agent.ts
import { generateText } from 'ai'import { webinfer } from 'webinfer-ai-provider'// AI companion that can control your app's UIconst result = await generateText({  model: webinfer(),  system: 'You are a helpful UI assistant. When users express discomfort, help them.',  prompt: 'My eyes hurt from staring at this bright screen',  tools: {    setTheme: {      description: 'Change the website theme. Use "dark" for low-light environments or when users mention eye strain, headaches, or brightness issues.',      inputSchema: {        type: 'object',        properties: {          theme: {            type: 'string',            enum: ['light', 'dark', 'system'],            description: 'The theme to apply'          }        },        required: ['theme']      },      execute: async ({ theme }) => {        // Direct DOM manipulation in the browser!        document.documentElement.classList.remove('light', 'dark')        if (theme !== 'system') {          document.documentElement.classList.add(theme)        }        localStorage.setItem('theme', theme)        return { success: true, appliedTheme: theme }      }    }  }})// The AI understands "my eyes hurt" → switches to dark mode// Response: "I've switched to dark mode for you. This should be easier on your eyes."

DOM Access

Modify elements, toggle classes, update styles in real-time

Storage APIs

Read/write localStorage, sessionStorage, IndexedDB

Browser APIs

Notifications, clipboard, geolocation, media devices

Defining Custom Tools

Define tools using JSON Schema for input validation:

custom-tools.ts
import { generateText } from 'ai'import { webinfer } from 'webinfer-ai-provider'const result = await generateText({  model: webinfer(),  prompt: 'Show an alert saying "Hello World"',  tools: {    showAlert: { // [!code highlight]      description: 'Display an alert notification to the user', // [!code highlight]      inputSchema: { // [!code highlight]        type: 'object', // [!code highlight]        properties: { // [!code highlight]          title: { // [!code highlight]            type: 'string', // [!code highlight]            description: 'The alert title' // [!code highlight]          }, // [!code highlight]          message: { // [!code highlight]            type: 'string', // [!code highlight]            description: 'The alert message body' // [!code highlight]          } // [!code highlight]        }, // [!code highlight]        required: ['title', 'message'] // [!code highlight]      }, // [!code highlight]      execute: async ({ title, message }) => { // [!code highlight]        // Runs in the browser! // [!code highlight]        alert(`${title}\n\n${message}`) // [!code highlight]        return { success: true, displayed: true } // [!code highlight]      } // [!code highlight]    }  }})

Tool Schema Reference

Tool Properties

description: string — Tells the LLM when to use this tool

inputSchema: JSONSchema7 — JSON Schema defining input parameters

execute?: (input, options) => Promise<output> — Function to run when called

needsApproval?: boolean | ((input) => boolean) — Require user confirmation

inputSchema Structure

type: 'object' — Always 'object' for tool inputs

properties: { [name]: { type, description } } — Define each parameter

required: string[] — List of required parameter names

Stock Tools

WebInfer includes built-in tools that you can easily add to your requests. These tools are production-ready and work out of the box.

webSearch
Built-in

Search the web using multiple engines (DuckDuckGo, Wikipedia, Reddit). Returns results with titles, snippets, URLs, and optional citations.

web-search.ts
import { createWebSearchTool } from '@webinfer/server'// Create with custom configconst webSearch = createWebSearchTool({  mode: 'auto',           // 'auto' | 'on' | 'off'  returnCitations: true,  // Include [1], [2] citations  maxSearchResults: 5,    // Limit results  engines: ['duckduckgo', 'wikipedia'], // Search engines})// Use in generateTextconst result = await generateText({  model: webinfer(),  prompt: 'What are the latest developments in AI?',  tools: { webSearch }})

Configuration Options

mode: 'auto' | 'on' | 'off'

returnCitations: boolean (default: true)

maxSearchResults: number (default: 5)

engines: ('duckduckgo' | 'wikipedia' | 'reddit')[]

Output

query: The search query executed

results: Array of {title, snippet, url, source}

citations: Formatted citation strings

totalResults: Number of results

crawlWebsite
Built-in

Fetch and extract content from web pages. Extracts title, description, main text content, and structured data (JSON-LD, Open Graph).

web-crawl.ts
import { createWebCrawlTool } from '@webinfer/server'// Create with custom configconst crawlWebsite = createWebCrawlTool({  mode: 'auto',  extractStructuredData: true,  // Extract JSON-LD, Open Graph  maxContentLength: 10000,      // Max chars to return  timeout: 10000,               // Request timeout (ms)  allowedPatterns: ['https://docs\\..*'],  // URL whitelist  blockedPatterns: ['.*\\.pdf$'],          // URL blacklist})// Use in generateTextconst result = await generateText({  model: webinfer(),  prompt: 'Summarize the content at https://example.com/article',  tools: { crawlWebsite }})

Configuration Options

mode: 'auto' | 'on' | 'off'

extractStructuredData: boolean (default: true)

maxContentLength: number (default: 10000)

timeout: number (default: 10000ms)

allowedPatterns: string[] (regex)

blockedPatterns: string[] (regex)

Output

url: The URL that was crawled

title: Page title

content: Extracted text content

description: Meta description

structuredData: JSON-LD, Open Graph data

Using Stock Tools

There are several ways to use the built-in tools:

1. Use Default Instances

default-tools.ts
import { webSearchTool, webCrawlTool, stockTools } from '@webinfer/server'// Use individual toolsconst result = await generateText({  model: webinfer(),  prompt: 'Search for TypeScript tutorials',  tools: {    webSearch: webSearchTool,    crawlWebsite: webCrawlTool,  }})// Or use all stock tools at onceconst result2 = await generateText({  model: webinfer(),  prompt: 'Find and summarize an article about React hooks',  tools: stockTools  // Includes webSearch and crawlWebsite})

2. Merge with Custom Tools

merge-tools.ts
import { mergeWithStockTools } from '@webinfer/server'// Define your custom toolsconst myTools = {  showNotification: {    description: 'Show a browser notification',    inputSchema: {      type: 'object',      properties: {        message: { type: 'string', description: 'Notification message' }      },      required: ['message']    },    execute: async ({ message }) => {      new Notification('WebInfer', { body: message })      return { sent: true }    }  }}// Merge with stock toolsconst allTools = mergeWithStockTools(myTools, {  webSearch: { maxSearchResults: 10 },  // Custom config  webCrawl: { mode: 'auto' }})// Now allTools contains: webSearch, crawlWebsite, showNotification

Using Tools Directly

You can also use the search and crawl functions directly without going through an LLM. This is useful for building custom UIs or testing tools.

direct-tools.ts
// Import from client package (browser-safe)import { webSearch, webCrawl, searchWikipedia } from 'webinfer'// Or from @webinfer/clientimport { webSearch, webCrawl } from '@webinfer/client'// Run a web search directlyconst searchResults = await webSearch('TypeScript tutorials', {  engines: ['duckduckgo', 'wikipedia'],  maxResults: 5,  returnCitations: true,})console.log(searchResults.results)// Crawl a URL directlyconst pageContent = await webCrawl('https://example.com', {  maxContentLength: 5000,  extractStructuredData: true,})console.log(pageContent.title, pageContent.content)// Use individual search enginesconst wikiResults = await searchWikipedia('JavaScript', 5)console.log(wikiResults)

Controlling Tool Selection

Use toolChoice to control how the LLM uses tools:

tool-choice.ts
// Let the LLM decide (default)toolChoice: 'auto'// Force the LLM to use at least one tooltoolChoice: 'required'// Prevent tool usagetoolChoice: 'none'// Force a specific tooltoolChoice: { type: 'tool', toolName: 'webSearch' }

Next Steps

Vercel AI SDK

Use tools with the Vercel AI SDK provider

View Guide →
API Reference

Complete API documentation

View API Docs →
Browser Usage

Use tools with the WebInfer SDK

View Guide →
Tool Playground

Test webSearch and webCrawl tools interactively

Open Playground →