
Brave Search Agent
Overview
A Cloudflare Workers AI agent that provides advanced search capabilities using the Brave Search API. This agent offers multiple search modes, from standard web search to AI-powered intelligent search, with comprehensive logging and performance metrics.
The agent can be interacted with via HTTP requests or WebSockets, providing flexible integration options for various applications. It features robust parameter handling, type validation, and detailed performance logging throughout the search process.
Built with a focus on performance and reliability, the agent includes automatic type conversion, empty value handling, and parameter filtering to ensure optimal interaction with the Brave Search API.
Key Features
Multiple Search Modes
- Direct Search: Standard web search using Brave Search API
- Optimized Search: Enhanced search using query suggestions to improve results
- Agentic Search: AI-powered search using Google's Gemini Pro model
- AI Search: Configurable AI-powered search with graceful error handling
Performance Optimization
- Comprehensive logging system with timing measurements
- Performance metrics for all API calls and data processing
- Smart retry logic for API failures
- Efficient parameter processing and validation
Advanced Query Processing
- Query suggestions from Brave Suggest API
- Automatic parameter type conversion
- Empty value handling to prevent API errors
- Customizable search parameters (count, safesearch, country, etc.)
State Management
- Conversation history tracking
- Recent searches storage
- User preference management
- Session state persistence
Flexible Integration
- RESTful HTTP endpoints
- WebSocket support for real-time interaction
- JSON-based request/response format
- Comprehensive error handling and reporting
Architecture
Core Components
Search Engine
- Handles all search operations across different modes
- Manages API interactions with Brave Search and Suggest APIs
- Implements parameter validation and processing
- Provides unified response formatting
AI Integration
- Google Gemini Pro integration for intelligent search
- Context-aware query processing
- Natural language understanding
- Enhanced result synthesis
Logging System
- Structured logging with consistent prefixes
- Timing measurements for performance analysis
- Error tracking and debugging information
- Request/response logging for troubleshooting
State Manager
- Maintains conversation context
- Stores user preferences
- Tracks search history
- Manages session data
Technical Implementation
The Brave Search Agent is built using TypeScript and deployed on Cloudflare Workers, leveraging edge computing for global low-latency performance. The implementation focuses on robustness, performance, and ease of use.
Parameter Processing
The agent includes sophisticated parameter processing utilities that ensure all parameters are correctly formatted before being sent to the Brave Search API. This includes automatic type conversion from strings to their expected types (numbers, booleans, arrays).
Performance Logging
Comprehensive performance logging throughout the codebase provides detailed insights into execution times for specific operations, helping identify bottlenecks and optimize performance.
Error Handling
Robust error handling ensures graceful degradation when services are unavailable, with detailed error messages for debugging and user-friendly responses for production use.
API Endpoints
HTTP Endpoints
POST /agents/brave-search-agent/default/search
- Direct searchPOST /agents/brave-search-agent/default/optimized-search
- Optimized search with suggestionsPOST /agents/brave-search-agent/default/agentic-search
- AI-powered searchPOST /agents/brave-search-agent/default/ai-search
- Configurable AI searchPOST /agents/brave-search-agent/default/suggest
- Query suggestionsGET /agents/brave-search-agent/default/state
- Get current statePOST /agents/brave-search-agent/default/preferences
- Update preferencesPOST /agents/brave-search-agent/default/clear-history
- Clear search history
WebSocket Messages
The agent supports WebSocket connections for real-time interaction with JSON message types including:
search_request
- Standard searchoptimized_search_request
- Enhanced searchagentic_search_request
- AI-powered searchai_search_request
- Configurable AI searchsuggest_request
- Query suggestionsupdate_preferences
- Preference updatesclear_history
- History clearing
Usage Examples
Direct Search
curl -X POST http://localhost:8787/agents/brave-search-agent/default/search \
-H "Content-Type: application/json" \
-d '{
"query": "weather in San Francisco",
"options": {
"count": 10,
"safesearch": "moderate"
}
}'
AI-Powered Search
curl -X POST http://localhost:8787/agents/brave-search-agent/default/agentic-search \
-H "Content-Type: application/json" \
-d '{
"query": "What are the best restaurants in New York City?",
"preferences": {
"safesearch": "moderate",
"country": "US"
}
}'
WebSocket Example
const ws = new WebSocket('ws://localhost:8787/agents/brave-search/default');
ws.send(JSON.stringify({
type: 'optimized_search_request',
query: 'latest AI developments',
searchOptions: {
count: 15,
safesearch: 'moderate'
},
suggestOptions: {
count: 3
}
}));
Performance Log Example
[SEARCH] Direct search started for: "weather in San Francisco"
[TIMING] Direct search - Update history: 5ms
[BRAVE_SEARCH] Search started for: "weather in San Francisco"
[TIMING] Brave search - Process parameters: 2ms
[TIMING] Brave search - Build URL: 1ms
[TIMING] Brave search - Fetch request: 320ms
[TIMING] Brave search - Parse JSON: 15ms
[TIMING] Brave search - Process results: 8ms
[TIMING] Brave search - Total execution time: 346ms
[SEARCH] Direct search results: 10 web results, 10 total results
Deployment
The agent is designed for easy deployment on Cloudflare Workers:
Prerequisites
- Node.js (v16 or later)
- Wrangler CLI (v4 or later)
- Cloudflare account
- Brave Search API key
- Brave Suggest API key
- Google Gemini API key (for AI features)
Deployment Steps
# Install dependencies
npm install
# Deploy to Cloudflare Workers
npm run deploy
# Set up API keys as secrets
wrangler secret put BRAVE_SEARCH_API_KEY
wrangler secret put BRAVE_SUGGEST_API_KEY
wrangler secret put GEMINI_API_KEY