> For the complete documentation index, see [llms.txt](https://developers.oxylabs.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.oxylabs.io/ai-workflows/es/llamaindex.md).

# LlamaIndex

Aprovecha la integración de LlamaIndex con la Oxylabs Web Scraper API para ingerir fácilmente contenido en línea y crear flujos de trabajo impulsados por LLM.

La integración de LlamaIndex con la [**Oxylabs Web Scraper API**](https://oxylabs.io/products/scraper-api/web) te permite extraer y procesar datos web a través de un LLM (modelo de lenguaje grande) en el mismo flujo de trabajo.

## Descripción general

[**LlamaIndex**](https://docs.llamaindex.ai/en/stable/examples/data_connectors/OxylabsDemo/) es un marco de datos diseñado para crear aplicaciones LLM con fuentes de datos externas. Úsalo con [**Oxylabs Web Scraper API**](https://oxylabs.io/products/scraper-api/web) para:

* Extraer datos estructurados sin manejar CAPTCHAs, bloqueos de IP ni renderizado de JS
* Procesar resultados con un LLM en la misma canalización
* Crear flujos de trabajo de extremo a extremo, desde la extracción hasta la salida impulsada por IA

## Primeros pasos

**Crea tus credenciales de usuario de API:** regístrate para una prueba gratuita o compra el producto en el [**panel de Oxylabs**](https://dashboard.oxylabs.io/en/registration) para crear tus credenciales de usuario de API (`USERNAME` y `PASSWORD`).

{% hint style="info" %}
Si necesitas más de un usuario de API para tu cuenta, ponte en contacto con nuestro soporte al cliente o escribe a nuestro soporte de chat en vivo 24/7.
{% endhint %}

### Configuración del entorno

En esta guía usaremos el lenguaje de programación Python. Instala las bibliotecas requeridas usando pip:

```
pip install -qU llama-index llama-index-readers-oxylabs llama-index-readers-web
```

Crea un `.env` archivo en el directorio de tu proyecto con tus credenciales de Oxylabs Web Scraper API y la clave API de OpenAI:

```
OXYLABS_USERNAME=your_API_username
OXYLABS_PASSWORD=your_API_password
OPENAI_API_KEY=your-openai-key
```

Carga estas variables de entorno en tu script de Python:

```python
import os
from dotenv import load_dotenv

load_dotenv()
```

## Métodos de integración

Hay dos formas de acceder al contenido web a través de Web Scraper API en LlamaIndex:

### Lector de Oxylabs

El `llama-index-readers-oxylabs` módulo contiene clases específicas que te permiten extraer datos de varias fuentes:

| Fuente de datos de la API      | Clase de lector            |
| ------------------------------ | -------------------------- |
| Búsqueda web de Google         | OxylabsGoogleSearchReader  |
| Anuncios de búsqueda de Google | OxylabsGoogleAdsReader     |
| Producto de Amazon             | OxylabsAmazonProductReader |
| Búsqueda de Amazon             | OxylabsAmazonSearchReader  |
| Reseñas de Amazon              | OxylabsAmazonReviewsReader |

Por ejemplo, puedes extraer resultados de búsqueda de Google:

```python
import os
from dotenv import load_dotenv
from llama_index.readers.oxylabs import OxylabsGoogleSearchReader

load_dotenv()
reader = OxylabsGoogleSearchReader(
    os.getenv('OXYLABS_USERNAME'), os.getenv('OXYLABS_PASSWORD')
)
results = reader.load_data({
    'query': 'best pancake recipe',
    'parse': True
})
print(results[0].text)
```

### Oxylabs Web Reader

Con la `OxylabsWebReader` clase, puedes extraer datos de cualquier URL:

```python
import os
from dotenv import load_dotenv
from llama_index.readers.web import OxylabsWebReader

load_dotenv()
reader = OxylabsWebReader(
    os.getenv('OXYLABS_USERNAME'), os.getenv('OXYLABS_PASSWORD')
)
results = reader.load_data(
    [
        'https://sandbox.oxylabs.io/products/1',
        'https://sandbox.oxylabs.io/products/2'
    ]
)
for result in results:
    print(result.text + '\n')
```

## Creación de un agente de búsqueda de IA básico

A continuación se muestra un ejemplo de un agente de IA sencillo que puede buscar en Google y responder preguntas:

```python
import os
import asyncio
from dotenv import load_dotenv
from llama_index.readers.oxylabs import OxylabsGoogleSearchReader
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI

load_dotenv()
reader = OxylabsGoogleSearchReader(
    os.getenv('OXYLABS_USERNAME'), os.getenv('OXYLABS_PASSWORD')
)

def web_search(query: str) -> str:
    results = reader.load_data({'query': query, 'parse': True})
    return results[0].text

agent = FunctionAgent(
    tools=[web_search],
    llm=OpenAI(model='gpt-4o-mini'),
    max_function_calls=1,
    system_prompt=(
        'Crea una consulta breve de búsqueda de Google para usar con la herramienta `web_search`. '
        'Analiza los resultados más relevantes y responde la pregunta.'
    )
)

async def main():
    response = await agent.run('How did DeepSeek affect the stock market?')
    print(response)

if __name__ == '__main__':
    asyncio.run(main())
```

## Configuración avanzada

### Manejo de contenido dinámico

Web Scraper API puede manejar el renderizado de JavaScript:

```python
reader = OxylabsWebReader(
    os.getenv('OXYLABS_USERNAME'), os.getenv('OXYLABS_PASSWORD')
)

results = reader.load_data(
    [
        'https://quotes.toscrape.com/js/'
    ],
    {'render': 'html'}
)
```

### Configuración del tipo de agente de usuario

Puedes especificar diferentes agentes de usuario:

```python
reader = OxylabsWebReader(
    os.getenv('OXYLABS_USERNAME'), os.getenv('OXYLABS_PASSWORD')
)

results = reader.load_data(
    [
        'https://sandbox.oxylabs.io/products/1'
    ],
    {'user_agent_type': 'mobile'}
)
```

### Uso de parámetros específicos del objetivo

Muchos scrapers específicos del objetivo admiten parámetros adicionales:

```python
reader = OxylabsGoogleSearchReader(
    os.getenv('OXYLABS_USERNAME'),
    os.getenv('OXYLABS_PASSWORD')
)
results = reader.load_data({
    'query': 'iphone',
    'parse': True,
    'domain': 'com',
    'start_page': 2,
    'pages': 3
})
```

## Creación de índices vectoriales

LlamaIndex es especialmente útil para crear índices vectoriales a partir de contenido web:

```python
import os
from dotenv import load_dotenv
from llama_index.readers.web import OxylabsWebReader
from llama_index.core import Settings, VectorStoreIndex
from llama_index.llms.openai import OpenAI

load_dotenv()
reader = OxylabsWebReader(
    os.getenv('OXYLABS_USERNAME'), os.getenv('OXYLABS_PASSWORD')
)
documents = reader.load_data([
    'https://sandbox.oxylabs.io/products/1',
    'https://sandbox.oxylabs.io/products/2'
])

# Configure LlamaIndex settings
Settings.llm = OpenAI(model='gpt-4o-mini')

# Create an index
index = VectorStoreIndex.from_documents(documents)

# Query the index
query_engine = index.as_query_engine()
response = query_engine.query('What is the main topic of these pages?')
print(response)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developers.oxylabs.io/ai-workflows/es/llamaindex.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
