How to track individual usage?

Edit [3/14 2:06 AM]: Made important corrections and also changed the code to make the start_date and end_data parameters dynamic and grab today and tomorrow’s date relative to when you run the code. The code should work now!

I wrote a quick script in PowerShell to grab each user and their usage. Since I only have a personal organization because I’m a lone developer, I do not know if this will work for grabbing each user within an organization. For best results, assuming you’re the owner of the organization, I would use your API key for the following script and see if you’re able to access the user usage data within the organization or not. Also, if you need the script written in Python, I could also get that written up for you as well.

Please perform the following steps to (hopefully) get the usage data for each user for only this day within your organization:

  1. Go to OpenAI organization settings page and note your organization ID and API key
  2. Code to grab all users and their usage data in your organization (Need your organization ID):
$openai_org_id = "<org-id>"
$openai_api_key = "<api_key>"
$today = Get-Date
$tomorrow = Get-Date $today.AddDays(1) -Format "yyyy-MM-dd"
$today = Get-Date $today -Format "yyyy-MM-dd"
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$users = Invoke-WebRequest -UseBasicParsing -Uri "https://api.openai.com/v1/organizations/$openai_org_id/users" `
-WebSession $session `
-Headers @{
"method"="GET"
  "authority"="api.openai.com"
  "scheme"="https"
  "path"="/v1/organizations/$openai_org_id/users"
  "authorization"="Bearer $openai_api_key"
}
$your_users = @()
foreach ($line in ($users.Content | Out-String | ConvertFrom-JSON)) {
      $your_users += $line.members.data.user | Select-Object id,name,email
}
$each_user_usage = @{}
foreach ($user in $your_users){
	$id_of_user = $user.id
	$data = Invoke-WebRequest -UseBasicParsing -Uri "https://api.openai.com/v1/usage?end_date=$tomorrow&start_date=$today&user_public_id=$id_of_user" `
	-WebSession $session `
	-Headers @{
		"method"="GET"
		"authority"="api.openai.com"
		"authorization"="Bearer $openai_api_key"
		"openai-organization"=$openai_org_id
	}
	
	foreach ($line in ($data.Content | Out-String | ConvertFrom-JSON)) {
      $each_user_usage[$user.email] += @($user.name,$user.id,$line)
	}
}
/* 
$each_user_usage["<user's email>"] ->  (user's name, user's id, user's usage data)
$each_user_usage["<user's email>"][0] -> user's name
$each_user_usage["<user's email>"][1] -> user's id
$each_user_usage["<user's email>"][2] -> user's usage data
...
*/
8 Likes