@molecule/api-ai-moonshot
Provider bond · ai · API (Node) · v1.1.4 · Apache-2.0
Moonshot (Kimi) AI provider for molecule.dev
npm install @molecule/api-ai-moonshotnpm · Source on GitHub · Implements @molecule/api-ai
How it works
@molecule/api-ai-moonshot is a provider bond on the API (Node) side: it implements the ai core interface (@molecule/api-ai) with a concrete vendor or library behind it.
Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.
// npm install @molecule/api-ai-moonshot --workspace=api
import { setProvider, requireProvider } from '@molecule/api-ai'
import { provider } from '@molecule/api-ai-moonshot'
// Named registration — several AI providers can be bonded side by side
// (getProviderByName('moonshot') targets this one); the FIRST one
// registered also answers requireProvider() (see @molecule/api-ai).
setProvider('moonshot', provider) // reads MOONSHOT_API_KEY from the environment
let reply = ''
for await (const event of requireProvider().chat({
messages: [{ role: 'user', content: 'Hello!' }],
})) {
if (event.type === 'text') reply += event.content // or forward the chunk to the client (SSE)
}Works with: @molecule/api-bond, @molecule/api-i18n, @molecule/api-secrets
Secrets: MOONSHOT_API_KEY
Reference
Moonshot (Kimi) AI provider for molecule.dev.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
// npm install @molecule/api-ai-moonshot --workspace=api
import { setProvider, requireProvider } from '@molecule/api-ai'
import { provider } from '@molecule/api-ai-moonshot'
// Named registration — several AI providers can be bonded side by side
// (getProviderByName('moonshot') targets this one); the FIRST one
// registered also answers requireProvider() (see @molecule/api-ai).
setProvider('moonshot', provider) // reads MOONSHOT_API_KEY from the environment
let reply = ''
for await (const event of requireProvider().chat({
messages: [{ role: 'user', content: 'Hello!' }],
})) {
if (event.type === 'text') reply += event.content // or forward the chunk to the client (SSE)
}
Type
provider
Installation
npm install @molecule/api-ai-moonshot @molecule/api-ai @molecule/api-bond @molecule/api-i18n @molecule/api-secrets
API
Interfaces
MoonshotConfig
Configuration for Moonshot.
interface MoonshotConfig {
/** API key. Defaults to MOONSHOT_API_KEY env var. */
apiKey?: string
/** Default model. Defaults to 'kimi-k3'. */
defaultModel?: string
/** Maximum tokens for completions. */
maxTokens?: number
/** Base URL override (for proxies). Defaults to 'https://api.moonshot.cn'. */
baseUrl?: string
/**
* Chat-completions path appended to `baseUrl`. Defaults to
* `/v1/chat/completions` (Moonshot-direct puts the version in the path). Set
* this when the same open-weight model is served by a US OpenAI-compatible
* host whose version prefix lives in the base URL instead — e.g. DeepInfra:
* `baseUrl='https://api.deepinfra.com/v1/openai'` + `completionsPath='/chat/completions'`.
*/
completionsPath?: string
/**
* Optional catalog-id → upstream-model-id map, applied to the outbound request
* ONLY. Lets a US OpenAI-compatible host (DeepInfra) receive its namespaced id
* (`moonshotai/Kimi-K3`) while the rest of the platform — pricing, cost
* ceilings, display — keeps using the canonical catalog id (`kimi-k3`). An id
* not in the map passes through unchanged.
*/
modelMap?: Record<string, string>
/** Called on each rate-limited/overloaded upstream response, before any retry sleep. */
onRateLimit?: AiRateLimitCallback
}
ProcessEnv
Process Env interface.
interface ProcessEnv {
MOONSHOT_API_KEY: string
/** Base URL override (for credential brokers / gateways / US OpenAI-compatible hosts). */
MOONSHOT_BASE_URL?: string
/** Chat-completions path override (see `MoonshotConfig.completionsPath`). */
MOONSHOT_COMPLETIONS_PATH?: string
}
Functions
createProvider(config)
Creates a Moonshot (Kimi) AI provider instance.
function createProvider(config?: MoonshotConfig): AIProvider
config— Moonshot-specific configuration (API key, model, max tokens, base URL).
Returns: An AIProvider backed by the Moonshot Chat Completions API.
Constants
provider
The provider implementation.
const provider: AIProvider
aiMoonshotSecretDefinitions
Secret definitions required by the Moonshot AI bond.
const aiMoonshotSecretDefinitions: SecretDefinition[]
Core Interface
Implements @molecule/api-ai interface.
Bond Wiring
Setup function to register this provider with the bond system:
import { bond } from '@molecule/api-bond'
import { provider } from '@molecule/api-ai-moonshot'
export function setupAiMoonshot(): void {
bond('ai', 'moonshot', provider)
}
Injection Notes
Requirements
Peer dependencies:
@molecule/api-ai^1.0.1@molecule/api-bond^1.0.1@molecule/api-i18n^1.0.1@molecule/api-secrets^1.0.1
Environment Variables
MOONSHOT_API_KEY(required) — Moonshot API key- Setup: Create an API key in the Moonshot AI console.
- Get it here: https://platform.moonshot.ai/console/api-keys
- Example:
sk-...
Runtime Dependencies
@molecule/api-ai@molecule/api-bond@molecule/api-i18n@molecule/api-secrets
Config: MOONSHOT_API_KEY (SERVER-side only) plus an optional default model id/base URL.
Missing MOONSHOT_API_KEY fails fast: the provider throws naming the exact env var on
first use (the exported provider is a lazy proxy, so this fires on the first chat() call,
not at bond/module-load time) — it never silently sends an empty key.
Error message disambiguation: a plain 400 that ISN'T a context-length error (bad param, malformed tool schema) gets its own non-retryable message distinct from the generic "AI service error. Please try again." used for retryable failures.
Reasoning effort (KIMI_REASONING_EFFORT, optional): when a call doesn't pass
params.thinking, the provider reads this env var — disabled (default) fully disables
thinking (fastest, least accurate); minimal | low | medium | high set the API's
reasoning_effort. Note: on kimi-k2.6 even minimal produces ~1000 chars of reasoning
per turn (~5x slower than disabled, but more reliable for complex multi-step tasks).
E2E Tests
Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual chat/AI screens, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip. The sandbox HAS an AI provider bonded, so the flow runs live end-to-end; AI output is NON-DETERMINISTIC, so assert on STRUCTURE/behavior, not exact text:
- A message sent through the real chat UI comes back as a RELEVANT AI reply — not an echo of the prompt, a hardcoded stub, or an empty bubble. Ask something with a checkable answer (e.g. "What is 2 + 2?") and confirm the response actually contains it ("4"), proving a live model answered.
- If the app streams, tokens render INCREMENTALLY — text grows word by
word in the UI, not one final blob dumped after a long frozen spinner. (A
streamed
chat()yieldstextchunks then a finaldone; a single late blob means the reply was awaited whole and streaming is broken.) - Multi-turn CONTEXT is preserved: a follow-up that refers back to the
previous turn (e.g. after "2 + 2", ask "now double that" -> understood as 8) works — proving the full
messageshistory is sent, not just the last line. - A provider failure (bad/missing key, rate limit, timeout) surfaces as a graceful in-UI error message, NOT a crash, blank screen, a spinner that never resolves, or an unhandled 500. Force one and watch the UI recover.
- The provider key + the provider call are SERVER-side only: the key
never reaches the browser (check the network tab, the JS bundle, and page
globals), and no route proxies arbitrary prompts to the model without auth
- a token cap — an open AI endpoint is an unbounded bill and abuse vector.