Agent SkillsAgent Skills
jeremylongshore

klingai-common-errors

@jeremylongshore/klingai-common-errors
jeremylongshore
2,103
284 forks
Updated 5/5/2026
View on GitHub

Diagnose and fix common Kling AI API errors. Use when troubleshooting failed video generation or API issues. Trigger with phrases like 'kling ai error', 'klingai not working', 'fix klingai', 'klingai failed'.

Installation

$npx agent-skills-cli install @jeremylongshore/klingai-common-errors
Claude Code
Cursor
Copilot
Codex
Antigravity

Details

Pathplugins/saas-packs/klingai-pack/skills/klingai-common-errors/SKILL.md
Branchmain
Scoped Name@jeremylongshore/klingai-common-errors

Usage

After installing, this skill will be available to your AI coding assistant.

Verify installation:

npx agent-skills-cli list

Skill Instructions


name: klingai-common-errors description: 'Diagnose and fix common Kling AI API errors. Use when troubleshooting failed video generation

or API issues. Trigger with phrases like ''kling ai error'', ''klingai not working'', ''fix klingai'',

''klingai failed''.

' allowed-tools: Read, Write, Edit, Bash(npm:*), Grep version: 1.0.0 license: MIT author: Jeremy Longshore jeremy@intentsolutions.io tags:

  • saas
  • kling-ai
  • debugging
  • errors compatibility: Designed for Claude Code, also compatible with Codex and OpenClaw

Kling AI Common Errors

Overview

Complete error reference for the Kling AI API. Covers HTTP status codes, task-level failures, JWT issues, and generation-specific problems with tested solutions.

HTTP Error Codes

CodeErrorCauseSolution
400Bad RequestInvalid parameters, malformed JSONValidate all required fields; check model_name is valid
401UnauthorizedInvalid/expired JWT tokenRegenerate JWT; verify AK/SK; check exp claim
402Payment RequiredInsufficient creditsTop up API resource pack or subscription
403ForbiddenContent policy violation or API disabledReview prompt against content policy; enable API access
404Not FoundInvalid task_id or wrong endpointVerify task_id; check endpoint path spelling
429Too Many RequestsRate limit exceededImplement exponential backoff (see pattern below)
500Internal Server ErrorKling platform issueRetry after 30s; if persistent, check status page
502Bad GatewayUpstream service unavailableRetry with backoff; typically transient
503Service UnavailableSystem maintenanceWait and retry; check announcements

Task-Level Failures

When HTTP returns 200 but task_status is "failed":

task_status_msgCauseSolution
Content policy violationPrompt contains restricted contentRemove violent, adult, or copyrighted references
Image quality too lowSource image is blurry or too smallUse image >= 300x300px, clear and sharp
Prompt too complexToo many scene elementsSimplify to 1-2 subjects, clear action
Generation timeoutInternal processing exceeded limitRetry; reduce duration from 10s to 5s
Invalid image formatUnsupported file typeUse JPG, PNG, or WebP
Mask dimension mismatchMask size differs from sourceEnsure mask matches source image dimensions exactly

JWT Authentication Errors

Problem: 401 on every request

# WRONG — missing headers parameter
token = jwt.encode(payload, sk, algorithm="HS256")

# CORRECT — include explicit headers
token = jwt.encode(payload, sk, algorithm="HS256",
                   headers={"alg": "HS256", "typ": "JWT"})

Problem: Token works then fails after 30 min

# WRONG — token generated once at import time
TOKEN = generate_token()

# CORRECT — refresh before expiry
class TokenManager:
    def __init__(self, ak, sk):
        self.ak, self.sk = ak, sk
        self._token = None
        self._exp = 0

    @property
    def token(self):
        if time.time() >= self._exp - 300:  # 5 min buffer
            payload = {"iss": self.ak, "exp": int(time.time()) + 1800,
                       "nbf": int(time.time()) - 5}
            self._token = jwt.encode(payload, self.sk, algorithm="HS256",
                                     headers={"alg": "HS256", "typ": "JWT"})
            self._exp = int(time.time()) + 1800
        return self._token

Rate Limit Handling

import time
import requests

def request_with_backoff(method, url, headers, json=None, max_retries=5):
    """Retry with exponential backoff on 429 and 5xx errors."""
    for attempt in range(max_retries):
        response = method(url, headers=headers, json=json)

        if response.status_code == 429:
            retry_after = int(response.headers.get("Retry-After", 2 ** attempt))
            print(f"Rate limited. Retrying in {retry_after}s...")
            time.sleep(retry_after)
            continue
        elif response.status_code >= 500:
            wait = 2 ** attempt
            print(f"Server error {response.status_code}. Retrying in {wait}s...")
            time.sleep(wait)
            continue

        response.raise_for_status()
        return response

    raise RuntimeError(f"Max retries ({max_retries}) exceeded")

Diagnostic Checklist

When a generation fails, check in order:

  1. Auth valid? — Test with a simple GET request first
  2. Credits available? — Check balance in developer console
  3. Model valid? — Verify model_name matches catalog exactly
  4. Parameters valid?duration must be "5" or "10" (string, not int)
  5. Prompt clean? — Remove special characters, keep under 2500 chars
  6. Image accessible? — For I2V, verify image URL is publicly accessible
  7. Feature exclusivity?image_tail, dynamic_masks, and camera_control are mutually exclusive

Debug Logging

import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("kling")

def debug_request(method, url, headers, json=None):
    """Log request/response for debugging."""
    logger.debug(f"→ {method.__name__.upper()} {url}")
    logger.debug(f"→ Body: {json}")
    r = method(url, headers=headers, json=json)
    logger.debug(f"← Status: {r.status_code}")
    logger.debug(f"← Body: {r.text[:500]}")
    return r

Resources

More by jeremylongshore

View all
docker-compose-generator
2,103

generating-docker-compose-files: This skill enables Claude to generate Docker Compose configurations for multi-container applications. It leverages best practices for production-ready deployments, including defining services, networks, volumes, health checks, and resource limits. Claude should use this skill when the user requests a Docker Compose file, specifies application architecture involving multiple containers, or mentions needs for container orchestration, environment variables, or persistent data management in a Docker environment. Trigger terms include "docker-compose", "docker compose file", "multi-container", "container orchestration", "docker environment", "service definition", "volume management", "network configuration", "health checks", "resource limits", and ".env files".

environment-config-manager
2,103

managing-environment-configurations: This skill enables Claude to manage environment configurations and secrets across different deployments using the environment-config-manager plugin. It is invoked when the user needs to generate, update, or retrieve configuration settings for various environments (e.g., development, staging, production). Use this skill when the user explicitly mentions "environment configuration," "secrets management," "deployment configuration," or asks to "generate config files". It helps streamline DevOps workflows by providing production-ready configurations based on best practices.

fairdb-backup-manager
2,103

Automatically manages PostgreSQL backups with pgBackRest and Wasabi S3 storage when working with FairDB databases Activates when you request "fairdb backup manager" functionality.

git-commit-smart
2,103

generating-smart-commits: This skill generates conventional commit messages using AI analysis of staged Git changes. It automatically determines the commit type (feat, fix, docs, etc.), identifies breaking changes, and formats the message according to conventional commit standards. Use this when asked to create a commit message, write a Git commit, or when the user uses the `/commit-smart` or `/gc` command. It is especially useful after changes have been staged with `git add`.