Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
OpenAI-compatible: a turn llama.cpp refuses as over its context resends smaller
Absterrg064376f685403
diff --git a/server/drivers/chat-size-limit.test.ts b/server/drivers/chat-size-limit.test.tsindex c6c497d492..b6220ab038 100644--- a/server/drivers/chat-size-limit.test.ts+++ b/server/drivers/chat-size-limit.test.ts@@ -8,13 +8,14 @@ import type { SendTurnInput } from "../contracts.ts";import { recordEvents } from "../testing/events.ts";import { removeTempDir } from "../testing/cleanup.ts";import { requestTooLargeMessage } from "../../shared/request-too-large.ts";-import { IMAGE_OMITTED, refusesRequestSize, smallerResend, TOOL_OUTPUT_SHORTENED } from "./chat-size-limit.ts";+import { IMAGE_OMITTED, refusesRequestSize, shareThatFits, smallerResend, TOOL_OUTPUT_SHORTENED } from "./chat-size-limit.ts";import type { OpenAIChatMessage } from "./openai-chat.ts";import { OpenAICompatDriver } from "./openai-compat.ts";const NGINX_413 = "<html>\r\n<head><title>413 Request Entity Too Large</title></head>\r\n<body>\r\n<center><h1>413 Request Entity Too Large</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n";const CONTEXT_CODE = '{"error":{"code":"context_length_exceeded","message":"This model\'s maximum context length is 262142 tokens. Your messages resulted in 555619 tokens."}}';const CONTEXT_TYPE = '{"error":{"type":"context_length_exceeded","message":"prompt is too long: 300000 tokens > 262144 maximum"}}';+const LLAMA_CPP = '{"error":{"code":400,"message":"request (98312 tokens) exceeds the available context size (98304 tokens), try increasing it","type":"exceed_context_size_error","n_prompt_tokens":98312,"n_ctx":98304}}';const SIZE_REFUSALS = [{ name: "HTTP 413", status: 413, body: NGINX_413 },{ name: "HTTP 400 error.code", status: 400, body: CONTEXT_CODE },@@ -33,6 +34,7 @@ describe("refusesRequestSize", () => {[429, '{"error":{"message":"Request too large for gpt-4o in organization org-fixture on tokens per min (TPM): Limit 30000, Requested 45000."}}'],[400, CONTEXT_CODE],[400, CONTEXT_TYPE],+ [400, LLAMA_CPP],])("reads HTTP %i %j as a size refusal", (status, body) => {expect(refusesRequestSize(status, body)).toBe(true);});@@ -46,6 +48,8 @@ describe("refusesRequestSize", () => {[400, '{"error":[{"code":"context_length_exceeded"}]}'],[400, '{"error":{"code":"context_length_exceeded_extra"}}'],[400, '{"error":{"type":"context_length_exceeded_extra"}}'],+ [400, '{"error":{"message":"exceed_context_size_error"}}'],+ [500, LLAMA_CPP],[400, "null"],[400, "[]"],[400, '{"error":'],@@ -62,6 +66,23 @@ describe("refusesRequestSize", () => {});});+describe("shareThatFits", () => {+ it("keeps what fits the window llama.cpp counted, with room left for the reply", () => {+ expect(shareThatFits(LLAMA_CPP)).toBeCloseTo(0.8, 3);+ expect(shareThatFits('{"error":{"type":"exceed_context_size_error","n_prompt_tokens":400,"n_ctx":100}}')).toBeCloseTo(0.2);+ });++ it.each([+ CONTEXT_CODE, CONTEXT_TYPE, NGINX_413, "",+ '{"error":{"type":"exceed_context_size_error","n_prompt_tokens":100,"n_ctx":100}}',+ '{"error":{"type":"exceed_context_size_error","n_prompt_tokens":"98312","n_ctx":"98304"}}',+ '{"error":{"type":"exceed_context_size_error","n_prompt_tokens":98312,"n_ctx":0}}',+ '{"n_prompt_tokens":98312,"n_ctx":98304}',+ ])("says nothing about %j", (body) => {+ expect(shareThatFits(body)).toBeUndefined();+ });+});+describe("smallerResend", () => {const history = (count: number, bytes: number): OpenAIChatMessage[] => Array.from({ length: count }, (_, index) =>({ role: index % 2 ? "assistant" : "user", content: `history ${index} ${"h".repeat(bytes)}` }));@@ -110,6 +131,15 @@ describe("smallerResend", () => {expect(resend.after.bytes).toBeLessThanOrEqual(refused / 2);});+ it("drops only as much as the provider's own count asks for", () => {+ const { request, messages, refused } = turn(history(10, 4_000));+ const halved = smallerResend(messages, request, refused)!;+ const counted = smallerResend(messages, request, refused, 0.8)!;+ expect(counted.after.bytes).toBeLessThanOrEqual(refused * 0.8);+ expect(counted.after.bytes).toBeGreaterThan(halved.after.bytes);+ expect(counted.after.messages).toBeGreaterThan(halved.after.messages);+ });+it("offers nothing to resend when only the system prompt and the request are left", () => {const { request, messages, refused } = turn([]);expect(smallerResend(messages, request, refused)).toBeNull();@@ -209,6 +239,51 @@ describe("an OpenAI-compatible provider that refuses large requests", () => {expect(logged[0]).not.toMatch(/earlier \d|Summarize|Fixture system/);});+ const tokens = (bytes: number) => Math.ceil(bytes / 4);+ const llamaCpp = (window: (firstTokens: number) => number) => {+ let n_ctx: number | undefined;+ return (bytes: number) => {+ n_ctx ??= window(tokens(bytes));+ return tokens(bytes) > n_ctx ? { status: 400, body: JSON.stringify({ error: { code: 400,+ message: `request (${tokens(bytes)} tokens) exceeds the available context size (${n_ctx} tokens), try increasing it`,+ type: "exceed_context_size_error", n_prompt_tokens: tokens(bytes), n_ctx } }) } : null;+ };+ };++ it("resends a request llama.cpp counts a few tokens over its window with most of the history kept", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const f = await provider(llamaCpp((first) => first - 2));+ const done = await f.run({ system: "Fixture system prompt.", transcript: transcript(20, 3_000) });+ expect(done).toMatchObject({ ok: true });+ expect(f.requests).toHaveLength(2);+ const [refused, resent] = f.requests;+ expect(resent!.bytes).toBeLessThanOrEqual(refused!.bytes * 0.8);+ expect(resent!.bytes).toBeGreaterThan(refused!.bytes * 0.6);+ expect(resent!.messages.length).toBeGreaterThan(refused!.messages.length / 2);+ expect(resent!.messages.at(-1)).toEqual(refused!.messages.at(-1));+ expect(f.retries()).toEqual([expect.objectContaining({ attempt: 1, delayMs: 0, reason: "request_too_large" })]);+ expect(f.errors()).toEqual([]);+ });++ it("resends a request llama.cpp counts at three times its window small enough to fit, where half would not", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const f = await provider(llamaCpp((first) => Math.floor(first / 3)));+ const done = await f.run({ system: "Fixture system prompt.", transcript: transcript(20, 3_000) });+ expect(done).toMatchObject({ ok: true });+ expect(f.requests).toHaveLength(2);+ expect(tokens(f.requests[1]!.bytes)).toBeLessThanOrEqual(Math.floor(tokens(f.requests[0]!.bytes) / 3));+ expect(f.errors()).toEqual([]);+ });++ it("fails with one plain message when not even the newest message fits llama.cpp's window", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const f = await provider(llamaCpp(() => 100));+ const done = await f.run({ system: "Fixture system prompt.", transcript: transcript(20, 3_000) });+ expect(done).toMatchObject({ ok: false });+ expect(f.requests).toHaveLength(2);+ expect(f.errors()).toEqual([requestTooLargeMessage("Fixture Flash")]);+ });+it.each(SIZE_REFUSALS)("$name fails with one plain message when the smaller resend is still too large", async (refusal) => {vi.spyOn(console, "warn").mockImplementation(() => {});const f = await provider(above(10_000, refusal));diff --git a/server/drivers/chat-size-limit.ts b/server/drivers/chat-size-limit.tsindex e6533661ee..f8e8fadb3c 100644--- a/server/drivers/chat-size-limit.ts+++ b/server/drivers/chat-size-limit.ts@@ -6,23 +6,41 @@ import { object } from "./openai-chat-protocol.ts";/** nginx's "413 Request Entity Too Large" page, Express's "request entity too large", "Payload Too Large", and* OpenAI's "Request too large for <model>". */const TOO_LARGE = /\b(?:request entity|payload|request) too large\b/i;+/** OpenAI's context_length_exceeded, and llama.cpp server's exceed_context_size_error (seen on b12532, streamed or not). */+const CONTEXT_REFUSALS: ReadonlySet<unknown> = new Set(["context_length_exceeded", "exceed_context_size_error"]);-export function refusesRequestSize(status: number, body: string): boolean {- if (status === 413 || TOO_LARGE.test(body)) return true;- if (status !== 400) return false;+const WINDOW_FILLED_BY_RESEND = 0.8;++function bodyError(body: string): Record<string, unknown> | undefined {try {- const error = object(object(JSON.parse(body))?.error);- return error?.code === "context_length_exceeded" || error?.type === "context_length_exceeded";+ return object(object(JSON.parse(body))?.error);} catch {- return false;+ return undefined;}}+export function refusesRequestSize(status: number, body: string): boolean {+ if (status === 413 || TOO_LARGE.test(body)) return true;+ if (status !== 400) return false;+ const error = bodyError(body);+ return error?.code === "context_length_exceeded" || CONTEXT_REFUSALS.has(error?.type);+}++/** The share of a refused request that fits the window its provider counted (llama.cpp's n_ctx of n_prompt_tokens). */+export function shareThatFits(body: string): number | undefined {+ const error = bodyError(body);+ const window = error?.n_ctx, prompt = error?.n_prompt_tokens;+ if (typeof window !== "number" || typeof prompt !== "number" || window <= 0 || prompt <= window) return undefined;+ return window / prompt * WINDOW_FILLED_BY_RESEND;+}+export class RequestTooLargeError extends Error {readonly bytes: number;- constructor(message: string, bytes: number) {+ readonly fits: number | undefined;+ constructor(message: string, bytes: number, fits?: number) {super(message);this.bytes = bytes;+ this.fits = fits;}}@@ -64,17 +82,19 @@ function shortenedToolOutput(message: OpenAIChatMessage): OpenAIChatMessage {return { ...message, content: typeof envelope?.result === "string" ? JSON.stringify({ ...envelope, result: shorten(envelope.result) }) : shorten(content) };}-/** Aims at half of `refusedBytes`; null when nothing but the system prompt and `request` could shrink. */+/** Aims at `fits` of `refusedBytes`, half when the provider did not say; null when nothing but the system prompt and+ * `request` could shrink. */export function smallerResend(messages: readonly OpenAIChatMessage[],request: OpenAIChatMessage,refusedBytes: number,+ fits = 0.5,): { messages: OpenAIChatMessage[]; before: RequestSize; after: RequestSize } | null {const requestAt = messages.indexOf(request);if (requestAt < 0) throw new Error("the turn's request is not among the messages to resend");const before = requestSize(messages);const overhead = Math.max(0, refusedBytes - before.bytes);- const target = Math.floor(refusedBytes / 2) - overhead;+ const target = Math.floor(refusedBytes * fits) - overhead;const out: Array<OpenAIChatMessage | null> = [...messages];const sizes = out.map(bytesOf);let total = sizes.reduce((sum, size) => sum + size, 0);diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 1b6b611a61..5ad47200e4 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -30,7 +30,7 @@ import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS }import { plainFailure } from "./engine-errors.ts";import { noticeFailure } from "../chat-notices.ts";import { toolFailureMessage } from "./tool-failure.ts";-import { refusesRequestSize, RequestTooLargeError, sizeChange, smallerResend } from "./chat-size-limit.ts";+import { refusesRequestSize, RequestTooLargeError, shareThatFits, sizeChange, smallerResend } from "./chat-size-limit.ts";import { requestTooLargeMessage } from "../../shared/request-too-large.ts";import { toolSchemaProfileFor } from "../tool-schema-profile.ts";import { classifyContinuable, writeTurnHandoff } from "../turn-continuation.ts";@@ -300,7 +300,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const refused = tools.length ? routeRefusal(route, status, body) : null;if (refused) return new ModelRouteRefused(refused, message);if (rejectsKey(status, body)) noteKeyRejected(options.apiUrl, options.apiKey);- if (refusesRequestSize(status, body)) return new RequestTooLargeError(message, Buffer.byteLength(payload));+ if (refusesRequestSize(status, body)) return new RequestTooLargeError(message, Buffer.byteLength(payload), shareThatFits(body));if (rejectsToolsParameter(status, body)) return new UnsupportedChatToolsError(message);const refusal = refusedToolCall(status, body);if (refusal) return new RejectedToolCallError(message, refusal);@@ -697,7 +697,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)}// A provider refuses an oversized request before running anything, so one smaller copy may go again.if (error instanceof RequestTooLargeError && !abort.signal.aborted) {- const resend = resized ? null : smallerResend(messages, request, error.bytes);+ const resend = resized ? null : smallerResend(messages, request, error.bytes, error.fits);native("out", { refused: "request_too_large", bytes: error.bytes, ...(resend ? { before: resend.before, after: resend.after } : {}) });console.warn(`${options.driverKind}: ${model} refused a ${error.bytes}-byte request as too large; ${resend ? `resending smaller (${sizeChange(resend.before, resend.after)})` : "not resending"}`);if (!resend) throw new ChatProtocolError(requestTooLargeMessage(options.models().options.find((option) => option.id === model)?.label ?? model));