kling-ai
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseKling AI - Image & Video Generation
Kling AI - 图片与视频生成
When to use this skill
何时使用该功能
- Generating images from text prompts (Text-to-Image)
- Creating videos from text descriptions (Text-to-Video)
- Animating static images into videos (Image-to-Video)
- Producing high-quality AI video content (up to 1080p, 30fps)
- Building applications with AI-generated media
- 根据文本提示词生成图片(文本转图片)
- 根据文本描述生成视频(文本转视频)
- 将静态图片动化为视频(图片转视频)
- 生成高质量AI视频内容(最高1080p,30帧/秒)
- 构建包含AI生成媒体的应用程序
Instructions
操作指南
Step 1: Authentication Setup
步骤1:身份验证设置
Kling AI uses JWT (JSON Web Tokens) for authentication.
Required credentials:
- Access Key (AK) - Public identifier
- Secret Key (SK) - Private signing key
Get credentials: app.klingai.com/global/dev
Generate JWT token (Python):
python
import jwt
import time
def generate_kling_token(access_key: str, secret_key: str) -> str:
"""Generate JWT token for Kling AI API."""
headers = {
"alg": "HS256",
"typ": "JWT"
}
payload = {
"iss": access_key,
"exp": int(time.time()) + 1800, # 30 minutes
"nbf": int(time.time()) - 5
}
return jwt.encode(payload, secret_key, algorithm="HS256", headers=headers)Kling AI 使用JWT(JSON Web Tokens)进行身份验证。
所需凭证:
- Access Key(AK)- 公开标识符
- Secret Key(SK)- 私有签名密钥
生成JWT令牌(Python版):
python
import jwt
import time
def generate_kling_token(access_key: str, secret_key: str) -> str:
"""Generate JWT token for Kling AI API."""
headers = {
"alg": "HS256",
"typ": "JWT"
}
payload = {
"iss": access_key,
"exp": int(time.time()) + 1800, # 30 minutes
"nbf": int(time.time()) - 5
}
return jwt.encode(payload, secret_key, algorithm="HS256", headers=headers)Usage
Usage
access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"
token = generate_kling_token(access_key, secret_key)
**Headers for all requests**:
```python
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"
token = generate_kling_token(access_key, secret_key)
**所有请求的请求头**:
```python
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}Step 2: Text-to-Image Generation
步骤2:文本转图片生成
Endpoint:
POST https://api.klingai.com/v1/images/generationsRequest:
python
import requests
def generate_image(prompt: str, token: str) -> dict:
"""Generate image from text prompt."""
url = "https://api.klingai.com/v1/images/generations"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
data = {
"model_name": "kling-v1",
"prompt": prompt,
"negative_prompt": "blur, distortion, low quality",
"n": 1,
"aspect_ratio": "16:9", # 16:9, 9:16, 1:1, 4:3, 3:4, 3:2, 2:3
"image_fidelity": 0.5, # 0-1
"callback_url": "" # Optional webhook
}
response = requests.post(url, json=data, headers=headers)
return response.json()端点:
POST https://api.klingai.com/v1/images/generations请求示例:
python
import requests
def generate_image(prompt: str, token: str) -> dict:
"""Generate image from text prompt."""
url = "https://api.klingai.com/v1/images/generations"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
data = {
"model_name": "kling-v1",
"prompt": prompt,
"negative_prompt": "blur, distortion, low quality",
"n": 1,
"aspect_ratio": "16:9", # 16:9, 9:16, 1:1, 4:3, 3:4, 3:2, 2:3
"image_fidelity": 0.5, # 0-1
"callback_url": "" # Optional webhook
}
response = requests.post(url, json=data, headers=headers)
return response.json()Usage
Usage
result = generate_image(
prompt="A futuristic cityscape at sunset, cinematic lighting, ultra-realistic",
token=token
)
task_id = result["data"]["task_id"]
**Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `model_name` | string | Yes | `kling-v1` |
| `prompt` | string | Yes | Image description (max 500 chars) |
| `negative_prompt` | string | No | Elements to avoid |
| `n` | integer | No | Number of images (1-9, default 1) |
| `aspect_ratio` | string | No | `16:9`, `9:16`, `1:1`, `4:3`, `3:4` |
| `image_fidelity` | float | No | 0-1, default 0.5 |
| `callback_url` | string | No | Webhook for completion |result = generate_image(
prompt="A futuristic cityscape at sunset, cinematic lighting, ultra-realistic",
token=token
)
task_id = result["data"]["task_id"]
**参数说明**:
| 参数 | 类型 | 是否必填 | 描述 |
|-----------|------|----------|-------------|
| `model_name` | string | 是 | `kling-v1` |
| `prompt` | string | 是 | 图片描述(最多500字符) |
| `negative_prompt` | string | 否 | 需要避免的元素 |
| `n` | integer | 否 | 生成图片数量(1-9,默认1) |
| `aspect_ratio` | string | 否 | `16:9`, `9:16`, `1:1`, `4:3`, `3:4` |
| `image_fidelity` | float | 否 | 0-1,默认0.5 |
| `callback_url` | string | 否 | 完成通知的Webhook地址 |Step 3: Text-to-Video Generation
步骤3:文本转视频生成
Endpoint:
POST https://api.klingai.com/v1/videos/text2videoRequest:
python
def generate_video_from_text(prompt: str, token: str, duration: int = 5) -> dict:
"""Generate video from text prompt."""
url = "https://api.klingai.com/v1/videos/text2video"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
data = {
"model_name": "kling-v1", # kling-v1, kling-v1-5, kling-v1-6
"prompt": prompt,
"negative_prompt": "blur, distortion",
"duration": duration, # 5 or 10 seconds
"aspect_ratio": "16:9", # 16:9, 9:16, 1:1
"mode": "std", # std (standard) or pro
"cfg_scale": 0.5, # 0-1
"camera_control": {
"type": "simple",
"config": {
"horizontal": 0, # -10 to 10
"vertical": 0, # -10 to 10
"zoom": 0, # -10 to 10
"tilt": 0, # -10 to 10
"pan": 0, # -10 to 10
"roll": 0 # -10 to 10
}
},
"callback_url": ""
}
response = requests.post(url, json=data, headers=headers)
return response.json()端点:
POST https://api.klingai.com/v1/videos/text2video请求示例:
python
def generate_video_from_text(prompt: str, token: str, duration: int = 5) -> dict:
"""Generate video from text prompt."""
url = "https://api.klingai.com/v1/videos/text2video"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
data = {
"model_name": "kling-v1", # kling-v1, kling-v1-5, kling-v1-6
"prompt": prompt,
"negative_prompt": "blur, distortion",
"duration": duration, # 5 or 10 seconds
"aspect_ratio": "16:9", # 16:9, 9:16, 1:1
"mode": "std", # std (standard) or pro
"cfg_scale": 0.5, # 0-1
"camera_control": {
"type": "simple",
"config": {
"horizontal": 0, # -10 to 10
"vertical": 0, # -10 to 10
"zoom": 0, # -10 to 10
"tilt": 0, # -10 to 10
"pan": 0, # -10 to 10
"roll": 0 # -10 to 10
}
},
"callback_url": ""
}
response = requests.post(url, json=data, headers=headers)
return response.json()Usage
Usage
result = generate_video_from_text(
prompt="A dragon flying over mountains at sunset, epic cinematic shot",
token=token,
duration=5
)
task_id = result["data"]["task_id"]
**Camera control presets**:
```python
camera_presets = {
"zoom_in": {"zoom": 5},
"zoom_out": {"zoom": -5},
"pan_left": {"horizontal": -5},
"pan_right": {"horizontal": 5},
"tilt_up": {"vertical": 5},
"tilt_down": {"vertical": -5},
"dolly_forward": {"zoom": 3, "vertical": 2},
"orbit_right": {"horizontal": 5, "pan": 3}
}result = generate_video_from_text(
prompt="A dragon flying over mountains at sunset, epic cinematic shot",
token=token,
duration=5
)
task_id = result["data"]["task_id"]
**相机控制预设**:
```python
camera_presets = {
"zoom_in": {"zoom": 5},
"zoom_out": {"zoom": -5},
"pan_left": {"horizontal": -5},
"pan_right": {"horizontal": 5},
"tilt_up": {"vertical": 5},
"tilt_down": {"vertical": -5},
"dolly_forward": {"zoom": 3, "vertical": 2},
"orbit_right": {"horizontal": 5, "pan": 3}
}Step 4: Image-to-Video Generation
步骤4:图片转视频生成
Endpoint:
POST https://api.klingai.com/v1/videos/image2videoRequest:
python
import base64
def generate_video_from_image(
image_path: str,
prompt: str,
token: str,
duration: int = 5
) -> dict:
"""Animate an image into a video."""
url = "https://api.klingai.com/v1/videos/image2video"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Load and encode image
with open(image_path, "rb") as f:
image_base64 = base64.b64encode(f.read()).decode()
data = {
"model_name": "kling-v1",
"image": image_base64, # Base64 or URL
"image_tail": "", # Optional: end frame image
"prompt": prompt,
"negative_prompt": "blur, distortion",
"duration": duration,
"mode": "std",
"cfg_scale": 0.5,
"callback_url": ""
}
response = requests.post(url, json=data, headers=headers)
return response.json()端点:
POST https://api.klingai.com/v1/videos/image2video请求示例:
python
import base64
def generate_video_from_image(
image_path: str,
prompt: str,
token: str,
duration: int = 5
) -> dict:
"""Animate an image into a video."""
url = "https://api.klingai.com/v1/videos/image2video"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Load and encode image
with open(image_path, "rb") as f:
image_base64 = base64.b64encode(f.read()).decode()
data = {
"model_name": "kling-v1",
"image": image_base64, # Base64 or URL
"image_tail": "", # Optional: end frame image
"prompt": prompt,
"negative_prompt": "blur, distortion",
"duration": duration,
"mode": "std",
"cfg_scale": 0.5,
"callback_url": ""
}
response = requests.post(url, json=data, headers=headers)
return response.json()Usage
Usage
result = generate_video_from_image(
image_path="portrait.jpg",
prompt="Person smiling and waving at camera",
token=token
)
**With URL instead of base64**:
```python
data = {
"model_name": "kling-v1",
"image": "https://example.com/image.jpg",
"prompt": "The subject slowly turns their head",
"duration": 5
}result = generate_video_from_image(
image_path="portrait.jpg",
prompt="Person smiling and waving at camera",
token=token
)
**使用URL替代Base64**:
```python
data = {
"model_name": "kling-v1",
"image": "https://example.com/image.jpg",
"prompt": "The subject slowly turns their head",
"duration": 5
}Step 5: Check Task Status (Polling)
步骤5:检查任务状态(轮询)
All generation tasks are asynchronous. Poll for completion:
Endpoint:
GET https://api.klingai.com/v1/videos/text2video/{task_id}python
import time
def poll_task_status(task_id: str, token: str, task_type: str = "text2video") -> dict:
"""Poll task status until completion."""
url = f"https://api.klingai.com/v1/videos/{task_type}/{task_id}"
headers = {"Authorization": f"Bearer {token}"}
while True:
response = requests.get(url, headers=headers)
result = response.json()
status = result["data"]["task_status"]
print(f"Status: {status}")
if status == "succeed":
return result
elif status == "failed":
raise Exception(f"Task failed: {result['data'].get('task_status_msg')}")
time.sleep(10) # Poll every 10 seconds所有生成任务均为异步执行,需轮询获取完成状态:
端点:
GET https://api.klingai.com/v1/videos/text2video/{task_id}python
import time
def poll_task_status(task_id: str, token: str, task_type: str = "text2video") -> dict:
"""Poll task status until completion."""
url = f"https://api.klingai.com/v1/videos/{task_type}/{task_id}"
headers = {"Authorization": f"Bearer {token}"}
while True:
response = requests.get(url, headers=headers)
result = response.json()
status = result["data"]["task_status"]
print(f"Status: {status}")
if status == "succeed":
return result
elif status == "failed":
raise Exception(f"Task failed: {result['data'].get('task_status_msg')}")
time.sleep(10) # Poll every 10 secondsUsage
Usage
result = poll_task_status(task_id, token)
video_url = result["data"]["task_result"]["videos"][0]["url"]
print(f"Video URL: {video_url}")
**Task status values**:
| Status | Description |
|--------|-------------|
| `submitted` | Task queued |
| `processing` | Currently generating |
| `succeed` | Completed successfully |
| `failed` | Generation failed |result = poll_task_status(task_id, token)
video_url = result["data"]["task_result"]["videos"][0]["url"]
print(f"Video URL: {video_url}")
**任务状态值**:
| 状态 | 描述 |
|--------|-------------|
| `submitted` | 任务已排队 |
| `processing` | 正在生成中 |
| `succeed` | 生成成功完成 |
| `failed` | 生成失败 |Step 6: Download Generated Media
步骤6:下载生成的媒体文件
python
def download_media(url: str, output_path: str) -> None:
"""Download generated image or video."""
response = requests.get(url, stream=True)
with open(output_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Downloaded: {output_path}")python
def download_media(url: str, output_path: str) -> None:
"""Download generated image or video."""
response = requests.get(url, stream=True)
with open(output_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Downloaded: {output_path}")Usage
Usage
download_media(video_url, "output.mp4")
undefineddownload_media(video_url, "output.mp4")
undefinedExamples
示例
Example 1: Complete Text-to-Video Workflow
示例1:完整的文本转视频工作流
python
import jwt
import time
import requests
class KlingClient:
BASE_URL = "https://api.klingai.com/v1"
def __init__(self, access_key: str, secret_key: str):
self.access_key = access_key
self.secret_key = secret_key
def _get_token(self) -> str:
headers = {"alg": "HS256", "typ": "JWT"}
payload = {
"iss": self.access_key,
"exp": int(time.time()) + 1800,
"nbf": int(time.time()) - 5
}
return jwt.encode(payload, self.secret_key, algorithm="HS256", headers=headers)
def _headers(self) -> dict:
return {
"Authorization": f"Bearer {self._get_token()}",
"Content-Type": "application/json"
}
def text_to_video(self, prompt: str, duration: int = 5, mode: str = "std") -> str:
"""Generate video and return URL."""
# Create task
response = requests.post(
f"{self.BASE_URL}/videos/text2video",
json={
"model_name": "kling-v1",
"prompt": prompt,
"duration": duration,
"mode": mode,
"aspect_ratio": "16:9"
},
headers=self._headers()
)
task_id = response.json()["data"]["task_id"]
# Poll for completion
while True:
result = requests.get(
f"{self.BASE_URL}/videos/text2video/{task_id}",
headers=self._headers()
).json()
status = result["data"]["task_status"]
if status == "succeed":
return result["data"]["task_result"]["videos"][0]["url"]
elif status == "failed":
raise Exception("Generation failed")
time.sleep(10)python
import jwt
import time
import requests
class KlingClient:
BASE_URL = "https://api.klingai.com/v1"
def __init__(self, access_key: str, secret_key: str):
self.access_key = access_key
self.secret_key = secret_key
def _get_token(self) -> str:
headers = {"alg": "HS256", "typ": "JWT"}
payload = {
"iss": self.access_key,
"exp": int(time.time()) + 1800,
"nbf": int(time.time()) - 5
}
return jwt.encode(payload, self.secret_key, algorithm="HS256", headers=headers)
def _headers(self) -> dict:
return {
"Authorization": f"Bearer {self._get_token()}",
"Content-Type": "application/json"
}
def text_to_video(self, prompt: str, duration: int = 5, mode: str = "std") -> str:
"""Generate video and return URL."""
# Create task
response = requests.post(
f"{self.BASE_URL}/videos/text2video",
json={
"model_name": "kling-v1",
"prompt": prompt,
"duration": duration,
"mode": mode,
"aspect_ratio": "16:9"
},
headers=self._headers()
)
task_id = response.json()["data"]["task_id"]
# Poll for completion
while True:
result = requests.get(
f"{self.BASE_URL}/videos/text2video/{task_id}",
headers=self._headers()
).json()
status = result["data"]["task_status"]
if status == "succeed":
return result["data"]["task_result"]["videos"][0]["url"]
elif status == "failed":
raise Exception("Generation failed")
time.sleep(10)Usage
Usage
client = KlingClient("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY")
video_url = client.text_to_video(
prompt="A majestic eagle soaring through clouds at golden hour",
duration=5
)
print(f"Generated video: {video_url}")
undefinedclient = KlingClient("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY")
video_url = client.text_to_video(
prompt="A majestic eagle soaring through clouds at golden hour",
duration=5
)
print(f"Generated video: {video_url}")
undefinedExample 2: Batch Image Generation
示例2:批量生成图片
python
def batch_generate_images(prompts: list, token: str) -> list:
"""Generate multiple images in parallel."""
import concurrent.futures
results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
futures = {
executor.submit(generate_image, prompt, token): prompt
for prompt in prompts
}
for future in concurrent.futures.as_completed(futures):
prompt = futures[future]
try:
result = future.result()
results.append({"prompt": prompt, "task_id": result["data"]["task_id"]})
except Exception as e:
results.append({"prompt": prompt, "error": str(e)})
return resultspython
def batch_generate_images(prompts: list, token: str) -> list:
"""Generate multiple images in parallel."""
import concurrent.futures
results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
futures = {
executor.submit(generate_image, prompt, token): prompt
for prompt in prompts
}
for future in concurrent.futures.as_completed(futures):
prompt = futures[future]
try:
result = future.result()
results.append({"prompt": prompt, "task_id": result["data"]["task_id"]})
except Exception as e:
results.append({"prompt": prompt, "error": str(e)})
return resultsUsage
Usage
prompts = [
"A serene Japanese garden with cherry blossoms",
"A cyberpunk street scene at night",
"An underwater coral reef teeming with life"
]
tasks = batch_generate_images(prompts, token)
undefinedprompts = [
"A serene Japanese garden with cherry blossoms",
"A cyberpunk street scene at night",
"An underwater coral reef teeming with life"
]
tasks = batch_generate_images(prompts, token)
undefinedExample 3: Image-to-Video with Motion Control
示例3:带运动控制的图片转视频
python
def animate_portrait(image_url: str, token: str) -> str:
"""Animate a portrait with subtle motion."""
url = "https://api.klingai.com/v1/videos/image2video"
response = requests.post(
url,
json={
"model_name": "kling-v1",
"image": image_url,
"prompt": "Subtle head movement, natural blinking, gentle smile",
"negative_prompt": "distortion, unnatural movement, glitch",
"duration": 5,
"mode": "pro", # Higher quality for portraits
"cfg_scale": 0.7
},
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
)
task_id = response.json()["data"]["task_id"]
return poll_task_status(task_id, token, "image2video")python
def animate_portrait(image_url: str, token: str) -> str:
"""Animate a portrait with subtle motion."""
url = "https://api.klingai.com/v1/videos/image2video"
response = requests.post(
url,
json={
"model_name": "kling-v1",
"image": image_url,
"prompt": "Subtle head movement, natural blinking, gentle smile",
"negative_prompt": "distortion, unnatural movement, glitch",
"duration": 5,
"mode": "pro", # Higher quality for portraits
"cfg_scale": 0.7
},
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
)
task_id = response.json()["data"]["task_id"]
return poll_task_status(task_id, token, "image2video")Usage
Usage
result = animate_portrait("https://example.com/portrait.jpg", token)
undefinedresult = animate_portrait("https://example.com/portrait.jpg", token)
undefinedExample 4: Video with Camera Movement
示例4:带相机运动的视频生成
python
def cinematic_video(prompt: str, camera_motion: str, token: str) -> str:
"""Generate video with specific camera movement."""
camera_configs = {
"epic_reveal": {"zoom": -5, "vertical": 3},
"dramatic_push": {"zoom": 5},
"orbit_subject": {"horizontal": 7, "pan": 3},
"crane_up": {"vertical": 5, "zoom": 2},
"dolly_back": {"zoom": -3, "horizontal": 2}
}
config = camera_configs.get(camera_motion, {})
response = requests.post(
"https://api.klingai.com/v1/videos/text2video",
json={
"model_name": "kling-v1-6",
"prompt": prompt,
"duration": 10,
"mode": "pro",
"aspect_ratio": "16:9",
"camera_control": {
"type": "simple",
"config": {
"horizontal": config.get("horizontal", 0),
"vertical": config.get("vertical", 0),
"zoom": config.get("zoom", 0),
"tilt": config.get("tilt", 0),
"pan": config.get("pan", 0),
"roll": config.get("roll", 0)
}
}
},
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
)
task_id = response.json()["data"]["task_id"]
return poll_task_status(task_id, token)python
def cinematic_video(prompt: str, camera_motion: str, token: str) -> str:
"""Generate video with specific camera movement."""
camera_configs = {
"epic_reveal": {"zoom": -5, "vertical": 3},
"dramatic_push": {"zoom": 5},
"orbit_subject": {"horizontal": 7, "pan": 3},
"crane_up": {"vertical": 5, "zoom": 2},
"dolly_back": {"zoom": -3, "horizontal": 2}
}
config = camera_configs.get(camera_motion, {})
response = requests.post(
"https://api.klingai.com/v1/videos/text2video",
json={
"model_name": "kling-v1-6",
"prompt": prompt,
"duration": 10,
"mode": "pro",
"aspect_ratio": "16:9",
"camera_control": {
"type": "simple",
"config": {
"horizontal": config.get("horizontal", 0),
"vertical": config.get("vertical", 0),
"zoom": config.get("zoom", 0),
"tilt": config.get("tilt", 0),
"pan": config.get("pan", 0),
"roll": config.get("roll", 0)
}
}
},
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
)
task_id = response.json()["data"]["task_id"]
return poll_task_status(task_id, token)Usage
Usage
video_url = cinematic_video(
prompt="Ancient temple emerging from jungle mist",
camera_motion="epic_reveal",
token=token
)
undefinedvideo_url = cinematic_video(
prompt="Ancient temple emerging from jungle mist",
camera_motion="epic_reveal",
token=token
)
undefinedModel Comparison
模型对比
Video Models
视频模型
| Model | Resolution | Duration | Quality | Cost |
|---|---|---|---|---|
| 720p | 5-10s | Good | $ |
| 1080p | 5-10s | Better | $$ |
| 720p | 5-10s | Good | $ |
| 1080p | 5-10s | Better | $$ |
| 720p | 5-10s | Great | $$ |
| 1080p | 5-10s | Excellent | $$$ |
| 模型 | 分辨率 | 时长 | 质量 | 成本 |
|---|---|---|---|---|
| 720p | 5-10秒 | 良好 | $ |
| 1080p | 5-10秒 | 优秀 | $$ |
| 720p | 5-10秒 | 良好 | $ |
| 1080p | 5-10秒 | 优秀 | $$ |
| 720p | 5-10秒 | 极佳 | $$ |
| 1080p | 5-10秒 | 卓越 | $$$ |
Image Models
图片模型
| Model | Max Resolution | Quality |
|---|---|---|
| 1024x1024 | Standard |
| 2048x2048 | High |
| 模型 | 最大分辨率 | 质量 |
|---|---|---|
| 1024x1024 | 标准 |
| 2048x2048 | 高清 |
Pricing Reference
定价参考
| Feature | Standard Mode | Pro Mode |
|---|---|---|
| 5s video | ~$0.14 | ~$0.49 |
| 10s video | ~$0.28 | ~$0.98 |
| Image | ~$0.01 | - |
| 功能 | 标准模式 | 专业模式 |
|---|---|---|
| 5秒视频 | ~$0.14 | ~$0.49 |
| 10秒视频 | ~$0.28 | ~$0.98 |
| 图片生成 | ~$0.01 | - |
Best practices
最佳实践
- Prompt quality: Be specific and descriptive. Include style keywords like "cinematic", "photorealistic", "4K"
- Negative prompts: Always include to avoid common artifacts: "blur, distortion, low quality, watermark"
- Start with standard mode: Test with mode first, upgrade to
stdfor final outputpro - Use 5-second videos: More cost-effective for testing; use 10s only when needed
- Handle rate limits: Implement exponential backoff for retries
- Cache tokens: Reuse JWT tokens within their validity period (30 min recommended)
- Webhook for production: Use instead of polling in production environments
callback_url
- 提示词质量:描述要具体详细,包含风格关键词如“电影感”、“照片级真实”、“4K”
- 反向提示词:始终添加反向提示词以避免常见瑕疵:“模糊、失真、低质量、水印”
- 从标准模式开始:先使用模式测试,最终输出再升级为
std模式pro - 优先使用5秒视频:测试时更具成本效益;仅在需要时使用10秒视频
- 处理速率限制:实现指数退避策略进行重试
- 缓存令牌:在令牌有效期内重复使用JWT令牌(建议30分钟)
- 生产环境使用Webhook:生产环境中使用替代轮询
callback_url
Common pitfalls
常见陷阱
- Token expiration: JWT tokens expire. Regenerate before making requests if expired
- Prompt length: Text-to-image max 500 chars, text-to-video max 2500 chars
- Image format: Image-to-video supports JPEG, PNG. Max size varies by model
- Polling too fast: Don't poll faster than every 5-10 seconds to avoid rate limits
- Missing negative prompt: Always include to prevent common artifacts
- Wrong aspect ratio: Match aspect ratio to your use case (16:9 for landscape, 9:16 for portrait)
- 令牌过期:JWT令牌会过期,若已过期需重新生成后再发起请求
- 提示词长度:文本转图片最多500字符,文本转视频最多2500字符
- 图片格式:图片转视频支持JPEG、PNG格式,最大尺寸因模型而异
- 轮询过于频繁:不要以低于5-10秒的间隔轮询,避免触发速率限制
- 缺少反向提示词:始终添加反向提示词以防止常见瑕疵
- 错误的宽高比:根据使用场景匹配正确的宽高比(16:9适用于横屏,9:16适用于竖屏)
Error Handling
错误处理
python
class KlingAPIError(Exception):
pass
def handle_kling_response(response: requests.Response) -> dict:
"""Handle API response with proper error handling."""
data = response.json()
if response.status_code == 401:
raise KlingAPIError("Authentication failed. Check your credentials.")
elif response.status_code == 429:
raise KlingAPIError("Rate limit exceeded. Wait and retry.")
elif response.status_code >= 400:
error_msg = data.get("message", "Unknown error")
raise KlingAPIError(f"API Error: {error_msg}")
if data.get("code") != 0:
raise KlingAPIError(f"Request failed: {data.get('message')}")
return datapython
class KlingAPIError(Exception):
pass
def handle_kling_response(response: requests.Response) -> dict:
"""Handle API response with proper error handling."""
data = response.json()
if response.status_code == 401:
raise KlingAPIError("Authentication failed. Check your credentials.")
elif response.status_code == 429:
raise KlingAPIError("Rate limit exceeded. Wait and retry.")
elif response.status_code >= 400:
error_msg = data.get("message", "Unknown error")
raise KlingAPIError(f"API Error: {error_msg}")
if data.get("code") != 0:
raise KlingAPIError(f"Request failed: {data.get('message')}")
return data