Skip to content

thedriveAI/thedriveai-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

The Drive AI — Developer API

Send a file or URL. Define a schema. Get structured, verified answers back.

File intelligence endpoints from The Drive AI — extract structured data, analyze documents, cross-reference files, convert to markdown, and generate thumbnails from any file or URL. 107+ formats. Python and TypeScript SDKs.

PyPI npm Docs License

The Drive AI is an AI-powered workspace for working with documents. These are standalone developer APIs — built internally to power our workspace, now available as public endpoints at dev.thedrive.ai. This is not the SDK for the core workspace product.


What are these APIs?

The Drive AI developer API is a set of file intelligence endpoints for developers who need to extract structured data from files, reason over documents, and cross-reference multiple sources — without building their own parsing, OCR, or AI pipelines.

You send a file (or URL), define the fields you want, and get back typed, structured JSON with confidence scores, reasoning traces, and source citations. It works on PDFs, spreadsheets, images, websites, presentations, code files, videos, and 100+ other formats through a single unified endpoint.

Built for AI agents and developers who need to process documents programmatically.

Key differences from calling an LLM directly:

  • Agent architecture — multi-step extraction with verification, not a single prompt
  • Math is computed, not guessed — numerical fields run through a sandboxed calculator
  • 107+ formats in one call — no separate parsers for PDF vs DOCX vs images
  • OCR + vision proofreading — handwritten text, stamps, and scanned documents work out of the box
  • 1000+ page support — large documents are chunked and processed with cross-page table continuity
  • Every answer is auditable — source citations point to exact pages and locations

Quick Start

Install

# Python
pip install thedriveai

# TypeScript / JavaScript
npm install @thedriveai/sdk

Get your API key

Sign up at dev.thedrive.ai/login — you get 100 free credits/month to start.

Your first extraction

Python:

from thedriveai import TheDriveAI

client = TheDriveAI(api_key="your-api-key")

result = client.extract(
    file="invoice.pdf",
    schema={
        "vendor_name": { "type": "string", "description": "Company that issued the invoice" },
        "invoice_total": { "type": "number", "description": "Total amount due" },
        "due_date": { "type": "string", "description": "Payment due date" },
        "line_items": {
            "type": "array",
            "description": "Each line item with description and amount",
            "items": {
                "description": { "type": "string" },
                "amount": { "type": "number" }
            }
        }
    }
)

print(result.data)
# {
#   "vendor_name": "Acme Corp",
#   "invoice_total": 4250.00,
#   "due_date": "2025-02-15",
#   "line_items": [
#     { "description": "Consulting — January", "amount": 3500.00 },
#     { "description": "Expenses", "amount": 750.00 }
#   ]
# }

TypeScript:

import { TheDriveAI } from "@thedriveai/sdk";

const client = new TheDriveAI({ apiKey: "your-api-key" });

const result = await client.extract({
  file: "invoice.pdf",
  schema: {
    vendor_name: { type: "string", description: "Company that issued the invoice" },
    invoice_total: { type: "number", description: "Total amount due" },
    due_date: { type: "string", description: "Payment due date" },
    line_items: {
      type: "array",
      description: "Each line item with description and amount",
      items: {
        description: { type: "string" },
        amount: { type: "number" },
      },
    },
  },
});

console.log(result.data);

cURL:

curl -X POST https://dev.thedrive.ai/api/v1/extract \
  -H "Authorization: Bearer your-api-key" \
  -F "file=@invoice.pdf" \
  -F 'schema={
    "vendor_name": { "type": "string", "description": "Company that issued the invoice" },
    "invoice_total": { "type": "number", "description": "Total amount due" },
    "due_date": { "type": "string", "description": "Payment due date" }
  }'

API Endpoints

Extract — Pull structured data from any file

Fast path for pulling literal values out of documents. Define a schema with typed fields, get back structured JSON with confidence scores and source citations.

Feature Detail
Input File upload or URL
Output Typed JSON matching your schema
Confidence Per-field confidence scores (0-1)
Citations Source page and location for each field
Schema types string, number, boolean, array, enum
Partial results Returns what it can if some fields aren't found

Python — Using Pydantic models:

from pydantic import BaseModel, Field
from thedriveai import TheDriveAI

class Invoice(BaseModel):
    vendor: str = Field(description="Company name")
    total: float = Field(description="Total amount due")
    currency: str = Field(description="Currency code (USD, EUR, etc.)")
    is_paid: bool = Field(description="Whether the invoice is marked as paid")

client = TheDriveAI(api_key="your-api-key")
result = client.extract(file="invoice.pdf", schema=Invoice)

print(result.data)         # Invoice(vendor="Acme Corp", total=4250.0, ...)
print(result.confidence)   # {"vendor": 0.98, "total": 0.95, ...}

TypeScript — Using Zod schemas:

import { z } from "zod";
import { TheDriveAI } from "@thedriveai/sdk";

const InvoiceSchema = z.object({
  vendor: z.string().describe("Company name"),
  total: z.number().describe("Total amount due"),
  currency: z.string().describe("Currency code (USD, EUR, etc.)"),
  is_paid: z.boolean().describe("Whether the invoice is marked as paid"),
});

const client = new TheDriveAI({ apiKey: "your-api-key" });
const result = await client.extract({
  file: "invoice.pdf",
  schema: InvoiceSchema,
});

console.log(result.data);       // { vendor: "Acme Corp", total: 4250, ... }
console.log(result.confidence); // { vendor: 0.98, total: 0.95, ... }

Cost: 1 credit per page, 5 credits per website


Analyze — Compute, reason, and verify

Analyze goes beyond extraction. It reads the document, performs multi-step reasoning, runs calculations in a sandboxed environment, and returns computed answers — not just values pulled from text.

Use Analyze when you need the API to think, not just read.

Example: Invoice verification

result = client.analyze(
    file="invoice.pdf",
    schema={
        "line_items_match_total": {
            "type": "boolean",
            "description": "Do the individual line items sum to the stated total?"
        },
        "discrepancy_amount": {
            "type": "number",
            "description": "If line items don't match total, the difference in dollars"
        },
        "tax_rate_applied": {
            "type": "number",
            "description": "The effective tax rate as a percentage"
        },
        "is_tax_correct": {
            "type": "boolean",
            "description": "Is the tax amount mathematically correct given the subtotal?"
        }
    },
    include_steps=True
)

print(result.data)
# {
#   "line_items_match_total": false,
#   "discrepancy_amount": 47.50,
#   "tax_rate_applied": 8.875,
#   "is_tax_correct": true
# }

print(result.reasoning)
# "Summed 12 line items: $3,952.50. Stated subtotal: $4,000.00.
#  Difference: $47.50. Tax: 8.875% of $4,000.00 = $355.00 (matches stated tax)."

Example: Contract analysis

result = client.analyze(
    file="service_agreement.pdf",
    schema={
        "is_active": {
            "type": "boolean",
            "description": "Is the contract currently active based on start and end dates?"
        },
        "days_until_expiry": {
            "type": "number",
            "description": "Number of days until the contract expires"
        },
        "total_liability_exposure": {
            "type": "number",
            "description": "Maximum total liability across all clauses"
        },
        "auto_renews": {
            "type": "boolean",
            "description": "Does the contract auto-renew?"
        }
    }
)

Cost: 2 credits per page, 10 credits per website


Cross-Document Analysis — Reason across multiple files

Send 2-5 documents and ask questions that span all of them. The API cross-references information between files and traces each answer back to its source document.

Example: Invoice vs. contract validation

result = client.analyze_cross(
    files=[
        {"file": "invoice_march.pdf", "label": "March Invoice"},
        {"file": "master_services_agreement.pdf", "label": "MSA"},
    ],
    schema={
        "rates_match": {
            "type": "boolean",
            "description": "Do the hourly rates on the invoice match the rates in the MSA?"
        },
        "correct_vendor": {
            "type": "boolean",
            "description": "Is the vendor on the invoice the same entity as the contractor in the MSA?"
        },
        "within_budget": {
            "type": "boolean",
            "description": "Is the invoice total within the budget cap specified in the MSA?"
        },
        "overbilled_amount": {
            "type": "number",
            "description": "If rates don't match, the total overbilled amount"
        }
    }
)

print(result.data)
# {
#   "rates_match": false,
#   "correct_vendor": true,
#   "within_budget": true,
#   "overbilled_amount": 1250.00
# }

print(result.sources)
# [
#   { "label": "March Invoice", "pages": 2, "fields_sourced": ["rates_match", "overbilled_amount"] },
#   { "label": "MSA", "pages": 14, "fields_sourced": ["rates_match", "correct_vendor", "within_budget"] }
# ]

Cost: 5 credits per document + 3 credits per page


Markdown — Convert any file or URL to clean markdown

Convert documents, spreadsheets, presentations, images, and web pages to well-structured markdown. Tables, headings, lists, and code blocks are preserved.

# From a file
result = client.markdown(file="report.pdf")
print(result.markdown)

# From a URL (shorthand)
result = client.markdown_url("https://example.com/pricing")
print(result.markdown)
// From a URL
const result = await client.markdown({ url: "https://example.com/pricing" });
console.log(result.markdown);

Thumbnails — Generate preview images from 107+ file types

Generate thumbnail images from documents, spreadsheets, presentations, images, videos, code files, and web pages. Returns either a hosted URL or base64-encoded image data.

result = client.thumbnail(
    file="presentation.pptx",
    response_type="url"
)
print(result.url)          # https://dev.thedrive.ai/thumbnails/...
print(result.metadata)     # { "file_type": "pptx", "width": 800, "height": 600, ... }
const result = await client.thumbnail({
  file: "presentation.pptx",
  responseType: "url",
});
console.log(result.url);
console.log(result.metadata);

Screenshots — Capture any webpage

Take full-page screenshots of any URL. The API renders JavaScript, waits for dynamic content, and returns a JPEG image.

image_bytes = client.screenshot(
    url="https://example.com",
    width=1440,
    height=900
)

with open("screenshot.jpg", "wb") as f:
    f.write(image_bytes)
const imageBytes = await client.screenshot({
  url: "https://example.com",
  width: 1440,
  height: 900,
});

Website Intelligence

Every endpoint that accepts a file also accepts a URL. The API renders the page in a headless browser (including JavaScript-heavy SPAs), extracts content from the rendered DOM, and processes it the same way it would a file.

# Extract structured data from a website
result = client.extract(
    url="https://example.com/product/widget-pro",
    schema={
        "product_name": { "type": "string", "description": "Product name" },
        "price": { "type": "number", "description": "Price in USD" },
        "in_stock": { "type": "boolean", "description": "Whether the product is available" },
        "features": { "type": "array", "description": "List of product features" }
    }
)

Multi-page research with follow_links

For use cases like competitive analysis or lead enrichment, enable follow_links to let the API crawl linked pages and aggregate data across them.

result = client.extract(
    url="https://competitor.com",
    schema={
        "company_name": { "type": "string" },
        "pricing_tiers": { "type": "array", "description": "Pricing plans with name, price, features" },
        "team_size": { "type": "number", "description": "Number of team members listed" },
        "tech_stack": { "type": "array", "description": "Technologies mentioned on the site" }
    },
    follow_links=True
)

Use cases for website intelligence:

  • Lead enrichment — Extract company info, team size, tech stack from prospect websites
  • Competitive monitoring — Track competitor pricing, features, and positioning
  • Brand extraction — Pull logos, colors, taglines, social links from any site
  • Real estate listings — Extract property details from listing websites
  • Job board scraping — Pull structured job data from career pages

Async Processing & Batch Jobs

Async — Process large files without waiting

For files that take longer to process (large PDFs, long videos), use async mode. Submit the task, get a task_id, and either poll for results or receive a webhook when it's done.

# Submit async task
task = client.extract_async(
    file="500_page_report.pdf",
    schema=my_schema
)
print(task.task_id)    # "task_abc123"
print(task.poll_url)   # "https://dev.thedrive.ai/api/v1/jobs/task_abc123"

# Option 1: Wait for completion (polls automatically)
result = client.wait_for_task(task.task_id, poll_interval=2, timeout=300)

# Option 2: Use a webhook
task = client.extract_async(
    file="500_page_report.pdf",
    schema=my_schema,
    webhook_url="https://your-app.com/webhooks/thedrive"
)

Batch — Process multiple files at once

Send up to 20 files or URLs with a single schema. Each file is processed independently, and you get results for all of them.

batch = client.extract_batch(
    files=["invoice_jan.pdf", "invoice_feb.pdf", "invoice_mar.pdf"],
    schema={
        "vendor": { "type": "string" },
        "total": { "type": "number" },
        "date": { "type": "string" }
    }
)

print(batch.batch_id)       # "batch_xyz789"
print(batch.total)          # 3
print(batch.completed)      # 0 (initially)

# Wait for all to finish
results = client.wait_for_batch(batch.batch_id)
for r in results:
    print(r.data)

Supported File Formats

The developer API processes 107+ file formats through a single unified endpoint. No separate parsers or format-specific code needed.

Documents

Format Extensions
PDF .pdf
Microsoft Word .docx, .doc
OpenDocument .odt
Rich Text .rtf
Apple Pages .pages
EPUB .epub
Plain Text .txt

Spreadsheets

Format Extensions
Microsoft Excel .xlsx, .xls
OpenDocument .ods
CSV .csv
TSV .tsv
Apple Numbers .numbers

Presentations

Format Extensions
Microsoft PowerPoint .pptx, .ppt
OpenDocument .odp
Apple Keynote .key

Images

Format Extensions
JPEG .jpg, .jpeg
PNG .png
GIF .gif
WebP .webp
SVG .svg
TIFF .tiff, .tif
BMP .bmp
HEIC .heic
AVIF .avif
ICO .ico

Video & Audio

Format Extensions
MP4 .mp4
QuickTime .mov
WebM .webm
AVI .avi
MKV .mkv
3GP .3gp
WMV .wmv
FLV .flv
MP3 .mp3
WAV .wav
M4A .m4a
FLAC .flac
OGG .ogg

Code & Data

Format Extensions
JSON .json
XML .xml
YAML .yaml, .yml
HTML .html, .htm
Markdown .md
Python .py
JavaScript .js
TypeScript .ts
Go .go
Rust .rs
Java .java
C/C++ .c, .cpp, .h
C# .cs
Ruby .rb
PHP .php
Swift .swift
Kotlin .kt
Scala .scala
Shell .sh, .bash
SQL .sql
R .r
Lua .lua
Perl .pl
Haskell .hs
Elixir .ex
Dart .dart
+ 30 more See full list

Web

Input Description
Any URL Full JavaScript rendering, SPA support, dynamic content

Use Cases

Invoice Processing & Accounts Payable

Extract vendor details, line items, totals, tax amounts, and due dates from invoices in any format. Verify that line items sum correctly. Cross-reference invoices against purchase orders or contracts.

result = client.analyze(
    file="invoice.pdf",
    schema={
        "vendor_name": { "type": "string", "description": "Vendor company name" },
        "invoice_number": { "type": "string", "description": "Invoice reference number" },
        "line_items": { "type": "array", "description": "Each line item" },
        "subtotal": { "type": "number", "description": "Subtotal before tax" },
        "tax": { "type": "number", "description": "Tax amount" },
        "total": { "type": "number", "description": "Total due" },
        "math_is_correct": { "type": "boolean", "description": "Do line items + tax = total?" }
    }
)

Contract Review & Legal Document Analysis

Extract key terms, dates, obligations, and clauses from contracts. Compute days until expiry, aggregate liability caps across sections, and check for auto-renewal clauses.

Medical Document Processing

Extract patient information, diagnosis codes, procedure codes, and claim amounts from healthcare forms. OCR + vision mode handles handwritten notes, stamps, and poor-quality scans.

Real Estate Document Processing

Pull property details from listings, appraisals, inspection reports, and title documents. Works on both uploaded documents and real estate listing URLs with the same schema.

Financial Document Analysis

Process bank statements, tax returns, financial reports, and audit documents. Compute ratios, verify totals, and cross-reference across multiple financial documents.

AI Agent & RAG Pipelines

The developer API is designed to be called by AI agents and used in retrieval-augmented generation pipelines. Convert documents to markdown for vector embedding, or extract structured data for agent tool use.

# Convert document to markdown for RAG indexing
markdown = client.markdown(file="knowledge_base.pdf")

# Or extract structured data for agent tool use
data = client.extract(
    file="customer_record.pdf",
    schema=CustomerSchema
)

Receipt & Expense Management

Scan receipts from any source — photos, PDFs, emails — and extract merchant, date, amount, category, and payment method.

Website Data Extraction

Extract structured data from any website without building scrapers. Product pages, job listings, company profiles, pricing pages, news articles — define a schema and get typed JSON back.


API Reference

Method Endpoint Description Credits
extract POST /api/v1/extract Extract structured data from a file or URL 1/page, 5/site
analyze POST /api/v1/analyze Analyze with reasoning and computation 2/page, 10/site
analyze_cross POST /api/v1/cross_analyze Cross-reference 2-5 documents 5/doc + 3/page
markdown POST /api/v1/markdown Convert file or URL to markdown 1/page
thumbnail POST /api/v1/thumbnails Generate thumbnail image 1/file
screenshot POST /api/v1/screenshots Capture webpage screenshot 1/URL
extract_async POST /api/v1/extract Async extraction (returns task_id) Same as sync
extract_batch POST /api/v1/batch Batch extraction (up to 20 files) Same as sync
analyze_async POST /api/v1/analyze Async analysis (returns task_id) Same as sync
analyze_batch POST /api/v1/batch Batch analysis (up to 20 files) Same as sync
poll_task GET /api/v1/jobs/{task_id} Check async task status Free
poll_batch GET /api/v1/batch/{batch_id} Check batch job status Free
health GET /api/v1/health Health check and cache stats Free

Full OpenAPI documentation: dev.thedrive.ai/docs


SDKs

Python

pip install thedriveai
  • Python 3.8+
  • Sync and async clients
  • Pydantic model support for schemas
  • Context manager for connection cleanup

PyPI · Python SDK docs

TypeScript / JavaScript

npm install @thedriveai/sdk
  • Node.js 18+
  • Full TypeScript types
  • Zod schema support
  • ESM and CommonJS

npm · TypeScript SDK docs

REST API

No SDK required. All endpoints accept standard multipart form data or JSON. See the OpenAPI spec for complete request/response schemas.


Pricing

Plan Price Credits Rate Limit Support
Free $0/month 100 credits/month 30 req/min Community
Pro $0.01/credit Pay as you go 120 req/min Priority
Enterprise Custom Custom 600 req/min Dedicated + SLA

Credit costs by endpoint

Endpoint File Website
Extract 1 credit/page 5 credits/site
Analyze 2 credits/page 10 credits/site
Cross-Analyze 5 credits/doc + 3 credits/page
Markdown 1 credit/page 1 credit/site
Thumbnail 1 credit/file 1 credit/site
Screenshot 1 credit/site

Sign up for free · View pricing


Performance

  • < 3 second average response time for single-page documents
  • 100ms response for cached results (LRU in-memory + storage-backed cache)
  • 1000+ page documents supported with multi-page table continuity
  • 50MB maximum file size
  • 20 files per batch request

Security

  • SSRF protection — URL inputs are validated against internal network ranges
  • MIME type validation — Files are verified against declared types
  • File size limits — 50MB maximum to prevent abuse
  • API key authentication — All requests require a valid API key
  • Rate limiting — Per-plan rate limits to ensure fair usage
  • HTTPS only — All API traffic is encrypted in transit

Error Handling

Both SDKs throw a TheDriveAIError with structured error information:

from thedriveai import TheDriveAI, TheDriveAIError

client = TheDriveAI(api_key="your-api-key")

try:
    result = client.extract(file="document.pdf", schema=my_schema)
except TheDriveAIError as e:
    print(e.status_code)  # 422
    print(e.detail)       # "Schema validation failed: 'amount' must have a type"
import { TheDriveAI, TheDriveAIError } from "@thedriveai/sdk";

const client = new TheDriveAI({ apiKey: "your-api-key" });

try {
  const result = await client.extract({ file: "document.pdf", schema: mySchema });
} catch (e) {
  if (e instanceof TheDriveAIError) {
    console.log(e.statusCode); // 422
    console.log(e.detail);     // "Schema validation failed: ..."
  }
}

Configuration

client = TheDriveAI(
    api_key="your-api-key",          # Required
    base_url="https://dev.thedrive.ai",  # Default
    timeout=30,                       # Seconds (Python)
)
const client = new TheDriveAI({
  apiKey: "your-api-key",             // Required
  baseUrl: "https://dev.thedrive.ai", // Default
  timeout: 30000,                     // Milliseconds (TypeScript)
});

FAQ

What is The Drive AI?

The Drive AI is an AI-powered workspace for working with documents — upload, organize, search, and understand any file. These developer APIs are a subset of that platform: the file intelligence endpoints we built internally, now available for any developer to use at dev.thedrive.ai.

Why not just send a PDF to ChatGPT or Claude directly?

LLMs are general-purpose text generators. These APIs are purpose-built for document intelligence with an agent architecture that extracts, computes, and verifies. Math is run in a sandboxed calculator (not hallucinated), OCR and vision are combined for proofreading, and every answer includes source citations. You also get typed schemas, confidence scores, and support for 107+ formats — none of which you get from a raw LLM call.

What file formats are supported?

107+ formats including PDF, DOCX, XLSX, PPTX, images (JPG, PNG, HEIC, etc.), video (MP4, MOV, etc.), audio (MP3, WAV, etc.), code files (67 languages), and any URL/website. See the full format list above.

What is the difference between Extract and Analyze?

Extract is the fast path — it pulls literal values from the document (names, dates, amounts, lists). Analyze is the reasoning path — it reads the document, performs multi-step computation, cross-checks numbers, and returns derived answers (e.g., "do line items sum to the total?", "is the contract active?", "days until expiry"). Use Extract when the answer is written in the document. Use Analyze when the answer requires thinking.

Can these APIs process websites?

Yes. Every endpoint accepts a URL instead of a file. The API renders the page in a headless browser (including JavaScript-heavy SPAs), extracts content from the rendered DOM, and processes it identically to a file. You can also enable follow_links for multi-page research across an entire website.

How much does it cost?

The free tier includes 100 credits/month. Extract costs 1 credit/page, Analyze costs 2 credits/page, and Cross-Analyze costs 5 credits/doc + 3 credits/page. Pro is pay-as-you-go at $0.01/credit. See pricing for full details.

Can I use this in my AI agent or RAG pipeline?

Yes — that's a core use case. Use markdown to convert documents for vector embedding and retrieval, or use extract/analyze for structured tool-use responses that your agent can act on directly. The typed JSON output maps cleanly to function call results in agent frameworks like LangChain, CrewAI, or the Anthropic Agent SDK.

What about large documents?

The API handles documents up to 1000+ pages. Large documents are automatically chunked with cross-page table continuity, so tables that span multiple pages are reconstructed correctly. For very large files, use async mode to avoid timeouts.

Is there a rate limit?

Free: 30 requests/minute. Pro: 120 requests/minute. Enterprise: 600 requests/minute. Batch endpoints allow up to 20 files per request.

How is this different from the main Drive AI product?

The Drive AI is a full workspace — upload files, search across them, collaborate with your team. The developer API at dev.thedrive.ai gives you programmatic access to the file intelligence layer underneath. If you want a UI for working with documents, use thedrive.ai. If you want to build document processing into your own app, use these APIs.


Links


License

MIT

About

File intelligence API — extract, analyze, and convert 107+ file types. Python & TypeScript SDKs.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors