Los agentes de LangChain necesitan herramientas de búsqueda para acceder a información actual. Este tutorial crea una herramienta LangChain personalizada utilizando la API de Scavio que admite múltiples plataformas (Google, Reddit, YouTube, Amazon, Walmart) a través de una única definición de herramienta. El agente selecciona la plataforma según el contexto de la consulta y la herramienta devuelve resultados estructurados listos para el contexto del LLM.
Requisitos previos
- Python 3.8+ instalado
- Paquetes langchain y langchain-core instalados
- Una clave API de Scavio de scavio.dev
Guia paso a paso
Paso 1: Instalar dependencias de LangChain
Agregue los paquetes necesarios para crear herramientas personalizadas.
pip install langchain langchain-core requestsPaso 2: Crear la herramienta de búsqueda
Defina una herramienta LangChain que llame a la API de Scavio con enrutamiento de plataforma.
from langchain.tools import tool
import requests, os
@tool
def web_search(query: str, platform: str = 'google') -> str:
"""Search the web for current information. Use platform='google' for general queries,
'reddit' for community discussions, 'youtube' for video content,
'amazon' for products, 'walmart' for retail prices."""
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': os.environ['SCAVIO_API_KEY']},
json={'platform': platform, 'query': query}, timeout=10)
results = resp.json().get('organic', [])[:5]
return '\n'.join(f'[{i+1}] {r["title"]}: {r.get("snippet", "")} ({r.get("link", "")})'
for i, r in enumerate(results))Paso 3: Crear un agente con la herramienta de búsqueda
Cree un agente LangChain que utilice la herramienta de búsqueda para responder preguntas.
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model='gpt-4o')
tools = [web_search]
prompt = ChatPromptTemplate.from_messages([
('system', 'You are a helpful research assistant. Use the web_search tool to find current information.'),
('human', '{input}'),
('placeholder', '{agent_scratchpad}'),
])
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)Paso 4: Probar el agente
Ejecute consultas que deberían desencadenar diferentes búsquedas en plataformas.
# General web search (google)
result = executor.invoke({'input': 'What are the top CRM tools in 2026?'})
print(result['output'])
# Reddit discussions
result = executor.invoke({'input': 'What do people on Reddit think about Notion?'})
print(result['output'])
# Product search
result = executor.invoke({'input': 'Find the best-rated wireless earbuds on Amazon under $100'})
print(result['output'])Ejemplo en Python
from langchain.tools import tool
import requests, os
@tool
def web_search(query: str, platform: str = 'google') -> str:
"""Search the web. Platforms: google, reddit, youtube, amazon, walmart."""
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': os.environ['SCAVIO_API_KEY']},
json={'platform': platform, 'query': query}, timeout=10)
return '\n'.join(f'{r["title"]}: {r.get("snippet","")}' for r in resp.json().get('organic', [])[:5])Ejemplo en JavaScript
import { tool } from '@langchain/core/tools';
import { z } from 'zod';
const webSearch = tool(async ({ query, platform }) => {
const resp = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST', headers: {'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json'},
body: JSON.stringify({platform: platform || 'google', query})
});
return (await resp.json()).organic?.slice(0, 5).map(r => `${r.title}: ${r.snippet}`).join('\n') || 'No results';
}, {
name: 'web_search',
description: 'Search the web. Platforms: google, reddit, youtube, amazon, walmart.',
schema: z.object({ query: z.string(), platform: z.string().optional() })
});Salida esperada
A LangChain search tool with multi-platform support and an agent that routes queries to the right platform.