import {z} from 'zod' export type TunerSpaceInputBlock = {[key: string]: unknown}; export type TunerSpaceDSPBlock = {[key: string]: unknown}; export type TunerSpaceLearnBlock = {[key: string]: unknown}; export type TunerSpaceImpulse = {parameters?: Record | undefined, inputBlocks: Array, dspBlocks: Array, learnBlocks: Array>}; export type OptimizeConfig = {name?: string | undefined, targetLatency: number, targetDevice: {name: string, ram?: number | undefined, rom?: number | undefined}, compiler?: Array | undefined, precision?: Array | undefined, trainingCycles?: number | undefined, tuningMaxTrials?: number | undefined, tuningWorkers?: number | undefined, initialTrials?: number | undefined, optimizationRounds?: number | undefined, trialsPerOptimizationRound?: number | undefined, minMACCS?: number | undefined, maxMACCS?: number | undefined, tuningAlgorithm?: ('random' | 'hyperband' | 'bayesian' | 'custom') | undefined, notificationOnCompletion?: boolean | undefined, importProjectMetrics?: boolean | undefined, importResourceMetrics?: boolean | undefined, numImportProjectMetrics?: number | undefined, numImportResourceMetrics?: number | undefined, enableSEM?: boolean | undefined, accuracySEM?: number | undefined, latencySEM?: number | undefined, optimizationObjectives?: Array<{objective: string, label: string, weight: number}> | undefined, rawObjectives?: string | undefined, optimizationPrecision?: ('float32' | 'int8') | undefined, earlyStopping?: boolean | undefined, earlyStoppingWindowSize?: number | undefined, earlyStoppingImprovementBar?: number | undefined, MOMF?: boolean | undefined, verboseLogging?: boolean | undefined, disableConstraints?: boolean | undefined, disableDeduplicate?: boolean | undefined, maxTotalTrainingTime?: number | undefined, tunerChildJobMemoryMiB?: number | undefined, tunerSpaceOptions?: {[key: string]: Array} | undefined, space?: Array | undefined, searchSpaceTemplate?: ({identifier: 'speech_keyword' | 'speech_continuous' | 'audio_event' | 'audio_continuous' | 'visual' | 'motion_event' | 'motion_continuous' | 'audio_syntiant' | 'object_detection_bounding_boxes' | 'object_detection_centroids' | 'visual_ad' | 'object_detection_yolo_pro', classification?: boolean | undefined, anomaly?: boolean | undefined, regression?: boolean | undefined}) | undefined, searchSpaceSource?: ({type: 'template' | 'run' | 'impulse' | 'custom', templateTitle?: string | undefined, runTitle?: string | undefined, impulseTitle?: string | undefined}) | undefined}; export type CreateApiApiProjectIdOptimizeConfigArgs = {projectId: number, body: OptimizeConfig}; export type CreateApiApiProjectIdOptimizeConfigOptions = {baseUrl?: string | undefined, ApiKeyAuthentication?: string | undefined, fetch?: typeof fetch | undefined}; export const genericApiResponse = z.object({success: z.boolean(), error: z.string().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 }; /** * Update config * * POST /api/{projectId}/optimize/config * * Also accepts auth: JWTAuthentication, JWTHttpHeaderAuthentication, OAuth2 */ export const createApiApiProjectIdOptimizeConfig = async (args: CreateApiApiProjectIdOptimizeConfigArgs, options?: CreateApiApiProjectIdOptimizeConfigOptions) => { const {baseUrl = "https://studio.edgeimpulse.com/v1", fetch: fetchFn = fetch, ApiKeyAuthentication} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKeyAuthentication !== undefined) headers.set("x-api-key", ApiKeyAuthentication) const url = `${baseUrl.replace(/\/+$/, '')}/api/${encodeURIComponent(String(args.projectId))}/optimize/config${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(genericApiResponse, await res.json()) };