Skip to main content

The official Python library for the graphor-prd 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

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

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

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}")

# 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())

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")

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.10.0.tar.gz (228.1 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.10.0-py3-none-any.whl (86.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: graphor-0.10.0.tar.gz
  • Upload date:
  • Size: 228.1 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.10.0.tar.gz
Algorithm Hash digest
SHA256 21baa2c983f06cae3355169580e11bca7cfb3b5b4bffb1f7205fbb2dc565fb9c
MD5 e7ff9478ce8a1f99cc29b769323b3032
BLAKE2b-256 c6b4baf53e9256ac721aa2da779dc65a4447919a455b7b762041f09ac2ccea25

See more details on using hashes here.

File details

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

File metadata

  • Download URL: graphor-0.10.0-py3-none-any.whl
  • Upload date:
  • Size: 86.6 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.10.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dbe343b42d05b6c2cebc64d5bc07b50d6ae869dc0be98cad80ff52ddfd495337
MD5 d054ea279b040a3e48d2689163e8c7f4
BLAKE2b-256 07ce01034ea863c854689326de2f811912d331434128c375e2d865cd39927784

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