mike-backend / backend /src /lib /assistantErrors.ts
bardd's picture
Deploy Mike backend-only Space
06671aa verified
Raw History Blame Contribute Delete
3.08 kB
export type AssistantErrorCode =
| "context_budget_exceeded"
| "tool_loop_detected"
| "too_many_document_reads"
| "duplicate_document_read_loop"
| "proxy_all_credentials_exhausted"
| "proxy_timeout"
| "provider_context_window_exceeded"
| "assistant_stream_error";
export type NormalizedAssistantError = {
code: AssistantErrorCode;
userMessage: string;
safeDetails: Record<string, unknown>;
};
export class ControlledUserFacingError extends Error {
public readonly code: AssistantErrorCode;
public readonly safeDetails: Record<string, unknown>;
constructor(params: {
code: AssistantErrorCode;
message: string;
safeDetails?: Record<string, unknown>;
}) {
super(params.message);
this.name = "ControlledUserFacingError";
this.code = params.code;
this.safeDetails = params.safeDetails ?? {};
}
}
function messageFromUnknown(err: unknown): string {
if (err instanceof Error) return err.message;
if (typeof err === "string") return err;
try {
return JSON.stringify(err);
} catch {
return String(err);
}
}
export function normalizeAssistantError(err: unknown): NormalizedAssistantError {
if (err instanceof ControlledUserFacingError) {
return {
code: err.code,
userMessage: err.message,
safeDetails: err.safeDetails,
};
}
const rawMessage = messageFromUnknown(err);
const message = rawMessage.toLowerCase();
if (message.includes("proxy_all_credentials_exhausted")) {
return {
code: "proxy_all_credentials_exhausted",
userMessage:
"The model provider is temporarily overloaded or out of available credentials. The request was stopped safely. Please retry with a narrower request or a different model/provider.",
safeDetails: {},
};
}
if (message.includes("proxy_timeout") || message.includes("request timed out")) {
return {
code: "proxy_timeout",
userMessage:
"The model provider timed out before completing the response. The request was stopped safely. Please retry with a narrower request or a different model/provider.",
safeDetails: {},
};
}
if (
message.includes("context_budget_exceeded") ||
message.includes("context window") ||
message.includes("maximum context") ||
message.includes("context length") ||
message.includes("token limit")
) {
return {
code: "provider_context_window_exceeded",
userMessage:
"The request is too large to process safely in one pass. Please ask about a specific section, clause, issue, or smaller set of documents.",
safeDetails: {},
};
}
return {
code: "assistant_stream_error",
userMessage:
"The assistant hit an internal error while streaming. The session was stopped safely.",
safeDetails: {},
};
}