> 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/pt-br/llamaindex.md).

# LlamaIndex

Aproveite a integração do LlamaIndex com a Web Scraper API da Oxylabs para ingerir facilmente conteúdo online e criar fluxos de trabalho orientados por LLM.

A integração do LlamaIndex com a [**Oxylabs Web Scraper API**](https://oxylabs.io/products/scraper-api/web) permite extrair e processar dados da web por meio de um LLM (Modelo de linguagem de grande porte) no mesmo fluxo de trabalho.

## Visão geral

[**LlamaIndex**](https://docs.llamaindex.ai/en/stable/examples/data_connectors/OxylabsDemo/) é um framework de dados projetado para criar aplicações de LLM com fontes de dados externas. Use-o com [**Oxylabs Web Scraper API**](https://oxylabs.io/products/scraper-api/web) para:

* Extraia dados estruturados sem lidar com CAPTCHAs, bloqueios de IP ou renderização de JS
* Processe os resultados com um LLM no mesmo pipeline
* Crie fluxos de trabalho de ponta a ponta, da extração à saída com IA

## Primeiros passos

**Crie suas credenciais de usuário da API:** cadastre-se para um teste gratuito ou adquira o produto no [**painel da Oxylabs**](https://dashboard.oxylabs.io/en/registration) para criar suas credenciais de usuário da API (`USERNAME` e `PASSWORD`).

{% hint style="info" %}
Se você precisar de mais de um usuário da API para sua conta, entre em contato com nosso suporte ao cliente ou envie uma mensagem para nosso suporte por chat ao vivo 24/7.
{% endhint %}

### Configuração do ambiente

Neste guia, usaremos a linguagem de programação Python. Instale as bibliotecas necessárias usando pip:

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

Crie um `.env` arquivo no diretório do seu projeto com suas credenciais do Oxylabs Web Scraper API e a chave de API da OpenAI:

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

Carregue essas variáveis de ambiente no seu script Python:

```python
import os
from dotenv import load_dotenv

load_dotenv()
```

## Métodos de integração

Há duas maneiras de acessar conteúdo da web via Web Scraper API no LlamaIndex:

### Leitor da Oxylabs

O `llama-index-readers-oxylabs` módulo contém classes específicas que permitem extrair dados de várias fontes:

| Fonte de dados da API          | Classe do leitor           |
| ------------------------------ | -------------------------- |
| Pesquisa na Web do Google      | OxylabsGoogleSearchReader  |
| Anúncios de pesquisa do Google | OxylabsGoogleAdsReader     |
| Produto da Amazon              | OxylabsAmazonProductReader |
| Pesquisa na Amazon             | OxylabsAmazonSearchReader  |
| Avaliações da Amazon           | OxylabsAmazonReviewsReader |

Por exemplo, você pode extrair resultados da pesquisa do 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)
```

### Leitor Web da Oxylabs

Com a `OxylabsWebReader` classe, você pode extrair dados de qualquer 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')
```

## Construindo um agente básico de busca com IA

Abaixo está um exemplo de um agente de IA simples que pode pesquisar no Google e responder perguntas:

```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=(
        'Crie uma consulta curta de pesquisa no Google para usar com a ferramenta `web_search`. '
        'Analise os resultados mais relevantes e responda à pergunta.'
    )
)

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

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

## Configuração avançada

### Tratando conteúdo dinâmico

A Web Scraper API pode lidar com renderização de JavaScript:

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

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

### Definindo o tipo de user agent

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

### Usando parâmetros específicos do alvo

Muitos scrapers específicos do alvo suportam parâmetros adicionais:

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

## Criando índices vetoriais

O LlamaIndex é particularmente útil para criar índices vetoriais a partir de conteúdo da 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/pt-br/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.
