File size: 9,809 Bytes
bffc389
da04961
 
bffc389
 
 
 
 
 
 
 
 
 
da04961
bffc389
 
 
 
 
 
 
 
 
 
 
 
da04961
bffc389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da04961
bffc389
 
 
 
 
 
 
 
 
 
 
 
 
da04961
bffc389
 
 
 
 
 
 
 
 
 
 
 
 
da04961
bffc389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da04961
 
bffc389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da04961
bffc389
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# app.py
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import os
from typing import Optional, Dict, List
import requests
import json
import altair as alt
from pathlib import Path
import base64

class OpenAIUsageTracker:
    def __init__(self, api_key: Optional[str] = None):
        """Initialize the OpenAI Usage Tracker."""
        self.api_key = api_key
        if not self.api_key:
            raise ValueError("API key must be provided")
        
        self.base_url = "https://api.openai.com/v1/dashboard/billing/usage"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def get_usage(self, start_date: datetime, end_date: datetime) -> Dict:
        """Get API usage for a specific date range."""
        params = {
            'start_date': start_date.strftime('%Y-%m-%d'),
            'end_date': end_date.strftime('%Y-%m-%d')
        }
        
        try:
            response = requests.get(
                self.base_url,
                headers=self.headers,
                params=params
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            st.error(f"Error fetching usage data: {str(e)}")
            return None

    def get_subscription_data(self) -> Dict:
        """Get subscription data including total available credits."""
        subscription_url = "https://api.openai.com/v1/dashboard/billing/subscription"
        try:
            response = requests.get(
                subscription_url,
                headers=self.headers
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            st.error(f"Error fetching subscription data: {str(e)}")
            return None

def create_daily_usage_chart(daily_costs: pd.DataFrame) -> alt.Chart:
    """Create an interactive daily usage chart using Altair."""
    chart = alt.Chart(daily_costs).mark_bar().encode(
        x=alt.X('date:T', title='Date'),
        y=alt.Y('cost:Q', title='Cost ($)'),
        tooltip=['date', 'cost']
    ).properties(
        title='Daily API Usage Cost',
        width=600,
        height=400
    ).interactive()
    
    return chart

def create_model_usage_chart(model_usage: pd.DataFrame) -> go.Figure:
    """Create a pie chart for model usage distribution."""
    fig = px.pie(
        model_usage,
        values='cost',
        names='model',
        title='Cost Distribution by Model'
    )
    fig.update_traces(textposition='inside', textinfo='percent+label')
    return fig

def format_large_number(num: float) -> str:
    """Format large numbers with K/M suffix."""
    if num >= 1_000_000:
        return f"${num/1_000_000:.2f}M"
    elif num >= 1_000:
        return f"${num/1_000:.2f}K"
    return f"${num:.2f}"

def export_to_csv(df: pd.DataFrame, filename: str):
    """Generate a CSV download link."""
    csv = df.to_csv(index=False)
    b64 = base64.b64encode(csv.encode()).decode()
    href = f'data:file/csv;base64,{b64}'
    return href

def main():
    st.set_page_config(
        page_title="OpenAI API Usage Analytics",
        page_icon="๐Ÿ“Š",
        layout="wide"
    )

    # Custom CSS
    st.markdown("""
        <style>
        .stApp {
            max-width: 1200px;
            margin: 0 auto;
        }
        .metric-card {
            background-color: #f0f2f6;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
        }
        .metric-value {
            font-size: 24px;
            font-weight: bold;
            color: #0068c9;
        }
        </style>
    """, unsafe_allow_html=True)

    st.title("๐Ÿ“Š OpenAI API Usage Analytics Dashboard")
    
    # Sidebar
    st.sidebar.header("Configuration")
    
    # API Key input
    api_key = st.sidebar.text_input("Enter OpenAI API Key", type="password")
    if not api_key:
        st.warning("Please enter your OpenAI API key to continue.")
        st.stop()

    # Date range selection
    st.sidebar.subheader("Date Range")
    end_date = datetime.now()
    date_ranges = {
        "Last 7 days": 7,
        "Last 30 days": 30,
        "Last 90 days": 90,
        "Custom range": 0
    }
    selected_range = st.sidebar.selectbox("Select time period", list(date_ranges.keys()))
    
    if selected_range == "Custom range":
        col1, col2 = st.sidebar.columns(2)
        with col1:
            start_date = st.date_input("Start date", end_date - timedelta(days=30))
        with col2:
            end_date = st.date_input("End date", end_date)
    else:
        days = date_ranges[selected_range]
        start_date = end_date - timedelta(days=days)

    try:
        tracker = OpenAIUsageTracker(api_key)
        
        # Get usage data
        usage_data = tracker.get_usage(start_date, end_date)
        subscription_data = tracker.get_subscription_data()

        if usage_data and subscription_data:
            # Process data
            daily_costs = pd.DataFrame(usage_data.get('daily_costs', []))
            total_usage = usage_data.get('total_usage', 0) / 100  # Convert to dollars
            
            # Create metrics row
            col1, col2, col3, col4 = st.columns(4)
            
            with col1:
                st.markdown("""
                    <div class="metric-card">
                        <h3>Total Cost</h3>
                        <div class="metric-value">{}</div>
                    </div>
                """.format(format_large_number(total_usage)), unsafe_allow_html=True)
                
            with col2:
                remaining_credits = subscription_data.get('hard_limit_usd', 0)
                st.markdown("""
                    <div class="metric-card">
                        <h3>Available Credits</h3>
                        <div class="metric-value">{}</div>
                    </div>
                """.format(format_large_number(remaining_credits)), unsafe_allow_html=True)
                
            with col3:
                daily_avg = total_usage / len(daily_costs) if len(daily_costs) > 0 else 0
                st.markdown("""
                    <div class="metric-card">
                        <h3>Daily Average</h3>
                        <div class="metric-value">${:.2f}</div>
                    </div>
                """.format(daily_avg), unsafe_allow_html=True)
                
            with col4:
                projected_monthly = daily_avg * 30
                st.markdown("""
                    <div class="metric-card">
                        <h3>Projected Monthly</h3>
                        <div class="metric-value">{}</div>
                    </div>
                """.format(format_large_number(projected_monthly)), unsafe_allow_html=True)

            # Process daily costs data
            if not daily_costs.empty:
                daily_costs['timestamp'] = pd.to_datetime(daily_costs['timestamp'])
                daily_costs['date'] = daily_costs['timestamp'].dt.date
                daily_costs['cost'] = daily_costs.apply(
                    lambda x: sum(item['cost'] for item in x['line_items']) / 100,
                    axis=1
                )
                
                # Create model usage DataFrame
                model_data = []
                for _, row in daily_costs.iterrows():
                    for item in row['line_items']:
                        model_data.append({
                            'model': item['name'],
                            'cost': item['cost'] / 100
                        })
                model_usage = pd.DataFrame(model_data)
                model_usage = model_usage.groupby('model')['cost'].sum().reset_index()

                # Display charts
                col1, col2 = st.columns(2)
                
                with col1:
                    st.altair_chart(create_daily_usage_chart(daily_costs), use_container_width=True)
                
                with col2:
                    st.plotly_chart(create_model_usage_chart(model_usage), use_container_width=True)

                # Display detailed data tables
                st.subheader("Detailed Usage Data")
                tab1, tab2 = st.tabs(["Daily Usage", "Model Distribution"])
                
                with tab1:
                    daily_table = daily_costs[['date', 'cost']].copy()
                    st.dataframe(daily_table, use_container_width=True)
                    
                    # Download button for daily usage
                    st.download_button(
                        label="Download Daily Usage Data",
                        data=daily_table.to_csv(index=False),
                        file_name="daily_usage.csv",
                        mime="text/csv"
                    )
                
                with tab2:
                    st.dataframe(model_usage, use_container_width=True)
                    
                    # Download button for model usage
                    st.download_button(
                        label="Download Model Usage Data",
                        data=model_usage.to_csv(index=False),
                        file_name="model_usage.csv",
                        mime="text/csv"
                    )

            else:
                st.info("No usage data available for the selected period.")
        
        else:
            st.error("Failed to fetch data. Please check your API key and try again.")

    except Exception as e:
        st.error(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    main()