Make a Kimi API request in Python using an environment-loaded key and visible completion details. Keep the normal request and a deliberate wrong-model failure easy to reproduce.
What you'll build
You will create a small script that asks for a concise explanation, prints the response and usage, and exits clearly if the provider returns an API error. Its purpose is to establish a request baseline you can inspect. It does not claim to be a benchmark, a complete coding agent or an observed account run.
The Kimi quickstart supports the OpenAI Python SDK with the documented Moonshot base URL; this example uses Chat Completions and kimi-k3. Official documentation.
Keep the fixture deliberately small. A successful result should show that the credential, endpoint, model and parser agree before you introduce repository files, tools or conversation state. If an optional feature fails later, return to this baseline to separate the new feature from account setup.
Prerequisites
Complete the Kimi API-key guide in the intended project. Confirm its billing and spending controls before running the script, then make the key available to the Python process as MOONSHOT_API_KEY.
Use a Python environment dedicated to the application and record the installed client version. If your editor and terminal select different interpreters, a package can appear installed while the script cannot import it. Check the interpreter used for execution before changing the request code.
The example’s model can be overridden with MOONSHOT_MODEL, but its parameter choice is intended for the shown K3 request. If you select another family, inspect the model parameter reference and adapt the settings rather than assuming the override makes every combination valid.
Install SDK
python -m pip install --upgrade openai
Run the installation command in the same environment that will execute the file. Save the script as first_moonshot.py. Keep the secret in protected environment configuration; do not edit the source to insert the credential for convenience. This makes the example shareable once its outputs and surrounding files are checked for sensitive material.
python first_moonshot.py
That command sends an actual provider request when the key is configured. Run it only in the intended account and inspect the result before allowing repeated calls. The tutorial text itself does not assert that your account has executed the example.
Full script
import os
import sys
from openai import OpenAI, APIStatusError
model = os.environ.get("MOONSHOT_MODEL", "kimi-k3")
if "--bad-model" in sys.argv:
model = "ai-api-hub-invalid-model"
client = OpenAI(
api_key=os.environ["MOONSHOT_API_KEY"],
base_url="https://api.moonshot.ai/v1",
timeout=60.0,
max_retries=0,
)
try:
result = client.chat.completions.create(
model=model,
messages=[{"role":"user","content":"Explain why a code patch needs a test in one sentence."}],
reasoning_effort="low",
max_tokens=1024,
)
print(result.choices[0].message.content)
print("finish_reason:", result.choices[0].finish_reason)
print(result.usage.model_dump_json() if result.usage else "Usage unavailable")
except APIStatusError as exc:
print(f"HTTP {exc.status_code}")
print(exc.response.text)
raise SystemExit(1)
finally:
client.close()
The explicit timeout bounds how long the client waits, while disabling automatic retries makes a single invocation easier to inspect. A production worker can add a deliberate retry policy after separating retryable service conditions from account and request errors. Keep that policy in one layer so attempt counts remain understandable.
The script prints the completion reason because visible text alone does not establish that the response finished as intended. It also prints returned usage when present. Preserve those fields with the safe fixture so later prompt and model changes can be compared against the same baseline.
Expected output
The following is schematic output, not a captured inference response. The actual wording, completion state and usage come from your authorized run. Treat the numbers only as illustration of the output format, not as a measurement of the model or a forecast.
A test checks that the patch produces the intended behavior without breaking existing behavior.
finish_reason: stop
{"prompt_tokens":12,"completion_tokens":18,"total_tokens":30}
Inspect the actual sentence against the task. If the result is empty, truncated or unexpectedly long, keep that observation and inspect the returned state before changing the prompt. A useful first run is one you can explain, even when it exposes a configuration or parameter problem.
One deliberate error and its fix
python first_moonshot.py --bad-model
The branch sends ai-api-hub-invalid-model instead of the normal model identifier. Keep the credential configured so the request reaches model validation. The script exposes the returned rejection and stops; restore the ordinary command to use the supported model again.
The following error-field excerpt was captured on 2026-09-12 15:53 UTC from an authorized HTTP request to the same provider interface. It used harmless connection-validation input and small output settings. This records the provider’s rejection; it does not claim that the Python SDK example itself was executed.
These are normalized captured fields with the message preserved verbatim. They are not a reconstructed full provider response envelope. Empty fields and request identifiers are omitted.
{
"http_status": 404,
"type": "resource_not_found_error",
"message": "Not found the model ai-api-hub-invalid-model or Permission denied"
}
Fix the deliberate error by restoring a current accessible model identifier. Do not resend the invalid identifier in a retry loop. If the ordinary request also fails, inspect that response independently because permission, funding and request validation can fail at different stages. Official error reference.
Keep the missing-key startup check as an additional local configuration guard. It tests whether the process can read its environment; it does not establish that the provider accepted the key or evaluated the requested model.
What this request costs
Estimate your API costs
Your text and estimates stay in this browser. No API requests are sent to model providers.
Loading verified model records…
Enter your returned usage in the Kimi workload calculator. Keep the selected model and applicable charge categories visible when comparing the result with a larger application scenario.
A single short request does not establish the cost of a tool-using agent. Before extending the script, list the additional model stages and expected retry or repair work. Measure those stages independently and compare cost per accepted task rather than multiplying a demonstration response without checking its representativeness.
Next steps
Add one requirement at a time: a safe document fixture, a requested output structure or a narrowly defined tool. Keep the original baseline as a separate test. Validate the output before any downstream side effect and define the state for a refusal, invalid structure or incomplete stream.
Read Kimi error handling, shared capacity planning and model migration guidance before making the worker unattended.
Finish by recording the model, client version, safe input, accepted result and returned usage from your own run. If you later change the model or request interface, reuse that record to explain what changed and which assumptions still need evaluation.
Last verified · Source ↗
Frequently asked questions
Which Python client does this use?
Where does the key come from?
Was the displayed output captured from a live call?
What does the deliberate error test?
Can I switch the model without inspecting parameters?
What should I add before unattended use?
Sources
- Kimi API quickstart ↗
- Kimi model list ↗
- Inference pricing ↗
- Recharge and limits ↗
- Error reference ↗
- Organization management ↗
- Account and billing ↗
- Context caching ↗
- Batch API ↗
- Model parameters ↗
Last verified · Source ↗