π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(model-runtime): fail-fast pre-flight context check for OpenAI-compatible providers (#14824)
Arvin Xu625cf80b84e9
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex 19de492f940..19200c1a991 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -691,6 +691,141 @@ describe('LobeOpenAICompatibleFactory', () => {});});+ describe('contextPreFlight option', () => {+ const tightModel: any = {+ contextWindowTokens: 2000,+ displayName: 'Tight',+ id: 'tight-model',+ maxOutput: 8000,+ type: 'chat',+ };+ const roomyModel: any = {+ contextWindowTokens: 200_000,+ displayName: 'Roomy',+ id: 'roomy-model',+ maxOutput: 8000,+ type: 'chat',+ };++ it('aborts before dispatch with ExceededContextWindow when prompt exceeds ctx', async () => {+ const LobePreFlightProvider = createOpenAICompatibleRuntime({+ baseURL: defaultBaseURL,+ chatCompletion: {+ contextPreFlight: { models: [tightModel] },+ },+ provider: 'preflight-test',+ });++ const instance = new LobePreFlightProvider({ apiKey: 'test' });+ const mockCreateMethod = vi+ .spyOn(instance['client'].chat.completions, 'create')+ .mockResolvedValue(new ReadableStream() as any);++ const longContent = 'a'.repeat(20_000);++ try {+ await instance.chat({+ messages: [{ content: longContent, role: 'user' }],+ model: 'tight-model',+ temperature: 0,+ });+ expect.fail('expected chat to reject');+ } catch (error) {+ expect((error as any).errorType).toBe(AgentRuntimeErrorType.ExceededContextWindow);+ expect((error as any).error.type).toBe('context_exceeded_pre_flight');+ expect((error as any).error.model).toBe('tight-model');+ expect((error as any).error.ctx).toBe(2000);+ expect((error as any).error.promptTokens).toBeGreaterThan(0);+ expect((error as any).error.shortBy).toBe(+ (error as any).error.promptTokens - (error as any).error.ctx,+ );+ expect((error as any).error.suggestions).toEqual([+ 'fork_topic',+ 'switch_to_larger_ctx_model',+ ]);+ }++ expect(mockCreateMethod).not.toHaveBeenCalled();+ });++ it('passes through when prompt fits comfortably', async () => {+ const LobePreFlightProvider = createOpenAICompatibleRuntime({+ baseURL: defaultBaseURL,+ chatCompletion: {+ contextPreFlight: { models: [roomyModel] },+ },+ provider: 'preflight-test',+ });++ const instance = new LobePreFlightProvider({ apiKey: 'test' });+ const mockCreateMethod = vi+ .spyOn(instance['client'].chat.completions, 'create')+ .mockResolvedValue(new ReadableStream() as any);++ await instance.chat({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'roomy-model',+ temperature: 0,+ });++ expect(mockCreateMethod).toHaveBeenCalledTimes(1);+ });++ it('skips when the model is unknown to the pre-flight list', async () => {+ const LobePreFlightProvider = createOpenAICompatibleRuntime({+ baseURL: defaultBaseURL,+ chatCompletion: {+ contextPreFlight: { models: [tightModel] },+ },+ provider: 'preflight-test',+ });++ const instance = new LobePreFlightProvider({ apiKey: 'test' });+ const mockCreateMethod = vi+ .spyOn(instance['client'].chat.completions, 'create')+ .mockResolvedValue(new ReadableStream() as any);++ const longContent = 'a'.repeat(20_000);+ await instance.chat({+ messages: [{ content: longContent, role: 'user' }],+ model: 'unknown-model',+ temperature: 0,+ });++ expect(mockCreateMethod).toHaveBeenCalledTimes(1);+ });++ it('passes through a near-limit prompt that still fits the window', async () => {+ // Regression: prior implementation deducted a 1024 buffer + 1024+ // minOutputTokens before deciding, which rejected a ~198.5k-token+ // prompt against a 200k-token window. The corrected threshold+ // only fires on real overflow.+ const LobePreFlightProvider = createOpenAICompatibleRuntime({+ baseURL: defaultBaseURL,+ chatCompletion: {+ contextPreFlight: { models: [roomyModel] },+ },+ provider: 'preflight-test',+ });++ const instance = new LobePreFlightProvider({ apiKey: 'test' });+ const mockCreateMethod = vi+ .spyOn(instance['client'].chat.completions, 'create')+ .mockResolvedValue(new ReadableStream() as any);++ // ~4 chars/token, so this estimates around 198.5k tokens.+ const nearLimitContent = 'a'.repeat(794_000);++ await instance.chat({+ messages: [{ content: nearLimitContent, role: 'user' }],+ model: 'roomy-model',+ temperature: 0,+ });++ expect(mockCreateMethod).toHaveBeenCalledTimes(1);+ });+ });+describe('cancel request', () => {it('should cancel ongoing request correctly', async () => {const controller = new AbortController();diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex d4d19cb660b..2c7d9f84d52 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -2,7 +2,7 @@ import type { ChatModelCard } from '@lobechat/types';import dayjs from 'dayjs';import utc from 'dayjs/plugin/utc';import debug from 'debug';-import type { AiModelType } from 'model-bank';+import type { AiFullModelCard, AiModelType } from 'model-bank';import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';import type { ClientOptions } from 'openai';import OpenAI from 'openai';@@ -44,6 +44,11 @@ import { isExceededContextWindowError } from '../../utils/isExceededContextWindoimport { isInsufficientQuotaError } from '../../utils/isInsufficientQuotaError';import { isQuotaLimitError } from '../../utils/isQuotaLimitError';import { postProcessModelList } from '../../utils/postProcessModelList';+import {+ assertContextWithinWindow,+ type AssertContextWithinWindowOptions,+ ContextExceededPreFlightError,+} from '../../utils/resolveSafeMaxTokens';import { StreamingResponse } from '../../utils/response';import type { LobeRuntimeAI } from '../BaseAI';import { convertOpenAIMessages, convertOpenAIResponseInputs } from '../contextBuilders/openai';@@ -103,6 +108,23 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =apiKey?: string;baseURL?: string;chatCompletion?: {+ /**+ * When set, the factory runs a pre-flight token estimate against the+ * provided model list before dispatching to upstream. If the estimated+ * prompt tokens strictly exceed the model's context window, the+ * request is aborted with a structured `ExceededContextWindow` error+ * β see LOBE-8974.+ *+ * This is for providers like NVIDIA / DeepSeek where the harness does+ * not cap `max_tokens` itself but we still want to fail fast on doomed+ * requests instead of round-tripping to the upstream just to get a+ * 400 back. Providers that manage `max_tokens` themselves (e.g.+ * MiniMax via `resolveSafeMaxTokens`) still benefit because the+ * factory's centralised error handler converts the same error class.+ */+ contextPreFlight?: AssertContextWithinWindowOptions & {+ models: AiFullModelCard[];+ };excludeUsage?: boolean;forceImageBase64?: boolean;forceVideoBase64?: boolean;@@ -406,6 +428,14 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anprocessedPayload = { ...payload, apiMode: 'responses' } as any;}+ // Pre-flight: abort doomed requests before invoking handlePayload so+ // providers don't waste a round-trip to upstream just to get a 400.+ // See LOBE-8974.+ if (chatCompletion?.contextPreFlight) {+ const { models: preFlightModels, ...preFlightOptions } = chatCompletion.contextPreFlight;+ assertContextWithinWindow(processedPayload, preFlightModels, preFlightOptions);+ }+// Then perform factory-level processingconst handledPayload = chatCompletion?.handlePayload? chatCompletion.handlePayload(processedPayload, this._options)@@ -968,6 +998,20 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = andesensitizedEndpoint = desensitizeUrl(this.baseURL);}+ // Pre-flight context-window failures get a structured payload so the+ // UI can offer fork / switch-model affordances instead of surfacing a+ // raw provider 400. See LOBE-8974.+ if (error instanceof ContextExceededPreFlightError) {+ log('pre-flight context exceeded: %s', error.message);+ return AgentRuntimeError.chat({+ endpoint: desensitizedEndpoint,+ error: error.toPayload(),+ errorType: AgentRuntimeErrorType.ExceededContextWindow,+ message: error.message,+ provider: this.id,+ });+ }+if (chatCompletion?.handleError) {log('using custom error handler');const errorResult = chatCompletion.handleError(error, this._options);diff --git a/packages/model-runtime/src/providers/deepseek/index.ts b/packages/model-runtime/src/providers/deepseek/index.tsindex 86395315e64..c7bde32550c 100644--- a/packages/model-runtime/src/providers/deepseek/index.ts+++ b/packages/model-runtime/src/providers/deepseek/index.ts@@ -1,6 +1,6 @@import type Anthropic from '@anthropic-ai/sdk';import type { ChatModelCard } from '@lobechat/types';-import { ModelProvider } from 'model-bank';+import { deepseek as deepseekChatModels, ModelProvider } from 'model-bank';import type OpenAI from 'openai';import {@@ -251,6 +251,10 @@ export const LobeDeepSeekAnthropicAI = createAnthropicCompatibleRuntime(anthropiexport const openAIParams = {baseURL: DEFAULT_DEEPSEEK_BASE_URL,chatCompletion: {+ // DeepSeek upstream rejects requests where input alone exceeds the+ // model context window with a 400 carrying `max_completion=0` in the+ // message. Fail fast before round-tripping. See LOBE-8974.+ contextPreFlight: { models: deepseekChatModels },handlePayload: buildDeepSeekOpenAIPayload,},debug: {diff --git a/packages/model-runtime/src/providers/minimax/index.test.ts b/packages/model-runtime/src/providers/minimax/index.test.tsindex b51bf502aea..4a81d670670 100644--- a/packages/model-runtime/src/providers/minimax/index.test.ts+++ b/packages/model-runtime/src/providers/minimax/index.test.ts@@ -3,8 +3,7 @@ import { ModelProvider } from 'model-bank';import { describe, expect, it } from 'vitest';import { testProvider } from '../../providerTestUtils';-import { AgentRuntimeErrorType } from '../../types/error';-import { MaxTokensExceededError } from '../../utils/resolveSafeMaxTokens';+import { ContextExceededPreFlightError } from '../../utils/resolveSafeMaxTokens';import { LobeMinimaxAI, params } from './index';const provider = ModelProvider.Minimax;@@ -22,7 +21,6 @@ testProvider({});const handlePayload = params.chatCompletion.handlePayload;-const handleError = params.chatCompletion.handleError;describe('LobeMinimaxAI - handlePayload', () => {it('respects an explicitly provided max_tokens', () => {@@ -73,7 +71,7 @@ describe('LobeMinimaxAI - handlePayload', () => {expect(result.max_tokens).toBeGreaterThanOrEqual(1024);});- it('throws MaxTokensExceededError when no headroom remains', () => {+ it('throws ContextExceededPreFlightError when no headroom remains', () => {// M2-her: contextWindow=65_536. With ~67k tokens of input there is no// room left for the minimum 1024 output tokens, so we should bail out// before the request reaches the upstream API.@@ -85,7 +83,7 @@ describe('LobeMinimaxAI - handlePayload', () => {model: 'M2-her',temperature: 1,} as any),- ).toThrow(MaxTokensExceededError);+ ).toThrow(ContextExceededPreFlightError);});it('estimates tokens against the sanitized messages, not the raw payload', () => {@@ -142,27 +140,3 @@ describe('LobeMinimaxAI - handlePayload', () => {expect(result.reasoning_split).toBe(true);});});--describe('LobeMinimaxAI - handleError', () => {- it('converts MaxTokensExceededError into ExceededContextWindow', () => {- const error = new MaxTokensExceededError({- contextWindowTokens: 204_800,- estimatedInputTokens: 200_000,- minOutputTokens: 1024,- modelId: 'MiniMax-M2.7',- });-- const result = handleError!(error);-- expect(result).toBeDefined();- expect(result!.errorType).toBe(AgentRuntimeErrorType.ExceededContextWindow);- expect(result!.message).toContain('context window');- expect((result!.error as any).estimatedInputTokens).toBe(200_000);- expect((result!.error as any).modelId).toBe('MiniMax-M2.7');- });-- it('passes through unrelated errors', () => {- const result = handleError!(new Error('boom'));- expect(result).toBeUndefined();- });-});diff --git a/packages/model-runtime/src/providers/minimax/index.ts b/packages/model-runtime/src/providers/minimax/index.tsindex ff1140e8d04..e5a0d8182cd 100644--- a/packages/model-runtime/src/providers/minimax/index.ts+++ b/packages/model-runtime/src/providers/minimax/index.ts@@ -2,29 +2,13 @@ import { minimax as minimaxChatModels, ModelProvider } from 'model-bank';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';import { resolveParameters } from '../../core/parameterResolver';-import { AgentRuntimeErrorType } from '../../types/error';-import { MaxTokensExceededError, resolveSafeMaxTokens } from '../../utils/resolveSafeMaxTokens';+import { resolveSafeMaxTokens } from '../../utils/resolveSafeMaxTokens';import { createMiniMaxImage } from './createImage';import { createMiniMaxVideo } from './createVideo';export const params = {baseURL: 'https://api.minimaxi.com/v1',chatCompletion: {- handleError: (error: any) => {- if (error instanceof MaxTokensExceededError) {- return {- error: {- contextWindowTokens: error.contextWindowTokens,- estimatedInputTokens: error.estimatedInputTokens,- message: error.message,- modelId: error.modelId,- },- errorType: AgentRuntimeErrorType.ExceededContextWindow,- message: error.message,- };- }- return undefined;- },handlePayload: (payload: any) => {const { enabledSearch, max_tokens, messages, temperature, top_p, ...params } = payload;diff --git a/packages/model-runtime/src/providers/nvidia/index.ts b/packages/model-runtime/src/providers/nvidia/index.tsindex 207fbdf6a8b..4fb2a96a70c 100644--- a/packages/model-runtime/src/providers/nvidia/index.ts+++ b/packages/model-runtime/src/providers/nvidia/index.ts@@ -1,4 +1,4 @@-import { ModelProvider } from 'model-bank';+import { ModelProvider, nvidia as nvidiaChatModels } from 'model-bank';import { type OpenAICompatibleFactoryOptions } from '../../core/openaiCompatibleFactory';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';@@ -19,6 +19,12 @@ export interface NvidiaModelCard {export const params = {baseURL: 'https://integrate.api.nvidia.com/v1',chatCompletion: {+ // NVIDIA NIM rejects requests where prompt tokens already meet or+ // exceed the model context window (returns 400 "requested 0 output+ // tokens and your prompt contains at least N+1 input tokens"). Fail+ // fast so the UI can surface a fork / switch-model affordance instead+ // of a raw provider error. See LOBE-8974.+ contextPreFlight: { models: nvidiaChatModels },handlePayload: (payload) => {const { model, thinking, messages, ...rest } = payload;diff --git a/packages/model-runtime/src/utils/resolveSafeMaxTokens.test.ts b/packages/model-runtime/src/utils/resolveSafeMaxTokens.test.tsindex 6b4da6ef37c..4688ac57fac 100644--- a/packages/model-runtime/src/utils/resolveSafeMaxTokens.test.ts+++ b/packages/model-runtime/src/utils/resolveSafeMaxTokens.test.ts@@ -3,9 +3,12 @@ import { type AiFullModelCard } from 'model-bank';import { describe, expect, it } from 'vitest';import {+ assertContextWithinWindow,+ CONTEXT_EXCEEDED_PRE_FLIGHT_TYPE,+ ContextExceededPreFlightError,DEFAULT_MAX_TOKENS_BUFFER,DEFAULT_MIN_OUTPUT_TOKENS,- MaxTokensExceededError,+ DEFAULT_PRE_FLIGHT_SUGGESTIONS,resolveSafeMaxTokens,} from './resolveSafeMaxTokens';@@ -66,8 +69,6 @@ describe('resolveSafeMaxTokens', () => {});it('caps max_tokens to remaining window when input is large', () => {- // Build a payload large enough that contextWindow - input - buffer < maxOutput- // contextWindow=10_000, maxOutput=8000, big input β must be capped below 8000.const longContent = 'a'.repeat(20_000); // ~5000+ estimated tokensconst result = resolveSafeMaxTokens({@@ -82,8 +83,7 @@ describe('resolveSafeMaxTokens', () => {expect(result!).toBeGreaterThanOrEqual(DEFAULT_MIN_OUTPUT_TOKENS);});- it('throws MaxTokensExceededError when remaining window < minOutputTokens', () => {- // contextWindow=2000, big input β no room left+ it('throws ContextExceededPreFlightError when remaining window < minOutputTokens', () => {const longContent = 'a'.repeat(20_000);expect(() =>resolveSafeMaxTokens(@@ -93,10 +93,10 @@ describe('resolveSafeMaxTokens', () => {} as any,[baseModel({ contextWindowTokens: 2000, maxOutput: 8000 })],),- ).toThrow(MaxTokensExceededError);+ ).toThrow(ContextExceededPreFlightError);});- it('attaches diagnostic data to MaxTokensExceededError', () => {+ it('attaches structured diagnostic data to ContextExceededPreFlightError', () => {const longContent = 'a'.repeat(20_000);try {resolveSafeMaxTokens(@@ -108,17 +108,19 @@ describe('resolveSafeMaxTokens', () => {);throw new Error('should have thrown');} catch (error) {- expect(error).toBeInstanceOf(MaxTokensExceededError);- const err = error as MaxTokensExceededError;- expect(err.modelId).toBe('tight-model');- expect(err.contextWindowTokens).toBe(2000);- expect(err.estimatedInputTokens).toBeGreaterThan(0);+ expect(error).toBeInstanceOf(ContextExceededPreFlightError);+ const err = error as ContextExceededPreFlightError;+ expect(err.type).toBe(CONTEXT_EXCEEDED_PRE_FLIGHT_TYPE);+ expect(err.model).toBe('tight-model');+ expect(err.ctx).toBe(2000);+ expect(err.promptTokens).toBeGreaterThan(0);+ expect(err.shortBy).toBe(err.promptTokens - err.ctx);expect(err.minOutputTokens).toBe(DEFAULT_MIN_OUTPUT_TOKENS);+ expect(err.suggestions).toEqual(DEFAULT_PRE_FLIGHT_SUGGESTIONS);}});it('factors tools into the input estimate', () => {- // Same messages, but adding many tool definitions should reduce remaining headroom.const baseArgs = {messages: [{ content: 'hi', role: 'user' }],model: 'test-model',@@ -165,3 +167,101 @@ describe('resolveSafeMaxTokens', () => {expect(largerBuffer).toBe(defaultBuffer! - 1000);});});++describe('assertContextWithinWindow', () => {+ it('is a no-op when input fits comfortably', () => {+ expect(() =>+ assertContextWithinWindow(+ { messages: [{ content: 'hi', role: 'user' }], model: 'test-model' } as any,+ [baseModel({ contextWindowTokens: 200_000 })],+ ),+ ).not.toThrow();+ });++ it('is a no-op when the model is unknown (we cannot decide)', () => {+ expect(() =>+ assertContextWithinWindow(+ { messages: [{ content: 'hi', role: 'user' }], model: 'unknown' } as any,+ [baseModel()],+ ),+ ).not.toThrow();+ });++ it('is a no-op when the model has no contextWindowTokens', () => {+ expect(() =>+ assertContextWithinWindow(+ {+ messages: [{ content: 'a'.repeat(1_000_000), role: 'user' }],+ model: 'test-model',+ } as any,+ [baseModel({ contextWindowTokens: undefined as any })],+ ),+ ).not.toThrow();+ });++ it('throws ContextExceededPreFlightError when prompt overflows the window', () => {+ const longContent = 'a'.repeat(20_000);+ expect(() =>+ assertContextWithinWindow(+ { messages: [{ content: longContent, role: 'user' }], model: 'tight-model' } as any,+ [baseModel({ contextWindowTokens: 2000, id: 'tight-model' })],+ ),+ ).toThrow(ContextExceededPreFlightError);+ });++ it('attaches LOBE-8974 structured payload via toPayload()', () => {+ const longContent = 'a'.repeat(20_000);+ try {+ assertContextWithinWindow(+ { messages: [{ content: longContent, role: 'user' }], model: 'tight-model' } as any,+ [baseModel({ contextWindowTokens: 2000, id: 'tight-model' })],+ );+ throw new Error('should have thrown');+ } catch (error) {+ const err = error as ContextExceededPreFlightError;+ const payload = err.toPayload();+ expect(payload.type).toBe('context_exceeded_pre_flight');+ expect(payload.model).toBe('tight-model');+ expect(payload.ctx).toBe(2000);+ expect(payload.shortBy).toBe(payload.promptTokens - payload.ctx);+ expect(payload.shortBy).toBeGreaterThan(0); // strict overflow path: shortBy must be positive+ expect(payload.suggestions).toEqual(['fork_topic', 'switch_to_larger_ctx_model']);+ // Pre-flight-only path doesn't enforce completion headroom, so the+ // payload omits the minOutputTokens field.+ expect((payload as any).minOutputTokens).toBeUndefined();+ }+ });++ it('does NOT reject a near-limit prompt that still fits within the window', () => {+ // Regression test for LOBE-8974 PR review feedback: the helper was+ // previously deducting a 1024 buffer + 1024 minOutputTokens and would+ // throw for a 198.5k-token prompt against a 200k-token window even+ // though the upstream would accept it. With the corrected threshold,+ // this must pass through.+ // ~4 chars per token, so 'a'.repeat(794_000) estimates to ~198.5k.+ const nearLimitContent = 'a'.repeat(794_000);++ expect(() =>+ assertContextWithinWindow(+ { messages: [{ content: nearLimitContent, role: 'user' }], model: 'big-model' } as any,+ [baseModel({ contextWindowTokens: 200_000, id: 'big-model' })],+ ),+ ).not.toThrow();+ });++ it('honors safetyMarginTokens for stricter callers', () => {+ // With no margin, a ~5k-token prompt against a 6k-token window fits.+ const baseArgs = {+ messages: [{ content: 'a'.repeat(20_000), role: 'user' }],+ model: 'snug-model',+ } as any;+ const models = [baseModel({ contextWindowTokens: 6000, id: 'snug-model' })];++ expect(() => assertContextWithinWindow(baseArgs, models)).not.toThrow();++ // With a generous margin, the same prompt is treated as overflow.+ expect(() => assertContextWithinWindow(baseArgs, models, { safetyMarginTokens: 3000 })).toThrow(+ ContextExceededPreFlightError,+ );+ });+});diff --git a/packages/model-runtime/src/utils/resolveSafeMaxTokens.ts b/packages/model-runtime/src/utils/resolveSafeMaxTokens.tsindex 7cedce4956f..4ee33342580 100644--- a/packages/model-runtime/src/utils/resolveSafeMaxTokens.ts+++ b/packages/model-runtime/src/utils/resolveSafeMaxTokens.ts@@ -16,6 +16,12 @@ export const DEFAULT_MAX_TOKENS_BUFFER = 1024;*/export const DEFAULT_MIN_OUTPUT_TOKENS = 1024;+export const CONTEXT_EXCEEDED_PRE_FLIGHT_TYPE = 'context_exceeded_pre_flight' as const;++export const DEFAULT_PRE_FLIGHT_SUGGESTIONS = ['fork_topic', 'switch_to_larger_ctx_model'] as const;++export type PreFlightSuggestion = (typeof DEFAULT_PRE_FLIGHT_SUGGESTIONS)[number];+export interface ResolveSafeMaxTokensOptions {/** Safety buffer reserved on top of estimated input tokens. */bufferTokens?: number;@@ -24,31 +30,62 @@ export interface ResolveSafeMaxTokensOptions {}/**- * Thrown when the estimated input tokens leave less room than- * `minOutputTokens` for completion. Caught by provider-level `handleError`- * and converted into an `ExceededContextWindow` chat error.+ * Thrown when the estimated prompt tokens leave less room than+ * `minOutputTokens` for completion (or already exceed the model's context+ * window). Caught by `openaiCompatibleFactory` and surfaced as an+ * `ExceededContextWindow` chat error carrying structured diagnostic fields+ * β see LOBE-8974 for the rationale of failing fast instead of issuing a+ * doomed upstream request.*/-export class MaxTokensExceededError extends Error {- readonly contextWindowTokens: number;- readonly estimatedInputTokens: number;- readonly minOutputTokens: number;- readonly modelId: string;+export class ContextExceededPreFlightError extends Error {+ readonly type = CONTEXT_EXCEEDED_PRE_FLIGHT_TYPE;+ readonly model: string;+ readonly promptTokens: number;+ readonly ctx: number;+ readonly shortBy: number;+ /**+ * Only populated by `resolveSafeMaxTokens` (max_tokens-capping path). The+ * pre-flight-only `assertContextWithinWindow` leaves it undefined since+ * it does not require headroom for completion to consider the prompt+ * valid.+ */+ readonly minOutputTokens?: number;+ readonly suggestions: readonly PreFlightSuggestion[];constructor(params: {- contextWindowTokens: number;- estimatedInputTokens: number;- minOutputTokens: number;- modelId: string;+ ctx: number;+ minOutputTokens?: number;+ model: string;+ promptTokens: number;+ suggestions?: readonly PreFlightSuggestion[];}) {- const { modelId, contextWindowTokens, estimatedInputTokens, minOutputTokens } = params;- super(- `Estimated input tokens (${estimatedInputTokens}) leave less than ${minOutputTokens} tokens for completion within the model context window (${contextWindowTokens}) for model "${modelId}". Reduce input or attached tools, or pick a model with a larger context window.`,- );- this.name = 'MaxTokensExceededError';- this.modelId = modelId;- this.contextWindowTokens = contextWindowTokens;- this.estimatedInputTokens = estimatedInputTokens;+ const { model, ctx, promptTokens, minOutputTokens, suggestions } = params;+ const shortBy = promptTokens - ctx;+ const message =+ minOutputTokens !== undefined+ ? `Prompt tokens (${promptTokens}) leave less than ${minOutputTokens} tokens for completion within the model context window (${ctx}) for model "${model}". Reduce input or attached tools, or pick a model with a larger context window.`+ : `Prompt tokens (${promptTokens}) exceed the model context window (${ctx}) for model "${model}". Reduce input or attached tools, or pick a model with a larger context window.`;+ super(message);+ this.name = 'ContextExceededPreFlightError';+ this.model = model;+ this.promptTokens = promptTokens;+ this.ctx = ctx;+ this.shortBy = shortBy;this.minOutputTokens = minOutputTokens;+ this.suggestions = suggestions ?? DEFAULT_PRE_FLIGHT_SUGGESTIONS;+ }++ /** Convert to a plain object suitable for embedding in a chat error body. */+ toPayload() {+ return {+ ctx: this.ctx,+ model: this.model,+ promptTokens: this.promptTokens,+ shortBy: this.shortBy,+ suggestions: [...this.suggestions],+ type: this.type,+ ...(this.minOutputTokens !== undefined ? { minOutputTokens: this.minOutputTokens } : {}),+ };}}@@ -66,8 +103,8 @@ const estimatePayloadInputTokens = (payload: Pick<ChatStreamPayload, 'messages'* - If the user explicitly passed `max_tokens`, return it untouched.* - Otherwise compute `min(maxOutput, contextWindow - estimatedInput - buffer)`.* - If the resulting value would be smaller than `minOutputTokens`, throw- * `MaxTokensExceededError` so callers can surface a clear error before- * issuing a doomed request.+ * `ContextExceededPreFlightError` so callers can surface a clear error+ * before issuing a doomed request.*/export const resolveSafeMaxTokens = (payload: Pick<ChatStreamPayload, 'max_tokens' | 'messages' | 'model' | 'tools'>,@@ -92,13 +129,59 @@ export const resolveSafeMaxTokens = (const remaining = contextWindow - estimatedInputTokens - bufferTokens;if (remaining < minOutputTokens) {- throw new MaxTokensExceededError({- contextWindowTokens: contextWindow,- estimatedInputTokens,+ throw new ContextExceededPreFlightError({+ ctx: contextWindow,minOutputTokens,- modelId: payload.model,+ model: payload.model,+ promptTokens: estimatedInputTokens,});}return maxOutput !== undefined ? Math.min(maxOutput, remaining) : remaining;};++export interface AssertContextWithinWindowOptions {+ /**+ * Number of tokens to subtract from the model context window before+ * comparing against the estimated prompt size. Use a small positive+ * value to be conservative against estimator drift / per-message+ * protocol overhead that `tokenx` doesn't model. Default `0` β only+ * reject when the estimated prompt strictly exceeds the model window.+ */+ safetyMarginTokens?: number;+}++/**+ * Pre-flight check for providers where the harness does not need to cap+ * `max_tokens` itself (the upstream picks its own default), but we still+ * want to bail fast when the prompt alone already overflows the model's+ * context window.+ *+ * Unlike `resolveSafeMaxTokens` this does NOT require headroom for+ * completion β the upstream will pick its own `max_tokens` default once+ * the request is dispatched. Rejecting near-limit-but-fitting prompts+ * (e.g. 198.5k tokens against a 200k window) would block valid requests+ * that the upstream would happily serve. See LOBE-8974 review feedback.+ */+export const assertContextWithinWindow = (+ payload: Pick<ChatStreamPayload, 'messages' | 'model' | 'tools'>,+ models: AiFullModelCard[],+ options: AssertContextWithinWindowOptions = {},+): void => {+ const model = models.find((m) => m.id === payload.model);+ if (!model) return;++ const contextWindow = model.contextWindowTokens;+ if (!contextWindow) return;++ const safetyMarginTokens = options.safetyMarginTokens ?? 0;+ const estimatedInputTokens = estimatePayloadInputTokens(payload);++ if (estimatedInputTokens <= contextWindow - safetyMarginTokens) return;++ throw new ContextExceededPreFlightError({+ ctx: contextWindow,+ model: payload.model,+ promptTokens: estimatedInputTokens,+ });+};