Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(batches): add wizard types + Zod schemas (F1)

diegosouzapw0156e03780e7
diff --git a/src/lib/batches/schemas.ts b/src/lib/batches/schemas.ts
new file mode 100644
index 0000000000..c0cad460f7
--- /dev/null
+++ b/src/lib/batches/schemas.ts
@@ -0,0 +1,38 @@
+import { z } from "zod";
+import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
+import { BATCH_SUPPORTED_PROVIDERS } from "./types";
+
+export const wizardDestinationSchema = z.object({
+ provider: z.enum(BATCH_SUPPORTED_PROVIDERS),
+ endpoint: z.enum(SUPPORTED_BATCH_ENDPOINTS),
+ model: z.string().min(1).max(128),
+});
+
+export const wizardCsvMappingSchema = z
+ .record(z.string().max(256), z.string().max(256))
+ .refine((m) => Object.values(m).includes("custom_id"), {
+ message: "CSV mapping must include a column → custom_id",
+ })
+ .refine(
+ (m) =>
+ Object.values(m).some((v) =>
+ v.startsWith("body.messages[") || v === "body.input" || v === "body.prompt"
+ ),
+ { message: "CSV mapping must produce request body content" }
+ );
+
+// Used only for client-side parsing — backend keeps using v1BatchCreateSchema.
+// Zod 4 note: `.required()` was removed from `defaults`; in Zod 4 it strips
+// `.default()` making the field required with no fallback — breaking `method`.
+// All non-optional fields are already required by z.object without `.required()`.
+export const csvToJsonlInputSchema = z.object({
+ csv: z.string().min(1),
+ mapping: wizardCsvMappingSchema,
+ defaults: z.object({
+ model: z.string().min(1),
+ method: z.literal("POST").default("POST"),
+ url: z.enum(SUPPORTED_BATCH_ENDPOINTS),
+ }),
+});
+
+export type CsvToJsonlInput = z.infer<typeof csvToJsonlInputSchema>;
diff --git a/src/lib/batches/types.ts b/src/lib/batches/types.ts
new file mode 100644
index 0000000000..f493352b95
--- /dev/null
+++ b/src/lib/batches/types.ts
@@ -0,0 +1,88 @@
+import { SUPPORTED_BATCH_ENDPOINTS, type SupportedBatchEndpoint }
+ from "@/shared/constants/batchEndpoints";
+
+// ── Wizard state ─────────────────────────────────────────────────────────────
+
+export type WizardStep = "destination" | "input" | "validate" | "cost";
+
+export interface WizardDestination {
+ provider: "openai" | "anthropic" | "gemini";
+ endpoint: SupportedBatchEndpoint;
+ model: string;
+}
+
+export type WizardInputKind = "jsonl" | "csv";
+
+export interface WizardCsvMapping {
+ // CSV header name → JSONL field path.
+ // Supported paths: "custom_id", "body.messages[0].content",
+ // "body.messages[0].role", "body.max_tokens",
+ // "body.temperature", "body.model" (defaults to wizard.model).
+ [csvColumn: string]: string;
+}
+
+export interface WizardInput {
+ kind: WizardInputKind;
+ fileName: string | null;
+ rawContent: string | null; // utf-8 text (read via FileReader)
+ csvMapping?: WizardCsvMapping; // only when kind === "csv"
+}
+
+// ── Validation result ────────────────────────────────────────────────────────
+
+export interface JsonlLineError {
+ lineNumber: number; // 1-based
+ reason: string; // user-facing, short
+ field?: string; // optional path of offending field
+}
+
+export interface ValidationResult {
+ ok: boolean;
+ totalLines: number;
+ sampledLines: number; // how many lines actually inspected
+ uniqueCustomIds: number;
+ duplicateCustomIds: string[]; // up to first 10
+ errors: JsonlLineError[]; // up to first 50
+ preview: unknown[]; // first 5 parsed request bodies
+ byteSize: number;
+}
+
+// ── Cost estimate ────────────────────────────────────────────────────────────
+
+export interface CostEstimate {
+ model: string;
+ totalRequests: number;
+ estimatedInputTokens: number;
+ estimatedOutputTokens: number;
+ syncCostUsd: number; // baseline
+ batchCostUsd: number; // syncCost * 0.5
+ savingsUsd: number; // syncCost - batchCost
+ pricingSource: "exact-match" | "alias-match" | "fallback";
+ warnings: string[]; // e.g. "model not in pricing table"
+}
+
+// ── Retry plan ───────────────────────────────────────────────────────────────
+
+export interface RetryPlan {
+ failedCustomIds: string[]; // from error_file_id
+ retriableLines: number;
+ skippedLines: number;
+ newJsonl: string; // ready to upload
+}
+
+// ── Provider catalog (D16 / D17) ─────────────────────────────────────────────
+
+export const BATCH_SUPPORTED_PROVIDERS = ["openai", "anthropic", "gemini"] as const;
+export type BatchProvider = (typeof BATCH_SUPPORTED_PROVIDERS)[number];
+
+export interface BatchProviderConfig {
+ provider: BatchProvider;
+ defaultEndpoint: SupportedBatchEndpoint;
+ defaultModels: string[]; // canonical model ids
+}
+
+// ── Re-exports ───────────────────────────────────────────────────────────────
+
+export type { SupportedBatchEndpoint };
+export { SUPPORTED_BATCH_ENDPOINTS };
+
diff --git a/tests/unit/lib/batches/schemas.test.ts b/tests/unit/lib/batches/schemas.test.ts
new file mode 100644
index 0000000000..0c3fa7f9fc
--- /dev/null
+++ b/tests/unit/lib/batches/schemas.test.ts
@@ -0,0 +1,118 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+
+const { wizardDestinationSchema, wizardCsvMappingSchema, csvToJsonlInputSchema } =
+ await import("../../../../src/lib/batches/schemas.ts");
+
+// ── wizardDestinationSchema ──────────────────────────────────────────────────
+
+test("wizardDestinationSchema: accepts valid destination (openai / /v1/chat/completions / gpt-4o)", () => {
+ const result = wizardDestinationSchema.safeParse({
+ provider: "openai",
+ endpoint: "/v1/chat/completions",
+ model: "gpt-4o",
+ });
+ assert.ok(result.success, "valid destination should parse successfully");
+});
+
+test("wizardDestinationSchema: rejects invalid provider (mistral)", () => {
+ const result = wizardDestinationSchema.safeParse({
+ provider: "mistral",
+ endpoint: "/v1/chat/completions",
+ model: "mistral-7b",
+ });
+ assert.equal(result.success, false, "unknown provider should fail validation");
+});
+
+test("wizardDestinationSchema: rejects unsupported endpoint", () => {
+ const result = wizardDestinationSchema.safeParse({
+ provider: "openai",
+ endpoint: "/v1/audio/transcriptions",
+ model: "gpt-4o",
+ });
+ assert.equal(result.success, false, "unsupported endpoint should fail validation");
+});
+
+test("wizardDestinationSchema: rejects empty model string", () => {
+ const result = wizardDestinationSchema.safeParse({
+ provider: "anthropic",
+ endpoint: "/v1/chat/completions",
+ model: "",
+ });
+ assert.equal(result.success, false, "empty model should fail validation");
+});
+
+// ── wizardCsvMappingSchema ───────────────────────────────────────────────────
+
+test("wizardCsvMappingSchema: accepts valid mapping with custom_id + body.messages[0].content", () => {
+ const result = wizardCsvMappingSchema.safeParse({
+ id_col: "custom_id",
+ prompt_col: "body.messages[0].content",
+ });
+ assert.ok(result.success, "valid mapping should parse successfully");
+});
+
+test("wizardCsvMappingSchema: rejects mapping without custom_id target", () => {
+ const result = wizardCsvMappingSchema.safeParse({
+ prompt_col: "body.messages[0].content",
+ });
+ assert.equal(result.success, false, "missing custom_id target should fail");
+ if (!result.success) {
+ const messages = result.error.issues.map((e) => e.message);
+ assert.ok(
+ messages.some((m) => m.includes("custom_id")),
+ "error should mention custom_id"
+ );
+ }
+});
+
+test("wizardCsvMappingSchema: rejects mapping with custom_id only (no content/input/prompt)", () => {
+ const result = wizardCsvMappingSchema.safeParse({
+ id_col: "custom_id",
+ });
+ assert.equal(result.success, false, "mapping without content path should fail");
+ if (!result.success) {
+ const messages = result.error.issues.map((e) => e.message);
+ assert.ok(
+ messages.some((m) => m.includes("request body content")),
+ "error should mention body content requirement"
+ );
+ }
+});
+
+// ── csvToJsonlInputSchema ────────────────────────────────────────────────────
+
+test("csvToJsonlInputSchema: accepts valid complete input", () => {
+ const result = csvToJsonlInputSchema.safeParse({
+ csv: "id,prompt\n1,hello",
+ mapping: {
+ id: "custom_id",
+ prompt: "body.messages[0].content",
+ },
+ defaults: {
+ model: "gpt-4o",
+ url: "/v1/chat/completions",
+ },
+ });
+ assert.ok(result.success, "valid csv input should parse successfully");
+ if (result.success) {
+ // Verify method defaults to POST
+ assert.equal(result.data.defaults.method, "POST");
+ assert.equal(result.data.defaults.model, "gpt-4o");
+ }
+});
+
+test("csvToJsonlInputSchema: rejects empty csv string", () => {
+ const result = csvToJsonlInputSchema.safeParse({
+ csv: "",
+ mapping: {
+ id: "custom_id",
+ prompt: "body.messages[0].content",
+ },
+ defaults: {
+ model: "gpt-4o",
+ url: "/v1/chat/completions",
+ },
+ });
+ assert.equal(result.success, false, "empty csv should fail min(1) constraint");
+});