Finault Python SDK
Official Python SDK for Finault - The economic proof layer for AI
Installation
pip install finault
Requires Python 3.8+.
Quick Start
Initialize the Client
import finault
client = finault.FinaultClient(api_key="fk_live_...")
Route AI Requests Through Finault
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What is machine learning?"}],
provider_api_key="sk-..." # Your OpenAI API key
)
print(f"Response: {response.content}")
print(f"Cost: ${response.cost}")
print(f"Tokens: {response.tokens}")
print(f"Request ID: {response.request_id}")
LiteLLM Integration
Use Finault with LiteLLM for multi-provider support:
from finault import FinaultLiteLLMCallback
import litellm
# Initialize Finault callback
finault_callback = FinaultLiteLLMCallback(
api_key="fk_live_...",
organization_id="org_123abc"
)
# Route all LiteLLM calls through Finault
litellm.callbacks = [finault_callback]
# Use LiteLLM as normal
response = litellm.completion(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello"}],
api_key="sk-..."
)
# Finault automatically seals the call
print(f"Cost tracked: ${finault_callback.last_seal.cost_usd}")
print(f"Seal ID: {finault_callback.last_seal.seal_id}")
Named Chains
Organize seals into scoped audit trails:
# Create a response with multiple chain memberships
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Analyze sales data"}],
provider_api_key="sk-...",
# Assign to multiple chains for organizational scoping
finault_chains=["product:analytics", "customer:acme-corp"]
)
print(f"Seal belongs to chains: {response.chains}")
# List all active chains
chains = client.chains.list()
for chain in chains:
print(f"{chain.id}: {chain.seal_count} seals")
# Export a specific chain for offline verification
export = client.chains.export("product:analytics", format="jsonl")
with open("audit-trail.jsonl", "w") as f:
f.write(export)
# Verify a chain server-side
result = client.chains.verify("product:analytics")
print(f"Chain valid: {result.valid}")
print(f"Total cost: ${result.total_cost_usd}")
CLI Usage
The Python SDK includes a CLI for common operations:
# Initialize
finault init --api-key fk_live_...
# Create a seal
finault seal create \
--model gpt-4o \
--cost 0.015 \
--provider openai
# List chains
finault chains list
# Export a chain
finault chains export org --format json > audit.json
# Verify a chain
finault chains verify product:analytics
Stream Chat Completions
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a poem about AI"}],
provider_api_key="sk-...",
stream=True
)
for chunk in stream:
print(chunk.delta.get("content", ""), end="", flush=True)
Budget Management
Create a Budget
budget = client.budgets.create(
name="GPT-4 Monthly Budget",
limit=1000.0,
period="monthly"
)
print(f"Budget ID: {budget.id}")
List Budgets
budgets = client.budgets.list()
for budget in budgets:
print(f"{budget.name}: ${budget.spent}/${budget.limit}")
print(f"Utilization: {budget.utilization_percent:.1f}%")
print(f"Remaining: ${budget.remaining}")
Get Budget Details
budget = client.budgets.get("budget_123")
print(f"Status: {budget.status}")
print(f"Alert count: {len(budget.alerts)}")
Cost Anomaly Detection
List Detected Anomalies
anomalies = client.anomalies.list()
for anomaly in anomalies:
print(f"[{anomaly.severity}] {anomaly.description}")
print(f"Variance: {anomaly.percentage_variance:.1f}%")
Filter by Severity
critical_anomalies = client.anomalies.list(severity="critical")
Acknowledge an Anomaly
anomaly = client.anomalies.acknowledge("anomaly_123")
print(f"Acknowledged at: {anomaly.acknowledged_at}")
Financial Close Pack
Generate a Close Pack
pack = client.closepack.generate(period="2026-02")
print(f"Period: {pack.period}")
print(f"Total Spend: ${pack.total_spend}")
print(f"Summary: {pack.summary}")
print(f"Journal Entries: {len(pack.journal_entries)}")
List Previous Close Packs
packs = client.closepack.list()
for pack in packs:
print(f"{pack.period}: ${pack.total_spend} ({pack.status})")
API Key Management
Create an API Key
key = client.keys.create(name="Production Gateway")
print(f"Key ID: {key.id}")
# Note: The full key is only shown once upon creation
List API Keys
keys = client.keys.list()
for key in keys:
print(f"{key.name} (Preview: {key.key_preview})")
Revoke an API Key
client.keys.revoke("key_123")
print("Key revoked successfully")
Dashboard & Insights
Get Overview Metrics
metrics = client.dashboard.overview()
print(f"Total Spend: ${metrics.total_spend}")
print(f"Trend: {metrics.spend_trend:+.1f}%")
print(f"Requests: {metrics.request_count}")
print(f"Avg Cost/Request: ${metrics.average_cost_per_request:.4f}")
print("\nTop Models:")
for model in metrics.top_models:
print(f" {model['name']}: {model['usage']} calls, ${model['cost']}")
Get Insights and Recommendations
insights = client.dashboard.insights()
print("Key Findings:")
for finding in insights.key_findings:
print(f" - {finding}")
print("\nRecommendations:")
for rec in insights.recommendations:
print(f" - {rec}")
System Health & Pricing
Check API Health
health = client.health.status()
print(f"Status: {health.status}")
print(f"Version: {health.version}")
Get Pricing Information
pricing = client.pricing.get()
print("Model Pricing:")
for model, rates in pricing.models.items():
print(f" {model}: ${rates['input']}/1K input, ${rates['output']}/1K output")
Error Handling
from finault import (
FinaultError,
AuthenticationError,
RateLimitError,
ValidationError,
APIError,
)
try:
response = client.chat.completions.create(...)
except AuthenticationError as e:
print(f"Authentication failed: {e.message}")
print(f"Request ID: {e.request_id}")
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after}s")
except ValidationError as e:
print(f"Validation error: {e.message}")
print(f"Field errors: {e.field_errors}")
except APIError as e:
print(f"API error: {e.message}")
print(f"Status: {e.status_code}")
Context Manager
Use the client as a context manager for automatic cleanup:
with finault.FinaultClient(api_key="fk_live_...") as client:
response = client.chat.completions.create(...)
print(response.cost)
Configuration Options
client = finault.FinaultClient(
api_key="fk_live_...",
base_url="https://api.finault.ai", # Custom base URL
timeout=30.0, # Request timeout in seconds
max_retries=3, # Automatic retry attempts for 429/5xx
)
Retry Logic
The SDK automatically retries requests that fail with:
- 429 (Rate Limit)
- 500, 502, 503, 504 (Server Errors)
Retries use exponential backoff starting at 1 second.
Streaming
Chat completions support streaming for real-time token delivery:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[...],
provider_api_key="sk-...",
stream=True
)
for chunk in stream:
if chunk.delta.get("content"):
print(chunk.delta["content"], end="", flush=True)
API Reference
Resources
client.chat.completions.create()- Create a chat completionclient.closepack.generate()- Generate a financial close packclient.closepack.list()- List previous close packsclient.budgets.create()- Create a new budgetclient.budgets.list()- List all budgetsclient.budgets.get()- Get a specific budgetclient.budgets.update()- Update a budgetclient.anomalies.list()- List detected anomaliesclient.anomalies.get()- Get specific anomalyclient.anomalies.acknowledge()- Mark anomaly as acknowledgedclient.keys.create()- Create an API keyclient.keys.list()- List API keysclient.keys.revoke()- Revoke an API keyclient.dashboard.overview()- Get dashboard overviewclient.dashboard.insights()- Get dashboard insightsclient.health.status()- Check API healthclient.pricing.get()- Get pricing information
API Reference
Complete API documentation is available at:
- Docs: https://docs.finault.ai
- SDK Reference: https://docs.finault.ai/sdk/python
- OpenAPI Spec: https://api.finault.ai/openapi.yaml
Support
For issues, questions, or feedback:
- Email: support@finault.ai
- GitHub Issues: https://github.com/finault/finault-python/issues
- Discussions: https://github.com/finault/finault-python/discussions
- Discord: https://discord.gg/finault
License
MIT License - see LICENSE file for details
Metadata
Release files for finault 4.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| finault-4.3.0.tar.gz | 110.4 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| finault-4.3.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 226.8 kB
Release files / finault-4.3.0.tar.gz
| Download URL | finault-4.3.0.tar.gz |
|---|---|
| Size | 110.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ca0b59c440d1ace32ade881334b2fbf95d235028ade38505c25d526800e517c6
|
|
BLAKE2b-256 checksum How to use checksums |
4fde61eaee6826ebfcbe011a607787c44ee026eeea89f57ca09072b3451df519
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.6
|
Release files / finault-4.3.0-py3-none-any.whl
| Download URL | finault-4.3.0-py3-none-any.whl |
|---|---|
| Size | 116.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
22e06ea3a47b0ad43804b630e33aa475bbe47ad1f712298b691019c621fcf345
|
|
BLAKE2b-256 checksum How to use checksums |
bb4295e7b9619d2d892b6e57bd45dd3025ebdd3a2f99c51a67e3fc74c9fb8262
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.6
|