Call the Kimi K3 API with the OpenAI SDK
A minimal, verifiable Python integration using Moonshot's OpenAI-compatible endpoint and the kimi-k3 model ID.
Prerequisites
Prepare the smallest safe environment before making the request.
- Python 3.9 or newer
- A Moonshot platform API key
- A local environment variable; never commit the key
- Network access to api.moonshot.cn
Implementation
Install the SDK, configure the client and make one streaming request.
- 1
Install the OpenAI SDK
Use the maintained Python client supported by Moonshot's compatibility layer.
Terminalpython3 -m pip install --upgrade 'openai>=1.0' - 2
Store the API key
Keep the credential outside source control and load it from the process environment.
Terminalexport MOONSHOT_API_KEY='replace-with-your-key' - 3
Create the client and stream a response
Set Moonshot's base URL, select kimi-k3 and request the currently supported max reasoning effort.
Pythonimport os from openai import OpenAI client = OpenAI( api_key=os.environ["MOONSHOT_API_KEY"], base_url="https://api.moonshot.cn/v1", ) stream = client.chat.completions.create( model="kimi-k3", messages=[ {"role": "user", "content": "Plan a safe migration for this service."} ], reasoning_effort="max", stream=True, ) for chunk in stream: if not chunk.choices: continue delta = chunk.choices[0].delta reasoning = getattr(delta, "reasoning_content", None) if reasoning: print(reasoning, end="", flush=True) if delta.content: print(delta.content, end="", flush=True) - 4
Preserve complete assistant messages
For tool calls or later turns, append the complete assistant message object, including reasoning and tool-call fields, instead of reconstructing only visible text.
Verify the integration
A successful HTTP response is not enough; check the fields your Agent depends on.
- The returned model or request configuration identifies kimi-k3
- Streaming emits content deltas and terminates cleanly
- The request accepts reasoning_effort=max
- Usage data is captured for cost and latency monitoring
Troubleshooting
Start with the documented constraints before adding retries or wrappers.
| Symptom | Likely cause | Direct fix |
|---|---|---|
| 401 or authentication error | Missing, invalid or wrong-platform key | Regenerate the Moonshot key and verify MOONSHOT_API_KEY in the current shell |
| Unsupported parameter error | A sampling value or reasoning effort outside the current contract | Use the documented fixed sampling values and reasoning_effort=max |
| Tool loop loses state | Only visible assistant text was appended | Carry the complete assistant message into the next request |
Official references
Use these pages as the live contract when the API changes.
API FAQ
Answers for the first production integration.
Specify the Agent before production integration
Document tools, data boundaries, cost limits and acceptance scenarios. Model credentials and provisioning remain part of the implementation.

