La búsqueda en tierra brinda a los agentes de inteligencia artificial acceso a datos web en tiempo real para que dejen de alucinar con hechos obsoletos. El patrón funciona con cualquier marco de agente de Python: antes de que el LLM genere una respuesta, consulte una API de búsqueda para obtener resultados relevantes e inyéctelos en el contexto del mensaje. Este tutorial muestra un enfoque independiente del marco utilizando la API de Scavio que funciona ya sea que use OpenAI, Anthropic, LangChain o un bucle simple de Python. A $0,005 por búsqueda, la inmovilización agrega menos de un centavo por turno de agente.
Requisitos previos
- Python 3.9+ instalado
- solicita biblioteca instalada
- Una clave API de Scavio de scavio.dev
- Cualquier clave API de LLM (OpenAI, Anthropic, etc.)
Guia paso a paso
Paso 1: Crear la función de base de búsqueda
Cree una función reutilizable que acepte una consulta y devuelva un contexto formateado. Esta función se convierte en el puente entre su agente y los datos web en vivo.
import requests, os
API_KEY = os.environ['SCAVIO_API_KEY']
def ground_with_search(query: str, max_results: int = 5) -> str:
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'})
resp.raise_for_status()
results = resp.json().get('organic_results', [])[:max_results]
context = '\n'.join(
f'[{r["position"]}] {r["title"]}\n {r.get("snippet", "")}\n Source: {r["link"]}'
for r in results
)
return f'Search results for: {query}\n\n{context}'Paso 2: Inyecte conexión a tierra en cualquier plantilla de aviso
Envuelva su mensaje existente con contexto de búsqueda. Los datos de conexión a tierra van antes de la pregunta del usuario para que el LLM pueda hacer referencia a ellos.
def build_grounded_prompt(user_question: str) -> str:
search_context = ground_with_search(user_question)
return f"""Use the following search results to answer accurately.
Do not make up information not present in the results.
{search_context}
Question: {user_question}
Answer:"""
prompt = build_grounded_prompt('What is the latest Python version in 2026?')
print(prompt[:500])Paso 3: Usar con OpenAI / Anthropic directamente
Pase el mensaje básico a cualquier API de LLM. Este ejemplo muestra patrones OpenAI y Anthropic.
# With OpenAI:
from openai import OpenAI
client = OpenAI()
def ask_grounded_openai(question: str) -> str:
prompt = build_grounded_prompt(question)
response = client.chat.completions.create(
model='gpt-4o',
messages=[{'role': 'user', 'content': prompt}],
max_tokens=500
)
return response.choices[0].message.content
# With Anthropic:
import anthropic
client_a = anthropic.Anthropic()
def ask_grounded_anthropic(question: str) -> str:
prompt = build_grounded_prompt(question)
msg = client_a.messages.create(
model='claude-sonnet-4-20250514',
max_tokens=500,
messages=[{'role': 'user', 'content': prompt}]
)
return msg.content[0].textPaso 4: Úselo como herramienta LangChain
Si usa LangChain, incluya la función de búsqueda como una herramienta para que el agente pueda llamarla de forma autónoma cuando necesite datos actuales.
from langchain.tools import tool
@tool
def web_search(query: str) -> str:
"""Search the web for current information. Use this when you need
up-to-date facts, prices, or recent events."""
return ground_with_search(query)
# Register with any LangChain agent:
# agent = create_react_agent(llm, tools=[web_search], ...)Paso 5: Agregue almacenamiento en caché para reducir las búsquedas duplicadas
En conversaciones de varios turnos, el agente puede buscar lo mismo dos veces. Un caché TTL simple evita llamadas API duplicadas.
from functools import lru_cache
import hashlib
_cache = {}
def cached_ground(query: str, ttl_seconds: int = 300) -> str:
import time
key = hashlib.md5(query.encode()).hexdigest()
if key in _cache:
result, timestamp = _cache[key]
if time.time() - timestamp < ttl_seconds:
return result
result = ground_with_search(query)
_cache[key] = (result, time.time())
return result
# First call hits API, second returns cached result
ctx1 = cached_ground('python 3.14 release date')
ctx2 = cached_ground('python 3.14 release date') # cached, no API call
print(f'Cache size: {len(_cache)} entries')Ejemplo en Python
import os, requests
API_KEY = os.environ['SCAVIO_API_KEY']
def ground_with_search(query: str, max_results: int = 5) -> str:
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'})
resp.raise_for_status()
results = resp.json().get('organic_results', [])[:max_results]
return '\n'.join(
f'[{r["position"]}] {r["title"]}\n {r.get("snippet", "")}\n Source: {r["link"]}'
for r in results
)
def build_grounded_prompt(question: str) -> str:
ctx = ground_with_search(question)
return f'Use these search results to answer accurately:\n\n{ctx}\n\nQuestion: {question}\nAnswer:'
def main():
question = 'What is the latest Python version in 2026?'
prompt = build_grounded_prompt(question)
print(prompt)
print(f'\nGrounding cost: $0.005 per search')
if __name__ == '__main__':
main()Ejemplo en JavaScript
const API_KEY = process.env.SCAVIO_API_KEY;
async function groundWithSearch(query, maxResults = 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' })
});
const data = await resp.json();
return (data.organic_results || []).slice(0, maxResults)
.map(r => `[${r.position}] ${r.title}\n ${r.snippet || ''}\n Source: ${r.link}`)
.join('\n');
}
async function main() {
const question = 'What is the latest Python version in 2026?';
const context = await groundWithSearch(question);
const prompt = `Use these results to answer:\n\n${context}\n\nQ: ${question}\nA:`;
console.log(prompt);
console.log('\nGrounding cost: $0.005 per search');
}
main().catch(console.error);Salida esperada
Search results for: What is the latest Python version in 2026?
[1] Python Release Python 3.14.0
Python 3.14.0 was released on April 15, 2026 with experimental JIT...
Source: https://www.python.org/downloads/release/python-3140/
[2] What's New In Python 3.14
This article explains the new features in Python 3.14...
Source: https://docs.python.org/3/whatsnew/3.14.html
Grounding cost: $0.005 per search