Skip to content

🀯 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.

πŸ› fix(minimax): derive `max_tokens` from context window to avoid ExceededContextWindow (#14814)

Arvin Xuba6980ffe963
diff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.json
index aa44ef83bb8..7d9d37f1748 100644
--- a/packages/model-runtime/package.json
+++ b/packages/model-runtime/package.json
@@ -33,6 +33,7 @@
"ollama": "^0.6.2",
"openai": "^4.104.0",
"replicate": "^1.4.0",
+ "tokenx": "^1.3.0",
"type-fest": "^5.2.0",
"url-join": "^5.0.0"
},
diff --git a/packages/model-runtime/src/providers/minimax/index.test.ts b/packages/model-runtime/src/providers/minimax/index.test.ts
index c5ba6581163..b51bf502aea 100644
--- a/packages/model-runtime/src/providers/minimax/index.test.ts
+++ b/packages/model-runtime/src/providers/minimax/index.test.ts
@@ -1,8 +1,11 @@
// @vitest-environment node
import { ModelProvider } from 'model-bank';
+import { describe, expect, it } from 'vitest';
import { testProvider } from '../../providerTestUtils';
-import { LobeMinimaxAI } from './index';
+import { AgentRuntimeErrorType } from '../../types/error';
+import { MaxTokensExceededError } from '../../utils/resolveSafeMaxTokens';
+import { LobeMinimaxAI, params } from './index';
const provider = ModelProvider.Minimax;
const defaultBaseURL = 'https://api.minimaxi.com/v1';
@@ -17,3 +20,149 @@ testProvider({
skipAPICall: true,
},
});
+
+const handlePayload = params.chatCompletion.handlePayload;
+const handleError = params.chatCompletion.handleError;
+
+describe('LobeMinimaxAI - handlePayload', () => {
+ it('respects an explicitly provided max_tokens', () => {
+ const result = handlePayload({
+ max_tokens: 4096,
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'MiniMax-M2.7',
+ temperature: 1,
+ } as any);
+
+ expect(result.max_tokens).toBe(4096);
+ });
+
+ it('derives max_tokens from the model maxOutput when input is small', () => {
+ const result = handlePayload({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'MiniMax-M2.7',
+ temperature: 1,
+ } as any);
+
+ // MiniMax-M2.7 maxOutput is 131_072 and contextWindowTokens is 204_800.
+ // With a tiny input, max_tokens should equal maxOutput.
+ expect(result.max_tokens).toBe(131_072);
+ });
+
+ it('caps max_tokens when input + tools fill most of the context window', () => {
+ // Mimic the LOBE-7017 scenario: many large tool definitions.
+ // MiniMax-M2.7: contextWindow=204_800, maxOutput=131_072. Need >72k tokens
+ // of input to push the dynamic cap below maxOutput.
+ const heavyTool = {
+ function: {
+ description: 'x'.repeat(500_000),
+ name: 'big_tool',
+ parameters: { properties: {}, type: 'object' },
+ },
+ type: 'function',
+ };
+
+ const result = handlePayload({
+ messages: [{ content: 'hello', role: 'user' }],
+ model: 'MiniMax-M2.7',
+ temperature: 1,
+ tools: [heavyTool],
+ } as any);
+
+ expect(result.max_tokens).toBeDefined();
+ expect(result.max_tokens).toBeLessThan(131_072);
+ expect(result.max_tokens).toBeGreaterThanOrEqual(1024);
+ });
+
+ it('throws MaxTokensExceededError 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.
+ const longContent = 'a'.repeat(450_000);
+
+ expect(() =>
+ handlePayload({
+ messages: [{ content: longContent, role: 'user' }],
+ model: 'M2-her',
+ temperature: 1,
+ } as any),
+ ).toThrow(MaxTokensExceededError);
+ });
+
+ it('estimates tokens against the sanitized messages, not the raw payload', () => {
+ // Signed reasoning is stripped before sending, so a long signed
+ // reasoning trace must NOT count toward the input estimate.
+ // M2-her has contextWindow=65_536; ~60k tokens of signed reasoning
+ // would otherwise exceed the window and throw.
+ const longSignedReasoning = 'r'.repeat(400_000);
+
+ expect(() =>
+ handlePayload({
+ messages: [
+ {
+ content: 'short reply',
+ reasoning: { content: longSignedReasoning, signature: 'sig-1' },
+ role: 'assistant',
+ },
+ { content: 'next', role: 'user' },
+ ],
+ model: 'M2-her',
+ temperature: 1,
+ } as any),
+ ).not.toThrow();
+ });
+
+ it('preserves existing message and parameter handling', () => {
+ const result = handlePayload({
+ messages: [
+ {
+ content: 'reply',
+ reasoning: { content: 'thought', signature: undefined },
+ role: 'assistant',
+ },
+ { content: 'next', role: 'user' },
+ ],
+ model: 'MiniMax-M2.7',
+ temperature: 0,
+ top_p: 0.9,
+ } as any);
+
+ // Reasoning content without a signature should become reasoning_details.
+ expect(result.messages[0].reasoning_details).toEqual([
+ {
+ format: 'MiniMax-response-v1',
+ id: 'reasoning-text-0',
+ index: 0,
+ text: 'thought',
+ type: 'reasoning.text',
+ },
+ ]);
+ // Temperature <= 0 is dropped because MiniMax rejects it.
+ expect(result.temperature).toBeUndefined();
+ // Reasoning split is always enabled.
+ 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.ts
index 08841e9b24c..ff1140e8d04 100644
--- a/packages/model-runtime/src/providers/minimax/index.ts
+++ b/packages/model-runtime/src/providers/minimax/index.ts
@@ -2,14 +2,30 @@ import { minimax as minimaxChatModels, ModelProvider } from 'model-bank';
import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
import { resolveParameters } from '../../core/parameterResolver';
-import { getModelMaxOutputs } from '../../utils/getModelMaxOutputs';
+import { AgentRuntimeErrorType } from '../../types/error';
+import { MaxTokensExceededError, resolveSafeMaxTokens } from '../../utils/resolveSafeMaxTokens';
import { createMiniMaxImage } from './createImage';
import { createMiniMaxVideo } from './createVideo';
-export const LobeMinimaxAI = createOpenAICompatibleRuntime({
+export const params = {
baseURL: 'https://api.minimaxi.com/v1',
chatCompletion: {
- handlePayload: (payload) => {
+ 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;
// Interleaved thinking
@@ -40,13 +56,19 @@ export const LobeMinimaxAI = createOpenAICompatibleRuntime({
return message;
});
+ // MiniMax API enforces `input_tokens + max_tokens <= context_window`,
+ // so we must derive max_tokens dynamically from the actual input size
+ // when the caller did not specify one. Estimate against the sanitized
+ // messages (with stripped reasoning) β€” that's what we actually send.
+ const safeMaxTokens = resolveSafeMaxTokens(
+ { ...payload, messages: processedMessages },
+ minimaxChatModels,
+ );
+
// Resolve parameters with constraints
const resolvedParams = resolveParameters(
{
- max_tokens:
- max_tokens !== undefined
- ? max_tokens
- : getModelMaxOutputs(payload.model, minimaxChatModels),
+ max_tokens: safeMaxTokens,
temperature,
top_p,
},
@@ -74,15 +96,17 @@ export const LobeMinimaxAI = createOpenAICompatibleRuntime({
},
createImage: createMiniMaxImage,
createVideo: createMiniMaxVideo,
- handlePollVideoStatus: async (inferenceId, options) => {
+ debug: {
+ chatCompletion: () => process.env.DEBUG_MINIMAX_CHAT_COMPLETION === '1',
+ },
+ handlePollVideoStatus: async (inferenceId: string, options: any) => {
const { pollMiniMaxVideoStatus } = await import('./createVideo');
return pollMiniMaxVideoStatus(inferenceId, {
apiKey: options.apiKey,
baseURL: options.baseURL || '',
});
},
- debug: {
- chatCompletion: () => process.env.DEBUG_MINIMAX_CHAT_COMPLETION === '1',
- },
provider: ModelProvider.Minimax,
-});
+};
+
+export const LobeMinimaxAI = createOpenAICompatibleRuntime(params);
diff --git a/packages/model-runtime/src/utils/resolveSafeMaxTokens.test.ts b/packages/model-runtime/src/utils/resolveSafeMaxTokens.test.ts
new file mode 100644
index 00000000000..6b4da6ef37c
--- /dev/null
+++ b/packages/model-runtime/src/utils/resolveSafeMaxTokens.test.ts
@@ -0,0 +1,167 @@
+// @vitest-environment node
+import { type AiFullModelCard } from 'model-bank';
+import { describe, expect, it } from 'vitest';
+
+import {
+ DEFAULT_MAX_TOKENS_BUFFER,
+ DEFAULT_MIN_OUTPUT_TOKENS,
+ MaxTokensExceededError,
+ resolveSafeMaxTokens,
+} from './resolveSafeMaxTokens';
+
+const baseModel = (overrides: Partial<AiFullModelCard> = {}): AiFullModelCard =>
+ ({
+ contextWindowTokens: 200_000,
+ displayName: 'Test',
+ id: 'test-model',
+ maxOutput: 131_072,
+ type: 'chat',
+ ...overrides,
+ }) as AiFullModelCard;
+
+describe('resolveSafeMaxTokens', () => {
+ it('returns the user-provided max_tokens unchanged', () => {
+ const result = resolveSafeMaxTokens(
+ {
+ max_tokens: 4096,
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'test-model',
+ } as any,
+ [baseModel()],
+ );
+ expect(result).toBe(4096);
+ });
+
+ it('returns undefined when the model is not found', () => {
+ const result = resolveSafeMaxTokens(
+ {
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'unknown',
+ } as any,
+ [baseModel()],
+ );
+ expect(result).toBeUndefined();
+ });
+
+ it('falls back to maxOutput when contextWindowTokens is missing', () => {
+ const result = resolveSafeMaxTokens(
+ {
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'test-model',
+ } as any,
+ [baseModel({ contextWindowTokens: undefined as any })],
+ );
+ expect(result).toBe(131_072);
+ });
+
+ it('uses maxOutput when input is small enough', () => {
+ const result = resolveSafeMaxTokens(
+ {
+ messages: [{ content: 'short message', role: 'user' }],
+ model: 'test-model',
+ } as any,
+ [baseModel({ contextWindowTokens: 200_000, maxOutput: 4096 })],
+ );
+ expect(result).toBe(4096);
+ });
+
+ 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 tokens
+ const result = resolveSafeMaxTokens(
+ {
+ messages: [{ content: longContent, role: 'user' }],
+ model: 'test-model',
+ } as any,
+ [baseModel({ contextWindowTokens: 10_000, maxOutput: 8000 })],
+ );
+
+ expect(result).toBeDefined();
+ expect(result!).toBeLessThan(8000);
+ expect(result!).toBeGreaterThanOrEqual(DEFAULT_MIN_OUTPUT_TOKENS);
+ });
+
+ it('throws MaxTokensExceededError when remaining window < minOutputTokens', () => {
+ // contextWindow=2000, big input β†’ no room left
+ const longContent = 'a'.repeat(20_000);
+ expect(() =>
+ resolveSafeMaxTokens(
+ {
+ messages: [{ content: longContent, role: 'user' }],
+ model: 'test-model',
+ } as any,
+ [baseModel({ contextWindowTokens: 2000, maxOutput: 8000 })],
+ ),
+ ).toThrow(MaxTokensExceededError);
+ });
+
+ it('attaches diagnostic data to MaxTokensExceededError', () => {
+ const longContent = 'a'.repeat(20_000);
+ try {
+ resolveSafeMaxTokens(
+ {
+ messages: [{ content: longContent, role: 'user' }],
+ model: 'tight-model',
+ } as any,
+ [baseModel({ contextWindowTokens: 2000, id: 'tight-model', maxOutput: 8000 })],
+ );
+ 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(err.minOutputTokens).toBe(DEFAULT_MIN_OUTPUT_TOKENS);
+ }
+ });
+
+ 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',
+ } as any;
+ const models = [baseModel({ contextWindowTokens: 10_000, maxOutput: 8000 })];
+
+ const withoutTools = resolveSafeMaxTokens(baseArgs, models);
+
+ const heavyTool = {
+ function: {
+ description: 'x'.repeat(10_000),
+ name: 'big_tool',
+ parameters: { properties: {}, type: 'object' },
+ },
+ type: 'function',
+ };
+ const withTools = resolveSafeMaxTokens({ ...baseArgs, tools: [heavyTool] }, models);
+
+ expect(withTools).toBeDefined();
+ expect(withoutTools).toBeDefined();
+ expect(withTools!).toBeLessThan(withoutTools!);
+ });
+
+ it('honors a custom buffer', () => {
+ const models = [baseModel({ contextWindowTokens: 10_000, maxOutput: 100_000 })];
+ const longContent = 'a'.repeat(8000); // ~2000 estimated tokens
+
+ const defaultBuffer = resolveSafeMaxTokens(
+ {
+ messages: [{ content: longContent, role: 'user' }],
+ model: 'test-model',
+ } as any,
+ models,
+ );
+ const largerBuffer = resolveSafeMaxTokens(
+ {
+ messages: [{ content: longContent, role: 'user' }],
+ model: 'test-model',
+ } as any,
+ models,
+ { bufferTokens: DEFAULT_MAX_TOKENS_BUFFER + 1000 },
+ );
+
+ expect(largerBuffer).toBe(defaultBuffer! - 1000);
+ });
+});
diff --git a/packages/model-runtime/src/utils/resolveSafeMaxTokens.ts b/packages/model-runtime/src/utils/resolveSafeMaxTokens.ts
new file mode 100644
index 00000000000..7cedce4956f
--- /dev/null
+++ b/packages/model-runtime/src/utils/resolveSafeMaxTokens.ts
@@ -0,0 +1,104 @@
+import { type AiFullModelCard } from 'model-bank';
+import { estimateTokenCount } from 'tokenx';
+
+import type { ChatStreamPayload } from '../types/chat';
+
+/**
+ * Default safety buffer (in tokens) reserved on top of the estimated input
+ * to absorb estimator inaccuracy and per-message protocol overhead.
+ */
+export const DEFAULT_MAX_TOKENS_BUFFER = 1024;
+
+/**
+ * Default minimum allowed `max_tokens`. If the dynamically-derived value
+ * falls below this, we treat the request as already exceeding the context
+ * window and abort early instead of letting the upstream API reject it.
+ */
+export const DEFAULT_MIN_OUTPUT_TOKENS = 1024;
+
+export interface ResolveSafeMaxTokensOptions {
+ /** Safety buffer reserved on top of estimated input tokens. */
+ bufferTokens?: number;
+ /** Minimum acceptable `max_tokens`; below this we throw. */
+ minOutputTokens?: number;
+}
+
+/**
+ * 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.
+ */
+export class MaxTokensExceededError extends Error {
+ readonly contextWindowTokens: number;
+ readonly estimatedInputTokens: number;
+ readonly minOutputTokens: number;
+ readonly modelId: string;
+
+ constructor(params: {
+ contextWindowTokens: number;
+ estimatedInputTokens: number;
+ minOutputTokens: number;
+ modelId: string;
+ }) {
+ 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;
+ this.minOutputTokens = minOutputTokens;
+ }
+}
+
+const estimatePayloadInputTokens = (payload: Pick<ChatStreamPayload, 'messages' | 'tools'>) => {
+ const { messages = [], tools } = payload;
+ const messagesText = JSON.stringify(messages);
+ const toolsText = tools && tools.length > 0 ? JSON.stringify(tools) : '';
+ return estimateTokenCount(messagesText) + (toolsText ? estimateTokenCount(toolsText) : 0);
+};
+
+/**
+ * Resolve a safe `max_tokens` for providers whose API enforces
+ * `input_tokens + max_tokens <= context_window` (e.g. MiniMax).
+ *
+ * - 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.
+ */
+export const resolveSafeMaxTokens = (
+ payload: Pick<ChatStreamPayload, 'max_tokens' | 'messages' | 'model' | 'tools'>,
+ models: AiFullModelCard[],
+ options: ResolveSafeMaxTokensOptions = {},
+): number | undefined => {
+ if (payload.max_tokens !== undefined) return payload.max_tokens;
+
+ const model = models.find((m) => m.id === payload.model);
+ if (!model) return undefined;
+
+ const maxOutput = model.maxOutput;
+ const contextWindow = model.contextWindowTokens;
+
+ // Without contextWindow info, fall back to the model's maxOutput.
+ if (!contextWindow) return maxOutput;
+
+ const bufferTokens = options.bufferTokens ?? DEFAULT_MAX_TOKENS_BUFFER;
+ const minOutputTokens = options.minOutputTokens ?? DEFAULT_MIN_OUTPUT_TOKENS;
+
+ const estimatedInputTokens = estimatePayloadInputTokens(payload);
+ const remaining = contextWindow - estimatedInputTokens - bufferTokens;
+
+ if (remaining < minOutputTokens) {
+ throw new MaxTokensExceededError({
+ contextWindowTokens: contextWindow,
+ estimatedInputTokens,
+ minOutputTokens,
+ modelId: payload.model,
+ });
+ }
+
+ return maxOutput !== undefined ? Math.min(maxOutput, remaining) : remaining;
+};