The open-source agent harness - the runtime layer that turns an LLM into a working agent.
AGE-1577: Surface provider LLM API errors (#86)
Bhavesh Patelc8d437177fa5
diff --git a/packages/harness/src/core/llm/VercelAILLM.ts b/packages/harness/src/core/llm/VercelAILLM.tsindex 4d76716a4..3d4c661da 100644--- a/packages/harness/src/core/llm/VercelAILLM.ts+++ b/packages/harness/src/core/llm/VercelAILLM.ts@@ -26,7 +26,7 @@ import type {ToolSet,UserContent,} from 'ai';-import { jsonSchema, Output, streamText } from 'ai';+import { APICallError, jsonSchema, Output, streamText } from 'ai';import type {ChatCompletionContentPart,ChatCompletionCreateParams,@@ -904,10 +904,19 @@ export function normalizeUsage(usage: {}/**- * Providers surface stream errors as plain objects as often as Errors; `String()` on those- * yields "[object Object]" and loses the only description of what went wrong.+ * Prefer AI SDK `APICallError` (`message` / `statusCode`):+ * https://ai-sdk.dev/docs/reference/ai-sdk-errors/ai-api-call-error#properties+ * Fallback is required because stream `error` parts are typed `unknown` (not only+ * `APICallError`) — plain objects would otherwise stringify to "[object Object]".*/export function describeStreamError(raw: unknown): string {+ if (APICallError.isInstance(raw)) {+ if (raw.statusCode != null) {+ return `Request failed (${String(raw.statusCode)}): ${raw.message}`;+ }+ return raw.message;+ }+if (typeof raw !== 'object' || raw === null) {return String(raw);}@@ -1214,8 +1223,10 @@ export async function* mapStreamToChunks({case 'error': {const raw = part.error;- const err = raw instanceof Error ? raw : new Error(describeStreamError(raw));- throw new Error('LLM stream error', { cause: err });+ const message = describeStreamError(raw);+ // Preserve the original stream error as cause; toast/turn use .message only.+ const cause = raw instanceof Error ? raw : new Error(message);+ throw new Error(message, { cause });}case 'abort': {diff --git a/packages/harness/tests/core/llm/VercelAILLM.stream.test.ts b/packages/harness/tests/core/llm/VercelAILLM.stream.test.tsindex 8a304b63f..c1ffe08c9 100644--- a/packages/harness/tests/core/llm/VercelAILLM.stream.test.ts+++ b/packages/harness/tests/core/llm/VercelAILLM.stream.test.ts@@ -10,8 +10,14 @@ import type {TextStreamPart,ToolSet,} from 'ai';+import { APICallError } from 'ai';import type { ExtendedChatCompletionChunk, RawAssistantMessageWithUsage } from '../../../src/core/llm/LLMTypes';-import { mapFinishReason, mapStreamToChunks, normalizeUsage } from '../../../src/core/llm/VercelAILLM';+import {+ describeStreamError,+ mapFinishReason,+ mapStreamToChunks,+ normalizeUsage,+} from '../../../src/core/llm/VercelAILLM';// ─────────── Helpers ───────────@@ -121,6 +127,80 @@ describe('mapFinishReason', () => {});});+// ─────────── describeStreamError ───────────++describe('describeStreamError', () => {+ describe('APICallError', () => {+ it.each([+ {+ provider: 'openai',+ statusCode: 401,+ message: 'Incorrect API key provided: sk-inval***********-key.',+ expected: 'Request failed (401): Incorrect API key provided: sk-inval***********-key.',+ },+ {+ provider: 'anthropic',+ statusCode: 401,+ message: 'invalid x-api-key',+ expected: 'Request failed (401): invalid x-api-key',+ },+ {+ provider: 'google-gemini',+ statusCode: 400,+ message: 'API key not valid. Please pass a valid API key.',+ expected: 'Request failed (400): API key not valid. Please pass a valid API key.',+ },+ ] as const)('includes HTTP status for $provider invalid-key failures', ({ statusCode, message, expected }) => {+ expect(+ describeStreamError(+ new APICallError({+ message,+ url: 'https://example.com',+ requestBodyValues: {},+ statusCode,+ }),+ ),+ ).toBe(expected);+ });++ it('omits status prefix when statusCode is absent', () => {+ expect(+ describeStreamError(+ new APICallError({+ message: 'upstream failed',+ url: 'https://example.com',+ requestBodyValues: {},+ }),+ ),+ ).toBe('upstream failed');+ });+ });++ describe('fallback', () => {+ it('uses Error.message', () => {+ expect(describeStreamError(new Error('upstream error'))).toBe('upstream error');+ });++ it('uses a plain object message field', () => {+ expect(describeStreamError({ message: 'The requested model does not exist.' })).toBe(+ 'The requested model does not exist.',+ );+ });++ it('JSON-serialises a message-less object instead of [object Object]', () => {+ expect(describeStreamError({ code: 'model_not_found', status: 404 })).toBe(+ '{"code":"model_not_found","status":404}',+ );+ });++ it('stringifies non-object values', () => {+ expect(describeStreamError('string error')).toBe('string error');+ expect(describeStreamError(42)).toBe('42');+ expect(describeStreamError(null)).toBe('null');+ });+ });+});+// ─────────── mapStreamToChunks ───────────describe('mapStreamToChunks', () => {@@ -474,7 +554,7 @@ describe('mapStreamToChunks', () => {expect(final.finish_reason).toBe('length');});- it('rejects (with cause) on an error part', async () => {+ it('rejects with the provider message on an error part', async () => {const cause = new Error('upstream error');await expect(drainStream(@@ -483,7 +563,7 @@ describe('mapStreamToChunks', () => {chunkMeta: CHUNK_META,}),),- ).rejects.toMatchObject({ message: 'LLM stream error', cause });+ ).rejects.toMatchObject({ message: 'upstream error', cause });});it('rejects on an abort part rather than returning the partial message as a clean stop', async () => {@@ -497,45 +577,40 @@ describe('mapStreamToChunks', () => {).rejects.toMatchObject({ name: 'AbortError' });});- it('keeps the provider message when the error part carries a plain object', async () => {+ it('rejects with describeStreamError output for an APICallError part', async () => {+ const cause = new APICallError({+ message: 'invalid x-api-key',+ url: 'https://example.com',+ requestBodyValues: {},+ statusCode: 401,+ });await expect(drainStream(mapStreamToChunks({- stream: makeStream([{ type: 'error', error: { message: 'The requested model does not exist.' } }]),+ stream: makeStream([{ type: 'error', error: cause }]),chunkMeta: CHUNK_META,}),),).rejects.toMatchObject({- message: 'LLM stream error',- cause: { message: 'The requested model does not exist.' },+ message: 'Request failed (401): invalid x-api-key',+ cause,});});- it('serialises a message-less error object rather than stringifying it to [object Object]', async () => {+ it('rejects with describeStreamError output for a plain-object error part', async () => {await expect(drainStream(mapStreamToChunks({- stream: makeStream([{ type: 'error', error: { code: 'model_not_found', status: 404 } }]),+ stream: makeStream([{ type: 'error', error: { message: 'The requested model does not exist.' } }]),chunkMeta: CHUNK_META,}),),).rejects.toMatchObject({- message: 'LLM stream error',- cause: { message: '{"code":"model_not_found","status":404}' },+ message: 'The requested model does not exist.',+ cause: { message: 'The requested model does not exist.' },});});- it('wraps non-Error error values in an Error with cause', async () => {- await expect(- drainStream(- mapStreamToChunks({- stream: makeStream([{ type: 'error', error: 'string error' }]),- chunkMeta: CHUNK_META,- }),- ),- ).rejects.toMatchObject({ message: 'LLM stream error' });- });-it('sets chunk metadata (id, model, object) on emitted chunks', async () => {const meta = { id: 'vc-test-001', created: 1000, model: 'my-model' };const { chunks } = await drainStream(