ScavioScavio
ProductoPreciosDocumentación
Iniciar sesionComenzar
  1. Inicio
  2. Tutoriales
  3. Cómo crear un agente de IA sin marcos
Tutorial

Cómo crear un agente de IA sin marcos

Cree un agente de IA que funcione en Python simple, sin LangChain ni CrewAI. Solo solicitudes, una herramienta de búsqueda y una llamada API de LLM.

Obtener clave API gratisDocumentacion API

La mayoría de los tutoriales para agentes comienzan con LangChain o CrewAI, pero no necesita un marco para crear un agente útil. Este tutorial crea un agente de búsqueda y respuesta funcional en Python simple utilizando solo solicitudes, una API LLM y búsqueda Scavio. Usted controla cada línea de código y comprende cada decisión. Dependencias totales: solicitudes.

Requisitos previos

  • Python 3.8+
  • solicita biblioteca
  • Una clave API de Scavio de scavio.dev
  • Una clave API de LLM (OpenAI, Anthropic o similar)

Guia paso a paso

Paso 1: Definir la herramienta de búsqueda

Cree una función simple que el agente pueda llamar para buscar en la web.

Python
import os, requests, json

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

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

def extract(url):
    """Extract page content from URL."""
    data = requests.post('https://api.scavio.dev/api/v1/extract',
        headers=SH, json={'url': url}).json()
    return data.get('content', '')[:2000]

TOOLS = {
    'search': {'fn': search, 'desc': 'Search the web for information'},
    'extract': {'fn': extract, 'desc': 'Extract content from a URL'},
}
print(f'Tools available: {list(TOOLS.keys())}')
results = search('python 3.13 new features')
print(f'Test search: {len(results)} results')

Paso 2: Construya el bucle del agente

Cree un ciclo de pensar, actuar y observar que llame a las herramientas hasta que finalice la tarea.

Python
def agent(task, max_steps=5):
    """Plain Python agent: think -> act -> observe -> repeat."""
    memory = [f'Task: {task}']
    cost = 0
    for step in range(1, max_steps + 1):
        print(f'\n--- Step {step} ---')
        # Think: decide what to do based on memory
        context = '\n'.join(memory[-5:])  # Keep last 5 items
        # Simple heuristic: search if no results yet, extract if we have URLs
        if step == 1:
            action = 'search'
            args = {'query': task}
        elif any('http' in m for m in memory) and step == 2:
            # Extract from first URL found
            for m in memory:
                if 'http' in m:
                    url = m.split('http')[1].split()[0]
                    url = 'http' + url
                    action = 'extract'
                    args = {'url': url}
                    break
        else:
            action = 'done'
            args = {}
        if action == 'done':
            print('Agent: Task complete.')
            break
        # Act
        print(f'Action: {action}({json.dumps(args)[:60]})')
        tool = TOOLS.get(action)
        if tool:
            result = tool['fn'](**args)
            cost += 0.005
            observation = json.dumps(result)[:500] if isinstance(result, list) else str(result)[:500]
            memory.append(f'Action: {action} -> {observation[:200]}')
            print(f'Observation: {observation[:100]}...')
        else:
            print(f'Unknown action: {action}')
    print(f'\nTotal cost: ${cost:.3f} ({step} steps)')
    return memory

memory = agent('What are the top Python web frameworks in 2026?')

Paso 3: Agregar salida estructurada y manejo de errores

Haga que el agente produzca una respuesta final limpia con las fuentes.

Python
def robust_agent(task, max_steps=5):
    """Agent with error handling and structured output."""
    results_cache = []
    cost = 0
    errors = 0
    # Step 1: Search
    try:
        search_results = search(task)
        cost += 0.005
        results_cache.extend(search_results)
        print(f'Searched: {len(search_results)} results')
    except Exception as e:
        print(f'Search failed: {e}')
        errors += 1
    # Step 2: Extract top result if available
    if results_cache and results_cache[0].get('link'):
        try:
            content = extract(results_cache[0]['link'])
            cost += 0.005
            print(f'Extracted: {len(content)} chars from {results_cache[0]["link"][:40]}')
        except Exception as e:
            content = ''
            print(f'Extract failed: {e}')
            errors += 1
    else:
        content = ''
    # Step 3: Compile answer
    answer = {
        'task': task,
        'sources': [{'title': r['title'], 'url': r['link']} for r in results_cache[:5]],
        'summary': content[:300] if content else 'See sources below.',
        'cost': cost,
        'errors': errors
    }
    print(f'\n=== Agent Result ===')
    print(f'Sources: {len(answer["sources"])}')
    print(f'Summary: {answer["summary"][:100]}...')
    print(f'Cost: ${cost:.3f} | Errors: {errors}')
    print(f'\nNo frameworks needed. Just Python and an API.')
    return answer

robust_agent('best search api for ai agents 2026')

Ejemplo en Python

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

def agent(task):
    data = requests.post('https://api.scavio.dev/api/v1/search',
        headers=SH, json={'query': task, 'country_code': 'us'}).json()
    results = data.get('organic_results', [])[:5]
    print(f'Task: {task}')
    for r in results:
        print(f'  [{r.get("title", "")}]({r.get("link", "")})')
    print(f'Cost: $0.005 | No framework needed')

agent('best python web framework 2026')

Ejemplo en JavaScript

JavaScript
const SH = { 'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json' };
async function agent(task) {
  const data = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST', headers: SH,
    body: JSON.stringify({ query: task, country_code: 'us' })
  }).then(r => r.json());
  console.log(`Task: ${task}`);
  (data.organic_results || []).slice(0, 5).forEach(r => console.log(`  ${r.title}`));
  console.log('Cost: $0.005 | No framework needed');
}
await agent('best python web framework 2026');

Salida esperada

JSON
Tools available: ['search', 'extract']
Test search: 5 results

--- Step 1 ---
Action: search({"query": "What are the top Python web frameworks in 2026"})
Observation: [{"title": "Top Python Web Frameworks 2026", "link": "https://...

--- Step 2 ---
Action: extract({"url": "https://realpython.com/top-python-frameworks-2026"})
Observation: FastAPI continues to lead for API development...

--- Step 3 ---
Agent: Task complete.

Total cost: $0.010 (3 steps)

Tutoriales relacionados

  • Cómo crear su primer agente de IA (sin código) en 2026
  • Cómo construir un agente de investigación autónomo con Scavio
  • Cómo agregar una base de búsqueda a cualquier agente Python

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+. solicita biblioteca. Una clave API de Scavio de scavio.dev. Una clave API de LLM (OpenAI, Anthropic o similar). 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 para crear agentes sin marcos (2026)

Read more
Best Of

Las mejores aplicaciones de productividad de IA en 2026

Read more
Glossary

Panorama de proveedores de API de búsqueda (2026)

Read more
Glossary

Buscar Era del muro de pago (2026)

Read more
Solution

Búsqueda de agentes Python sin framework

Read more
Use Case

Monolito CLI de Python frente a modular

Read more

Empieza a construir

Cree un agente de IA que funcione en Python simple, sin LangChain ni CrewAI. Solo solicitudes, una herramienta de búsqueda y una llamada API de LLM.

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