Claude
Skills
Sign in
Back

web-search

Included with Lifetime
$97 forever

Implement web search capabilities using the z-ai-web-dev-sdk. Use this skill when the user needs to search the web, retrieve current information, find relevant content, or build applications with real-time web search functionality. Returns structured search results with URLs, snippets, and metadata.

Backend & APIsscripts

What this skill does


# Web Search Skill

This skill guides the implementation of web search functionality using the z-ai-web-dev-sdk package, enabling applications to search the web and retrieve current information.

## Installation Path

**Recommended Location**: `{project_path}/skills/web-search`

Extract this skill package to the above path in your project.

**Reference Scripts**: Example test scripts are available in the `{project_path}/skills/web-search/scripts/` directory for quick testing and reference. See `{project_path}/skills/web-search/scripts/web_search.ts` for a working example.

## Overview

The Web Search skill allows you to build applications that can search the internet, retrieve current information, and access real-time data from web sources.

**IMPORTANT**: z-ai-web-dev-sdk MUST be used in backend code only. Never use it in client-side code.

## Prerequisites

The z-ai-web-dev-sdk package is already installed. Import it as shown in the examples below.

## CLI Usage (For Simple Tasks)

For simple web search queries, you can use the z-ai CLI instead of writing code. This is ideal for quick information retrieval, testing search functionality, or command-line automation.

### Basic Web Search

```bash
# Simple search query
z-ai function --name "web_search" --args '{"query": "artificial intelligence"}'

# Using short options
z-ai function -n web_search -a '{"query": "latest tech news"}'
```

### Search with Custom Parameters

```bash
# Limit number of results
z-ai function \
  -n web_search \
  -a '{"query": "machine learning", "num": 5}'

# Search with recency filter (results from last N days)
z-ai function \
  -n web_search \
  -a '{"query": "cryptocurrency news", "num": 10, "recency_days": 7}'
```

### Save Search Results

```bash
# Save results to JSON file
z-ai function \
  -n web_search \
  -a '{"query": "climate change research", "num": 5}' \
  -o search_results.json

# Recent news with file output
z-ai function \
  -n web_search \
  -a '{"query": "AI breakthroughs", "num": 3, "recency_days": 1}' \
  -o ai_news.json
```

### Advanced Search Examples

```bash
# Search for specific topics
z-ai function \
  -n web_search \
  -a '{"query": "quantum computing applications", "num": 8}' \
  -o quantum.json

# Find recent scientific papers
z-ai function \
  -n web_search \
  -a '{"query": "genomics research", "num": 5, "recency_days": 30}' \
  -o genomics.json

# Technology news from last 24 hours
z-ai function \
  -n web_search \
  -a '{"query": "tech industry updates", "recency_days": 1}' \
  -o today_tech.json
```

### CLI Parameters

- `--name, -n`: **Required** - Function name (use "web_search")
- `--args, -a`: **Required** - JSON arguments object with:
  - `query` (string, required): Search keywords
  - `num` (number, optional): Number of results (default: 10)
  - `recency_days` (number, optional): Filter results from last N days
- `--output, -o <path>`: Optional - Output file path (JSON format)

### Search Result Structure

Each result contains:
- `url`: Full URL of the result
- `name`: Title of the page
- `snippet`: Preview text/description
- `host_name`: Domain name
- `rank`: Result ranking
- `date`: Publication/update date
- `favicon`: Favicon URL

### When to Use CLI vs SDK

**Use CLI for:**
- Quick information lookups
- Testing search queries
- Simple automation scripts
- One-off research tasks

**Use SDK for:**
- Dynamic search in applications
- Multi-step search workflows
- Custom result processing and filtering
- Production applications with complex logic

## Search Result Type

Each search result is a `SearchFunctionResultItem` with the following structure:

```typescript
interface SearchFunctionResultItem {
  url: string;          // Full URL of the result
  name: string;         // Title of the page
  snippet: string;      // Preview text/description
  host_name: string;    // Domain name
  rank: number;         // Result ranking
  date: string;         // Publication/update date
  favicon: string;      // Favicon URL
}
```

## Basic Web Search

### Simple Search Query

```javascript
import ZAI from 'z-ai-web-dev-sdk';

async function searchWeb(query) {
  const zai = await ZAI.create();

  const results = await zai.functions.invoke('web_search', {
    query: query,
    num: 10
  });

  return results;
}

// Usage
const searchResults = await searchWeb('What is the capital of France?');
console.log('Search Results:', searchResults);
```

### Search with Custom Result Count

```javascript
import ZAI from 'z-ai-web-dev-sdk';

async function searchWithLimit(query, numberOfResults) {
  const zai = await ZAI.create();

  const results = await zai.functions.invoke('web_search', {
    query: query,
    num: numberOfResults
  });

  return results;
}

// Usage - Get top 5 results
const topResults = await searchWithLimit('artificial intelligence news', 5);

// Usage - Get top 20 results
const moreResults = await searchWithLimit('JavaScript frameworks', 20);
```

### Formatted Search Results

```javascript
import ZAI from 'z-ai-web-dev-sdk';

async function getFormattedResults(query) {
  const zai = await ZAI.create();

  const results = await zai.functions.invoke('web_search', {
    query: query,
    num: 10
  });

  // Format results for display
  const formatted = results.map((item, index) => ({
    position: index + 1,
    title: item.name,
    url: item.url,
    description: item.snippet,
    domain: item.host_name,
    publishDate: item.date
  }));

  return formatted;
}

// Usage
const results = await getFormattedResults('climate change solutions');
results.forEach(result => {
  console.log(`${result.position}. ${result.title}`);
  console.log(`   ${result.url}`);
  console.log(`   ${result.description}`);
  console.log('');
});
```

## Advanced Use Cases

### Search with Result Processing

```javascript
import ZAI from 'z-ai-web-dev-sdk';

class SearchProcessor {
  constructor() {
    this.zai = null;
  }

  async initialize() {
    this.zai = await ZAI.create();
  }

  async search(query, options = {}) {
    const {
      num = 10,
      filterDomain = null,
      minSnippetLength = 0
    } = options;

    const results = await this.zai.functions.invoke('web_search', {
      query: query,
      num: num
    });

    // Filter results
    let filtered = results;

    if (filterDomain) {
      filtered = filtered.filter(item => 
        item.host_name.includes(filterDomain)
      );
    }

    if (minSnippetLength > 0) {
      filtered = filtered.filter(item => 
        item.snippet.length >= minSnippetLength
      );
    }

    return filtered;
  }

  extractDomains(results) {
    return [...new Set(results.map(item => item.host_name))];
  }

  groupByDomain(results) {
    const grouped = {};
    
    results.forEach(item => {
      if (!grouped[item.host_name]) {
        grouped[item.host_name] = [];
      }
      grouped[item.host_name].push(item);
    });

    return grouped;
  }

  sortByDate(results, ascending = false) {
    return results.sort((a, b) => {
      const dateA = new Date(a.date);
      const dateB = new Date(b.date);
      return ascending ? dateA - dateB : dateB - dateA;
    });
  }
}

// Usage
const processor = new SearchProcessor();
await processor.initialize();

const results = await processor.search('machine learning tutorials', {
  num: 15,
  minSnippetLength: 50
});

console.log('Domains found:', processor.extractDomains(results));
console.log('Grouped by domain:', processor.groupByDomain(results));
console.log('Sorted by date:', processor.sortByDate(results));
```

### News Search

```javascript
import ZAI from 'z-ai-web-dev-sdk';

async function searchNews(topic, timeframe = 'recent') {
  const zai = await ZAI.create();

  // Add time-based keywords to query
  const timeKeywords = {
    recent: 'latest news',
    today: 'today news',
    week: 'this week news',
    month: 'this month news'
  };

  const query = `${topic} ${timeKeywords[timeframe] || timeKeywords.recent}`;

  const results = await zai.functions.in

Related in Backend & APIs