Skip to main content

Graphor Python SDK

PyPI version Python 3.9+

The official Python SDK for the Graphor API. Build intelligent document applications with ease.

Features:

  • 📄 Document Ingestion — Upload files, web pages, GitHub repos, and YouTube videos
  • 💬 Document Chat — Ask questions with conversational memory
  • 📊 Structured Extraction — Extract data using JSON Schema
  • 🔍 Semantic Search — Retrieve relevant chunks for custom RAG pipelines
  • ⚡ Async Support — Full async/await support with AsyncGraphor
  • 🔒 Type Safety — Complete type definitions for all params and responses

Documentation

📚 Full documentation: docs.graphorlm.com/sdk/overview

Installation

pip install graphor

For better async performance with aiohttp:

pip install graphor[aiohttp]

Quick Start

from pathlib import Path

from graphor import Graphor

client = Graphor()  # Uses GRAPHOR_API_KEY env var

# Upload a document; it is parsed in the background
build = client.sources.ingest_file(
    file=Path("document.pdf"),
    method="agentic",  # Options: fast, balanced, accurate, agentic, auto
)

# Check the build
status = client.sources.get_build_status(build.build_id)
print(f"{status.file_name}: {status.status}")

# Ask questions about your documents
response = client.sources.ask(question="What are the main topics?")
print(f"Answer: {response.answer}")

Authentication

Set your API key as an environment variable (recommended):

export GRAPHOR_API_KEY="grlm_your_api_key_here"
from graphor import Graphor

client = Graphor()  # Automatically uses GRAPHOR_API_KEY

Or pass it directly:

client = Graphor(api_key="grlm_your_api_key_here")

Core Features

📄 Upload Documents

Upload files, web pages, GitHub repositories, or YouTube videos:

from pathlib import Path
from graphor import Graphor

client = Graphor()

# Upload a local file
build = client.sources.ingest_file(file=Path("report.pdf"))

# Upload from URL
source = client.sources.ingest_url(url="https://example.com/article")

# Upload from GitHub
source = client.sources.ingest_github(url="https://github.com/org/repo")

# Upload from YouTube
source = client.sources.ingest_youtube(url="https://youtube.com/watch?v=...")

Supported formats: PDF, DOCX, TXT, MD, HTML, CSV, XLSX, PNG, JPG, MP3, MP4, and more.

📖 Full upload documentation

Large files work the same way: above 30 MiB, ingest_file sends the file in chunks that resume after a network error, then returns the same build_id. A large upload can take a while, and timeout applies to each request rather than to the whole upload.

⚙️ Process Documents

Reprocess documents with different OCR/parsing methods:

# Reprocess with high-resolution parsing
source = client.sources.reprocess(
    file_id="<file_id>",
    method="balanced",  # Options: fast, balanced, accurate, agentic, auto
)

📖 Full processing documentation

💬 Chat with Documents

Ask questions about your documents with conversational memory:

# Ask a question
response = client.sources.ask(
    question="What are the key findings?"
)
print(response.answer)

# Follow-up question (maintains context)
follow_up = client.sources.ask(
    question="Can you elaborate on the first point?",
    conversation_id=response.conversation_id
)
print(follow_up.answer)

# Scope to specific documents
response = client.sources.ask(
    question="Compare these two reports",
    file_names=["report-2023.pdf", "report-2024.pdf"]
)

📖 Full chat documentation

📊 Extract Structured Data

Extract structured information using JSON Schema:

result = client.sources.extract(
    file_names=["invoice.pdf"],
    user_instruction="Extract invoice details",
    output_schema={
        "type": "object",
        "properties": {
            "invoice_number": {"type": "string"},
            "total_amount": {"type": "number"},
            "line_items": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "description": {"type": "string"},
                        "amount": {"type": "number"}
                    }
                }
            }
        }
    }
)

print(result.structured_output)
# {"invoice_number": "INV-001", "total_amount": 1500.00, "line_items": [...]}

📖 Full extraction documentation

🔍 Retrieve Chunks (Prebuilt RAG)

Build custom RAG pipelines with semantic search:

# Retrieve relevant chunks
result = client.sources.retrieve_chunks(
    query="What are the payment terms?"
)

for chunk in result.chunks:
    print(f"[{chunk.file_name}, Page {chunk.page_number}]")
    print(f"Score: {chunk.score:.2f}")
    print(chunk.text)
    print("---")

# Use with your preferred LLM
context = "\n".join([c.text for c in result.chunks])
# Pass context to OpenAI, Anthropic, etc.

📖 Full RAG documentation

📋 Manage Sources

List, inspect, and delete documents:

# List all sources
sources = client.sources.list()
for source in sources:
    print(f"{source.file_name}: {source.status}")

# Get document elements
elements = client.sources.load_elements(
    file_name="document.pdf",
    page=1,
    page_size=50
)

# Delete a source
result = client.sources.delete(file_name="document.pdf")

Async Usage

Use AsyncGraphor for async/await support:

import asyncio
from graphor import AsyncGraphor

async def main():
    client = AsyncGraphor()
    
    # All methods support await
    build = await client.sources.ingest_file(file=("notes.txt", b"content"))
    response = await client.sources.ask(question="Summarize this document")
    
    print(response.answer)

asyncio.run(main())

With aiohttp (Better Concurrency)

from graphor import AsyncGraphor, DefaultAioHttpClient

async def main():
    async with AsyncGraphor(http_client=DefaultAioHttpClient()) as client:
        sources = await client.sources.list()
        print(f"Found {len(sources)} sources")

asyncio.run(main())

File uploads

Request parameters that correspond to file uploads can be passed as bytes, or a PathLike instance or a tuple of (filename, contents, media type).

from pathlib import Path
from graphor import Graphor

client = Graphor()

client.sources.ingest_file(
    file=Path("/path/to/file"),
)

The async client uses the exact same interface. If you pass a PathLike instance, the file contents will be read asynchronously automatically.

Files above 30 MiB are uploaded in chunks, so a path or an open file is never read into memory whole. If the upload cannot finish, ingest_file raises graphor.UploadError; when its build_id is set, the file was sent and its build may still complete, so check that build before uploading again.

Error Handling

import graphor
from graphor import Graphor

client = Graphor()

try:
    response = client.sources.ask(question="What is this about?")
except graphor.AuthenticationError:
    print("Invalid API key")
except graphor.NotFoundError:
    print("Resource not found")
except graphor.RateLimitError:
    print("Rate limited - back off and retry")
except graphor.APIConnectionError:
    print("Network error")
except graphor.APIStatusError as e:
    print(f"API error: {e.status_code}")
Status Code Error Type
400 BadRequestError
401 AuthenticationError
403 PermissionDeniedError
404 NotFoundError
422 UnprocessableEntityError
429 RateLimitError
≥500 InternalServerError
N/A APIConnectionError

Configuration

Retries

Requests are not retried by default (max_retries=0). With retries enabled, connection errors, 408, 409, 429 and 5xx responses are retried with a short exponential backoff. Large file uploads retry their own chunks regardless of this setting.

# Configure default retries
client = Graphor(max_retries=5)

# Or per-request
client.with_options(max_retries=3).sources.ask(question="...")

Timeouts

Default timeout is 60 seconds:

# Configure default timeout
client = Graphor(timeout=120.0)

# Or per-request
client.with_options(timeout=300.0).sources.reprocess(
    file_id="<file_id>",
    method="agentic",
)

Complete Example

from pathlib import Path
from graphor import Graphor

client = Graphor()

# 1. Upload a document, parsed in the background
build = client.sources.ingest_file(file=Path("contract.pdf"), method="balanced")

# 2. Check the build
status = client.sources.get_build_status(build.build_id)
print(f"✅ {status.file_name}: {status.status}")
source = status

# 3. Ask questions
response = client.sources.ask(
    question="What are the key terms of this contract?",
    file_names=[source.file_name]
)
print(f"📝 Answer: {response.answer}")

# 4. Extract structured data
extracted = client.sources.extract(
    file_names=[source.file_name],
    user_instruction="Extract contract details",
    output_schema={
        "type": "object",
        "properties": {
            "parties": {"type": "array", "items": {"type": "string"}},
            "effective_date": {"type": "string"},
            "termination_date": {"type": "string"},
            "total_value": {"type": "number"}
        }
    }
)
print(f"📊 Extracted: {extracted.structured_output}")

# 5. Build custom RAG
chunks = client.sources.retrieve_chunks(
    query="payment obligations",
    file_names=[source.file_name]
)
print(f"🔍 Found {chunks.total} relevant chunks")

MCP Server

Use the Graphor MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.

Add to Cursor

Or manually add it to your MCP client's configuration:

{
  "mcpServers": {
    "graphor_api": {
      "command": "npx",
      "args": ["-y", "graphor-mcp@latest"],
      "env": {
        "GRAPHOR_API_KEY": "grlm_your_api_key_here"
      }
    }
  }
}

Note: You may need to set environment variables in your MCP client.

Remote MCP Server (Web Apps & Agentic Workflows)

For web-based AI clients (e.g. Claude.ai) or agentic frameworks (e.g. LangChain, CrewAI) that cannot run local npx processes, use the hosted remote MCP server. Authentication is handled via OAuth — a browser window will open for you to log in.

https://mcp.graphor.workers.dev/sse

Web apps (e.g. Claude.ai) — in Claude.ai, go to Settings > Connectors > Add custom connector, fill in the name and the remote MCP server URL. You will be redirected to log in through the OAuth flow:

https://mcp.graphor.workers.dev/sse

Desktop clients (e.g. Claude Desktop) — use mcp-remote as a local proxy:

{
  "mcpServers": {
    "graphor_api": {
      "command": "npx",
      "args": ["mcp-remote", "https://mcp.graphor.workers.dev/sse"]
    }
  }
}

Agentic workflows (e.g. LangChain) — connect via SSE transport:

from langchain_mcp_adapters.client import MultiServerMCPClient

async with MultiServerMCPClient(
    {
        "graphor": {
            "url": "https://mcp.graphor.workers.dev/sse",
            "transport": "sse",
        }
    }
) as client:
    tools = client.get_tools()
    # Use tools with your LangChain agent

See the MCP Server README for more details.

API Reference

Sources

Method Description Docs
sources.ingest_file() Upload a local file, of any size up to the limit 📖
sources.ingest_url() Upload from web URL 📖
sources.ingest_github() Upload from GitHub 📖
sources.ingest_youtube() Upload from YouTube 📖
sources.reprocess() Reprocess with different method 📖
sources.list() List all sources 📖
sources.delete() Delete a source 📖
sources.load_elements() Get parsed elements 📖

Chat & AI

Method Description Docs
sources.ask() Ask questions about documents 📖
sources.extract() Extract structured data 📖
sources.retrieve_chunks() Retrieve chunks for RAG 📖

Requirements

  • Python 3.9+

Contributing

See CONTRIBUTING.md for guidelines.

License

MIT License - see LICENSE for details.

Metadata

Release files for graphor 0.27.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for graphor 0.27.0
File Size Uploaded Provenance Actions
graphor-0.27.0.tar.gz 271.4 kB Without provenance Details for graphor-0.27.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for graphor 0.27.0
File Interpreter ABI Platform Actions
graphor-0.27.0-py3-none-any.whl Python 3 none any Details for graphor-0.27.0-py3-none-any.whl

Total release size: 395.0 kB

Release files / graphor-0.27.0.tar.gz

Download URL graphor-0.27.0.tar.gz
Size 271.4 kB
Tags Source
SHA-256 checksum
How to use checksums
7881d0942f0e55cd7def895b69b376a512772cd934b6d7558b17ca63f542f297
BLAKE2b-256 checksum
How to use checksums
d548604c0aa82f798cdba2e44855015ef9ddb5f6ecb74dfaec4e78f1d336b580
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / graphor-0.27.0-py3-none-any.whl

Download URL graphor-0.27.0-py3-none-any.whl
Size 123.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eaf8b89435684c8c4e9ceb52bdfeebd0f037bb280be87be131efb17324850ab5
BLAKE2b-256 checksum
How to use checksums
b57645f30ef643f46f5b3c2e2f6a92facd3f4d0a600f9ddd824c81db1c940f7a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for graphor 0.27.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.27.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page