# Live-ответы Perplexity LLM

**API:** Data API

**Endpoint:** `POST /v1/beta/dataforseo/ai_optimization/perplexity/llm_responses/live`

**Tags:** DataForSEO

Синхронно отправляет `user_prompt` модели Perplexity и возвращает её ответ. `model_name` должен быть взят из `get_dataforseo_ai_perplexity_llm_responses_models` — `sonar`, `sonar-pro` и `sonar-reasoning-pro`. `web_search_country_iso_code` ограничивает поиск страной; другие три поставщика этого не предлагают. Возвращает `model_name`, `input_tokens`, `output_tokens`, `reasoning_tokens`, `web_search`, `money_spent`, `datetime`, `items` и `fan_out_queries`. Прочитайте `money_spent` в ответе, чтобы узнать фактическую стоимость промпта. Упаковано в конверт DataForSEO: данные в `tasks[0].result`, результат в `tasks[0].status_code` — отклонённый запрос всё равно возвращает HTTP 200.

### Справочная информация о цене

- Тарификация: по заявленной стоимости ответа.
- Ориентировочная стоимость запроса: 0.0163 USD.
- Справочный коэффициент клиента: 1.0. Не применяйте его повторно к уже рассчитанной сумме клиента.

Только справочные метаданные, а не предложение для аккаунта, гарантированная цена или лимит расходов. Кредиты ресурсов — не кредиты Felo. Окончательные списания определяются записями биллинга Felo.

## Base URL

- `https://openapi.felo.ai`

## Authentication

- `FeloBearerAuth` (http bearer, bearer format Felo API Key)
- `FeloApiKey` (apiKey in header `X-API-Key`)

## Request body

Required: **no**

### application/json

Schema:

```json
{
  "type": "array",
  "items": {
    "type": [
      "object",
      "null"
    ],
    "oneOf": [
      {
        "type": "object",
        "properties": {
          "user_prompt": {
            "type": "string",
            "description": "<em>промпт для AI-модели</em><br><strong>обязательное поле</strong><br>вопрос или задача, которые нужно отправить AI-модели;<br>в поле <code>user_prompt</code> можно указать <strong>до 500 символов</strong>"
          },
          "model_name": {
            "type": "string",
            "description": "<em>название модели AI</em><br><strong>обязательное поле</strong><br><code>model_name</code >состоит из фактического названия модели и названия версии;<br>если указано базовое название модели, по умолчанию будет установлена её последняя версия;<br>список доступных моделей LLM можно получить, сделав отдельный запрос к следующему эндпоинту: <code>https://api.dataforseo.com/v3/ai_optimization/perplexity/llm_responses/models</code>"
          },
          "max_output_tokens": {
            "type": [
              "integer",
              "null"
            ],
            "description": "<em>максимальное количество токенов в ответе AI</em><br>необязательное поле<br>минимальное значение: <code>1</code><br>максимальное значение: <code>4096</code>;<br>значение по умолчанию: <code>2048</code>;<br><strong>Примечание:</strong> если в запросе указана рассуждающая модель, количество выходных токенов может превысить указанный лимит <code>max_output_tokens</code>"
          },
          "temperature": {
            "type": [
              "number",
              "null"
            ],
            "description": "<em>степень случайности ответа AI</em><br>необязательное поле<br>более высокие значения делают вывод более разнообразным <br>более низкие значения делают вывод более сфокусированным<br>минимальное значение: <code>0</code><br>максимальное значение: <code>1.9</code><br>значение по умолчанию: <code>0.77</code>"
          },
          "top_p": {
            "type": [
              "number",
              "null"
            ],
            "description": "<em>разнообразие ответа AI</em><br>необязательное поле <br>управляет разнообразием ответа, ограничивая выбор токенов<br>минимальное значение: <code>0</code><br>максимальное значение: <code>1</code> <br>значение по умолчанию: <code>0.9</code>"
          },
          "web_search_country_iso_code": {
            "type": [
              "string",
              "null"
            ],
            "description": "<em>код страны для локализации веб-поиска</em><br>необязательное поле<br>укажите код страны ISO, чтобы получать локализованные результаты веб-поиска<br><strong>Примечание:</strong> доступно только для моделей Perplexity Sonar<br>пример: <code>US</code>"
          },
          "system_message": {
            "type": [
              "string",
              "null"
            ],
            "description": "<em>инструкции для поведения AI</em><br>необязательное поле<br>определяет роль, тон или конкретное поведение AI <br>в поле <code>system_message</code> можно указать <strong>до 500 символов</strong>"
          },
          "message_chain": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": [
                "object",
                "null"
              ],
              "oneOf": [
                {
                  "type": "object",
                  "properties": {
                    "role": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "роль пользователя, от которого исходит сообщение"
                    },
                    "message": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "текст сообщения"
                    }
                  }
                }
              ]
            },
            "description": "история диалога\nнеобязательное поле\nмассив объектов сообщений, представляющих предыдущие реплики диалога;\nкаждый объект должен содержать:\nrole — строка с ролью user или ai;\nmessage — строка с текстом сообщения (не более 500 символов);\nв массиве можно указать не более 10 объектов сообщений;\nПримечание: для моделей Perplexity сообщения должны строго чередоваться по ролям user и AI (user → ai);\nпример:\n\"message_chain\": [{\"role\":\"user\",\"message\":\"Hello, what’s up?\"},{\"role\":\"ai\",\"message\":\"Hello! I’m doing well, thank you. How can I assist you today?\"}]"
          },
          "tag": {
            "type": [
              "string",
              "null"
            ],
            "description": "<em>пользовательский идентификатор задачи</em><br>необязательное поле<br><em>ограничение — 255 символов</em><br>этот параметр позволяет идентифицировать задачу и сопоставить её с результатом<br>указанное значение <code>tag</code> вы найдёте в объекте <code>data</code> ответа"
          }
        },
        "example": [
          {
            "system_message": "communicate as if we are in a business meeting",
            "message_chain": [
              {
                "role": "user",
                "message": "Hello, what’s up?"
              },
              {
                "role": "ai",
                "message": "Hello! I’m doing well, thank you. How can I assist you today? Are there any specific topics or projects you’d like to discuss in our meeting?"
              }
            ],
            "max_output_tokens": 200,
            "temperature": 0.3,
            "top_p": 0.5,
            "web_search_country_iso_code": "FR",
            "model_name": "sonar",
            "user_prompt": "provide information on how relevant the amusement park business is in France now"
          }
        ]
      }
    ]
  },
  "example": [
    {
      "system_message": "communicate as if we are in a business meeting",
      "message_chain": [
        {
          "role": "user",
          "message": "Hello, what’s up?"
        },
        {
          "role": "ai",
          "message": "Hello! I’m doing well, thank you. How can I assist you today? Are there any specific topics or projects you’d like to discuss in our meeting?"
        }
      ],
      "max_output_tokens": 200,
      "temperature": 0.3,
      "top_p": 0.5,
      "web_search_country_iso_code": "FR",
      "model_name": "sonar",
      "user_prompt": "provide information on how relevant the amusement park business is in France now"
    }
  ]
}
```

## Responses

### 200 — Успешная операция

Headers:
- `X-Request-Id` (string) — Идентификатор запроса, который нужно указать при обращении в поддержку Felo.

**application/json**

Schema: object | null

```json
{
  "type": [
    "object",
    "null"
  ],
  "oneOf": [
    {
      "$ref": "#/components/schemas/Response36Afe1097B20_AiOptimizationPerplexityLlmResponsesLiveResponseInfo"
    }
  ]
}
```

### 400 — Запрос не удалось обработать. Проверьте параметры запроса.

### 401 — Требуется действительный API-ключ Felo.

### 402 — Запрос не может быть выполнен: не выполнено требование биллинга.

### 403 — Аккаунту не разрешено выполнять эту операцию.

### 429 — Достигнут лимит запросов или расходов.

### 502 — Сервис не смог выполнить запрос.

### 503 — API или сервис биллинга временно недоступны.

### 504 — Истекло время ожидания обработки запроса.

### default — Ответ с ошибкой; сквозные ответы upstream могут использовать форматы провайдера

**application/json**

Schema:

```json
{}
```

## Schema definitions

### Response36Afe1097B20_AiOptimizationPerplexityLlmResponsesLiveResponseInfo

`#/components/schemas/Response36Afe1097B20_AiOptimizationPerplexityLlmResponsesLiveResponseInfo`

```json
{
  "type": "object",
  "allOf": [
    {
      "$ref": "#/components/schemas/Response36Afe1097B20_BaseResponseInfo"
    },
    {
      "type": "object",
      "properties": {
        "tasks": {
          "type": [
            "array",
            "null"
          ],
          "items": {
            "type": [
              "object",
              "null"
            ],
            "oneOf": [
              {
                "$ref": "#/components/schemas/Response36Afe1097B20_AiOptimizationPerplexityLlmResponsesLiveTaskInfo"
              }
            ]
          },
          "description": "<em>массив задач</em>"
        }
      }
    }
  ]
}
```

### Response36Afe1097B20_AiOptimizationPerplexityLlmResponsesLiveResultInfo

`#/components/schemas/Response36Afe1097B20_AiOptimizationPerplexityLlmResponsesLiveResultInfo`

```json
{
  "type": "object",
  "properties": {
    "model_name": {
      "type": [
        "string",
        "null"
      ],
      "description": "<em>название используемой AI-модели</em>"
    },
    "input_tokens": {
      "type": [
        "integer",
        "null"
      ],
      "description": "<em>количество токенов во входных данных</em><br>общее число обработанных токенов"
    },
    "output_tokens": {
      "type": [
        "integer",
        "null"
      ],
      "description": "<em>количество токенов в выходных данных</em><br>общее число токенов, сгенерированных в ответе AI"
    },
    "reasoning_tokens": {
      "type": [
        "integer",
        "null"
      ]
    },
    "web_search": {
      "type": [
        "boolean",
        "null"
      ],
      "description": "<em>указывает, использовался ли веб-поиск</em><br><strong>Примечание:</strong> в моделях Perplexity Sonar веб-поиск включен по умолчанию"
    },
    "money_spent": {
      "type": [
        "number",
        "null"
      ],
      "description": "<em>стоимость AI-токенов, USD</em><br>цена, которую сторонний поставщик AI-модели взимает согласно своим <a href=\"https://docs.perplexity.ai/guides/pricing\" target=\"_blank\">тарифам</a>"
    },
    "datetime": {
      "type": [
        "string",
        "null"
      ],
      "description": "<em>дата и время получения результата</em><br>в формате UTC: “yyyy-mm-dd hh-mm-ss +00:00”<br>пример:<br><code class=\"long-string\">2019-11-15 12:57:46 +00:00</code>"
    },
    "items": {
      "type": [
        "array",
        "null"
      ],
      "items": {
        "type": [
          "object",
          "null"
        ],
        "oneOf": [
          {
            "$ref": "#/components/schemas/Response36Afe1097B20_MessageAiOptimizationLlmResponseElementItem"
          }
        ]
      },
      "description": "<em>массив элементов ответа</em><br>содержит структурированные данные ответа AI"
    },
    "fan_out_queries": {
      "type": [
        "object",
        "null"
      ],
      "description": "<em>массив fan-out запросов</em><br>содержит связанные поисковые запросы, производные от основного запроса, для более полного ответа"
    }
  }
}
```

### Response36Afe1097B20_AiOptimizationPerplexityLlmResponsesLiveTaskInfo

`#/components/schemas/Response36Afe1097B20_AiOptimizationPerplexityLlmResponsesLiveTaskInfo`

```json
{
  "type": "object",
  "allOf": [
    {
      "$ref": "#/components/schemas/Response36Afe1097B20_BaseResponseTaskInfo"
    },
    {
      "type": "object",
      "properties": {
        "result": {
          "type": [
            "array",
            "null"
          ],
          "items": {
            "type": [
              "object",
              "null"
            ],
            "oneOf": [
              {
                "$ref": "#/components/schemas/Response36Afe1097B20_AiOptimizationPerplexityLlmResponsesLiveResultInfo"
              }
            ]
          },
          "description": "<em>массив результатов</em>"
        }
      }
    }
  ]
}
```

### Response36Afe1097B20_AnnotationInfo

`#/components/schemas/Response36Afe1097B20_AnnotationInfo`

```json
{
  "type": "object",
  "properties": {
    "title": {
      "type": [
        "string",
        "null"
      ],
      "description": "<em>доменное имя или заголовок цитируемого источника</em>"
    },
    "url": {
      "type": [
        "string",
        "null"
      ],
      "description": "<em>URL перенаправления к цитируемому источнику</em><br>содержит перенаправление Vertex AI, ведущее к исходному источнику"
    },
    "direct_url": {
      "type": [
        "string",
        "null"
      ],
      "description": "<em>прямой URL к цитируемому источнику</em><br>содержит URL исходного источника, на который ведет перенаправление Vertex AI в поле `url`"
    },
    "start_index": {
      "type": [
        "integer",
        "null"
      ],
      "description": "<em>начало индексации аннотации</em>"
    },
    "end_index": {
      "type": [
        "integer",
        "null"
      ],
      "description": "<em>конец индексации аннотации</em>"
    },
    "text": {
      "type": [
        "string",
        "null"
      ],
      "description": "<em>текст раздела цепочки рассуждений</em><br>текст раздела цепочки рассуждений, обобщающего мыслительный процесс модели"
    }
  }
}
```

### Response36Afe1097B20_BaseAiOptimizationLlmResponseElementItem

`#/components/schemas/Response36Afe1097B20_BaseAiOptimizationLlmResponseElementItem`

```json
{
  "type": "object",
  "properties": {
    "type": {
      "type": [
        "string",
        "null"
      ],
      "description": "тип элемента"
    }
  },
  "additionalProperties": false,
  "discriminator": {
    "propertyName": "type",
    "mapping": {
      "reasoning": "#/components/schemas/Response36Afe1097B20_ReasoningAiOptimizationLlmResponseElementItem",
      "message": "#/components/schemas/Response36Afe1097B20_MessageAiOptimizationLlmResponseElementItem"
    }
  }
}
```

### Response36Afe1097B20_BaseResponseInfo

`#/components/schemas/Response36Afe1097B20_BaseResponseInfo`

```json
{
  "properties": {
    "version": {
      "type": [
        "string",
        "null"
      ],
      "description": "текущая версия API"
    },
    "status_code": {
      "type": [
        "integer",
        "null"
      ],
      "description": "общий код состояния.\nПолный список кодов ответа можно найти здесь."
    },
    "status_message": {
      "type": [
        "string",
        "null"
      ],
      "description": "общее информационное сообщение.\nПолный список общих информационных сообщений можно найти здесь."
    },
    "time": {
      "type": [
        "string",
        "null"
      ],
      "description": "общее время выполнения, секунды"
    },
    "cost": {
      "type": [
        "number",
        "null"
      ],
      "description": "общая стоимость задач, USD",
      "format": "double"
    },
    "tasks_count": {
      "type": [
        "integer",
        "null"
      ],
      "description": "число задач в массиве tasks",
      "format": "int64"
    },
    "tasks_error": {
      "type": [
        "integer",
        "null"
      ],
      "description": "число задач в массиве tasks, возвращённых с ошибкой",
      "format": "int64"
    }
  }
}
```

### Response36Afe1097B20_BaseResponseTaskInfo

`#/components/schemas/Response36Afe1097B20_BaseResponseTaskInfo`

```json
{
  "properties": {
    "id": {
      "type": [
        "string",
        "null"
      ],
      "description": "идентификатор задачи\nуникальный идентификатор задачи в нашей системе в формате UUID"
    },
    "status_code": {
      "type": [
        "integer",
        "null"
      ],
      "description": "код состояния задачи\nформируется DataForSEO, может находиться в диапазоне 10000-60000\nПолный список кодов ответа можно найти здесь."
    },
    "status_message": {
      "type": [
        "string",
        "null"
      ],
      "description": "информационное сообщение задачи\nПолный список общих информационных сообщений можно найти здесь."
    },
    "time": {
      "type": [
        "string",
        "null"
      ],
      "description": "время выполнения, секунды"
    },
    "cost": {
      "type": [
        "number",
        "null"
      ],
      "description": "общая стоимость задач, USD",
      "format": "double"
    },
    "result_count": {
      "type": [
        "integer",
        "null"
      ],
      "description": "число элементов в массиве result",
      "format": "int64"
    },
    "path": {
      "type": [
        "array",
        "null"
      ],
      "items": {
        "type": [
          "string",
          "null"
        ]
      },
      "description": "путь URL"
    },
    "data": {
      "type": [
        "object",
        "null"
      ],
      "additionalProperties": {
        "type": [
          "object",
          "null"
        ]
      },
      "description": "содержит те же параметры, что вы указали в POST-запросе"
    }
  }
}
```

### Response36Afe1097B20_LlmMessageSectionInfo

`#/components/schemas/Response36Afe1097B20_LlmMessageSectionInfo`

```json
{
  "type": "object",
  "properties": {
    "type": {
      "type": [
        "string",
        "null"
      ],
      "description": "тип элемента"
    },
    "text": {
      "type": [
        "string",
        "null"
      ],
      "description": "<em>текст раздела цепочки рассуждений</em><br>текст раздела цепочки рассуждений, обобщающего мыслительный процесс модели"
    },
    "annotations": {
      "type": [
        "array",
        "null"
      ],
      "items": {
        "type": [
          "object",
          "null"
        ],
        "oneOf": [
          {
            "$ref": "#/components/schemas/Response36Afe1097B20_AnnotationInfo"
          }
        ]
      },
      "description": "<em>массив ссылок, использованных для генерации ответа</em><br>равен <code>null</code>, если параметр <code>web_search</code> не имеет значения <code>true</code><br><strong>Примечание:</strong> <code>annotations</code> может вернуться пустым, даже если <code>web_search</code> имеет значение <code>true</code>, так как ИИ попытается получить информацию из интернета, но может не найти релевантных результатов"
    }
  }
}
```

### Response36Afe1097B20_MessageAiOptimizationLlmResponseElementItem

`#/components/schemas/Response36Afe1097B20_MessageAiOptimizationLlmResponseElementItem`

```json
{
  "type": "object",
  "allOf": [
    {
      "$ref": "#/components/schemas/Response36Afe1097B20_BaseAiOptimizationLlmResponseElementItem"
    },
    {
      "type": "object",
      "properties": {
        "sections": {
          "type": [
            "array",
            "null"
          ],
          "items": {
            "type": [
              "object",
              "null"
            ],
            "oneOf": [
              {
                "$ref": "#/components/schemas/Response36Afe1097B20_LlmMessageSectionInfo"
              }
            ]
          },
          "description": "<em>разделы цепочки рассуждений</em><br>массив объектов с разделами цепочки рассуждений, сгенерированными LLM"
        }
      }
    }
  ]
}
```
