Skip to content

Commit 9e37b27

Browse files
committed
Added example of admin api usage
1 parent 0679f32 commit 9e37b27

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

examples/admin_usage/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
### OpenAI Administration Endpoints
2+
3+
The examples in this directory require the use of an Admin API Key, which differ from a normal API key. You must create at least one Admin API Key using the OpenAI Console before using these functions.
4+
5+
You can generate the link in the [Admin Keys Console](https://platform.openai.com/organization/admin-keys).
6+
7+
For additional information, refer to the Administrator section of the [API Reference](https://platform.openai.com/docs/api-reference/administration).

examples/admin_usage/main.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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

Comments
 (0)