## Description
Adds the experimental `GET
/api/experimental/organizations/{organization}/ai/model-prices/unpriced`
endpoint behind the "N models not set up" warning on the organization AI
spend page
([Figma](https://www.figma.com/design/6TkixpkUIM5Qv6I7qhM3xZ/AI-Gov---user-spend?node-id=70-11964&t=KQwENGjcQvVT9qkh-4)).
It lists the models used in the period that still hold no price in the
organization, using the query from this stack.
## Changes
- Add the `organizationUnpricedAIModels` handler and
`ExperimentalClient.OrganizationUnpricedAIModels`:
- Reuses `aiSpendRetainedPeriod`, since token usage is subject to data
retention.
- Returns the applied period, `count`, and `models` (provider name,
display name, icon and type, model, token count), most unpriced tokens
first.
- Requires read on the organization's model prices (owners and
organization admins), so the UI only requests it for users who can set
prices.
- Add handler tests for the response, period validation, organization
scoping and role access.
Note: pagination will be added in a follow-up.
Closes AIGOV-730
> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
185 lines
6.6 KiB
Go
185 lines
6.6 KiB
Go
package codersdk
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
)
|
|
|
|
// AIModelPrice is a per-model token price used by AI Gateway to compute the
|
|
// cost of an interception.
|
|
//
|
|
// Prices are integer micro-units per million tokens, so 1000000 is $1.00 per
|
|
// million tokens. A nil price means the price is not known, which the cost
|
|
// calculation treats the same as zero. Distinguish that from an explicit 0,
|
|
// which declares the model free of charge.
|
|
type AIModelPrice struct {
|
|
Provider string `json:"provider"`
|
|
Model string `json:"model"`
|
|
InputPrice *int64 `json:"input_price"`
|
|
OutputPrice *int64 `json:"output_price"`
|
|
CacheReadPrice *int64 `json:"cache_read_price"`
|
|
CacheWritePrice *int64 `json:"cache_write_price"`
|
|
Source AIModelPriceSource `json:"source"`
|
|
CreatedAt time.Time `json:"created_at" format:"date-time"`
|
|
UpdatedAt time.Time `json:"updated_at" format:"date-time"`
|
|
}
|
|
|
|
// AIModelPriceSource is where a model price came from.
|
|
type AIModelPriceSource string
|
|
|
|
const (
|
|
// AIModelPriceSourceDefault is a price from the embedded price book.
|
|
AIModelPriceSourceDefault AIModelPriceSource = "default"
|
|
// AIModelPriceSourceCustom is a price set through the API.
|
|
AIModelPriceSourceCustom AIModelPriceSource = "custom"
|
|
)
|
|
|
|
// AIModelPriceSourceFilter selects which prices a listing reports. It is
|
|
// distinct from AIModelPriceSource because no stored price is "all".
|
|
//
|
|
// @typescript-ignore AIModelPriceSourceFilter
|
|
type AIModelPriceSourceFilter string
|
|
|
|
const (
|
|
AIModelPriceSourceFilterDefault = AIModelPriceSourceFilter(AIModelPriceSourceDefault)
|
|
AIModelPriceSourceFilterCustom = AIModelPriceSourceFilter(AIModelPriceSourceCustom)
|
|
// AIModelPriceSourceFilterAll reports every price a model holds, so a model
|
|
// carrying both appears twice.
|
|
AIModelPriceSourceFilterAll AIModelPriceSourceFilter = "all"
|
|
)
|
|
|
|
// MaxAIModelPricesBytes bounds an upsert request body.
|
|
const MaxAIModelPricesBytes = 1 << 20 // 1 MiB
|
|
|
|
// UpsertAIModelPricesRequest sets prices for the listed models. Models absent
|
|
// from the request are left untouched.
|
|
type UpsertAIModelPricesRequest struct {
|
|
Prices []AIModelPriceUpsert `json:"prices"`
|
|
}
|
|
|
|
// AIModelPriceUpsert is one model's prices in an upsert request. It carries
|
|
// only the writable fields of AIModelPrice.
|
|
type AIModelPriceUpsert struct {
|
|
Provider string `json:"provider"`
|
|
Model string `json:"model"`
|
|
InputPrice *int64 `json:"input_price"`
|
|
OutputPrice *int64 `json:"output_price"`
|
|
CacheReadPrice *int64 `json:"cache_read_price"`
|
|
CacheWritePrice *int64 `json:"cache_write_price"`
|
|
}
|
|
|
|
// AIModelPricesFilter narrows the listed model prices. An empty field does not
|
|
// filter on that attribute.
|
|
//
|
|
// @typescript-ignore AIModelPricesFilter
|
|
type AIModelPricesFilter struct {
|
|
Provider string `json:"provider,omitempty"`
|
|
Model string `json:"model,omitempty"`
|
|
// Source narrows to prices from one source. A model with both reports only
|
|
// its custom price unless this is set.
|
|
Source AIModelPriceSourceFilter `json:"source,omitempty"`
|
|
}
|
|
|
|
func (f AIModelPricesFilter) asRequestOption() RequestOption {
|
|
return func(r *http.Request) {
|
|
query := r.URL.Query()
|
|
if f.Provider != "" {
|
|
query.Set("provider", f.Provider)
|
|
}
|
|
if f.Model != "" {
|
|
query.Set("model", f.Model)
|
|
}
|
|
if f.Source != "" {
|
|
query.Set("source", string(f.Source))
|
|
}
|
|
r.URL.RawQuery = query.Encode()
|
|
}
|
|
}
|
|
|
|
// ListAIModelPrices returns the AI model prices matching the filter.
|
|
func (c *ExperimentalClient) ListAIModelPrices(ctx context.Context, filter AIModelPricesFilter) ([]AIModelPrice, error) {
|
|
res, err := c.Request(ctx, http.MethodGet, "/api/experimental/ai/model-prices", nil, filter.asRequestOption())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, ReadBodyAsError(res)
|
|
}
|
|
|
|
var prices []AIModelPrice
|
|
return prices, ReadBodyAsJSON(res, &prices)
|
|
}
|
|
|
|
// UpsertAIModelPrices sets prices for the models in req. The request is
|
|
// rejected in full if any model fails validation.
|
|
func (c *ExperimentalClient) UpsertAIModelPrices(ctx context.Context, req UpsertAIModelPricesRequest) error {
|
|
res, err := c.Request(ctx, http.MethodPost, "/api/experimental/ai/model-prices", req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != http.StatusNoContent {
|
|
return ReadBodyAsError(res)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UnpricedAIModels lists the models with token usage recorded without a price
|
|
// in the organization over the applied period. Only models without a price now
|
|
// are listed.
|
|
type UnpricedAIModels struct {
|
|
AISpendPeriodWindow
|
|
// Count is the number of models listed.
|
|
Count int64 `json:"count"`
|
|
// Models are ordered by unpriced token count, highest first.
|
|
Models []UnpricedAIModel `json:"models"`
|
|
}
|
|
|
|
// UnpricedAIModel is a requested model with token usage recorded without a
|
|
// price on one provider, and without a price now.
|
|
type UnpricedAIModel struct {
|
|
// ProviderName is the name of the configured provider.
|
|
ProviderName string `json:"provider_name"`
|
|
// ProviderDisplayName falls back to the provider name when unset.
|
|
ProviderDisplayName string `json:"provider_display_name"`
|
|
// ProviderIcon is empty when the provider has no configured icon.
|
|
ProviderIcon string `json:"provider_icon"`
|
|
// ProviderType is the type of the configured provider.
|
|
ProviderType AIProviderType `json:"provider_type"`
|
|
// Model is the model the client requested.
|
|
Model string `json:"model"`
|
|
// TokenCount is the number of tokens used without a price in the period.
|
|
TokenCount int64 `json:"token_count"`
|
|
}
|
|
|
|
// OrganizationUnpricedAIModels returns the models with token usage recorded
|
|
// without a price in the organization over the period. Only models without a
|
|
// price now are returned. The period bounds must be set together. When both
|
|
// are zero, they are omitted and the server uses the current budget period.
|
|
func (c *ExperimentalClient) OrganizationUnpricedAIModels(ctx context.Context, organization uuid.UUID, period AISpendPeriodWindow) (UnpricedAIModels, error) {
|
|
filter := OrganizationAISpendDetailsFilter{
|
|
PeriodStart: period.PeriodStart,
|
|
PeriodEnd: period.PeriodEnd,
|
|
}
|
|
res, err := c.Request(ctx, http.MethodGet,
|
|
fmt.Sprintf("/api/experimental/organizations/%s/ai/model-prices/unpriced", organization.String()),
|
|
nil,
|
|
filter.asRequestOption(),
|
|
)
|
|
if err != nil {
|
|
return UnpricedAIModels{}, xerrors.Errorf("make request: %w", err)
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != http.StatusOK {
|
|
return UnpricedAIModels{}, ReadBodyAsError(res)
|
|
}
|
|
var models UnpricedAIModels
|
|
return models, ReadBodyAsJSON(res, &models)
|
|
}
|