ScavioScavio
ProductoPreciosDocumentación
Iniciar sesionComenzar
  1. Inicio
  2. Tutoriales
  3. Cómo construir el agente LangGraph con Critic Loop
Tutorial

Cómo construir el agente LangGraph con Critic Loop

Cree un agente LangGraph que busque, redacte, autocritique e investigue hasta que pase la calidad. Implementación de Python.

Obtener clave API gratisDocumentacion API

Un agente de un solo paso pierde de vista los matices. Un agente del bucle crítico busca, redacta una respuesta, evalúa su propia producción e investiga para llenar los vacíos. Este tutorial construye el patrón en LangGraph con la búsqueda Scavio como herramienta. Cada ciclo de crítica de búsqueda cuesta entre 0,005 y 0,015 dólares, dependiendo de cuántas pasadas de refinamiento se necesiten.

Requisitos previos

  • Python 3.8+
  • langgraph y langchain instalados
  • Una clave API de Scavio de scavio.dev
  • Clave OpenAI o Anthropic API para LLM

Guia paso a paso

Paso 1: Definir la herramienta de búsqueda y el estado

Cree la herramienta de búsqueda y el esquema de estado LangGraph para el bucle crítico.

Python
import os, requests, json
from typing import TypedDict, List, Optional

API_KEY = os.environ['SCAVIO_API_KEY']
SH = {'x-api-key': API_KEY, 'Content-Type': 'application/json'}

class AgentState(TypedDict):
    query: str
    search_results: List[dict]
    draft: str
    critique: str
    is_good: bool
    iteration: int
    max_iterations: int

def search_tool(query, num_results=5):
    data = requests.post('https://api.scavio.dev/api/v1/search',
        headers=SH, json={'query': query, 'country_code': 'us', 'num_results': num_results}).json()
    return [{'title': r.get('title', ''), 'snippet': r.get('snippet', ''),
             'link': r.get('link', '')} for r in data.get('organic_results', [])[:num_results]]

# Test
results = search_tool('best python web framework 2026')
print(f'Search returned {len(results)} results')
for r in results[:3]:
    print(f'  {r["title"]}')

Paso 2: Construya los nodos del gráfico

Cree nodos de búsqueda, borrador, crítica y refinamiento para el bucle.

Python
def search_node(state: AgentState) -> AgentState:
    """Search for information based on query."""
    results = search_tool(state['query'])
    state['search_results'] = results
    state['iteration'] = state.get('iteration', 0) + 1
    return state

def draft_node(state: AgentState) -> AgentState:
    """Draft an answer from search results."""
    context = '\n'.join([f'- {r["title"]}: {r["snippet"]}' for r in state['search_results']])
    # In production, send to LLM. Simulating here:
    state['draft'] = f'Based on {len(state["search_results"])} sources: {context[:200]}'
    return state

def critique_node(state: AgentState) -> AgentState:
    """Evaluate the draft for completeness and accuracy."""
    draft = state['draft']
    issues = []
    if len(draft) < 100:
        issues.append('Too short - needs more detail')
    if 'source' not in draft.lower() and 'http' not in draft:
        issues.append('Missing source citations')
    if len(state['search_results']) < 3:
        issues.append('Too few sources consulted')
    state['is_good'] = len(issues) == 0
    state['critique'] = '; '.join(issues) if issues else 'Draft is acceptable'
    return state

def refine_node(state: AgentState) -> AgentState:
    """Refine the search query based on critique."""
    state['query'] = f'{state["query"]} {state["critique"].split(";")[0]}'
    return state

print('Nodes defined: search -> draft -> critique -> [refine -> search] or done')

Paso 3: Ensamble y ejecute LangGraph

Conecte los nodos a un LangGraph con bordes condicionales para el bucle crítico.

Python
def should_refine(state: AgentState) -> str:
    if state['is_good']:
        return 'done'
    if state['iteration'] >= state.get('max_iterations', 3):
        return 'done'
    return 'refine'

def run_critic_agent(query, max_iterations=3):
    """Run the critic loop agent."""
    state = {
        'query': query,
        'search_results': [],
        'draft': '',
        'critique': '',
        'is_good': False,
        'iteration': 0,
        'max_iterations': max_iterations
    }
    print(f'\n=== Critic Agent: "{query}" ===')
    while True:
        state = search_node(state)
        print(f'\n  [Iteration {state["iteration"]}] Searched: {len(state["search_results"])} results')
        state = draft_node(state)
        print(f'  Draft: {state["draft"][:80]}...')
        state = critique_node(state)
        print(f'  Critique: {state["critique"]}')
        decision = should_refine(state)
        if decision == 'done':
            break
        print(f'  -> Refining query for next iteration')
        state = refine_node(state)
    cost = state['iteration'] * 0.005
    print(f'\n  Final answer ({state["iteration"]} iterations, ${cost:.3f}):')
    print(f'  {state["draft"][:200]}')
    return state

run_critic_agent('best python web framework for AI apps 2026')

Ejemplo en Python

Python
import os, requests
SH = {'x-api-key': os.environ['SCAVIO_API_KEY'], 'Content-Type': 'application/json'}

def search(q):
    return requests.post('https://api.scavio.dev/api/v1/search',
        headers=SH, json={'query': q, 'country_code': 'us'}).json().get('organic_results', [])[:5]

# Critic loop: search -> evaluate -> re-search if needed
query = 'best AI framework 2026'
for i in range(3):
    results = search(query)
    print(f'Pass {i+1}: {len(results)} results')
    if len(results) >= 3: break
    query += ' comparison'
print(f'Cost: ${(i+1) * 0.005:.3f}')

Ejemplo en JavaScript

JavaScript
const SH = { 'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json' };
async function search(q) {
  const data = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST', headers: SH,
    body: JSON.stringify({ query: q, country_code: 'us' })
  }).then(r => r.json());
  return (data.organic_results || []).slice(0, 5);
}
let query = 'best AI framework 2026';
for (let i = 0; i < 3; i++) {
  const results = await search(query);
  console.log(`Pass ${i+1}: ${results.length} results`);
  if (results.length >= 3) break;
  query += ' comparison';
}

Salida esperada

JSON
=== Critic Agent: "best python web framework for AI apps 2026" ===

  [Iteration 1] Searched: 5 results
  Draft: Based on 5 sources: - FastAPI vs Django 2026: FastAPI leads for AI...
  Critique: Missing source citations
  -> Refining query for next iteration

  [Iteration 2] Searched: 5 results
  Draft: Based on 5 sources with citations: FastAPI (https://fastapi.tiang...
  Critique: Draft is acceptable

  Final answer (2 iterations, $0.010):
  Based on 5 sources with citations: FastAPI leads for AI applications...

Tutoriales relacionados

  • Cómo crear un agente de búsqueda LangGraph con control presupuestario
  • Cómo agregar búsqueda a un agente LangGraph
  • Cómo agregar búsqueda web en vivo a un agente LangGraph con Scavio

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.

Python 3.8+. langgraph y langchain instalados. Una clave API de Scavio de scavio.dev. Clave OpenAI o Anthropic API para LLM. 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

La mejor API de búsqueda para agentes LangGraph en 2026

Read more
Best Of

Las mejores herramientas para crear agentes sin marcos (2026)

Read more
Solution

Agregar nodos de búsqueda en vivo a los flujos de trabajo del agente LangGraph

Read more
Use Case

Base de búsqueda de LangGraph

Read more
Workflow

Diario LangGraph Search Research Workflow

Read more
Glossary

Máquina de estados LangGraph

Read more

Empieza a construir

Cree un agente LangGraph que busque, redacte, autocritique e investigue hasta que pase la calidad. Implementación de Python.

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