EN ▾
Get API key

klingapis.comKling AI API Documentation: Text LLM API Reference

Kling AI API Documentation: Text LLM API Reference

This page is the working reference for our text API, not the documentation of Kling's video service, which has its own docs from its provider. If you were after kling ai api documentation for the language side of a media pipeline, everything you need to call it is below.

Updated

Open reference book releasing request cards and a data stream into a terminal, representing API documentation

What these docs cover

The service is a hosted text-only LLM API. It is not Kling and it is not affiliated with Kling, so it has no endpoints for video or image generation. It has two: one for chat completions and one for listing models. If you build around AI video tools, this is the part that writes and revises text for them, and the interface is the same OpenAI format that most client libraries already speak.

Short version of the contract:

  • Base URL: https://api.klingapis.com/v1
  • Auth header: Authorization: Bearer YOUR_API_KEY
  • Model: uncensored
  • Methods: POST /v1/chat/completions, GET /v1/models
  • Context window: 100,000 tokens, prompt and completion together

The model is one open-weight model run by an independent provider and tuned to answer without content refusals for lawful adult use. The one hard rule is no sexual content involving minors. The short quickstart lives on the docs page; this article goes further into the parts people ask about.

Get a key and make the first request

Sign up with Google or with email and password, then open the API key page. A new account can claim $0.50 of trial credit there with one click, one per person, valid for 7 days, no card needed. Copy the key and keep it out of source control; an environment variable is enough.

First check that the key works by listing models:

curl https://api.klingapis.com/v1/models \
  -H "Authorization: Bearer $API_KEY"

Then send a chat completion. The body is the usual list of messages with a role and content each:

curl https://api.klingapis.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [
      {"role": "system", "content": "You write short scene descriptions."},
      {"role": "user", "content": "A fishing boat at first light."}
    ],
    "temperature": 0.8
  }'

With the Python SDK the same call looks like this:

from openai import OpenAI

client = OpenAI(base_url="https://api.klingapis.com/v1", api_key="YOUR_API_KEY")

r = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "A fishing boat at first light."}],
)
print(r.choices[0].message.content)
print(r.usage)

Request parameters

The standard sampling settings are passed through to the model: temperature, top_p, stop, seed and the frequency and presence penalties. max_tokens is optional. If you leave it out, the completion can use whatever remains of the 100,000-token window after your prompt, so set a ceiling when you want to bound cost or length.

A few practical notes:

  • Seed. Pass seed with a fixed temperature when you want repeatable drafts while testing. Treat repeatability as best effort rather than a guarantee.
  • Stop sequences. Use stop to cut output at a delimiter, which is handy when you ask for a single line and do not want trailing commentary.
  • Body size. The maximum request body is 8 MB. Text rarely gets near that, but pasted logs or long histories can.
  • Roles. Use system for standing instructions, user for input, assistant for earlier replies, and tool for tool results.

Only text goes in and comes out. There are no image or audio inputs, no embeddings endpoint and no fine-tuning.

Settings that work for media text

The right sampling settings depend on the job, and a few starting points save trial and error. These are suggestions to tune, not rules from the provider.

  • Scene and prompt writing: temperature around 0.8 to 1.0 gives varied wording. Raise the frequency penalty slightly if the model keeps reusing the same adjectives.
  • Extraction and classification: temperature at 0 to 0.3, JSON mode on, and a short output ceiling. You want the same answer for the same input.
  • Dialogue and role-play: temperature near 0.9, a clear system message that fixes the character, and a stop sequence if the model tends to speak for the other party.
  • Batch variations: send the same prompt several times with different seed values, or ask for five variants in one JSON array. One call with five variants is cheaper in input tokens; five calls give more diversity.

Change one setting at a time and compare outputs on the same three or four test prompts. Changing temperature, top_p and penalties together makes it impossible to tell which one helped.

Streaming

Set stream: true and the response arrives as server-sent events, one chunk per piece of text, so a UI can print words as they are generated. Usage is reported at the end of the stream. In Node:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.klingapis.com/v1",
  apiKey: process.env.API_KEY,
});

const stream = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Describe a night market in 80 words." }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

Remember that a streamed request occupies its concurrency slot until the stream ends. A client that stops reading but leaves the connection open keeps that slot taken. Close the stream when you are done or when the user navigates away.

Tool calling

Pass tools and, if you want to steer it, tool_choice. When the model decides to call a function, the reply contains tool_calls (also streamed in chunks if you stream). You run the function yourself, then send the result back as a message with role: "tool" and the matching tool_call_id.

import json
from openai import OpenAI

client = OpenAI(base_url="https://api.klingapis.com/v1", api_key="YOUR_API_KEY")

tools = [{
    "type": "function",
    "function": {
        "name": "word_count",
        "description": "Count the words in a piece of text.",
        "parameters": {
            "type": "object",
            "properties": {"text": {"type": "string"}},
            "required": ["text"],
        },
    },
}]

messages = [{"role": "user", "content": "How many words are in: the quick brown fox?"}]
first = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message

if msg.tool_calls:
    messages.append(msg)
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = len(args["text"].split())
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": str(result),
        })
    final = client.chat.completions.create(
        model="uncensored", messages=messages, tools=tools
    )
    print(final.choices[0].message.content)

Always validate the arguments before running anything with side effects. The model produces them as JSON text, and nothing guarantees a schema match, so wrap json.loads in error handling.

JSON mode

For machine-readable output, set response_format to {"type": "json_object"}. Also say in the prompt that you want JSON and describe the keys; the setting constrains the format, and your wording decides the content.

curl https://api.klingapis.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "response_format": {"type": "json_object"},
    "messages": [
      {"role": "system", "content": "Reply with JSON: {\"title\": string, \"tags\": [string]}"},
      {"role": "user", "content": "A short film about a lighthouse keeper."}
    ]
  }'

Parse the reply with a real JSON parser and keep a fallback path. If parsing fails, retry once with the parse error appended. Failed or refused requests are not charged, which keeps that loop cheap.

Limits, headers and errors

Key typeConcurrent requestsRequests per minute
Full key8300
Trial key260

Every response includes X-Request-Id (quote it when you contact support), X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency.

Past a limit the API answers HTTP 429. The error code rate_limited means too many requests per minute; concurrency means too many at once. A 429 can also mean temporary overload, in which case the response carries Retry-After: 5. Honour that header, wait, and retry. The Python SDK already retries a couple of times by default; you can raise it:

from openai import OpenAI

client = OpenAI(
    base_url="https://api.klingapis.com/v1",
    api_key="YOUR_API_KEY",
    max_retries=4,
)

r = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "ping"}],
)
print(r.choices[0].message.content)

If you hit concurrency often, add a semaphore in your own code that caps in-flight requests at 8. Billing is $0.15 per 1M input tokens and $0.50 per 1M output tokens; details are on the pricing page. Prompts are not used for training.

Troubleshooting checklist

Most integration problems come from a short list of causes. Work through it in order before you contact support.

The request fails right away

Check the base URL ends in /v1 and that your client appends /chat/completions itself. A doubled path such as /v1/v1 is a common slip when a library adds the suffix for you. Confirm the header is Authorization: Bearer followed by the key with no extra quotes or trailing newline from a copied file.

The model name is rejected

The only valid model ID is uncensored. Libraries sometimes default to a different name; set it explicitly in every call. A GET /v1/models request shows what the endpoint accepts.

You see 429 although traffic is light

Count open streams as well as requests. Each streamed request holds a concurrency slot until the stream finishes, so slow readers fill the eight slots of a full key fast. If the code is rate_limited, you passed the per-minute cap and need to space out calls. If the response has Retry-After: 5, the service was briefly overloaded and a short wait is enough. A trial key has tighter caps (2 concurrent, 60 per minute), so a script that works on a funded key can fail on a trial one.

Replies are cut off

If you set max_tokens, the reply stops at that number even mid-sentence. Raise it or remove it. Also make sure the prompt plus completion stays under the 100,000-token window.

JSON does not parse

Mention JSON in the prompt as well as in response_format, describe the exact keys, and keep a retry path. The balance header X-Balance-USD lets you confirm that failed attempts were not charged.

When you do write to support, include the X-Request-Id of the failing response, the time, and the request without your key. That is usually enough to find the call.

Questions and answers

Where is the documentation for Kling's video API?

Not here. This service is an independent text LLM API with no video or image endpoints. Use the video provider's own documentation for that.

Which model ID do I send?

Always uncensored. You can confirm it with GET /v1/models.

Can I use LangChain or other OpenAI-compatible clients?

Any client that lets you set a custom base URL and API key should work. Point it at https://api.klingapis.com/v1 and use the model uncensored.

What happens when I hit a rate limit?

You get HTTP 429 with the code rate_limited or concurrency. On temporary overload the 429 includes Retry-After: 5, so wait that long and try again.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.