Official Python SDK for Finault AI Cost Governance API
Project description
Finault Python SDK
Official Python SDK for Finault - AI Cost Governance Platform
Installation
pip install finault
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}")
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
Support
For issues, questions, or feedback:
- Email: support@finault.ai
- Docs: https://docs.finault.ai
- Issues: https://github.com/finault/finault-python/issues
License
MIT License - see LICENSE file for details
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file finault-1.0.0.tar.gz.
File metadata
- Download URL: finault-1.0.0.tar.gz
- Upload date:
- Size: 82.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cac901f3d9cd4d604dffd37d4b1d28063ee5e0fbedf55457fafb12d481ba9358
|
|
| MD5 |
4891939a56ec3921a44f954a3aa168a1
|
|
| BLAKE2b-256 |
ff7421d5a4051b7ff540e6bb97d6a74dd7584661035425fcddfba0aae056b626
|
File details
Details for the file finault-1.0.0-py3-none-any.whl.
File metadata
- Download URL: finault-1.0.0-py3-none-any.whl
- Upload date:
- Size: 86.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
efdcb2ea61f56ee8aa95e7e4250cb89c4a31b3f7f7c209d05b594f7b3909ab42
|
|
| MD5 |
6534eea0e4806e1552ee6d9ea9eda506
|
|
| BLAKE2b-256 |
552ec75a7e4188713bbe48a63946d1ed5f20c7716fc820f8cd1b01bc25071258
|