> 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/products/es/web-scraper-api/solutions-for-ai-workflows/llamaindex.md).

# LlamaIndex

La integración de LlamaIndex con la [**Oxylabs Web Scraper API**](https://oxylabs.io/products/scraper-api/web) le 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. Úselo con [**Oxylabs Web Scraper API**](https://oxylabs.io/products/scraper-api/web) para:

* Extraer datos estructurados sin lidiar con CAPTCHAs, bloqueos de IP o renderizado de JS
* Procesar resultados con un LLM en el mismo pipeline
* Crear flujos de trabajo de extremo a extremo desde la extracción hasta la salida impulsada por IA

## Primeros pasos

**Cree sus credenciales de usuario de la API:** regístrese para una prueba gratuita o compre el producto en el [**panel de Oxylabs**](https://dashboard.oxylabs.io/en/registration) para crear sus credenciales de usuario de la API (`USERNAME` y `PASSWORD`).

{% hint style="info" %}
Si necesita más de un usuario de API para su cuenta, póngase en contacto con nuestro servicio de atención al cliente o escriba 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. Instale las bibliotecas requeridas con pip:

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

Cree un `.env` archivo en el directorio de su proyecto con sus credenciales de Oxylabs Web Scraper API y la clave de API de OpenAI:

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

Cargue estas variables de entorno en su 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 mediante Web Scraper API en LlamaIndex:

### Lector de Oxylabs

El `llama-index-readers-oxylabs` módulo contiene clases específicas que le 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, puede 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)
```

### Lector web de Oxylabs

Con la `OxylabsWebReader` clase, puede 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 básico de búsqueda con IA

A continuación, un ejemplo de un agente de IA simple 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=(
        'Craft a short Google search query to use with the `web_search` tool. '
        'Analyze the most relevant results and answer the question.'
    )
)

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'}
)
```

### Establecimiento del tipo de user agent

Puede especificar diferentes user agents:

```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 destino

Muchos extractores específicos del destino 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developers.oxylabs.io/products/es/web-scraper-api/solutions-for-ai-workflows/llamaindex.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
