-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat(providers): hosted-key support for LLM providers (flag-gated, no rate limiting) #5127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TheodoreSpeaks
wants to merge
8
commits into
staging
Choose a base branch
from
fix/use-hosted-key-agent
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
17f342c
feat(providers): hosted-key support for LLM providers (flag-gated, no…
TheodoreSpeaks 12a4dd1
Merge remote-tracking branch 'origin/staging' into fix/use-hosted-key…
TheodoreSpeaks 03f9159
test(providers): complete provider-utils/env mocks for hosted-key str…
TheodoreSpeaks 5f9046e
fix(providers): respect user-provided key over hosted pool in hosted-…
TheodoreSpeaks 8d6b768
fix(providers): settle hosted-key streaming cost on stream drain, not…
TheodoreSpeaks ed64de9
fix(providers): record hosted-key failure when a hosted stream errors…
TheodoreSpeaks c96a2f8
fix(providers): record hosted-stream failures provider-agnostically a…
TheodoreSpeaks 4d27d1b
fix(providers): strip client-supplied hostedKey so it can't skew host…
TheodoreSpeaks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { mockRecordUsed, mockRecordCostCharged } = vi.hoisted(() => ({ | ||
| mockRecordUsed: vi.fn(), | ||
| mockRecordCostCharged: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/monitoring/metrics', () => ({ | ||
| hostedKeyMetrics: { | ||
| recordUsed: mockRecordUsed, | ||
| recordCostCharged: mockRecordCostCharged, | ||
| }, | ||
| })) | ||
|
|
||
| import { | ||
| calculateHostedCost, | ||
| classifyHostedKeyFailure, | ||
| emitHostedKeyUsage, | ||
| } from '@/lib/api-key/hosted-cost' | ||
|
|
||
| describe('calculateHostedCost (tool pricing)', () => { | ||
| it('per_request returns the flat fee', () => { | ||
| expect(calculateHostedCost({ type: 'per_request', cost: 0.005 }, {}, {})).toEqual({ | ||
| cost: 0.005, | ||
| }) | ||
| }) | ||
|
|
||
| it('custom returns a numeric getCost result', () => { | ||
| const pricing = { type: 'custom' as const, getCost: () => 0.42 } | ||
| expect(calculateHostedCost(pricing, {}, {})).toEqual({ cost: 0.42 }) | ||
| }) | ||
|
|
||
| it('custom passes through a structured getCost result with metadata', () => { | ||
| const pricing = { | ||
| type: 'custom' as const, | ||
| getCost: () => ({ cost: 1.5, metadata: { units: 3 } }), | ||
| } | ||
| expect(calculateHostedCost(pricing, {}, {})).toEqual({ cost: 1.5, metadata: { units: 3 } }) | ||
| }) | ||
|
|
||
| it('forwards params and response to custom getCost', () => { | ||
| const getCost = vi.fn(() => 1) | ||
| const params = { a: 1 } | ||
| const response = { b: 2 } | ||
| calculateHostedCost({ type: 'custom', getCost }, params, response) | ||
| expect(getCost).toHaveBeenCalledWith(params, response) | ||
| }) | ||
| }) | ||
|
|
||
| describe('classifyHostedKeyFailure', () => { | ||
| it('classifies structured SDK errors by status', () => { | ||
| expect(classifyHostedKeyFailure({ status: 429 })).toBe('rate_limited') | ||
| expect(classifyHostedKeyFailure({ status: 503 })).toBe('rate_limited') | ||
| expect(classifyHostedKeyFailure({ status: 401 })).toBe('auth') | ||
| expect(classifyHostedKeyFailure({ status: 403, message: 'quota exceeded' })).toBe( | ||
| 'rate_limited' | ||
| ) | ||
| expect(classifyHostedKeyFailure({ status: 500 })).toBe('other') | ||
| }) | ||
|
|
||
| it('classifies message-embedded status (provider errors with no .status)', () => { | ||
| // Regression: the previous `\bunauthor\b` regex never matched "Unauthorized". | ||
| expect(classifyHostedKeyFailure(new Error('Unauthorized'))).toBe('auth') | ||
| expect(classifyHostedKeyFailure(new Error('OpenAI API error (401): bad key'))).toBe('auth') | ||
| expect(classifyHostedKeyFailure(new Error('Forbidden'))).toBe('auth') | ||
| expect(classifyHostedKeyFailure(new Error('Invalid API key provided'))).toBe('auth') | ||
| expect(classifyHostedKeyFailure(new Error('API error (429): rate limit'))).toBe('rate_limited') | ||
| expect(classifyHostedKeyFailure(new Error('Internal Server Error (500)'))).toBe('other') | ||
| }) | ||
| }) | ||
|
|
||
| describe('emitHostedKeyUsage', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| it('records both usage and cost with the provider/tool/key labels', () => { | ||
| emitHostedKeyUsage({ | ||
| provider: 'openai', | ||
| tool: 'gpt-4o', | ||
| key: 'OPENAI_API_KEY_2', | ||
| costTotal: 0.03, | ||
| }) | ||
|
|
||
| expect(mockRecordUsed).toHaveBeenCalledWith({ | ||
| provider: 'openai', | ||
| tool: 'gpt-4o', | ||
| key: 'OPENAI_API_KEY_2', | ||
| }) | ||
| expect(mockRecordCostCharged).toHaveBeenCalledWith(0.03, { provider: 'openai', tool: 'gpt-4o' }) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import { hostedKeyMetrics } from '@/lib/monitoring/metrics' | ||
| import type { ToolHostingPricing } from '@/tools/types' | ||
|
|
||
| export interface HostedCostResult { | ||
| /** Total billable cost in dollars. */ | ||
| cost: number | ||
| /** Optional metadata about the cost (e.g. provider breakdown from `custom` pricing). */ | ||
| metadata?: Record<string, unknown> | ||
| } | ||
|
|
||
| /** | ||
| * Cost for a hosted-key **tool** call. Tools declare config-driven pricing — | ||
| * a flat `per_request` fee or a response-derived `custom` fee. LLM providers do | ||
| * NOT use this: their cost is token-based and computed directly via | ||
| * {@link import('@/providers/utils').calculateCost}. | ||
| */ | ||
| export function calculateHostedCost( | ||
| pricing: ToolHostingPricing, | ||
| params: Record<string, unknown>, | ||
| response: Record<string, unknown> | ||
| ): HostedCostResult { | ||
| switch (pricing.type) { | ||
| case 'per_request': | ||
| return { cost: pricing.cost } | ||
|
|
||
| case 'custom': { | ||
| const result = pricing.getCost(params, response) | ||
| return typeof result === 'number' ? { cost: result } : result | ||
| } | ||
|
|
||
| default: { | ||
| const exhaustiveCheck: never = pricing | ||
| throw new Error(`Unknown pricing type: ${(exhaustiveCheck as ToolHostingPricing).type}`) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Classify a thrown error into a hosted-key failure reason for metrics. Handles | ||
| * both structured SDK errors (numeric `.status`) and provider errors that embed | ||
| * the status in the message string (e.g. `API error (401): ...`). Some providers | ||
| * signal quota/rate-limit via 401/403 + a descriptive message, so those count as | ||
| * `rate_limited`, not `auth`. | ||
| */ | ||
| export function classifyHostedKeyFailure(error: unknown): 'rate_limited' | 'auth' | 'other' { | ||
| const status = (error as { status?: number } | null)?.status | ||
| const message = ((error as { message?: string } | null)?.message ?? '').toLowerCase() | ||
|
|
||
| if (status === 429 || status === 503) return 'rate_limited' | ||
| if (status === 401 || status === 403) { | ||
| return message.includes('quota') || message.includes('rate limit') ? 'rate_limited' : 'auth' | ||
| } | ||
|
|
||
| // No structured status (e.g. provider errors that embed it in the message). | ||
| if (status === undefined) { | ||
| if ( | ||
| message.includes('quota') || | ||
| message.includes('rate limit') || | ||
| /\b(429|503)\b/.test(message) | ||
| ) | ||
| return 'rate_limited' | ||
| if ( | ||
| /\b(401|403)\b/.test(message) || | ||
| message.includes('unauthor') || | ||
| message.includes('forbidden') || | ||
| message.includes('invalid api key') | ||
| ) | ||
| return 'auth' | ||
| } | ||
| return 'other' | ||
| } | ||
|
|
||
| /** | ||
| * Emit hosted-key usage telemetry for a completed call. CloudWatch only — never | ||
| * a billing write. `recordCostCharged` self-guards on `costTotal > 0`. The | ||
| * `tool` label carries the tool id for tools, or the model id for LLM calls. | ||
| */ | ||
| export function emitHostedKeyUsage(labels: { | ||
| provider: string | ||
| tool: string | ||
| key: string | ||
| costTotal: number | ||
| }): void { | ||
| hostedKeyMetrics.recordUsed({ | ||
| provider: labels.provider, | ||
| tool: labels.tool, | ||
| key: labels.key, | ||
| }) | ||
| hostedKeyMetrics.recordCostCharged(labels.costTotal, { | ||
| provider: labels.provider, | ||
| tool: labels.tool, | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.