# UsageTap ## Recommended first integration UsageTap Meter is the default onboarding product. Gateway and Compress are optional later products and must not be added unless the user explicitly requests them. Canonical reference: https://usagetap.com/llmreference Code integration and verification: https://usagetap.com/embed-api?features=meter API-key consistency: POST /call, /call_begin, /call_end and /custom_meter use fast index-based key authentication. Revoked/replaced keys and previous permissions may remain usable there until index propagation, with no promised maximum delay. Other durable-key requests recheck the current primary record and fail closed on verification failure. New/replacement key discovery, issued-session lifetimes and the internal verifier's permitted 30-second positive cache retain their existing behavior. API reference: https://usagetap.com/docs/API_REFERENCE SDK reference: https://usagetap.com/docs/SDK_REFERENCE Guard instrumentation and task attribution: https://usagetap.com/docs/GUARD_INTEGRATION Gateway request contract: https://usagetap.com/docs/LLM_GATEWAY Gateway request limits: Chat Completions and Responses (including streams) allow at most 1 MiB (1,048,576 bytes) of decoded UTF-8 JSON before compression; no fixed message/input-item count cap. Provider/model input, context and output limits still apply. Budget for every fallback model; upstream HTTP 400 input errors do not trigger fallback. Native batches have separate limits. Detection behavior and readiness: https://usagetap.com/docs/ANOMALY_DETECTION Public model lifecycle explorer: https://usagetap.com/model-lifecycle Public model replacement API: https://api.usagetap.com/v1/model-alternatives/{provider}/{model} Model Alternatives API reference: https://usagetap.com/docs/MODEL_ALTERNATIVES_API Model Alternatives OpenAPI 3.1: https://usagetap.com/openapi/model-alternatives.yaml Implementation facts: - Guard Settings provides separate Alert and Notification dropdowns per detector, each with Off, All, Major. All includes minor and major changes. Development is the default preset for organizations without saved detector settings: major behavioral alerts and notifications, with Environment mix Off. Production uses Alert: All and Notification: Major for every connected detector. Individual overrides show Custom; presets populate the existing controls and apply on Save. Existing saved preferences keep their behavior. Alert: Major keeps smaller or unclassified changes neutral in evidence/history, without warning icons, active findings or amber timeline emphasis. Alert: Off removes visual alerts while allowing opted-in notifications; both Off skips evaluation. Both levels are saved together in the existing detector preference. Notification: Off stops pending delivery; channel opt-in is still required. Meter recording and saved findings are preserved. The Production preset shows all supported changes; notifications default to major changes, with an optional all-supported-changes setting per detector. Major describes detector-specific change magnitude, not proven harm or confidence. Email and Slack still require explicit channel opt-in. A smaller change can notify when it first becomes major; settings do not reset history or create catch-up alerts. - API/custom-meter task-type mix reuses top-level taskType and actual consumed calls/units; update shares support batching investigation. Unspecified labels remain measurement context. One report is one sampling event. This compares reported consumption, not distinct/completed tasks or cost per task; taskId remains customer-scoped lookup identity. The application monitor adds no continuous customer/end-user or LLM task-type collection. - Guard monitors reported application behavior automatically for all organizations. Organization administrators can inspect evidence; offline detector preflight remains restricted to UsageTap platform administrators. Only R1 collection runs; R0 evaluation, historical initialization, configured Guard rules and incident handling are retired. Cache reuse, output/input, output size and API/custom-meter feature mix have population comparison adapters. Genuine calls/reports remain the sampling units; quantities do not invent independent calls. Applications automatically compare trailing two-hour populations using each detector's supported calendar history. The organization timezone is used, with an explicit UTC default. Same-weekday, weekday/weekend and daily references activate according to eligible support; sparse checks use labelled recent compatible history. Customers do not configure comparison policies. Dense calendar periods are reproducibly sampled without replacement, up to 256 observations per historical period and 4,096 current observations. Numeric comparisons use 512 observations per population within those caps, dividing the reference budget across periods to bound exact-test runtime. Periods below their allocated quota retain every observation. Categorical recent-history fallback can use the 4,096-observation reference budget. Full recorded counts, missingness and sampling support remain separate; samples can miss rare changes. Provisional sampling assumptions and a per-assessment statistical budget do not establish a daily or lifetime false-positive rate. No policy or insufficient/descriptive evidence is not health. Recorded cost-per-call distributions, reported completion reasons and denominator-based token/user/task coverage have comparison adapters. Missing historical measurements stay unknown. Token coverage and end-user attribution coverage measure eligible completed LLM calls; API/custom attribution coverage measures genuine reports. Historical LLM samples without the user-coverage measurement stay unknown; reporting an ID does not establish authorization or enable individual-user behavioral monitoring. Errors compares the recorded response-code distribution across eligible finalized successes, failures and timeouts, including shifts among successful codes; missing codes stay unknown. API call rate uses reported AGENTIC_API quantities over five-minute exposure with an explicit daily UTC reference. Batches do not reveal individual call times; missing/delayed windows remain unknown. Detector preflight replays saved offline cases. Application comparisons are enabled across organizations; customer detail is investigated on demand. Change and recovery notifications use the existing UsageTap Guard email/Slack opt-ins and shared destinations; neither channel is enabled automatically. Repeated changed windows do not repeat alerts. Recovery requires a completed no-change comparison and is sent only on a channel that received the change alert; quiet, unknown and unavailable evidence never establish recovery. There is no incident case-management workflow or automatic blocking. Task lookup and configured Meter enforcement remain separate. - Send customerId, stable feature, optional customerUserId, taskId and stable taskType at the top level of call_begin and custom_meter. Use one taskId per business operation across LLM/API/tool events; use distinct per-event idempotency keys. Task strings are trimmed, case-sensitive, 1-128 characters without controls. runId is SDK-local only. - Traffic environment: set server USAGETAP_ENVIRONMENT=production or test (SDK/observer), or UsageTapClient defaultEnvironment. Direct HTTP sends X-UsageTap-Environment on every UsageTap request including customers, begin/end, custom_meter and reads. Customer-panel Traffic group pins override request labels for new usage; Automatic restores request labels. Existing usage, active calls and retries retain their recorded group. Without a pin, omission stays unlabelled; do not infer from NODE_ENV or tags/metadata. Preserve labels across lifecycle/retries/workers; conflicts are rejected. Customers may have both labels. Filters do not isolate balances, make test traffic free, switch Stripe mode or partition customer signals. Page-level Environment filters group unlabelled usage with Production and keeps Dev/Test separate; API header filters still match exact recorded labels. Usage Forecast defaults to All traffic, offers Production, and does not offer Dev/Test-only forecasting. Guard behavioral checks always compare Production + unlabelled usage with matching retained history. Dev/Test is excluded from those checks. A separate environment-mix check uses all recorded traffic to detect substantial Dev/Test growth and share increases; it follows existing Guard notification opt-ins. There is no Dev/Test inclusion setting. Viewing filters do not change detection, and eligible retained history is reused without restarting learning. Verify emitted headers with a supporting release. - HTTP metadata.method/endpoint and MCP metadata.serverName/toolName label operations in Live View; tags and arbitrary metadata do not create Guard detector dimensions. Send safe route templates without query strings or private data. Report actual consumed units with consistent batching. - Verify installed wrapper task forwarding. Older builds may accept fields in types but omit them from call_begin; explicit withUsage/beginCall is the fallback until a fixed build is installed. - Existing Gateway integrations send top-level taskId and taskType on Chat Completions/Responses (including streams) or in each native batch item's body. Gateway validates and forwards them to call_begin and strips them before provider dispatch. Do not add a second LLM metering lifecycle. - Read one task using GET /usage/monitoring?customerId=...&taskId=... or MCP get_task_usage (usage:read). There is no SDK task-read method. Follow all nextToken pages; totalsScope is this_page and taskCompletion is not_reported. Keep LLM provider cost separate from meter charges; inspect missing-cost/open-call counts. Untagged history cannot be joined. - Guard scope reads without taskId (REST GET /usage/monitoring or MCP get_usage_monitoring) return scopes=[], nextToken=null, retired="r0". They do not initialize old history. Exact task lookup is unchanged. - For daily operational briefs, use MCP get_guard_summary (usage:read) alongside usage totals and get_customer_signals. Guard application behavioral findings are separate from customer signals and ordinary usage/cost anomalies. Defaults to trailing 24 hours; explicit inclusive startTime/exclusive endTime select a prior day converted to UTC (up to seven days within 56-day retention). Follow nextToken until null, merging finding groups by id; page comparison counts are overlapping comparisons, not incidents. Keep period findings/support counts separate from current readiness. Missing, quiet, stale, pending, disabled or insufficient evidence is not an all clear. Notification delivery is sent, skipped or unknown_or_pending per channel; reading never sends alerts or enables opt-ins. There is no SDK Guard-summary method. - Guard monitors reported application behavior automatically for all organizations. Organization administrators can inspect evidence; offline detector preflight remains restricted to UsageTap platform administrators. Only R1 collection runs; R0 evaluation, historical initialization, configured Guard rules and incident handling are retired. Cache reuse, output/input, output size and API/custom-meter feature mix have population comparison adapters. Genuine calls/reports remain the sampling units; quantities do not invent independent calls. Applications automatically compare trailing two-hour populations using each detector's supported calendar history. The organization timezone is used, with an explicit UTC default. Same-weekday, weekday/weekend and daily references activate according to eligible support; sparse checks use labelled recent compatible history. Customers do not configure comparison policies. Dense calendar periods are reproducibly sampled without replacement, up to 256 observations per historical period and 4,096 current observations. Numeric comparisons use 512 observations per population within those caps, dividing the reference budget across periods to bound exact-test runtime. Periods below their allocated quota retain every observation. Categorical recent-history fallback can use the 4,096-observation reference budget. Full recorded counts, missingness and sampling support remain separate; samples can miss rare changes. Provisional sampling assumptions and a per-assessment statistical budget do not establish a daily or lifetime false-positive rate. No policy or insufficient/descriptive evidence is not health. Recorded cost-per-call distributions, reported completion reasons and denominator-based token/user/task coverage have comparison adapters. Missing historical measurements stay unknown. Token coverage and end-user attribution coverage measure eligible completed LLM calls; API/custom attribution coverage measures genuine reports. Historical LLM samples without the user-coverage measurement stay unknown; reporting an ID does not establish authorization or enable individual-user behavioral monitoring. Errors compares the recorded response-code distribution across eligible finalized successes, failures and timeouts, including shifts among successful codes; missing codes stay unknown. API call rate uses reported AGENTIC_API quantities over five-minute exposure with an explicit daily UTC reference. Batches do not reveal individual call times; missing/delayed windows remain unknown. Detector preflight replays saved offline cases. Application comparisons are enabled across organizations; customer detail is investigated on demand. Change and recovery notifications use the existing UsageTap Guard email/Slack opt-ins and shared destinations; neither channel is enabled automatically. Repeated changed windows do not repeat alerts. Recovery requires a completed no-change comparison and is sent only on a channel that received the change alert; quiet, unknown and unavailable evidence never establish recovery. There is no incident case-management workflow or automatic blocking. Task lookup and configured Meter enforcement remain separate. - For HTTP API requests and MCP tool calls, use POST /custom_meter or incrementCustomMeter with meterSlot AGENTIC_API, a positive integer amount, and a stable idempotency key. Configure its allocation and overage pricing like a custom meter. Read https://usagetap.com/llmreference#agentic-api. - Agentic/API reports have no model, token, or tier fields. Inspect data.blocked for unfunded usage; the application enforces the flag. Reports do not reserve credit or impose a rolling limiter. The provider lifecycle facts below apply to LLM calls. - Use a server-side utk- key with usage:write as USAGETAP_API_KEY. - Keep the application's existing provider key and model. - Every authenticated direct API request sends Accept: application/vnd.usagetap.v1+json. - GET /v1/model-alternatives/{provider}/{model} is public, uses ordinary JSON, and needs no UsageTap account or API key. Add response=light for a compact real-time decision payload; response=full is the default inspection payload. The optional keyGuidance object identifies provider-verified aliases for the same model; recommendedModelKey is a separate upgrade or fallback decision. Provider equivalents are source-backed; cross-provider alternatives require workload evaluation. - Direct call_begin requests use one unique idempotencyKey per logical call and reuse it only for retries. - call_begin returns HTTP 200 for denied entitlements; inspect data.allowed before invoking the provider. A denied call is already finalized. - Report optional top-level completionReason at call_end/endCall from the primary finish_reason, stop_reason, or Responses incomplete_details.reason (otherwise terminal status such as completed). Omit unknown values; never infer from HTTP 200 or token counts. Values are trimmed, 1-128 characters, without control characters. Verify outgoing payloads with a supporting package release or direct HTTP. This does not change pricing/lifecycle. Guard can compare reported reason categories when sufficient eligible data is available. - Finalize successful calls with actual provider model and usage. Finalize provider failures with error: { code, message }. - Do not send secrets, prompts, or raw provider response bodies in error metadata. - For a read-only account brief, call GET /customers/{customerId}/usage-context or the MCP tool get_customer_usage_context with the exact external customer ID. Both require customers:read and usage:read. Check evidence.complete, component statuses, forecast quality, units, and inclusive-start/exclusive-end periods. - Included allowance exhaustion does not necessarily mean service interruption. PAYG funding, purchased meter credit, or another configured policy may allow usage to continue. The account brief recommends human review and never changes a plan or contacts a customer. ## Copyable coding-agent prompt Implement UsageTap Meter in this repository. For requested daily operational briefs, use MCP get_guard_summary with usage:read alongside usage totals and get_customer_signals. Guard is application behavioral monitoring, separate from customer signals and ordinary usage/cost anomalies. It defaults to the last 24 hours; explicit inclusive startTime and exclusive endTime select a prior day converted to UTC (up to seven days within 56-day retention). Follow nextToken until null and merge finding groups by id; overlapping comparisons are not independent incidents. Keep period findings and saved comparison support counts separate from current readiness. Missing, quiet, stale, pending, disabled or insufficient evidence is not an all clear. Notification email/Slack delivery is sent, skipped or unknown_or_pending; reading does not send alerts or enable opt-ins. There is no SDK Guard-summary method. POST /call, /call_begin, /call_end and /custom_meter use fast index-based key authentication. Revoked/replaced keys and previous permissions may remain usable there until index propagation, with no promised maximum delay. Other durable-key requests recheck the current primary record and fail closed on verification failure. New/replacement key discovery, issued-session lifetimes and the internal verifier's permitted 30-second positive cache retain their existing behavior. Read https://usagetap.com/llmreference first and treat it as the canonical contract. The initial goal is Meter only. Do not add UsageTap Gateway, UsageTap Compress, prompt compression, provider migration, model changes, or Stripe synchronization unless I explicitly ask. If this application already uses UsageTap Gateway, extend its existing requests instead of adding a second LLM metering lifecycle. Read https://usagetap.com/docs/LLM_GATEWAY. Send top-level taskId and taskType on Chat Completions/Responses requests, including streams, or in each native batch item's body. Gateway validates these fields, forwards them to call_begin, and removes them before provider dispatch. Start by wrapping the application's existing LLM calls. New UsageTap workspaces receive a Metering plan with unlimited calls and output tokens and no plan quota blocking. Existing workspaces retain their configured plans; do not overwrite them or bypass their enforcement. Pricing tiers, limiting, and usage widgets are optional follow-up work, not prerequisites for a new workspace's first metered call. When the requested target is HTTP API requests or MCP tool calls, use the dedicated Agentic & API Calls meter: POST /custom_meter or incrementCustomMeter with meterSlot AGENTIC_API and a positive integer amount. Read https://usagetap.com/llmreference#agentic-api. Configure the allocation, eligible purchased credits, PAYG funding and single or graduated prices just like a custom meter. Report completed usage with a stable idempotency key; inspect data.blocked and enforce it in the application. This reporting API does not reserve credit or impose rolling rate limits. Skip the provider-specific lifecycle, model and token steps below for this target; those steps apply only to LLM usage. Read https://usagetap.com/docs/GUARD_INTEGRATION to make recorded usage useful for Guard. Send stable customerId and feature plus optional customerUserId, taskId, and stable taskType as top-level fields on call_begin and meter reports. Propagate one operation's taskId across LLM calls, tools, and workers, with separate idempotency keys for each event. runId is SDK-local circuit-breaker state, not remote task attribution. Verify installed wrapper transport because older SDK builds may accept task fields in types but omit them. Use explicit withUsage/beginCall until a fixed build is available. For HTTP labels send sanitized metadata.method/endpoint; for MCP send metadata.toolName and optional serverName. Arbitrary metadata/tags are not additional Guard detector dimensions. API/custom-meter task-type mix compares reported consumption shares, with update shares supporting batching investigation; unspecified taskType remains measurement context. It does not count distinct/completed tasks or create taskId baselines. Report real consumed units and keep batching consistent; one report is not necessarily one consumed call. Preserve actual total input/output, cache subsets, provider/model, and known pricing/reasoning settings; omit unknown usage rather than inventing zeros. Verify linked usage with GET /usage/monitoring?customerId=...&taskId=... or MCP get_task_usage using usage:read. No SDK task-read method exists. Follow every nextToken; totals cover each page only. Report missing-cost/open-call counts and keep LLM cost separate from commercial meter charges. Task completion and cost per completed task are not inferred. Guard monitors reported application behavior automatically for all organizations. Organization administrators can inspect evidence; offline detector preflight remains restricted to UsageTap platform administrators. Only R1 collection runs; R0 evaluation, historical initialization, configured Guard rules and incident handling are retired. Cache reuse, output/input, output size and API/custom-meter feature mix have population comparison adapters. Genuine calls/reports remain the sampling units; quantities do not invent independent calls. Applications automatically compare trailing two-hour populations using each detector's supported calendar history. The organization timezone is used, with an explicit UTC default. Same-weekday, weekday/weekend and daily references activate according to eligible support; sparse checks use labelled recent compatible history. Customers do not configure comparison policies. Dense calendar periods are reproducibly sampled without replacement, up to 256 observations per historical period and 4,096 current observations. Numeric comparisons use 512 observations per population within those caps, dividing the reference budget across periods to bound exact-test runtime. Periods below their allocated quota retain every observation. Categorical recent-history fallback can use the 4,096-observation reference budget. Full recorded counts, missingness and sampling support remain separate; samples can miss rare changes. Provisional sampling assumptions and a per-assessment statistical budget do not establish a daily or lifetime false-positive rate. No policy or insufficient/descriptive evidence is not health. Recorded cost-per-call distributions, reported completion reasons and denominator-based token/user/task coverage have comparison adapters. Missing historical measurements stay unknown. Token coverage and end-user attribution coverage measure eligible completed LLM calls; API/custom attribution coverage measures genuine reports. Historical LLM samples without the user-coverage measurement stay unknown; reporting an ID does not establish authorization or enable individual-user behavioral monitoring. Errors compares the recorded response-code distribution across eligible finalized successes, failures and timeouts, including shifts among successful codes; missing codes stay unknown. API call rate uses reported AGENTIC_API quantities over five-minute exposure with an explicit daily UTC reference. Batches do not reveal individual call times; missing/delayed windows remain unknown. Detector preflight replays saved offline cases. Application comparisons are enabled across organizations; customer detail is investigated on demand. Change and recovery notifications use the existing UsageTap Guard email/Slack opt-ins and shared destinations; neither channel is enabled automatically. Guard Settings provides separate Alert and Notification dropdowns per detector, each with Off, All, Major. All includes minor and major changes. Development is the default preset for organizations without saved detector settings: major behavioral alerts and notifications, with Environment mix Off. Production uses Alert: All and Notification: Major for every connected detector. Individual overrides show Custom; presets populate the existing controls and apply on Save. Existing saved preferences keep their behavior. Alert: Major keeps smaller or unclassified changes neutral in evidence/history, without warning icons, active findings or amber timeline emphasis. Alert: Off removes visual alerts while allowing opted-in notifications; both Off skips evaluation. Both levels are saved together in the existing detector preference. Notification: Off stops pending delivery; channel opt-in is still required. Meter recording and saved findings are preserved. The Production preset shows all supported changes; notifications default to major changes, with an optional all-supported-changes setting per detector. Major means detector-specific change magnitude, not proven harm or confidence. A smaller change can notify when it first becomes major. Repeated changed windows do not repeat alerts. Recovery requires a completed no-change comparison and is sent only on a channel that received the change alert; quiet, unknown and unavailable evidence never establish recovery. There is no incident case-management workflow or automatic blocking. Task lookup and configured Meter enforcement remain separate. Do not change plans or notification preferences unless requested. In the application, use Meter → Guard → Dashboard or Live View → Guard for detector status, active findings and compact history. Findings retains earlier changes, expandable evidence and recorded task lookup. Integration guide opens the instrumentation instructions; Email / Slack notifications opens the existing notification settings. Enable UsageTap Guard changes and recovery only when requested. Notification destinations are shared with other admin alerts. Set USAGETAP_ENVIRONMENT=production or test in the server deployment, or configure UsageTapClient defaultEnvironment. SDK and observer read that variable; direct HTTP must send X-UsageTap-Environment on every UsageTap request, including customer creation, reads/updates, call_begin/end and custom_meter. Do not send it to provider requests, infer from NODE_ENV, or hide it in metadata/tags. A customer-panel Traffic group pin overrides request labels for new usage. Respect it and do not change admin groups unless asked. Automatic restores request labels; without a pin, omission stays unlabelled. Existing usage, active calls and retries keep their recorded group. Preserve the label across retries and workers; explicit lifecycle conflicts are rejected. Verify outgoing headers and stored labels with a supporting SDK release. One customer ID can have both labels. Filters do not create separate allowances, change Stripe mode, make test traffic free, or partition customer signals. Page-level Environment filters group unlabelled usage with Production and keeps Dev/Test separate; API header filters still match exact recorded labels. Usage Forecast defaults to All traffic, offers Production, and does not offer Dev/Test-only forecasting. Guard behavioral checks always compare Production + unlabelled usage with matching retained history. Dev/Test is excluded from those checks. A separate environment-mix check uses all recorded traffic to detect substantial Dev/Test growth and share increases; it follows existing Guard notification opt-ins. There is no Dev/Test inclusion setting. Viewing filters do not change detection, and eligible retained history is reused without restarting learning. Work autonomously: 1. Inspect the repository to find every server-side AI/provider call, the framework/runtime, existing provider SDKs, streaming behavior, tests, environment-variable conventions, and the trusted authenticated customer or tenant ID. 2. Choose the smallest safe integration. Prefer @usagetap/sdk for supported server-side JavaScript/TypeScript provider clients. Use the explicit SDK lifecycle when BLOCK or DOWNGRADE must control provider invocation or model selection; provider wrappers do not invent a safe fallback model. Use direct HTTPS for other languages or when the SDK is not a safe fit. Preserve the existing provider, model, request/response shape, and error behavior. 3. Ask one concise clarification only if a stable server-trusted customerId cannot be inferred or there are multiple materially different integration targets. Otherwise proceed. 4. Report optional top-level completionReason at call_end/endCall from the primary provider finish_reason, stop_reason, or Responses incomplete_details.reason (otherwise terminal status such as completed). Omit unknown values; never infer from HTTP 200 or token counts. Use a supporting package release or direct HTTP, and verify the outgoing payload. Values are trimmed, 1-128 characters, without control characters. This does not change pricing/lifecycle. Guard can compare reported reason categories when sufficient eligible data is available. Implement the complete Meter lifecycle. Attribute every call to a stable customerId and feature; begin before provider work; inspect data.allowed before invoking the provider; do not end a denied call because call_begin already finalized it; finalize an allowed call exactly once on success, error, stream completion, cancellation, or abort; report the actual model and usage returned by the provider; sanitize error metadata; and use one unique idempotency key per logical call, reused only for its retries. 5. Keep all credentials server-side. Never read, print, log, or commit secret values. Add placeholders only to the project's example environment file. UsageTap Meter needs USAGETAP_API_KEY (create a utk-… key with usage:write at https://usagetap.com/configure#api-keys). Keep the app's existing provider key such as OPENAI_API_KEY, ANTHROPIC_API_KEY, or OPENROUTER_API_KEY. 6. Add or update focused tests and run the relevant test, lint, and type/build checks. If credentials are unavailable, finish and verify the code without attempting a live provider request. When done, report: - what you changed and which calls are now metered; - the exact environment-variable names the user must set, without values; - any one remaining user decision or action; - the command or request that produces the first metered call; - how to watch it in Live View at https://usagetap.com/live and find the completed request in recent calls at https://usagetap.com/dashboard#recent-calls; - the integration guide at https://usagetap.com/embed-api?features=meter if setup needs attention; - optional next steps in Control Center at https://usagetap.com/dashboard?tab=system. The first successful metered call completes the initial setup. Do not stop at a plan or code sample. Make the changes when it is safe to do so.