fix(ai): drive the structured stream and use the chat endpoint
Dialogue drafting hung on "Drafting..." forever against OpenRouter, with the provider having received and completed the request. Two independent faults, both found by running the app's own code against the live endpoint. The hang: streamObject is lazy. Awaiting result.object alone does not pump the stream in this SDK version, so the promise waited for a parse that never started and the call sat until its ten minute ceiling. One identical request, measured twice: object-only never returned in 60s, draining textStream first returned a valid draft in 6.9s. generateStructured now drains the stream before reading the object. The endpoint: provider(modelId) resolves to OpenAI's Responses API, which only OpenAI implements. OpenRouter answered 200 and never completed. Every OpenAI-compatible service the app targets serves /chat/completions, which the plain path already used, so chatModelFor reaches the model through .chat(). The instrumented request now goes to /chat/completions and Compose's structured branch uses the same call. Defences, since a provider can still answer and then go quiet: an idle watchdog aborts a body that delivers no bytes for 60s on both paths, transport retries are off so one stall is one wait, a draft is capped at four minutes, and the dialog has a UI watchdog plus a catch that shows the failure instead of spinning. Against the live endpoint the real function now returns a five node draft in 6.2s. 246 tests across 24 files pass, including a regression test that fails if the stream drain is ever removed.
This commit is contained in:
parent
90037711e2
commit
51ead07da0
8 changed files with 317 additions and 16 deletions
|
|
@ -100,16 +100,44 @@ result write would invalidate itself.
|
|||
- `… API error: 401 … Invalid API key`: the key is wrong or expired. Note that the
|
||||
Unsloth box rejects an unknown key with this, so a 401 against the LAN host usually
|
||||
means `UNSLOTH_API_KEY` is stale, not that a connection is misconfigured.
|
||||
- `The provider stopped sending data (60s with no response).`: the provider
|
||||
answered and then went quiet mid-response. The idle watchdog abandons the call
|
||||
rather than waiting for the total ceiling. Try again: the request is likely to
|
||||
route to a different upstream, and the connection's Test button tells you
|
||||
whether the endpoint itself is healthy.
|
||||
- `… API error: 400 … response_format`: the provider rejects the structured mode.
|
||||
Switch to `json_object` or `prompt`, or turn off the reasoning toggle if the
|
||||
error names `reasoning_effort`.
|
||||
- Drafts fail twice with `before blaming the model`: the prompt voice is suspect,
|
||||
not the provider. The message names which voice was in use.
|
||||
|
||||
## Sending the request
|
||||
|
||||
Two things about the request are easy to get wrong, and both produced silent
|
||||
hangs rather than errors:
|
||||
|
||||
- **The chat-completions endpoint, always.** `chatModelFor` reaches the model
|
||||
through `provider.chat(modelId)`. Calling the provider as a function
|
||||
(`provider(modelId)`) resolves to OpenAI's *Responses* API, which only OpenAI
|
||||
implements: OpenRouter, DeepSeek, Unsloth Studio and Ollama serve
|
||||
`/chat/completions` and nothing else. There the request still returned 200 and
|
||||
the draft never arrived.
|
||||
- **The stream must be drained.** `streamObject` is lazy: `result.object` does
|
||||
not resolve unless something reads the stream, so awaiting that promise alone
|
||||
waits for a parse that never starts. `generateStructured` drains `textStream`
|
||||
first. Measured against OpenRouter with one identical request: object-only never
|
||||
returned in 60s, draining returned a draft in 6.9s.
|
||||
- Transport retries are off (`maxRetries: 0`) so one stall is one wait. The draft
|
||||
runner already retries for a better reason: validator complaints.
|
||||
|
||||
## Tests
|
||||
|
||||
- `tests/int/ai-connections.int.spec.ts`: key write-only contract, blank-means-keep,
|
||||
clear, per-surface resolution, half-filled fallback, test-result invalidation.
|
||||
- `tests/int/ai-structured-stream.int.spec.ts`: the lazy-stream guard. Fails if the
|
||||
drain is ever removed, which is the bug that made every draft hang.
|
||||
- `tests/int/ai-idle-watchdog.int.spec.ts`: healthy body passes through, a silent
|
||||
body fails in the silence window, a body-less response is left alone.
|
||||
- `tests/int/ai-generate-modes.int.spec.ts`: request shape against a local stub
|
||||
server (URL, model, key header, reasoning toggle), all three structured modes, and
|
||||
provider-error surfacing.
|
||||
|
|
|
|||
|
|
@ -196,13 +196,31 @@ export function GenerateDraftDialog({
|
|||
setError(null);
|
||||
try {
|
||||
const scope = effectivePlacement === "replace" ? "full" : "fragment";
|
||||
const res = await generateNpcDialogueDraft(npcId, { ...brief, goal }, dialogueId, {
|
||||
scope,
|
||||
insertionHint:
|
||||
scope === "fragment" && effectivePlacement === "attach" && attachTarget
|
||||
? `${attachTarget.label}, through ${attachTarget.output}`
|
||||
: null,
|
||||
});
|
||||
// Watchdog for the UI only: the server bounds the model call itself (an
|
||||
// idle stream aborts in 60s, a draft in 4 minutes), so this only fires if
|
||||
// the action's own response never reaches us, which is what a dead socket
|
||||
// looks like. Without it the button spins with no way out.
|
||||
const deadline = new Promise<never>((_, reject) =>
|
||||
setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
new Error(
|
||||
"No answer from the server. The model may be stalled; try again, or test the AI connection.",
|
||||
),
|
||||
),
|
||||
330_000,
|
||||
),
|
||||
);
|
||||
const res = await Promise.race([
|
||||
generateNpcDialogueDraft(npcId, { ...brief, goal }, dialogueId, {
|
||||
scope,
|
||||
insertionHint:
|
||||
scope === "fragment" && effectivePlacement === "attach" && attachTarget
|
||||
? `${attachTarget.label}, through ${attachTarget.output}`
|
||||
: null,
|
||||
}),
|
||||
deadline,
|
||||
]);
|
||||
if (!res.success || !res.data) {
|
||||
setError(res.error ?? "The model could not produce a usable conversation.");
|
||||
return;
|
||||
|
|
@ -215,6 +233,12 @@ export function GenerateDraftDialog({
|
|||
returnToCaller: attachTarget?.returnsTo != null && returnToCaller,
|
||||
});
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
setError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The draft request failed before the model answered.",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -86,9 +86,74 @@ export interface AiConnection {
|
|||
sendReasoningOff?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a provider may go silent mid-response before the call is abandoned.
|
||||
*
|
||||
* A total timeout is not enough. OpenRouter (and any provider behind a proxy)
|
||||
* can answer 200, stream most of a response, and then stop without finishing or
|
||||
* closing: the model has produced tokens and the connection simply goes quiet.
|
||||
* `fetch` waits for EOF, so without an idle guard the call sits until the total
|
||||
* ceiling, which is why a draft could hang on "Drafting..." for ten minutes.
|
||||
* Sixty seconds with no bytes at all is not a slow model, it is a dead stream.
|
||||
*/
|
||||
export const PROVIDER_IDLE_TIMEOUT_MS = 60_000;
|
||||
|
||||
/** Abort a response body that stops delivering bytes for `idleMs`. */
|
||||
export function idleWatchdogFetch(idleMs: number = PROVIDER_IDLE_TIMEOUT_MS): typeof fetch {
|
||||
return async (input, init) => {
|
||||
const response = await fetch(input, init);
|
||||
if (!response.body) return response;
|
||||
|
||||
const reader = response.body.getReader();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const clear = () => {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
timer = undefined;
|
||||
};
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
const stalled = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
reject(
|
||||
new Error(
|
||||
`The provider stopped sending data (${Math.round(idleMs / 1000)}s with no response).`,
|
||||
),
|
||||
);
|
||||
}, idleMs);
|
||||
});
|
||||
try {
|
||||
const result = await Promise.race([reader.read(), stalled]);
|
||||
clear();
|
||||
if (result.done) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
controller.enqueue(result.value);
|
||||
} catch (error) {
|
||||
clear();
|
||||
void reader.cancel().catch(() => undefined);
|
||||
controller.error(error);
|
||||
}
|
||||
},
|
||||
cancel(reason) {
|
||||
clear();
|
||||
return reader.cancel(reason);
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: response.headers,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export const unslothProvider = createOpenAI({
|
||||
apiKey: process.env.UNSLOTH_API_KEY,
|
||||
baseURL: UNSLOTH_BASE_URL,
|
||||
fetch: idleWatchdogFetch(),
|
||||
});
|
||||
|
||||
/** An OpenAI-compatible provider for one connection, or the shared default. */
|
||||
|
|
@ -97,12 +162,30 @@ function providerFor(connection?: AiConnection | null) {
|
|||
return createOpenAI({
|
||||
apiKey: connection.apiKey || process.env.UNSLOTH_API_KEY,
|
||||
baseURL: connection.baseUrl,
|
||||
fetch: idleWatchdogFetch(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider for a connection, for callers that build their own stream (the
|
||||
* Compose plugin's non-prose branch does).
|
||||
* The chat-completions model for a connection or the env default.
|
||||
*
|
||||
* `provider(modelId)` is NOT this: an `@ai-sdk/openai` provider called directly
|
||||
* resolves to OpenAI's **Responses API** (`/responses`), which only OpenAI
|
||||
* implements. Every OpenAI-compatible service the app talks to (OpenRouter,
|
||||
* DeepSeek, Unsloth Studio/llama.cpp, Ollama) serves `/chat/completions` and
|
||||
* nothing else, and the plain path below already posts there. Calling the
|
||||
* provider as a function therefore sent structured requests to an endpoint the
|
||||
* provider does not have: OpenRouter answered 200 and then never streamed a
|
||||
* complete response, so a draft sat on "Drafting..." until the 10 minute
|
||||
* timeout. Always reach the model through `.chat()`.
|
||||
*/
|
||||
export function chatModelFor(connection: AiConnection | null | undefined, modelId: string) {
|
||||
return providerFor(connection).chat(modelId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider for a connection, kept for callers that need the raw client (the
|
||||
* Compose plugin builds its stream through `chatModelFor`, not this).
|
||||
*/
|
||||
export function connectionProvider(connection?: AiConnection | null) {
|
||||
return providerFor(connection);
|
||||
|
|
@ -178,7 +261,7 @@ export async function generatePlainText(
|
|||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(completionsUrl(connection), {
|
||||
response = await idleWatchdogFetch()(completionsUrl(connection), {
|
||||
method: "POST",
|
||||
// Bounded because the base URL is now admin-configured: a host that accepts
|
||||
// the connection and never answers would otherwise hang this call forever,
|
||||
|
|
@ -246,6 +329,13 @@ export interface StructuredGenerationOptions {
|
|||
temperature?: number;
|
||||
/** Route through a stored connection, which also determines the mode. */
|
||||
connection?: AiConnection | null;
|
||||
/**
|
||||
* Ceiling for this call, in milliseconds. Defaults to `REQUEST_TIMEOUT_MS`
|
||||
* (ten minutes, sized for a slow local model writing prose). A draft is short
|
||||
* and a stuck provider should surface as an error the author can read, so
|
||||
* callers pass something smaller.
|
||||
*/
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface StructuredResult<T> {
|
||||
|
|
@ -322,11 +412,16 @@ export async function generateStructured<T>(
|
|||
|
||||
const result = streamObject({
|
||||
maxOutputTokens: options.maxTokens ?? 5000,
|
||||
// No transport retries. The SDK's default (two) turns one stalled stream into
|
||||
// three sequential waits, which is how a 60s idle abort became a multi-minute
|
||||
// hang in testing. A draft already retries for a better reason (validator
|
||||
// complaints), and a caller that wants a blind retry can ask for one.
|
||||
maxRetries: 0,
|
||||
// Same ceiling as the plain path. Without it a provider that answers the
|
||||
// plain probe and then stalls leaves Generate busy forever, because the
|
||||
// modal waits on `result.object` for as long as the stream dribbles.
|
||||
abortSignal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
model: providerFor(connection)(connection?.modelId || options.model || resolveModel()),
|
||||
abortSignal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS),
|
||||
model: chatModelFor(connection, connection?.modelId || options.model || resolveModel()),
|
||||
onError: (error) => {
|
||||
console.error("AI generateStructured: ", error);
|
||||
},
|
||||
|
|
@ -343,8 +438,20 @@ export async function generateStructured<T>(
|
|||
},
|
||||
});
|
||||
|
||||
// Awaiting `object` drives the stream to completion and resolves once the
|
||||
// final JSON parses; it rejects when the output never satisfied the schema.
|
||||
// Drive the response before reading it.
|
||||
//
|
||||
// `result.object` on its own does NOT pump the stream in this SDK version: the
|
||||
// underlying stream is lazy, so awaiting that promise waits for a parse that
|
||||
// never starts and the call sits until its timeout. Measured against OpenRouter
|
||||
// with the same request: awaiting only `object` never returned in 60s, draining
|
||||
// the stream first returned a valid draft in 6.9s. That was the whole
|
||||
// "Drafting..." hang, independent of the provider. Draining is what advances the
|
||||
// parse; the chunks themselves are discarded, the object is read below.
|
||||
for await (const _chunk of result.textStream) {
|
||||
// Intentionally empty.
|
||||
}
|
||||
|
||||
// Now resolved: `object` rejects when the output never satisfied the schema.
|
||||
const object = (await result.object) as T;
|
||||
const finishReason = await result.finishReason;
|
||||
return { object, truncated: finishReason === "length" };
|
||||
|
|
|
|||
|
|
@ -121,6 +121,8 @@ export async function probeConnection(payload: Payload, id: number): Promise<Pro
|
|||
connection,
|
||||
maxTokens: 128,
|
||||
temperature: 0,
|
||||
// A probe is a two-word answer; a test button should not sit for minutes.
|
||||
timeoutMs: 90_000,
|
||||
});
|
||||
|
||||
if (!structured.object || typeof structured.object.status !== "string") {
|
||||
|
|
|
|||
|
|
@ -204,12 +204,21 @@ export interface DraftOutcome {
|
|||
connectionLabel: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ceiling for one draft attempt. A draft is a few hundred lines of JSON, so a
|
||||
* model that has not produced it in four minutes is not going to; the retry
|
||||
* after a validation failure gets its own window. Without this the only bound
|
||||
* was the ten-minute default sized for long prose.
|
||||
*/
|
||||
const DRAFT_TIMEOUT_MS = 240_000;
|
||||
|
||||
const defaultRunner: DraftRunner = (input) =>
|
||||
generateStructured<{ nodes?: RawDraftNode[] }>({
|
||||
...input,
|
||||
model: effectiveModel(input.connection),
|
||||
maxTokens: 4000,
|
||||
temperature: 0.8,
|
||||
timeoutMs: DRAFT_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -125,7 +125,7 @@ import { surveyFormBuilderConfig } from "@/lib/surveys/formBuilderConfig";
|
|||
import { buildComposeSystem, resolveProseShape, wrapProse } from "@/lib/ai/composeSystem";
|
||||
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
|
||||
import {
|
||||
connectionProvider,
|
||||
chatModelFor,
|
||||
DEFAULT_MODEL,
|
||||
generatePlainText,
|
||||
MODEL_ID,
|
||||
|
|
@ -786,7 +786,7 @@ export default buildConfig({
|
|||
// Same ceiling as every other model call: Compose runs inside an
|
||||
// admin request, and a stalled provider would hold it open.
|
||||
abortSignal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
model: connectionProvider(connection)(model),
|
||||
model: chatModelFor(connection, model),
|
||||
onError: (error) => {
|
||||
console.error("Unsloth generateObject: ", error);
|
||||
},
|
||||
|
|
|
|||
73
tests/int/ai-idle-watchdog.int.spec.ts
Normal file
73
tests/int/ai-idle-watchdog.int.spec.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { idleWatchdogFetch, PROVIDER_IDLE_TIMEOUT_MS } from "@/lib/ai/generate";
|
||||
|
||||
/**
|
||||
* The idle watchdog exists because a provider can answer 200, stream part of a
|
||||
* response, and then go quiet without finishing or closing. These tests drive
|
||||
* the wrapper with fake streams: a healthy body must pass through unchanged, a
|
||||
* silent one must fail fast instead of waiting for a total timeout.
|
||||
*/
|
||||
describe("provider idle watchdog", () => {
|
||||
it("is a full minute by default", () => {
|
||||
expect(PROVIDER_IDLE_TIMEOUT_MS).toBe(60_000);
|
||||
});
|
||||
|
||||
it("delivers a healthy stream byte for byte", async () => {
|
||||
const encoder = new TextEncoder();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(encoder.encode("data: one\n\n"));
|
||||
controller.enqueue(encoder.encode("data: two\n\n"));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () =>
|
||||
new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } });
|
||||
try {
|
||||
const response = await idleWatchdogFetch(500)("https://example.test/chat/completions");
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toBe("text/event-stream");
|
||||
await expect(response.text()).resolves.toBe("data: one\n\ndata: two\n\n");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("fails a stream that stops sending instead of hanging", async () => {
|
||||
const encoder = new TextEncoder();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(encoder.encode("data: partial\n\n"));
|
||||
// Never closes: this is the OpenRouter stall, in miniature.
|
||||
},
|
||||
});
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => new Response(body, { status: 200 });
|
||||
try {
|
||||
const response = await idleWatchdogFetch(60)("https://example.test/chat/completions");
|
||||
const started = Date.now();
|
||||
await expect(response.text()).rejects.toThrow(/stopped sending data/i);
|
||||
// Fast, not after a total timeout: the silence window, not the call budget.
|
||||
expect(Date.now() - started).toBeLessThan(2_000);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves a body-less response alone", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => new Response(null, { status: 204 });
|
||||
try {
|
||||
const response = await idleWatchdogFetch(50)("https://example.test/chat/completions");
|
||||
expect(response.status).toBe(204);
|
||||
expect(response.body).toBeNull();
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
58
tests/int/ai-structured-stream.int.spec.ts
Normal file
58
tests/int/ai-structured-stream.int.spec.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
// @vitest-environment node
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* Regression: `streamObject`'s stream is lazy, so `result.object` never resolves
|
||||
* unless something drains the stream first. Awaiting only the object promise is
|
||||
* what made every NPC draft hang on "Drafting..." against OpenRouter, with the
|
||||
* provider having delivered a complete answer.
|
||||
*
|
||||
* The stub below models that laziness: `object` resolves only after the text
|
||||
* stream has been read.
|
||||
*/
|
||||
vi.mock("ai", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("ai")>();
|
||||
return {
|
||||
...actual,
|
||||
streamObject: () => {
|
||||
let drained = false;
|
||||
return {
|
||||
textStream: (async function* () {
|
||||
drained = true;
|
||||
yield '{"nodes":[{"id":"n1"}]}';
|
||||
})(),
|
||||
object: new Promise((resolve) => {
|
||||
const timer = setInterval(() => {
|
||||
if (!drained) return;
|
||||
clearInterval(timer);
|
||||
resolve({ nodes: [{ id: "n1" }] });
|
||||
}, 5);
|
||||
}),
|
||||
finishReason: Promise.resolve("stop"),
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { generateStructured } = await import("@/lib/ai/generate");
|
||||
|
||||
describe("structured generation drives the stream", () => {
|
||||
it("resolves the object instead of waiting on a lazy stream", async () => {
|
||||
const result = await generateStructured<{ nodes: { id: string }[] }>({
|
||||
prompt: "Draft something.",
|
||||
system: "Stub.",
|
||||
schema: { type: "object", properties: {}, additionalProperties: false },
|
||||
connection: {
|
||||
label: "stub",
|
||||
baseUrl: "https://example.test/v1",
|
||||
modelId: "stub-model",
|
||||
apiKey: "unused",
|
||||
structuredMode: "json_schema",
|
||||
sendReasoningOff: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.object.nodes).toHaveLength(1);
|
||||
expect(result.truncated).toBe(false);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue