> 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/api-targets/es/llms-e-ia/perplexity.md).

# Perplexity

El `Perplexity` La fuente Perplexity te permite enviar un prompt y recibir una respuesta completamente analizada y estructurada, incluyendo la respuesta formateada, las fuentes web utilizadas, las consultas relacionadas y las pestañas de la interfaz mostradas. Los prompts relacionados con productos pueden devolver resultados de compras y listados de productos integrados.

## Ejemplos de solicitud

Los ejemplos de código a continuación ilustran cómo enviar prompts a Perplexity y recuperar respuestas analizadas.

{% tabs %}
{% tab title="cURL" %}

```bash
curl 'https://realtime.oxylabs.io/v1/queries' \
--user 'USERNAME:PASSWORD' \
-H 'Content-Type: application/json' \
-d '{
        "source": "perplexity",
        "prompt": "best supplements for better sleep",
        "geo_location": "United States",
        "parse": true
    }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
from pprint import pprint


# Structure payload.
payload = {
    'source': 'perplexity',
    'prompt': 'top 3 smartphones in 2025, compare pricing across US marketplaces',
    'geo_location': 'United States',
    'parse': True
}

# Get a response.
response = requests.post(
    'https://realtime.oxylabs.io/v1/queries',
    auth=('USERNAME', 'PASSWORD'),
    json=payload
)

# Print prettified response to stdout.
pprint(response.json())
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require("https");

const username = "USERNAME";
const password = "PASSWORD";
const body = {
    source: "perplexity",
    prompt: "top 3 smartphones in 2025, compare pricing across US marketplaces",
    geo_location: "United States",
    parse: true
};

const options = {
    hostname: "realtime.oxylabs.io",
    path: "/v1/queries",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        Authorization:
            "Basic " + Buffer.from(`${username}:${password}`).toString("base64"),
    },
};

const request = https.request(options, (response) => {
    let data = "";

    response.on("data", (chunk) => {
        data += chunk;
    });

    response.on("end", () => {
        const responseData = JSON.parse(data);
        console.log(JSON.stringify(responseData, null, 2));
    });
});

request.on("error", (error) => {
    console.error("Error:", error);
});

request.write(JSON.stringify(body));
request.end();
```

{% endtab %}

{% tab title="HTTP" %}

```http
https://realtime.oxylabs.io/v1/queries?source=perplexity&prompt=top%203%20smartphones%20in%202025%2C%20compare%20pricing%20across%20US%20marketplaces&geo_location=United%20States&parse=true&access_token=12345abcde
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$params = array(
    'source' => 'perplexity',
    'prompt' => 'top 3 smartphones in 2025, compare pricing across US marketplaces',
    'geo_location' => 'United States',
    'parse' => true
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://realtime.oxylabs.io/v1/queries");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "USERNAME" . ":" . "PASSWORD");


$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
echo $result;

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);
```

{% endtab %}

{% tab title="Golang" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

func main() {
	const Username = "USERNAME"
	const Password = "PASSWORD"

	payload := map[string]interface{}{
		"source":       "perplexity",
		"prompt":       "top 3 smartphones in 2025, compare pricing across US marketplaces",
		"geo_location": "United States",
		"parse":        true,
	}

	jsonValue, _ := json.Marshal(payload)

	client := &http.Client{}
	request, _ := http.NewRequest("POST",
		"https://realtime.oxylabs.io/v1/queries",
		bytes.NewBuffer(jsonValue),
	)

	request.SetBasicAuth(Username, Password)
	response, _ := client.Do(request)

	responseText, _ := io.ReadAll(response.Body)
	fmt.Println(string(responseText))
}

```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace OxyApi
{
    class Program
    {
        static async Task Main()
        {
            const string Username = "USERNAME";
            const string Password = "PASSWORD";

            var parameters = new
            {
                source = "perplexity",
                prompt = "top 3 smartphones in 2025, compare pricing across US marketplaces",
                geo_location = "United States",
                parse = true
            };

            var client = new HttpClient();

            Uri baseUri = new Uri("https://realtime.oxylabs.io");
            client.BaseAddress = baseUri;

            var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/v1/queries");
            requestMessage.Content = JsonContent.Create(parameters);

            var authenticationString = $"{Username}:{Password}";
            var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.UTF8.GetBytes(authenticationString));
            requestMessage.Headers.Add("Authorization", "Basic " + base64EncodedAuthenticationString);

            var response = await client.SendAsync(requestMessage);
            var contents = await response.Content.ReadAsStringAsync();

            Console.WriteLine(contents);
        }
    }
}
```

{% endtab %}

{% tab title="Java" %}

```java
package org.example;

import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;

public class Main implements Runnable {
    private static final String AUTHORIZATION_HEADER = "Authorization";
    public static final String USERNAME = "USERNAME";
    public static final String PASSWORD = "PASSWORD";

    public void run() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("source", "perplexity");
        jsonObject.put("prompt", "top 3 smartphones in 2025, compare pricing across US marketplaces");
        jsonObject.put("geo_location", "United States");
        jsonObject.put("parse", true);

        Authenticator authenticator = (route, response) -> {
            String credential = Credentials.basic(USERNAME, PASSWORD);
            return response
                    .request()
                    .newBuilder()
                    .header(AUTHORIZATION_HEADER, credential)
                    .build();
        };

        var client = new OkHttpClient.Builder()
                .authenticator(authenticator)
                .readTimeout(180, TimeUnit.SECONDS)
                .build();

        var mediaType = MediaType.parse("application/json; charset=utf-8");
        var body = RequestBody.create(jsonObject.toString(), mediaType);
        var request = new Request.Builder()
                .url("https://realtime.oxylabs.io/v1/queries")
                .post(body)
                .build();

        try (var response = client.newCall(request).execute()) {
            if (response.body() != null) {
                try (var responseBody = response.body()) {
                    System.out.println(responseBody.string());
                }
            }
        } catch (Exception exception) {
            System.out.println("Error: " + exception.getMessage());
        }

        System.exit(0);
    }

    public static void main(String[] args) {
        new Thread(new Main()).start();
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
    "source": "perplexity",
    "prompt": "top 3 smartphones in 2025, compare pricing across US marketplaces",
    "geo_location": "United States",
    "parse": true
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Nota:** JavaScript rendering is enabled by default for all LLM sources. You do not need to include rendering parameters in your request payload.
{% endhint %}

Usamos el método de integración síncrono [**Realtime**](/products/es/web-scraper-api/integration-methods/realtime.md) en nuestros ejemplos. Si deseas usar [**Proxy Endpoint**](/products/es/web-scraper-api/integration-methods/proxy-endpoint.md) o la integración asíncrona [**Push-Pull**](/products/es/web-scraper-api/integration-methods/push-pull.md) (incluyendo [consultas por lotes](/products/es/web-scraper-api/integration-methods/push-pull.md#batch-query)), consulta la [**sección de métodos de integración**](/products/es/web-scraper-api/integration-methods.md) .

### Parámetros de solicitud

Parámetros básicos de configuración para extraer respuestas de Perplexity.

<table><thead><tr><th width="222">Parámetro</th><th width="350.3333333333333">Descripción</th><th>Valor predeterminado</th></tr></thead><tbody><tr><td><mark style="background-color:green;"><strong><code>source</code></strong></mark></td><td>Establece el objetivo del scraper. Usa <code>Perplexity</code>.</td><td>–</td></tr><tr><td><mark style="background-color:green;"><strong><code>prompt</code></strong></mark></td><td>El prompt o pregunta para enviar a Perplexity. Debe tener menos de 8000 caracteres.</td><td>–</td></tr><tr><td><code>parse</code></td><td>Establécelo en <code>true</code> para datos JSON estructurados.</td><td><code>false</code></td></tr><tr><td><code>geo_location</code></td><td>Especifica un país desde el que enrutar la solicitud. <a href="/spaces/xofNngbwiAAH0MB3lMAb/pages/420947c2a7ffcd522d505758107770ed31701a21"><strong>Más información</strong></a>.</td><td>–</td></tr><tr><td><code>browser_instructions</code></td><td>Instrucciones personalizadas opcionales del navegador al renderizar JavaScript. <a href="/spaces/xofNngbwiAAH0MB3lMAb/pages/47852075b446d7f11217f4c0334348f21fb197b8#browser-instructions"><strong>Más información</strong></a>.</td><td>–</td></tr><tr><td><code>callback_url</code></td><td>URL de tu endpoint de callback. <a href="https://developers.oxylabs.io/products/web-scraper-api/integration-methods/push-pull"><strong>Más información</strong></a></td><td>–</td></tr></tbody></table>

&#x20;    \- parámetro obligatorio

## Datos estructurados

Web Scraper API devuelve un documento HTML o un objeto JSON con la salida de Perplexity, que contiene datos estructurados de la página de resultados.

<details>

<summary><code>Perplexity</code> salida estructurada</summary>

```json
{
  "results": [
    {
      "job_id": "7470032181138587649",
      "status_code": 200,
      "url": "https://www.perplexity.ai/search/915bee3e-2d59-48ba-8b19-701f527c9b60",
      "content": {
        "prompt_query": "best supplements for better sleep",
        "model": "turbo",
        "answer_results": [
          "Here are the most evidence-supported supplements people typically try for better sleep—plus who they're best for and key safety notes.",
          "Best-supported options (start here)",
          ...
        ],
        "answer_results_md": "\nHere are the most evidence-supported supplements people typically try for better sleep—plus who they're best for and key safety notes.\n\nBest-supported options (start here)\n-----------------------------------\n\n...",
        "additional_results": {
          "sources_results": [
            {
              "title": "Best Supplements and Habits for Better Sleep (20 min.)",
              "url": "https://coopercomplete.com/blog/best-supplements-for-better-sleep/"
            },
            {
              "title": "Sleep Better With These 9 Sleep Supplements",
              "url": "https://drruscio.com/sleep-supplements/"
            },
            {
              "title": "10 Best Supplements for Sleep Support: A Dietitian's Picks",
              "url": "https://letsliveitup.com/blogs/supergreens/best-sleep-supplements"
            },
            ...
          ]
        },
        "related_queries": [
          "Which sleep aids have the strongest evidence in adults",
          "How to cycle supplements for sleep without tolerance",
          "What are safest melatonin dosing guidelines for adults",
          "Lifestyle tweaks to maximize sleep while using supplements"
        ],
        "displayed_tabs": [
          "Answer",
          "Links",
          "Images"
        ],
        "url": "https://www.perplexity.ai/search/915bee3e-2d59-48ba-8b19-701f527c9b60",
        "parse_status_code": 12000
      }
    }
  ]
}
```

</details>

### Diccionario de datos de salida

#### **Ejemplo HTML**

<div data-full-width="false"><figure><img src="/files/2397c7d69fc2ff6d6a6975da31b339637826e93b" alt=""><figcaption></figcaption></figure></div>

#### **Estructura JSON**

Todos los objetivos LLM devuelven el mismo `job` y `results[]` envoltorio. Consulta [LLMs and AI](/api-targets/es/llms-e-ia.md) para la referencia completa de metadatos.

La siguiente tabla muestra los `results[].content` campos específicos de Perplexity:

{% hint style="info" %}
El número de elementos y campos para un tipo de resultado específico puede variar según el prompt enviado.
{% endhint %}

<table><thead><tr><th width="171">Campo</th><th width="408">Descripción</th><th>Tipo</th></tr></thead><tbody><tr><td><code>prompt_query</code></td><td>Prompt enviado o consulta de búsqueda.</td><td>cadena</td></tr><tr><td><code>model</code></td><td>Modelo de Perplexity usado para la respuesta (p. ej., <code>turbo</code>).</td><td>cadena</td></tr><tr><td><code>answer_results</code></td><td>Respuesta generada como árbol JSON de Markdown.</td><td>array</td></tr><tr><td><code>answer_results_md</code></td><td>Respuesta generada en Markdown</td><td>cadena</td></tr><tr><td><mark style="background-color:yellow;"><code>additional_results</code></mark></td><td>Elementos de interfaz agrupados. <code>sources_results</code> – lista de fuentes web que usó Perplexity (<code>title</code> y <code>url</code>). Puede incluir <code>images_results</code>, <code>hotels_results</code>, <code>places_results</code>, <code>videos_results</code>, y <code>shopping_results</code>.</td><td>objeto</td></tr><tr><td><mark style="background-color:yellow;"><code>top_images</code></mark></td><td>Resultados de imágenes de Perplexity en la pestaña "Images". Los objetos incluyen <code>url</code> y <code>title</code>.</td><td>array</td></tr><tr><td><mark style="background-color:yellow;"><code>top_sources</code></mark></td><td>Resultados de fuentes mejor clasificadas de Perplexity. Los objetos incluyen <code>url</code>, <code>title</code>, y <code>source</code>.</td><td>array</td></tr><tr><td><mark style="background-color:yellow;"><code>inline_products</code></mark></td><td>Resultados de compras activados por consultas relacionadas con productos.</td><td>array</td></tr><tr><td><mark style="background-color:yellow;"><code>related_queries</code></mark></td><td>Preguntas de seguimiento sugeridas por Perplexity.</td><td>arreglo de cadenas</td></tr><tr><td><code>displayed_tabs</code></td><td>Pestañas de interfaz visibles en la página analizada (p. ej., Answer, Links, Images).</td><td>arreglo de cadenas</td></tr><tr><td><code>url</code></td><td>La URL de la página de búsqueda de Perplexity para esta consulta.</td><td>cadena</td></tr><tr><td><code>parse_status_code</code></td><td><code>12000</code> – correcto. De lo contrario, el analizador no pudo extraer algunos o todos los campos estructurados.</td><td>entero</td></tr></tbody></table>

&#x20;    – condicional, devuelto solo cuando el contenido está en la respuesta del LLM.

#### Resultados adicionales y productos integrados

Junto con la respuesta principal de la IA, devolvemos datos adicionales bajo `additional_results`, como

* `sources_results`
* `images_results`
* `shopping_results`
* `videos_results`
* `places_results`
* `hotels_results`

Estos arreglos se extraen de las pestañas de la página de resultados original y solo se incluyen si hay contenido relevante disponible:

<figure><img src="/files/a473531b318860da6b0ac74ea86ab8b8d2c79ee8" alt=""><figcaption></figcaption></figure>

El `inline_products` el arreglo también contiene productos que están incrustados directamente en la respuesta:

<figure><img src="/files/471a1a6443cdf29ed6ade7a0b7b58d044e774163" alt=""><figcaption></figcaption></figure>


---

# 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/api-targets/es/llms-e-ia/perplexity.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.
