← Back to Plugins
Integration

Serpapi Openclaw

guxiaolong01 By guxiaolong01 ⭐ 1 stars 👁 5 views ▲ 0 votes

SerpApi search plugin for OpenClaw with optional tools, config validation, and retry logic

GitHub

Install

npm install
   npm

Configuration Example

{
  "plugins": {
    "load": {
      "paths": ["/path/to/serpapi-search-plugin"]  // โš ๏ธ IMPORTANT: Update this path!
    },
    "entries": {
      "serpapi-search": {
        "enabled": true,
        "config": {
          "apiKey": "your-serpapi-api-key",
          "cacheTtl": 3600,
          "rateLimit": 50,
          "defaultLocation": "cn",
          "defaultLanguage": "zh-cn"
        }
      }
    }
  },
  "agents": {
    "defaults": {
      "tools": {
        "allow": ["serpapi_search", "serpapi_stats", "serpapi_clear_cache"]
      }
    }
  }
}

README

# SerpApi Search Plugin for OpenClaw

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![OpenClaw Plugin](https://img.shields.io/badge/OpenClaw-Plugin-blue.svg)](https://docs.openclaw.ai/plugins)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue.svg)](https://www.typescriptlang.org/)

A powerful SerpApi search provider plugin for OpenClaw that enables real-time web search with intelligent caching, rate limiting, and Chinese language optimization.

## ๐Ÿš€ Features

- **๐Ÿ” Real-time Web Search**: Google search via SerpApi with rich result parsing
- **๐ŸŒ Chinese Optimization**: Default Chinese language (zh-cn) and China location (cn)
- **๐Ÿ’พ Smart Caching**: LRU cache with configurable TTL to reduce API calls
- **โšก Rate Limiting**: Built-in rate limit protection (configurable per hour)
- **๐Ÿ“Š Statistics Monitoring**: Real-time cache hit rate and usage statistics
- **๐Ÿ”„ Automatic Retry**: Exponential backoff retry mechanism for network resilience
- **๐Ÿ”’ Security First**: All tools marked as optional (require explicit enable)
- **๐Ÿ”ง Flexible Configuration**: Customizable search parameters and defaults

## ๐Ÿ“ฆ Installation

### From ClawHub (Recommended)
```bash
clawhub install serpapi-search
```

### Manual Installation
1. Download or clone this repository to your OpenClaw extensions directory:
   ```bash
   cd ~/.openclaw/extensions
   git clone https://github.com/gomelong/serpapi-openclaw-plugin serpapi-search
   ```

2. Install dependencies and build:
   ```bash
   cd serpapi-search
   npm install
   npm run build
   ```

## โš™๏ธ Configuration

### Step 1: Add plugin configuration

Add the following to your OpenClaw configuration file (`~/.openclaw/openclaw.json`):

```json
{
  "plugins": {
    "load": {
      "paths": ["/path/to/serpapi-search-plugin"]  // โš ๏ธ IMPORTANT: Update this path!
    },
    "entries": {
      "serpapi-search": {
        "enabled": true,
        "config": {
          "apiKey": "your-serpapi-api-key",
          "cacheTtl": 3600,
          "rateLimit": 50,
          "defaultLocation": "cn",
          "defaultLanguage": "zh-cn"
        }
      }
    }
  },
  "agents": {
    "defaults": {
      "tools": {
        "allow": ["serpapi_search", "serpapi_stats", "serpapi_clear_cache"]
      }
    }
  }
}
```

### Step 2: Important Configuration Notes

#### 1. **Plugin Path Configuration**
- **CRITICAL**: You must set the correct path in `plugins.load.paths`
- **Example**: If installed via ClawHub, path might be `~/.openclaw/extensions/serpapi-search`
- **Verification**: After restart, check logs for `[plugins] ๆญฃๅœจๆณจๅ†Œ SerpApi ๆœ็ดขๆ’ไปถ...`

#### 2. **Tool Allow List**
- All tools are marked as `optional: true` (security best practice)
- You must explicitly allow them in `agents.defaults.tools.allow`
- Tools will not be available without this configuration

#### 3. **API Key Requirement**
- A valid SerpApi API key is **required**
- Get your API key from: https://serpapi.com/manage-api-key
- Free tier available with 100 searches/month

### Configuration Options

| Option | Type | Default | Description | Validation |
|--------|------|---------|-------------|------------|
| `apiKey` | string | **Required** | Your SerpApi API key | Must be valid API key |
| `cacheTtl` | number | 3600 | Cache TTL in seconds | 60-86400 seconds |
| `rateLimit` | number | 50 | Maximum searches per hour | 1-1000 per hour |
| `defaultLocation` | string | "cn" | Default country code | Any valid country code |
| `defaultLanguage` | string | "zh-cn" | Default language code | Any valid language code |

## ๐Ÿ› ๏ธ Usage

### Available Tools

The plugin provides three tools:

#### 1. `serpapi_search` - Execute web search
```typescript
// Parameters
{
  query: "search query",      // Required
  num_results: 5,            // Optional, default: 5 (1-10)
  location: "cn",            // Optional, default: from config
  language: "zh-cn"          // Optional, default: from config
}

// Returns formatted search results with:
// - Direct answers (if available)
// - Knowledge graph (if available)
// - Organic search results
```

#### 2. `serpapi_stats` - Get plugin statistics
```typescript
// Returns
{
  cache: {
    size: 10,                // Current cache size
    hits: 45,                // Cache hits
    misses: 5,               // Cache misses
    hitRate: "90%"           // Cache hit rate
  },
  rate_limit: {
    used: 15,                // Searches used this hour
    limit: 50,               // Rate limit
    remaining: 35,           // Remaining searches
    reset_in: "1800็ง’"       // Time until reset
  }
}
```

#### 3. `serpapi_clear_cache` - Clear search cache
```typescript
// Clears all cached search results
// Returns: { success: true, message: "็ผ“ๅญ˜ๅทฒๆธ…้™ค" }
```

### CLI Commands

The plugin also provides CLI commands:

```bash
# Test search functionality
openclaw serpapi:test "OpenClaw documentation" -n 3

# View plugin statistics
openclaw serpapi:stats
```

## ๐Ÿ”ง Development

### Project Structure
```
serpapi-search-plugin/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ index.ts            # Plugin entry point
โ”‚   โ”œโ”€โ”€ search.ts           # Core search logic
โ”‚   โ””โ”€โ”€ types.ts            # TypeScript definitions
โ”œโ”€โ”€ dist/                   # Built files
โ”œโ”€โ”€ test/                   # Test files
โ”œโ”€โ”€ package.json           # Project configuration
โ”œโ”€โ”€ tsconfig.json          # TypeScript configuration
โ””โ”€โ”€ openclaw.plugin.json   # Plugin manifest
```

### Build and Test
```bash
# Install dependencies
npm install

# Build the plugin
npm run build

# Run tests
npm test

# Lint code
npm run lint

# Development mode (watch for changes)
npm run dev
```

## ๐Ÿ“Š Performance Optimizations

This plugin includes several optimizations:

### 1. Security Optimization
- All tools are marked as `optional: true`
- Requires explicit enable in agent tool allowlists
- Follows OpenClaw security best practices

### 2. Configuration Validation
- Range validation for `cacheTtl` (60-86400 seconds)
- Range validation for `rateLimit` (1-1000 per hour)
- Prevents configuration errors

### 3. Error Handling
- Automatic retry with exponential backoff (1s, 2s, 4s...)
- Default 3 retry attempts
- Detailed error messages

## ๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## ๐Ÿ“ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- [SerpApi](https://serpapi.com/) for providing the search API
- [OpenClaw](https://openclaw.ai/) for the amazing platform
- All contributors and users of this plugin

## ๐Ÿšจ Troubleshooting

### Common Installation Issues

#### 1. Plugin Not Loading
**Symptoms**: No `[plugins] ๆญฃๅœจๆณจๅ†Œ SerpApi ๆœ็ดขๆ’ไปถ...` in logs
**Solutions**:
- Check `plugins.load.paths` points to correct directory
- Verify plugin is built: `ls -la dist/index.js`
- Restart OpenClaw: `openclaw gateway restart`

#### 2. Tools Not Available
**Symptoms**: Tools not showing in agent tool list
**Solutions**:
- Verify `agents.defaults.tools.allow` includes all three tools
- Check plugin is enabled: `openclaw plugins list | grep serpapi`
- Tools are optional - must be explicitly allowed

#### 3. Search Not Working
**Symptoms**: Search returns errors or no results
**Solutions**:
- Verify API key is valid and has remaining searches
- Check rate limit: `openclaw serpapi:stats`
- Test with simple query: `openclaw serpapi:test "test"`

#### 4. Configuration Errors
**Symptoms**: OpenClaw fails to start
**Solutions**:
- Validate JSON: `python3 -m json.tool ~/.openclaw/openclaw.json`
- Check config ranges: `cacheTtl` (60-86400), `rateLimit` (1-1000)
- Remove and re-add plugin configuration

### Verification Steps

After installation, run these checks:

```bash
# 1. Check plugin loaded
openclaw plugins list | grep serpapi

# 2. Test search functionality
openclaw serpapi:test "OpenClaw" -n 2

# 3. Check statistics
openclaw serpapi:stats

# 4. Verify service status
openclaw gateway status
```

## ๐Ÿ“ž Support

- **Issues**: [GitHub Issues](https://github.com/gomelong/serpapi-openclaw-plugin/issues)
- **Documentation**: [OpenClaw Docs](https://docs.openclaw.ai/plugins)
- **Email**: [email protected]

## ๐Ÿ”„ Changelog

### 1.0.0 (Initial Release)
- Initial release with three core optimizations
- Security: Tools marked as optional
- Configuration: Added range validation
- Error handling: Added retry mechanism
- Basic search functionality with caching and rate limiting

---

**Enjoy powerful web search in your OpenClaw assistant!** ๐Ÿ”๐Ÿš€
integration

Comments

Sign in to leave a comment

Loading comments...