Skip to content

nvrunx/openrouter-web-search

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OpenRouter Web Search

A Python application that combines OpenRouter AI models with web search capabilities to provide intelligent responses enriched with current web information.

Features

  • 🤖 Multiple AI Models: Access 100+ AI models through OpenRouter
  • 🔍 Web Search Integration: Search DuckDuckGo, Wikipedia, and Google
  • 💬 Interactive Chat Mode: Real-time conversation with AI
  • 📦 CLI Interface: Single query processing with various options
  • 📊 JSON Output: Structured data output for integrations
  • 🔄 Model Switching: Easy switching between different AI models

Installation

  1. Clone the repository:

    git clone https://github.com/nvrunx/openrouter-web-search.git
    cd openrouter-web-search
  2. Install dependencies:

    pip install -r requirements.txt
  3. Set up environment variables:

    cp .env.example .env

    Edit .env and add your OpenRouter API key:

    OPENROUTER_API_KEY=your_openrouter_api_key_here
    

Getting API Keys

OpenRouter API Key (Required)

  1. Visit OpenRouter.ai
  2. Sign up for an account
  3. Go to Keys section
  4. Create a new API key
  5. Add it to your .env file

Cost: OpenRouter offers competitive pricing with models starting from $0.0005 per 1K tokens.

Usage

Interactive Mode

Run the application in interactive chat mode:

python main.py

This starts an interactive session where you can:

  • Ask questions and get AI responses with web search
  • Type models to see and switch between available AI models
  • Type nosearch <query> to query without web search
  • Type quit, exit, or q to end the session

Single Query Mode

Process a single query:

# Basic query
python main.py -q "What is the latest in AI technology?"

# Use specific model
python main.py -q "Explain quantum computing" -m "anthropic/claude-3-haiku"

# Skip web search
python main.py -q "What is Python?" --no-search

# JSON output
python main.py -q "Latest AI news" --json

Command Line Options

Options:
  -q, --query QUERY        Single query to process
  -m, --model MODEL        AI model to use (default: openai/gpt-3.5-turbo)
  --no-search              Skip web search and use AI only
  --json                   Output results in JSON format
  --list-models            List available models and exit
  -h, --help               Show help message

Available Models

List all available models:

python main.py --list-models

Popular models include:

  • openai/gpt-3.5-turbo (Default - Fast and cost-effective)
  • openai/gpt-4 (Most capable OpenAI model)
  • anthropic/claude-3-haiku (Fast Claude model)
  • anthropic/claude-3-sonnet (Balanced Claude model)
  • google/gemini-pro (Google's flagship model)
  • meta-llama/llama-3-70b-instruct (Open source alternative)

Code Structure

openrouter_client.py

Main OpenRouter API client with features:

  • Model listing and selection
  • Chat completions with streaming support
  • Token usage tracking
  • Error handling

web_search.py

Web search tool supporting:

  • DuckDuckGo API: Instant answers and related topics
  • Wikipedia API: Encyclopedia search results
  • Google Search: Web scraping (educational purposes)
  • Comprehensive Search: Combines multiple sources

main.py

Main application featuring:

  • Interactive chat mode
  • CLI argument processing
  • Query enhancement with search results
  • Multiple output formats

Examples

Basic Usage

from openrouter_client import OpenRouterClient
from web_search import WebSearchTool

# Initialize clients
ai_client = OpenRouterClient()
search_tool = WebSearchTool()

# Simple AI query
response = ai_client.simple_query("Explain machine learning")
print(response)

# Web search
results = search_tool.comprehensive_search("Python tutorials", 5)
print(search_tool.format_results(results))

Advanced Usage

from main import AIWebSearchApp

# Initialize the combined app
app = AIWebSearchApp()

# Query with web search
result = app.search_and_ask(
    "What are the latest developments in AI?",
    model="anthropic/claude-3-sonnet",
    use_search=True,
    max_search_results=10
)

print(result['ai_response'])

Cost Optimization

Since you're cost-conscious about API usage:

  1. Use efficient models: Start with gpt-3.5-turbo for most queries
  2. Limit search results: Reduce max_search_results to save on context tokens
  3. Skip search when not needed: Use --no-search for general knowledge questions
  4. Monitor usage: Check token usage in responses

Estimated costs (with gpt-3.5-turbo):

  • Simple query: ~$0.001-0.002
  • Query with web search: ~$0.003-0.005
  • Interactive session (10 queries): ~$0.02-0.05

Troubleshooting

Common Issues

  1. Missing API Key:

    ValueError: OpenRouter API key is required
    

    Solution: Set OPENROUTER_API_KEY in your .env file

  2. Network Errors:

    Error: Request timeout
    

    Solution: Check internet connection, try different search sources

  3. Rate Limiting:

    Error: Too Many Requests
    

    Solution: Wait a moment before retrying, consider upgrading API plan


Built by nvrunx 🚀

If you find this project useful, please give it a star! ⭐

About

Python application with OpenRouter API integration and web search capabilities

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages