import {z} from 'zod' export type CreateApiV1PlaygroundGroundArgs = {wait_seconds?: number | undefined, 'cf-turnstile-response'?: (string | null) | undefined, body: BodyInit}; export type CreateApiV1PlaygroundGroundOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const costLine = z.object({amount_usd: z.string(), execution: z.enum(["fresh", "reused"]), operation: z.enum(["parse", "split", "classify", "extract", "ground"]), quantity: z.number().int().gte(0), reuse_reason: z.enum(["reused_parse", "repeat_of_job"]).nullable().optional(), unit: z.enum(["page", "item"]), unit_price_usd: z.string()}); export const jobCost = z.object({currency: z.literal("USD").optional(), lines: z.array(costLine), pricing_version: z.string(), total_usd: z.string()}); export const errorCode = z.enum(["storage_connection_not_found", "storage_connection_in_use", "storage_limit_exceeded", "storage_conflict", "storage_auth_required", "storage_unavailable", "scan_required", "scan_rejected", "scan_unavailable", "invalid_request", "unsupported_file_type", "file_too_large", "invalid_schema", "invalid_sql", "invalid_path_prefix", "command_not_permitted", "batch_too_large", "domain_validation_failed", "default_label_required", "wait_required_for_zero_retention", "ledger_decision_invalid", "tenant_required", "partner_required", "workspace_not_found", "file_not_found", "job_not_found", "upload_not_found", "node_not_found", "schema_not_found", "domain_not_found", "session_not_found", "access_label_not_found", "ledger_understanding_not_found", "ledger_table_not_found", "tenant_not_found", "path_conflict", "schema_version_conflict", "access_label_name_taken", "workspace_name_taken", "access_label_in_use", "upload_expired", "file_not_ingested", "workspace_deleting", "workspace_not_deletable", "ingestion_in_progress", "job_not_cancellable", "confirmation_required", "domain_not_published", "domain_in_use", "reserved_domain_slug", "kg_not_built", "kg_build_in_progress", "ledger_understanding_in_progress", "ledger_understanding_version_outdated", "session_busy", "tenant_limit_reached", "range_not_satisfiable", "result_expired", "access_denied", "tenant_disabled", "access_backstop_violation", "access_mode_not_implemented", "rate_limited", "concurrency_limit_reached", "quota_exceeded", "corrupt_file", "zero_byte_file", "encrypted_file", "csv_dialect_ambiguous", "csv_parse_failed", "parse_failed", "ocr_failed", "conversion_failed", "sheetless_workbook", "unplayable_media", "unclassified_pages", "job_cancelled", "job_timeout", "upstream_unavailable", "internal_error", "unauthorized", "not_implemented"]); export const error = z.object({code: errorCode, detail: z.record(z.string(), z.unknown()).nullable().optional(), message: z.string(), request_id: z.string().nullable().optional(), retryable: z.boolean()}); export const knowledgeGraphBuildProgress = z.object({countable: z.boolean(), documents: z.number().int().nullable().optional(), mentions: z.number().int().nullable().optional(), phase_count: z.number().int(), phase_index: z.number().int(), step: z.string().nullable().optional(), step_done: z.number().int().nullable().optional(), step_total: z.number().int().nullable().optional()}); export const automaticLlmRouter = z.object({kind: z.literal("llm").optional()}); export const automaticNaceDmRouter = z.object({decision_point: z.number().gte(0).lte(1), kind: z.literal("nacedm").optional(), p_agent: z.number().gte(0).lte(1).nullable()}); export const automaticRequestedRouter = z.object({kind: z.literal("requested").optional()}); export const automaticSearchRouting = z.object({delegated_wall_ms: z.number().int().nullable().optional(), fact_wall_ms: z.number().int().nullable().optional(), final: z.enum(["fact", "agent", "deep", "filtered"]), reason: z.string(), router: z.discriminatedUnion("kind", [automaticLlmRouter, automaticNaceDmRouter, automaticRequestedRouter]).optional(), router_model: z.string(), router_wall_ms: z.number().int().nullable().optional(), selected: z.enum(["fact", "agent", "deep", "filtered"])}); export const jobProgress = z.object({items_done: z.number().int().optional(), items_failed: z.number().int().optional(), items_total: z.number().int().nullable().optional(), knowledge_graph: knowledgeGraphBuildProgress.nullable().optional(), routing: automaticSearchRouting.nullable().optional(), stage: z.string().nullable().optional(), units_done: z.number().int().optional(), units_total: z.number().int().nullable().optional()}); export const workspaceQueryScope = z.object({type: z.literal("workspace").optional()}); export const fileQueryScope = z.object({path: z.string().min(1).max(1024), type: z.literal("file").optional()}); export const pathPrefixQueryScope = z.object({prefix: z.string().min(1).max(1024), type: z.literal("path_prefix").optional()}); export const filesQueryScope = z.object({count: z.number().int().gte(2), type: z.literal("files").optional()}); export const pageRegion = z.object({kind: z.literal("page_region").optional(), page: z.number().int().gte(1), polygons: z.array(z.array(z.array(z.unknown()))).optional()}); export const sheetRange = z.object({a1_range: z.string(), kind: z.literal("sheet_range").optional(), sheet: z.string()}); export const textSpan = z.object({char_end: z.number().int().gte(0), char_start: z.number().int().gte(0), kind: z.literal("text_span").optional(), page: z.number().int().gte(1).nullable().optional()}); export const rowRange = z.object({column: z.string().nullable().optional(), end_row: z.number().int().gte(0), kind: z.literal("row_range").optional(), start_row: z.number().int().gte(0)}); export const tableRowRange = z.object({end: z.number().int().gte(0), start: z.number().int().gte(0)}); export const tableRegion = z.object({columns: z.array(z.string()).optional(), exact: z.boolean(), kind: z.literal("table_region").optional(), matched_rows: z.number().int().gte(0).optional(), row_ranges: z.array(tableRowRange).optional(), source_file_name: z.string(), sql: z.string()}); export const jsonPointer = z.object({kind: z.literal("json_pointer").optional(), pointer: z.string()}); export const textRange = z.object({char_end: z.number().int(), char_start: z.number().int(), kind: z.literal("text_range").optional(), page: z.number().int().nullable().optional(), pages: z.array(z.number().int()).optional()}); export const visualRegion = z.object({bbox: z.array(z.unknown()), kind: z.literal("visual_region").optional(), page: z.number().int()}); export const spreadsheetRange = z.object({a1_range: z.string(), kind: z.literal("spreadsheet_range").optional(), sheet: z.string()}); export const jsonlRecord = z.object({column: z.string().nullable().optional(), kind: z.literal("jsonl_record").optional(), row_offset: z.number().int()}); export const audioRange = z.object({end_ms: z.number().int(), kind: z.literal("audio_range").optional(), start_ms: z.number().int()}); export const wordAnchor = z.object({char_end: z.number().int().gt(0), char_start: z.number().int().gte(0), paragraph_index: z.number().int().gte(0), part: z.string()}); export const groundMatch = z.object({confidence: z.number().gte(0).lte(1).nullable().optional(), cropped_image_url: z.string().nullable().optional(), location: z.union([z.union([pageRegion, sheetRange, textSpan, rowRange, tableRegion, jsonPointer]), z.union([textRange, visualRegion, spreadsheetRange, jsonlRecord, jsonPointer, audioRange, rowRange])]), match_method: z.enum(["exact", "normalized", "semantic"]), matched_text: z.string(), rank: z.number().int().gte(1), word_anchor: wordAnchor.nullable().optional()}); export const groundTargetResult = z.object({error: z.string().nullable().optional(), id: z.string(), matches: z.array(groundMatch).optional(), status: z.enum(["found", "not_found", "failed"])}); export const ndiServiceAppPlatformApiResultsGroundResult = z.object({converted_pdf_url: z.string().nullable().optional(), result_type: z.literal("ground").optional(), targets: z.array(groundTargetResult), transcript_url: z.string().nullable().optional(), units: z.number().int(), warnings: z.array(z.string()).optional()}); export const resultState = z.enum(["available", "expired", "not_retained", "cancelled", "storage_unavailable"]); export const uploadSource = z.object({type: z.literal("upload").optional(), upload_id: z.string()}); export const urlSource = z.object({file_name: z.string().max(512), type: z.literal("url").optional(), url: z.string().max(2048)}); export const workspaceFileSource = z.object({file_id: z.string(), type: z.literal("workspace_file").optional(), workspace_id: z.string()}); export const parseResultSource = z.object({job_id: z.string(), type: z.literal("parse_result").optional()}); export const ndiServiceAppPlatformApiContractsJobStatus = z.enum(["queued", "running", "succeeded", "failed", "cancelled"]); export const usageWaiver = z.object({part: z.enum(["parse", "job"]), reason: z.enum(["reused_parse", "repeat_of_job"]), source_job_id: z.string().nullable().optional()}); export const usageLine = z.object({credits: z.number().int().gte(0), credits_per_unit: z.number().int().gte(0), multiplier: z.number().int().gte(1), part: z.enum(["parse", "operation", "image_ocr"]), quantity: z.number().int().gte(0), unit: z.enum(["page", "item", "unit", "image"]), waiver: usageWaiver.nullable().optional()}); export const jobUsage = z.object({lines: z.array(usageLine)}); export const groundJob = z.object({cost: jobCost.nullable().optional(), created_at: z.string(), credit_schedule_version: z.number().int().nullable().optional(), credits: z.number().int().nullable().optional(), deleted_at: z.string().nullable().optional(), effort: z.string().nullable().optional(), error: error.nullable().optional(), finished_at: z.string().nullable().optional(), force: z.boolean().nullable().optional(), idempotency_key: z.string().nullable().optional(), job_id: z.string(), kind: z.literal("ground").optional(), name: z.string().nullable().optional(), payload_expires_at: z.string().nullable().optional(), progress: jobProgress.nullable().optional(), project_id: z.string().nullable().optional(), query: z.string().nullable().optional(), query_scope: z.union([workspaceQueryScope, fileQueryScope, pathPrefixQueryScope, filesQueryScope]).nullable().optional(), replayed: z.boolean().optional(), result: ndiServiceAppPlatformApiResultsGroundResult.nullable().optional(), result_error: error.nullable().optional(), result_state: resultState.optional(), source: z.union([uploadSource, urlSource, workspaceFileSource, parseResultSource]).nullable().optional(), started_at: z.string().nullable().optional(), status: ndiServiceAppPlatformApiContractsJobStatus, surface: z.enum(["deep_search", "qa", "workbook"]).nullable().optional(), units: z.number().int().optional(), usage: jobUsage.nullable().optional(), usage_final: z.boolean().optional(), usage_finalized_at: z.string().nullable().optional(), workspace_id: z.string().nullable().optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * playground_ground * * POST /v1/playground/ground */ export const createApiV1PlaygroundGround = async (args: CreateApiV1PlaygroundGroundArgs, options?: CreateApiV1PlaygroundGroundOptions) => { const {baseUrl = "https://ndi-api.nace.ai", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.wait_seconds != null) query.append("wait_seconds", String(args.wait_seconds)) if (args['cf-turnstile-response'] != null) headers.set("cf-turnstile-response", String(args['cf-turnstile-response'])) const url = `${baseUrl.replace(/\/+$/, '')}/v1/playground/ground${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: args.body}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(groundJob, await res.json()) };