How to Use Kimi with the OpenAI-Compatible API

You can use Kimi through the official OpenAI Python or Node.js SDK without installing a separate Kimi-specific client. Create a Kimi API key, set the client’s base URL to https://api.moonshot.ai/v1, and replace the model name with a current Kimi model such as kimi-k3. The request still goes to Moonshot AI—not OpenAI—and compatibility does not mean that every OpenAI endpoint or parameter behaves identically.

This guide covers the direct global Kimi API route. It shows how to migrate Chat Completions code, run Kimi with the OpenAI SDK in Python and Node.js, stream responses, preserve multi-turn history, move legacy function calls to tools, and test the integration before routing production traffic.

Important distinction: the phrase “Moonshot OpenAI API” normally refers to Moonshot’s OpenAI-compatible interface. You use an OpenAI client library, but authentication, models, billing, rate limits, and inference are provided by Kimi’s API platform.

The three values that route an OpenAI client to Kimi

For a basic Chat Completions application, the provider switch is controlled by three values:

Official Kimi OpenAI-compatible API base URL and request configuration
Official Kimi API configuration showing the OpenAI-compatible connection pattern and endpoint setup. Screenshot captured September 8, 2026.
SettingDirect global Kimi valueWhat it changes
api_keyYour Kimi or Moonshot API keyAuthenticates the request with Kimi’s platform
base_urlhttps://api.moonshot.ai/v1Routes SDK calls to Moonshot instead of the SDK’s default provider
modelFor example, kimi-k3Selects the Kimi model that processes the request

The familiar messages array, assistant response object, streaming option, and modern tool-call structure can remain close to an OpenAI Chat Completions integration. The three changed values are enough for a first request, but they are not enough to prove that a production application is fully portable.

Before you start: direct Moonshot API or a third-party gateway?

Kimi models can appear behind several providers. A gateway may also accept the OpenAI SDK, but it can have its own API key, base URL, model aliases, prices, limits, logging rules, and feature support.

  • Direct Kimi API: uses a key created on the Kimi API Platform and the global base URL shown in this guide.
  • Third-party inference provider: uses that provider’s key, endpoint, model ID, balance, and documentation.
  • Self-hosted OpenAI-compatible server: uses the URL and authentication configured for your own inference stack.

Do not combine a Moonshot key with another provider’s endpoint, or copy a third-party model slug into a direct Kimi request. This article deliberately avoids provider-specific aliases and covers the direct global service.

Keys can also be isolated by Kimi platform or region. A key must be used with the matching platform endpoint. If a seemingly valid key produces a 401 response, confirm where the key was issued before changing application code.

Create and store the API key

Sign in to the Kimi API Platform, open the API Keys console, and create a key. Store it as a server-side environment variable rather than embedding it in source code.

# macOS or Linux
export MOONSHOT_API_KEY="your_kimi_api_key"
# Windows PowerShell, current session
$env:MOONSHOT_API_KEY="your_kimi_api_key"

Never send the key to browser JavaScript, a mobile application binary, a public Git repository, analytics software, or client-visible error messages. A browser or mobile app should call your own authenticated backend, and the backend should call Kimi.

Run a transport smoke test before installing an SDK

A raw cURL test separates provider configuration from framework or application problems. Test the model-list endpoint first, then send one minimal completion.

1. Check the models available to your key

curl https://api.moonshot.ai/v1/models \\
  -H "Authorization: Bearer $MOONSHOT_API_KEY"

The response should contain a data array with model IDs and capability information. This check is more reliable than assuming that an ID copied from an older tutorial is still available to your account.

2. Send a minimal Chat Completion

curl https://api.moonshot.ai/v1/chat/completions \\
  -H "Authorization: Bearer $MOONSHOT_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "model": "kimi-k3",
    "messages": [
      {
        "role": "system",
        "content": "Answer accurately and concisely."
      },
      {
        "role": "user",
        "content": "Explain API compatibility in three short bullets."
      }
    ]
  }'

If the model-list request and this completion both work, the key, endpoint, account, and basic model access are probably configured correctly. You can then move the same values into an SDK client.

Use Kimi with the OpenAI Python SDK

Kimi’s global API documentation supports the official OpenAI Python package. Install or update version 1.x or later:

python -m pip install --upgrade "openai>=1.0"

Create a file named kimi_example.py:

import os


from openai import OpenAI




api_key = os.getenv("MOONSHOT_API_KEY")
if not api_key:
    raise RuntimeError(
        "MOONSHOT_API_KEY is not set. Add it to your server environment."
    )


client = OpenAI(
    api_key=api_key,
    base_url="https://api.moonshot.ai/v1",
)


response = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {
            "role": "system",
            "content": "You are a concise technical assistant.",
        },
        {
            "role": "user",
            "content": "Explain prefix caching in three short bullets.",
        },
    ],
)


message = response.choices[0].message.content
if not message:
    raise RuntimeError("The API returned no final message content.")


print(message)

Run it with:

python kimi_example.py

What changed from a typical OpenAI client?

  1. The environment variable now contains a Kimi API key.
  2. The client has an explicit base_url pointing to Kimi.
  3. The request uses a Kimi model ID.

The OpenAI package acts as the HTTP client and response parser. It does not cause the request to be billed by OpenAI, and an OpenAI API key is not accepted in place of a Kimi key.

Use Kimi with the OpenAI Node.js SDK

Install the official OpenAI package in a Node.js 18 or later project:

npm install openai

Create kimi-example.mjs:

import OpenAI from "openai";


const apiKey = process.env.MOONSHOT_API_KEY;


if (!apiKey) {
  throw new Error(
    "MOONSHOT_API_KEY is not set. Add it to your server environment."
  );
}


const client = new OpenAI({
  apiKey,
  baseURL: "https://api.moonshot.ai/v1",
});


const response = await client.chat.completions.create({
  model: "kimi-k3",
  messages: [
    {
      role: "system",
      content: "You are a concise technical assistant.",
    },
    {
      role: "user",
      content: "Explain Chat Completions in three short bullets.",
    },
  ],
});


const message = response.choices[0]?.message?.content;


if (!message) {
  throw new Error("The API returned no final message content.");
}


console.log(message);

Run the file:

node kimi-example.mjs

The Node.js property is written as baseURL, while the Python client uses base_url. Both point to the same direct global Kimi API base URL.

What “OpenAI-compatible” actually covers

Compatibility is best understood in layers rather than as a single yes-or-no label.

OpenAI-compatible Kimi API layers showing reusable SDK features, required audits, and non-automatic compatibility.
Compatibility layerCurrent Kimi behaviorMigration decision
OpenAI Python and Node.js clientsSupported for the documented API formatReuse the SDK with a new key and base URL
Chat Completions request and response shapeOpenAI-compatibleReuse the messages-based request structure
Bearer authentication patternSame header pattern, different provider keyUse a Kimi key, not an OpenAI key
All OpenAI endpointsNot promised as a blanket compatibility guaranteeCheck each endpoint in Kimi’s current documentation
Model namesKimi-specificReplace the model ID and verify it through /v1/models
Sampling and reasoning parametersModel-specific constraints applyAudit the request instead of copying every value
Modern tool callsSupportedUse tools and tool_calls
Legacy functions parameterNot supportedMigrate to the modern tools format
StreamingSupported through server-sent eventsTest content, reasoning, finish state, and usage parsing

Do not assume Responses API compatibility

At the verification date, Kimi’s official OpenAI migration page explicitly lists Chat Completions and selected Files endpoints in its compatibility scope. It does not list OpenAI’s /v1/responses endpoint.

That does not prove that no tool or adapter can translate a Responses-style request. It means a direct migration should use Kimi’s documented Chat Completions interface unless the current official documentation explicitly adds the other endpoint you need.

Audit model-specific parameters before switching providers

The most common migration mistake is copying an entire OpenAI request object and changing only the endpoint. Current Kimi models impose model-specific parameter rules, and values that are accepted by another provider can return invalid_request_error on Kimi.

Parameterkimi-k3kimi-k2.7-codekimi-k2.6
Reasoning controlTop-level reasoning_effort: low, high, or maxThinking stays enabledThinking can be enabled or disabled
temperatureFixed at 1.0Fixed at 1.01.0 with thinking, 0.6 without thinking
top_pFixed at 0.95Fixed at 0.95Fixed at 0.95
nFixed at 1Fixed at 1Fixed at 1
Presence and frequency penaltiesFixed at 0Fixed at 0Fixed at 0
tool_choice: requiredSupportedNot supportedNot supported

When the documentation calls a value “fixed,” sending a different value can cause an error. The safest initial migration is to remove sampling parameters such as temperature, top_p, n, and penalties unless your selected model’s current reference explicitly requires them.

Set K3 reasoning effort only when needed

K3 reasons by default. You can control its effort with a top-level request field:

response = client.chat.completions.create(
    model="kimi-k3",
    reasoning_effort="low",
    messages=[
        {
            "role": "user",
            "content": "Classify this support request into one category.",
        }
    ],
)

Use lower effort for bounded tasks only after evaluating accuracy. Avoid changing reasoning effort in the middle of an active conversation because it can affect prefix-cache reuse.

Control K2.6 thinking through extra_body

The OpenAI SDK does not expose Kimi’s thinking object as a standard argument. Pass it through extra_body when you deliberately use K2.6 without thinking:

response = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[
        {
            "role": "user",
            "content": "Rewrite this sentence in plain English.",
        }
    ],
    extra_body={
        "thinking": {
            "type": "disabled"
        }
    },
)

Do not copy this setting to K3. K3 uses reasoning_effort, while K2.7 Code keeps thinking enabled and rejects attempts to disable it.

Stream Kimi responses without mixing reasoning and final content

Streaming is useful for long answers because the client receives incremental server-sent event chunks instead of waiting for the entire completion. Set stream=True in Python or stream: true in Node.js.

stream = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {
            "role": "user",
            "content": "Create a five-step migration checklist.",
        }
    ],
    stream=True,
    stream_options={
        "include_usage": True
    },
)


final_usage = None


for chunk in stream:
    if chunk.choices:
        delta = chunk.choices[0].delta


        # Render final answer content to the user.
        if delta.content:
            print(delta.content, end="", flush=True)


        # Kimi reasoning models may expose reasoning_content separately.
        # Do not concatenate it into the visible final answer by accident.
        reasoning = getattr(delta, "reasoning_content", None)
        if reasoning:
            pass


    if getattr(chunk, "usage", None):
        final_usage = chunk.usage


print()


if final_usage:
    print("Token usage:", final_usage)

Applications should define separate handling rules for reasoning and final content. A simple user interface normally displays content. If your backend needs reasoning_content for an officially documented workflow, keep it structurally separate rather than merging both fields into one answer.

When token accounting matters, enable stream_options.include_usage and test the exact SDK version used in production. Do not assume that a parser written around another provider’s final streaming chunk will capture Kimi usage in every case.

Preserve multi-turn conversations correctly

The Kimi API is stateless. It does not automatically remember a previous request. Your application must store the conversation history and send the relevant messages again on the next call.

messages = [
    {
        "role": "system",
        "content": "You are a precise API migration assistant.",
    },
    {
        "role": "user",
        "content": "Give this migration project a short name.",
    },
]


first = client.chat.completions.create(
    model="kimi-k3",
    messages=messages,
)


# Preserve the complete assistant message, including provider-specific
# fields that may be required for reasoning continuity.
assistant_message = first.choices[0].message.model_dump(
    exclude_none=True
)


messages.append(assistant_message)
messages.append(
    {
        "role": "user",
        "content": "Now turn that name into a three-step rollout plan.",
    }
)


second = client.chat.completions.create(
    model="kimi-k3",
    messages=messages,
)


print(second.choices[0].message.content)

Appending only the assistant’s visible text can discard fields used by Preserved Thinking. For K3, K2.7 Code, and applicable K2.6 thinking workflows, pass the complete assistant message back as returned unless the model documentation says otherwise.

Long-running chats also require context management. Store the source conversation in your application, estimate token use, and summarize orremove older turns before the total request exceeds the selected model’s context window.

Migrate legacy functions to modern tools

Kimi supports the modern tool-call format but not the deprecated OpenAI functions parameter. Applications built on an older function-calling implementation need a structural migration.

Legacy patternKimi-compatible pattern
Request field functionsRequest field tools
Request field function_callUse tool_choice when supported
Assistant field function_callAssistant field tool_calls
Function result without a call identifierA tool message with the matching tool_call_id

A modern tool definition follows this general shape:

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_order_status",
            "description": "Return the current status of an order.",
            "parameters": {
                "type": "object",
                "properties": {
                    "order_id": {
                        "type": "string",
                        "description": "The order identifier."
                    }
                },
                "required": ["order_id"]
            }
        }
    }
]

Your application—not the model—executes the function. It must validate the arguments, run the permitted operation, and return the result as a tool message. A complete implementation should also enforce timeouts, argument validation, authorization, and an allowlist of available tools.

Model choice affects tool behavior. K3 supports tool_choice values auto, none, and required. K2.6 and K2.7 Code do not support required, so a request copied from another provider can fail even though the tool schema itself is valid.

Choose a current Kimi model for the integration

Do not treat every Kimi model ID as an interchangeable alias. Select a model for the workload, then test its parameters and output structure separately.

Model IDPractical starting pointMain migration consideration
kimi-k3Default choice for new general, reasoning, knowledge-work, and advanced agent integrationsAlways reasons; uses reasoning_effort and a 1M-token context window
kimi-k2.7-codeCode-focused workflowsThinking remains enabled; tool_choice: required is unavailable
kimi-k2.7-code-highspeedThe same coding model when lower output latency is more importantUses the same model constraints as standard K2.7 Code
kimi-k2.6General-purpose workflows that need a selectable thinking or non-thinking modePass the thinking object through extra_body in the OpenAI SDK

At this article’s verification date, Kimi’s documentation stated that kimi-k2.5 and the moonshot-v1 series were unavailable to newly registered users and scheduled for a full platform sunset on August 31, 2026. They should not be used as the foundation of a new integration.

Use GET /v1/models during setup and deployment checks. A 404 can indicate either an incorrect model name or lack of access for the current account.

For a fuller comparison of current IDs, context windows, and capabilities, see the internal Kimi API models guide.

Use a production cutover gate, not a successful demo

A single successful prompt proves that the route works. It does not prove that the application is ready to switch providers. Run the following checks against the same SDK version, request templates, proxy, and infrastructure that production will use.

Kimi API production migration checklist covering transport tests, application validation, and the final production gate.Kimi API production migration checklist covering transport tests, application validation, and the final production gate.
  1. Model discovery: query /v1/models and confirm the configured model is available.
  2. Basic completion: test system and user messages with no optional parameters.
  3. Parameter audit: remove inherited sampling values and add only parameters supported by the selected Kimi model.
  4. Streaming: verify content chunks, completion state, disconnect behavior, and usage parsing.
  5. Conversation continuity: test several turns while preserving the complete assistant response.
  6. Tool loop: validate tool schemas, multiple calls, argument parsing, tool results, and the selected model’s tool_choice rules.
  7. Structured output: test every response schema your application parses rather than assuming provider parity.
  8. Error mapping: verify that 400, 401, 404, 429, 500, 503, and 504 responses reach the correct retry oruser-message path.
  9. Timeout policy: use streaming for long requests and set application, proxy, and load-balancer timeouts deliberately.
  10. Secret handling: confirm that the Kimi key never reaches client code, analytics, source maps, or verbose logs.
  11. Usage visibility: record the selected model, latency, status, request ID, and token usage without logging sensitive prompts by default.
  12. Rollback: keep provider configuration outside business logic so traffic can be restored to the previous route if the evaluation fails.

Run this gate on real examples from your application—not only a “Hello” prompt. Measure output quality, tool success, schema validity, latency, retry volume, and total workflow cost.

Troubleshoot Kimi migration errors by failure layer

SymptomLikely layerWhat to check
400 invalid_request_errorRequest schema orparameter compatibilityRemove unsupported values, confirm required fields, and compare the request with the selected model’s parameter reference
401 authentication errorKey, header, orplatform mismatchConfirm the Bearer header, the environment variable, and that the key belongs to the endpoint being called
404 model not foundModel ID oraccount accessCall /v1/models, check spelling, and confirm that the account can access the model
429 engine_overloaded_errorProvider capacityRespect Retry-After, reduce concurrency, and retry with exponential backoff
429 exceeded_current_quota_errorBalance oraccount quotaCheck the Kimi API balance and billing status; repeated retries do not restore balance
429 rate_limit_reached_errorConcurrency, RPM, TPM, orTPD limitInspect the error type, reduce the relevant load, wait for reset, orreview the account tier
504 after a long waitNon-streaming timeoutUse streaming, shorten the request, and review proxy and client timeouts

Do not apply one universal retry rule to every 429. Retrying with backoff can help with temporary engine overload, but it does not fix an empty balance. A daily token limit may require waiting for the reset, while a concurrency limit requires fewer simultaneous requests.

For a complete diagnostic reference, see the internal Kimi API errors and troubleshooting guide.

What not to copy unchanged from an OpenAI integration

  • An OpenAI API key.
  • OpenAI model names.
  • A default OpenAI base URL.
  • An assumption that every OpenAI endpoint is supported.
  • Legacy functions orfunction_call fields.
  • Sampling values that conflict with Kimi’s fixed model parameters.
  • A parser that merges reasoning and final answer content.
  • A conversation store that keeps only visible assistant text.
  • A retry handler that treats every 429 as temporary overload.
  • Client-side code that exposes the provider key.

The fastest reliable migration is not the one with the fewest edited lines. It is the one that keeps the client abstraction while explicitly testing every provider-dependent behavior.

Frequently asked questions

Is the Kimi API compatible with OpenAI?

Yes, Kimi documents compatibility with the OpenAI Chat Completions request and response format and supports the official OpenAI Python and Node.js SDKs. Compatibility is not a guarantee that every OpenAI endpoint, model parameter, orprovider behavior is identical.

Can I use the OpenAI Python SDK with Kimi?

Yes. Initialize OpenAI with your Kimi API key and set base_url to https://api.moonshot.ai/v1. Then use a current Kimi model ID in client.chat.completions.create().

Do I need an OpenAI API key?

No. The SDK is only the client library. Direct Kimi requests require a key created on the matching Kimi API platform, and usage is billed against that Kimi API account rather than an OpenAI account.

What is the Kimi API base URL?

The direct global SDK base URL is https://api.moonshot.ai/v1. The full Chat Completions endpoint is https://api.moonshot.ai/v1/chat/completions. A third-party provider will use its own endpoint instead.

Is Kimi a complete drop-in replacement for OpenAI?

Not for every application. Basic Chat Completions code can be highly portable, but model names, reasoning controls, sampling constraints, tool behavior, endpoint coverage, streaming details, rate limits, and billing remain provider-specific.

Does Kimi support OpenAI’s Responses API?

The official compatibility page reviewed for this article lists Chat Completions and selected Files endpoints, not /v1/responses. Use the documented Chat Completions route unless Kimi’s current documentation explicitly confirms the additional endpoint oryou intentionally use a tested translation layer.

Which Kimi model should a new integration start with?

Kimi’s current quickstart recommends beginning with kimi-k3 when you are unsure. Coding-focused workloads can evaluate kimi-k2.7-code orits HighSpeed route, while K2.6 is useful when a general-purpose workflow needs selectable thinking and non-thinking modes.

Official sources and update methodology

This guide was verified on August 29, 2026. The implementation details were checked against Kimi’s official API overview, migration guide, model list, parameter reference, streaming guide, multi-turn guide, model-list endpoint, and error documentation. Model availability, endpoints, limits, and parameter rules can change, so production systems should query the model-list endpoint and recheck the linked documentation during upgrades.

Related internal resources: review current Kimi API models, understand Kimi API pricing and token costs, ordiagnose failures with the Kimi API troubleshooting guide.

Last verified: August 29, 2026

Mohamed Hossam El-Din
Mohamed Hossam El-Din

Mohamed Hossam El-Din is a content editor at Thinkly for Digital Business, responsible for kimi-ai.free. He is a social work student at Helwan University, and he came to Kimi the way most of its users do: with long PDFs to read, research to gather, and reports to write. That is the angle he writes from — long-context work, document analysis, and research, tested on a live account before it is written about. He writes in English and Arabic. Every feature covered here was used first; error messages published on this site are errors that actually appeared. When a claim cannot be verified against Moonshot AI's official documentation, the article says so.

Articles: 49