mirror of
https://github.com/DayuanJiang/next-ai-draw-io.git
synced 2026-10-13 04:59:51 +08:00
## Problem
A review of how the app uses the Vercel AI SDK (two Claude reviewers and Codex, each finding checked against the SDK's type definitions and source) found five behaviours that are wrong and a set of places where the app re-implements what the SDK already provides:
1. Quota tokens were recorded in `onFinish`, which the SDK does not call when a later step fails; only a user stop was handled (`onAbort`), and the write was not awaited.
2. An automatic retry after a tool error re-sent the request body as it was when the message was sent, so the model was told the "authoritative" canvas XML was the diagram from before the turn, although `display_diagram` commits a drawing before its screenshot check can fail.
3. The screenshot check and the connection test ran their model call on `AbortSignal.timeout` only, so pressing Stop (or closing the dialog) did not stop a paid model call.
4. The client ignored `finishReason`; a reasoning model that spent the whole output budget before calling a tool left the user with no diagram and no message.
5. The connection test counted an `invalid` tool call (a tool that does not exist, unreadable input) as proof of tool support.
## Change
- `onStepFinish` records each step's `usage.totalTokens` and awaits the write; the copies in `onFinish` and `onAbort` are gone.
- `DefaultChatTransport.prepareSendMessagesRequest` sends the current canvas page XML on every request after the first of a turn; the first keeps the exported (or snapshot) XML.
- `validate-diagram` and the connection test pass `req.signal` and use the SDK's `timeout` option; `validate-diagram` reports to Langfuse under `functionId: "validate-diagram"`.
- The connection test only counts a valid tool call.
- The client's `onFinish` shows a notice (with Retry) when `finishReason === "length"` and no tool was called.
- The server validates incoming messages with `safeValidateUIMessages` (400 otherwise), drops client system messages explicitly and prunes empty model messages with `pruneMessages`.
- The chat's tools live in `lib/chat-tools.ts` with an `outputSchema` for the client-side ones; `lib/chat-message.ts` defines `ChatUIMessage` (metadata, a `data-notice` part, `InferUITools`) so `useChat`, `addToolOutput` and the tool handlers are typed.
- Error notices are assistant messages with a `data-notice` part instead of role `system` UI messages.
- Regenerate, edit and retry use `sendMessage({ messageId })`; `isResending` and `flushSync` are gone.
- `isToolUIPart` / `getToolName` replace slicing `"tool-"` off part types; `ToolPartLike` derives from the SDK's part types.
Net: 578 insertions, 439 deletions over 16 files.
## Testing
- New unit tests: a step that fails after a finished step still counts that step's tokens; the screenshot check's model call ends when the request is aborted; an invalid tool call in the connection test gives the warning; malformed messages get a 400. The first and third confirm SDK behaviour the review relied on.
- `tsc`, `biome ci` (0 errors), root `vitest run` 723 passed on the branch rebased onto #986, `next build`: clean
- Playwright, 10 chat-related specs on the dev server: 199 passed, 0 failed, both before and after the rebase onto #986
245 lines
8.5 KiB
TypeScript
245 lines
8.5 KiB
TypeScript
import { streamText, tool } from "ai"
|
|
import { NextResponse } from "next/server"
|
|
import { z } from "zod"
|
|
import {
|
|
edgeOneEndpoint,
|
|
getAIModel,
|
|
usesServerCredentials,
|
|
usesServerEndpoint,
|
|
} from "@/lib/ai-providers"
|
|
import {
|
|
checkAndIncrementRequest,
|
|
isQuotaEnabled,
|
|
} from "@/lib/dynamo-quota-manager"
|
|
import { classifyLLMError } from "@/lib/llm-errors"
|
|
import { allowPrivateUrls, isPrivateUrl } from "@/lib/ssrf-protection"
|
|
import { normalizeBaseUrl, type ProviderName } from "@/lib/types/model-config"
|
|
import { getUserIdFromRequest } from "@/lib/user-id"
|
|
|
|
export interface TestModelRequest {
|
|
provider: ProviderName
|
|
apiKey?: string
|
|
baseUrl?: string
|
|
modelId: string
|
|
// AWS Bedrock specific
|
|
awsAccessKeyId?: string
|
|
awsSecretAccessKey?: string
|
|
awsRegion?: string
|
|
awsSessionToken?: string
|
|
// Vertex AI specific
|
|
vertexApiKey?: string // Express Mode API key
|
|
}
|
|
|
|
const TEST_TIMEOUT_MS = 15_000
|
|
|
|
// Drawing works through tool calls, so the test asks for one
|
|
const PING_TOOL = tool({
|
|
description: "Report that the connection works.",
|
|
inputSchema: z.object({}),
|
|
})
|
|
|
|
const NO_TOOL_CALL_WARNING =
|
|
"Connected, but the model answered without calling a tool. It may not support tool calls, which drawing needs."
|
|
|
|
/**
|
|
* Run one tool call on a model, as the chat would, and report the result.
|
|
* Shared by the Settings dialog's Test (/api/validate-model) and the admin
|
|
* panel's Test (/api/admin/test-model). req supplies the EdgeOne endpoint,
|
|
* cookies, access code and the user id for the quota. trustedBaseUrl marks
|
|
* body.baseUrl as the server's own <P>_BASE_URL (the admin panel's Test of
|
|
* an entry without a URL), not one a user typed: chat uses it as it is, so
|
|
* no private-address or redirect rules, and no quota.
|
|
*/
|
|
export async function testModelConnection(
|
|
req: Request,
|
|
body: TestModelRequest,
|
|
trustedBaseUrl: boolean,
|
|
): Promise<NextResponse> {
|
|
try {
|
|
const {
|
|
provider,
|
|
apiKey,
|
|
modelId,
|
|
awsAccessKeyId,
|
|
awsSecretAccessKey,
|
|
awsRegion,
|
|
awsSessionToken,
|
|
// Note: Express Mode only needs vertexApiKey
|
|
vertexApiKey,
|
|
} = body
|
|
|
|
if (!provider || !modelId) {
|
|
return NextResponse.json(
|
|
{ valid: false, error: "Provider and model ID are required" },
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
// EdgeOne is this site's own function, as in the chat; the admin
|
|
// panel's Test sends no URL, and a relative one cannot be fetched
|
|
const baseUrl =
|
|
provider === "edgeone" ? edgeOneEndpoint(req) : body.baseUrl
|
|
|
|
// SECURITY: Block SSRF attacks via custom baseUrl
|
|
if (
|
|
baseUrl &&
|
|
!trustedBaseUrl &&
|
|
!allowPrivateUrls() &&
|
|
(await isPrivateUrl(baseUrl))
|
|
) {
|
|
return NextResponse.json(
|
|
{ valid: false, error: "Invalid base URL" },
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
|
|
// Validate credentials based on provider
|
|
if (provider === "bedrock") {
|
|
if (
|
|
!(apiKey || (awsAccessKeyId && awsSecretAccessKey)) ||
|
|
!awsRegion
|
|
) {
|
|
return NextResponse.json(
|
|
{
|
|
valid: false,
|
|
error: "AWS credentials (a Bedrock API key, or an Access Key ID and Secret Access Key, and a Region) are required",
|
|
},
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
} else if (provider === "vertexai") {
|
|
if (!vertexApiKey) {
|
|
return NextResponse.json(
|
|
{
|
|
valid: false,
|
|
error: "Vertex AI API key is required for Express Mode",
|
|
},
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
} else if (provider !== "ollama" && provider !== "edgeone" && !apiKey) {
|
|
return NextResponse.json(
|
|
{ valid: false, error: "API key is required" },
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
// The Test button checks the user's own provider. On the server's
|
|
// keys (Ollama Cloud without a key or URL) anyone could run any model.
|
|
if (
|
|
usesServerCredentials(provider, {
|
|
apiKey,
|
|
baseUrl,
|
|
awsAccessKeyId,
|
|
awsSecretAccessKey,
|
|
vertexApiKey,
|
|
})
|
|
) {
|
|
return NextResponse.json(
|
|
{ valid: false, error: "API key is required" },
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
|
|
// On the deployment's own endpoints a Test runs a model as a chat
|
|
// does, so with the quota on it counts as a chat request (an
|
|
// admin's Test of the server's URL does not)
|
|
const userId = getUserIdFromRequest(req)
|
|
if (
|
|
isQuotaEnabled() &&
|
|
!trustedBaseUrl &&
|
|
userId !== "anonymous" &&
|
|
(await usesServerEndpoint(
|
|
provider,
|
|
normalizeBaseUrl(body.baseUrl ?? ""),
|
|
apiKey,
|
|
))
|
|
) {
|
|
const quotaCheck = await checkAndIncrementRequest(userId, {
|
|
requests: Number(process.env.DAILY_REQUEST_LIMIT) || 10,
|
|
tokens: Number(process.env.DAILY_TOKEN_LIMIT) || 200000,
|
|
tpm: Number(process.env.TPM_LIMIT) || 20000,
|
|
})
|
|
if (!quotaCheck.allowed) {
|
|
return NextResponse.json(
|
|
{ valid: false, error: quotaCheck.error },
|
|
{ status: 429 },
|
|
)
|
|
}
|
|
}
|
|
|
|
// The same model the chat would use. A client base URL makes it
|
|
// refuse redirects to internal hosts.
|
|
const { model } = getAIModel({
|
|
provider,
|
|
modelId,
|
|
apiKey,
|
|
baseUrl,
|
|
trustedBaseUrl,
|
|
awsAccessKeyId,
|
|
awsSecretAccessKey,
|
|
awsRegion,
|
|
// Temporary AWS credentials need it, as in the chat
|
|
awsSessionToken,
|
|
vertexApiKey,
|
|
// EdgeOne checks the Pages cookies and the access code
|
|
...(provider === "edgeone" && {
|
|
headers: {
|
|
cookie: req.headers.get("cookie") || "",
|
|
"x-access-code": req.headers.get("x-access-code") || "",
|
|
},
|
|
}),
|
|
})
|
|
|
|
// Streaming, like the chat (some models only stream). Stop at the
|
|
// first tool call; a reasoning model that runs out of tokens first
|
|
// proves the connection but not tool support.
|
|
const startTime = Date.now()
|
|
const result = streamText({
|
|
model,
|
|
prompt: "Call the ping tool.",
|
|
tools: { ping: PING_TOOL },
|
|
maxOutputTokens: 1024,
|
|
maxRetries: 0,
|
|
// Ends with the request: the user closed the dialog or the page
|
|
abortSignal: req.signal,
|
|
timeout: TEST_TIMEOUT_MS,
|
|
})
|
|
let calledTool = false
|
|
let finishReason: string | undefined
|
|
for await (const part of result.fullStream) {
|
|
if (part.type === "error") throw part.error
|
|
// The timeout (or the request's end) ends the stream with an
|
|
// abort part, not an error
|
|
if (part.type === "abort") {
|
|
const timeout = new Error(
|
|
`The model did not answer within ${TEST_TIMEOUT_MS / 1000} s.`,
|
|
)
|
|
timeout.name = "TimeoutError"
|
|
throw timeout
|
|
}
|
|
// A call of a tool that does not exist, or with unreadable
|
|
// input, arrives marked invalid: no proof of tool support
|
|
if (part.type === "tool-call" && !part.invalid) {
|
|
calledTool = true
|
|
break
|
|
}
|
|
if (part.type === "finish") finishReason = part.finishReason
|
|
}
|
|
const responseTime = Date.now() - startTime
|
|
|
|
return NextResponse.json({
|
|
valid: true,
|
|
responseTime,
|
|
...(!calledTool &&
|
|
finishReason !== "length" && { warning: NO_TOOL_CALL_WARNING }),
|
|
})
|
|
} catch (error) {
|
|
console.error("[validate-model] Error:", error)
|
|
|
|
const { code, message } = classifyLLMError(error)
|
|
return NextResponse.json(
|
|
{ valid: false, code, error: message },
|
|
{ status: 200 }, // Return 200 so client can read error message
|
|
)
|
|
}
|
|
}
|