Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Set up logging and debugging for Kling AI API integrations. Use when troubleshooting video generation or building observability. Trigger with phrases like 'klingai debug', 'kling ai logging', 'klingai troubleshoot', 'debug kling video generation'.
.claude/skills/jeremylongshore-klingai-debug-bundle/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-02 | ✗→✓ | ▲ Improved | 56% | 0% |
| case-04 | ✗→✓ | ▲ Improved | 41% | 0% |
| case-06 | ✗→✓ | ▲ Improved | 72% | 0% |
| case-11 | ✗→✓ | ▲ Improved | 60% | 0% |
| case-12 | ✗→✓ | ▲ Improved | 69% | 0% |
Structured logging, request tracing, and diagnostic tools for Kling AI API integrations. Captures request/response pairs, task lifecycle events, and timing metrics for every call to https://api.klingai.com/v1.
pythonimport jwt, time, os, requests, logging, json from datetime import datetime logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s" ) logger = logging.getLogger("kling.debug") class KlingDebugClient: """Kling AI client with full request/response logging.""" BASE = "https://api.klingai.com/v1" def __init__(self): self.ak = os.environ["KLING_ACCESS_KEY"] self.sk = os.environ["KLING_SECRET_KEY"] self._request_log = [] def _get_headers(self): token = jwt.encode( {"iss": self.ak, "exp": int(time.time()) + 1800, "nbf": int(time.time()) - 5}, self.sk, algorithm="HS256", headers={"alg": "HS256", "typ": "JWT"} ) return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} def _traced_request(self, method, path, body=None): """Execute request with full tracing.""" url = f"{self.BASE}{path}" start = time.monotonic() trace = { "timestamp": datetime.utcnow().isoformat(), "method": method, "path": path, "request_body": body, } try: if method == "POST": r = requests.post(url, headers=self._get_headers(), json=body, timeout=30) else: r = requests.get(url, headers=self._get_headers(), timeout=30) trace["status_code"] = r.status_code trace["response_body"] = r.json() if r.content else None trace["duration_ms"] = round((time.monotonic() - start) * 1000) logger.debug(f"{method} {path} -> {r.status_code} ({trace['duration_ms']}ms)") if r.status_code >= 400: logger.error(f"API error: {r.status_code} -- {r.text[:300]}") r.raise_for_status() return r.json() except Exception as e: trace["error"] = str(e) trace["duration_ms"] = round((time.monotonic() - start) * 1000) logger.exception(f"Request failed: {path}") raise finally: self._request_log.append(trace) def text_to_video(self, prompt, **kwargs): body = { "model_name": kwargs.get("model", "kling-v2-master"), "prompt": prompt, "duration": str(kwargs.get("duration", 5)), "mode": kwargs.get("mode", "standard"), } result = self._traced_request("POST", "/videos/text2video", body) task_id = result["data"]["task_id"] logger.info(f"Task created: {task_id}") return self._poll_with_logging("/videos/text2video", task_id) def _poll_with_logging(self, endpoint, task_id, max_attempts=120): start = time.monotonic() for attempt in range(max_attempts): time.sleep(10) result = self._traced_request("GET", f"{endpoint}/{task_id}") status = result["data"]["task_status"] elapsed = round(time.monotonic() - start) logger.info(f"Poll #{attempt + 1}: status={status}, elapsed={elapsed}s") if status == "succeed": logger.info(f"Task {task_id} completed in {elapsed}s") return result["data"]["task_result"] elif status == "failed": msg = result["data"].get("task_status_msg", "Unknown") logger.error(f"Task {task_id} failed after {elapsed}s: {msg}") raise RuntimeError(msg) raise TimeoutError(f"Task {task_id} timed out after {max_attempts * 10}s") def dump_log(self, filepath="kling_debug.json"): with open(filepath, "w") as f: json.dump(self._request_log, f, indent=2, default=str) logger.info(f"Debug log written to {filepath} ({len(self._request_log)} entries)")
pythonclient = KlingDebugClient() try: result = client.text_to_video("A cat surfing ocean waves at sunset") print(f"Video: {result['videos'][0]['url']}") except Exception: pass finally: client.dump_log() # always save debug log
json{ "timestamp": "2026-03-22T10:30:00.000Z", "method": "POST", "path": "/videos/text2video", "request_body": {"model_name": "kling-v2-master", "prompt": "..."}, "status_code": 200, "response_body": {"code": 0, "data": {"task_id": "abc123"}}, "duration_ms": 342 }
bash#!/bin/bash # kling-diag.sh echo "=== Kling AI Diagnostics ===" echo "KLING_ACCESS_KEY: ${KLING_ACCESS_KEY:+set (${#KLING_ACCESS_KEY} chars)}" echo "KLING_SECRET_KEY: ${KLING_SECRET_KEY:+set (${#KLING_SECRET_KEY} chars)}" python3 -c " import jwt, time, os, requests ak = os.environ.get('KLING_ACCESS_KEY', '') sk = os.environ.get('KLING_SECRET_KEY', '') if not ak or not sk: print('ERROR: Missing credentials'); exit(1) token = jwt.encode({'iss': ak, 'exp': int(time.time())+1800, 'nbf': int(time.time())-5}, sk, algorithm='HS256', headers={'alg':'HS256','typ':'JWT'}) r = requests.get('https://api.klingai.com/v1/videos/text2video', headers={'Authorization': f'Bearer {token}'}, timeout=10) print(f'Auth test: HTTP {r.status_code}') if r.status_code == 401: print('Fix: Check AK/SK values') elif r.status_code in (200, 400): print('Auth OK') "
pythondef inspect_task(client, endpoint, task_id): """Print detailed task information.""" result = client._traced_request("GET", f"{endpoint}/{task_id}") data = result["data"] print(f"Task ID: {data['task_id']}") print(f"Status: {data['task_status']}") print(f"Created: {data.get('created_at', 'N/A')}") if data["task_status"] == "succeed": for i, video in enumerate(data["task_result"]["videos"]): print(f"Video [{i}]: {video['url']}") elif data["task_status"] == "failed": print(f"Error: {data.get('task_status_msg', 'No message')}")
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-02 | fail→pass | 23,856 | 25,531 | +7% | 1 | 1 | 0% | 4,054 | 6,310 | +56% | 0 | 0 | — |
case-01 | fail→fail | 40,279 | 22,046 | -45% | 1 | 1 | 0% | 7,551 | 5,968 | -21% | 0 | 0 | — |
case-03 | fail→fail | 55,549 | 11,289 | -80% | 1 | 1 | 0% | 4,377 | 4,493 | +3% | 0 | 0 | — |
case-04 | fail→pass | 14,003 | 14,720 | +5% | 1 | 1 | 0% | 2,794 | 3,939 | +41% | 0 | 0 | — |
case-05 | pass→pass | 9,584 | 7,583 | -21% | 1 | 1 | 0% | 799 | 2,476 | +210% | 0 | 0 | — |
case-06 | fail→pass | 15,257 | 10,085 | -34% | 1 | 1 | 0% | 1,716 | 2,947 | +72% | 0 | 0 | — |
case-07 | fail→fail | 19,797 | 10,620 | -46% | 1 | 1 | 0% | 2,679 | 4,049 | +51% | 0 | 0 | — |
case-08 | fail→fail | 21,401 | 21,488 | +0% | 1 | 1 | 0% | 3,129 | 5,313 | +70% | 0 | 0 | — |
case-09 | pass→pass | 17,195 | 14,820 | -14% | 1 | 1 | 0% | 2,377 | 3,847 | +62% | 0 | 0 | — |
case-10 | pass→pass | 15,717 | 9,453 | -40% | 1 | 1 | 0% | 1,525 | 2,860 | +88% | 0 | 0 | — |
case-11 | fail→pass | 14,934 | 14,399 | -4% | 1 | 1 | 0% | 2,087 | 3,343 | +60% | 0 | 0 | — |
case-12 | fail→pass | 19,659 | 18,987 | -3% | 1 | 1 | 0% | 2,881 | 4,871 | +69% | 0 | 0 | — |
case-13 | pass→pass | 13,099 | 11,541 | -12% | 1 | 1 | 0% | 1,605 | 3,276 | +104% | 0 | 0 | — |
case-14 | fail→pass | 15,425 | 11,870 | -23% | 1 | 1 | 0% | 2,282 | 3,818 | +67% | 0 | 0 | — |
case-15 | fail→fail | 34,218 | 18,224 | -47% | 1 | 1 | 0% | 3,153 | 4,861 | +54% | 0 | 0 | — |
case-16 | fail→pass | 8,791 | 3,065 | -65% | 1 | 1 | 0% | 1,508 | 2,553 | +69% | 0 | 0 | — |
case-17 | pass→pass | 19,661 | 12,703 | -35% | 1 | 1 | 0% | 2,612 | 4,469 | +71% | 0 | 0 | — |
case-18 | pass→pass | 17,864 | 4,319 | -76% | 1 | 1 | 0% | 2,231 | 2,621 | +17% | 0 | 0 | — |
case-19 | fail→pass | 11,319 | 8,561 | -24% | 1 | 1 | 0% | 1,845 | 2,720 | +47% | 0 | 0 | — |
case-20 | fail→pass | 14,818 | 2,967 | -80% | 1 | 1 | 0% | 1,483 | 2,573 | +73% | 0 | 0 | — |
case-21 | pass→pass | 16,649 | 13,720 | -18% | 1 | 1 | 0% | 2,137 | 3,465 | +62% | 0 | 0 | — |
case-22 | pass→pass | 30,566 | 21,096 | -31% | 1 | 1 | 0% | 4,188 | 5,621 | +34% | 0 | 0 | — |
case-23 | pass→pass | 21,886 | 21,771 | -1% | 1 | 1 | 0% | 3,277 | 5,369 | +64% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 23 cases were attempted. The headline lift of +39 percentage points is the difference between those two pass rates over the 23 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.