Skip to main content

Official Python SDK for Contextbase API

Project description

Contextbase Python SDK

Python Version License

The official Python SDK for Contextbase

Installation

pip install contextbase

Quick start

Setup

First, set your API key as an environment variable:

export CONTEXTBASE_API_KEY="your-api-key-here"

Or pass it directly when initializing the client:

from contextbase import Contextbase

client = Contextbase(api_key="your-api-key-here")

Basic usage

Publishing JSON data

from contextbase import Contextbase

cb = Contextbase()

# Publish JSON data
response = cb.publish(
    context_name="my-app",
    component_name="user-analytics", 
    body={"action": "login", "timestamp": "2024-01-15T10:30:00Z"},
    scopes={"user_id": 123}
)

if response.ok:
    print("Data published successfully!")
    print(f"Response: {response.json}")
else:
    print(f"Error: {response.error.message}")

Publishing files

from contextbase import Contextbase, ContextbaseFile

cb = Contextbase()

# Method 1: Use the convenience method
response = cb.publish_file(
    context_name="documents",
    component_name="reports",
    file_path="report.pdf"
)

# Method 2: Create file from path
file = ContextbaseFile.from_path("path/to/your/document.pdf")
response = cb.publish(
    context_name="documents",
    component_name="reports",
    file=file
)

# Method 3: Create from data content
content = "Daily report: All systems operational!"
file = ContextbaseFile.from_data(content, "daily-report.txt")
response = cb.publish(
    context_name="reports",
    component_name="daily",
    file=file
)

# Method 4: Create from binary data
with open("image.png", "rb") as f:
    binary_data = f.read()
file = ContextbaseFile.from_data(binary_data, "screenshot.png")
response = cb.publish(
    context_name="images",
    component_name="screenshots",
    file=file
)

Resolving context

# Basic query
response = client.resolve_context("my-app")

# Query with search term
response = client.resolve_context(
    context_name="my-app",
    query="user login events"
)

# Query with scopes
response = client.resolve_context(
    context_name="my-app",
    scopes={"environment": "production", "date_range": "last_week"}
)

if response.ok:
    print(f"Resolved context response: {response.json}")

Using the decorator

The @publish decorator automatically publishes function results to Contextbase:

For JSON data

from contextbase import publish

@publish(context_name="ml-models", component_name="predictions")
def predict_user_behavior(user_data):
    # Your ML logic here
    prediction = {"user_id": user_data["id"], "likely_to_churn": 0.23}
    return prediction

# Function runs normally, and result is automatically published
result = predict_user_behavior({"id": 123, "activity": "low"})

For file output

# Automatically upload function output as a file
@publish(
    context_name="reports", 
    component_name="daily-summary",
    as_file=True,
    file_name="summary.txt"
)
def generate_daily_report():
    return "Daily Summary: All systems operational!"

# Content is automatically converted to ContextbaseFile and uploaded
report = generate_daily_report()

# Works with binary data too
@publish(
    context_name="images",
    component_name="generated-charts", 
    as_file=True,
    file_name="chart.png"
)
def create_chart():
    # Return binary PNG data
    return generate_png_bytes()

Decorator with error handling

# Raise exceptions on publish failures
@publish(
    context_name="critical-data", 
    component_name="financial-calculations",
    raise_on_error=True
)
def calculate_risk_score(portfolio):
    return {"risk_score": 0.75, "confidence": 0.92}

# Silently continue on publish failures (default)
@publish(
    context_name="analytics", 
    component_name="user-events",
    raise_on_error=False
)
def track_user_action(user_id, action):
    return {"user_id": user_id, "action": action}

Decorator with scopes

@publish(
    context_name="monitoring",
    component_name="system-metrics",
    scopes={"environment": "production", "service": "api"}
)
def collect_metrics():
    return {
        "cpu_usage": 45.2,
        "memory_usage": 67.8,
        "timestamp": "2024-01-15T10:30:00Z"
    }

Advanced usage

Error handling

from contextbase import Contextbase, ContextbaseError

client = Contextbase()

try:
    response = client.publish("context", "component", body={"data": "value"})
    response.raise_for_status()  # Raises ContextbaseError if response failed
    print("Success!")
except ContextbaseError as e:
    print(f"API Error: {e.message}")
    print(f"Status Code: {e.status_code}")
    for error in e.errors:
        print(f"  - {error}")
except Exception as e:
    print(f"Unexpected error: {e}")

Response object methods

response = client.publish("context", "component", body={"data": "value"})

# Check success
if response.ok:  # or response.is_success
    print("Request successful")

# Access response data
data = response.json          # Parsed JSON response
text = response.text          # Raw response text  
headers = response.headers    # Response headers dict

# Dict-like access
value = response.get("key", "default")
if "field" in response:
    field_value = response["field"]

# Error information
if not response.ok:
    error = response.error
    print(f"Error: {error.message}")
    print(f"Details: {error.errors}")

File upload reference

ContextbaseFile class

The ContextbaseFile class provides an interface for file publishing:

from contextbase import ContextbaseFile

# Create from file path
file = ContextbaseFile.from_path("document.pdf")

# Create from string content
file = ContextbaseFile.from_data("Hello World", "greeting.txt")

# Create from binary content  
with open("image.png", "rb") as f:
    binary_data = f.read()
file = ContextbaseFile.from_data(binary_data, "image.png")

# Create with explicit MIME type
file = ContextbaseFile.from_data(
    content="Custom content",
    name="data.custom",
    mime_type="application/custom"
)

# Direct constructor
import base64
file = ContextbaseFile(
    name="file.txt",
    mime_type="text/plain",
    base64_content=base64.b64encode(b"content").decode()
)

# Access file properties
print(file.name)           # "file.txt"
print(file.mime_type)      # "text/plain"
print(file.get_content())  # b"content"
print(file.get_size())     # 7

Supported file types

See documentation

Error reference

ContextbaseError

Raised when the API returns an error response:

try:
    response = client.publish("context", "component", body={})
    response.raise_for_status()
except ContextbaseError as e:
    print(f"Status: {e.status_code}")     # HTTP status code
    print(f"Message: {e.message}")        # Error message
    print(f"Details: {e.errors}")         # List of detailed errors

Development

Running tests

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=contextbase --cov-report=html

# Run specific test file
pytest tests/test_file_upload.py -v

Support

License

This project is licensed under the MIT License - see the LICENSE file 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

contextbase-0.0.2.tar.gz (21.3 kB view details)

Uploaded Source

Built Distribution

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

contextbase-0.0.2-py3-none-any.whl (13.9 kB view details)

Uploaded Python 3

File details

Details for the file contextbase-0.0.2.tar.gz.

File metadata

  • Download URL: contextbase-0.0.2.tar.gz
  • Upload date:
  • Size: 21.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.6

File hashes

Hashes for contextbase-0.0.2.tar.gz
Algorithm Hash digest
SHA256 224ab1caf357d9fdd31c3ac59d85a5c7d5c049bdfcda70cb3d7368d4bb091bf1
MD5 6ba0d8f536632a0e811b86e1ca109f9d
BLAKE2b-256 ad92d2262d492d81184becb7b619d37424bfe4e1d6334fdd2e575fa9b9ec9bd2

See more details on using hashes here.

File details

Details for the file contextbase-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: contextbase-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 13.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.6

File hashes

Hashes for contextbase-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 0ef72cfad7f093eb9ecda942454c2e2fddb5dedb1b5f59f08ff7b7298f8b2025
MD5 235dd3a0f4c9fdc5d20a6eb03b98cfc5
BLAKE2b-256 4c521eefb46b8565dfa2bf48682f9619ea8b2a05b09eadad3c62913d841ea637

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