KL

klingai-usage-analytics

Set up event logging and analytics tracking for Kling AI video generation usage.

Install

mkdir -p .claude/skills/klingai-usage-analytics && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/7277" && unzip -o skill.zip -d .claude/skills/klingai-usage-analytics && rm skill.zip

Installs to .claude/skills/klingai-usage-analytics

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Build usage analytics and reporting for Kling AI video generation. Use
70 charsno explicit “when” trigger
Intermediate

Key capabilities

  • →Log generation events to JSONL files
  • →Aggregate daily usage metrics
  • →Calculate credit consumption and costs
  • →Generate usage reports and summaries
  • →Export usage data to CSV

How it works

The skill implements an append-only JSONL logger and an aggregator class to track, summarize, and analyze Kling AI generation events.

Inputs & outputs

You give it
Task submission and completion data
You get back
Usage report or CSV file

When to use klingai-usage-analytics

  • →Track video generation task completion times
  • →Monitor Kling AI credit usage by project
  • →Aggregate daily usage metrics
  • →Build custom analytics dashboards from JSONL logs

About this skill

Kling AI Usage Analytics

Overview

Track video generation usage with structured logging, aggregate metrics, daily reports, and cost analysis. Built on JSONL event logs that can feed into any analytics platform.

Event Logger

import json
import time
from datetime import datetime
from pathlib import Path

class KlingEventLogger:
    """Append-only JSONL event log for Kling AI operations."""

    def __init__(self, log_dir: str = "logs"):
        self.log_dir = Path(log_dir)
        self.log_dir.mkdir(exist_ok=True)

    def _write(self, event: dict):
        date = datetime.utcnow().strftime("%Y-%m-%d")
        filepath = self.log_dir / f"kling-{date}.jsonl"
        event["timestamp"] = datetime.utcnow().isoformat()
        with open(filepath, "a") as f:
            f.write(json.dumps(event) + "\n")

    def log_submission(self, task_id, prompt, model, duration, mode):
        self._write({
            "event": "task_submitted",
            "task_id": task_id,
            "model": model,
            "duration": int(duration),
            "mode": mode,
            "prompt_len": len(prompt),
        })

    def log_completion(self, task_id, status, elapsed_sec, credits_used):
        self._write({
            "event": "task_completed",
            "task_id": task_id,
            "status": status,
            "elapsed_sec": elapsed_sec,
            "credits_used": credits_used,
        })

    def log_error(self, task_id, error_type, message):
        self._write({
            "event": "task_error",
            "task_id": task_id,
            "error_type": error_type,
            "message": message[:200],
        })

Analytics Aggregator

from collections import defaultdict

class UsageAnalytics:
    """Aggregate metrics from JSONL event logs."""

    def __init__(self, log_dir: str = "logs"):
        self.log_dir = Path(log_dir)

    def _read_events(self, date: str = None):
        pattern = f"kling-{date}.jsonl" if date else "kling-*.jsonl"
        events = []
        for filepath in sorted(self.log_dir.glob(pattern)):
            with open(filepath) as f:
                for line in f:
                    events.append(json.loads(line))
        return events

    def daily_summary(self, date: str = None) -> dict:
        date = date or datetime.utcnow().strftime("%Y-%m-%d")
        events = self._read_events(date)

        submitted = [e for e in events if e["event"] == "task_submitted"]
        completed = [e for e in events if e["event"] == "task_completed"]
        errors = [e for e in events if e["event"] == "task_error"]

        succeeded = [e for e in completed if e["status"] == "succeed"]
        failed = [e for e in completed if e["status"] == "failed"]

        total_credits = sum(e.get("credits_used", 0) for e in completed)
        avg_elapsed = (sum(e["elapsed_sec"] for e in succeeded) / len(succeeded)
                      if succeeded else 0)

        by_model = defaultdict(int)
        for e in submitted:
            by_model[e["model"]] += 1

        return {
            "date": date,
            "total_submitted": len(submitted),
            "succeeded": len(succeeded),
            "failed": len(failed),
            "errors": len(errors),
            "success_rate": f"{len(succeeded) / max(len(completed), 1) * 100:.1f}%",
            "total_credits": total_credits,
            "avg_generation_sec": round(avg_elapsed),
            "by_model": dict(by_model),
        }

    def print_report(self, date: str = None):
        s = self.daily_summary(date)
        print(f"\n=== Kling AI Usage Report: {s['date']} ===")
        print(f"Submitted:    {s['total_submitted']}")
        print(f"Succeeded:    {s['succeeded']}")
        print(f"Failed:       {s['failed']}")
        print(f"Success rate: {s['success_rate']}")
        print(f"Credits used: {s['total_credits']}")
        print(f"Avg time:     {s['avg_generation_sec']}s")
        print(f"By model:")
        for model, count in s["by_model"].items():
            print(f"  {model}: {count}")

Cost Analysis

def cost_analysis(analytics: UsageAnalytics, days: int = 7):
    """Analyze cost trends over recent days."""
    from datetime import timedelta

    daily_costs = []
    for i in range(days):
        date = (datetime.utcnow() - timedelta(days=i)).strftime("%Y-%m-%d")
        summary = analytics.daily_summary(date)
        daily_costs.append({
            "date": date,
            "credits": summary["total_credits"],
            "videos": summary["total_submitted"],
            "estimated_usd": summary["total_credits"] * 0.14,
        })

    total_credits = sum(d["credits"] for d in daily_costs)
    total_videos = sum(d["videos"] for d in daily_costs)
    total_cost = sum(d["estimated_usd"] for d in daily_costs)

    print(f"\n=== {days}-Day Cost Summary ===")
    print(f"Total credits: {total_credits}")
    print(f"Total videos:  {total_videos}")
    print(f"Est. cost:     ${total_cost:.2f}")
    print(f"Avg/day:       ${total_cost / days:.2f}")

    for d in daily_costs:
        print(f"  {d['date']}: {d['credits']} credits, {d['videos']} videos, ${d['estimated_usd']:.2f}")

Export to CSV

import csv

def export_usage_csv(analytics: UsageAnalytics, output: str = "kling_usage.csv"):
    events = analytics._read_events()
    with open(output, "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=["timestamp", "event", "task_id",
                                                "model", "status", "credits_used",
                                                "elapsed_sec"])
        writer.writeheader()
        for e in events:
            writer.writerow({k: e.get(k, "") for k in writer.fieldnames})
    print(f"Exported {len(events)} events to {output}")

Prerequisites

  • An append-only event sink with restricted access, an explicit retention/deletion schedule, a timezone, and an approved pricing source for aggregate cost calculations.
  • Define an opaque run/task identifier and a schema that records operational facts only. Prompts, source media, faces/voices, signed URLs, personal data, credentials, and free-form provider messages are prohibited in logs.
  • Seed the parser and dashboard with synthetic events, and define anomaly thresholds, export destinations, and an owner who can pause generation when spend or policy signals drift.

Instructions

  1. Validate each event against the allowlisted schema before writing it. Normalize timestamps to the documented timezone and reject records with raw prompts, media, identities, or secrets.
  2. Use opaque IDs to correlate submission, completion, error, and cleanup events. Deduplicate retries and preserve the original event time so totals cannot be inflated by a replay.
  3. Aggregate by date, model, mode, status, and credit bucket. Apply the current approved rate only to totals, and keep dashboards and CSV exports at aggregate level.
  4. Alert on failure-rate, latency, credit, retention, policy, and unexpected-destination thresholds. Pause new work for a confirmed anomaly, run a synthetic canary after remediation, and require owner approval before resuming.
  5. Enforce retention deletion, verify the deletion receipt, and retain only a redacted aggregate report and incident/rollback reference.

Output

Produce an aggregate report containing date range, submitted/succeeded/failed counts, success rate, latency summary, credits, estimated cost range, model distribution, anomaly state, retention/deletion status, and owner approval or rollback state. It must not expose prompts, media, likenesses, audio, signed URLs, contact details, billing identifiers, or credentials.

Error Handling

  • Quarantine malformed, duplicate, out-of-order, or schema-breaking events without counting them twice; report the aggregate gap and repair from an approved source.
  • If a log contains prohibited content, stop exports, restrict access, remove the offending record under the retention policy, and record only the redacted cleanup receipt.
  • If pricing is missing or stale, show credits without currency conversion and mark cost as unknown. If storage, deletion, or anomaly checks fail, pause dependent reporting and generation until an owner approves recovery.

Examples

A safe fixture can contain run_id=synthetic-run-01, event=task_completed, model=kling-v2-5-turbo, status=succeed, credits_used=10, elapsed_sec=42, and no prompt or URL. A seven-day report may publish counts and cost ranges to an internal dashboard only after schema=pass, pii_scan=pass, retention=verified, and export=aggregate-only.

Resources

When not to use it

  • →Real-time monitoring requirements

Limitations

  • →Logs are stored locally on the file system
  • →Requires manual aggregation for historical trends

How it compares

It provides a local, file-based analytics structure instead of requiring external SaaS monitoring tools.

Compared to similar skills

klingai-usage-analytics side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
klingai-usage-analytics (this skill)12moReviewIntermediate
phoenix-observability38moReviewIntermediate
train-with-environments12moReviewAdvanced
phoenix-tracing12moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore →

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

phoenix-observability

davila7

Open-source AI observability platform for LLM tracing, evaluation, and monitoring. Use when debugging LLM applications with detailed traces, running evaluations on datasets, or monitoring production AI systems with real-time insights.

323

train-with-environments

PrimeIntellect-ai

Train models with verifiers environments using hosted RL or prime-rl. Use when asked to configure RL runs, tune key hyperparameters, diagnose instability, set up difficulty filtering and oversampling, or create practical train and eval loops for new environments.

14

phoenix-tracing

Arize-ai

OpenInference semantic conventions and instrumentation for Phoenix AI observability. Use when implementing LLM tracing, creating custom spans, or deploying to production.

13

genkit-production-expert

jeremylongshore

Build production Firebase Genkit applications including RAG systems, multi-step flows, and tool calling for Node.js/Python/Go. Deploy to Firebase Functions or Cloud Run with AI monitoring. Use when asked to "create genkit flow" or "implement RAG". Trigger with relevant phrases based on skill purpose.

01

langsmith-evaluator

dhar174

INVOKE THIS SKILL when building evaluation pipelines for LangSmith. Covers three core components: (1) Creating Evaluators - LLM-as-Judge, custom code; (2) Defining Run Functions - how to capture outputs and trajectories from your agent; (3) Running Evaluations - locally with evaluate() or auto-run v

00

senior-data-scientist

davila7

World-class data science skill for statistical modeling, experimentation, causal inference, and advanced analytics. Expertise in Python (NumPy, Pandas, Scikit-learn), R, SQL, statistical methods, A/B testing, time series, and business intelligence. Includes experiment design, feature engineering, model evaluation, and stakeholder communication. Use when designing experiments, building predictive models, performing causal analysis, or driving data-driven decisions.

952

Search skills

Search the agent skills registry