Python SDK for the Pudding API - Document processing and Q&A
Project description
Pudding SDK
A Python SDK for the Pudding API - Document processing and question answering.
Installation
pip install pudding-sdk
Requirements
- Python 3.10+
- httpx
- pydantic >= 2.0
Quick Start
from pudding import PuddingClient
from pudding.exceptions import NotFoundError, ValidationError
# Initialize client
client = PuddingClient(access_token="pk_your_api_key")
# Check API health
health = client.health.check()
print(f"API Status: {health.status}")
# Upload a document
doc = client.documents.upload(file_path="./contract.pdf")
print(f"Uploaded: {doc.id}")
# Ask a question about the document
job = client.jobs.create(
document_id=doc.id,
question="What is the effective date of this contract?"
)
if job.success:
print(f"Answer: {job.result.answer}")
print(f"Confidence: {job.result.confidence}")
for citation in job.result.citations:
print(f" - Page {citation.page}: {citation.quote}")
else:
print(f"Failed: {job.error}")
# List all documents with pagination
docs = client.documents.list(skip=0, limit=10)
print(f"Total documents: {docs.total}")
for doc in docs.items:
print(f" - {doc.filename} ({doc.size_bytes} bytes)")
# List jobs for a specific document
jobs = client.jobs.list(document_id=doc.id)
# Delete a document (also deletes associated jobs)
try:
deleted = client.documents.delete(document_id=doc.id)
print(f"Deleted: {deleted.filename}")
except NotFoundError:
print("Document not found")
Async Support
The SDK provides both synchronous and asynchronous clients:
from pudding import PuddingClient, AsyncPuddingClient
# Synchronous client
client = PuddingClient(access_token="pk_your_api_key")
docs = client.documents.list()
# Asynchronous client
async_client = AsyncPuddingClient(access_token="pk_your_api_key")
docs = await async_client.documents.list()
Context Manager Support
Both clients support context managers for proper resource cleanup:
# Synchronous
with PuddingClient(access_token="pk_your_api_key") as client:
docs = client.documents.list()
# Asynchronous
async with AsyncPuddingClient(access_token="pk_your_api_key") as client:
docs = await client.documents.list()
Configuration
Initialization Options
client = PuddingClient(
access_token="pk_your_api_key", # Required: Your API key
timeout=60.0, # Optional: Request timeout in seconds (default: 1800 for jobs)
max_retries=3, # Optional: Max retries for transient errors (default: 3)
)
Custom Timeout for Jobs
Job creation is a blocking operation that waits for document processing. The default timeout is 1800 seconds (30 minutes):
# Use a custom timeout for the entire client
client = PuddingClient(access_token="...", timeout=3600.0) # 1 hour
API Reference
Health Checks
# Check API health
health = client.health.check()
print(health.status) # "healthy"
print(health.version) # API version
print(health.environment) # Environment name
# Check readiness (includes database status)
ready = client.health.ready()
print(ready.status) # "ready" or "not_ready"
print(ready.database) # "connected" or error message
Documents
# Upload a document from file path
doc = client.documents.upload(file_path="/path/to/document.pdf")
# Upload a document from bytes
with open("document.pdf", "rb") as f:
doc = client.documents.upload(file=f.read(), filename="document.pdf")
# List documents with pagination
doc_list = client.documents.list(skip=0, limit=20)
print(f"Total: {doc_list.total}")
for doc in doc_list.items:
print(f"{doc.id}: {doc.filename}")
# Delete a document
deleted_doc = client.documents.delete(document_id="uuid-string")
Jobs
# Create a job (process document with a question)
job = client.jobs.create(
document_id="uuid-string",
question="What is the total revenue mentioned in this document?"
)
# Access job results
if job.success:
print(job.result.answer)
print(job.result.confidence) # "high", "medium", "low", or "not_found"
for citation in job.result.citations:
print(f"Page {citation.page}: {citation.quote}")
# List all jobs
job_list = client.jobs.list(skip=0, limit=20)
# List jobs for a specific document
job_list = client.jobs.list(document_id="uuid-string")
Exception Handling
The SDK provides a comprehensive exception hierarchy:
from pudding.exceptions import (
PuddingError, # Base exception for all SDK errors
AuthenticationError, # 401: Invalid or missing API key
NotFoundError, # 404: Resource not found
ValidationError, # 400: Invalid request
RateLimitError, # 429: Too many requests
ServerError, # 500: Internal server error
GatewayError, # 502: Upstream service error
TimeoutError, # 504: Request timed out
)
try:
doc = client.documents.upload(file_path="./document.txt")
except ValidationError as e:
print(f"Validation failed: {e.message}") # "Only PDF files are allowed"
except AuthenticationError as e:
print(f"Auth failed: {e.message}")
except PuddingError as e:
print(f"API error ({e.status_code}): {e.message}")
Logging
The SDK uses Python's standard logging module. Configure logging level as needed:
import logging
# Enable debug logging for the SDK
logging.getLogger("pudding").setLevel(logging.DEBUG)
Development
Setup
# Clone the repository
git clone https://github.com/pudding-ai/pudding-sdk.git
cd pudding-sdk
# Install with development dependencies
pip install -e ".[dev]"
Running Tests
pytest
Running Tests with Coverage
pytest --cov=pudding --cov-report=html
Type Checking
mypy src/pudding
Linting
ruff check src/pudding tests
License
MIT License - see LICENSE for details.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file proofpudding-0.1.1.tar.gz.
File metadata
- Download URL: proofpudding-0.1.1.tar.gz
- Upload date:
- Size: 15.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
319abba849c484b93a53437d6f1d47a702a7a98f03cbc885fab630053b0e37d2
|
|
| MD5 |
38eb7db12279d2a8de57a6511a667efc
|
|
| BLAKE2b-256 |
a9457803f43f77dc10a5a4a4f9c7a3a8e47a3e0b8a83b27a9853ba0d96291fc0
|
File details
Details for the file proofpudding-0.1.1-py3-none-any.whl.
File metadata
- Download URL: proofpudding-0.1.1-py3-none-any.whl
- Upload date:
- Size: 29.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f714ac8e21c87944b3e6dc2d069a6a8781c1be8e9b9f5da39fa8712d1a72233c
|
|
| MD5 |
32ea3465a781b627c469ae6a0680c660
|
|
| BLAKE2b-256 |
1da452f83b145169ab1ee3c317a5ceec63ded1fa39265cee25d1cb3f234dd563
|