Les agents LangChain ont besoin d'outils de recherche pour accéder aux informations actuelles. Ce tutoriel crée un outil LangChain personnalisé utilisant l'API de Scavio qui prend en charge plusieurs plateformes (Google, Reddit, YouTube, Amazon, Walmart) via une seule définition d'outil. L'agent sélectionne la plateforme en fonction du contexte de la requête, et l'outil renvoie des résultats structurés prêts pour le contexte du LLM.
Prérequis
- Python 3.8+ installé
- Packages langchain et langchain-core installés
- Une clé API Scavio depuis scavio.dev
Parcours
Étape 1: Installer les dépendances LangChain
Ajoutez les packages nécessaires pour créer des outils personnalisés.
pip install langchain langchain-core requestsÉtape 2: Créer l'outil de recherche
Définissez un outil LangChain qui appelle l'API de Scavio avec routage de plateforme.
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))Étape 3: Créer un agent avec l'outil de recherche
Construisez un agent LangChain qui utilise l'outil de recherche pour répondre aux questions.
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)Étape 4: Tester l'agent
Exécutez des requêtes qui devraient déclencher des recherches sur différentes plateformes.
# 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'])Exemple 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])Exemple 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() })
});Sortie attendue
A LangChain search tool with multi-platform support and an agent that routes queries to the right platform.