🤯 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(chat): return a structured error when a chat fails before byte 1 (#22314)
YuTengjing5ab7f3b8767c
diff --git a/apps/cli/src/commands/generate/text.ts b/apps/cli/src/commands/generate/text.tsindex 1f0894b0b10..686e3fe1a12 100644--- a/apps/cli/src/commands/generate/text.ts+++ b/apps/cli/src/commands/generate/text.ts@@ -3,6 +3,7 @@ import type { Command } from 'commander';import { getAuthInfo } from '../../api/http';import { CLI_PRIMARY_BIN } from '../../constants/identity';import { log } from '../../utils/logger';+import { formatTextGenerationError } from './textError';export function registerTextCommand(parent: Command) {parent@@ -73,7 +74,11 @@ export function registerTextCommand(parent: Command) {if (!res.ok) {const text = await res.text();- log.error(`Text generation failed: ${res.status} ${text}`);+ log.error(+ formatTextGenerationError(res.status, text, {+ maxTokens: payload.max_tokens as number | undefined,+ }),+ );process.exit(1);return;}diff --git a/apps/cli/src/commands/generate/textError.test.ts b/apps/cli/src/commands/generate/textError.test.tsnew file mode 100644index 00000000000..e2673b203a8--- /dev/null+++ b/apps/cli/src/commands/generate/textError.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import { formatTextGenerationError } from './textError';++describe('formatTextGenerationError', () => {+ it('explains an empty completion stopped by the output-token limit', () => {+ const text = JSON.stringify({+ body: { finishReason: 'MAX_TOKENS', provider: 'lobehub' },+ errorType: 'ModelEmptyCompletion',+ });++ expect(formatTextGenerationError(471, text, { maxTokens: 32 })).toBe(+ 'Text generation failed: ModelEmptyCompletion (HTTP 471). The model returned no visible output. It reached the output-token limit (--max-tokens 32) before writing any text; reasoning can use up the budget. Raise --max-tokens and retry.',+ );+ });++ it('reads the finish reason from serialized diagnostics', () => {+ const text = JSON.stringify({+ body: { diagnostics: { finishReason: 'length' }, provider: 'openai' },+ errorType: 'ModelEmptyCompletion',+ });++ expect(formatTextGenerationError(471, text)).toBe(+ 'Text generation failed: ModelEmptyCompletion (HTTP 471). The model returned no visible output. It reached the output-token limit before writing any text; reasoning can use up the budget. Raise --max-tokens and retry.',+ );+ });++ it('hints at --max-tokens for an empty completion without a known finish reason', () => {+ const text = JSON.stringify({ body: {}, errorType: 'ModelEmptyCompletion' });++ expect(formatTextGenerationError(471, text, { maxTokens: 16 })).toContain(+ 'If reasoning used up --max-tokens 16, raise it and retry.',+ );+ expect(formatTextGenerationError(471, text)).toBe(+ 'Text generation failed: ModelEmptyCompletion (HTTP 471). The model returned no visible output.',+ );+ });++ it('prints the message and trace id of other structured errors', () => {+ const text = JSON.stringify({+ body: { error: { message: 'upstream failure' }, traceId: 'log-1' },+ errorType: 'ProviderBizError',+ });++ expect(formatTextGenerationError(500, text)).toBe(+ 'Text generation failed: ProviderBizError (HTTP 500). upstream failure Trace ID: log-1',+ );+ });++ it('summarizes an HTML error page instead of dumping it', () => {+ const html = '<!DOCTYPE html><html><head><title>500</title></head><body>...</body></html>';++ expect(formatTextGenerationError(500, html)).toBe(+ 'Text generation failed: HTTP 500. The server returned an HTML error page instead of an error message.',+ );+ });++ it('truncates other raw bodies', () => {+ expect(formatTextGenerationError(502, `${'x'.repeat(300)}`)).toBe(+ `Text generation failed: HTTP 502 ${'x'.repeat(200)}`,+ );+ expect(formatTextGenerationError(500, 'Internal error')).toBe(+ 'Text generation failed: HTTP 500 Internal error',+ );+ });+});diff --git a/apps/cli/src/commands/generate/textError.ts b/apps/cli/src/commands/generate/textError.tsnew file mode 100644index 00000000000..9c2a56ffaa9--- /dev/null+++ b/apps/cli/src/commands/generate/textError.ts@@ -0,0 +1,73 @@+/** Longest raw non-JSON body excerpt printed with an HTTP error. */+const MAX_RAW_BODY_LENGTH = 200;++/** Finish reasons providers report when the output-token limit stopped the completion. */+const OUTPUT_LIMIT_FINISH_REASONS = new Set(['length', 'max_tokens', 'MAX_TOKENS']);++interface ChatErrorBody {+ body?: {+ /** `/webapi/chat/[provider]` serializes the error's diagnostics here. */+ diagnostics?: { finishReason?: unknown };+ error?: { message?: unknown };+ finishReason?: unknown;+ message?: unknown;+ traceId?: unknown;+ };+ errorType?: unknown;+}++const parseErrorBody = (text: string): ChatErrorBody | undefined => {+ try {+ const parsed = JSON.parse(text);+ return parsed && typeof parsed === 'object' ? (parsed as ChatErrorBody) : undefined;+ } catch {+ return undefined;+ }+};++const isHtml = (text: string) => /^\s*<(?:!doctype|html)/i.test(text);++/**+ * Turn a failed `/webapi/chat/*` response into one readable line. The route answers with+ * `{ errorType, body }`; an HTML error page or other raw text is summarized instead of dumped.+ */+export const formatTextGenerationError = (+ status: number,+ text: string,+ options: { maxTokens?: number } = {},+): string => {+ const parsed = parseErrorBody(text);++ if (!parsed || typeof parsed.errorType !== 'string') {+ if (isHtml(text)) {+ return `Text generation failed: HTTP ${status}. The server returned an HTML error page instead of an error message.`;+ }+ const excerpt = text.trim().slice(0, MAX_RAW_BODY_LENGTH);+ return `Text generation failed: HTTP ${status}${excerpt ? ` ${excerpt}` : ''}`;+ }++ const { body, errorType } = parsed;+ const parts = [`Text generation failed: ${errorType} (HTTP ${status}).`];++ if (errorType === 'ModelEmptyCompletion') {+ parts.push('The model returned no visible output.');+ // `/webapi/chat/lobehub` puts the finish reason on the body; `/webapi/chat/[provider]` keeps it+ // in the serialized error diagnostics.+ const rawFinishReason = body?.finishReason ?? body?.diagnostics?.finishReason;+ const finishReason = typeof rawFinishReason === 'string' ? rawFinishReason : undefined;+ if (finishReason && OUTPUT_LIMIT_FINISH_REASONS.has(finishReason)) {+ parts.push(+ `It reached the output-token limit${options.maxTokens ? ` (--max-tokens ${options.maxTokens})` : ''} before writing any text; reasoning can use up the budget. Raise --max-tokens and retry.`,+ );+ } else if (options.maxTokens) {+ parts.push(`If reasoning used up --max-tokens ${options.maxTokens}, raise it and retry.`);+ }+ } else {+ const message = body?.message ?? body?.error?.message;+ if (typeof message === 'string' && message) parts.push(message);+ }++ if (typeof body?.traceId === 'string') parts.push(`Trace ID: ${body.traceId}`);++ return parts.join(' ');+};diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.tsindex 626173d326d..5cfa5fa0248 100644--- a/packages/model-runtime/src/index.ts+++ b/packages/model-runtime/src/index.ts@@ -92,6 +92,7 @@ export { LobeZeroOneAI } from './providers/zeroone';export { LobeZhipuAI } from './providers/zhipu';export * from './types';export * from './types/error';+export { awaitFirstResponseChunk } from './utils/awaitFirstResponseChunk';export { consumeStreamUntilDone } from './utils/consumeStream';export { AgentRuntimeError } from './utils/createError';export { getModelPropertyWithFallback } from './utils/getFallbackModelProperty';diff --git a/packages/model-runtime/src/utils/awaitFirstResponseChunk.test.ts b/packages/model-runtime/src/utils/awaitFirstResponseChunk.test.tsnew file mode 100644index 00000000000..d0acf61ab4b--- /dev/null+++ b/packages/model-runtime/src/utils/awaitFirstResponseChunk.test.ts@@ -0,0 +1,116 @@+import { AgentRuntimeErrorType } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import type { LobeRuntimeAI } from '../core/BaseAI';+import { createRouterRuntime } from '../core/RouterRuntime/createRuntime';+import type { ChatMethodOptions } from '../types';+import { awaitFirstResponseChunk } from './awaitFirstResponseChunk';++const encode = (text: string) => new TextEncoder().encode(text);++describe('awaitFirstResponseChunk', () => {+ it('replays the first chunk and the rest of the body with the original status and headers', async () => {+ const response = new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(encode('a'));+ controller.enqueue(encode('b'));+ controller.close();+ },+ }),+ { headers: { 'Content-Type': 'text/event-stream' }, status: 201 },+ );++ const primed = await awaitFirstResponseChunk(response);++ expect(primed.status).toBe(201);+ expect(primed.headers.get('content-type')).toBe('text/event-stream');+ expect(await primed.text()).toBe('ab');+ });++ it('rejects when the body fails before yielding any chunk', async () => {+ const error = new Error('empty');+ const response = new Response(+ new ReadableStream<Uint8Array>({+ pull(controller) {+ controller.error(error);+ },+ }),+ );++ await expect(awaitFirstResponseChunk(response)).rejects.toBe(error);+ });++ it('keeps a failure after the first chunk inside the body', async () => {+ const error = new Error('late');+ let pulls = 0;+ const response = new Response(+ new ReadableStream<Uint8Array>({+ pull(controller) {+ pulls += 1;+ if (pulls === 1) controller.enqueue(encode('a'));+ else controller.error(error);+ },+ }),+ );++ const reader = (await awaitFirstResponseChunk(response)).body!.getReader();++ expect((await reader.read()).value).toEqual(encode('a'));+ await expect(reader.read()).rejects.toBe(error);+ });++ it('passes through an empty body and a response without a body', async () => {+ expect(await (await awaitFirstResponseChunk(new Response(''))).text()).toBe('');++ const bodiless = new Response(null, { status: 204 });+ expect(await awaitFirstResponseChunk(bodiless)).toBe(bodiless);+ });++ it('forwards cancellation to the source body', async () => {+ const cancel = vi.fn();+ const response = new Response(+ new ReadableStream<Uint8Array>({+ cancel,+ pull(controller) {+ controller.enqueue(encode('a'));+ },+ }),+ );++ const primed = await awaitFirstResponseChunk(response);+ await primed.body!.cancel('client gone');++ expect(cancel).toHaveBeenCalledWith('client gone');+ });++ it('rejects with the empty-completion error when every route returns an empty completion', async () => {+ class EmptyRuntime implements LobeRuntimeAI {+ chat = async (_payload: unknown, options?: ChatMethodOptions) =>+ new Response(+ new ReadableStream<Uint8Array>({+ async start(controller) {+ const final = { finishReason: 'MAX_TOKENS', text: '', usage: { cost: 0.001 } };+ await options?.callback?.onCompletion?.(final);+ await options?.callback?.onFinal?.(final);+ controller.enqueue(encode('event: stop\ndata: "MAX_TOKENS"\n\n'));+ controller.close();+ },+ }),+ );+ }+ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ onRouteAttemptFinished: vi.fn(),+ routers: [{ apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: EmptyRuntime }],+ shouldFallbackChatAttempt: () => true,+ });++ const response = await new Runtime().chat({ messages: [], model: 'gpt-4' } as any);++ await expect(awaitFirstResponseChunk(response)).rejects.toMatchObject({+ diagnostics: expect.objectContaining({ finishReason: 'MAX_TOKENS' }),+ errorType: AgentRuntimeErrorType.ModelEmptyCompletion,+ });+ });+});diff --git a/packages/model-runtime/src/utils/awaitFirstResponseChunk.ts b/packages/model-runtime/src/utils/awaitFirstResponseChunk.tsnew file mode 100644index 00000000000..19dc0467e50--- /dev/null+++ b/packages/model-runtime/src/utils/awaitFirstResponseChunk.ts@@ -0,0 +1,44 @@+/**+ * Wait until a chat response body yields its first chunk (or ends), and return an equivalent+ * response that replays it.+ *+ * A routed chat (`RouterRuntime`) keeps response bytes private until an attempt produces+ * visible output, so a terminal failure such as `ModelEmptyError` can error the body before a+ * single byte exists. An HTTP route that returns that body as-is lets the framework fail while+ * piping it: Next.js then answers with its generic 500 HTML page instead of the route's+ * structured error. Calling this inside the route's `try` turns such a failure into a rejection+ * the route can map to a structured error response. Failures after the first chunk still+ * surface in the body, because the response status is already committed by then.+ *+ * @throws The body error when the stream fails before yielding any chunk.+ */+export const awaitFirstResponseChunk = async (response: Response): Promise<Response> => {+ if (!response.body) return response;++ const reader = response.body.getReader();+ const first = await reader.read();++ const body = new ReadableStream<Uint8Array>(+ {+ async cancel(reason) {+ await reader.cancel(reason);+ },+ async pull(controller) {+ const { done, value } = await reader.read();+ if (done) controller.close();+ else controller.enqueue(value);+ },+ start(controller) {+ if (first.done) controller.close();+ else controller.enqueue(first.value);+ },+ },+ { highWaterMark: 0 },+ );++ return new Response(body, {+ headers: response.headers,+ status: response.status,+ statusText: response.statusText,+ });+};diff --git a/src/app/(backend)/webapi/chat/[provider]/route.test.ts b/src/app/(backend)/webapi/chat/[provider]/route.test.tsindex 0a6bc28f346..a87ee9a4c88 100644--- a/src/app/(backend)/webapi/chat/[provider]/route.test.ts+++ b/src/app/(backend)/webapi/chat/[provider]/route.test.ts@@ -1,7 +1,7 @@// @vitest-environment nodeimport { REQUEST_TOPIC_ID_HEADER } from '@lobechat/const';import { type LobeRuntimeAI } from '@lobechat/model-runtime';-import { ModelRuntime } from '@lobechat/model-runtime';+import { AgentRuntimeErrorType, ModelEmptyError, ModelRuntime } from '@lobechat/model-runtime';import { ChatErrorType } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -182,5 +182,44 @@ describe('POST handler', () => {errorType: 500,});});+ it('answers a structured error when the response body fails before its first byte', async () => {+ // A routed chat buffers bytes until visible output, so an empty completion errors the+ // body before anything is sent; returning it as-is made Next.js answer with its 500 page.+ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ controller.error(new ModelEmptyError(undefined, { finishReason: 'MAX_TOKENS' }));+ },+ });+ const mockRuntime: LobeRuntimeAI = {+ baseURL: 'abc',+ chat: vi.fn().mockResolvedValue(new Response(body)),+ };+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(new ModelRuntime(mockRuntime));++ const response = await POST(request, {+ params: Promise.resolve({ provider: 'test-provider' }),+ });++ expect(response.status).toBe(471);+ expect(await response.json()).toMatchObject({+ body: { provider: 'test-provider' },+ errorType: AgentRuntimeErrorType.ModelEmptyCompletion,+ });+ });++ it('streams a response whose body yields bytes', async () => {+ const mockRuntime: LobeRuntimeAI = {+ baseURL: 'abc',+ chat: vi.fn().mockResolvedValue(new Response('event: text\ndata: "OK"\n\n')),+ };+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(new ModelRuntime(mockRuntime));++ const response = await POST(request, {+ params: Promise.resolve({ provider: 'test-provider' }),+ });++ expect(response.status).toBe(200);+ expect(await response.text()).toBe('event: text\ndata: "OK"\n\n');+ });});});diff --git a/src/app/(backend)/webapi/chat/[provider]/route.ts b/src/app/(backend)/webapi/chat/[provider]/route.tsindex 369cf795f0d..f78a016dfb1 100644--- a/src/app/(backend)/webapi/chat/[provider]/route.ts+++ b/src/app/(backend)/webapi/chat/[provider]/route.ts@@ -1,6 +1,6 @@import { REQUEST_TOPIC_ID_HEADER } from '@lobechat/const';import { type ChatCompletionErrorPayload } from '@lobechat/model-runtime';-import { AGENT_RUNTIME_ERROR_SET } from '@lobechat/model-runtime';+import { AGENT_RUNTIME_ERROR_SET, awaitFirstResponseChunk } from '@lobechat/model-runtime';import { ChatErrorType } from '@lobechat/types';import { checkAuth } from '@/app/(backend)/middleware/auth';@@ -44,12 +44,16 @@ export const POST = checkAuth(async (req: Request, { params, userId, serverDB })traceOptions = createTraceOptions(data, { provider, trace: tracePayload });}- return await modelRuntime.chat(data, {+ const response = await modelRuntime.chat(data, {user: userId,...traceOptions,metadata: { topicId: req.headers.get(REQUEST_TOPIC_ID_HEADER) ?? undefined },signal: req.signal,});++ // A routed chat can fail before its first byte (e.g. an empty completion); surface that+ // as the structured error below instead of the framework's 500 page.+ return await awaitFirstResponseChunk(response);});} catch (e) {const {