|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/sashabaranov/go-openai" |
| 10 | +) |
| 11 | + |
| 12 | +func main() { |
| 13 | + ctx := context.Background() |
| 14 | + |
| 15 | + // Admin API Keys are different than regular API keys and require a different |
| 16 | + // endpoint to be used. You can find your Admin API key in the OpenAI dashboard. |
| 17 | + config := openai.DefaultConfig(os.Getenv("OPENAI_ADMIN_API_KEY")) |
| 18 | + client := openai.NewClientWithConfig(config) |
| 19 | + |
| 20 | + // Specify the date range of the usage data you want to retrieve, the end date is optional, |
| 21 | + // but when specified, it should include through the end of the day you want to retrieve. |
| 22 | + startTime := convertDateStringToTimestamp("2025-02-01") |
| 23 | + endTime := convertDateStringToTimestamp("2025-03-01") |
| 24 | + |
| 25 | + // In this example each bucket represents a day of usage data. To avoid |
| 26 | + // making several requests to get the data for each day, we'll increase |
| 27 | + // the limit to 31 to get all the data in one request. |
| 28 | + limit := 31 |
| 29 | + |
| 30 | + // Create the request object, only StartTime is required. |
| 31 | + req := openai.AdminUsageCostRequest{ |
| 32 | + StartTime: startTime, |
| 33 | + EndTime: &endTime, |
| 34 | + Limit: &limit, |
| 35 | + } |
| 36 | + |
| 37 | + // Request the usage data. |
| 38 | + res, err := client.GetAdminUsageCost(ctx, req) |
| 39 | + if err != nil { |
| 40 | + fmt.Printf("error getting openai usage data: %v\n", err) |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + // Calculate the total cost of the usage data. |
| 45 | + totalCost := 0.0 |
| 46 | + for _, bucket := range res.Data { |
| 47 | + for _, cost := range bucket.Results { |
| 48 | + totalCost += cost.Amount.Value |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + fmt.Printf("Total Cost: %f\n", totalCost) |
| 53 | +} |
| 54 | + |
| 55 | +// Helper function to convert a date string to a Unix timestamp. |
| 56 | +func convertDateStringToTimestamp(date string) int64 { |
| 57 | + t, err := time.Parse("2006-01-02", date) |
| 58 | + if err != nil { |
| 59 | + panic(err) |
| 60 | + } |
| 61 | + return t.Unix() |
| 62 | +} |
0 commit comments