Connect your application to CostFlow in minutes
# costflow_client.py
import requests
import json
import os
from datetime import datetime
from typing import Dict, Any, Optional
class CostFlowClient:
def __init__(self, api_url: str, api_key: str):
self.api_url = api_url.rstrip('/')
self.api_key = api_key
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
})
def track_cost(self,
model: str,
provider: str,
tokens: int,
cost: float,
user_id: str,
metadata: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Record an AI usage cost"""
data = {
'model': model,
'provider': provider,
'tokens': tokens,
'cost': cost,
'userId': user_id,
'metadata': metadata if metadata is not None else {}
}
try:
response = self.session.post(f'{self.api_url}/track-cost', json=data)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"Error recording cost: {e}")
return {'success': False, 'error': str(e)}
def get_costs(self, user_id: str, limit: int = 50) -> Dict[str, Any]:
"""Retrieve cost history for a user"""
try:
response = self.session.get(f'{self.api_url}/costs?userId={user_id}&limit={limit}')
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"Error retrieving costs: {e}")
return {'success': False, 'error': str(e)}
# Usage with Flask
from flask import Flask, request, jsonify
import openai
app = Flask(__name__)
# Initialisation CostFlow
costflow = CostFlowClient(
api_url=os.getenv('COSTFLOW_API_URL'),
api_key=os.getenv('COSTFLOW_API_KEY')
)
@app.route('/chat', methods=['POST'])
def chat():
try:
user_message = request.json.get('message')
user_id = request.json.get('user_id', 'default_user')
# Call OpenAI
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": user_message}]
)
# Calculate costs
tokens_used = response['usage']['total_tokens']
cost_per_1k = 0.03 # $0.03 pour 1000 tokens
total_cost = (tokens_used / 1000) * cost_per_1k
# Save to CostFlow
costflow.track_cost(
model="gpt-4",
provider="openai",
tokens=tokens_used,
cost=total_cost,
user_id=user_id,
metadata={
'endpoint': '/chat',
'session_id': request.json.get('session_id'),
'timestamp': datetime.now().isoformat()
}
)
return jsonify({
'response': response['choices'][0]['message']['content'],
'tokens_used': tokens_used,
'cost': total_cost
})
except Exception as e:
return jsonify({'error': str(e)}), 500Records an AI usage cost
Retrieves cost history for a user