Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

kling.ts

654 lines19.0 KB

1/**
2 * Kling AI — no public OpenAPI (the hinted docs URL is HTML; /openapi.json
3 * 404s on api.klingai.com and api-singapore.klingai.com). Spec is hand-written
4 * from official docs for the three generation POSTs.
5 *
6 * Auth: a modern console key is `Authorization: Bearer $KLING_API_KEY`.
7 * Legacy access-key + secret JWTs are not minted here. Kling publishes no
8 * /models list — listModels skips without the key and otherwise returns a
9 * small docs-derived catalog (calling the create URL would enqueue a job).
10 */
11import type { Activity } from '#/db/schema.ts'
12import { contentHash } from '#/server/kv.ts'
13import { klingModelPricing } from '../kling-pricing.ts'
14import { normalizeMediaModalities } from '../media-modalities.ts'
15import { skippedResult } from '../types.ts'
16import type {
17 ListModelsResult,
18 ModelInfo,
19 OpenApiDocument,
20 ProviderConfig,
21 ProviderSecrets,
22 SpecFetchResult,
23} from '../types.ts'
24​
25export const KLING_DOCS_URL = 'https://app.klingai.com/global/dev/document-api'
26export const KLING_API_BASE = 'https://api.klingai.com'
27export const KLING_SINGAPORE_API_BASE = 'https://api-singapore.klingai.com'
28export const KLING_MODELS_ENDPOINT = `${KLING_API_BASE}/v1/videos/text2video`
29​
30const GENERATION_PATHS: Record<string, Activity> = {
31 '/v1/videos/text2video': 'video',
32 '/v1/videos/image2video': 'video',
33 '/v1/images/generations': 'image',
35​
36type Schema = Record<string, unknown>
37​
38const cameraConfigSchema: Schema = {
39 type: 'object',
40 description:
41 'Fine-grained camera motion when camera_control.type is `simple`. Official docs allow only one non-zero axis per request. Each axis is in [-10, 10].',
42 properties: {
43 horizontal: { type: 'number', minimum: -10, maximum: 10 },
44 vertical: { type: 'number', minimum: -10, maximum: 10 },
45 pan: { type: 'number', minimum: -10, maximum: 10 },
46 tilt: { type: 'number', minimum: -10, maximum: 10 },
47 roll: { type: 'number', minimum: -10, maximum: 10 },
48 zoom: { type: 'number', minimum: -10, maximum: 10 },
49 },
51​
52const cameraControlSchema: Schema = {
53 type: 'object',
54 description:
55 'Camera movement. Presets: simple, down_back, forward_up, right_turn_forward, left_turn_forward. Supported on older models (kling-v1 / v1.5 / v1.6), not v2.x.',
56 properties: {
57 type: {
58 type: 'string',
59 enum: [
60 'simple',
61 'down_back',
62 'forward_up',
63 'right_turn_forward',
64 'left_turn_forward',
65 ],
66 },
67 config: { $ref: '#/components/schemas/CameraConfig' },
68 },
70​
71const voiceRefSchema: Schema = {
72 type: 'object',
73 required: ['voice_id'],
74 properties: {
75 voice_id: {
76 type: 'string',
77 description: 'Voice id referenced from the prompt as <<<voice_1>>> …',
78 },
79 },
81​
82const dynamicMaskSchema: Schema = {
83 type: 'object',
84 required: ['mask', 'trajectories'],
85 properties: {
86 mask: {
87 type: 'string',
88 description: 'Brush mask as a raw base64 image or https URL.',
89 },
90 trajectories: {
91 type: 'array',
92 description: 'Motion path; 2–77 {x,y} points for a 5s clip.',
93 minItems: 2,
94 items: {
95 type: 'object',
96 required: ['x', 'y'],
97 properties: {
98 x: { type: 'number' },
99 y: { type: 'number' },
100 },
101 },
102 },
103 },
105​
106const text2VideoRequest: Schema = {
107 type: 'object',
108 required: ['prompt'],
109 properties: {
110 model_name: {
111 type: 'string',
112 description:
113 'Video model id. Documented values include kling-v1, kling-v1-6, kling-v2-master, kling-v2-1-master, kling-v2-5-turbo, kling-v2-6, kling-v3. Default kling-v1.',
114 },
115 prompt: {
116 type: 'string',
117 maxLength: 2500,
118 description: 'Positive scene prompt.',
119 },
120 negative_prompt: { type: 'string', maxLength: 2500 },
121 sound: {
122 type: 'string',
123 enum: ['on', 'off'],
124 description:
125 'Native audio. v2.6+ (typically requires mode=pro). Default off.',
126 },
127 cfg_scale: {
128 type: 'number',
129 minimum: 0,
130 maximum: 1,
131 description: 'Prompt adherence. Default 0.5. Not supported on v2.x.',
132 },
133 mode: {
134 type: 'string',
135 enum: ['std', 'pro'],
136 description: 'Quality tier. Default std.',
137 },
138 aspect_ratio: {
139 type: 'string',
140 enum: ['16:9', '9:16', '1:1'],
141 description: 'Default 16:9.',
142 },
143 duration: {
144 type: 'string',
145 description:
146 'Clip length in seconds, sent as a string. Classic models: 5 or 10. Newer 3.0 models accept 3–15.',
147 },
148 camera_control: { $ref: '#/components/schemas/CameraControl' },
149 multi_shot: {
150 type: 'boolean',
151 description: 'Split the clip into storyboard shots (v3.0+).',
152 },
153 shot_type: {
154 type: 'string',
155 enum: ['customize', 'intelligence'],
156 description: 'Required when multi_shot is true.',
157 },
158 multi_prompt: {
159 type: 'array',
160 description:
161 'Per-shot prompts when shot_type=customize. Durations must sum to duration.',
162 items: { $ref: '#/components/schemas/MultiPromptShot' },
163 },
164 callback_url: {
165 type: 'string',
166 format: 'uri',
167 description: 'Webhook for task status changes.',
168 },
169 external_task_id: {
170 type: 'string',
171 description: 'Caller-chosen id; must be unique per account.',
172 },
173 },
175​
176const multiPromptShot: Schema = {
177 type: 'object',
178 required: ['index', 'prompt', 'duration'],
179 properties: {
180 index: { type: 'integer', minimum: 1 },
181 prompt: { type: 'string', maxLength: 512 },
182 duration: { type: 'string', description: 'Shot length in seconds.' },
183 },
185​
186const image2VideoRequest: Schema = {
187 type: 'object',
188 description:
189 'At least one of `image` or `image_tail` is required. image + image_tail, motion brushes, and camera_control are mutually exclusive families.',
190 properties: {
191 model_name: {
192 type: 'string',
193 description:
194 'Video model id. Documented values include kling-v1, kling-v1-5, kling-v1-6, kling-v2-master, kling-v2-1, kling-v2-1-master, kling-v2-5-turbo, kling-v2-6, kling-v3.',
195 },
196 image: {
197 type: 'string',
198 description:
199 'Start frame: https URL or raw base64 (no data: URI prefix). jpg/png, ≤10MB, ≥300px, aspect 1:2.5–2.5:1.',
200 },
201 image_tail: {
202 type: 'string',
203 description: 'End frame (same encoding). Usually requires mode=pro.',
204 },
205 prompt: { type: 'string', maxLength: 2500 },
206 negative_prompt: { type: 'string', maxLength: 2500 },
207 voice_list: {
208 type: 'array',
209 maxItems: 2,
210 description:
211 'Voice references (v2.6+). Reference via <<<voice_1>>> in prompt.',
212 items: { $ref: '#/components/schemas/VoiceRef' },
213 },
214 sound: { type: 'string', enum: ['on', 'off'] },
215 cfg_scale: { type: 'number', minimum: 0, maximum: 1 },
216 mode: { type: 'string', enum: ['std', 'pro'] },
217 static_mask: {
218 type: 'string',
219 description: 'Static brush mask (base64 or URL).',
220 },
221 dynamic_masks: {
222 type: 'array',
223 maxItems: 6,
224 items: { $ref: '#/components/schemas/DynamicMask' },
225 },
226 camera_control: { $ref: '#/components/schemas/CameraControl' },
227 aspect_ratio: { type: 'string', enum: ['16:9', '9:16', '1:1'] },
228 duration: {
229 type: 'string',
230 description: 'Clip length in seconds as a string (5 or 10; 3–15 on 3.0).',
231 },
232 callback_url: { type: 'string', format: 'uri' },
233 external_task_id: { type: 'string' },
234 },
236​
237const imageGenerationsRequest: Schema = {
238 type: 'object',
239 required: ['prompt'],
240 properties: {
241 model_name: {
242 type: 'string',
243 description:
244 'Image model id. Documented values include kling-v1, kling-v1-5, kling-v2, kling-v2-new, kling-v2-1, kling-image-o1. Default kling-v1.',
245 },
246 prompt: { type: 'string', maxLength: 2500 },
247 negative_prompt: {
248 type: 'string',
249 maxLength: 2500,
250 description: 'Not supported in image-to-image mode.',
251 },
252 image: {
253 type: 'string',
254 description: 'Reference image (raw base64 or https URL).',
255 },
256 image_reference: {
257 type: 'string',
258 enum: ['subject', 'face'],
259 description: 'Required on kling-v1-5 when `image` is set.',
260 },
261 image_fidelity: { type: 'number', minimum: 0, maximum: 1 },
262 human_fidelity: {
263 type: 'number',
264 minimum: 0,
265 maximum: 1,
266 description:
267 'Face similarity when image_reference=subject. Default 0.45.',
268 },
269 resolution: { type: 'string', enum: ['1k', '2k'] },
270 n: {
271 type: 'integer',
272 minimum: 1,
273 maximum: 9,
274 description: 'Number of images. Each occupies one concurrency slot.',
275 },
276 aspect_ratio: {
277 type: 'string',
278 enum: ['16:9', '9:16', '1:1', '4:3', '3:4', '3:2', '2:3', '21:9'],
279 },
280 callback_url: { type: 'string', format: 'uri' },
281 external_task_id: { type: 'string' },
282 },
284​
285const createTaskResponse: Schema = {
286 type: 'object',
287 description:
288 'Create-task ack. Poll GET {path}/{task_id} until task_status is succeed or failed; results live under data.task_result.',
289 properties: {
290 code: {
291 type: 'integer',
292 description: '0 on success. Non-zero is an API error even on HTTP 200.',
293 },
294 message: { type: 'string' },
295 request_id: { type: 'string' },
296 data: { $ref: '#/components/schemas/CreateTaskData' },
297 },
299​
300const createTaskData: Schema = {
301 type: 'object',
302 properties: {
303 task_id: { type: 'string' },
304 task_status: {
305 type: 'string',
306 enum: ['submitted', 'processing', 'succeed', 'failed'],
307 },
308 task_info: {
309 type: 'object',
310 properties: { external_task_id: { type: 'string' } },
311 },
312 created_at: { type: 'integer', description: 'Unix timestamp in ms.' },
313 updated_at: { type: 'integer', description: 'Unix timestamp in ms.' },
314 },
316​
317const queryTaskResponse: Schema = {
318 type: 'object',
319 properties: {
320 code: { type: 'integer' },
321 message: { type: 'string' },
322 request_id: { type: 'string' },
323 data: { $ref: '#/components/schemas/QueryTaskData' },
324 },
326​
327const queryTaskData: Schema = {
328 type: 'object',
329 properties: {
330 task_id: { type: 'string' },
331 task_status: {
332 type: 'string',
333 enum: ['submitted', 'processing', 'succeed', 'failed'],
334 },
335 task_status_msg: { type: 'string' },
336 task_info: {
337 type: 'object',
338 properties: { external_task_id: { type: 'string' } },
339 },
340 created_at: { type: 'integer' },
341 updated_at: { type: 'integer' },
342 task_result: { $ref: '#/components/schemas/TaskResult' },
343 },
345​
346const taskResult: Schema = {
347 type: 'object',
348 properties: {
349 videos: {
350 type: 'array',
351 items: {
352 type: 'object',
353 properties: {
354 id: { type: 'string' },
355 url: { type: 'string', format: 'uri' },
356 duration: { type: 'string' },
357 },
358 },
359 },
360 images: {
361 type: 'array',
362 items: {
363 type: 'object',
364 properties: {
365 index: { type: 'integer' },
366 url: { type: 'string', format: 'uri' },
367 },
368 },
369 },
370 },
372​
373function jsonBody(schemaRef: string) {
374 return {
375 required: true,
376 content: {
377 'application/json': {
378 schema: { $ref: `#/components/schemas/${schemaRef}` },
379 },
380 },
381 }
383​
384function jsonResponse(description: string, schemaRef: string) {
385 return {
386 description,
387 content: {
388 'application/json': {
389 schema: { $ref: `#/components/schemas/${schemaRef}` },
390 },
391 },
392 }
394​
395function klingSpec(): OpenApiDocument {
396 return {
397 openapi: '3.1.0',
398 info: {
399 title: 'Kling AI API',
400 version: 'docs-derived',
401 description:
402 'Hand-written from official Kling docs (https://app.klingai.com/global/dev/document-api). No published OpenAPI. Current host is api-singapore.klingai.com; api.klingai.com still appears in older docs. Auth is Bearer — a console API key, or a 30-minute HS256 JWT (iss=access key) for the legacy key pair. Create POSTs return a task ack; poll the sibling GET until succeed/failed.',
403 },
404 servers: [
405 { url: KLING_SINGAPORE_API_BASE, description: 'Current official host' },
406 { url: KLING_API_BASE, description: 'Legacy host from older docs' },
407 ],
408 security: [{ bearerAuth: [] }],
409 paths: {
410 '/v1/videos/text2video': {
411 post: {
412 operationId: 'createText2Video',
413 summary: 'Create a text-to-video task',
414 tags: ['video'],
415 requestBody: jsonBody('Text2VideoRequest'),
416 responses: {
417 '200': jsonResponse('Task accepted', 'CreateTaskResponse'),
418 },
419 },
420 get: {
421 operationId: 'listText2VideoTasks',
422 summary: 'List text-to-video tasks',
423 tags: ['platform'],
424 responses: {
425 '200': jsonResponse('Task page', 'QueryTaskResponse'),
426 },
427 },
428 },
429 '/v1/videos/text2video/{task_id}': {
430 get: {
431 operationId: 'getText2VideoTask',
432 summary: 'Query a text-to-video task',
433 tags: ['platform'],
434 parameters: [
435 {
436 name: 'task_id',
437 in: 'path',
438 required: true,
439 schema: { type: 'string' },
440 },
441 ],
442 responses: {
443 '200': jsonResponse('Task status', 'QueryTaskResponse'),
444 },
445 },
446 },
447 '/v1/videos/image2video': {
448 post: {
449 operationId: 'createImage2Video',
450 summary: 'Create an image-to-video task',
451 tags: ['video'],
452 requestBody: jsonBody('Image2VideoRequest'),
453 responses: {
454 '200': jsonResponse('Task accepted', 'CreateTaskResponse'),
455 },
456 },
457 },
458 '/v1/videos/image2video/{task_id}': {
459 get: {
460 operationId: 'getImage2VideoTask',
461 summary: 'Query an image-to-video task',
462 tags: ['platform'],
463 parameters: [
464 {
465 name: 'task_id',
466 in: 'path',
467 required: true,
468 schema: { type: 'string' },
469 },
470 ],
471 responses: {
472 '200': jsonResponse('Task status', 'QueryTaskResponse'),
473 },
474 },
475 },
476 '/v1/images/generations': {
477 post: {
478 operationId: 'createImageGeneration',
479 summary: 'Create an image generation task',
480 tags: ['image'],
481 requestBody: jsonBody('ImageGenerationsRequest'),
482 responses: {
483 '200': jsonResponse('Task accepted', 'CreateTaskResponse'),
484 },
485 },
486 },
487 '/v1/images/generations/{task_id}': {
488 get: {
489 operationId: 'getImageGenerationTask',
490 summary: 'Query an image generation task',
491 tags: ['platform'],
492 parameters: [
493 {
494 name: 'task_id',
495 in: 'path',
496 required: true,
497 schema: { type: 'string' },
498 },
499 ],
500 responses: {
501 '200': jsonResponse('Task status', 'QueryTaskResponse'),
502 },
503 },
504 },
505 '/account/costs': {
506 get: {
507 operationId: 'getAccountCosts',
508 summary: 'Query resource-pack usage',
509 tags: ['platform'],
510 responses: {
511 '200': { description: 'Account resource packs' },
512 },
513 },
514 },
515 },
516 components: {
517 securitySchemes: {
518 bearerAuth: {
519 type: 'http',
520 scheme: 'bearer',
521 description:
522 'Modern console API key, or a short-lived HS256 JWT minted from the legacy access-key + secret pair (iss=access key, exp ≈ now+1800, nbf ≈ now-5).',
523 },
524 },
525 schemas: {
526 CameraConfig: cameraConfigSchema,
527 CameraControl: cameraControlSchema,
528 VoiceRef: voiceRefSchema,
529 DynamicMask: dynamicMaskSchema,
530 MultiPromptShot: multiPromptShot,
531 Text2VideoRequest: text2VideoRequest,
532 Image2VideoRequest: image2VideoRequest,
533 ImageGenerationsRequest: imageGenerationsRequest,
534 CreateTaskResponse: createTaskResponse,
535 CreateTaskData: createTaskData,
536 QueryTaskResponse: queryTaskResponse,
537 QueryTaskData: queryTaskData,
538 TaskResult: taskResult,
539 },
540 },
541 }
543​
544function classify(path: string): Activity | null {
545 const bare = path.split('?')[0] ?? path
546 return GENERATION_PATHS[bare] ?? null
548​
549async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
550 const spec = klingSpec()
551 return {
552 specs: [spec],
553 sources: [{ url: KLING_DOCS_URL, hash: await contentHash(spec) }],
554 outputStrategy: 'post-200',
555 }
557​
558function klingModalities(activity: Activity): ModelInfo['modalities'] {
559 return (
560 normalizeMediaModalities({
561 activity,
562 requestSchemas:
563 activity === 'image'
564 ? [imageGenerationsRequest]
565 : [text2VideoRequest, image2VideoRequest],
566 }) ?? undefined
567 )
569​
570/** Docs-derived catalog — Kling has no GET /models. */
571const CURATED_MODELS: Array<ModelInfo> = (
572 [
573 { rawId: 'kling-v1', displayName: 'Kling V1', activity: 'video' },
574 { rawId: 'kling-v1-5', displayName: 'Kling V1.5', activity: 'image' },
575 { rawId: 'kling-v1-6', displayName: 'Kling V1.6', activity: 'video' },
576 {
577 rawId: 'kling-v2-master',
578 displayName: 'Kling V2 Master',
579 activity: 'video',
580 },
581 {
582 rawId: 'kling-v2-1',
583 displayName: 'Kling V2.1',
584 activity: 'image',
585 },
586 {
587 rawId: 'kling-v2-1-master',
588 displayName: 'Kling V2.1 Master',
589 activity: 'video',
590 },
591 {
592 rawId: 'kling-v2-5-turbo',
593 displayName: 'Kling V2.5 Turbo',
594 activity: 'video',
595 },
596 { rawId: 'kling-v2-6', displayName: 'Kling V2.6', activity: 'video' },
597 { rawId: 'kling-v2', displayName: 'Kling V2 Image', activity: 'image' },
598 { rawId: 'kling-v2-new', displayName: 'Kling V2 New', activity: 'image' },
599 { rawId: 'kling-v3', displayName: 'Kling V3', activity: 'video' },
600 {
601 rawId: 'kling-image-o1',
602 displayName: 'Kling Image O1',
603 activity: 'image',
604 },
605 {
606 rawId: 'kling-video-o1',
607 displayName: 'Kling Video O1',
608 activity: 'video',
609 },
610 ] satisfies Array<{
611 rawId: string
612 displayName: string
613 activity: Activity
614 }>
615).map((model) => ({
616 ...model,
617 modalities: klingModalities(model.activity),
618}))
619​
620async function listModels(
621 env: ProviderSecrets,
622 kv?: KVNamespace,
623): Promise<ListModelsResult> {
624 if (!env.KLING_API_KEY) {
625 return { models: [], ...skippedResult('kling', 'KLING_API_KEY') }
626 }
627 // Presence of the key enables the catalog. There is no models endpoint to
628 // call — POST /v1/videos/text2video creates a generation task.
629 const pricing = await klingModelPricing(kv)
630 return {
631 models: CURATED_MODELS.map((model) => ({
632 ...model,
633 ...pricing(model.rawId),
634 })),
635 }
637​
638export const provider: ProviderConfig = {
639 id: 'kling',
640 displayName: 'Kling AI',
641 authEnvVar: 'KLING_API_KEY',
642 specSourceUrl: KLING_DOCS_URL,
643 modelsEndpoint: KLING_MODELS_ENDPOINT,
644 defaultDerivation: 'docs-derived',
645 fetchSpec,
646 listModels,
647 classify,
648 generationEndpointId: ({ activity }) =>
649 activity === 'image'
650 ? 'v1/images/generations'
651 : activity === 'video'
652 ? 'v1/videos/text2video'
653 : null,