AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring the Humata API for Automated Document Q&A and Exact Page Citations

Caitlin Millman · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

For software engineers building enterprise intranets, legal contract review pipelines, or customer support ticketing systems, manual document ingestion through the Humata web UI is a non-starter. Manually dragging PDFs into a browser and copying generated summaries fails modern compliance standards, creates operational bottlenecks, and eliminates end-to-end auditability.

Humata provides an official REST API that automates this workflow: programmatically ingesting internal PDFs via secure presigned storage URLs, polling asynchronous vectorization jobs, spinning up multi-document conversation sessions, and streaming answers with exact page citations back to internal interfaces.

At 365Finds, our institutional judgment is straightforward: Humata is an exceptionally fast path to deploying auditable, citation-backed document retrieval into internal tools, provided you configure its retrieval mode to Grounded and wrap its URL-based ingestion in a robust asynchronous polling worker. However, engineering teams must account for two deliberate architectural constraints: Humata requires URL-accessible file endpoints rather than raw binary streaming uploads, and its exact page references arrive embedded within the streaming text response rather than as a separated JSON metadata payload.

Below is the complete engineering guide to architecting, configuring, and deploying an end-to-end automated Q&A pipeline using the Humata API.


Architecture Overview: From Object Store to Cited Answer

Integrating Humata into an enterprise application involves a five-stage pipeline:

[Internal Storage: S3 / GCS / Azure]
         │ (1) Generate short-lived presigned URL
         ▼
[Humata Ingestion: POST /api/v2/import-url] ──► Returns document UUID
         │
         ▼
[Ingestion Poller: GET /api/v1/pdf/{pdf-id}] ──► Poll until read_status == "SUCCESS"
         │
         ▼
[Session Manager: POST /api/v1/conversations] ──► Group documentIds into conversationId
         │
         ▼
[Grounded Q&A: POST /api/v1/ask] ──► Stream SSE chunks (data: {'content': ...})
         │
         ▼
[Client App Parser] ──► Extract inline markers [N] & page numbers ──► Deep-link to internal PDF viewer

Key Endpoint Specifications

EndpointHTTP MethodPrimary PurposeKey Parameters / Payload
https://app.humata.ai/api/v2/import-urlPOSTIngests PDF from presigned URLurl (URI), folder_id (UUID)
https://app.humata.ai/api/v1/pdf/{pdf-id}GETChecks vectorization & parse statusPath param: pdf-id
https://app.humata.ai/api/v1/conversationsPOSTInitializes multi-document contextdocumentIds (Array of UUIDs)
https://app.humata.ai/api/v1/askPOSTStreams answers with citationsconversationId, question, model, selectedAnswerApproach
https://app.humata.ai/api/v1/users/tokenPOSTGenerates 60-min OTP session tokenemail, provider

All requests require HTTP Bearer authentication:

Authorization: Bearer YOUR_HUMATA_API_KEY
Content-Type: application/json

Default rate limits are capped at 120 requests per minute. When rate limits are triggered, Humata returns 429 Too Many Requests along with standard X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset HTTP headers.


Step 1: Authentication & Folder Preparation

Before triggering programmatic imports, retrieve your credentials and target folder:

  1. Obtain API Key: Log into the Humata web console as an organization administrator, navigate to Settings > Developer Settings (https://app.humata.ai/settings/developers), and generate a secret API key.
  2. Retrieve Folder UUID: Documents imported via API must reside in a specific folder. Navigate to your desired workspace folder in app.humata.ai and extract the UUID from the browser URL (e.g., e507832b-bdef-4baf-8423-822c1cb68e35) or capture the folder_id returned from previously indexed documents.

Store these in your backend environment configuration:

HUMATA_API_KEY="humata_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
HUMATA_DEFAULT_FOLDER_ID="e507832b-bdef-4baf-8423-822c1cb68e35"

Step 2: Asynchronous PDF Ingestion via Presigned URLs

A frequent misunderstanding among developers is attempting to transmit multipart file payloads directly to Humata. Humata’s ingestion endpoint (/api/v2/import-url) does not accept direct binary file streams; instead, it expects a downloadable HTTP(S) URL.

For enterprise environments where internal PDFs cannot be hosted publicly, generate an ephemeral, presigned URL from your cloud storage bucket (AWS S3, Google Cloud Storage, or Azure Blob Storage) with a 5-to-15-minute expiration window.

Python Implementation: Presigned Handoff to Humata

import os
import requests
import boto3

HUMATA_API_KEY = os.environ["HUMATA_API_KEY"]
FOLDER_ID = os.environ["HUMATA_DEFAULT_FOLDER_ID"]
HUMATA_BASE_URL = "https://app.humata.ai/api"

headers = {
    "Authorization": f"Bearer {HUMATA_API_KEY}",
    "Content-Type": "application/json",
}

def import_private_document(s3_bucket: str, s3_key: str) -> str:
    # 1. Generate short-lived presigned URL (10 minutes)
    s3_client = boto3.client("s3")
    presigned_url = s3_client.generate_presigned_url(
        "get_object",
        Params={"Bucket": s3_bucket, "Key": s3_key},
        ExpiresIn=600,
    )

    # 2. Instruct Humata to ingest and vectorize the PDF
    payload = {
        "url": presigned_url,
        "folder_id": FOLDER_ID,
    }
    
    response = requests.post(
        f"{HUMATA_BASE_URL}/v2/import-url",
        headers=headers,
        json=payload,
        timeout=30,
    )
    response.raise_for_status()
    
    document_id = response.json()["id"]
    return document_id

Step 3: Polling Ingestion Status (read_status)

Document parsing, OCR, and embedding generation occur asynchronously on Humata’s processing infrastructure. Querying a document before indexing completes will return empty context or an error.

Backend services must poll GET /api/v1/pdf/{pdf-id} until read_status evaluates to SUCCESS.

import time

def wait_for_document_indexing(document_id: str, timeout_seconds: int = 180) -> dict:
    start_time = time.time()
    poll_interval = 3  # seconds

    while time.time() - start_time < timeout_seconds:
        resp = requests.get(
            f"{HUMATA_BASE_URL}/v1/pdf/{document_id}",
            headers=headers,
            timeout=15,
        )
        resp.raise_for_status()
        doc_data = resp.json()
        status = doc_data.get("read_status")

        if status == "SUCCESS":
            return doc_data
        elif status == "FAILED":
            raise RuntimeError(f"Humata document indexing failed for {document_id}")

        time.sleep(poll_interval)
        poll_interval = min(poll_interval * 1.5, 15)  # exponential backoff

    raise TimeoutError(f"Indexing timed out for document {document_id}")

The response includes essential audit metadata:

{
  "id": "a8283bc7-02ee-471b-8590-5ef5401afa40",
  "name": "Vendor_Master_Agreement_2026.pdf",
  "organization_id": "fcf6c954-ba68-4e39-a7b5-960dc8274ec0",
  "number_of_pages": 48,
  "folder_id": "e507832b-bdef-4baf-8423-822c1cb68e35",
  "read_status": "SUCCESS",
  "file_type": "PDF"
}

Step 4: Initializing Multi-Document Conversations

Humata separates raw document objects from conversational query sessions. Before asking questions, initialize a conversation bound to one or more documentIds via POST /api/v1/conversations.

Binding multiple document IDs allows cross-document correlation—such as analyzing a Master Services Agreement alongside three accompanying Statements of Work (SOWs) and an NDA in a single prompt.

def create_document_conversation(document_ids: list[str]) -> str:
    payload = {"documentIds": document_ids}
    
    resp = requests.post(
        f"{HUMATA_BASE_URL}/v1/conversations",
        headers=headers,
        json=payload,
        timeout=15,
    )
    resp.raise_for_status()
    return resp.json()["id"]

Step 5: Grounded Querying & Exact Citation Extraction

To embed Q&A into business workflows where factual integrity is non-negotiable (legal risk reviews, compliance verifications, or technical documentation), you must select the appropriate retrieval mode.

365Finds Recommendation: Mandate "Grounded" Mode

The Humata API provides three values for selectedAnswerApproach:

365Finds strongly advises setting selectedAnswerApproach: "Grounded" for all automated internal enterprise integrations. Allowing Balanced or Creative introduces subtle hallucinations that undermine automated contract review and audit workflows. For model selection, we recommend gpt-4o for the optimal balance of reasoning latency and complex citation mapping.

Handling SSE Streams & Parsing Exact Citations

The POST /api/v1/ask endpoint delivers answers over a Server-Sent Events (text/event-stream) connection. Each chunk arrives as data: { 'content': '...' }.

At the conclusion of the response, Humata automatically appends inline bracket markers (e.g., [1], [2]) in the body text and appends a structured citation trailer:

data: { 'content': 'The aggregate liability under Clause 14 is capped at twelve months of prior fees[1].' }
data: { 'content': '\n\nReferences - [1]: Page 23 of Master_Agreement.pdf' }

Full Streaming & Citation Parser Implementation

Here is an end-to-end Python client that streams the response token-by-token and parses out page-level citations for your UI:

import re
import json

def ask_humata_with_citations(
    conversation_id: str,
    prompt: str,
    model: str = "gpt-4o",
    approach: str = "Grounded",
):
    payload = {
        "conversationId": conversation_id,
        "question": prompt,
        "model": model,
        "selectedAnswerApproach": approach,
    }

    response = requests.post(
        f"{HUMATA_BASE_URL}/v1/ask",
        headers=headers,
        json=payload,
        stream=True,
        timeout=60,
    )
    response.raise_for_status()

    accumulated_text = ""

    # Stream SSE chunks
    for line in response.iter_lines(decode_unicode=True):
        if not line or not line.startswith("data:"):
            continue
        
        raw_json_str = line[len("data:"):].strip()
        try:
            # Humata SSE emits JSON with single or double quotes
            chunk_data = json.loads(raw_json_str.replace("'", '"'))
            content = chunk_data.get("content", "")
            accumulated_text += content
            # Yield content chunk for real-time frontend streaming
            yield {"type": "token", "content": content}
        except json.JSONDecodeError:
            continue

    # Extract exact page references from accumulated response
    # Target pattern: References - [1]: Page 10 of Filename.pdf
    citation_pattern = r"References\s*-\s*\[(\d+)\]:\s*Page\s*(\d+)\s+of\s+(.+)"
    citations = []

    for match in re.finditer(citation_pattern, accumulated_text):
        ref_id = match.group(1)
        page_num = int(match.group(2))
        file_name = match.group(3).strip()
        citations.append({
            "reference_index": ref_id,
            "page_number": page_num,
            "document_name": file_name,
        })

    # Separate clean answer text from references section
    clean_answer = accumulated_text.split("\n\nReferences -")[0].strip()

    yield {
        "type": "final_result",
        "answer": clean_answer,
        "citations": citations,
        "full_text": accumulated_text,
    }

Step 6: Deep-Linking Citations in Internal Frontends

Once citations are parsed into structured objects (page_number, document_name), your frontend application can transform plain [1] inline tags into clickable UI badges.

When a user clicks citation badge [1], trigger an event in your internal PDF reader (such as PDF.js or an embedded browser viewer):

// Frontend TypeScript interface
interface Citation {
  reference_index: string;
  page_number: number;
  document_name: string;
}

// Function to navigate internal PDF viewer to exact cited page
function openCitedDocumentPage(citation: Citation, documentBaseUrl: string) {
  const viewerUrl = `${documentBaseUrl}/${encodeURIComponent(citation.document_name)}#page=${citation.page_number}`;
  window.open(viewerUrl, "pdfViewerPane");
}

This transforms Humata from an opaque chat assistant into a verifiable audit copilot. Legal analysts and auditors can verify assertions in a single click, seeing the exact contractual clause or balance sheet line item on the original PDF page.


Step 7: Enterprise Authentication & User Provisioning

When embedding Humata capabilities across large organizations, managing individual developer API keys is inadequate. Humata provides dedicated endpoints for automated user provisioning and single sign-on (SSO) token generation:

  1. User Creation (POST /api/v1/users): Organization admins can provision internal employee accounts with bypass_email_verification: true.
  2. One-Time Password (OTP) Generation (POST /api/v1/users/token): Generate an ephemeral session token (valid for 60 minutes) mapped to an internal user’s email. This allows web applications to embed Humata components seamlessly without exposing primary administrative API keys to the browser client.
curl -X POST https://app.humata.ai/api/v1/users/token \
  -H "Authorization: Bearer $HUMATA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"email": "engineer@enterprise.internal", "provider": "email"}'

Engineering Trade-Offs & Best Practices

Architecture DecisionRecommended ApproachTechnical Rationale
Ingestion ProtocolPresigned S3/GCS URLs (5-15 min TTL)Prevents exposing persistent public links while working around Humata's lack of direct multipart byte streaming.
Indexing SynchronizationAsynchronous polling with exponential backoffPrevents thread blocking and eliminates race conditions when querying newly submitted documents.
Retrieval ParameterselectedAnswerApproach: "Grounded"Eliminates external model hallucination; forces citation accountability or explicit admission of missing facts.
Rate Limit ManagementToken-bucket client queue with 429 retryRespects the default 120 req/min threshold and inspects X-RateLimit-Reset to throttle burst requests.
Citation IntegrationRegex parsing on SSE completion + PDF.js deep-linkingConverts text markers into interactive jumps directly to the cited PDF page number in internal apps.

Limitations to Consider

  1. No Webhook Notifications: Humata does not currently emit webhook events upon completing document parsing. Systems must implement active polling against GET /api/v1/pdf/{pdf-id}.
  2. In-Band References: Citation data is not delivered as a separate structured JSON event over the SSE stream; it is embedded directly in the text stream, requiring server-side regex extraction before presentation.
  3. Strict PDF Focus: The ingestion pipeline (/v2/import-url) is optimized specifically for PDF payloads. For Office documents (DOCX, PPTX) or scanned images, convert files to PDF upstream before calling Humata.

Summary Checklist for Production Deployment

To take your Humata API integration live:

  1. Secure administrative API keys in an enterprise secret manager (e.g., AWS Secrets Manager, HashiCorp Vault).
  2. Configure cloud storage buckets to generate presigned URLs with minimal expiration windows.
  3. Deploy an ingestion poller checking read_status == "SUCCESS" before passing documentIds to POST /api/v1/conversations.
  4. Enforce selectedAnswerApproach: "Grounded" on all query endpoints to prevent hallucination.
  5. Ingest the SSE stream, extract References - [N]: Page X of Y.pdf, and bind inline citation badges to your internal PDF viewer.

References