Contex Python SDK
Official Python client for Contex - Semantic context routing for AI agents.
Installation
pip install contex-python
Quick Start
Async Client (Recommended)
from contex import ContexAsyncClient
async def main():
async with ContexAsyncClient(
url="http://localhost:8001",
api_key="ck_your_api_key_here"
) as client:
# Publish data
await client.publish(
project_id="my-app",
data_key="coding_standards",
data={
"style": "PEP 8",
"max_line_length": 100,
"quotes": "double"
}
)
# Register agent
response = await client.register_agent(
agent_id="code-reviewer",
project_id="my-app",
data_needs=[
"coding standards and style guidelines",
"testing requirements and coverage goals"
]
)
print(f"Matched needs: {response.matched_needs}")
print(f"Notification channel: {response.notification_channel}")
# Query for data
results = await client.query(
project_id="my-app",
query="authentication configuration"
)
for result in results.results:
print(f"{result.data_key}: {result.data}")
import asyncio
asyncio.run(main())
Sync Client
from contex import ContexClient
client = ContexClient(
url="http://localhost:8001",
api_key="ck_your_api_key_here"
)
# Publish data
client.publish(
project_id="my-app",
data_key="config",
data={"env": "prod", "debug": False}
)
# Register agent
response = client.register_agent(
agent_id="my-agent",
project_id="my-app",
data_needs=["configuration", "secrets"]
)
Features
- ✅ Async & Sync: Both async and synchronous interfaces
- ✅ Type Hints: Full type annotations with Pydantic models
- ✅ Error Handling: Comprehensive exception hierarchy
- ✅ Retry Logic: Automatic retries with exponential backoff
- ✅ Rate Limiting: Built-in rate limit handling
- ✅ Authentication: API key authentication support
API Reference
Client Initialization
client = ContexAsyncClient(
url="http://localhost:8001", # Contex server URL
api_key="ck_...", # API key for authentication
timeout=30.0, # Request timeout in seconds
max_retries=3, # Maximum number of retries
)
Publishing Data
await client.publish(
project_id="my-app", # Project identifier
data_key="unique-key", # Unique key for this data
data={"any": "json"}, # Data payload
data_format="json", # Format: json, yaml, toml, text
metadata={"tags": ["prod"]}, # Optional metadata
)
Registering Agents
response = await client.register_agent(
agent_id="agent-1", # Unique agent ID
project_id="my-app", # Project ID
data_needs=["config", "secrets"], # Data needs (natural language)
notification_method="redis", # redis or webhook
webhook_url="https://...", # Optional webhook URL
webhook_secret="secret", # Optional webhook secret
last_seen_sequence="0", # Last seen sequence
)
Querying Data
results = await client.query(
project_id="my-app",
query="authentication settings",
max_results=10,
)
for result in results.results:
print(f"{result.data_key}: {result.similarity_score}")
API Key Management
# Create API key
key_response = await client.create_api_key(name="production-key")
print(f"API Key: {key_response.key}") # Store this securely!
# List keys
keys = await client.list_api_keys()
# Revoke key
await client.revoke_api_key(key_id="key-123")
Health Checks
# Comprehensive health
health = await client.health()
# Readiness check
ready = await client.ready()
# Rate limit status
rate_limit = await client.rate_limit_status()
print(f"Remaining: {rate_limit.remaining}/{rate_limit.limit}")
Exception Handling
from contex import (
ContexError,
AuthenticationError,
RateLimitError,
ValidationError,
NotFoundError,
ServerError,
)
try:
await client.publish(...)
except AuthenticationError:
print("Invalid API key")
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after} seconds")
except ValidationError as e:
print(f"Validation error: {e}")
except NotFoundError:
print("Resource not found")
except ServerError:
print("Server error")
except ContexError as e:
print(f"Contex error: {e}")
Development
Setup
cd sdk/python
pip install -e ".[dev]"
Running Tests
pytest
Code Formatting
black contex/
ruff check contex/
mypy contex/
Examples
See the examples directory for more usage examples:
basic_usage.py- Basic publish and queryagent_registration.py- Agent registration and updateswebhook_agent.py- Webhook-based agenterror_handling.py- Error handling patternsbatch_operations.py- Batch publishing
License
MIT License - see LICENSE for details.
Links
Metadata
Release files for contex-python 0.3.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| contex_python-0.3.4.tar.gz | 19.3 kB | Without provenance | Details for contex_python-0.3.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| contex_python-0.3.4-py3-none-any.whl | Python 3 | none | any | Details for contex_python-0.3.4-py3-none-any.whl |
Total release size: 30.6 kB
Release files / contex_python-0.3.4.tar.gz
| Download URL | contex_python-0.3.4.tar.gz |
|---|---|
| Size | 19.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a33c1904d6b64d4d95cf29687e413c369971499f12903b912d4078ba1f188831
|
|
BLAKE2b-256 checksum How to use checksums |
c660a12f10e80cd309b5509b61141b152f685e93e0787997f36aee529daa0eef
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|
Release files / contex_python-0.3.4-py3-none-any.whl
| Download URL | contex_python-0.3.4-py3-none-any.whl |
|---|---|
| Size | 11.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
dd64a08e1d07a072796bda5ef0158ad3d06b2a4e0ef84b5ac72028252c5f7e22
|
|
BLAKE2b-256 checksum How to use checksums |
266c454a0e347bdc7dc9e7c5f89e07cb8f073fcac2d691bbe7751a0f33709a03
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.14
|
Security for contex-python 0.3.4
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.