import * as plugins from './plugins.js'; /** * The error object of an OpenAI error body, of a Responses `response.failed` stream frame or of a * Responses `error` stream frame. */ export interface IOpenAiErrorDetails { /** The error's `type` and `code`; HTTP bodies name the error in `type`, stream frames in `code`. */ readonly identifiers: readonly string[]; readonly fields: Readonly>; } function readIdentifiers(...values: unknown[]): string[] { return values.filter((value): value is string => typeof value === 'string'); } export function readOpenAiError(body: unknown): IOpenAiErrorDetails | undefined { const envelope = plugins.readJsonRecord(body); const fields = plugins.readJsonRecord(envelope?.error) ?? plugins.readJsonRecord(plugins.readJsonRecord(envelope?.response)?.error); if (fields) return { identifiers: readIdentifiers(fields.type, fields.code), fields }; // an `error` stream frame may carry its fields beside `type: 'error'`, which names the frame, not the error if (envelope?.type === 'error') return { identifiers: readIdentifiers(envelope.code), fields: envelope }; return undefined; } /** OpenAI API limits: `insufficient_quota` is an exhausted balance, any other 429 a rate limit. */ export const classifyOpenAiLimit: plugins.TModelLimitClassifier = (failure) => { const identifiers = readOpenAiError(failure.body)?.identifiers ?? []; if (identifiers.includes('insufficient_quota')) return { kind: 'usage_limit' }; if (failure.statusCode === 429 || identifiers.includes('rate_limit_exceeded')) return { kind: 'rate_limit' }; return undefined; };