Логотип Agent Cost And Latency Spike Investigation

Agent Cost And Latency Spike Investigation

Сообщество
selvarajmurugesan90
agent-cost-and-latency-spike-investigation

Помогает быстро разобраться с внезапным скачком затрат или задержки в одном конкретном сценарии работы агента: определить его масштаб, сопоставить с недавними изменениями и применить быстрое безопасное временное решение — до начала полной оптимизации. Используйте этот навык, если пользователь спрашивает: «почему за ночь так вырос счет за LLM», «почему этот сценарий внезапно стал медленным/дорогим», просит «разобраться со скачком затрат/задержки» или сообщает о неожиданном предупреждении или счете для одного агента либо типа задач. Навык предназначен именно для таких случаев, а не для планового снижения базовых затрат или задержки.

Add to TypingMind

Обзор

Издательselvarajmurugesan90
Репозиторийops-engineering-skills
Название навыкаagent-cost-and-latency-spike-investigation
Звёзды
44
Форки
18
Файлы в комплекте
Только инструкции
ЛицензияApache-2.0
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — selvarajmurugesan90. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Agent Cost And Latency Spike Investigation в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/selvarajmurugesan90/ops-engineering-skills/tree/main/plugins/ai-agent/skills/agent-cost-and-latency-spike-investigation
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/selvarajmurugesan90/ops-engineering-skills.git /tmp/ops-engineering-skills
mkdir -p .claude/skills
cp -r /tmp/ops-engineering-skills/plugins/ai-agent/skills/agent-cost-and-latency-spike-investigation .claude/skills/agent-cost-and-latency-spike-investigation
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Agent Cost And Latency Spike Investigation в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Agent Cost And Latency Spike Investigation, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Agent Cost And Latency Spike Investigation не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Agent Cost and Latency Spike Investigation

Purpose

A sudden cost or latency spike in one agent workflow is an incident, not an optimization project — the goal in the first hours is to scope it, identify what changed, and stop the bleeding, not to redesign the pipeline. llm-cost-and-latency-optimization covers the deliberate, scheduled work of reducing baseline cost/latency across an agent (right-sizing models, caching, batching); this skill covers the narrower, time-pressured question that comes first: why did this one workflow suddenly get more expensive or slower than it was yesterday, and what's the fastest safe action to take. Confusing the two wastes the window where a quick rollback would have worked and instead launches a multi-day optimization effort under incident pressure.

When to use

  • A cost dashboard or billing alert shows a step-change increase for one agent/workflow/task type, not a gradual trend.
  • p50/p95 latency for one specific workflow doubles (or worse) compared to its recent baseline, while other workflows are unaffected.
  • An unexpected line item appears on an LLM provider invoice tied to a specific agent.
  • Before scheduling a full cost/latency optimization pass — this investigation determines whether there's an active regression to fix first, so the optimization pass starts from a correct baseline.
  • Deciding whether a spike is a regression (something broke) or legitimate growth (more users, more traffic) — these require entirely different responses.

Prerequisites & environment

  • Per-call token usage and latency logging, segmented by workflow/task type (not just a single aggregate metric) — if the spike can't be isolated to one workflow because everything rolls into one dashboard number, segmenting the metrics is itself the first prerequisite to fix.
  • A deploy/change log with timestamps: prompt edits, tool schema changes, model version or provider changes, retrieval index re-indexing runs, and infrastructure/routing changes — the single most useful artifact for this investigation is a timeline that can be laid next to the metrics timeline.
  • Request volume metrics alongside cost/latency, so a spike in absolute cost can be distinguished from a spike in cost-per-request.
  • Access to a recent-history transcript sample for the affected workflow (see agent-bad-response-triage-and-root-cause-classification for full-transcript capture practices) so the investigation isn't limited to aggregate numbers alone.

Step-by-step guidance

  1. Scope the blast radius first: one workflow, or everything? If cost or latency moved across all workflows and all providers simultaneously, this is more likely a provider-wide event (outage, pricing change, regional latency issue) than a workflow-specific regression — that's the domain of llm-gateway-and-multi-provider-routing (check provider status, confirm fallback routing triggered correctly) rather than this skill. Confirm the spike is actually isolated to one workflow before proceeding with a workflow-specific investigation.

  2. Pull time series for four signals side by side, not cost alone: request volume, tokens per request (input and output separately), tool-call count per request, and latency p50/p95. Overlay all four against the deploy/change timeline from day one.

    metric               yesterday   today      delta
    requests/hour        1,180       1,205      flat (+2%)
    avg input tokens/req    2,400      2,410      flat
    avg output tokens/req     310      1,850      +497%  <-- signal
    avg tool calls/req        2.1        2.1      flat
    p95 latency (ms)        1,850      6,200      +235%

    A table like this immediately narrows the search: flat volume and flat input tokens with a jump in output tokens and latency points at a generation-side change (prompt, output-format drift, or a model change), not a traffic or context-bloat problem.

  3. Apply the decision tree once the shape of the change is visible:

    • Volume up, per-request metrics flat → legitimate traffic growth, not a regression; this is a capacity/budget conversation, not an incident.
    • Volume flat, tokens-per-request up → likely context bloat (uncontrolled history growth, duplicated retrieved chunks) or a prompt/tool-description change — see prompt-and-context-engineering.
    • Volume flat, tool-call count per request up → likely a stalled or looping agent — see agent-tool-call-loop-diagnosis-and-circuit-breaking.
    • Latency up, tokens flat → likely a provider-side latency change, a model/region switch, or a downstream tool/dependency slowdown — see llm-gateway-and-multi-provider-routing.
    • Cost up, tokens flat → likely a pricing change, a model routing change (silently routed to a pricier model/tier), or a provider billing anomaly — verify against the routing config and provider invoice line items directly.
    • RAG-backed workflow, retrieval-stage metrics implicated → check whether a recent re-indexing job changed chunk count/size or duplicated content — see vector-database-ingestion-pipeline-for-rag and vector-database-operations-pinecone-weaviate-milvus for query-side cost/latency levers (over-retrieval, ef_search misconfiguration).
  4. Correlate against the change log directly, not just by shape of the metrics. Pull every prompt edit, tool schema change, model version bump, and re-indexing run within the window the spike started, ordered by timestamp — the metrics tell you what kind of change to look for, the change log tells you which specific change it was.

  5. Sample actual transcripts from the spike window, not just aggregates — three or four real requests showing exactly where the extra tokens or latency landed (a much longer generated answer, an extra retrieved chunk, a retried tool call) turn a statistical correlation into a confirmed cause.

  6. Quantify blast radius before deciding urgency: is this an ongoing, accumulating cost (every request now costs more) or a one-time event (a single bad batch job)? An ongoing per-request regression justifies an immediate stopgap even before full root-cause is confirmed; a one-time event mostly needs a retrospective, not urgent action.

  7. Apply the fastest safe stopgap, correlated to the identified change — usually a rollback, not a redesign. If a specific prompt edit, model version bump, or config change correlates cleanly with the spike's start time, reverting that specific change is almost always faster and safer than attempting a fix forward under time pressure.

    Warning: A stopgap fix applied directly to production without a tested rollback path (e.g. hand-editing a live prompt or routing config with no previous version saved) risks replacing one incident with another. Roll back to the last known-good, versioned configuration rather than improvising a new one under pressure — see agent-evaluation-and-guardrails for why an unvalidated forward-fix is riskier than a clean rollback.

  8. Hand off to the deliberate optimization pass once contained. Once the spike is stopped and root-caused, if the investigation also surfaces general inefficiency (not just the regression that caused the spike — e.g. "we've never right-sized the model for this step"), that becomes a scheduled task for llm-cost-and-latency-optimization, not something to solve inside this incident.

  9. Add a per-workflow cost/latency regression alert (not just an aggregate account-level billing alert) so the next spike in this specific workflow pages before a month-end invoice surprises anyone — thresholds should be relative to that workflow's own recent baseline, not a single global number.

Best practices

  • Segment cost and latency dashboards by workflow/task type from the start; an aggregate-only dashboard dilutes a severe single-workflow spike into an unremarkable overall trend.
  • Prefer a clean rollback to the last known-good configuration over a forward fix improvised during the incident — validate any forward fix against the eval suite before it replaces the rollback as the permanent solution.
  • Always check the four signals (volume, tokens, tool-call count, latency) together — cost and latency spikes frequently share a root cause but not always the same one, and treating them as one signal hides the distinction.
  • Sample real transcripts, not just aggregate metrics, before closing out the investigation — a statistical correlation with the change log is strong evidence but a confirmed transcript is proof.
  • Keep a running timeline of prompt/tool/model/index changes with timestamps as a standing artifact, not something reconstructed from memory during each incident.
  • Distinguish "legitimate traffic growth" from "regression" early and explicitly — treating growth as an incident wastes urgency budget, and treating a regression as growth delays the fix.

Common pitfalls

  • Symptom: The team immediately schedules a full model/architecture optimization review in response to a sudden spike, before checking whether a single recent change (a prompt edit, a model version bump) is the actual, fixable cause. Fix: Run this fast triage first — correlate against the change log and roll back the specific change if one correlates cleanly — before committing to a multi-day optimization effort that the eval suite and metrics may show was unnecessary.

  • Symptom: The investigation concludes "the model provider must have changed something" with no supporting evidence, because it's easier to blame an external, unverifiable cause than to check the team's own recent deploys. Fix: Check the internal change log (prompt, tool, model version, index) first — most spikes correlate with an internal change; only escalate to a suspected provider-side cause after internal causes are actively ruled out, and verify against the provider's own status page or release notes rather than assuming.

  • Symptom: An aggregate, account-wide cost dashboard shows only a minor overall uptick, masking a severe spike in one specific low-volume but now much more expensive workflow. Fix: Segment cost and latency metrics by workflow/task type as a standing practice, not only when an incident is already suspected — aggregate-only monitoring structurally cannot catch this class of spike early.

  • Symptom: A quick prompt or routing-config edit is pushed directly to production to stop the spike, with the previous version not saved anywhere, and a subsequent issue traced to that same hotfix has no clean rollback target. Fix: Always roll back to a previously versioned, known-good configuration rather than hand-editing production under pressure; treat configuration (prompts, routing rules, model pins) as version-controlled artifacts specifically so this rollback path always exists.

  • Symptom: The spike is correctly root-caused and fixed, but no workflow-specific alert is added, so an unrelated regression in the same workflow six weeks later isn't caught until the next invoice cycle. Fix: Add a per-workflow cost/latency regression alert with a threshold relative to that workflow's own recent baseline as a mandatory last step of every spike investigation, not an optional follow-up.

Worked example

Scenario: The contract-summarizer agent's average cost per request jumps from roughly $0.04 to $0.31 overnight, with total request volume essentially unchanged; the on-call engineer is asked to investigate before anyone commits to a redesign.

  1. Scope: Cost dashboards for two other agents sharing the same model provider show no change — confirmed isolated to contract-summarizer, ruling out a provider-wide event.
  2. Signal table:
    metric                yesterday   today     delta
    requests/hour              340        335    flat
    avg input tokens/req      6,100      6,050    flat
    avg output tokens/req       420      3,900    +828%
    avg tool calls/req            0          0    flat
    p95 latency (ms)          2,100      9,700    +362%
    Flat volume and input tokens, output tokens and latency both up sharply → generation-side change, not traffic or retrieval.
  3. Change log correlation: a prompt edit merged the previous evening changed the summarization instruction from "produce a 3-5 sentence summary" to "produce a comprehensive summary covering all material terms," removing the previous length constraint entirely.
  4. Transcript sample: three sampled requests confirm outputs went from ~5-sentence summaries to multi-page summaries restating most of the input contract.
  5. Blast radius: ongoing and accumulating — every request since the prompt merge costs roughly 7x more, not a one-time event, so an immediate stopgap is justified.
  6. Stopgap: the prompt is rolled back to the previous versioned revision (length constraint restored) rather than hand-editing a new instruction under pressure; cost per request returns to baseline within the hour.
  7. Follow-up: the intent behind the original edit (some users wanted more comprehensive summaries for complex contracts) is handed to llm-cost-and-latency-optimization and prompt-and-context-engineering as a deliberate follow-up: an explicit, length-bounded "detailed mode" evaluated against the eval suite for both quality and cost before shipping, rather than an unbounded prompt change pushed directly to everyone.
  8. A per-workflow alert is added: page if contract-summarizer avg output tokens/request exceeds 2x its 7-day rolling baseline.

Cross-references

Часто задаваемые вопросы

Что делает навык ИИ Agent Cost And Latency Spike Investigation?

Помогает быстро разобраться с внезапным скачком затрат или задержки в одном конкретном сценарии работы агента: определить его масштаб, сопоставить с недавними изменениями и применить быстрое безопасное временное решение — до начала полной оптимизации. Используйте этот навык, если пользователь спрашивает: «почему за ночь так вырос счет за LLM», «почему этот сценарий внезапно стал медленным/дорогим», просит «разобраться со скачком затрат/задержки» или сообщает о неожиданном предупреждении или счете для одного агента либо типа задач. Навык предназначен именно для таких случаев, а не для планов...

Зачем использовать Agent Cost And Latency Spike Investigation в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Agent Cost And Latency Spike Investigation — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Agent Cost And Latency Spike Investigation в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/selvarajmurugesan90/ops-engineering-skills/tree/main/plugins/ai-agent/skills/agent-cost-and-latency-spike-investigation. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Agent Cost And Latency Spike Investigation?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Agent Cost And Latency Spike Investigation?

С любым количеством. В TypingMind вы можете использовать Agent Cost And Latency Spike Investigation с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Agent Cost And Latency Spike Investigation?

Да. Навык опубликован на GitHub по лицензии Apache-2.0. Издатель — selvarajmurugesan90. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип openclaw

Openclaw Testing

openclaw
ОрганизацияПопулярный

Выбирайте подходящие по масштабу тесты и проверки OpenClaw, диагностируйте сбои и направляйте вопросы, зависящие от окружения, и подтверждение релиза ответственным за них специалистам.

82.2K
391K
Файлы: 2
Открыть
Логотип mattpocock

Wizard

mattpocock
СообществоПопулярный

Создаёт интерактивный сценарий на bash, который шаг за шагом проводит человека через действия, доступные только ему. Используйте его для подготовки инфраструктуры, настройки учётных данных или секретов CI, работы с незнакомой…

22.3K
264.4K
Файлы: 2
Открыть
Логотип affaan-m

Deployment Patterns

affaan-m
СообществоПопулярный

Процессы развертывания, паттерны CI/CD-пайплайнов, контейнеризация с Docker, проверки работоспособности, стратегии отката и контрольные списки готовности приложений…

39.1K
261.1K
Инструкции
Открыть
Логотип affaan-m

Docker Patterns

affaan-m
СообществоПопулярный

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

39.1K
261.1K
Инструкции
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇