ScavioScavio
ProductoPreciosDocumentación
Iniciar sesionComenzar
  1. Inicio
  2. Tutoriales
  3. Cómo poner a tierra un LLM local con una API de búsqueda
Tutorial

Cómo poner a tierra un LLM local con una API de búsqueda

Conecte un LLM local (llama.cpp, Ollama, vLLM) a una API de búsqueda web para una conexión a tierra en tiempo real. Detenga las alucinaciones con un nuevo contexto de búsqueda.

Obtener clave API gratisDocumentacion API

Los LLM locales que se ejecutan en llama.cpp, Ollama o vLLM son potentes pero están congelados en el tiempo. Alucinan eventos actuales, lanzamientos recientes y datos en vivo porque sus datos de entrenamiento tienen un límite. Agregar una API de búsqueda les brinda una base en tiempo real: antes de responder, el LLM busca en la web y utiliza resultados nuevos como contexto. Este tutorial funciona con cualquier punto final LLM local compatible con OpenAI. Costo: $0.005 por respuesta fundamentada.

Requisitos previos

  • Un LLM local en ejecución (Ollama, servidor llama.cpp o vLLM)
  • Python 3.9+ instalado
  • solicita biblioteca instalada
  • Una clave API de Scavio de scavio.dev

Guia paso a paso

Paso 1: Conéctese a su LLM local

Configure la conexión con su LLM local. Funciona con cualquier punto final compatible con OpenAI (Ollama, servidor llama.cpp, vLLM).

Python
import requests

# Common local LLM endpoints:
# Ollama:     http://localhost:11434/v1/chat/completions
# llama.cpp:  http://localhost:8080/v1/chat/completions
# vLLM:       http://localhost:8000/v1/chat/completions

LLM_URL = 'http://localhost:11434/v1/chat/completions'  # Ollama default
LLM_MODEL = 'llama3'  # or 'mistral', 'codellama', etc.

def ask_llm(messages: list, max_tokens: int = 512) -> str:
    resp = requests.post(LLM_URL, json={
        'model': LLM_MODEL,
        'messages': messages,
        'max_tokens': max_tokens,
        'temperature': 0.3
    }, timeout=120)
    return resp.json()['choices'][0]['message']['content']

# Test connection
try:
    answer = ask_llm([{'role': 'user', 'content': 'Say hello in one word.'}], max_tokens=10)
    print(f'LLM connected: {answer}')
except Exception as e:
    print(f'LLM connection error: {e}')
    print('Make sure Ollama/llama.cpp is running.')

Paso 2: Agregue la función de base de búsqueda

Cree una función que busque en la web y formatee los resultados como contexto para el LLM. El LLM solo ve los fragmentos de búsqueda, no las páginas completas.

Python
import os

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']

def search_context(query: str, count: int = 5) -> str:
    """Search the web and return formatted context for the LLM."""
    resp = requests.post('https://api.scavio.dev/api/v1/search',
        headers={'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json'},
        json={'query': query, 'country_code': 'us', 'num_results': count})
    results = resp.json().get('organic_results', [])
    if not results:
        return 'No search results found.'
    context = 'Search results (use these to answer accurately):\n\n'
    for i, r in enumerate(results, 1):
        context += f'[{i}] {r["title"]}\n'
        context += f'    {r.get("snippet", "")}\n'
        context += f'    Source: {r["link"]}\n\n'
    return context

# Test
ctx = search_context('Python 3.14 release date')
print(ctx[:300])

Paso 3: Construya el canal de respuestas fundamentado

Combine búsqueda y LLM en una sola función. El LLM recibe el contexto de búsqueda y debe citar fuentes en su respuesta.

Python
def grounded_answer(question: str) -> dict:
    """Answer a question using search-grounded local LLM."""
    # Step 1: Search for context
    context = search_context(question, count=5)
    # Step 2: Ask LLM with context
    messages = [
        {'role': 'system', 'content': (
            'You are a helpful assistant. Answer ONLY based on the search results provided. '
            'Cite sources as [1], [2], etc. If the search results do not contain the answer, '
            'say "I could not find this information in the search results."'
        )},
        {'role': 'user', 'content': f'{context}\nQuestion: {question}'}
    ]
    answer = ask_llm(messages, max_tokens=512)
    return {
        'question': question,
        'answer': answer,
        'grounded': True,
        'search_cost': 0.005
    }

# Test with a question that requires current data
result = grounded_answer('What is the latest version of Python?')
print(f'Q: {result["question"]}')
print(f'A: {result["answer"]}')
print(f'Grounded: {result["grounded"]}, Cost: ${result["search_cost"]}')

Paso 4: Agregue conexión a tierra inteligente (busque solo cuando sea necesario)

No todas las preguntas necesitan búsqueda. Agregue un cheque que decide si aterrizar con búsqueda o responder directamente, ahorrando costos.

Python
def needs_grounding(question: str) -> bool:
    """Heuristic: does this question need real-time data?"""
    grounding_triggers = [
        'latest', 'current', 'today', '2026', '2025', 'now',
        'price', 'cost', 'version', 'release', 'new', 'update',
        'best', 'top', 'compare', 'vs', 'alternative',
        'how much', 'where to', 'who is',
    ]
    q_lower = question.lower()
    return any(trigger in q_lower for trigger in grounding_triggers)

def smart_answer(question: str) -> dict:
    """Answer with search grounding only when needed."""
    if needs_grounding(question):
        return grounded_answer(question)
    # Direct LLM answer (no search cost)
    messages = [{'role': 'user', 'content': question}]
    answer = ask_llm(messages, max_tokens=512)
    return {
        'question': question,
        'answer': answer,
        'grounded': False,
        'search_cost': 0
    }

# Test both paths
for q in ['What is a Python list comprehension?',
          'What is the latest Python version in 2026?']:
    result = smart_answer(q)
    print(f'[{"GROUNDED" if result["grounded"] else "DIRECT"}] '
          f'${result["search_cost"]} - {q}')
    print(f'  {result["answer"][:100]}...')
    print()

Ejemplo en Python

Python
import requests, os

LLM_URL = 'http://localhost:11434/v1/chat/completions'
SCAVIO_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': SCAVIO_KEY, 'Content-Type': 'application/json'},
        json={'query': query, 'country_code': 'us', 'num_results': count})
    return resp.json().get('organic_results', [])

def grounded_ask(question):
    results = search(question)
    ctx = '\n'.join(f'[{i+1}] {r["title"]}: {r.get("snippet","")}' for i, r in enumerate(results))
    resp = requests.post(LLM_URL, json={'model': 'llama3', 'messages': [
        {'role': 'system', 'content': 'Answer from search results. Cite [1],[2].'},
        {'role': 'user', 'content': f'{ctx}\n\nQ: {question}'}], 'max_tokens': 512})
    return resp.json()['choices'][0]['message']['content']

print(grounded_ask('latest Python version 2026'))

Ejemplo en JavaScript

JavaScript
const LLM_URL = 'http://localhost:11434/v1/chat/completions';
const SCAVIO_KEY = process.env.SCAVIO_API_KEY;

async function groundedAsk(question) {
  const searchResp = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST',
    headers: { 'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: question, country_code: 'us', num_results: 5 })
  });
  const results = (await searchResp.json()).organic_results || [];
  const ctx = results.map((r, i) => `[${i+1}] ${r.title}: ${r.snippet || ''}`).join('\n');
  const llmResp = await fetch(LLM_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ model: 'llama3', messages: [
      { role: 'system', content: 'Answer from search results. Cite [1],[2].' },
      { role: 'user', content: `${ctx}\n\nQ: ${question}` }], max_tokens: 512 })
  });
  return (await llmResp.json()).choices[0].message.content;
}

groundedAsk('latest Python version 2026').then(console.log);

Salida esperada

JSON
LLM connected: Hello

Search results (use these to answer accurately):

[1] Python Release Python 3.14.0
    Python 3.14.0 was released on October 7, 2025...
    Source: https://www.python.org/downloads/release/python-3140/

Q: What is the latest version of Python?
A: According to the search results, the latest version of Python is 3.14.0,
released on October 7, 2025 [1].

[DIRECT] $0 - What is a Python list comprehension?
  A list comprehension is a concise way to create lists...

[GROUNDED] $0.005 - What is the latest Python version in 2026?
  The latest Python version is 3.14.0, released October 2025 [1]...

Tutoriales relacionados

  • Cómo configurar YaCy Expert con llama.cpp para búsqueda local
  • Cómo configurar su primera herramienta de búsqueda de agentes de IA
  • Cómo verificar los resultados de la búsqueda de IA mediante programación

Preguntas frecuentes

La mayoria de los desarrolladores completan este tutorial en 15 a 30 minutos. Necesitaras una clave API de Scavio (el plan gratuito funciona) y un entorno de Python o JavaScript.

Un LLM local en ejecución (Ollama, servidor llama.cpp o vLLM). Python 3.9+ instalado. solicita biblioteca instalada. Una clave API de Scavio de scavio.dev. Una clave API de Scavio te da 50 creditos gratuitos al registrarte.

Si. El plan gratuito incluye 50 creditos al registrarte, mas que suficiente para completar este tutorial y crear un prototipo funcional.

Scavio tiene un paquete nativo de LangChain (langchain-scavio), un servidor MCP y una API REST simple que funciona con cualquier cliente HTTP. Este tutorial usa the raw REST API, pero puedes adaptarlo al framework que prefieras.

Recursos relacionados

Best Of

Las mejores herramientas de base de conocimientos personales para LLM locales en mayo de 2026

Read more
Use Case

Búsqueda web de agentes para LLM local

Read more
Best Of

Las mejores API de búsqueda para la conexión web local de LLM en 2026

Read more
Solution

Búsqueda local de LLM después de Google Paywall

Read more
Use Case

Recuperación de búsqueda web local LLM 2026

Read more
Workflow

Diario Local LLM Search Grounding Pipeline

Read more

Empieza a construir

Conecte un LLM local (llama.cpp, Ollama, vLLM) a una API de búsqueda web para una conexión a tierra en tiempo real. Detenga las alucinaciones con un nuevo contexto de búsqueda.

Obtener clave API gratuitaLeer la documentacion
ScavioScavio

API de busqueda en tiempo real para agentes de IA. Busca en todas las plataformas, no solo en Google.

Producto

  • Funciones
  • Precios
  • Panel
  • Afiliados

Desarrolladores

  • Documentacion
  • Referencia de API
  • Inicio rapido
  • Integracion MCP
  • Python SDK

Alternativas

  • Alternativa a Tavily
  • Alternativa a SerpAPI
  • Alternativa a Firecrawl
  • Alternativa a Exa

Herramientas

  • Formateador JSON
  • cURL a codigo
  • Contador de tokens
  • Todas las herramientas

© 2026 Scavio. Todos los derechos reservados.

Featured on TAAFT
Terminos de servicioPolitica de privacidad