Logo
Extraction

Timeline Builder

View API

Overview

The Timeline Builder API extracts temporal data and events from documents, organizing them into a structured, chronological timeline with relationship mapping. This powerful agent identifies dates, events, and their predecessor-successor relationships, making it ideal for legal documents, project histories, case files, and any content requiring temporal analysis.

Use this endpoint to:

  • Extract temporal data and events from documents
  • Build chronological timelines with relationship mapping
  • Identify predecessor-successor event relationships
  • Analyze legal cases, contracts, and court proceedings
  • Track project histories and milestones
  • Organize events by time periods and domains

Endpoint Details

Method: POST
Endpoint: /api/agent/timeline_builder
Base URL: https://api.k-v.ai
Authentication: Access Key (Required)


Request Specification

Headers

HeaderTypeRequiredDescription
access-keystringYesYour unique access-key generated from the platform UI
Content-TypestringYesMust be application/json

Request Body

{
   "doc_process_ids": [
       "b7c90fd1892870e25530ff375c9b851f"
   ],
   "domain": "general",
   "model_data": {
       "model_name": "gpt-5.1",
       "api_key": ""
   }
}

Body Fields

ParameterTypeRequiredDescription
doc_process_idsarrayYesArray of document processing IDs to analyze
domainstringYesAnalysis domain: general, pharma, legal, or finance
model_dataobjectYesAI model configuration
model_data.model_namestringYesAI model identifier (e.g., gpt-5.1)
model_data.api_keystringNoYour LLM API key (leave empty to use platform keys)

Domain Options

DomainUse Case
generalBusiness documents, reports, general content
pharmaPharmaceutical documents, drug trials, clinical timelines
legalLegal cases, contracts, court proceedings
financeFinancial transactions, investment records, audits

Supported AI Models

Model NameProvider
gpt-5.1OpenAI
gpt-5-miniOpenAI
claude-sonnet-4-5-20250929Anthropic
gemini/gemini-2.5-flash-liteGoogle
gemini/gemini-2.5-proGoogle
gemini/gemini-3-pro-previewGoogle
mistral/mistral-small-latestMistral AI
mistral/mistral-medium-latestMistral AI
llama3.1-70bMeta

Using Your Own LLM API Keys

Platform Keys (Default)

{
    "model_data": {
        "model_name": "gpt-5.1",
        "api_key": ""
    }
}

Your Own Keys

{
    "model_data": {
        "model_name": "gpt-5.1",
        "api_key": "sk-your-openai-api-key-here"
    }
}

Response Specification

Success Response (200 OK)

{
    "data": {
        "timeline": {
            "success": true,
            "data": {
                "timeline": {
                    "nodes": [
                        {
                            "id": 0,
                            "date": "2002-12-16",
                            "event": "Event description...",
                            "precision": "111",
                            "source": "document.pdf",
                            "page_number": "30",
                            "page_numbers": ["30"],
                            "sources": ["document.pdf"],
                            "domain": "general",
                            "topics": ["business", "corporate"],
                            "is_cluster": false,
                            "cluster_size": 1,
                            "is_merged": false,
                            "merged_count": 1,
                            "spans_multiple_pages": false,
                            "precision_flags": {
                                "year_exact": true,
                                "month_exact": true,
                                "day_exact": true
                            }
                        }
                    ],
                    "periods": [
                        {
                            "year": "2002",
                            "label": "2002",
                            "node_ids": [0, 1],
                            "event_count": 2
                        }
                    ],
                    "connections": [
                        {
                            "id": 0,
                            "source_node": 0,
                            "target_node": 1,
                            "type": "same_source",
                            "strength": 0.96
                        }
                    ]
                },
                "metadata": {
                    "total_events": 109,
                    "merged_events": 0,
                    "unique_events": 109,
                    "date_range": {
                        "start": "2002-12-16",
                        "end": "2016-12-29"
                    },
                    "sources": ["document.pdf"],
                    "total_sources": 1,
                    "domains": ["general"],
                    "topics": ["business", "contracts", "corporate"],
                    "total_topics": 7
                },
                "visualization_config": {
                    "layout": "horizontal",
                    "group_by": "year",
                    "show_precision": true,
                    "show_page_numbers": true,
                    "highlight_merged": true,
                    "cluster_threshold": 5,
                    "color_by_domain": true
                }
            },
            "metadata": {
                "total_events": 109,
                "filtered_events": 109,
                "total_tokens": {
                    "input": 41948,
                    "output": 11384,
                    "total": 53332
                },
                "model_used": "gpt-5.1",
                "export_format": "default",
                "filters_applied": false
            },
            "errors": []
        },
        "file_hash_mapping": {
            "document.pdf": "b7c90fd1892870e25530ff375c9b851f"
        },
        "metadata": {
            "user_name": "user@example.com",
            "domain": "general",
            "processed_at": "2026-01-07T10:51:22.262479",
            "total_files": 1,
            "total_chunks": 144
        }
    },
    "message": "Timelines generated successfully"
}

Response Fields

Timeline Nodes

Each event node contains:

FieldTypeDescription
idIntegerUnique identifier for the event
dateStringEvent date in ISO format (YYYY-MM-DD)
eventStringDetailed description of the event
precisionStringDate precision indicator (111 = full precision)
sourceStringSource document filename
page_numberStringPrimary page number where event appears
page_numbersArrayAll page numbers containing this event
sourcesArrayAll source documents for this event
domainStringDomain classification
topicsArrayRelevant topics/categories
is_clusterBooleanWhether event is part of a cluster
cluster_sizeIntegerNumber of events in cluster
is_mergedBooleanWhether event is merged from multiple sources
merged_countIntegerNumber of merged events
spans_multiple_pagesBooleanWhether event spans across pages
precision_flagsObjectGranular precision indicators

Precision Flags

FlagTypeDescription
year_exactBooleanYear is precisely known
month_exactBooleanMonth is precisely known
day_exactBooleanDay is precisely known

Timeline Periods

Grouping of events by time period:

FieldTypeDescription
yearStringYear identifier
labelStringDisplay label
node_idsArrayEvent IDs in this period
event_countIntegerNumber of events

Connections (Event Relationships)

The connections array defines relationships between events, including temporal sequences and predecessor-successor relationships:

FieldTypeDescription
idIntegerConnection identifier
source_nodeIntegerSource event ID (predecessor)
target_nodeIntegerTarget event ID (successor)
typeStringConnection type (e.g., "same_source", "temporal")
strengthFloatConnection strength/confidence (0-1)

Understanding Event Sequences

The connections enable navigation through the timeline by establishing predecessor-successor relationships:

Finding Successor Events

When looking at a specific event (e.g., source_node == 0), the target_node contains the ID of the successor event (the event that follows)

Example: {"source_node": 0, "target_node": 1} means event 1 is the successor to event 0

Finding Predecessor Events

When examining a specific event (e.g., target_node == 0), the source_node contains the ID of the predecessor event (the event that came before)

Example: {"source_node": 9, "target_node": 0} means event 9 is the predecessor to event 0

Connection Example

{
    "id": 1,
    "source_node": 0,
    "target_node": 1,
    "type": "same_source",
    "strength": 0.9616
}

This indicates that event ID 1 is the successor to event ID 0, with a strong relationship strength (0.96) from the same source document.


Code Snippets

curl --location 'https://api.k-v.ai/api/agent/timeline_builder' \
--header 'access-key: YOUR_ACCESS_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "doc_process_ids": [
        "b7c90fd1892870e25530ff375c9b851f"
    ],
    "domain": "general",
    "model_data": {
        "model_name": "gpt-5.1",
        "api_key": ""
    }
}'
import requests
import json

url = "https://api.k-v.ai/api/agent/timeline_builder"

payload = json.dumps({
  "doc_process_ids": [
    "b7c90fd1892870e25530ff375c9b851f"
  ],
  "domain": "general",
  "model_data": {
    "model_name": "gpt-5.1",
    "api_key": ""
  }
})
headers = {
  'access-key': 'YOUR_ACCESS_KEY',
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
const axios = require('axios');
let data = JSON.stringify({
  "doc_process_ids": [
    "b7c90fd1892870e25530ff375c9b851f"
  ],
  "domain": "general",
  "model_data": {
    "model_name": "gpt-5.1",
    "api_key": ""
  }
});

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api.k-v.ai/api/agent/timeline_builder',
  headers: { 
    'access-key': 'YOUR_ACCESS_KEY', 
    'Content-Type': 'application/json'
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
from kv_platform_sdk import AsyncClient
from kv_platform_sdk.models.extractor import TimelineBuilderRequest
from kv_platform_sdk.models.model_data import ModelData
import asyncio

ACCESS_KEY = "YOUR_ACCESS_KEY"

async def main():
    async with AsyncClient(access_key=ACCESS_KEY, timeout=10 * 60) as client:
        request = TimelineBuilderRequest(
            doc_process_ids=["b16be8415ed216509bbcd4c04dd05b9e"],
            domain="general",
            model_data=ModelData(model_name="gpt-5.1"),
        )

        result = await client.timeline_builder.build(request)

        print(result)


asyncio.run(main())
from kv_platform_sdk import Client
from kv_platform_sdk.models.extractor import TimelineBuilderRequest
from kv_platform_sdk.models.model_data import ModelData

ACCESS_KEY = "YOUR_ACCESS_KEY"

client = Client(access_key=ACCESS_KEY, timeout=10 * 60)

request = TimelineBuilderRequest(
    doc_process_ids=["b16be8415ed216509bbcd4c04dd05b9e"],
    domain="general",
    model_data=ModelData(model_name="gpt-5.1"),
)

result = client.timeline_builder.build(request)

print(result)

client.close()

Error Responses

401 Unauthorized

{
    "data": {},
    "message": "Invalid or missing access key"
}

Cause: Missing or invalid access-key header.


422 Unprocessable Entity - Invalid domain name

{
    "detail": [
        {
            "type": "literal_error",
            "loc": [
                "body",
                "domain"
            ],
            "msg": "Input should be 'general', 'pharma', 'legal' or 'finance'",
            "input": "generall",
            "ctx": {
                "expected": "'general', 'pharma', 'legal' or 'finance'"
            }
        }
    ]
}

Cause: Invalid or unsupported domain name. See supported domain list above.


422 Unprocessable Entity - Invalid Model Name

{
    "detail": [
        {
            "type": "literal_error",
            "loc": [
                "body",
                "model_data",
                "model_name"
            ],
            "msg": "Input should be 'gpt-5-chat-latest', 'gpt-5.1', 'gpt-5-mini', 'claude-sonnet-4-5-20250929', 'gemini/gemini-2.5-flash-lite', 'mistral/mistral-small-latest', 'mistral/mistral-medium-latest', 'gemini/gemini-2.5-pro', 'gemini/gemini-3-pro-preview' or 'llama3.1-70b'",
            "input": "",
            "ctx": {
                "expected": "'gpt-5-chat-latest', 'gpt-5.1', 'gpt-5-mini', 'claude-sonnet-4-5-20250929', 'gemini/gemini-2.5-flash-lite', 'mistral/mistral-small-latest', 'mistral/mistral-medium-latest', 'gemini/gemini-2.5-pro', 'gemini/gemini-3-pro-preview' or 'llama3.1-70b'"
            }
        }
    ]
}

Cause: Invalid or unsupported model_name in model_data. See supported models list above.


400 Bad Request - Invalid Document IDs

{
    "data": {},
    "message": "Invalid docs selected"
}

Causes: Missing or invalid doc_process_ids.


500 Internal Server Error - Invalid LLM API Key

{
    "data": {},
    "message": "litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: tyrdfuih**uhf7. You can find your API key at https://platform.openai.com/account/api-keys."
}

Cause: The api_key provided in model_data is invalid or expired. Verify your LLM provider API key.


500 Internal Server Error - General Error

{
    "data": {},
    "message": "Something went wrong"
}

Causes:

  • LLM service temporarily unavailable
  • Server-side processing error

Next Steps

After building timelines:

  • Validate Results: Review extracted events and their chronological accuracy
  • Analyze Relationships: Examine connections between events to understand sequences
  • Visualize Timelines: Use the timeline data to create visual representations
  • Automate Workflows: Integrate into document processing pipelines

Need Help? Contact support at support@k-v.ai

On this page