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

# Buscar no histórico

> Busca por palavra e por significado no histórico de um cliente, com recorrência calculada.



## OpenAPI

````yaml openapi/pt/cell.json POST /v1/history/search
openapi: 3.1.0
info:
  title: API de dados da Niadra
  version: '1'
  description: >-
    Escrita, contexto, histórico, objetos, identidade, privacidade e governança
    de um espaço. Cada espaço tem um endereço estável, com o espaço e a região
    no nome.
servers:
  - url: https://{space}.{region}.api.niadra.com
    variables:
      space:
        default: acme-prod
        description: O espaço, que vem na chave de fonte.
      region:
        default: us-east-1
        description: A região do espaço, que também vem na chave.
security: []
paths:
  /v1/history/search:
    post:
      tags:
        - read
      summary: Buscar no histórico
      description: >-
        Busca por palavra (BM25) e por significado, restrita a um perfil e
        fundida por posição. Cobre episódios, fatos, pendências, eventos de
        sistema, ações, objetos e padrões. O bloco `recurrence` conta quantas
        vezes a mesma categoria aconteceu. Mesma política, mesmo nível de
        verificação e mesmo comprovante do contexto. Menos de 200 ms.


        **Autenticação.** Chave de fonte: `Authorization: Bearer nia_sk_...`.
        Escopo exigido: `search`.
      operationId: search_v1_history_search_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SearchRequest'
            example:
              subject:
                type: phone_e164
                value: '+14155550123'
              query: credit for missed technician visit
              max_tokens: 300
              verification: V1
              conversation_id: call-4471
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchResponse'
              example:
                items:
                  - id: ep_01J2
                    kind: episode
                    text: >-
                      Technician did not show up · $40 credit on the April bill
                      · settled
                    at: '2026-03-12T14:20:00Z'
                    channel: voice
                    source_id: src_voice
                    outcome: resolved
                    confidence: 0.94
                    origin_event_id: evt_01J2A
                  - id: ep_01J3
                    kind: episode
                    text: Customer confirmed the credit and the new visit
                    at: '2026-03-14T12:02:00Z'
                    channel: whatsapp
                    source_id: src_whatsapp
                    outcome: resolved
                    confidence: 0.91
                    origin_event_id: evt_01J3C
                recurrence:
                  category: technician_visit
                  occurrences: 2
                  window_days: 365
                  last_at: '2026-03-12T14:20:00Z'
                  last_outcome: resolved
                  last_resolution: $40 credit
                withheld: 0
                as_of: '2026-09-22T17:07:02Z'
                tokens_used: 61
                degraded: null
          description: Os itens encontrados, cortados por valor até `max_tokens`.
        '422':
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
          description: >-
            422 `invalid_input`, `verification_not_allowed` ou
            `about_without_link`.
      security:
        - sourceKey: []
      x-codeSamples:
        - lang: python
          label: Python
          source: |-
            result = niadra.search(
                phone("+14155550123"),
                "credit for missed technician visit",
                max_tokens=300,
                conversation_id="call-4471",
                voice=True,
            )

            if result.recurrence:
                print(result.recurrence.occurrences, result.recurrence.last_resolution)
        - lang: typescript
          label: TypeScript
          source: |-
            const { data } = await niadra.search({
              subject: handles.phone("+14155550123"),
              query: "credit for missed technician visit",
              max_tokens: 300,
              conversation_id: "call-4471",
            });

            if (data?.recurrence) {
              console.log(data.recurrence.occurrences, data.recurrence.last_resolution);
            }
components:
  schemas:
    SearchRequest:
      additionalProperties: false
      properties:
        about:
          anyOf:
            - $ref: '#/components/schemas/Handle'
            - type: 'null'
        conversation_id:
          anyOf:
            - maxLength: 512
              minLength: 1
              type: string
            - type: 'null'
          title: Conversation Id
        filters:
          $ref: '#/components/schemas/HistoryFilters'
        max_tokens:
          default: 800
          maximum: 4000
          minimum: 50
          title: Max Tokens
          type: integer
          description: >-
            Orçamento da resposta. Os itens são cortados por valor, nunca pela
            ordem de chegada. Use 300 na voz.
        query:
          maxLength: 2000
          minLength: 1
          title: Query
          type: string
          description: Linguagem natural ou palavras-chave.
        subject:
          $ref: '#/components/schemas/Handle'
        task_id:
          anyOf:
            - maxLength: 512
              minLength: 1
              type: string
            - type: 'null'
          title: Task Id
        verification:
          $ref: '#/components/schemas/Verification'
          default: V0
      required:
        - subject
        - query
      title: SearchRequest
      type: object
    SearchResponse:
      additionalProperties: false
      properties:
        as_of:
          anyOf:
            - format: date-time
              type: string
            - type: 'null'
          title: As Of
        degraded:
          anyOf:
            - type: string
            - type: 'null'
          description: >-
            `text_only` quando a busca por significado não estava disponível e
            só a busca por palavra rodou.
          title: Degraded
        items:
          items:
            $ref: '#/components/schemas/HistoryItem'
          title: Items
          type: array
        recurrence:
          anyOf:
            - $ref: '#/components/schemas/Recurrence'
            - type: 'null'
        tokens_used:
          title: Tokens Used
          type: integer
        withheld:
          default: 0
          title: Withheld
          type: integer
      required:
        - items
        - tokens_used
      title: SearchResponse
      type: object
    Problem:
      additionalProperties: false
      description: >-
        Detalhes do problema no formato da RFC 9457; `code` vem do catálogo de
        erros versionado.
      properties:
        code:
          title: Code
          type: string
        detail:
          anyOf:
            - type: string
            - type: 'null'
          default: null
          title: Detail
        request_id:
          anyOf:
            - type: string
            - type: 'null'
          default: null
          title: Request Id
        status:
          title: Status
          type: integer
        title:
          title: Title
          type: string
        type:
          default: about:blank
          title: Type
          type: string
      required:
        - title
        - status
        - code
      title: Problem
      type: object
    Handle:
      additionalProperties: false
      description: >-
        Um identificador de um sujeito num canal ou sistema: um telefone, um
        e-mail, um id do CRM.
      properties:
        scope:
          anyOf:
            - maxLength: 256
              minLength: 1
              type: string
            - type: 'null'
          description: >-
            Espaço de nomes dos identificadores com escopo: a conta do WhatsApp
            Business para `wa_bsuid`, o sistema para `system_id`, o país para
            `gov_id_hmac`.
          title: Scope
        subject_kind:
          anyOf:
            - $ref: '#/components/schemas/SubjectKind'
            - type: 'null'
          description: >-
            O padrão é `person`, exceto nos tipos de handle que só identificam
            organizações.
        type:
          $ref: '#/components/schemas/HandleType'
        value:
          maxLength: 320
          minLength: 1
          title: Value
          type: string
          description: >-
            O identificador. Normalizado no servidor: E.164 para telefone,
            minúsculas para e-mail.
      required:
        - type
        - value
      title: Handle
      type: object
    HistoryFilters:
      additionalProperties: false
      properties:
        categories:
          items:
            maxLength: 256
            minLength: 1
            type: string
          title: Categories
          type: array
        channels:
          items:
            maxLength: 256
            minLength: 1
            type: string
          title: Channels
          type: array
        item_kinds:
          items:
            enum:
              - episode
              - fact
              - open_item
              - action
              - system_event
              - object
              - trait
            type: string
          title: Item Kinds
          type: array
        object:
          anyOf:
            - $ref: '#/components/schemas/ObjectRef'
            - type: 'null'
        outcome:
          anyOf:
            - maxLength: 256
              minLength: 1
              type: string
            - type: 'null'
          title: Outcome
        since:
          anyOf:
            - format: date-time
              type: string
            - type: 'null'
          title: Since
        until:
          anyOf:
            - format: date-time
              type: string
            - type: 'null'
          title: Until
      title: HistoryFilters
      type: object
    Verification:
      description: >-
        Nível de verificação da sessão. V0 autodeclarado, V1 plausível pelo
        canal, V2 atestado pelo canal, V3 desafiado (OTP ou login), V4 conferido
        com um sistema de registro ou por um atendente. `no_customer` vale para
        tarefas sem cliente presente e só é aceito de fontes de agente interno.
      enum:
        - V0
        - V1
        - V2
        - V3
        - V4
        - no_customer
      title: Verification
      type: string
    HistoryItem:
      additionalProperties: false
      properties:
        at:
          format: date-time
          title: At
          type: string
        channel:
          anyOf:
            - type: string
            - type: 'null'
          title: Channel
        confidence:
          anyOf:
            - type: number
            - type: 'null'
          title: Confidence
        id:
          title: Id
          type: string
        kind:
          title: Kind
          type: string
          description: >-
            Um de `episode`, `fact`, `open_item`, `action`, `system_event`,
            `object`, `trait`.
        origin_event_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Origin Event Id
          description: O evento de onde este item veio.
        outcome:
          anyOf:
            - type: string
            - type: 'null'
          title: Outcome
        source_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Source Id
        text:
          title: Text
          type: string
          description: Texto denso, no mesmo estilo chave e valor do contexto.
      required:
        - id
        - kind
        - text
        - at
      title: HistoryItem
      type: object
    Recurrence:
      additionalProperties: false
      properties:
        category:
          title: Category
          type: string
        last_at:
          anyOf:
            - format: date-time
              type: string
            - type: 'null'
          title: Last At
        last_outcome:
          anyOf:
            - type: string
            - type: 'null'
          title: Last Outcome
        last_resolution:
          anyOf:
            - type: string
            - type: 'null'
          title: Last Resolution
        occurrences:
          title: Occurrences
          type: integer
        window_days:
          title: Window Days
          type: integer
      required:
        - category
        - occurrences
        - window_days
      title: Recurrence
      type: object
      description: >-
        Quantas vezes isso aconteceu, contado sobre episódios tipados. Uma
        contagem, não um palpite.
    SubjectKind:
      enum:
        - person
        - account
        - partner
      title: SubjectKind
      type: string
      description: >-
        Uma pessoa, uma organização cliente (`account`) ou uma organização que
        participa sem ser cliente (`partner`).
    HandleType:
      enum:
        - phone_e164
        - wa_id
        - wa_jid
        - wa_lid
        - wa_bsuid
        - email
        - gov_id_hmac
        - app_user_id
        - system_id
        - org_registry_hmac
        - email_domain
        - anon_id
      title: HandleType
      type: string
      description: >-
        O tipo de identificador. O valor é classificado pelo formato, nunca pelo
        campo de onde veio.
    ObjectRef:
      additionalProperties: false
      description: Um objeto de negócio num sistema de registro.
      properties:
        id:
          maxLength: 512
          minLength: 1
          title: Id
          type: string
          description: O id nesse sistema.
        namespace:
          maxLength: 256
          minLength: 1
          title: Namespace
          type: string
          description: O sistema onde ele vive, como `erp`.
        type:
          maxLength: 256
          minLength: 1
          title: Type
          type: string
          description: Tipo do objeto, como `invoice`, `order` ou `ticket`.
      required:
        - type
        - namespace
        - id
      title: ObjectRef
      type: object
  securitySchemes:
    sourceKey:
      type: http
      scheme: bearer
      description: nia_sk_...

````