Skip to main content

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 completion
  • client.closepack.generate() - Generate a financial close pack
  • client.closepack.list() - List previous close packs
  • client.budgets.create() - Create a new budget
  • client.budgets.list() - List all budgets
  • client.budgets.get() - Get a specific budget
  • client.budgets.update() - Update a budget
  • client.anomalies.list() - List detected anomalies
  • client.anomalies.get() - Get specific anomaly
  • client.anomalies.acknowledge() - Mark anomaly as acknowledged
  • client.keys.create() - Create an API key
  • client.keys.list() - List API keys
  • client.keys.revoke() - Revoke an API key
  • client.dashboard.overview() - Get dashboard overview
  • client.dashboard.insights() - Get dashboard insights
  • client.health.status() - Check API health
  • client.pricing.get() - Get pricing information

Support

For issues, questions, or feedback:

License

MIT License - see LICENSE file for details

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

finault-1.0.0.tar.gz (82.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

finault-1.0.0-py3-none-any.whl (86.9 kB view details)

Uploaded Python 3

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

Hashes for finault-1.0.0.tar.gz
Algorithm Hash digest
SHA256 cac901f3d9cd4d604dffd37d4b1d28063ee5e0fbedf55457fafb12d481ba9358
MD5 4891939a56ec3921a44f954a3aa168a1
BLAKE2b-256 ff7421d5a4051b7ff540e6bb97d6a74dd7584661035425fcddfba0aae056b626

See more details on using hashes here.

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

Hashes for finault-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 efdcb2ea61f56ee8aa95e7e4250cb89c4a31b3f7f7c209d05b594f7b3909ab42
MD5 6534eea0e4806e1552ee6d9ea9eda506
BLAKE2b-256 552ec75a7e4188713bbe48a63946d1ed5f20c7716fc820f8cd1b01bc25071258

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page