-
Notifications
You must be signed in to change notification settings - Fork 45
feat(ai-gateway): add organization auto model routing #4056
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
pandemicsyn
wants to merge
12
commits into
main
Choose a base branch
from
florian/feat/org-defined-auto
base: main
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
12 commits
Select commit
Hold shift + click to select a range
4d934f5
feat(ai-gateway): add organization auto model routing
pandemicsyn 1162278
refactor(organizations): remove mode default model bridge
pandemicsyn 6e0261a
fix(organizations): harden organization auto routing
pandemicsyn b3107a9
fix(organizations): use transaction BYOK reads
pandemicsyn ae97b04
Merge remote-tracking branch 'origin/main' into florian/feat/org-defi…
pandemicsyn 48d4c09
Merge remote-tracking branch 'origin/main' into florian/feat/org-defi…
pandemicsyn 412123c
fix(ai-gateway): preserve auto model status
pandemicsyn 29a354e
feat(organizations): unify default model behavior
pandemicsyn cf3f457
fix(organizations): improve default behavior chooser
pandemicsyn f753b11
fix(organizations): capture locked default for audit logs
pandemicsyn 115791b
Merge remote-tracking branch 'origin/main' into florian/feat/org-defi…
pandemicsyn 9f9f610
fix(organizations): validate routed auto targets
pandemicsyn 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
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 |
|---|---|---|
|
|
@@ -17,6 +17,7 @@ import type { | |
| } from '@/lib/ai-gateway/providers/openrouter/types'; | ||
| import { applyProviderSpecificLogic } from '@/lib/ai-gateway/providers/apply-provider-specific-logic'; | ||
| import { getProvider } from '@/lib/ai-gateway/providers/get-provider'; | ||
| import { getDirectByokModel } from '@/lib/ai-gateway/providers/direct-byok'; | ||
| import { buildExperimentPromptCapture } from '@/lib/ai-gateway/experiments/persist'; | ||
| import { isPublicIdExperimented } from '@/lib/ai-gateway/experiments/membership'; | ||
| import { upstreamRequest } from '@/lib/ai-gateway/providers/upstream-request'; | ||
|
|
@@ -48,6 +49,7 @@ import { | |
| modelNotAllowedResponse, | ||
| extractHeaderAndLimitLength, | ||
| noFreeModelsAvailableResponse, | ||
| organizationAutoConfigurationResponse, | ||
| temporarilyUnavailableResponse, | ||
| usageLimitExceededResponse, | ||
| wrapInSafeNextResponse, | ||
|
|
@@ -95,6 +97,7 @@ import { | |
| isKiloAutoModel, | ||
| KILO_AUTO_FREE_MODEL, | ||
| KILO_AUTO_EFFICIENT_MODEL, | ||
| ORG_AUTO_MODEL, | ||
| } from '@/lib/ai-gateway/auto-model'; | ||
| import { applyResolvedAutoModel } from '@/lib/ai-gateway/auto-model/resolution'; | ||
| import { fetchEfficientAutoDecision } from '@/lib/ai-gateway/auto-routing-decision'; | ||
|
|
@@ -242,6 +245,13 @@ export async function POST(request: NextRequest): Promise<NextResponseType<unkno | |
| ? getBalanceAndOrgSettings(res.organizationId, res.user) | ||
| : { balance: 0, settings: undefined, plan: undefined } | ||
| ); | ||
| const organizationContextPromise = Promise.all([authPromise, balanceAndSettingsPromise]).then( | ||
| ([auth, balanceAndSettings]) => ({ | ||
| organizationId: auth.organizationId, | ||
| settings: balanceAndSettings.settings, | ||
| plan: balanceAndSettings.plan, | ||
| }) | ||
| ); | ||
|
|
||
| // Extract IP early (needed for free model routing fallback and rate limiting) | ||
| const ipAddress = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim(); | ||
|
|
@@ -271,6 +281,7 @@ export async function POST(request: NextRequest): Promise<NextResponseType<unkno | |
| } | ||
|
|
||
| let autoModel: string | null = null; | ||
| let routingTarget: string | null = null; | ||
| let classifierCostUsd = 0; | ||
| if (isKiloAutoModel(requestedModelLowerCased)) { | ||
| autoModel = requestedModelLowerCased; | ||
|
|
@@ -317,6 +328,7 @@ export async function POST(request: NextRequest): Promise<NextResponseType<unkno | |
| apiKind: requestBodyParsed.kind, | ||
| clientIp: ipAddress ?? null, | ||
| efficientDecision, | ||
| organizationContext: organizationContextPromise, | ||
| }, | ||
| requestBodyParsed, | ||
| authPromise.then(res => res.user), | ||
|
|
@@ -325,6 +337,10 @@ export async function POST(request: NextRequest): Promise<NextResponseType<unkno | |
| if (autoResult.kind === 'no_free_models_available') { | ||
| return noFreeModelsAvailableResponse(); | ||
| } | ||
| if (autoResult.kind === 'organization_auto_configuration_error') { | ||
| return organizationAutoConfigurationResponse(autoResult.message); | ||
| } | ||
| routingTarget = autoResult.routingTarget ?? null; | ||
| } | ||
|
|
||
| let effectiveModelIdLowerCased = requestBodyParsed.body.model.toLowerCase(); | ||
|
|
@@ -353,6 +369,7 @@ export async function POST(request: NextRequest): Promise<NextResponseType<unkno | |
| const isRateLimitedFreeModelRequest = | ||
| isKiloExclusiveFreeModel(effectiveModelIdLowerCased) || | ||
| autoModel === KILO_AUTO_FREE_MODEL.id || | ||
| routingTarget === KILO_AUTO_FREE_MODEL.id || | ||
| (await isPublicIdExperimented(effectiveModelIdLowerCased)); | ||
| if (isRateLimitedFreeModelRequest) { | ||
| const rateLimit = await resolveRateLimit(feature, ipAddress, authPromise); | ||
|
|
@@ -561,6 +578,29 @@ export async function POST(request: NextRequest): Promise<NextResponseType<unkno | |
| } | ||
| let effectiveProviderContext = initialProviderResultForAbuseService; | ||
|
|
||
| if (autoModel === ORG_AUTO_MODEL.id && routingTarget) { | ||
| try { | ||
| const directByokTarget = await getDirectByokModel(routingTarget); | ||
| if (directByokTarget.provider && effectiveProviderContext.provider.id !== 'direct-byok') { | ||
| return organizationAutoConfigurationResponse( | ||
| `Organization Auto route target '${routingTarget}' is unavailable because this organization does not have an enabled BYOK credential for ${directByokTarget.provider.id}.` | ||
| ); | ||
| } | ||
| } catch { | ||
| return organizationAutoConfigurationResponse( | ||
| 'Organization Auto could not validate this route target against the current model catalog.' | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| // Request-level data-collection opt-out: a caller can set | ||
| // `provider.data_collection: 'deny'` or `provider.zdr: true` on any | ||
| // request to opt that single request out of training/data-retention. | ||
| // Direct experiment upstreams ignore those OpenRouter/Vercel flags | ||
| // (we never reach OpenRouter), but we still capture the prompt to R2 | ||
| // for partner evaluation — which violates the caller's stated | ||
| // intent. Refuse here regardless of org settings, anon/BYOK status, | ||
| // or the org-level check below. | ||
|
Comment on lines
+596
to
+603
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. looks like a random addition? |
||
| if ( | ||
| (await hasBestEffortGuessDataCollectionRequirement(effectiveModelIdLowerCased)) && | ||
| isDataCollectionExplicitlyDisallowed(requestBodyParsed.body.provider) | ||
|
|
||
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
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.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this the only reason we need the extra routingTarget variable?