本文檔介紹如何在阿里雲百鍊平台通過OpenAI相容介面或DashScope SDK調用Kimi系列模型。
重要
本文檔僅適用於“中國大陸(北京)”地區。如需使用模型,需使用“中國大陸(北京)”地區的API Key。
模型介紹
Kimi 系列模型是由月之暗面公司(Moonshot AI)推出的大語言模型。
kimi-k2-thinking:僅支援深度思考模式,並通過
reasoning_content欄位展示思考過程,具有卓越的編碼和工具調用能力,適用於需要邏輯分析、規劃或深度理解的情境。Moonshot-Kimi-K2-Instruct:不支援深度思考,直接產生回複,響應速度更快,適用於需要快速直接回答的情境。
模型名稱 | 上下文長度 | 最大輸入 | 最大思維鏈長度 | 最大回複長度 | 輸入成本 | 輸出成本 |
(Token數) | (每百萬Token) | |||||
kimi-k2-thinking | 262,144 | 229,376 | 32,768 | 16,384 | $0.574 | $2.294 |
Moonshot-Kimi-K2-Instruct | 131,072 | 131,072 | - | 8,192 | $0.574 | $2.294 |
快速開始
API 使用前提:已準備工作:擷取與配置 API Key並完成配置API Key到環境變數(準備下線,併入配置 API Key)。如果通過SDK調用,需要安裝 OpenAI 或 DashScope SDK。
OpenAI相容
Python
範例程式碼
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="kimi-k2-thinking",
messages=[{"role": "user", "content": "你是誰"}],
stream=True,
)
reasoning_content = "" # 完整思考過程
answer_content = "" # 完整回複
is_answering = False # 是否進入回複階段
print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")
for chunk in completion:
if chunk.choices:
delta = chunk.choices[0].delta
# 只收集思考內容
if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
if not is_answering:
print(delta.reasoning_content, end="", flush=True)
reasoning_content += delta.reasoning_content
# 收到content,開始進行回複
if hasattr(delta, "content") and delta.content:
if not is_answering:
print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.content返回結果
====================思考過程====================
使用者問"你是誰",這是一個關於身份的直接問題。我需要根據我的實際身份如實回答。
我是由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手,我的名字是Kimi。我應該清晰、簡潔地介紹自己,包括:
1. 我的身份:AI助手
2. 我的開發人員:月之暗面科技有限公司(Moonshot AI)
3. 我的名字:Kimi
4. 我的核心能力:長文本處理、智能對話、檔案處理、搜尋等
我應該保持友好、專業的語氣,避免過於技術化的術語,讓普通使用者也能理解。同時,我應該強調我是一個AI,沒有個人意識、情感或個人經歷。
回答結構:
- 直接回答身份
- 說明開發人員
- 簡要介紹核心能力
- 保持簡潔明了
====================完整回複====================
我是由月之暗面科技有限公司(Moonshot AI)開發的AI助手,名叫Kimi。我基於混合專家(MoE)架構,具備超長上下文理解、智能對話、檔案處理、代碼產生和複雜任務推理等能力。有什麼可以幫您的嗎?Node.js
範例程式碼
import OpenAI from "openai";
import process from 'process';
// 初始化OpenAI用戶端
const openai = new OpenAI({
// 如果沒有配置環境變數,請用阿里雲百鍊API Key替換:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = ''; // 完整思考過程
let answerContent = ''; // 完整回複
let isAnswering = false; // 是否進入回複階段
async function main() {
const messages = [{ role: 'user', content: '你是誰' }];
const stream = await openai.chat.completions.create({
model: 'kimi-k2-thinking',
messages,
stream: true,
});
console.log('\n' + '='.repeat(20) + '思考過程' + '='.repeat(20) + '\n');
for await (const chunk of stream) {
if (chunk.choices?.length) {
const delta = chunk.choices[0].delta;
// 只收集思考內容
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
if (!isAnswering) {
process.stdout.write(delta.reasoning_content);
}
reasoningContent += delta.reasoning_content;
}
// 收到content,開始進行回複
if (delta.content !== undefined && delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + '完整回複' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
}
}
main();返回結果
====================思考過程====================
使用者問"你是誰",這是一個關於身份的直接問題。我需要根據我的實際身份如實回答。
我是由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手,我的名字是Kimi。我應該清晰、簡潔地介紹自己,包括:
1. 我的身份:AI助手
2. 我的開發人員:月之暗面科技有限公司(Moonshot AI)
3. 我的名字:Kimi
4. 我的核心能力:長文本處理、智能對話、檔案處理、搜尋等
我應該保持友好、專業的語氣,避免過於技術化的術語,讓普通使用者也能輕鬆理解。同時,我應該強調我是一個AI,沒有個人意識、情感或個人經歷,以避免誤解。
回答結構:
- 直接回答身份
- 說明開發人員
- 簡要介紹核心能力
- 保持簡潔明了
====================完整回複====================
我是由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手,名叫 Kimi。
我擅長:
- 長文本理解與產生
- 智能對話和問答
- 檔案處理與分析
- 資訊檢索與整合
作為一個AI助手,我沒有個人意識、情感或經歷,但會儘力為您提供準確、有用的協助。有什麼可以幫您的嗎?HTTP
範例程式碼
curl
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "kimi-k2-thinking",
"messages": [
{
"role": "user",
"content": "你是誰"
}
]
}'返回結果
{
"choices": [
{
"message": {
"content": "我是由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手,名叫 Kimi。我擅長處理長文本、智能對話、檔案分析、編程輔助和複雜任務推理,可以協助您回答問題、創作內容、分析文檔等。有什麼我可以幫您的嗎?",
"reasoning_content": "使用者問\"你是誰\",這是一個關於身份的直接問題。我需要根據我的實際身份如實回答。\n\n我是由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手,我的名字是Kimi。我應該清晰、簡潔地介紹自己,包括:\n1. 我的身份:AI助手\n2. 我的開發人員:月之暗面科技有限公司(Moonshot AI)\n3. 我的名字:Kimi\n4. 我的核心能力:長文本處理、智能對話、檔案處理、搜尋等\n\n我應該保持友好、專業的語氣,同時提供有用資訊。不需要過度複雜化,直接回答即可。",
"role": "assistant"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 8,
"completion_tokens": 183,
"total_tokens": 191
},
"created": 1762753998,
"system_fingerprint": null,
"model": "kimi-k2-thinking",
"id": "chatcmpl-485ab490-90ec-48c3-85fa-1c732b683db2"
}DashScope
Python
範例程式碼
import os
from dashscope import Generation
# 初始化請求參數
messages = [{"role": "user", "content": "你是誰?"}]
completion = Generation.call(
# 如果沒有配置環境變數,請用阿里雲百鍊API Key替換:api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="kimi-k2-thinking",
messages=messages,
result_format="message", # 設定結果格式為 message
stream=True, # 開啟流式輸出
incremental_output=True, # 開啟增量輸出
)
reasoning_content = "" # 完整思考過程
answer_content = "" # 完整回複
is_answering = False # 是否進入回複階段
print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")
for chunk in completion:
message = chunk.output.choices[0].message
# 只收集思考內容
if message.reasoning_content:
if not is_answering:
print(message.reasoning_content, end="", flush=True)
reasoning_content += message.reasoning_content
# 收到 content,開始進行回複
if message.content:
if not is_answering:
print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
is_answering = True
print(message.content, end="", flush=True)
answer_content += message.content
# 迴圈結束後,reasoning_content 和 answer_content 變數中包含了完整的內容
# 您可以在這雷根據需要進行後續處理
# print(f"\n\n完整思考過程:\n{reasoning_content}")
# print(f"\n完整回複:\n{answer_content}")返回結果
====================思考過程====================
使用者問"你是誰?",這是一個關於身份的直接問題。我需要根據我的實際身份如實回答。
我是由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手,我的名字是Kimi。我應當清晰、簡潔地說明這一點。
需要包含的關鍵資訊:
1. 我的名稱:Kimi
2. 我的開發人員:月之暗面科技有限公司(Moonshot AI)
3. 我的本質:人工智慧助手
4. 我可以提供協助:回答問題、協助創作等
我應該保持友好和樂於助人的語氣,同時準確說明我的身份。我不應該假裝是人類或具有個人身份。
一個合適的回答可以是:
"我是Kimi,由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手。我可以協助你回答問題、進行創作、分析文檔等多種任務。有什麼我可以幫你的嗎?"
這個回答直接、準確,並且邀請使用者進一步互動。
====================完整回複====================
我是Kimi,由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手。我可以協助你回答問題、進行創作、分析文檔等多種任務。有什麼我可以幫你的嗎?Java
範例程式碼
// dashscope SDK的版本 >= 2.19.4
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import java.lang.System;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static StringBuilder reasoningContent = new StringBuilder();
private static StringBuilder finalContent = new StringBuilder();
private static boolean isFirstPrint = true;
private static void handleGenerationResult(GenerationResult message) {
String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
String content = message.getOutput().getChoices().get(0).getMessage().getContent();
if (reasoning!= null&&!reasoning.isEmpty()) {
reasoningContent.append(reasoning);
if (isFirstPrint) {
System.out.println("====================思考過程====================");
isFirstPrint = false;
}
System.out.print(reasoning);
}
if (content!= null&&!content.isEmpty()) {
finalContent.append(content);
if (!isFirstPrint) {
System.out.println("\n====================完整回複====================");
isFirstPrint = true;
}
System.out.print(content);
}
}
private static GenerationParam buildGenerationParam(Message userMsg) {
return GenerationParam.builder()
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("kimi-k2-thinking")
.incrementalOutput(true)
.resultFormat("message")
.messages(Arrays.asList(userMsg))
.build();
}
public static void streamCallWithMessage(Generation gen, Message userMsg)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(userMsg);
Flowable<GenerationResult> result = gen.streamCall(param);
result.blockingForEach(message -> handleGenerationResult(message));
}
public static void main(String[] args) {
try {
Generation gen = new Generation();
Message userMsg = Message.builder().role(Role.USER.getValue()).content("你是誰?").build();
streamCallWithMessage(gen, userMsg);
// 列印最終結果
// if (reasoningContent.length() > 0) {
// System.out.println("\n====================完整回複====================");
// System.out.println(finalContent.toString());
// }
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}返回結果
====================思考過程====================
使用者問"你是誰?",這是一個關於身份的直接問題。我需要根據我的實際身份如實回答。
我是由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手,我的名字是Kimi。我應當清晰、簡潔地說明這一點。
回答應該包括:
1. 我的身份:AI助手
2. 我的開發人員:月之暗面科技有限公司(Moonshot AI)
3. 我的名字:Kimi
4. 我的核心能力:長文本處理、智能對話、檔案處理等
我不應該假裝是人類,也不應該提供過多技術細節,只需給出清晰、友好的回答即可。
====================完整回複====================
我是由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手,名叫 Kimi。我擅長處理長文本、進行智能對話、解答問題、輔助創作,還能幫您分析和處理檔案。有什麼可以幫您的嗎?HTTP
範例程式碼
curl
curl -X POST "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "kimi-k2-thinking",
"input":{
"messages":[
{
"role": "user",
"content": "你是誰?"
}
]
},
"parameters": {
"result_format": "message"
}
}'返回結果
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"content": "我是Kimi,由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手。我可以協助你回答問題、進行創作、分析文檔、編寫代碼等。有什麼可以幫你的嗎?",
"reasoning_content": "使用者問\"你是誰?\",這是一個關於身份的直接問題。我需要根據我的實際身份如實回答。\n\n我是由月之暗面科技有限公司(Moonshot AI)開發的人工智慧助手,我的名字是Kimi。我應當清晰、簡潔地說明這一點。\n\n需要包含的關鍵資訊:\n1. 我的名稱:Kimi\n2. 我的開發人員:月之暗面科技有限公司(Moonshot AI)\n3. 我的本質:人工智慧助手\n4. 我可以提供協助:回答問題、協助創作等\n\n我應該以友好、直接的方式回應,使使用者容易理解。",
"role": "assistant"
}
}
]
},
"usage": {
"input_tokens": 9,
"output_tokens": 156,
"total_tokens": 165
},
"request_id": "709a0697-ed1f-4298-82c9-a4b878da1849"
}模型功能
模型 | |||||||
kimi-k2-thinking | |||||||
Moonshot-Kimi-K2-Instruct |
參數預設值
模型 | temperature | top_p | presence_penalty |
kimi-k2-thinking | 1.0 | - | - |
Moonshot-Kimi-K2-Instruct | 0.6 | 1.0 | 0 |
“-” 表示沒有預設值,也不支援設定。
錯誤碼
如果模型調用失敗並返回報錯資訊,請參見錯誤資訊進行解決。