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(agent-runtime): harden LLM outbound guards (empty enum / empty messages / deepseek budget) (#16793)

Arvin Xu5a4026e6bd91
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
index d6c03cb1905..c2e15993a8c 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
@@ -918,6 +918,22 @@ export const callLlm =
processedMessages = llmPayload.messages;
}
+ // A turn must carry at least one non-system message. Anthropic-compatible
+ // providers (anthropic / deepseek) move `role: system` into a separate
+ // top-level field, so a system-only array dispatches `messages: []` and
+ // the upstream rejects it with a 400 `messages: at least one message is
+ // required` (surfaced as an opaque UpstreamHttpError); for other providers
+ // a system-only turn has nothing to respond to. Either way the context
+ // pipeline dropped everything real β€” fail fast with a locatable internal
+ // error instead of a doomed round-trip. Attributed here (agent-runtime),
+ // not the provider layer, since it's our own pipeline that emptied it.
+ if (!processedMessages.some((message) => message.role !== 'system')) {
+ throw new Error(
+ `call_llm produced no non-system messages for ${provider}/${model} ` +
+ `(topic=${state.metadata?.topicId ?? 'n/a'}, step=${stepIndex}); refusing to dispatch`,
+ );
+ }
+
// Initialize ModelRuntime (read user's keyVaults from database)
const modelRuntime = await initModelRuntimeFromDB(
ctx.serverDB,
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
index 6e1cd4abe6e..b4723496d4a 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
@@ -192,8 +192,7 @@ export const buildDefaultAnthropicPayload = async (
}
let postTools = buildAnthropicTools(tools, { enabledContextCaching }) as
- | AnthropicTools[]
- | undefined;
+ AnthropicTools[] | undefined;
if (enabledSearch) {
const webSearchTool = buildSearchTool();
diff --git a/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.test.ts b/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.test.ts
index 5788fd204a0..87b7e488c18 100644
--- a/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.test.ts
@@ -93,6 +93,38 @@ describe('normalizeToolJsonSchema', () => {
expect(result.additionalProperties.items).toEqual({});
});
+ // xAI/grok variant β€” property carrying an empty enum
+ it('drops an empty enum constraint', () => {
+ const result = normalizeToolJsonSchema({
+ properties: {
+ sort: { enum: [], type: 'string' },
+ },
+ type: 'object',
+ });
+
+ expect('enum' in result.properties.sort).toBe(false);
+ expect(result.properties.sort.type).toBe('string');
+ });
+
+ it('keeps a non-empty enum untouched', () => {
+ const result = normalizeToolJsonSchema({
+ enum: ['asc', 'desc'],
+ type: 'string',
+ });
+
+ expect(result.enum).toEqual(['asc', 'desc']);
+ });
+
+ it('drops empty enums nested inside combinators and items', () => {
+ const result = normalizeToolJsonSchema({
+ anyOf: [{ enum: [], type: 'string' }],
+ items: { enum: [] },
+ });
+
+ expect('enum' in result.anyOf[0]).toBe(false);
+ expect('enum' in result.items).toBe(false);
+ });
+
it('keeps boolean additionalProperties untouched (a valid, accepted form)', () => {
expect(normalizeToolJsonSchema({ additionalProperties: false, type: 'object' })).toEqual({
additionalProperties: false,
diff --git a/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.ts b/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.ts
index 4ad2921dcc2..6a935606c76 100644
--- a/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.ts
+++ b/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.ts
@@ -15,6 +15,10 @@ import type OpenAI from 'openai';
* `type: 'array'`. Gemini rejects it with
* `field predicate failed: $type == Type.ARRAY`.
* β†’ backfill `type: 'array'`.
+ * - **Empty `enum`** (`enum: []`). An enum with no members constrains the
+ * value to nothing; strict validators reject it β€” xAI/grok with
+ * `/properties/sort/enum: [] has less than 1 item`.
+ * β†’ drop the empty enum constraint so the property stays usable.
*
* Normalization is the harness's responsibility (the same family as the Gemini
* enum / required sanitizers), so we clean the schema before it reaches any
@@ -78,6 +82,13 @@ export const normalizeToolJsonSchema = (schema: any): any => {
}
}
+ // An empty `enum` ([]) allows no value at all β€” nonsensical, and strict
+ // validators (xAI/grok: `enum: [] has less than 1 item`) reject the whole
+ // request. Drop the constraint entirely rather than let it fail upstream.
+ if (Array.isArray(normalized.enum) && normalized.enum.length === 0) {
+ delete normalized.enum;
+ }
+
return normalized;
};
diff --git a/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts b/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts
new file mode 100644
index 00000000000..15c6aa2ca2a
--- /dev/null
+++ b/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts
@@ -0,0 +1,46 @@
+import { deepseek as deepseekChatModels } from 'model-bank';
+import { describe, expect, it } from 'vitest';
+
+import { ContextExceededPreFlightError } from '../../utils/resolveSafeMaxTokens';
+import { buildDeepSeekAnthropicPayload } from './chatPayload';
+
+describe('buildDeepSeekAnthropicPayload β€” completion budget', () => {
+ // The dynamic-reservation fix engages only when resolveSafeMaxTokens can look
+ // up the model card. If these fields ever change/disappear, the fix silently
+ // degrades back to the fixed 384k reservation β€” guard against that here.
+ it('deepseek-v4-pro card exposes the context window the fix depends on', () => {
+ const card = deepseekChatModels.find((m) => m.id === 'deepseek-v4-pro');
+ expect(card?.contextWindowTokens).toBe(1_048_576);
+ expect(card?.maxOutput).toBe(393_216);
+ });
+
+ // Wiring proof: with the fixed 393_216 reservation this prompt (which alone
+ // fits nowhere near the window) would be shipped and rejected upstream as an
+ // opaque ExceededContextWindow. Routing max_tokens through resolveSafeMaxTokens
+ // makes it fail fast, locally, with a structured pre-flight error.
+ it('fails fast with a pre-flight error when the prompt overflows the window', async () => {
+ // ~10M chars β€” unambiguously over the 1,048,576-token window regardless of
+ // the exact tokenizer ratio.
+ const huge = 'lorem ipsum dolor '.repeat(560_000);
+
+ await expect(
+ buildDeepSeekAnthropicPayload({
+ messages: [{ content: huge, role: 'user' }],
+ model: 'deepseek-v4-pro',
+ } as any),
+ ).rejects.toBeInstanceOf(ContextExceededPreFlightError);
+ });
+
+ // A normal small prompt must still produce a usable payload (no regression /
+ // no spurious pre-flight throw for the common case).
+ it('produces a payload with a positive max_tokens for a small prompt', async () => {
+ const payload = await buildDeepSeekAnthropicPayload({
+ messages: [{ content: 'hello', role: 'user' }],
+ model: 'deepseek-v4-pro',
+ } as any);
+
+ expect(typeof payload.max_tokens).toBe('number');
+ expect(payload.max_tokens).toBeGreaterThan(0);
+ expect(payload.max_tokens).toBeLessThanOrEqual(393_216);
+ });
+});
diff --git a/packages/model-runtime/src/providers/deepseek/chatPayload.ts b/packages/model-runtime/src/providers/deepseek/chatPayload.ts
index 946b94b8734..422a687eb18 100644
--- a/packages/model-runtime/src/providers/deepseek/chatPayload.ts
+++ b/packages/model-runtime/src/providers/deepseek/chatPayload.ts
@@ -1,11 +1,12 @@
import type Anthropic from '@anthropic-ai/sdk';
-import { ModelProvider } from 'model-bank';
+import { deepseek as deepseekChatModels, ModelProvider } from 'model-bank';
import type OpenAI from 'openai';
import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatibleFactory';
import type { ChatStreamPayload } from '../../types';
import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { isDeepSeekV4FamilyModel } from '../../utils/modelParse';
+import { resolveSafeMaxTokens } from '../../utils/resolveSafeMaxTokens';
import { sanitizeDeepSeekJsonPayload } from './sanitizePayload';
export const isDeepSeekV4Model = (model: string | undefined) => isDeepSeekV4FamilyModel(model);
@@ -94,8 +95,26 @@ export const buildDeepSeekAnthropicPayload = async (
): Promise<Anthropic.MessageCreateParams> => {
const resolvedThinking = resolveDeepSeekThinking(payload);
const isThinkingDisabled = resolvedThinking?.type === 'disabled';
+
+ const anthropicMessages = normalizeMessagesForAnthropic(
+ payload.messages,
+ shouldEnableDeepSeekThinking(payload),
+ );
+
const resolvedMaxTokens =
payload.max_tokens ??
+ // Cap the completion budget against the actual input size instead of always
+ // reserving the model's full `maxOutput`. DeepSeek-v4-pro reserves 384k for
+ // completion; with a prompt that on its own fits the 1M window, that fixed
+ // reservation tipped the total over the limit and produced a "phantom"
+ // ExceededContextWindow. resolveSafeMaxTokens shrinks the reservation to the
+ // remaining room, and fails fast with a structured ContextExceededPreFlight
+ // error when the prompt leaves less than ~1k tokens for completion (below
+ // deepseek-v4's default thinking budget β†’ effectively context-full) β€” which
+ // is more actionable (fork_topic / larger-ctx suggestions) than either a
+ // doomed upstream 400 or a truncated stub completion. Estimate against the
+ // messages we actually send (anthropic-normalized).
+ resolveSafeMaxTokens({ ...payload, messages: anthropicMessages }, deepseekChatModels) ??
(await getModelPropertyWithFallback<number | undefined>(
payload.model,
'maxOutput',
@@ -107,10 +126,7 @@ export const buildDeepSeekAnthropicPayload = async (
...payload,
effort: !isThinkingDisabled ? ((payload.effort ?? payload.reasoning_effort) as any) : undefined,
max_tokens: resolvedMaxTokens,
- messages: normalizeMessagesForAnthropic(
- payload.messages,
- shouldEnableDeepSeekThinking(payload),
- ),
+ messages: anthropicMessages,
thinking: isThinkingDisabled ? undefined : resolvedThinking,
});