Отчёты о расходах, выполнениях и точности

Прочитайте, сколько потратил проект, чем закончились его выполнения, насколько точными были оценки его вызовов модели и во что обошлись его клиенты.

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

Какой отчёт на что отвечает

ОтчётНа что он отвечает
GET /v1/analytics/spendСколько проект потратил сегодня и в текущем календарном месяце, по дням, и сколько осталось в его бюджетах.
GET /v1/analytics/costsКуда ушли деньги за окно: по дням, по моделям и по подключениям провайдеров.
GET /v1/analytics/deliveryЧем закончились выполнения флоу проекта за окно, сколько ответов пришло из кеша и сколько кеш сэкономил.
GET /v1/analytics/accuracyНасколько оценки вызовов модели отличались от того, сколько стоили вызовы, — в целом и по операциям.
GET /v1/analytics/customer-marginКредиты, списанные с ваших клиентов, против того, сколько стоили их вызовы.

Отчёт о расходах и разбивка стоимости считают по-разному, поэтому их итоги могут расходиться. Отчёт о расходах суммирует то, что проведено по реестру. Разбивка стоимости суммирует стоимость каждой попытки обращения к провайдеру.

Отчёт о выполнениях считает выполнения флоу.

Окно отчёта

Отчёт о расходах не принимает окно. Каждый из остальных отчётов принимает from и to, и оба необязательны.

  • Без to окно заканчивается сейчас. Без from оно начинается за семь дней до своего конца.

  • Слишком длинное окно не отклоняется: его начало сдвигается вперёд. Разбивка стоимости и маржа по клиентам охватывают 31 день до конца окна, а отчёты о выполнениях и о точности — 366 дней.

  • Когда from не раньше, чем to, окно — это семь дней перед to.

Правило списков — оба конца вместе, не больше семи дней — к отчёту не применяется, и отчёт не отвечает invalid_date_range. Ответ называет окно, которое было использовано.

Сводка флоу (Флоу) берёт окно так же и считает только целые закрытые часы: её from и to сдвигаются к началу своего часа, а текущий час не учитывается.

Операции

Описания операций и полей приведены на английском.

Расходы по реестру — сегодня, за месяц, остаток

GET /v1/analytics/spend

  • Разрешение: read

No window: today, this month, and the headroom right now.

Ответы

200

Spend summary

application/json
{
  "data": {
    "currency": "USD",
    "spend_today": "0.02700000",
    "spend_month": "0.02700000",
    "active_reservations": 1,
    "request_count": 1,
    "average_cost": "0.02700000",
    "denied_operations": 1,
    "available_budget": "0.02700000",
    "daily": [
      {
        "date": "string",
        "spend": "0.02700000",
        "count": 1
      }
    ]
  }
}

Ошибки

СтатусКодыКогда
401

No credential, or one that is not valid

403

Authenticated, but not allowed: scope (insufficient_scope), policy or tenant (not_a_member); a blocked end customer (customer_blocked); an act only a signed-in person may take (session_required); the role rule on members and invitations (member_forbidden, invite_forbidden); a write to the organization's own rows, or a read of the audit journal, by a caller that does not reach every project (project_access_restricted)

Заголовки

  • X-Request-Id

Тело каждой ошибки — конверт ошибки.

Доля успешных запросов и попаданий в кеш по часам

GET /v1/analytics/delivery

  • Разрешение: read

Параметры

ПараметрОписание
from необязательно

querystring

Start of the window an analytics answer covers — a date the server can parse, ISO-8601 recommended (a value without an offset is read as UTC). Unlike the lists, each end is optional on its own and the window is never refused, only fitted (AnalyticsWindowResolver):

  • Формат: date-time
to необязательно

querystring

End of the window an analytics answer covers; now when absent. See from (WindowFrom) for how the window is fitted rather than refused.

  • Формат: date-time

Ответы

200

Delivery summary

application/json
{
  "data": {
    "from": "2026-10-02T09:30:00Z",
    "to": "2026-10-02T09:30:00Z",
    "requests": 1,
    "completed": 1,
    "failed": 1,
    "rejected": 1,
    "cache_hits": 1,
    "success_rate": "string",
    "cache_hit_rate": "string",
    "p95_duration_ms": 1,
    "active_flows": 1,
    "saved_cost": "0.02700000",
    "prevented_spend": "0.02700000"
  }
}

Ошибки

СтатусКодыКогда
401

No credential, or one that is not valid

403

Authenticated, but not allowed: scope (insufficient_scope), policy or tenant (not_a_member); a blocked end customer (customer_blocked); an act only a signed-in person may take (session_required); the role rule on members and invitations (member_forbidden, invite_forbidden); a write to the organization's own rows, or a read of the audit journal, by a caller that does not reach every project (project_access_restricted)

422

Validation failure or a semantically impossible request. Field-level validation from the framework answers {"message", "errors"}; domain refusals answer the standard error envelope. An Idempotency-Key longer than 190 characters is invalid_request in that envelope.

Заголовки

  • X-Request-Id

Тело каждой ошибки — конверт ошибки.

Точность оценок

GET /v1/analytics/accuracy

  • Разрешение: read

Summed over the daily accuracy snapshots, so the window is honoured. A window the snapshots do not cover yet answers the lifetime counters with is_all_time: true.

Параметры

ПараметрОписание
from необязательно

querystring

Start of the window an analytics answer covers — a date the server can parse, ISO-8601 recommended (a value without an offset is read as UTC). Unlike the lists, each end is optional on its own and the window is never refused, only fitted (AnalyticsWindowResolver):

  • Формат: date-time
to необязательно

querystring

End of the window an analytics answer covers; now when absent. See from (WindowFrom) for how the window is fitted rather than refused.

  • Формат: date-time

Ответы

200

Estimation accuracy

application/json
{
  "data": {
    "window": {
      "from": "string",
      "to": "string"
    },
    "is_all_time": true,
    "history_since": "string",
    "trend": [
      {
        "day": "string",
        "sample_count": 1,
        "mae_cost": "0.02700000",
        "bias_cost": "0.02700000",
        "cost_relative_error": "string"
      }
    ],
    "sample_count": 1,
    "underestimated_input_count": 1,
    "underestimated_input_rate": "string",
    "avg_input_token_error": "string",
    "avg_output_token_error": "string",
    "avg_cost_error": "0.02700000",
    "cost_error_sum": "0.02700000",
    "mae_cost": "0.02700000",
    "mae_input_tokens": "string",
    "mae_output_tokens": "string",
    "cost_relative_error": "string",
    "input_token_relative_error": "string",
    "output_token_relative_error": "string",
    "bias_direction": "under",
    "estimated_cost_sum": "0.02700000",
    "actual_cost_sum": "0.02700000",
    "by_operation": [
      {
        "operation_code": "generate_email",
        "provider": "string",
        "model": "gpt-4o-mini",
        "sample_count": 1,
        "underestimated_input_count": 1,
        "avg_cost_error": "0.02700000",
        "mae_cost": "0.02700000",
        "cost_relative_error": "string",
        "bias_direction": "under",
        "needs_attention": true,
        "estimated_cost_sum": "0.02700000",
        "actual_cost_sum": "0.02700000"
      }
    ]
  }
}

Ошибки

СтатусКодыКогда
401

No credential, or one that is not valid

403

Authenticated, but not allowed: scope (insufficient_scope), policy or tenant (not_a_member); a blocked end customer (customer_blocked); an act only a signed-in person may take (session_required); the role rule on members and invitations (member_forbidden, invite_forbidden); a write to the organization's own rows, or a read of the audit journal, by a caller that does not reach every project (project_access_restricted)

Заголовки

  • X-Request-Id

Тело каждой ошибки — конверт ошибки.

Куда ушли деньги — по дням, моделям и подключениям

GET /v1/analytics/costs

  • Разрешение: read

Attributed per attempt over a caller-chosen window — deliberately not the same number as /v1/analytics/spend, which is the ledger's.

Параметры

ПараметрОписание
from необязательно

querystring

Start of the window an analytics answer covers — a date the server can parse, ISO-8601 recommended (a value without an offset is read as UTC). Unlike the lists, each end is optional on its own and the window is never refused, only fitted (AnalyticsWindowResolver):

  • Формат: date-time
to необязательно

querystring

End of the window an analytics answer covers; now when absent. See from (WindowFrom) for how the window is fitted rather than refused.

  • Формат: date-time

Ответы

200

Cost breakdown

application/json
{
  "data": {
    "window": {
      "from": "2026-10-02T09:30:00Z",
      "to": "2026-10-02T09:30:00Z"
    },
    "currency": "USD",
    "total_cost": "0.02700000",
    "requests": 1,
    "attempts": 1,
    "by_day": [
      {
        "key": "string",
        "cost": "0.02700000",
        "requests": 1,
        "attempts": 1,
        "share": "string"
      }
    ],
    "by_model": [
      {
        "key": "string",
        "cost": "0.02700000",
        "requests": 1,
        "attempts": 1,
        "share": "string"
      }
    ],
    "by_connection": [
      {
        "key": "string",
        "cost": "0.02700000",
        "requests": 1,
        "attempts": 1,
        "share": "string"
      }
    ],
    "by_model_connection": [
      {
        "model_code": "gpt-4o-mini",
        "connection_id": "74438200973594624",
        "cost": "0.02700000",
        "requests": 1,
        "attempts": 1,
        "share": "string"
      }
    ]
  }
}

Ошибки

СтатусКодыКогда
401

No credential, or one that is not valid

403

Authenticated, but not allowed: scope (insufficient_scope), policy or tenant (not_a_member); a blocked end customer (customer_blocked); an act only a signed-in person may take (session_required); the role rule on members and invitations (member_forbidden, invite_forbidden); a write to the organization's own rows, or a read of the audit journal, by a caller that does not reach every project (project_access_restricted)

422

Validation failure or a semantically impossible request. Field-level validation from the framework answers {"message", "errors"}; domain refusals answer the standard error envelope. An Idempotency-Key longer than 190 characters is invalid_request in that envelope.

Заголовки

  • X-Request-Id

Тело каждой ошибки — конверт ошибки.

Маржа — списанные кредиты против стоимости вызовов

GET /v1/analytics/customer-margin

  • Разрешение: read

Two sides in two units, never a ratio: credits and dollars are different things, and only the tenant knows what a credit sells for. Reads raw journal and attempt rows, so the window is capped.

Параметры

ПараметрОписание
from необязательно

querystring

Start of the window an analytics answer covers — a date the server can parse, ISO-8601 recommended (a value without an offset is read as UTC). Unlike the lists, each end is optional on its own and the window is never refused, only fitted (AnalyticsWindowResolver):

  • Формат: date-time
to необязательно

querystring

End of the window an analytics answer covers; now when absent. See from (WindowFrom) for how the window is fitted rather than refused.

  • Формат: date-time
external_user_id необязательно

querystring

Narrows the report to one customer; absent means all of them.

  • Максимальная длина: 190

Ответы

200

Margin for the window, in total and per customer

application/json
{
  "data": {
    "window": {
      "from": "2026-10-02T09:30:00Z",
      "to": "2026-10-02T09:30:00Z"
    },
    "currency": "USD",
    "total": {
      "external_user_id": "user_8421",
      "credits_spent": "12.5000",
      "usd_cost": "0.02700000",
      "requests": 1
    },
    "by_customer": [
      {
        "external_user_id": "user_8421",
        "credits_spent": "12.5000",
        "usd_cost": "0.02700000",
        "requests": 1
      }
    ]
  }
}

Ошибки

СтатусКодыКогда
401

No credential, or one that is not valid

403

Authenticated, but not allowed: scope (insufficient_scope), policy or tenant (not_a_member); a blocked end customer (customer_blocked); an act only a signed-in person may take (session_required); the role rule on members and invitations (member_forbidden, invite_forbidden); a write to the organization's own rows, or a read of the audit journal, by a caller that does not reach every project (project_access_restricted)

422

Validation failure or a semantically impossible request. Field-level validation from the framework answers {"message", "errors"}; domain refusals answer the standard error envelope. An Idempotency-Key longer than 190 characters is invalid_request in that envelope.

Заголовки

  • X-Request-Id

Тело каждой ошибки — конверт ошибки.

Примеры

Прочитать расходы за месяц

average_cost — это spend_month, делённое на request_count. available_budget — наименьший остаток среди бюджетов проекта и null, когда у проекта их нет.

Terminal
curl https://api.slen.ai/api/v1/analytics/spend \
  -H "Authorization: Bearer $SLEN_API_KEY"
200 OK
{
  "data": {
    "currency": "USD",
    "spend_today": "3.18240000",
    "spend_month": "41.90775000",
    "active_reservations": 0,
    "request_count": 1301,
    "average_cost": "0.03221195",
    "denied_operations": 5,
    "available_budget": "458.09225000",
    "daily": [
      {
        "date": "2026-10-01",
        "spend": "38.72535000",
        "count": 1204
      },
      {
        "date": "2026-10-02",
        "spend": "3.18240000",
        "count": 97
      }
    ]
  }
}

Прочитать, чем закончились выполнения

Окно — сентябрь.

Terminal
curl "https://api.slen.ai/api/v1/analytics/delivery?from=2026-09-01T00%3A00%3A00Z&to=2026-10-01T00%3A00%3A00Z" \
  -H "Authorization: Bearer $SLEN_API_KEY"

Прочитать точность оценок

Когда в окне нет измерений, ответ несёт показатели за всю историю проекта и говорит об этом значением true в is_all_time.

Terminal
curl "https://api.slen.ai/api/v1/analytics/accuracy?from=2026-09-01T00%3A00%3A00Z&to=2026-10-01T00%3A00%3A00Z" \
  -H "Authorization: Bearer $SLEN_API_KEY"

Разбить стоимость

Окно — семь дней. share у среза — это его доля в total_cost.

Terminal
curl "https://api.slen.ai/api/v1/analytics/costs?from=2026-09-25T00%3A00%3A00Z&to=2026-10-02T00%3A00%3A00Z" \
  -H "Authorization: Bearer $SLEN_API_KEY"

Прочитать маржу по клиентам

Две стороны — в двух единицах: credits_spent — это кредиты, а usd_cost — деньги. Считаются только вызовы со списанием. external_user_id в строке запроса сужает отчёт до одного клиента.

Terminal
curl "https://api.slen.ai/api/v1/analytics/customer-margin?from=2026-09-25T00%3A00%3A00Z&to=2026-10-02T00%3A00%3A00Z" \
  -H "Authorization: Bearer $SLEN_API_KEY"
200 OK
{
  "data": {
    "window": {
      "from": "2026-09-25T00:00:00+00:00",
      "to": "2026-10-02T00:00:00+00:00"
    },
    "currency": "USD",
    "total": {
      "credits_spent": "36.0000",
      "usd_cost": "0.41280000",
      "requests": 18
    },
    "by_customer": [
      {
        "external_user_id": "user_8421",
        "credits_spent": "24.0000",
        "usd_cost": "0.27520000",
        "requests": 12
      },
      {
        "external_user_id": "user_3107",
        "credits_spent": "12.0000",
        "usd_cost": "0.13760000",
        "requests": 6
      }
    ]
  }
}

Что читать дальше

  • Обзор — как в ответе записываются деньги, кредиты и время.

  • Аутентификация — разрешение, которое нужно ключу, чтобы прочитать отчёт.

Собрано из openapi b070e1f, sdk contract 5cc7055, php ae4a53b, node 84bc62d