# Contextbase Python SDK
[](https://python.org)
[](LICENSE)
The official Python SDK for [Contextbase](https://contextbase.dev)
## Installation
```bash
pip install contextbase
```
## Quick start
### Setup
First, set your API key as an environment variable:
```bash
export CONTEXTBASE_API_KEY="your-api-key-here"
```
Or pass it directly when initializing the client:
```python
from contextbase import Contextbase
client = Contextbase(api_key="your-api-key-here")
```
### Basic usage
#### Publishing JSON data
```python
from contextbase import Contextbase
cb = Contextbase()
# Publish JSON data
response = cb.publish(
context_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
```python
from contextbase import Contextbase, ContextbaseFile
cb = Contextbase()
# Method 1: Use the convenience method
response = cb.publish_file(
context_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="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="daily_reports",
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="screenshots",
file=file
)
```
#### Resolving context
```python
# 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
```python
from contextbase import publish
@publish(context_name="ml-models")
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
```python
# Automatically upload function output as a file
@publish(
context_name="daily_reports",
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="generated_charts",
as_file=True,
file_name="chart.png"
)
def create_chart():
# Return binary PNG data
return generate_png_bytes()
```
#### Decorator with error handling
```python
# Raise exceptions on publish failures
@publish(
context_name="financial_calculations",
scopes=lambda result: {"category": "critical" if result["risk_score"] > 0.70 else "normal"},
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="user_events",
raise_on_error=False
)
def track_user_action(user_id, action):
return {"user_id": user_id, "action": action}
```
#### Decorator with scopes
```python
@publish(
context_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
```python
from contextbase import Contextbase, ContextbaseError
client = Contextbase()
try:
response = client.publish("context", 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
```python
response = client.publish("context", 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:
```python
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](https://docs.contextbase.dev)
## Error reference
### ContextbaseError
Raised when the API returns an error response:
```python
try:
response = client.publish("context", 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
```bash
# 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
- **Documentation**: [https://docs.contextbase.dev](https://docs.contextbase.dev)
- **Issues**: [GitHub Issues](https://github.com/contextbaseco/python-sdk/issues)
- **Email**: support@contextbase.dev
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
Raw data
{
"_id": null,
"home_page": null,
"name": "contextbase",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "contextbase, api, sdk, context, management",
"author": null,
"author_email": "Contextbase <support@contextbase.dev>",
"download_url": "https://files.pythonhosted.org/packages/4f/f1/5581ae7fd5d668f6ada9d9b1a718f0dc429bd1d079a66910fbffe903211e/contextbase-0.0.4.tar.gz",
"platform": null,
"description": "# Contextbase Python SDK\n\n[](https://python.org)\n[](LICENSE)\n\nThe official Python SDK for [Contextbase](https://contextbase.dev)\n\n## Installation\n\n```bash\npip install contextbase\n```\n\n## Quick start\n\n### Setup\n\nFirst, set your API key as an environment variable:\n\n```bash\nexport CONTEXTBASE_API_KEY=\"your-api-key-here\"\n```\n\nOr pass it directly when initializing the client:\n\n```python\nfrom contextbase import Contextbase\n\nclient = Contextbase(api_key=\"your-api-key-here\")\n```\n\n### Basic usage\n\n#### Publishing JSON data\n\n```python\nfrom contextbase import Contextbase\n\ncb = Contextbase()\n\n# Publish JSON data\nresponse = cb.publish(\n context_name=\"user_analytics\",\n body={\"action\": \"login\", \"timestamp\": \"2024-01-15T10:30:00Z\"},\n scopes={\"user_id\": 123}\n)\n\nif response.ok:\n print(\"Data published successfully!\")\n print(f\"Response: {response.json}\")\nelse:\n print(f\"Error: {response.error.message}\")\n```\n\n#### Publishing files\n\n```python\nfrom contextbase import Contextbase, ContextbaseFile\n\ncb = Contextbase()\n\n# Method 1: Use the convenience method\nresponse = cb.publish_file(\n context_name=\"reports\",\n file_path=\"report.pdf\"\n)\n\n# Method 2: Create file from path\nfile = ContextbaseFile.from_path(\"path/to/your/document.pdf\")\nresponse = cb.publish(\n context_name=\"reports\",\n file=file\n)\n\n# Method 3: Create from data content\ncontent = \"Daily report: All systems operational!\"\nfile = ContextbaseFile.from_data(content, \"daily-report.txt\")\nresponse = cb.publish(\n context_name=\"daily_reports\",\n file=file\n)\n\n# Method 4: Create from binary data\nwith open(\"image.png\", \"rb\") as f:\n binary_data = f.read()\nfile = ContextbaseFile.from_data(binary_data, \"screenshot.png\")\nresponse = cb.publish(\n context_name=\"screenshots\",\n file=file\n)\n```\n\n\n\n\n#### Resolving context\n\n```python\n# Basic query\nresponse = client.resolve_context(\"my-app\")\n\n# Query with search term\nresponse = client.resolve_context(\n context_name=\"my-app\",\n query=\"user login events\"\n)\n\n# Query with scopes\nresponse = client.resolve_context(\n context_name=\"my-app\",\n scopes={\"environment\": \"production\", \"date_range\": \"last_week\"}\n)\n\nif response.ok:\n print(f\"Resolved context response: {response.json}\")\n```\n\n### Using the decorator\n\nThe `@publish` decorator automatically publishes function results to Contextbase:\n\n#### For JSON data\n\n```python\nfrom contextbase import publish\n\n@publish(context_name=\"ml-models\")\ndef predict_user_behavior(user_data):\n # Your ML logic here\n prediction = {\"user_id\": user_data[\"id\"], \"likely_to_churn\": 0.23}\n return prediction\n\n# Function runs normally, and result is automatically published\nresult = predict_user_behavior({\"id\": 123, \"activity\": \"low\"})\n```\n\n#### For file output\n\n```python\n# Automatically upload function output as a file\n@publish(\n context_name=\"daily_reports\", \n as_file=True,\n file_name=\"summary.txt\"\n)\ndef generate_daily_report():\n return \"Daily Summary: All systems operational!\"\n\n# Content is automatically converted to ContextbaseFile and uploaded\nreport = generate_daily_report()\n\n# Works with binary data too\n@publish(\n context_name=\"generated_charts\",\n as_file=True,\n file_name=\"chart.png\"\n)\ndef create_chart():\n # Return binary PNG data\n return generate_png_bytes()\n```\n\n#### Decorator with error handling\n\n```python\n# Raise exceptions on publish failures\n@publish(\n context_name=\"financial_calculations\", \n scopes=lambda result: {\"category\": \"critical\" if result[\"risk_score\"] > 0.70 else \"normal\"},\n raise_on_error=True\n)\ndef calculate_risk_score(portfolio):\n return {\"risk_score\": 0.75, \"confidence\": 0.92}\n\n# Silently continue on publish failures (default)\n@publish(\n context_name=\"user_events\", \n raise_on_error=False\n)\ndef track_user_action(user_id, action):\n return {\"user_id\": user_id, \"action\": action}\n```\n\n#### Decorator with scopes\n\n```python\n@publish(\n context_name=\"system_metrics\",\n scopes={\"environment\": \"production\", \"service\": \"api\"}\n)\ndef collect_metrics():\n return {\n \"cpu_usage\": 45.2,\n \"memory_usage\": 67.8,\n \"timestamp\": \"2024-01-15T10:30:00Z\"\n }\n```\n\n\n## Advanced usage\n\n### Error handling\n\n```python\nfrom contextbase import Contextbase, ContextbaseError\n\nclient = Contextbase()\n\ntry:\n response = client.publish(\"context\", body={\"data\": \"value\"})\n response.raise_for_status() # Raises ContextbaseError if response failed\n print(\"Success!\")\nexcept ContextbaseError as e:\n print(f\"API Error: {e.message}\")\n print(f\"Status Code: {e.status_code}\")\n for error in e.errors:\n print(f\" - {error}\")\nexcept Exception as e:\n print(f\"Unexpected error: {e}\")\n```\n\n### Response object methods\n\n```python\nresponse = client.publish(\"context\", body={\"data\": \"value\"})\n\n# Check success\nif response.ok: # or response.is_success\n print(\"Request successful\")\n\n# Access response data\ndata = response.json # Parsed JSON response\ntext = response.text # Raw response text \nheaders = response.headers # Response headers dict\n\n# Dict-like access\nvalue = response.get(\"key\", \"default\")\nif \"field\" in response:\n field_value = response[\"field\"]\n\n# Error information\nif not response.ok:\n error = response.error\n print(f\"Error: {error.message}\")\n print(f\"Details: {error.errors}\")\n```\n\n## File upload reference\n\n### ContextbaseFile class\n\nThe `ContextbaseFile` class provides an interface for file publishing:\n\n```python\nfrom contextbase import ContextbaseFile\n\n# Create from file path\nfile = ContextbaseFile.from_path(\"document.pdf\")\n\n# Create from string content\nfile = ContextbaseFile.from_data(\"Hello World\", \"greeting.txt\")\n\n# Create from binary content \nwith open(\"image.png\", \"rb\") as f:\n binary_data = f.read()\nfile = ContextbaseFile.from_data(binary_data, \"image.png\")\n\n# Create with explicit MIME type\nfile = ContextbaseFile.from_data(\n content=\"Custom content\",\n name=\"data.custom\",\n mime_type=\"application/custom\"\n)\n\n# Direct constructor\nimport base64\nfile = ContextbaseFile(\n name=\"file.txt\",\n mime_type=\"text/plain\",\n base64_content=base64.b64encode(b\"content\").decode()\n)\n\n# Access file properties\nprint(file.name) # \"file.txt\"\nprint(file.mime_type) # \"text/plain\"\nprint(file.get_content()) # b\"content\"\nprint(file.get_size()) # 7\n```\n\n### Supported file types\nSee [documentation](https://docs.contextbase.dev)\n\n\n## Error reference\n\n### ContextbaseError\n\nRaised when the API returns an error response:\n\n```python\ntry:\n response = client.publish(\"context\", body={})\n response.raise_for_status()\nexcept ContextbaseError as e:\n print(f\"Status: {e.status_code}\") # HTTP status code\n print(f\"Message: {e.message}\") # Error message\n print(f\"Details: {e.errors}\") # List of detailed errors\n```\n\n\n## Development\n\n### Running tests\n\n```bash\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run tests with coverage\npytest --cov=contextbase --cov-report=html\n\n# Run specific test file\npytest tests/test_file_upload.py -v\n```\n\n## Support\n\n- **Documentation**: [https://docs.contextbase.dev](https://docs.contextbase.dev)\n- **Issues**: [GitHub Issues](https://github.com/contextbaseco/python-sdk/issues)\n- **Email**: support@contextbase.dev\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n",
"bugtrack_url": null,
"license": null,
"summary": "Official Python SDK for Contextbase API",
"version": "0.0.4",
"project_urls": {
"Documentation": "https://docs.contextbase.dev",
"Homepage": "https://docs.contextbase.dev",
"Issues": "https://github.com/contextbase/python-sdk/issues",
"Repository": "https://github.com/contextbase/python-sdk"
},
"split_keywords": [
"contextbase",
" api",
" sdk",
" context",
" management"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "76cbdfb144499b8185e96bde5ae64aa11bf98187a619f7c128c0664f30a5cc81",
"md5": "c46f7f4815e779bc803bad3362380438",
"sha256": "cb858c998ea3d41d030cb39d4c40c8f30fa4472a3f15c0040ccd446e51686fb4"
},
"downloads": -1,
"filename": "contextbase-0.0.4-py3-none-any.whl",
"has_sig": false,
"md5_digest": "c46f7f4815e779bc803bad3362380438",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 13911,
"upload_time": "2025-08-18T01:59:48",
"upload_time_iso_8601": "2025-08-18T01:59:48.112773Z",
"url": "https://files.pythonhosted.org/packages/76/cb/dfb144499b8185e96bde5ae64aa11bf98187a619f7c128c0664f30a5cc81/contextbase-0.0.4-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "4ff15581ae7fd5d668f6ada9d9b1a718f0dc429bd1d079a66910fbffe903211e",
"md5": "3e7dbc2e11e3876ff8ab7d7b5d2bc7cf",
"sha256": "6561a09ea4b46a700f071e1b51269df395d36b3bbd6c9df7876344c40b4c7581"
},
"downloads": -1,
"filename": "contextbase-0.0.4.tar.gz",
"has_sig": false,
"md5_digest": "3e7dbc2e11e3876ff8ab7d7b5d2bc7cf",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 21251,
"upload_time": "2025-08-18T01:59:49",
"upload_time_iso_8601": "2025-08-18T01:59:49.330488Z",
"url": "https://files.pythonhosted.org/packages/4f/f1/5581ae7fd5d668f6ada9d9b1a718f0dc429bd1d079a66910fbffe903211e/contextbase-0.0.4.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-18 01:59:49",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "contextbase",
"github_project": "python-sdk",
"github_not_found": true,
"lcname": "contextbase"
}