> 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/cn/llm-he-ai/perplexity.md).

# Perplexity

该 `Perplexity` Perplexity 来源允许你提交提示并接收完整解析的结构化响应，其中包括格式化答案、使用的网页来源、相关查询和显示的 UI 选项卡。产品相关提示可以返回购物结果和内联产品列表。

## 请求示例

下面的代码示例展示了如何向 Perplexity 发送提示并获取解析后的响应。

{% 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" %}
**注意：** 所有 LLM 来源默认启用 JavaScript 渲染。你无需在请求负载中包含渲染参数。
{% endhint %}

我们在示例中使用同步 [**Realtime**](/products/cn/web-scraper-api/integration-methods/realtime.md) 集成方式。如果你想使用 [**Proxy Endpoint**](/products/cn/web-scraper-api/integration-methods/proxy-endpoint.md) 或异步 [**Push-Pull**](/products/cn/web-scraper-api/integration-methods/push-pull.md) 集成（包括 [批量查询](/products/cn/web-scraper-api/integration-methods/push-pull.md#batch-query)），请参阅 [**集成方式**](/products/cn/web-scraper-api/integration-methods.md) 部分。

### 请求参数

用于抓取 Perplexity 响应的基本设置和配置参数。

<table><thead><tr><th width="222">参数</th><th width="350.3333333333333">描述</th><th>默认值</th></tr></thead><tbody><tr><td><mark style="background-color:green;"><strong><code>source</code></strong></mark></td><td>设置抓取目标。使用 <code>Perplexity</code>.</td><td>–</td></tr><tr><td><mark style="background-color:green;"><strong><code>prompt</code></strong></mark></td><td>要提交给 Perplexity 的提示或问题。必须少于 8000 个字符。</td><td>–</td></tr><tr><td><code>parse</code></td><td>设为 <code>true</code> 用于结构化 JSON 数据。</td><td><code>false</code></td></tr><tr><td><code>geo_location</code></td><td>指定请求来源国家。 <a href="/spaces/ZwEHB9k4MH4pDy80n9mF/pages/eb847b3738ee0ad9f321c5de8b8291a0dd7ff7af"><strong>更多信息</strong></a>.</td><td>–</td></tr><tr><td><code>browser_instructions</code></td><td>渲染 JavaScript 时可选的自定义浏览器指令。 <a href="/spaces/ZwEHB9k4MH4pDy80n9mF/pages/9d7133837001de31de5dfd0796cfbc6fdd7c78c8#browser-instructions"><strong>更多信息</strong></a>.</td><td>–</td></tr><tr><td><code>callback_url</code></td><td>你的回调端点 URL。 <a href="https://developers.oxylabs.io/products/web-scraper-api/integration-methods/push-pull"><strong>更多信息</strong></a></td><td>–</td></tr></tbody></table>

&#x20;    \- 必填参数

## 结构化数据

网页爬虫API 返回 HTML 文档或 Perplexity 输出的 JSON 对象，其中包含结果页面中的结构化数据。

<details>

<summary><code>Perplexity</code> 结构化输出</summary>

```json
{
  "results": [
    {
      "job_id": "7470032181138587649",
      "status_code": 200,
      "url": "https://www.perplexity.ai/search/915bee3e-2d59-48ba-8b19-701f527c9b60",
      "content": {
        "prompt_query": "用于改善睡眠的最佳补充剂",
        "model": "turbo",
        "answer_results": [
          "以下是人们通常为了改善睡眠而尝试、且证据支持最充分的补充剂——以及最适合的人群和关键安全注意事项。",
          "证据支持最充分的选项（从这里开始）",
          ...
        ],
        "answer_results_md": "\n以下是人们通常为了改善睡眠而尝试、且证据支持最充分的补充剂——以及最适合的人群和关键安全注意事项。\n\n证据支持最充分的选项（从这里开始）\n-----------------------------------\n\n...",
        "additional_results": {
          "sources_results": [
            {
              "title": "改善睡眠的最佳补充剂和习惯（20 分钟）",
              "url": "https://coopercomplete.com/blog/best-supplements-for-better-sleep/"
            },
            {
              "title": "用这些 9 种睡眠补充剂睡得更好",
              "url": "https://drruscio.com/sleep-supplements/"
            },
            {
              "title": "睡眠支持的 10 种最佳补充剂：营养师推荐",
              "url": "https://letsliveitup.com/blogs/supergreens/best-sleep-supplements"
            },
            ...
          ]
        },
        "related_queries": [
          "成年人有哪些证据最强的睡眠辅助方法",
          "如何在不产生耐受的情况下轮换睡眠补充剂",
          "成年人最安全的褪黑素剂量指南是什么",
          "在使用补充剂时可最大化睡眠的生活方式调整"
        ],
        "displayed_tabs": [
          "答案",
          "链接",
          "图片"
        ],
        "url": "https://www.perplexity.ai/search/915bee3e-2d59-48ba-8b19-701f527c9b60",
        "parse_status_code": 12000
      }
    }
  ]
}
```

</details>

### 输出数据字典

#### **HTML 示例**

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

#### **JSON 结构**

所有 LLM 目标都会返回相同的顶层 `job` 和 `results[]` 封装。参见 [LLMs 与 AI](/api-targets/cn/llm-he-ai.md) 以获取完整元数据参考。

下表显示 Perplexity 专属的 `results[].content` 字段：

{% hint style="info" %}
特定结果类型的条目和字段数量可能因提交的提示而异。
{% endhint %}

<table><thead><tr><th width="171">字段</th><th width="408">描述</th><th>类型</th></tr></thead><tbody><tr><td><code>prompt_query</code></td><td>提交的提示或搜索查询。</td><td>字符串</td></tr><tr><td><code>model</code></td><td>用于响应的 Perplexity 模型（例如， <code>turbo</code>).</td><td>字符串</td></tr><tr><td><code>answer_results</code></td><td>以 Markdown JSON 树形式生成的答案。</td><td>数组</td></tr><tr><td><code>answer_results_md</code></td><td>以 Markdown 形式生成的答案</td><td>字符串</td></tr><tr><td><mark style="background-color:yellow;"><code>additional_results</code></mark></td><td>分组的 UI 元素。 <code>sources_results</code> – Perplexity 使用的网页来源列表（<code>title</code> 和 <code>url</code>）。可包括 <code>images_results</code>, <code>hotels_results</code>, <code>places_results</code>, <code>videos_results</code>，以及 <code>shopping_results</code>.</td><td>对象</td></tr><tr><td><mark style="background-color:yellow;"><code>top_images</code></mark></td><td>Perplexity 在“图片”选项卡中的图片结果。对象包括 <code>url</code> 和 <code>title</code>.</td><td>数组</td></tr><tr><td><mark style="background-color:yellow;"><code>top_sources</code></mark></td><td>Perplexity 排名靠前的来源结果。对象包括 <code>url</code>, <code>title</code>，以及 <code>source</code>.</td><td>数组</td></tr><tr><td><mark style="background-color:yellow;"><code>inline_products</code></mark></td><td>由产品相关查询触发的购物结果。</td><td>数组</td></tr><tr><td><mark style="background-color:yellow;"><code>related_queries</code></mark></td><td>Perplexity 建议的后续问题。</td><td>字符串数组</td></tr><tr><td><code>displayed_tabs</code></td><td>解析页面上可见的 UI 选项卡（例如 答案、链接、图片）。</td><td>字符串数组</td></tr><tr><td><code>url</code></td><td>此查询对应的 Perplexity 搜索页面 URL。</td><td>字符串</td></tr><tr><td><code>parse_status_code</code></td><td><code>12000</code> – 成功。否则，解析器未能提取部分或全部结构化字段。</td><td>整数</td></tr></tbody></table>

&#x20;    – 条件返回，仅当内容出现在 LLM 的响应中时返回。

#### 附加结果和内嵌产品

除主要 AI 响应外，我们还会在下返回额外数据 `additional_results`，例如

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

这些数组是从原始结果页的各个标签页中提取的，仅在有相关内容可用时才包含：

<figure><img src="/files/820d21067faceaefe19ede9c7823eb2e9de6335f" alt=""><figcaption></figcaption></figure>

该 `inline_products` 该数组还包含直接嵌入在响应中的产品：

<figure><img src="/files/2d5b9be4b20178ba101dea8e0e4eacdf5629a06f" 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/cn/llm-he-ai/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.
