From 51074426c1446ae958a7b48a8dee617217817eae Mon Sep 17 00:00:00 2001 From: markstuart-oai <323302876+markstuart-oai@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:24:16 +0000 Subject: [PATCH] feat(api): group Completions usage and costs by completion window Castiron-Internal-PR: https://github.com/openai/openai-python-internal/pull/476 Castiron-Source-SHA: be7c319cb97f92940566230a7a09b2062cfe3d4c Castiron-Public-Base-SHA: ba6e57797bfcc9a9a700ee1ef4263b3cf16cf747 --- .castiron.stats.yml | 12 +- api.md | 2 +- api_reference/openapi.transformed.yml | 71 ++++++++++-- scripts/castiron/generated-files.json | 32 +++--- .../resources/admin/organization/usage.py | 98 ++++++++++++---- .../usage_audio_speeches_response.py | 2 + .../usage_audio_transcriptions_response.py | 2 + ...sage_code_interpreter_sessions_response.py | 2 + .../organization/usage_completions_params.py | 22 +++- .../usage_completions_response.py | 2 + .../admin/organization/usage_costs_params.py | 21 ++-- .../organization/usage_costs_response.py | 9 ++ .../organization/usage_embeddings_response.py | 2 + .../usage_file_search_calls_response.py | 2 + .../organization/usage_images_response.py | 2 + .../usage_moderations_response.py | 2 + .../usage_vector_stores_response.py | 2 + .../usage_web_search_calls_response.py | 2 + .../admin/organization/test_usage.py | 20 ++-- tests/test_usage_completion_window.py | 106 ++++++++++++++++++ 20 files changed, 332 insertions(+), 81 deletions(-) create mode 100644 tests/test_usage_completion_window.py diff --git a/.castiron.stats.yml b/.castiron.stats.yml index 667f73dd89..e28b1681d5 100644 --- a/.castiron.stats.yml +++ b/.castiron.stats.yml @@ -1,7 +1,7 @@ schema_version: 1 -generation_id: 246f879d-8464-4b41-bb24-d89bc1e8df3c -openapi_spec_hash: 0ce316f78a89857b9483e1ec86e095ea -openapi_transformed_spec_hash: 45b9b080467ec914b61d840811bed260 -config_hash: 036100415594abcf279907b22cc8d2f1 -codegen_sha: cc041f0d27315d1a33d649dd1e5fb6f2ec04c72b -codegen_hash: 52084edd6ec47c7ad6066c4f16600f52381ceb96fcad79a85380928a81299e80 +generation_id: 4f4dbc91-5b78-46d8-97f7-15096d8e430c +openapi_spec_hash: 85300592bd12a4d6666b4f2972c5b340 +openapi_transformed_spec_hash: a7e0ebe69483471b43a3667b70c53fca +config_hash: 4bd03da3ce58c2786da57469e6022f83 +codegen_sha: 3a70cedb841472aff4cc80602656795087f0c1b0 +codegen_hash: 90a067163c95f062e08d68c3eac2947ba43ca99c22e8d9c353bff40bab06b6c6 diff --git a/api.md b/api.md index 2ee97d3501..cf2c1a27af 100644 --- a/api.md +++ b/api.md @@ -1413,11 +1413,11 @@ Types: ```python from openai.types.admin.organization import ( CostQuantityUnit, - UsageCostsResponse, UsageAudioSpeechesResponse, UsageAudioTranscriptionsResponse, UsageCodeInterpreterSessionsResponse, UsageCompletionsResponse, + UsageCostsResponse, UsageDecisionsResponse, UsageEmbeddingsResponse, UsageFileSearchCallsResponse, diff --git a/api_reference/openapi.transformed.yml b/api_reference/openapi.transformed.yml index f8af3d4f7f..00ac3dbad9 100644 --- a/api_reference/openapi.transformed.yml +++ b/api_reference/openapi.transformed.yml @@ -11106,12 +11106,14 @@ paths: required: true schema: type: integer + example: 1796256000 - name: end_time in: query description: End time (Unix seconds) of the query time range, exclusive. required: false schema: type: integer + example: 1796342400 - name: bucket_width in: query description: Width of each time bucket in response. Currently only `1d` is supported, default to `1d`. @@ -11147,7 +11149,7 @@ paths: type: string - name: group_by in: query - description: Group the costs by the specified fields. Supported fields include `project_id`, `user_id`, `line_item`, `api_key_id`, and `api_source`. Support for combining `user_id` with `project_id` grouping or the `project_ids` filter depends on the organization and requested time range. Unsupported combinations return HTTP 400. When grouped by `api_source`, results use `agents_api` for attributed Agents API activity and `unlabeled` for all other activity. Without source grouping, `api_source` is null. + description: Group the costs by the specified fields. Supported fields include `project_id`, `user_id`, `line_item`, `api_key_id`, `api_source`, and `completion_window`. Support for combining `user_id` with `project_id` grouping or the `project_ids` filter depends on the organization and requested time range. Unsupported combinations return HTTP 400. When grouped by `api_source`, results use `agents_api` for attributed Agents API activity and `unlabeled` for all other activity. Without source grouping, `api_source` is null. When grouped by `completion_window`, results use `2h`, `8h`, or `unlabeled` when no known or applicable window is available. Without window grouping, `completion_window` is null. Unlabeled does not imply Standard traffic. The field may be omitted when completion-window reporting is unavailable. Batch's 24h window and legacy Flex scheduling are not included. Existing line item names and exact-name filters are unchanged. Keep the same grouping and filters when following `next_page`. required: false schema: type: array @@ -11159,6 +11161,7 @@ paths: - line_item - api_key_id - api_source + - completion_window - name: limit in: query description: | @@ -11178,7 +11181,26 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/CostsResponseWithDimensions' + allOf: + - $ref: '#/components/schemas/CostsResponseWithDimensions' + example: + object: page + data: + - object: bucket + start_time: 1796256000 + end_time: 1796342400 + results: + - object: organization.costs.result + amount: + value: 0.06 + currency: usd + line_item: null + model: null + token_type: null + completion_window: null + project_id: null + has_more: false + next_page: null '400': description: The request parameters are invalid or the requested operation cannot be performed. content: @@ -11199,7 +11221,7 @@ paths: - title: Total costs request: curl: | - curl "https://api.openai.com/v1/organization/costs?start_time=1730419200&limit=1" \ + curl "https://api.openai.com/v1/organization/costs?start_time=1796256000&end_time=1796342400" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" response: | @@ -11208,8 +11230,8 @@ paths: "data": [ { "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, + "start_time": 1796256000, + "end_time": 1796342400, "results": [ { "object": "organization.costs.result", @@ -11220,6 +11242,7 @@ paths: "line_item": null, "model": null, "token_type": null, + "completion_window": null, "project_id": null, "api_key_id": null, "quantity": null, @@ -11231,10 +11254,10 @@ paths: "has_more": false, "next_page": null } - - title: Costs by line item + - title: Costs by line item and completion window request: curl: | - curl "https://api.openai.com/v1/organization/costs?start_time=1730419200&limit=1&group_by=line_item" \ + curl "https://api.openai.com/v1/organization/costs?start_time=1796256000&end_time=1796342400&group_by=line_item&group_by=completion_window" \ -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ -H "Content-Type: application/json" response: | @@ -11243,8 +11266,8 @@ paths: "data": [ { "object": "bucket", - "start_time": 1730419200, - "end_time": 1730505600, + "start_time": 1796256000, + "end_time": 1796342400, "results": [ { "object": "organization.costs.result", @@ -11255,6 +11278,7 @@ paths: "line_item": "gpt-6.2-astra, input_tokens", "model": "gpt-6.2-astra", "token_type": "input", + "completion_window": "2h", "project_id": null, "api_key_id": null, "quantity": 10000, @@ -17073,7 +17097,7 @@ paths: type: boolean - name: group_by in: query - description: Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `batch`, `service_tier`, `api_source` or any combination of them. When grouped by `api_source`, results use `agents_api` for attributed Agents API activity and `unlabeled` for all other activity. Without source grouping, `api_source` is null. + description: Group the usage data by the specified fields. Supported fields include `project_id`, `user_id`, `api_key_id`, `model`, `batch`, `service_tier`, `api_source`, `completion_window` or any combination of them. When grouped by `api_source`, results use `agents_api` for attributed Agents API activity and `unlabeled` for all other activity. Without source grouping, `api_source` is null. When grouped by `completion_window`, results use `2h`, `8h`, or `unlabeled` when no known or applicable window is available. Without window grouping, `completion_window` is null. Unlabeled does not imply Standard traffic. The field may be omitted when completion-window reporting is unavailable. Completion window is separate from `service_tier`; Batch's 24h window and legacy Flex scheduling are not included. Keep the same grouping and filters when following `next_page`. required: false schema: type: array @@ -17087,6 +17111,7 @@ paths: - batch - service_tier - api_source + - completion_window - name: limit in: query description: | @@ -74322,6 +74347,8 @@ components: type: object description: The aggregated completions usage details of the specific time bucket. properties: + completion_window: + $ref: '#/components/schemas/completion_window' api_source: description: When grouped by `api_source`, `agents_api` identifies attributed Agents API activity and `unlabeled` includes all records without published source attribution, including historical and unknown origins. Unlabeled does not imply direct API usage. Without source grouping, this field is null. anyOf: @@ -74448,7 +74475,8 @@ components: "api_key_id": "key_abc", "model": "gpt-6.2-astra", "batch": false, - "service_tier": "default" + "service_tier": "default", + "completion_window": null } UsageEmbeddingsResult: type: object @@ -116606,6 +116634,11 @@ components: - results PublicOrganizationCostResultModel: properties: + completion_window: + anyOf: + - description: The background completion window for this result. When group_by includes completion_window, the value is 2h, 8h, or unlabeled if the window is unknown or does not apply. Otherwise, the value is null. + $ref: '#/components/schemas/ReportedCompletionWindow' + - type: 'null' api_source: anyOf: - type: string @@ -117365,6 +117398,17 @@ components: - next - has_more additionalProperties: false + ReportedCompletionWindow: + type: string + enum: + - 2h + - 8h + - unlabeled + completion_window: + anyOf: + - description: The background completion window for this result. When group_by includes completion_window, the value is 2h, 8h, or unlabeled if the window is unknown or does not apply. Otherwise, the value is null. + $ref: '#/components/schemas/ReportedCompletionWindow' + - type: 'null' CostsResultWithDimensions: type: object description: The aggregated costs details of the specific time bucket. @@ -117427,6 +117471,11 @@ components: - type: string description: 'The billed token category: `input`, `output`, `input_cached`, `input_cache_write_30m`, `input_cache_write_12h`, or `total`. For inference charges, `input` excludes separately billed cache reads and writes. For Scale Tier purchases, these categories describe purchased capacity. Null when line_item is null or when the category is unknown or inapplicable. Additional values may be introduced in the future.' - type: 'null' + completion_window: + anyOf: + - description: The background completion window for this result. When group_by includes completion_window, the value is 2h, 8h, or unlabeled if the window is unknown or does not apply. Otherwise, the value is null. + $ref: '#/components/schemas/ReportedCompletionWindow' + - type: 'null' required: - object x-oaiMeta: diff --git a/scripts/castiron/generated-files.json b/scripts/castiron/generated-files.json index 2b6725f575..d396d0bf39 100644 --- a/scripts/castiron/generated-files.json +++ b/scripts/castiron/generated-files.json @@ -3,7 +3,7 @@ "files": { "api.md": { "mode": "100644", - "sha256": "023cc38670f9e15c47e8592fb4c04b1c879f7178060446775ae3f57f22d25d83" + "sha256": "359777878b88a838a484de3e737ea0c3d7aedb57d68214c06a66eb78bcab22ef" }, "src/openai/__init__.py": { "mode": "100644", @@ -219,7 +219,7 @@ }, "src/openai/resources/admin/organization/usage.py": { "mode": "100644", - "sha256": "ec767c61744615ac7899a3155c14f8342226e077973b87656189927bd01f8b84" + "sha256": "0b87f2d4e0c26109a1c27f69ddb18b5d72e7a82a08432abeae601d9eb911ae43" }, "src/openai/resources/admin/organization/users/__init__.py": { "mode": "100644", @@ -1451,7 +1451,7 @@ }, "src/openai/types/admin/organization/usage_audio_speeches_response.py": { "mode": "100644", - "sha256": "be0b5d71e86f5b631dcb7f058910c28d963181112de32c53a9b891f6405aee3c" + "sha256": "28b7377a115339600eca741d86b625c26f5206257e084946a33c312879829660" }, "src/openai/types/admin/organization/usage_audio_transcriptions_params.py": { "mode": "100644", @@ -1459,7 +1459,7 @@ }, "src/openai/types/admin/organization/usage_audio_transcriptions_response.py": { "mode": "100644", - "sha256": "73f935a7c8a2943b4f6791f50da7152c383c69cd063fe886b51a179fe80ee196" + "sha256": "0d15bf9e1842d078ce8141a963f24f6647997628a8e153544f92525aaa63d59a" }, "src/openai/types/admin/organization/usage_code_interpreter_sessions_params.py": { "mode": "100644", @@ -1467,23 +1467,23 @@ }, "src/openai/types/admin/organization/usage_code_interpreter_sessions_response.py": { "mode": "100644", - "sha256": "c4d16ba26fcc203831645cad0493427983e25f35924d5ab067664ba548c2fef0" + "sha256": "2e8481a9774be583792b04f123a2ff4df76c0bc9ea0619db0a5af888895891f1" }, "src/openai/types/admin/organization/usage_completions_params.py": { "mode": "100644", - "sha256": "69497b03766e90c60209eec3f43e0e912d49a6466bfb6403eb1974df659408e9" + "sha256": "3877a857c7f355b3df42cadaa4809ed1c3b8cc43b0c7b7ad3da57e105af92f42" }, "src/openai/types/admin/organization/usage_completions_response.py": { "mode": "100644", - "sha256": "b067bb58f59a51dc4cc7cdb6ff811c25a103b62c8ddbf2fa00f9070dab42b179" + "sha256": "6c21e8b6066ecfafabbb6db73b83f4a7a4ea4bc559b7b2b3e58b12b699e5f152" }, "src/openai/types/admin/organization/usage_costs_params.py": { "mode": "100644", - "sha256": "524d5d4553f5985167250036d224f75da568c8aa86913ff014995c2748f021cb" + "sha256": "a5fa71036218c6260c5830e79b74bbf29406f6601748722f49672d22b20eec2e" }, "src/openai/types/admin/organization/usage_costs_response.py": { "mode": "100644", - "sha256": "291441b12df73417c2c1a385c8e2492c801f3760f0bcc75338de721bdeb3552d" + "sha256": "e17ee4d954b6f9abcfeec619bc3c5d19b4bef00dddf7414a77183ab158ba11e3" }, "src/openai/types/admin/organization/usage_decisions_params.py": { "mode": "100644", @@ -1499,7 +1499,7 @@ }, "src/openai/types/admin/organization/usage_embeddings_response.py": { "mode": "100644", - "sha256": "8237167123c50b07038996c660575ce48b0c1455fa6d654b390b5c44899b2270" + "sha256": "f5104baaf4cb8824914c9d861dbdd00ee323294c573d4635771312a6e9fcc4c3" }, "src/openai/types/admin/organization/usage_file_search_calls_params.py": { "mode": "100644", @@ -1507,7 +1507,7 @@ }, "src/openai/types/admin/organization/usage_file_search_calls_response.py": { "mode": "100644", - "sha256": "9b274a94aa5d05a815aae5c356c5d72c338a04833e995283acfc5addc3a8ea09" + "sha256": "ef77c22b8c75d1408fd2c2e738fb7863f049f562c59a95e44dadd4199c656108" }, "src/openai/types/admin/organization/usage_images_params.py": { "mode": "100644", @@ -1515,7 +1515,7 @@ }, "src/openai/types/admin/organization/usage_images_response.py": { "mode": "100644", - "sha256": "be86ff8f13e0420cecf2b6f500f97ec1e1831f82edf4d1292f54152d5cfdcb17" + "sha256": "43df8179d9298d28475566b0b4f3cc25a60cdd45096b8a138cadabb96700c77a" }, "src/openai/types/admin/organization/usage_moderations_params.py": { "mode": "100644", @@ -1523,7 +1523,7 @@ }, "src/openai/types/admin/organization/usage_moderations_response.py": { "mode": "100644", - "sha256": "e63e527408f23e6e43059c5aeb04380233eb03a28be42679e29a8a420feb7a3d" + "sha256": "b0471c8fda033e9b137b48820df2deba90103dcb8342011db5e9219c52468295" }, "src/openai/types/admin/organization/usage_vector_stores_params.py": { "mode": "100644", @@ -1531,7 +1531,7 @@ }, "src/openai/types/admin/organization/usage_vector_stores_response.py": { "mode": "100644", - "sha256": "fb5a4478701a61369cf0c87c615d7b5b41b18e5394b83f469fc805565e3251e4" + "sha256": "40fe67627acd8986d133a016de2ce8e62b7f673af3547fcace9f65c28f9337eb" }, "src/openai/types/admin/organization/usage_web_search_calls_params.py": { "mode": "100644", @@ -1539,7 +1539,7 @@ }, "src/openai/types/admin/organization/usage_web_search_calls_response.py": { "mode": "100644", - "sha256": "fe8f464c0045fddf327041b4e2e00ff50ba2e212b6142a94676ae475ae076faa" + "sha256": "c8ac69d751e2fccffcb48ed7fc9f64eb74c2f7406a9d6b08b5835592a69ababf" }, "src/openai/types/admin/organization/user_delete_response.py": { "mode": "100644", @@ -7899,7 +7899,7 @@ }, "tests/api_resources/admin/organization/test_usage.py": { "mode": "100644", - "sha256": "67935642b6d09060b7bdd1b15c4d5e8881c6bc96b11934f5ff772bf82860a675" + "sha256": "b75cac81c4de2f67a7bbd4d1e950162b98e87d98a41ac44cb3a4c3bf46156272" }, "tests/api_resources/admin/organization/test_users.py": { "mode": "100644", diff --git a/src/openai/resources/admin/organization/usage.py b/src/openai/resources/admin/organization/usage.py index 140880a756..0a76c199c3 100644 --- a/src/openai/resources/admin/organization/usage.py +++ b/src/openai/resources/admin/organization/usage.py @@ -318,7 +318,18 @@ def completions( batch: bool | Omit = omit, bucket_width: Literal["1m", "1h", "1d"] | Omit = omit, end_time: int | Omit = omit, - group_by: List[Literal["project_id", "user_id", "api_key_id", "model", "batch", "service_tier", "api_source"]] + group_by: List[ + Literal[ + "project_id", + "user_id", + "api_key_id", + "model", + "batch", + "service_tier", + "api_source", + "completion_window", + ] + ] | Omit = omit, limit: int | Omit = omit, models: SequenceNotStr[str] | Omit = omit, @@ -348,11 +359,18 @@ def completions( end_time: End time (Unix seconds) of the query time range, exclusive. - group_by: Group the usage data by the specified fields. Support fields include + group_by: Group the usage data by the specified fields. Supported fields include `project_id`, `user_id`, `api_key_id`, `model`, `batch`, `service_tier`, - `api_source` or any combination of them. When grouped by `api_source`, results - use `agents_api` for attributed Agents API activity and `unlabeled` for all - other activity. Without source grouping, `api_source` is null. + `api_source`, `completion_window` or any combination of them. When grouped by + `api_source`, results use `agents_api` for attributed Agents API activity and + `unlabeled` for all other activity. Without source grouping, `api_source` is + null. When grouped by `completion_window`, results use `2h`, `8h`, or + `unlabeled` when no known or applicable window is available. Without window + grouping, `completion_window` is null. Unlabeled does not imply Standard + traffic. The field may be omitted when completion-window reporting is + unavailable. Completion window is separate from `service_tier`; Batch's 24h + window and legacy Flex scheduling are not included. Keep the same grouping and + filters when following `next_page`. limit: Specifies the number of buckets to return. @@ -412,7 +430,8 @@ def costs( api_key_ids: SequenceNotStr[str] | Omit = omit, bucket_width: Literal["1d"] | Omit = omit, end_time: int | Omit = omit, - group_by: List[Literal["project_id", "user_id", "line_item", "api_key_id", "api_source"]] | Omit = omit, + group_by: List[Literal["project_id", "user_id", "line_item", "api_key_id", "api_source", "completion_window"]] + | Omit = omit, limit: int | Omit = omit, line_items: SequenceNotStr[str] | Omit = omit, page: str | Omit = omit, @@ -438,12 +457,18 @@ def costs( end_time: End time (Unix seconds) of the query time range, exclusive. group_by: Group the costs by the specified fields. Supported fields include `project_id`, - `user_id`, `line_item`, `api_key_id`, and `api_source`. Support for combining - `user_id` with `project_id` grouping or the `project_ids` filter depends on the - organization and requested time range. Unsupported combinations return HTTP 400. - When grouped by `api_source`, results use `agents_api` for attributed Agents API - activity and `unlabeled` for all other activity. Without source grouping, - `api_source` is null. + `user_id`, `line_item`, `api_key_id`, `api_source`, and `completion_window`. + Support for combining `user_id` with `project_id` grouping or the `project_ids` + filter depends on the organization and requested time range. Unsupported + combinations return HTTP 400. When grouped by `api_source`, results use + `agents_api` for attributed Agents API activity and `unlabeled` for all other + activity. Without source grouping, `api_source` is null. When grouped by + `completion_window`, results use `2h`, `8h`, or `unlabeled` when no known or + applicable window is available. Without window grouping, `completion_window` is + null. Unlabeled does not imply Standard traffic. The field may be omitted when + completion-window reporting is unavailable. Batch's 24h window and legacy Flex + scheduling are not included. Existing line item names and exact-name filters are + unchanged. Keep the same grouping and filters when following `next_page`. limit: A limit on the number of buckets to be returned. Limit can range between 1 and 180, and the default is 7. @@ -1386,7 +1411,18 @@ async def completions( batch: bool | Omit = omit, bucket_width: Literal["1m", "1h", "1d"] | Omit = omit, end_time: int | Omit = omit, - group_by: List[Literal["project_id", "user_id", "api_key_id", "model", "batch", "service_tier", "api_source"]] + group_by: List[ + Literal[ + "project_id", + "user_id", + "api_key_id", + "model", + "batch", + "service_tier", + "api_source", + "completion_window", + ] + ] | Omit = omit, limit: int | Omit = omit, models: SequenceNotStr[str] | Omit = omit, @@ -1416,11 +1452,18 @@ async def completions( end_time: End time (Unix seconds) of the query time range, exclusive. - group_by: Group the usage data by the specified fields. Support fields include + group_by: Group the usage data by the specified fields. Supported fields include `project_id`, `user_id`, `api_key_id`, `model`, `batch`, `service_tier`, - `api_source` or any combination of them. When grouped by `api_source`, results - use `agents_api` for attributed Agents API activity and `unlabeled` for all - other activity. Without source grouping, `api_source` is null. + `api_source`, `completion_window` or any combination of them. When grouped by + `api_source`, results use `agents_api` for attributed Agents API activity and + `unlabeled` for all other activity. Without source grouping, `api_source` is + null. When grouped by `completion_window`, results use `2h`, `8h`, or + `unlabeled` when no known or applicable window is available. Without window + grouping, `completion_window` is null. Unlabeled does not imply Standard + traffic. The field may be omitted when completion-window reporting is + unavailable. Completion window is separate from `service_tier`; Batch's 24h + window and legacy Flex scheduling are not included. Keep the same grouping and + filters when following `next_page`. limit: Specifies the number of buckets to return. @@ -1480,7 +1523,8 @@ async def costs( api_key_ids: SequenceNotStr[str] | Omit = omit, bucket_width: Literal["1d"] | Omit = omit, end_time: int | Omit = omit, - group_by: List[Literal["project_id", "user_id", "line_item", "api_key_id", "api_source"]] | Omit = omit, + group_by: List[Literal["project_id", "user_id", "line_item", "api_key_id", "api_source", "completion_window"]] + | Omit = omit, limit: int | Omit = omit, line_items: SequenceNotStr[str] | Omit = omit, page: str | Omit = omit, @@ -1506,12 +1550,18 @@ async def costs( end_time: End time (Unix seconds) of the query time range, exclusive. group_by: Group the costs by the specified fields. Supported fields include `project_id`, - `user_id`, `line_item`, `api_key_id`, and `api_source`. Support for combining - `user_id` with `project_id` grouping or the `project_ids` filter depends on the - organization and requested time range. Unsupported combinations return HTTP 400. - When grouped by `api_source`, results use `agents_api` for attributed Agents API - activity and `unlabeled` for all other activity. Without source grouping, - `api_source` is null. + `user_id`, `line_item`, `api_key_id`, `api_source`, and `completion_window`. + Support for combining `user_id` with `project_id` grouping or the `project_ids` + filter depends on the organization and requested time range. Unsupported + combinations return HTTP 400. When grouped by `api_source`, results use + `agents_api` for attributed Agents API activity and `unlabeled` for all other + activity. Without source grouping, `api_source` is null. When grouped by + `completion_window`, results use `2h`, `8h`, or `unlabeled` when no known or + applicable window is available. Without window grouping, `completion_window` is + null. Unlabeled does not imply Standard traffic. The field may be omitted when + completion-window reporting is unavailable. Batch's 24h window and legacy Flex + scheduling are not included. Existing line item names and exact-name filters are + unchanged. Keep the same grouping and filters when following `next_page`. limit: A limit on the number of buckets to be returned. Limit can range between 1 and 180, and the default is 7. diff --git a/src/openai/types/admin/organization/usage_audio_speeches_response.py b/src/openai/types/admin/organization/usage_audio_speeches_response.py index 72b2e1a406..1de18ba8f4 100644 --- a/src/openai/types/admin/organization/usage_audio_speeches_response.py +++ b/src/openai/types/admin/organization/usage_audio_speeches_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/src/openai/types/admin/organization/usage_audio_transcriptions_response.py b/src/openai/types/admin/organization/usage_audio_transcriptions_response.py index 82f602e4d3..f2a3337be9 100644 --- a/src/openai/types/admin/organization/usage_audio_transcriptions_response.py +++ b/src/openai/types/admin/organization/usage_audio_transcriptions_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/src/openai/types/admin/organization/usage_code_interpreter_sessions_response.py b/src/openai/types/admin/organization/usage_code_interpreter_sessions_response.py index 431db8543d..fe4729e6a3 100644 --- a/src/openai/types/admin/organization/usage_code_interpreter_sessions_response.py +++ b/src/openai/types/admin/organization/usage_code_interpreter_sessions_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/src/openai/types/admin/organization/usage_completions_params.py b/src/openai/types/admin/organization/usage_completions_params.py index 907c5858ce..ee267d84a6 100644 --- a/src/openai/types/admin/organization/usage_completions_params.py +++ b/src/openai/types/admin/organization/usage_completions_params.py @@ -32,14 +32,24 @@ class UsageCompletionsParams(TypedDict, total=False): end_time: int """End time (Unix seconds) of the query time range, exclusive.""" - group_by: List[Literal["project_id", "user_id", "api_key_id", "model", "batch", "service_tier", "api_source"]] + group_by: List[ + Literal[ + "project_id", "user_id", "api_key_id", "model", "batch", "service_tier", "api_source", "completion_window" + ] + ] """Group the usage data by the specified fields. - Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `batch`, - `service_tier`, `api_source` or any combination of them. When grouped by - `api_source`, results use `agents_api` for attributed Agents API activity and - `unlabeled` for all other activity. Without source grouping, `api_source` is - null. + Supported fields include `project_id`, `user_id`, `api_key_id`, `model`, + `batch`, `service_tier`, `api_source`, `completion_window` or any combination of + them. When grouped by `api_source`, results use `agents_api` for attributed + Agents API activity and `unlabeled` for all other activity. Without source + grouping, `api_source` is null. When grouped by `completion_window`, results use + `2h`, `8h`, or `unlabeled` when no known or applicable window is available. + Without window grouping, `completion_window` is null. Unlabeled does not imply + Standard traffic. The field may be omitted when completion-window reporting is + unavailable. Completion window is separate from `service_tier`; Batch's 24h + window and legacy Flex scheduling are not included. Keep the same grouping and + filters when following `next_page`. """ limit: int diff --git a/src/openai/types/admin/organization/usage_completions_response.py b/src/openai/types/admin/organization/usage_completions_response.py index c6ad04f186..9df2789df0 100644 --- a/src/openai/types/admin/organization/usage_completions_response.py +++ b/src/openai/types/admin/organization/usage_completions_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/src/openai/types/admin/organization/usage_costs_params.py b/src/openai/types/admin/organization/usage_costs_params.py index 46fa727c13..7ab44cf04f 100644 --- a/src/openai/types/admin/organization/usage_costs_params.py +++ b/src/openai/types/admin/organization/usage_costs_params.py @@ -26,15 +26,22 @@ class UsageCostsParams(TypedDict, total=False): end_time: int """End time (Unix seconds) of the query time range, exclusive.""" - group_by: List[Literal["project_id", "user_id", "line_item", "api_key_id", "api_source"]] + group_by: List[Literal["project_id", "user_id", "line_item", "api_key_id", "api_source", "completion_window"]] """Group the costs by the specified fields. - Supported fields include `project_id`, `user_id`, `line_item`, `api_key_id`, and - `api_source`. Support for combining `user_id` with `project_id` grouping or the - `project_ids` filter depends on the organization and requested time range. - Unsupported combinations return HTTP 400. When grouped by `api_source`, results - use `agents_api` for attributed Agents API activity and `unlabeled` for all - other activity. Without source grouping, `api_source` is null. + Supported fields include `project_id`, `user_id`, `line_item`, `api_key_id`, + `api_source`, and `completion_window`. Support for combining `user_id` with + `project_id` grouping or the `project_ids` filter depends on the organization + and requested time range. Unsupported combinations return HTTP 400. When grouped + by `api_source`, results use `agents_api` for attributed Agents API activity and + `unlabeled` for all other activity. Without source grouping, `api_source` is + null. When grouped by `completion_window`, results use `2h`, `8h`, or + `unlabeled` when no known or applicable window is available. Without window + grouping, `completion_window` is null. Unlabeled does not imply Standard + traffic. The field may be omitted when completion-window reporting is + unavailable. Batch's 24h window and legacy Flex scheduling are not included. + Existing line item names and exact-name filters are unchanged. Keep the same + grouping and filters when following `next_page`. """ limit: int diff --git a/src/openai/types/admin/organization/usage_costs_response.py b/src/openai/types/admin/organization/usage_costs_response.py index 09585155cf..3635757ed3 100644 --- a/src/openai/types/admin/organization/usage_costs_response.py +++ b/src/openai/types/admin/organization/usage_costs_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" @@ -492,6 +494,13 @@ class DataResultOrganizationCostsResult(BaseModel): direct API usage. Without source grouping, this field is null. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + """The background completion window for this result. + + When group_by includes completion_window, the value is 2h, 8h, or unlabeled if + the window is unknown or does not apply. Otherwise, the value is null. + """ + line_item: Optional[str] = None """ When `group_by=line_item`, this field provides the line item of the grouped diff --git a/src/openai/types/admin/organization/usage_embeddings_response.py b/src/openai/types/admin/organization/usage_embeddings_response.py index f2b7339cad..89d848d1dd 100644 --- a/src/openai/types/admin/organization/usage_embeddings_response.py +++ b/src/openai/types/admin/organization/usage_embeddings_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/src/openai/types/admin/organization/usage_file_search_calls_response.py b/src/openai/types/admin/organization/usage_file_search_calls_response.py index 49c6cf276a..6d27c3656c 100644 --- a/src/openai/types/admin/organization/usage_file_search_calls_response.py +++ b/src/openai/types/admin/organization/usage_file_search_calls_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/src/openai/types/admin/organization/usage_images_response.py b/src/openai/types/admin/organization/usage_images_response.py index 513a0eb6c8..3f3c570509 100644 --- a/src/openai/types/admin/organization/usage_images_response.py +++ b/src/openai/types/admin/organization/usage_images_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/src/openai/types/admin/organization/usage_moderations_response.py b/src/openai/types/admin/organization/usage_moderations_response.py index 6f1985258f..a513e76392 100644 --- a/src/openai/types/admin/organization/usage_moderations_response.py +++ b/src/openai/types/admin/organization/usage_moderations_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/src/openai/types/admin/organization/usage_vector_stores_response.py b/src/openai/types/admin/organization/usage_vector_stores_response.py index 60c4567985..37b4101188 100644 --- a/src/openai/types/admin/organization/usage_vector_stores_response.py +++ b/src/openai/types/admin/organization/usage_vector_stores_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/src/openai/types/admin/organization/usage_web_search_calls_response.py b/src/openai/types/admin/organization/usage_web_search_calls_response.py index 209d3e4e21..1623762c01 100644 --- a/src/openai/types/admin/organization/usage_web_search_calls_response.py +++ b/src/openai/types/admin/organization/usage_web_search_calls_response.py @@ -68,6 +68,8 @@ class DataResultOrganizationUsageCompletionsResult(BaseModel): batch or not. """ + completion_window: Optional[Literal["2h", "8h", "unlabeled"]] = None + input_audio_tokens: Optional[int] = None """The aggregated number of uncached audio input tokens used.""" diff --git a/tests/api_resources/admin/organization/test_usage.py b/tests/api_resources/admin/organization/test_usage.py index c304d45c55..a35527a9f2 100644 --- a/tests/api_resources/admin/organization/test_usage.py +++ b/tests/api_resources/admin/organization/test_usage.py @@ -219,17 +219,17 @@ def test_streaming_response_completions(self, client: OpenAI) -> None: @parametrize def test_method_costs(self, client: OpenAI) -> None: usage = client.admin.organization.usage.costs( - start_time=0, + start_time=1796256000, ) assert_matches_type(UsageCostsResponse, usage, path=["response"]) @parametrize def test_method_costs_with_all_params(self, client: OpenAI) -> None: usage = client.admin.organization.usage.costs( - start_time=0, + start_time=1796256000, api_key_ids=["string"], bucket_width="1d", - end_time=0, + end_time=1796342400, group_by=["project_id"], limit=0, line_items=["string"], @@ -241,7 +241,7 @@ def test_method_costs_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_costs(self, client: OpenAI) -> None: response = client.admin.organization.usage.with_raw_response.costs( - start_time=0, + start_time=1796256000, ) assert response.is_closed is True @@ -252,7 +252,7 @@ def test_raw_response_costs(self, client: OpenAI) -> None: @parametrize def test_streaming_response_costs(self, client: OpenAI) -> None: with client.admin.organization.usage.with_streaming_response.costs( - start_time=0, + start_time=1796256000, ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -787,17 +787,17 @@ async def test_streaming_response_completions(self, async_client: AsyncOpenAI) - @parametrize async def test_method_costs(self, async_client: AsyncOpenAI) -> None: usage = await async_client.admin.organization.usage.costs( - start_time=0, + start_time=1796256000, ) assert_matches_type(UsageCostsResponse, usage, path=["response"]) @parametrize async def test_method_costs_with_all_params(self, async_client: AsyncOpenAI) -> None: usage = await async_client.admin.organization.usage.costs( - start_time=0, + start_time=1796256000, api_key_ids=["string"], bucket_width="1d", - end_time=0, + end_time=1796342400, group_by=["project_id"], limit=0, line_items=["string"], @@ -809,7 +809,7 @@ async def test_method_costs_with_all_params(self, async_client: AsyncOpenAI) -> @parametrize async def test_raw_response_costs(self, async_client: AsyncOpenAI) -> None: response = await async_client.admin.organization.usage.with_raw_response.costs( - start_time=0, + start_time=1796256000, ) assert response.is_closed is True @@ -820,7 +820,7 @@ async def test_raw_response_costs(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_costs(self, async_client: AsyncOpenAI) -> None: async with async_client.admin.organization.usage.with_streaming_response.costs( - start_time=0, + start_time=1796256000, ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" diff --git a/tests/test_usage_completion_window.py b/tests/test_usage_completion_window.py new file mode 100644 index 0000000000..409631b895 --- /dev/null +++ b/tests/test_usage_completion_window.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +import httpx2 +import pytest + +from openai import OpenAI, omit +from openai.types.admin.organization.usage_costs_response import DataResultOrganizationCostsResult +from openai.types.admin.organization.usage_completions_response import DataResultOrganizationUsageCompletionsResult + + +@pytest.mark.parametrize("costs", [True, False], ids=["costs", "completions"]) +def test_completion_window(costs: bool) -> None: + cursor = "next+/page=?&," + line_item = "example, input_tokens" + + def respond(request: httpx2.Request) -> httpx2.Response: + assert request.method == "GET" + query = request.url.params + assert query["start_time"] == "0" + groups = query.get_list("group_by[]") + if costs: + assert request.url.path == "/organization/costs" + row: dict[str, object] = { + "object": "organization.costs.result", + "amount": {"value": 0.06, "currency": "usd"}, + "line_item": line_item if groups else None, + "project_id": None, + "model": "example" if groups else None, + "token_type": "input" if groups else None, + } + if groups: + assert groups == ["line_item", "completion_window"] + assert query.get_list("line_items[]") == [line_item] + else: + assert request.url.path == "/organization/usage/completions" + row = { + "object": "organization.usage.completions.result", + "model": "example" if groups else None, + "input_tokens": 100, + "output_tokens": 5, + "num_model_requests": 1, + } + if groups: + assert groups == ["model", "completion_window"] + + next_page = None + if not groups: + rows = [{**row, "completion_window": None}, row] + elif "page" in query: + assert query["page"] == cursor + rows = [{**row, "completion_window": "unlabeled"}] + else: + next_page = cursor + rows = [{**row, "completion_window": w} for w in ("2h", "8h")] + + return httpx2.Response( + 200, + json={ + "object": "page", + "data": [{"object": "bucket", "start_time": 0, "end_time": 86400, "results": rows}], + "has_more": next_page is not None, + "next_page": next_page, + }, + ) + + with OpenAI( + api_key="fake-project-key", + admin_api_key="fake-admin-key", + base_url="https://example.test", + max_retries=0, + http_client=httpx2.Client(transport=httpx2.MockTransport(respond)), + ) as client: + usage = client.admin.organization.usage + windows = [] + page = None + for _ in range(2): + result = ( + usage.costs( + start_time=0, + group_by=["line_item", "completion_window"], + line_items=[line_item], + page=omit if page is None else page, + ) + if costs + else usage.completions( + start_time=0, group_by=["model", "completion_window"], page=omit if page is None else page + ) + ) + for item in result.data[0].results: + if costs: + assert isinstance(item, DataResultOrganizationCostsResult) + assert item.token_type == "input" + else: + assert isinstance(item, DataResultOrganizationUsageCompletionsResult) + assert item.model == "example" + windows.append(item.completion_window) + page = result.next_page + assert result.has_more is (page is not None) + assert windows == ["2h", "8h", "unlabeled"] + assert page is None + + ungrouped = usage.costs(start_time=0) if costs else usage.completions(start_time=0) + for item, present in zip(ungrouped.data[0].results, (True, False), strict=True): + assert isinstance(item, (DataResultOrganizationCostsResult, DataResultOrganizationUsageCompletionsResult)) + assert item.completion_window is None + assert ("completion_window" in item.model_dump(exclude_unset=True)) is present