Los agentes de IA sin acceso a búsquedas alucinan con información obsoleta. Agregar una herramienta de búsqueda lleva menos de 10 minutos y le brinda a su agente acceso web en tiempo real. Este tutorial para principiantes le explica cómo obtener una clave API, realizar su primera llamada de búsqueda e integrar la búsqueda en un ciclo de agente básico. Scavio ofrece 250 búsquedas gratuitas al mes, para que puedas crear y probar sin gastar nada.
Requisitos previos
- Python 3.9+ o Node.js 18+ instalado
- Una clave API de Scavio gratuita de scavio.dev
- 10 minutos de tiempo
Guia paso a paso
Paso 1: Obtenga su clave API y realice su primera búsqueda
Regístrese en scavio.dev para obtener una clave API gratuita (250 búsquedas al mes incluidas). Luego haga su primera llamada de búsqueda.
import requests, os
# Set your API key as an environment variable:
# export SCAVIO_API_KEY=your-key-here
API_KEY = os.environ['SCAVIO_API_KEY']
# Your first search
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={
'x-api-key': API_KEY,
'Content-Type': 'application/json'
},
json={
'query': 'what is an AI agent',
'country_code': 'us',
'num_results': 5
})
results = resp.json().get('organic_results', [])
print(f'Search returned {len(results)} results:\n')
for r in results:
print(f' {r["title"]}')
print(f' {r["link"]}')
print(f' {r.get("snippet", "")[:100]}...')
print()Paso 2: Envuélvalo en una función de búsqueda reutilizable
Cree una función de búsqueda limpia que pueda utilizar en todo su proyecto. Esta es la función que llamará su agente.
def search(query: str, count: int = 5) -> list:
"""Search the web and return structured results."""
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
json={'query': query, 'country_code': 'us', 'num_results': count})
if resp.status_code != 200:
print(f'Search error: {resp.status_code}')
return []
results = resp.json().get('organic_results', [])
return [{
'title': r['title'],
'url': r['link'],
'snippet': r.get('snippet', '')
} for r in results]
# Test it
results = search('best python libraries 2026')
for r in results:
print(f'{r["title"]}: {r["url"]}')
print(f'\nCost: $0.005 per search, {250} free/month')Paso 3: Cree un bucle de agente simple con búsqueda
Cree un agente básico que decida cuándo buscar y utilice los resultados para responder preguntas. Ésta es la base de cualquier agente de búsqueda aumentada.
def simple_agent(question: str) -> str:
"""A basic agent that searches before answering."""
print(f'Question: {question}')
# Step 1: Search for relevant information
results = search(question, count=3)
if not results:
return 'I could not find any search results for that question.'
# Step 2: Build context from search results
context = '\n'.join(
f'- {r["title"]}: {r["snippet"][:150]}'
for r in results
)
# Step 3: Format the answer (in a real agent, send to LLM)
answer = f'Based on {len(results)} search results:\n\n{context}'
answer += f'\n\nSources:\n'
for r in results:
answer += f' - {r["url"]}\n'
return answer
# Ask the agent a question
answer = simple_agent('What are the best Python web frameworks in 2026?')
print(answer)
print(f'\nTotal cost: $0.005 (1 search query)')Ejemplo en Python
import requests, os
API_KEY = os.environ['SCAVIO_API_KEY']
def search(query, count=5):
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
json={'query': query, 'country_code': 'us', 'num_results': count})
return [{'title': r['title'], 'url': r['link'], 'snippet': r.get('snippet', '')}
for r in resp.json().get('organic_results', [])]
results = search('what is an AI agent')
for r in results:
print(f'{r["title"]}: {r["url"]}')
print(f'\nFree tier: 250 searches/month')Ejemplo en JavaScript
const API_KEY = process.env.SCAVIO_API_KEY;
async function search(query, count = 5) {
const resp = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST',
headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ query, country_code: 'us', num_results: count })
});
const data = await resp.json();
return (data.organic_results || []).map(r => ({
title: r.title, url: r.link, snippet: r.snippet || ''
}));
}
search('what is an AI agent').then(results => {
results.forEach(r => console.log(`${r.title}: ${r.url}`));
console.log(`\nFree tier: 250 searches/month`);
});Salida esperada
Search returned 5 results:
What Is an AI Agent? - IBM
https://www.ibm.com/topics/ai-agents
An AI agent is a software program that can interact with its environment...
AI Agents Explained - Microsoft
https://learn.microsoft.com/en-us/ai/agents
AI agents are autonomous systems that perceive, decide, and act...
Based on 3 search results:
- What Is an AI Agent? - IBM: An AI agent is a software program...
- AI Agents Explained - Microsoft: AI agents are autonomous systems...
Total cost: $0.005 (1 search query)
Free tier: 250 searches/month