-
Notifications
You must be signed in to change notification settings - Fork 1
Client python
Official Python client for ThemisDB - A high-performance multi-model database.
- β Type Hints - Full type annotations (PEP 484)
- β Transaction Support - BEGIN/COMMIT/ROLLBACK with isolation levels
- β LLM Integration - Native support for LLM interactions (v1.4.0+) π
- β
Context Manager - Pythonic
withstatement support - β Multi-Model - Relational, Graph, Vector operations
- β Query Support - AQL (Advanced Query Language)
- β Topology-Aware - Automatic shard routing
- β Batch Operations - Efficient bulk operations
- β Vector Search - Similarity search
- β Retry Logic - Automatic retries
pip install themisdb-clientOr for development:
pip install -e .[dev]from themis import ThemisClient
client = ThemisClient(endpoints=["http://localhost:8080"])
# Basic CRUD
client.put("relational", "users", "user1", {"name": "Alice"})
user = client.get("relational", "users", "user1")
print(user)
# Transactions (NEW!)
tx = client.begin_transaction()
try:
tx.put("relational", "accounts", "acc1", {"balance": 1000})
tx.put("relational", "accounts", "acc2", {"balance": 500})
tx.commit()
except Exception:
tx.rollback()
raiseThemisDB now supports ACID transactions with BEGIN/COMMIT/ROLLBACK semantics.
from themis import ThemisClient
client = ThemisClient(endpoints=["http://localhost:8080"])
# Begin a transaction
tx = client.begin_transaction()
try:
# Perform operations within the transaction
tx.put("relational", "accounts", "acc1", {"balance": 1000})
tx.put("relational", "accounts", "acc2", {"balance": 500})
# Read within transaction
acc1 = tx.get("relational", "accounts", "acc1")
print(acc1) # {"balance": 1000}
# Commit the transaction
tx.commit()
except Exception as error:
# Rollback on error
tx.rollback()
raiseThe recommended way to use transactions in Python is with the with statement:
# Automatically commits on success, rolls back on exception
with client.begin_transaction() as tx:
tx.put("relational", "accounts", "acc1", {"balance": 1000})
tx.put("relational", "accounts", "acc2", {"balance": 500})
acc1 = tx.get("relational", "accounts", "acc1")
print(acc1) # {"balance": 1000}
# Transaction is automatically committed hereIf an exception occurs, the transaction is automatically rolled back:
try:
with client.begin_transaction() as tx:
tx.put("relational", "users", "user1", {"name": "Alice"})
raise ValueError("Something went wrong")
except ValueError:
pass
# Transaction was automatically rolled backThemisDB supports three isolation levels:
-
READ_COMMITTED(default) β Prevents dirty reads. Non-repeatable reads and phantom reads are possible. -
SNAPSHOTβ Provides a consistent snapshot of the database as of transaction start.β οΈ Write-skew and phantom-read anomalies are possible at SNAPSHOT isolation. Two concurrent SNAPSHOT transactions that each read the same data and write disjoint keys can both commit even when their combined effect violates an application invariant (e.g. double-booking, over-withdrawal). UseSERIALIZABLEwhen strict correctness is required. -
SERIALIZABLEβ Full serializability via SSI / predicate locking. Prevents write skew and phantom reads. May abort more transactions and has higher latency than SNAPSHOT.
# Use SNAPSHOT isolation for repeatable reads
# WARNING: write skew and phantom reads are possible at this level
tx = client.begin_transaction(isolation_level="SNAPSHOT")
# Use SERIALIZABLE to prevent write skew and phantom reads
tx = client.begin_transaction(isolation_level="SERIALIZABLE")
try:
user1 = tx.get("relational", "users", "user1")
user2 = tx.get("relational", "users", "user2")
# These reads are from the same snapshot
# even if other transactions modify the data
tx.commit()
except Exception:
tx.rollback()with client.begin_transaction() as tx:
# Execute AQL query within transaction
result = tx.query("FOR user IN users FILTER user.active == true RETURN user")
# Update based on query results
for user in result.items:
user["last_seen"] = "2025-11-20T12:00:00Z"
tx.put("relational", "users", user["id"], user)
# Automatically committeddef transfer_money(client, from_account: str, to_account: str, amount: float):
"""Transfer money between accounts using a transaction."""
with client.begin_transaction(isolation_level="SNAPSHOT") as tx:
# Read both accounts
from_acc = tx.get("relational", "accounts", from_account)
to_acc = tx.get("relational", "accounts", to_account)
if not from_acc or not to_acc:
raise ValueError("Account not found")
if from_acc["balance"] < amount:
raise ValueError("Insufficient funds")
# Update balances
from_acc["balance"] -= amount
to_acc["balance"] += amount
tx.put("relational", "accounts", from_account, from_acc)
tx.put("relational", "accounts", to_account, to_acc)
# Transaction automatically committed
# Usage
transfer_money(client, "alice", "bob", 100.0)ThemisDB v1.8.0-rc1 introduces native LLM integration with support for various models and features like prefix caching, response caching, multi-GPU, and more.
from themis import ThemisClient
client = ThemisClient(endpoints=["http://localhost:8080"])
# Create an LLM interaction
result = client.llm_interaction(
model="gpt-4o",
messages=[
{"role": "user", "content": "Explain MVCC in databases"}
]
)
print(f"Interaction ID: {result.id}")
print(f"Success: {result.success}")# Create interaction with chain-of-thought reasoning
result = client.llm_interaction(
model="llama-3.1",
messages=[
{"role": "system", "content": "You are a database expert"},
{"role": "user", "content": "How does ThemisDB handle transactions?"}
],
reasoning_steps=[
{
"type": "chain_of_thought",
"content": [
"MVCC allows parallel reading/writing",
"Each transaction gets a snapshot",
"Commit checks for conflicts"
]
}
],
metadata={"use_case": "documentation", "version": "1.4.0"}
)# Get a specific interaction
interaction = client.get_llm_interaction("interaction_id_123")
if interaction:
print(f"Model: {interaction.model}")
print(f"Created: {interaction.created_at}")
for msg in interaction.messages:
print(f"{msg.role}: {msg.content}")
if interaction.reasoning_steps:
for step in interaction.reasoning_steps:
print(f"Reasoning ({step.type}): {step.content}")# List all interactions
interactions = client.list_llm_interactions(limit=50, offset=0)
for interaction in interactions:
print(f"{interaction.id}: {interaction.model} - {interaction.created_at}")
# Filter by model
gpt4_interactions = client.list_llm_interactions(model="gpt-4o", limit=10)# Vision model interaction (requires v1.4.0+ with vision support)
result = client.llm_interaction(
model="gpt-4-vision",
messages=[
{
"role": "user",
"content": "What's in this image?",
"image_url": "https://example.com/image.jpg" # Or base64 encoded
}
]
)ThemisClient(
endpoints: list[str],
*,
namespace: str = "default",
timeout: float = 30.0,
max_retries: int = 3,
metadata_endpoint: str | None = None,
metadata_path: str = "/_admin/cluster/topology",
max_workers: int | None = None,
transport: httpx.BaseTransport | None = None
)-
get(model, collection, uuid)- Retrieve an entity -
put(model, collection, uuid, data)- Create/update an entity -
delete(model, collection, uuid)- Delete an entity -
batch_get(model, collection, uuids)- Batch retrieve -
batch_put(model, collection, items)- Batch create/update -
batch_delete(model, collection, uuids)- Batch delete -
query(aql, *, params=None)- Execute AQL query -
vector_search(embedding, top_k=10)- Vector similarity search -
graph_traverse(start_node, max_depth=3)- Graph traversal -
health(endpoint=None)- Health check -
begin_transaction(*, isolation_level="READ_COMMITTED")- Start transaction -
llm_interaction(model, messages, *, reasoning_steps=None, metadata=None)- NEW: Create LLM interaction -
get_llm_interaction(interaction_id)- NEW: Retrieve LLM interaction -
list_llm_interactions(*, model=None, limit=100, offset=0)- NEW: List LLM interactions
-
transaction_id: str- Unique transaction identifier -
is_active: bool- Whether the transaction is active
-
get(model, collection, uuid)- Retrieve within transaction -
put(model, collection, uuid, data)- Update within transaction -
delete(model, collection, uuid)- Delete within transaction -
query(aql, *, params=None)- Query within transaction -
commit()- Commit the transaction -
rollback()- Rollback the transaction
with client.begin_transaction() as tx:
# Operations here
pass
# Automatically commits on success, rolls back on exception# Install with dev dependencies
pip install -e .[dev]
# Run tests
pytest tests/
# Run tests with coverage
pytest --cov=themis tests/Apache-2.0
ThemisDB 1.9.0-beta Β· Home Β· Module-Index Β· GitHub Β· Issues
ThemisDB 1.9.0-beta Β· Home Β· Wiki-Index Β· Module-Index Β· FAQ Β· Quick-Reference Β· GitHub Β· Issues Β· Discussions Β· License
- Batch Operations
- Best Practices
- CRUD Tutorial
- Custom Document Ingestion
- Getting Started Tutorial
- Interactive Examples
- Schema Design
- Video Tutorials
- AQL Reference
- AQL Examples
- AQL Overview
- AQL Feature Roadmap
- AQL Geospatial Guide
- AQL LLM Migration Guide
- AQL API
- AQL Grammar (EBNF)
- AQL Root Overview
- AQL Examples (root)
- API Reference
- API Module README
- OpenAPI Overview
- Client SDK Overview
- SDK Overview
- Operations
- Operations Overview
- Operations Runbook
- Operations Handbook
- ThemisCtl Admin Guide
- Pipeline E2E SOPs
- Deploy Overview
- Docker Overview
- Docker Hub README
- Helm Overview
- Packaging Overview
- Operator Overview
- Security Policy
- Production Hardening Checklist
- Security Hardening Guide
- Encryption Key Management
- Access Control Framework
- Zero Trust Policy
- API Authentication & Authorization
- HSM Production Setup
- PKCS11 Integration
- DSGVO / SOC2 Checklist
- Access Model Runbooks
- Access Model Dashboard
- Maturity Automation Runbook
- Access Review Automation
- Access Model Dashboard
- Access Model Runbooks
- Rights Revocation
- Dr Checklists
- Dr Testing
- Incident Response Playbook
- Incident Response Testing
- GPU Oom Recovery
- Grammar Debugging
- Metrics Scrape Troubleshooting
- Model Swap Procedure
- Quota Tuning
- Subagent Deployment
- Logging Configuration
- Content Model
- Crypto & Keys
- Feature Flags Reference
- Modular Architecture Roadmap
- Modularization Guide
- Module Architecture Index
- PostgreSQL Wire Protocol
- Query Scheduling
- Raft Consensus Design
- Resource Pooling
- Source Directory Guide
- Unified Access Model
- E1 001 Layered Retrieval Design
- E1 002 Ann Abstraction Strategy
- E1 003 Tensor Summary Types
- E1 004 Lora Package Distinction
- E1 005 Model Switch Compatibility
- E1 006 Federated Tensor Summaries
- E2 001 Evaluation Framework Design
- E2 002 Hardware Profile Strategy
- E2 003 Query Planner Routing Model
- E2 004 Approximation Governance Rules
- E2 005 Cross Layer Fallback Confidence Policy
- E3 001 Distributed Tensor Design
- E3 002 Manifest Coordination Strategy
- E3 003 Recovery And Erasure Choice
- E3 004 Tensor Fabric Infrastructure
- Contributing
- Contributing (root)
- Code of Conduct
- Support
- Maintainers
- CTest Guide
- Build Quick Reference
- Developer Wiki Index
- Build / Test / CI
- Module Index
- Branching Strategy
- Disabled Stub Policy
- Docs PR Policy
- GA Promotion Sign Off
- Github Milestones Setup
- Maturity Claim Verification Checklist
- Maturity Evidence Registry
- Merge Gate Bot Config
- Merge Gate Status Live
- Phase 1 Closure Report
- Phase Closure Policy
- Phase Dependency Graph
- Phase3 Enforcement Runbook
- Plugin Submodule Rollback
- PR Version Targeting
- PR Version Targeting Backfill
- Production Ready 2026 Delivery Plan
- Query Module Status
- Readme
- Release Promotion Gate Policy
- Release Validation Checklist
- Security Module 5671 Evidence Summary
- Sharding P6 Residual Risk Acceptance
- Sourcecode Compliance Governance
- Updates Development Status Sign Off
- Wave C Implementation Complete
- Blob Storage
- Cuda
- Ethics Ai
- Exporters
- Huggingface
- Image Analysis
- Importers
- RPC
- Scraper
- Themisdb Ai Watermark Detector
- User Storage Encrypted
- Chimera Architecture
- Chimera Future
- Chimera Readme
- Chimera Roadmap
- Covina Fastapi Ingestion Architecture
- Covina Fastapi Ingestion Future
- Covina Fastapi Ingestion Roadmap
- Vcc Base Architecture
- Vcc Base Future
- Vcc Base Roadmap
- Vcc Clara Ingestion Architecture
- Vcc Clara Ingestion Future
- Vcc Clara Ingestion Roadmap
- Vcc Veritas Architecture
- Vcc Veritas Future
- Vcc Veritas Roadmap
- 01 Hello World
- 02 Todo App
- 03 Contact Manager
- 04 Inventory System
- 05 Time Series Monitor
- 06 Graph Social Network
- 07 Vector Search Documents
- 08 Dms Erp System
- 09 Iot Sensor Network
- 10 Drone Image Analysis
- 11 Blog Wiki
- 12 Expense Tracker
- 13 Recipe Manager
- 14 Ecommerce Catalog
- 15 Event Management
- 16 Kanban Board
- 17 Crm
- 18 Realtime Chat
- 19 Recommendation Engine
- 20 Smart Home
- 21 Coding Platform
- 22 AQL Diagram Tool
- 23 Traveling Salesman
- 24 Moral Philosophy Debates
- API Versioning
- Distributed Sharding
- Feedback Plugins
- Geo
- Gnn
- Image Analysis
- Legal Lora Training
- LLM
- Lora Sync
- Migration
- Nlp
- Performance
- Railway
- Replication
- Rope Visualization
- Sample Product Config
- Security
- Client SDK Overview
- Quickstart
- Sdk Enhancements
- Sdk Implementation Summary
- Test Suite Readme
- Go
- Java
- Javascript
- Php
- Python
- Ruby
- Rust
- Typescript
- 01 Grundlegende Operationen
- 02 AQL Queries
- 03 Graph Daten
- 04 Multimodell Anwendung
- 01 Quickstart Guide
- 02 AQL Referenz Kurzuebersicht
- 03 Datenmodellierung Guide
- 04 Uebungsaufgaben
- 05 Best Practices Guide
- Training Documents
- Training Overview
- 01 Einfuehrung Und Uebersicht
- 02 Datenmodelle Und Architektur
- 03 AQL Abfragesprache
- 04 Installation Und Setup
- 05 Anwendungsbeispiele
- Training Presentations
- Dependencies Readme
- Processmonitor Readme
- Themis.admintools.shared Readme
- Themis.aqlquerybuilder Readme
- Themis.aqlquerybuilder Roadmap
- Themis.auditlogviewer Readme
- Themis.auditlogviewer Roadmap
- Themis.classificationdashboard Readme
- Themis.classificationdashboard Roadmap
- Themis.compliancereports Readme
- Themis.compliancereports Roadmap
- Themis.gisviewer.controlpanel Readme
- Themis.gisviewer.controlpanel Roadmap
- Themis.impactanalysisviewer Readme
- Themis.impactanalysisviewer Roadmap
- Themis.ingestiontool Readme
- Themis.ingestiontool Roadmap
- Themis.keyrotationdashboard Readme
- Themis.keyrotationdashboard Roadmap
- Themis.piimanager Readme
- Themis.piimanager Roadmap
- Themis.retentionmanager Readme
- Themis.retentionmanager Roadmap
- Themis.sagaverifier Readme
- Themis.sagaverifier Roadmap
- Themis.usbadmintool Readme
- Themis.usbadmintool Roadmap
- CI Readme
- CI Roadmap
- Compiler Diagnostics Readme
- Compiler Diagnostics Roadmap
- Completion Readme
- Copilot Ollama Router Readme
- Copilot Ollama Router Roadmap
- Gnn Readme
- Gnn Roadmap
- Rope Visualizer Readme
- Rope Visualizer Roadmap
- Tco Calculator Readme
- Tco Calculator Roadmap
- Tests Readme
- Tests Roadmap
- Themis Config Wx Readme
- Themis Docs Builder Readme
- Wikipedia Ingestion Readme