> ## Documentation Index
> Fetch the complete documentation index at: https://docs.opper.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Count Tokens

> Anthropic Messages token-counting compatible endpoint. Returns the number of input tokens a Messages request would consume, without creating a message. Mirrors Anthropic's POST /v1/messages/count_tokens (same request body as the Messages endpoint, minus the required max_tokens).

The model resolves exactly as it does on the Messages endpoint, so every model a message accepts can be counted, and one a message would reject fails the same way (404 for an unknown model, 403 for one the allowlist or an entitlement denies). Claude models are counted exactly by their own backend, in the model's region. Every other model, and a dynamic route, gets Opper's estimate in the same shape: characters / 4 over the system prompt, messages and tool declarations, plus 1 (within about 20% on English prose), with a flat amount per image and 3,000 tokens per PDF page. The `X-Opper-Count-Source` response header says which.



## OpenAPI

````yaml post /v3/compat/v1/messages/count_tokens
openapi: 3.1.0
info:
  description: Schema-driven generative API that orchestrates LLM-powered workflows.
  title: Task API
  version: 3.0.0
servers:
  - description: Production
    url: https://api.opper.ai
  - description: Local development
    url: http://localhost:8080
security:
  - BearerAuth: []
tags:
  - description: OpenAI-compatible chat completions
    name: Chat
  - description: OpenAI Responses API compatible endpoint
    name: Responses
  - description: Google-compatible interactions endpoint
    name: Interactions
  - description: Model registry and capabilities
    name: Models
  - description: Synchronous image generation
    name: Images
  - description: Text-to-speech and speech-to-text
    name: Audio
  - description: Asynchronous video generation
    name: Videos
  - description: Realtime WebSocket sessions and their ephemeral tickets
    name: Realtime
  - description: Many requests on a provider's batch API at the batch price
    name: Batches
  - description: Reusable file storage for media inputs and generated outputs
    name: Files
  - description: Async generation status and downloads
    name: Artifacts
  - description: >-
      Signed completion webhooks for async jobs, and the project secret that
      signs them
    name: Webhooks
  - description: OpenAI-compatible embeddings
    name: Embeddings
  - description: Recorded HTTP request/response generations
    name: Generations
  - description: System health and status
    name: System
  - description: Roundtable endpoint — fan out a query to multiple LLMs and combine results
    name: Roundtable
  - description: Web search, fetch, and other utility tools
    name: Tools
  - description: Caller identity, credits, and usage
    name: Account
  - description: >-
      Programmatic project and API-key management. Authenticates with an
      `op-mak-…` management token; available on the control_plane and enterprise
      plans.
    name: Management
paths:
  /v3/compat/v1/messages/count_tokens:
    post:
      tags:
        - Compatibility
      summary: Count Message tokens
      description: >-
        Anthropic Messages token-counting compatible endpoint. Returns the
        number of input tokens a Messages request would consume, without
        creating a message. Mirrors Anthropic's POST /v1/messages/count_tokens
        (same request body as the Messages endpoint, minus the required
        max_tokens).


        The model resolves exactly as it does on the Messages endpoint, so every
        model a message accepts can be counted, and one a message would reject
        fails the same way (404 for an unknown model, 403 for one the allowlist
        or an entitlement denies). Claude models are counted exactly by their
        own backend, in the model's region. Every other model, and a dynamic
        route, gets Opper's estimate in the same shape: characters / 4 over the
        system prompt, messages and tool declarations, plus 1 (within about 20%
        on English prose), with a flat amount per image and 3,000 tokens per PDF
        page. The `X-Opper-Count-Source` response header says which.
      operationId: countMessageTokens
      parameters:
        - description: >-
            Names the call. The model span takes this name, and so does the
            trace when that span is its root. Up to 256 bytes.
          in: header
          name: X-Opper-Name
          schema:
            type: string
        - description: Parent span ID for distributed tracing context.
          in: header
          name: X-Opper-Parent-Span-Id
          schema:
            format: uuid
            type: string
        - description: >-
            Comma-separated `key:value` usage-attribution tags (e.g.
            `tenant:acme,project:demo`, max 8). Recorded on the generation's
            billing/metrics rows; group spend by any key via GET
            /v2/analytics/usage?group_by=<key>. Header-borne twin of the
            /v3/session URL prefix tags (which win per key when both are
            present); `opper.`-prefixed keys and `session_id` are reserved.
            Malformed values return 400.
          in: header
          name: X-Opper-Tags
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MessagesRequest'
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                additionalProperties: false
                properties:
                  input_tokens:
                    description: The number of input tokens the request would consume.
                    type: integer
                required:
                  - input_tokens
                type: object
          description: Successful response
          headers:
            X-Opper-Count-Source:
              description: >-
                Where `input_tokens` came from: `provider` when the model's
                provider counted it exactly, `estimate` when it is Opper's
                estimate.
              schema:
                enum:
                  - provider
                  - estimate
                type: string
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
          description: Bad request
        '401':
          description: Unauthorized - missing or invalid API key
        '500':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
          description: Internal server error
components:
  schemas:
    MessagesRequest:
      properties:
        cache_control:
          description: >-
            Opt in to top-level automatic prompt caching: {"type":"ephemeral"}
            (optionally "ttl":"1h"). Places one moving breakpoint on the largest
            cacheable prefix. Explicit per-block cache_control on
            system/message/tool content takes precedence. Caching is off unless
            set. Cache writes cost 1.25x input and reads 0.1x
          type: object
        max_tokens:
          type: integer
        messages:
          items:
            properties:
              content:
                description: Any value
              role:
                type: string
            required:
              - role
              - content
            type: object
          type: array
        metadata:
          type: object
        model:
          type: string
        models:
          description: >-
            Fallback models tried in order when the model before them fails for
            any reason (provider error; rate limit; timeout; a member blocked by
            one of your rules). Same OpenRouter shape: send the primary in model
            and the rest here; or omit model and the first entry is the primary.
            Each entry is any model string: a bare pooled name; a provider/model
            id; an org alias. Not allowed together with a dynamic/<name> route.
            At most 10 entries. Which model answered is in the
            X-Opper-Served-Model header; the model field still echoes what you
            sent.
          items:
            type: string
          type: array
        output_config:
          description: >-
            Output configuration. A format of {"type":"json_schema" +
            "schema":{...}} constrains the response to that JSON Schema. An
            effort of low|medium|high sets adaptive-thinking effort. Sending a
            format here and a top-level output_format is a 400.
          type: object
        output_format:
          description: >-
            Structured output; superseded by output_config.format. Accepts
            either the Messages API shape ({"type":"json_schema" +
            "schema":{...}}) or the OpenAI-style envelope ({"type":"json_schema"
            + "json_schema":{"name":... + "schema":{...}}}).
          type: object
        service_tier:
          description: >-
            Processing tier. Anthropic values auto and standard_only run at the
            default tier; the OpenAI names flex; priority (alias fast) and
            ultrafast and Opper's economy pick that tier where the model has an
            endpoint for it. The tier that ran is in the
            X-Opper-Served-Service-Tier header.
          type: string
        speed:
          description: >-
            fast asks for Anthropic fast mode (the priority tier; premium price)
            where the model has an endpoint for it; standard or empty is the
            default tier.
          type: string
        stop_sequences:
          items:
            type: string
          type: array
        stream:
          type: boolean
        system:
          description: Any value
        temperature:
          type: number
        thinking:
          description: Any value
        tool_choice:
          description: Any value
        tools:
          items:
            properties:
              cache_control:
                type: object
              description:
                type: string
              input_schema:
                type: object
              name:
                type: string
              type:
                type: string
            required:
              - name
            type: object
          type: array
        top_k:
          type: integer
        top_p:
          type: number
      required:
        - model
        - messages
        - max_tokens
      type: object
    ErrorResponse:
      properties:
        error:
          properties:
            code:
              type: string
            details:
              description: Any value
            message:
              type: string
          required:
            - code
            - message
          type: object
        meta:
          type: object
      required:
        - error
      type: object
  securitySchemes:
    BearerAuth:
      bearerFormat: API Key
      description: API key authentication. Pass your API key as a Bearer token.
      scheme: bearer
      type: http

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.