Ketch for Pi est un agent de codage qui ne dispose pas de recherche web intégrée. Sans recherche, il ne peut pas consulter la documentation, vérifier les API ou trouver des réponses actuelles. Ce tutoriel ajoute la recherche Scavio comme outil que l'agent peut appeler, renvoyant des résultats structurés sans avoir besoin d'un navigateur ou d'une instance SearXNG. Chaque recherche coûte 0,005 $.
Prérequis
- Python 3.8+
- bibliothèque requests
- Une clé API Scavio depuis scavio.dev
- Agent Ketch for Pi installé
Parcours
Étape 1: Créer la fonction d'outil de recherche
Construire une fonction de recherche qui renvoie des résultats dans le format attendu par Ketch.
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"]}')Étape 2: Enregistrer comme outil Ketch
Envelopper la fonction de recherche en une définition d'outil que Ketch peut découvrir et appeler.
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)Étape 3: Intégrer dans la boucle de l'agent
Ajouter l'outil de recherche aux outils disponibles de l'agent afin qu'il puisse appeler la recherche pendant les tâches.
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')Exemple 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"]}')Exemple 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}`));Sortie attendue
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