diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index a54306ba70a..cc451074c68 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -770,6 +770,20 @@ const docTemplate = `{ ], "summary": "List AI Gateway models", "operationId": "list-ai-gateway-models", + "parameters": [ + { + "type": "string", + "description": "Search query in the format ` + "`" + `key:value` + "`" + `. Available keys are: model. A bare term searches by model prefix.", + "name": "q", + "in": "query" + }, + { + "type": "string", + "description": "Literal model identifier prefix. Cannot be combined with q.", + "name": "model", + "in": "query" + } + ], "responses": { "200": { "description": "OK", diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index f5627684095..4674a29be23 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -673,6 +673,20 @@ "tags": ["AI Gateway"], "summary": "List AI Gateway models", "operationId": "list-ai-gateway-models", + "parameters": [ + { + "type": "string", + "description": "Search query in the format `key:value`. Available keys are: model. A bare term searches by model prefix.", + "name": "q", + "in": "query" + }, + { + "type": "string", + "description": "Literal model identifier prefix. Cannot be combined with q.", + "name": "model", + "in": "query" + } + ], "responses": { "200": { "description": "OK", diff --git a/codersdk/aibridge.go b/codersdk/aibridge.go index 8460154ee6a..45e255f45f4 100644 --- a/codersdk/aibridge.go +++ b/codersdk/aibridge.go @@ -20,6 +20,9 @@ import ( // $1,000,000 per member per budget period. const MaxAISpendLimitMicros int64 = 1_000_000_000_000 +// MaxAISpendPeriodDays bounds explicit AI spend reporting windows. +const MaxAISpendPeriodDays = 31 + // AIBudgetLimitSource identifies which tier produced the user's // effective budget limit. type AIBudgetLimitSource string @@ -417,6 +420,36 @@ func (c *Client) AIBridgeGetSessionThreads(ctx context.Context, sessionID string return resp, ReadBodyAsJSON(res, &resp) } +// AIBridgeListModelsFilter narrows the distinct models visible to the caller. +// @typescript-ignore AIBridgeListModelsFilter +type AIBridgeListModelsFilter struct { + // Limit defaults to 100, max is 1000. + Pagination Pagination + // Model keeps only identifiers starting with this literal prefix. + Model string +} + +// AIBridgeListModels returns the distinct AI models visible to the caller. +func (c *Client) AIBridgeListModels(ctx context.Context, filter AIBridgeListModelsFilter) ([]string, error) { + res, err := c.Request(ctx, http.MethodGet, "/api/v2/ai-gateway/models", nil, filter.Pagination.asRequestOption(), func(r *http.Request) { + if filter.Model == "" { + return + } + q := r.URL.Query() + q.Set("model", filter.Model) + r.URL.RawQuery = q.Encode() + }) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return nil, ReadBodyAsError(res) + } + var models []string + return models, ReadBodyAsJSON(res, &models) +} + // AIBridgeListClients returns the distinct AI clients visible to the caller. func (c *Client) AIBridgeListClients(ctx context.Context) ([]string, error) { res, err := c.Request(ctx, http.MethodGet, "/api/v2/ai-gateway/clients", nil) diff --git a/docs/reference/api/aigateway.md b/docs/reference/api/aigateway.md index 94cfa6040e2..37aab4b7531 100644 --- a/docs/reference/api/aigateway.md +++ b/docs/reference/api/aigateway.md @@ -55,6 +55,13 @@ curl -X GET http://coder-server:8080/api/v2/ai-gateway/models \ Alias: also available at /api/v2/aibridge/models for backward compatibility. +### Parameters + +| Name | In | Type | Required | Description | +|---------|-------|--------|----------|----------------------------------------------------------------------------------------------------------| +| `q` | query | string | false | Search query in the format `key:value`. Available keys are: model. A bare term searches by model prefix. | +| `model` | query | string | false | Literal model identifier prefix. Cannot be combined with q. | + ### Example responses > 200 Response diff --git a/enterprise/coderd/aibridge.go b/enterprise/coderd/aibridge.go index cb3aa6e46ab..0fbdd86e8ec 100644 --- a/enterprise/coderd/aibridge.go +++ b/enterprise/coderd/aibridge.go @@ -46,7 +46,7 @@ const ( maxGroupMembersAISpendUserIDs = 100 // maxAISpendExportPeriod bounds an explicit AI spend export window to at // most 31 days, matching the maximum length of the monthly default period. - maxAISpendExportPeriod = 31 * 24 * time.Hour + maxAISpendExportPeriod = codersdk.MaxAISpendPeriodDays * 24 * time.Hour // The per-user spend report lists users, not events, so its pages are small. defaultOrganizationAISpendLimit = 10 maxOrganizationAISpendLimit = 100 @@ -503,6 +503,10 @@ func (api *API) aiBridgeGetSessionThreads(rw http.ResponseWriter, r *http.Reques httpapi.Write(ctx, rw, http.StatusOK, resp) } +// likePatternEscaper makes a string match itself under a Postgres LIKE +// pattern, which uses backslash as its default escape character. +var likePatternEscaper = strings.NewReplacer(`\`, `\\`, "%", `\%`, "_", `\_`) + // aiBridgeListModels returns all AI Bridge models a user can see. // // @Summary List AI Gateway models @@ -511,6 +515,8 @@ func (api *API) aiBridgeGetSessionThreads(rw http.ResponseWriter, r *http.Reques // @Security CoderSessionToken // @Produce json // @Tags AI Gateway +// @Param q query string false "Search query in the format `key:value`. Available keys are: model. A bare term searches by model prefix." +// @Param model query string false "Literal model identifier prefix. Cannot be combined with q." // @Success 200 {array} string // @Router /api/v2/ai-gateway/models [get] func (api *API) aiBridgeListModels(rw http.ResponseWriter, r *http.Request) { @@ -534,8 +540,15 @@ func (api *API) aiBridgeListModels(rw http.ResponseWriter, r *http.Request) { } queryStr := r.URL.Query().Get("q") - filter, errs := searchquery.AIBridgeModels(queryStr, page) + modelPrefix := r.URL.Query().Get("model") + if queryStr != "" && modelPrefix != "" { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: "Query parameters \"q\" and \"model\" cannot be combined.", + }) + return + } + filter, errs := searchquery.AIBridgeModels(queryStr, page) if len(errs) > 0 { httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ Message: "Invalid AI Gateway models search query.", @@ -543,6 +556,12 @@ func (api *API) aiBridgeListModels(rw http.ResponseWriter, r *http.Request) { }) return } + // The search grammar cannot carry every recorded identifier (quotes end a + // quoted value) and the query matches with LIKE, so the explicit parameter + // escapes the pattern characters to match the identifier literally. + if modelPrefix != "" { + filter.Model = likePatternEscaper.Replace(modelPrefix) + } models, err := api.Database.ListAIBridgeModels(ctx, filter) if err != nil { diff --git a/enterprise/coderd/aibridge_test.go b/enterprise/coderd/aibridge_test.go index befb09b4de0..f01f99bb1bf 100644 --- a/enterprise/coderd/aibridge_test.go +++ b/enterprise/coderd/aibridge_test.go @@ -1300,6 +1300,89 @@ func TestAIBridgeListSessions(t *testing.T) { }) } +func TestAIBridgeListModels(t *testing.T) { + t.Parallel() + + dv := coderdtest.DeploymentValues(t) + dv.AI.BridgeConfig.Enabled = serpent.Bool(true) + client, db, firstUser := coderdenttest.NewWithDatabase(t, &coderdenttest.Options{ + Options: &coderdtest.Options{ + DeploymentValues: dv, + }, + LicenseOptions: &coderdenttest.LicenseOptions{ + Features: license.Features{ + codersdk.FeatureAIBridge: 1, + }, + }, + }) + + now := dbtime.Now() + endedAt := now.Add(time.Minute) + models := []string{ + "us.anthropic.claude-3-5-sonnet-20241022-v2:0", + `=HYPERLINK("http://insecure/","invoice")`, + "gpt-4", + "gpt_4", + "gpt%4", + `gpt\4`, + } + for _, model := range models { + dbgen.AIBridgeInterception(t, db, database.InsertAIBridgeInterceptionParams{ + InitiatorID: firstUser.UserID, + StartedAt: now, + Model: model, + }, &endedAt) + } + dbgen.AIBridgeInterception(t, db, database.InsertAIBridgeInterceptionParams{ + InitiatorID: firstUser.UserID, + StartedAt: now, + Model: "gpt-5", + }, nil) + + t.Run("ModelMatchesLiterally", func(t *testing.T) { + t.Parallel() + ctx := testutil.Context(t, testutil.WaitLong) + for _, model := range models { + got, err := client.AIBridgeListModels(ctx, codersdk.AIBridgeListModelsFilter{Model: model}) + require.NoError(t, err, model) + require.Equal(t, []string{model}, got, model) + } + }) + + t.Run("ModelIsAPrefix", func(t *testing.T) { + t.Parallel() + ctx := testutil.Context(t, testutil.WaitLong) + got, err := client.AIBridgeListModels(ctx, codersdk.AIBridgeListModelsFilter{Model: "gpt"}) + require.NoError(t, err) + require.ElementsMatch(t, []string{"gpt-4", "gpt_4", "gpt%4", `gpt\4`}, got) + }) + + t.Run("SearchQueryKeepsPatternMatching", func(t *testing.T) { + t.Parallel() + ctx := testutil.Context(t, testutil.WaitLong) + res, err := client.Request(ctx, http.MethodGet, "/api/v2/ai-gateway/models", nil, func(r *http.Request) { + r.URL.RawQuery = "q=gpt_4" + }) + require.NoError(t, err) + defer res.Body.Close() + require.Equal(t, http.StatusOK, res.StatusCode) + var got []string + require.NoError(t, json.NewDecoder(res.Body).Decode(&got)) + require.ElementsMatch(t, []string{"gpt-4", "gpt_4", "gpt%4", `gpt\4`}, got) + }) + + t.Run("RejectsSearchQueryWithModel", func(t *testing.T) { + t.Parallel() + ctx := testutil.Context(t, testutil.WaitLong) + res, err := client.Request(ctx, http.MethodGet, "/api/v2/ai-gateway/models", nil, func(r *http.Request) { + r.URL.RawQuery = "q=gpt&model=gpt" + }) + require.NoError(t, err) + defer res.Body.Close() + require.Equal(t, http.StatusBadRequest, res.StatusCode) + }) +} + func TestAIBridgeListClients(t *testing.T) { t.Parallel() diff --git a/site/src/api/api.test.ts b/site/src/api/api.test.ts index f845911a6bb..9d1424d4194 100644 --- a/site/src/api/api.test.ts +++ b/site/src/api/api.test.ts @@ -2,6 +2,7 @@ import { MockChatModelACL, MockMCPServerConfigACL, MockMCPServerConfigACLAvailable, + MockOrganizationAISpendReport, MockProvisionerJob, MockStoppedWorkspace, MockTemplate, @@ -264,6 +265,51 @@ describe("api.ts", () => { }); }); + describe("getOrganizationAISpendUsers", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("passes the filters and page to the per-user spend endpoint", async () => { + const getSpy = vi + .spyOn(axiosInstance, "get") + .mockResolvedValueOnce({ data: MockOrganizationAISpendReport }); + + const result = await API.getOrganizationAISpendUsers("my-org", { + period_start: "2026-07-01T00:00:00Z", + period_end: "2026-08-01T00:00:00Z", + provider_name: "openai", + limit: 10, + offset: 20, + }); + + expect(getSpy).toHaveBeenCalledTimes(1); + const [url] = getSpy.mock.calls[0]; + expect(url).toContain("/api/v2/organizations/my-org/ai/spend/users?"); + expect(url).toContain("provider_name=openai"); + expect(url).toContain("limit=10"); + expect(url).toContain("offset=20"); + expect(result).toStrictEqual(MockOrganizationAISpendReport); + }); + + it("omits a zero limit and offset so the server applies its defaults", async () => { + const getSpy = vi + .spyOn(axiosInstance, "get") + .mockResolvedValueOnce({ data: MockOrganizationAISpendReport }); + + await API.getOrganizationAISpendUsers("my-org", { + provider_name: "openai", + limit: 0, + offset: 0, + }); + + const [url] = getSpy.mock.calls[0]; + expect(url).toBe( + "/api/v2/organizations/my-org/ai/spend/users?provider_name=openai", + ); + }); + }); + describe("update", () => { describe("given a running workspace", () => { it("stops with current version before starting with the latest version", async () => { diff --git a/site/src/api/api.ts b/site/src/api/api.ts index 71597edfeb7..d7bb2162621 100644 --- a/site/src/api/api.ts +++ b/site/src/api/api.ts @@ -423,6 +423,9 @@ export class ParameterValidationError extends Error { } } +type OrganizationAISpendParams = TypesGen.OrganizationAISpendFilter & + TypesGen.OrganizationAISpendPage; + export type GetProvisionerJobsParams = { status?: string; limit?: number; @@ -3103,6 +3106,25 @@ class ApiMethods { return response.data; }; + getOrganizationAISpendUsers = async ( + organizationId: string, + { limit, offset, ...filter }: OrganizationAISpendParams, + ): Promise => { + // Like the Go SDK, a zero page value means the server default; the + // endpoint rejects an explicit limit=0. + const url = getURLWithSearchParams( + `/api/v2/organizations/${organizationId}/ai/spend/users`, + { + ...filter, + limit: limit !== undefined && limit > 0 ? limit : undefined, + offset: offset !== undefined && offset > 0 ? offset : undefined, + }, + ); + const response = + await this.axios.get(url); + return response.data; + }; + getAIProviders = async (): Promise => { const response = await this.axios.get( "/api/v2/ai/providers", diff --git a/site/src/api/typesGenerated.ts b/site/src/api/typesGenerated.ts index 76ee61e9c5a..9b4cae9916a 100644 --- a/site/src/api/typesGenerated.ts +++ b/site/src/api/typesGenerated.ts @@ -6126,6 +6126,12 @@ export const MaxAIModelPricesBytes = 1048576; // 1 MiB */ export const MaxAISpendLimitMicros = 1000000000000; +// From codersdk/aibridge.go +/** + * MaxAISpendPeriodDays bounds explicit AI spend reporting windows. + */ +export const MaxAISpendPeriodDays = 31; + // From codersdk/chats.go /** * MaxChatFileIDs is the number of most recent attachments a chat diff --git a/site/src/testHelpers/entities.ts b/site/src/testHelpers/entities.ts index a46c5a480aa..9cc3086c5da 100644 --- a/site/src/testHelpers/entities.ts +++ b/site/src/testHelpers/entities.ts @@ -5596,6 +5596,41 @@ export const MockAIProviderCopilot: TypesGen.AIProvider = { updated_at: "2026-05-14T10:00:00Z", }; +const MockOrganizationAISpendUser: TypesGen.OrganizationAISpendUser = { + user_id: MockUserOwner.id, + username: MockUserOwner.username, + name: "Test User", + avatar_url: "https://avatars.githubusercontent.com/u/95932066?s=200&v=4", + cost_micros: 2_500_000, + unpriced_usage_count: 0, + providers: ["anthropic", "openai"], + clients: ["Claude Code", "Cursor"], + models: ["claude-opus-4-6", "gpt-5.4"], +}; + +export const MockOrganizationAISpendReport: TypesGen.OrganizationAISpendReport = + { + period_start: "2026-02-10T00:00:00Z", + period_end: "2026-03-12T00:00:00Z", + retention_start: "2026-01-11T15:30:00Z", + count: 2, + totals: { cost_micros: 3_500_000, unpriced_usage_count: 0 }, + users: [ + MockOrganizationAISpendUser, + { + ...MockOrganizationAISpendUser, + user_id: "5e1a2b3c-4d5e-4f60-8a9b-0c1d2e3f4a5b", + username: "alice", + name: "Alice Liddell", + avatar_url: "", + cost_micros: 1_000_000, + providers: ["anthropic"], + clients: ["Unknown"], + models: ["claude-opus-4-6"], + }, + ], + }; + export const MockAIProviders: TypesGen.AIProvider[] = [ MockAIProviderOpenAI, MockAIProviderAnthropic,