Skip to main content

The official Python library for the graphor API

Project description

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 graphor import Graphor

client = Graphor()  # Uses GRAPHOR_API_KEY env var

# Upload a document
source = client.sources.upload(file=open("document.pdf", "rb"))
print(f"Uploaded: {source.file_name}")

# Process with advanced parsing
client.sources.parse(
    file_name=source.file_name, 
    partition_method="graphorlm" # Options: basic (Fast), hi_res (Balanced), hi_res_ft (Accurate), mai (VLM), graphorlm (Agentic)
)

# 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
source = client.sources.upload(file=Path("report.pdf"))

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

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

# Upload from YouTube
source = client.sources.upload_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

Certain errors are automatically retried 0 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default.

โš™๏ธ Process Documents

Reprocess documents with different OCR/parsing methods:

# Reprocess with high-resolution parsing
source = client.sources.parse(
    file_name="document.pdf",
    partition_method="hi_res"  # Options: basic, hi_res, hi_res_ft, mai, graphorlm
)

๐Ÿ“– 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
    source = await client.sources.upload(file=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.

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 automatically retried twice with exponential backoff:

# 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.parse(
    file_name="large-document.pdf",
    partition_method="graphorlm"
)

Complete Example

from pathlib import Path
from graphor import Graphor

client = Graphor()

# 1. Upload a document
source = client.sources.upload(file=Path("contract.pdf"))
print(f"โœ… Uploaded: {source.file_name}")

# 2. Process with advanced parsing
processed = client.sources.parse(
    file_name=source.file_name,
    partition_method="hi_res"
)
print(f"โœ… Processed: {processed.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 Install in VS Code

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.upload() Upload a local file ๐Ÿ“–
sources.upload_url() Upload from web URL ๐Ÿ“–
sources.upload_github() Upload from GitHub ๐Ÿ“–
sources.upload_youtube() Upload from YouTube ๐Ÿ“–
sources.parse() 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.

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

graphor-0.20.0.tar.gz (247.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

graphor-0.20.0-py3-none-any.whl (105.4 kB view details)

Uploaded Python 3

File details

Details for the file graphor-0.20.0.tar.gz.

File metadata

  • Download URL: graphor-0.20.0.tar.gz
  • Upload date:
  • Size: 247.7 kB
  • Tags: Source
  • Uploaded using 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}

File hashes

Hashes for graphor-0.20.0.tar.gz
Algorithm Hash digest
SHA256 b8239678500446ea1c7e2ad33b4689ed2b0be49e1038ee365e6f4f529717b90a
MD5 2c3d8adb8f4686c6b0f24bbadd68e728
BLAKE2b-256 c69168738ce89f8bd45c099a7a357961f79ff4a322a86b875d9d4e7dea40000d

See more details on using hashes here.

File details

Details for the file graphor-0.20.0-py3-none-any.whl.

File metadata

  • Download URL: graphor-0.20.0-py3-none-any.whl
  • Upload date:
  • Size: 105.4 kB
  • Tags: Python 3
  • Uploaded using 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}

File hashes

Hashes for graphor-0.20.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1956f50cef841d87939019d52694a625da8b45826800e2d77e8aabd3b402752e
MD5 e2aea4ada423e4ebdabd7fe72e80451d
BLAKE2b-256 98b5495417891177e3bc303d930cd521ca1742f68c94eaf6e1a088a15d238594

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page