Tutorial

How to Add Search to Ketch for Pi Coding Agent

Give Ketch for Pi coding agent live search using the Scavio API. No browser, no SearXNG, just structured results via API.

Ketch for Pi is a coding agent that lacks built-in web search. Without search, it cannot look up documentation, verify APIs, or find current answers. This tutorial adds Scavio search as a tool the agent can call, returning structured results without needing a browser or SearXNG instance. Each search costs $0.005.

Prerequisites

  • Python 3.8+
  • requests library
  • A Scavio API key from scavio.dev
  • Ketch for Pi agent installed

Walkthrough

Step 1: Create the search tool function

Build a search function that returns results in the format Ketch expects.

Python
import os, requests, json

API_KEY = os.environ['SCAVIO_API_KEY']
SH = {'x-api-key': API_KEY, 'Content-Type': 'application/json'}

def search_web(query, num_results=5):
    """Search the web and return structured results for the agent."""
    resp = requests.post('https://api.scavio.dev/api/v1/search',
        headers=SH, json={'query': query, 'country_code': 'us'}, timeout=10)
    resp.raise_for_status()
    data = resp.json()
    results = []
    for r in data.get('organic_results', [])[:num_results]:
        results.append({
            'title': r.get('title', ''),
            'url': r.get('link', ''),
            'snippet': r.get('snippet', ''),
        })
    paa = data.get('people_also_ask', [])
    related = [q.get('question', '') for q in paa[:3]]
    return {
        'results': results,
        'related_questions': related,
        'query': query,
        'count': len(results)
    }

# Test
result = search_web('python requests library documentation')
print(f'Found {result["count"]} results for: {result["query"]}')
for r in result['results'][:3]:
    print(f'  - {r["title"][:50]}')
    print(f'    {r["url"]}')

Step 2: Register as a Ketch tool

Wrap the search function as a tool definition that Ketch can discover and call.

Python
SEARCH_TOOL = {
    'name': 'web_search',
    'description': 'Search the web for current information. Use for docs, APIs, errors, or any question needing fresh data.',
    'parameters': {
        'type': 'object',
        'properties': {
            'query': {'type': 'string', 'description': 'Search query'},
            'num_results': {'type': 'integer', 'description': 'Number of results (default 5)', 'default': 5}
        },
        'required': ['query']
    }
}

def handle_tool_call(tool_name, arguments):
    """Route tool calls from the agent."""
    if tool_name == 'web_search':
        query = arguments.get('query', '')
        num = arguments.get('num_results', 5)
        result = search_web(query, num)
        return json.dumps(result, indent=2)
    return json.dumps({'error': f'Unknown tool: {tool_name}'})

# Simulate agent calling the tool
response = handle_tool_call('web_search', {'query': 'ketch pi agent setup guide'})
print(response)

Step 3: Integrate into the agent loop

Add the search tool to the agent's available tools so it can call search during tasks.

Python
def agent_loop_with_search(task):
    """Example agent loop that uses search when needed."""
    print(f'Agent task: {task}')
    print(f'Available tools: [web_search]')
    # Step 1: Agent decides it needs to search
    print(f'\n  Agent: I need current information. Calling web_search...')
    search_result = search_web(task)
    print(f'  Search returned {search_result["count"]} results')
    # Step 2: Agent processes results
    if search_result['results']:
        top = search_result['results'][0]
        print(f'  Agent: Top result is "{top["title"][:40]}"')
        print(f'  Agent: URL - {top["url"]}')
        print(f'  Agent: Snippet - {top["snippet"][:80]}')
    # Step 3: Agent uses related questions for deeper search
    if search_result['related_questions']:
        print(f'\n  Agent: Found related questions:')
        for q in search_result['related_questions']:
            print(f'    - {q}')
    print(f'\n  Cost: $0.005 per search call')

agent_loop_with_search('how to use FastAPI with async database')

Python Example

Python
import os, requests
SH = {'x-api-key': os.environ['SCAVIO_API_KEY'], 'Content-Type': 'application/json'}

def agent_search(query):
    data = requests.post('https://api.scavio.dev/api/v1/search',
        headers=SH, json={'query': query, 'country_code': 'us'}, timeout=10).json()
    return [{'title': r['title'], 'url': r['link']} for r in data.get('organic_results', [])[:5]]

results = agent_search('FastAPI async tutorial')
for r in results:
    print(f'{r["title"][:50]} -> {r["url"]}')

JavaScript Example

JavaScript
const SH = { 'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json' };
const data = await fetch('https://api.scavio.dev/api/v1/search', {
  method: 'POST', headers: SH,
  body: JSON.stringify({ query: 'FastAPI async tutorial', country_code: 'us' })
}).then(r => r.json());
const results = (data.organic_results || []).slice(0, 5);
results.forEach(r => console.log(`${r.title} -> ${r.link}`));

Expected Output

JSON
Found 5 results for: python requests library documentation
  - Requests: HTTP for Humans - Python Requests
    https://docs.python-requests.org/en/latest/
  - Requests Library Documentation - PyPI
    https://pypi.org/project/requests/

Agent task: how to use FastAPI with async database
Available tools: [web_search]

  Agent: I need current information. Calling web_search...
  Search returned 5 results
  Agent: Top result is "FastAPI with Async SQLAlchemy Guide"

  Cost: $0.005 per search call

Related Tutorials

Frequently Asked Questions

Most developers complete this tutorial in 15 to 30 minutes. You will need a Scavio API key (free tier works) and a working Python or JavaScript environment.

Python 3.8+. requests library. A Scavio API key from scavio.dev. Ketch for Pi agent installed. A Scavio API key gives you 250 free credits per month.

Yes. The free tier includes 250 credits per month, which is more than enough to complete this tutorial and prototype a working solution.

Scavio has a native LangChain package (langchain-scavio), an MCP server, and a plain REST API that works with any HTTP client. This tutorial uses the raw REST API, but you can adapt to your framework of choice.

Start Building

Give Ketch for Pi coding agent live search using the Scavio API. No browser, no SearXNG, just structured results via API.