Open History to see the last commit
1/**
2 * Moonshot (Kimi) — international surface. Spec is
3 * platform.kimi.ai/docs/openapi.json (`servers.url` = api.moonshot.ai).
4 * Keys are region-bound: this host accepts international keys; a CN key
5 * 401s here the same way an international key 401s on api.moonshot.cn.
6 * Generation is POST /v1/chat/completions; files, batches, billing, and
7 * token-estimate classify as platform.
8 *
9 * The spec's chat request is a per-model union, as on the China host. A
10 * model whose own branch takes only the `thinking.type` switch gets a
11 * toggle from it. A failed spec read leaves the stored value alone.
12 */
13import {
14 applyReplay,
15 KIMI_THINKING_URL,
16 loadReplayDoc,
17 parseKimiReplay,
18} from '../provider-replay.ts'
19import { docsReport, docsRun, tryDocs, unavailable } from '../model-facts.ts'
20import { moonshotModelPricing } from '../moonshot-pricing.ts'
21import {
22 classifyOpenAiCompat,
23 listOpenAiCompatibleModels,
24} from '../openai-compat.ts'
25import {
26 compatGenerationEndpointId,
27 flaggedChatModalities,
28 moonshotModelActivity,
29} from '../model-meta.ts'
30import { fetchOpenApi } from '../types.ts'
31import type {
32 ListModelsResult,
33 ModelInfo,
34 ProviderConfig,
35 ProviderSecrets,
36 SpecFetchResult,
37} from '../types.ts'
38import { moonshotChatFacts } from './moonshotai-cn.ts'
39import type { MoonshotHost } from './moonshotai-cn.ts'
40
41const MOONSHOT_OPENAPI_URL = 'https://platform.kimi.ai/docs/openapi.json'
42const MOONSHOT_MODELS_URL = 'https://api.moonshot.ai/v1/models'
43
44const HOST: MoonshotHost = {
45 label: 'moonshot',
46 server: 'https://api.moonshot.ai',
47 specUrl: MOONSHOT_OPENAPI_URL,
48}
49
50async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
51 const { spec, hash } = await fetchOpenApi(MOONSHOT_OPENAPI_URL)
52 return {
53 specs: [spec],
54 sources: [{ url: MOONSHOT_OPENAPI_URL, hash }],
55 outputStrategy: 'post-200',
56 }
57}
58
59async function listModels(
60 env: ProviderSecrets,
61 kv?: KVNamespace,
62): Promise<ListModelsResult> {
63 const listed = await listOpenAiCompatibleModels({
64 providerId: 'moonshot',
65 url: MOONSHOT_MODELS_URL,
66 env,
67 envVar: 'MOONSHOT_API_KEY',
68 activity: moonshotModelActivity,
69 extend: async (row) =>
70 row.supports_image_in !== undefined || row.supports_video_in !== undefined
71 ? { modalities: flaggedChatModalities(row) }
72 : {},
73 })
74 if (listed.models.length === 0) return listed
75 const pricing = await moonshotModelPricing(kv)
76 const replay = await loadReplayDoc(KIMI_THINKING_URL, kv)
77 const replayIds = new Set(parseKimiReplay(replay.text))
78 const docs = docsRun()
79 const chat = await tryDocs(docs, MOONSHOT_OPENAPI_URL, (cached) =>
80 cached(kv, MOONSHOT_OPENAPI_URL, async () => {
81 const { spec, hash } = await fetchOpenApi(MOONSHOT_OPENAPI_URL)
82 return moonshotChatFacts(spec, hash, HOST)
83 }),
84 )
85 const toggle = (rawId: string): Partial<ModelInfo> => {
86 if (!chat) return unavailable('reasoning')
87 const facts = chat[rawId]
88 // Only the switch is taken here: the listing and the schema walk
89 // already supply this host's other facts.
90 return facts?.reasoning?.mode === 'toggle'
91 ? {
92 reasoning: facts.reasoning,
93 factSources: { reasoning: facts.factSources.reasoning },
94 }
95 : {}
96 }
97 return {
98 ...listed,
99 models: listed.models.map((model) => {
100 const over = {
101 ...pricing(model.rawId),
102 ...toggle(model.rawId),
103 }
104 const enriched: ModelInfo = {
105 ...model,
106 ...over,
107 // `created` is one clock on every id and it moves forward on each
108 // list, so it is not a release date. `cleared` drops a value a
109 // previous poll stored from it.
110 releasedAt: null,
111 absent: { ...model.absent, ...over.absent, releasedAt: 'cleared' },
112 }
113 return replayIds.has(model.rawId)
114 ? applyReplay(enriched, replay.source)
115 : enriched
116 }),
117 docsFailures: docsReport(docs),
118 }
119}
120
121export const provider: ProviderConfig = {
122 id: 'moonshot',
123 // Hosts' `maker/model` ids (Novita `moonshotai/kimi-k3`).
124 modelNamespaces: ['moonshotai'],
125 displayName: 'Moonshot',
126 authEnvVar: 'MOONSHOT_API_KEY',
127 specSourceUrl: MOONSHOT_OPENAPI_URL,
128 modelsEndpoint: MOONSHOT_MODELS_URL,
129 defaultDerivation: 'upstream-spec',
130 fetchSpec,
131 listModels,
132 classify: classifyOpenAiCompat,
133 generationEndpointId: ({ activity }) =>
134 compatGenerationEndpointId(activity, 'v1/'),
135}