本文檔介紹如何在阿里雲百鍊平台通過OpenAI相容介面或DashScope SDK調用Kimi系列模型。
本文檔僅適用於“中國大陸(北京)”地區。如需使用模型,需使用“中國大陸(北京)”地區的API Key。
模型介紹
Kimi 系列模型是由月之暗面公司(Moonshot AI)推出的大語言模型。
kimi-k2.5:Kimi系列迄今最全能的模型,在 Agent、代碼產生、視覺理解及一系列通用智慧工作提示上取得開源 SOTA 表現。同時支援映像、視頻與文本輸入、思考與非思考模式、對話與 Agent 任務。
kimi-k2-thinking:僅支援深度思考模式,並通過
reasoning_content欄位展示思考過程,具有卓越的編碼和工具調用能力,適用於需要邏輯分析、規劃或深度理解的情境。Moonshot-Kimi-K2-Instruct:不支援深度思考,直接產生回複,響應速度更快,適用於需要快速直接回答的情境。
模型名稱 | 模式 | 上下文長度 | 最大輸入 | 最大思維鏈長度 | 最大回複長度 | 輸入成本 | 輸出成本 |
(Token數) | (每百萬Token) | ||||||
kimi-k2.5 | 思考模式 | 262,144 | 258,048 | 32,768 | 32,768 | $0.574 | $3.011 |
kimi-k2.5 | 非思考模式 | 262,144 | 260,096 | - | 32,768 | $0.574 | $3.011 |
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 Host並完成配置API Key到環境變數(準備下線,併入配置 API Key)。如果通過SDK調用,需要安裝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.5 多模態調用樣本
kimi-k2.5 支援同時處理文本、映像或視頻輸入,並可通過 enable_thinking 參數開啟思考模式。以下樣本展示如何調用多模態能力。
開啟或關閉思考模式
kimi-k2.5屬於混合思考模型,模型可以在思考後回複,也可直接回複;通過enable_thinking參數控制是否開啟思考模式:
true:開啟思考模式false(預設):關閉思考模式
以下樣本展示如何使用映像 URL 並開啟思考模式,支援單圖輸入(主樣本)和多圖輸入(注釋代碼)。
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.5",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "圖中描繪的是什麼景象?"},
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
}
}
]
}
],
extra_body={"enable_thinking":True} # 開啟思考模式
)
# 輸出思考過程
if hasattr(completion.choices[0].message, 'reasoning_content') and completion.choices[0].message.reasoning_content:
print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")
print(completion.choices[0].message.reasoning_content)
# 輸出回複內容
print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
print(completion.choices[0].message.content)
# 多圖傳入樣本(開啟思考模式,取消注釋使用)
# completion = client.chat.completions.create(
# model="kimi-k2.5",
# messages=[
# {
# "role": "user",
# "content": [
# {"type": "text", "text": "這些圖描繪了什麼內容?"},
# {
# "type": "image_url",
# "image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"}
# },
# {
# "type": "image_url",
# "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"}
# }
# ]
# }
# ],
# extra_body={"enable_thinking":True}
# )
#
# # 輸出思考過程和回複
# if hasattr(completion.choices[0].message, 'reasoning_content') and completion.choices[0].message.reasoning_content:
# print("\n思考過程:\n" + completion.choices[0].message.reasoning_content)
# print("\n完整回複:\n" + completion.choices[0].message.content)Node.js
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1'
});
// 單圖傳入樣本(開啟思考模式)
const completion = await openai.chat.completions.create({
model: 'kimi-k2.5',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: '圖中描繪的是什麼景象?' },
{
type: 'image_url',
image_url: {
url: 'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg'
}
}
]
}
],
enable_thinking: true // 開啟思考模式
});
// 輸出思考過程
if (completion.choices[0].message.reasoning_content) {
console.log('\n' + '='.repeat(20) + '思考過程' + '='.repeat(20) + '\n');
console.log(completion.choices[0].message.reasoning_content);
}
// 輸出回複內容
console.log('\n' + '='.repeat(20) + '完整回複' + '='.repeat(20) + '\n');
console.log(completion.choices[0].message.content);
// 多圖傳入樣本(開啟思考模式,取消注釋使用)
// const multiCompletion = await openai.chat.completions.create({
// model: 'kimi-k2.5',
// messages: [
// {
// role: 'user',
// content: [
// { type: 'text', text: '這些圖描繪了什麼內容?' },
// {
// type: 'image_url',
// image_url: { url: 'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg' }
// },
// {
// type: 'image_url',
// image_url: { url: 'https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png' }
// }
// ]
// }
// ],
// enable_thinking: true
// });
//
// // 輸出思考過程和回複
// if (multiCompletion.choices[0].message.reasoning_content) {
// console.log('\n思考過程:\n' + multiCompletion.choices[0].message.reasoning_content);
// }
// console.log('\n完整回複:\n' + multiCompletion.choices[0].message.content);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.5",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "圖中描繪的是什麼景象?"
},
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
}
}
]
}
],
"enable_thinking": true
}'
# 多圖輸入樣本(取消注釋使用)
# 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.5",
# "messages": [
# {
# "role": "user",
# "content": [
# {
# "type": "text",
# "text": "這些圖描繪了什麼內容?"
# },
# {
# "type": "image_url",
# "image_url": {
# "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
# }
# },
# {
# "type": "image_url",
# "image_url": {
# "url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"
# }
# }
# ]
# }
# ],
# "enable_thinking": true,
# "stream": false
# }'DashScope
Python
import os
from dashscope import MultiModalConversation
# 單圖傳入樣本(開啟思考模式)
response = MultiModalConversation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="kimi-k2.5",
messages=[
{
"role": "user",
"content": [
{"text": "圖中描繪的是什麼景象?"},
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"}
]
}
],
enable_thinking=True # 開啟思考模式
)
# 輸出思考過程
if hasattr(response.output.choices[0].message, 'reasoning_content') and response.output.choices[0].message.reasoning_content:
print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")
print(response.output.choices[0].message.reasoning_content)
# 輸出回複內容
print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
print(response.output.choices[0].message.content[0]["text"])
# 多圖傳入樣本(開啟思考模式,取消注釋使用)
# response = MultiModalConversation.call(
# api_key=os.getenv("DASHSCOPE_API_KEY"),
# model="kimi-k2.5",
# messages=[
# {
# "role": "user",
# "content": [
# {"text": "這些圖描繪了什麼內容?"},
# {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},
# {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"}
# ]
# }
# ],
# enable_thinking=True
# )
#
# # 輸出思考過程和回複
# if hasattr(response.output.choices[0].message, 'reasoning_content') and response.output.choices[0].message.reasoning_content:
# print("\n思考過程:\n" + response.output.choices[0].message.reasoning_content)
# print("\n完整回複:\n" + response.output.choices[0].message.content[0]["text"])Java
// dashscope SDK的版本 >= 2.19.4
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
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 com.alibaba.dashscope.utils.JsonUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class KimiK25MultiModalExample {
public static void main(String[] args) {
try {
// 單圖輸入樣本(開啟思考模式)
MultiModalConversation conv = new MultiModalConversation();
// 構建訊息內容
Map<String, Object> textContent = new HashMap<>();
textContent.put("text", "圖中描繪的是什麼景象?");
Map<String, Object> imageContent = new HashMap<>();
imageContent.put("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg");
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(textContent, imageContent))
.build();
// 構建請求參數
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 若沒有配置環境變數,請用阿里雲百鍊API Key替換
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("kimi-k2.5")
.messages(Arrays.asList(userMessage))
.enableThinking(true) // 開啟思考模式
.build();
// 調用模型
MultiModalConversationResult result = conv.call(param);
// 輸出結果
String content = result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text");
System.out.println("回複內容: " + content);
// 如果開啟了思考模式,輸出思考過程
if (result.getOutput().getChoices().get(0).getMessage().getReasoningContent() != null) {
System.out.println("\n思考過程: " +
result.getOutput().getChoices().get(0).getMessage().getReasoningContent());
}
// 多圖輸入樣本(取消注釋使用)
// Map<String, Object> imageContent1 = new HashMap<>();
// imageContent1.put("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg");
// Map<String, Object> imageContent2 = new HashMap<>();
// imageContent2.put("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png");
//
// Map<String, Object> textContent2 = new HashMap<>();
// textContent2.put("text", "這些圖描繪了什麼內容?");
//
// MultiModalMessage multiImageMessage = MultiModalMessage.builder()
// .role(Role.USER.getValue())
// .content(Arrays.asList(textContent2, imageContent1, imageContent2))
// .build();
//
// MultiModalConversationParam multiParam = MultiModalConversationParam.builder()
// .apiKey(System.getenv("DASHSCOPE_API_KEY"))
// .model("kimi-k2.5")
// .messages(Arrays.asList(multiImageMessage))
// .enableThinking(true)
// .build();
//
// MultiModalConversationResult multiResult = conv.call(multiParam);
// System.out.println(multiResult.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("調用失敗: " + e.getMessage());
}
}
}curl
curl -X POST "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "kimi-k2.5",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"text": "圖中描繪的是什麼景象?"
},
{
"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
}
]
}
]
},
"parameters": {
"enable_thinking": true
}
}'
# 多圖輸入樣本(取消注釋使用)
# curl -X POST "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
# -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
# -H "Content-Type: application/json" \
# -d '{
# "model": "kimi-k2.5",
# "input": {
# "messages": [
# {
# "role": "user",
# "content": [
# {
# "text": "這些圖描繪了什麼內容?"
# },
# {
# "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
# },
# {
# "image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"
# }
# ]
# }
# ]
# },
# "parameters": {
# "enable_thinking": true
# }
# }'視頻理解
視頻檔案
kimi-k2.5模型通過從視頻中提取幀序列進行內容分析。您可以通過以下兩個參數控制抽幀策略:
fps:控制抽幀頻率,每隔
秒抽取一幀。取值範圍為 [0.1, 10],預設值為 2.0。 高速運動情境:建議設定較高的 fps 值,以捕捉更多細節
靜態或長視頻:建議設定較低的 fps 值,以提高處理效率
max_frames:限制視頻抽取幀的上限,預設值和最大值均為2000。
當按 fps 計算的總幀數超過此限制時,系統將自動在 max_frames 內均勻抽幀。此參數僅在使用 DashScope SDK 時可用。
OpenAI相容
使用OpenAI SDK或HTTP方式向模型直接輸入視頻檔案時,需要將使用者訊息中的"type"參數設為"video_url"。
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.5",
messages=[
{
"role": "user",
"content": [
# 直接傳入的視訊檔案時,請將type的值設定為video_url
{
"type": "video_url",
"video_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"
},
"fps": 2
},
{
"type": "text",
"text": "這段視頻的內容是什麼?"
}
]
}
]
)
print(completion.choices[0].message.content)Node.js
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.chat.completions.create({
model: "kimi-k2.5",
messages: [
{
role: "user",
content: [
// 直接傳入的視訊檔案時,請將type的值設定為video_url
{
type: "video_url",
video_url: {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"
},
"fps": 2
},
{
type: "text",
text: "這段視頻的內容是什麼?"
}
]
}
]
});
console.log(response.choices[0].message.content);
}
main();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.5",
"messages": [
{
"role": "user",
"content": [
{
"type": "video_url",
"video_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"
},
"fps":2
},
{
"type": "text",
"text": "這段視頻的內容是什麼?"
}
]
}
]
}'DashScope
Python
import dashscope
import os
dashscope.base_http_api_url = "https://dashscope.aliyuncs.com/api/v1"
messages = [
{"role": "user",
"content": [
# fps 可參數控制視頻抽幀頻率,表示每隔 1/fps 秒抽取一幀
{"video": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4","fps":2},
{"text": "這段視頻的內容是什麼?"}
]
}
]
response = dashscope.MultiModalConversation.call(
# 若沒有配置環境變數, 請用百鍊API Key將下行替換為: api_key ="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='kimi-k2.5',
messages=messages
)
print(response.output.choices[0].message.content[0]["text"])Java
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {Constants.baseHttpApiUrl="https://dashscope.aliyuncs.com/api/v1";}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
// fps 可參數控制視頻抽幀頻率,表示每隔 1/fps 秒抽取一幀
Map<String, Object> params = new HashMap<>();
params.put("video", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4");
params.put("fps", 2);
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
params,
Collections.singletonMap("text", "這段視頻的內容是什麼?"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("kimi-k2.5")
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "kimi-k2.5",
"input":{
"messages":[
{"role": "user","content": [{"video": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4","fps":2},
{"text": "這段視頻的內容是什麼?"}]}]}
}'映像列表
當視頻以映像列表(即預先抽取的視訊框架)傳入時,可通過fps參數告知模型視訊框架之間的時間間隔,這能協助模型更準確地理解事件的順序、期間和動態變化。模型支援通過 fps 參數指定原始視頻的抽幀率,表示視訊框架是每隔
OpenAI相容
使用OpenAI SDK或HTTP方式向模型輸入圖片列表形式的視頻時,需要將使用者訊息中的"type"參數設為"video"。
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.5",
messages=[{"role": "user","content": [
# 傳入映像列表時,使用者訊息中的"type"參數為"video"
{"type": "video","video": [
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"],
"fps":2},
{"type": "text","text": "描述這個視頻的具體過程"},
]}]
)
print(completion.choices[0].message.content)Node.js
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.chat.completions.create({
model: "kimi-k2.5",
messages: [{
role: "user",
content: [
{
// 傳入映像列表時,使用者訊息中的"type"參數為"video"
type: "video",
video: [
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"],
"fps":2
},
{
type: "text",
text: "描述這個視頻的具體過程"
}
]
}]
});
console.log(response.choices[0].message.content);
}
main();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.5",
"messages": [{"role": "user","content": [{"type": "video","video": [
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"],
"fps":2},
{"type": "text","text": "描述這個視頻的具體過程"}]}]
}'DashScope
Python
import os
import dashscope
dashscope.base_http_api_url = "https://dashscope.aliyuncs.com/api/v1"
messages = [{"role": "user",
"content": [
{"video":["https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"],
"fps":2},
{"text": "描述這個視頻的具體過程"}]}]
response = dashscope.MultiModalConversation.call(
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model='kimi-k2.5',
messages=messages
)
print(response.output.choices[0].message.content[0]["text"])Java
// DashScope SDK版本需要不低於2.21.10
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {Constants.baseHttpApiUrl="https://dashscope.aliyuncs.com/api/v1";}
private static final String MODEL_NAME = "kimi-k2.5";
public static void videoImageListSample() throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> params = new HashMap<>();
params.put("video", Arrays.asList("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"));
params.put("fps", 2);
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(
params,
Collections.singletonMap("text", "描述這個視頻的具體過程")))
.build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model(MODEL_NAME)
.messages(Arrays.asList(userMessage)).build();
MultiModalConversationResult result = conv.call(param);
System.out.print(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
videoImageListSample();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "kimi-k2.5",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"video": [
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
],
"fps":2
},
{
"text": "描述這個視頻的具體過程"
}
]
}
]
}
}'傳入本地檔案
以下樣本展示如何傳入本地檔案。OpenAI 相容介面僅支援 Base 64 編碼方式,DashScope 同時支援 Base 64 編碼和檔案路徑兩種方式。
OpenAI相容
Base 64 編碼方式傳入需要構建 Data URL,構建方法請參見構建 Data URL。
Python
from openai import OpenAI
import os
import base64
# 編碼函數: 將本地檔案轉換為 Base 64 編碼的字串
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# 將xxx/eagle.png替換為你本地映像的絕對路徑
base64_image = encode_image("xxx/eagle.png")
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.5",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{base64_image}"},
},
{"type": "text", "text": "圖中描繪的是什麼景象?"},
],
}
],
)
print(completion.choices[0].message.content)
# 以下為傳入本地視頻檔案、本地映像列表的樣本
# 【本地視頻檔案】將本地視頻編碼為 Data URL 後傳入 video_url:
# def encode_video_to_data_url(video_path):
# with open(video_path, "rb") as f:
# return "data:video/mp4;base64," + base64.b64encode(f.read()).decode("utf-8")
# video_data_url = encode_video_to_data_url("xxx/local.mp4")
# content = [{"type": "video_url", "video_url": {"url": video_data_url}, "fps": 2}, {"type": "text", "text": "這段視頻的內容是什麼?"}]
# 【本地映像列表】將多張本地圖片分別 Base64 後組成 video 列表傳入:
# image_data_urls = [f"data:image/jpeg;base64,{encode_image(p)}" for p in ["xxx/f1.jpg", "xxx/f2.jpg", "xxx/f3.jpg", "xxx/f4.jpg"]]
# content = [{"type": "video", "video": image_data_urls, "fps": 2}, {"type": "text", "text": "描述這個視頻的具體過程"}]
Node.js
import OpenAI from "openai";
import { readFileSync } from 'fs';
const openai = new OpenAI(
{
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
);
const encodeImage = (imagePath) => {
const imageFile = readFileSync(imagePath);
return imageFile.toString('base64');
};
// 將xxx/eagle.png替換為你本地映像的絕對路徑
const base64Image = encodeImage("xxx/eagle.png")
async function main() {
const completion = await openai.chat.completions.create({
model: "kimi-k2.5",
messages: [
{"role": "user",
"content": [{"type": "image_url",
"image_url": {"url": `data:image/png;base64,${base64Image}`},},
{"type": "text", "text": "圖中描繪的是什麼景象?"}]}]
});
console.log(completion.choices[0].message.content);
}
main();
// 以下為傳入本地視頻檔案、本地映像列表示例
// 【本地視頻檔案】將本地視頻編碼為 Data URL 後傳入 video_url:
// const encodeVideoToDataUrl = (videoPath) => "data:video/mp4;base64," + readFileSync(videoPath).toString("base64");
// const videoDataUrl = encodeVideoToDataUrl("xxx/local.mp4");
// content: [{ type: "video_url", video_url: { url: videoDataUrl }, fps: 2 }, { type: "text", text: "這段視頻的內容是什麼?" }]
// 【本地映像列表】將多張本地圖片分別 Base64 後組成 video 列表傳入:
// const imageDataUrls = ["xxx/f1.jpg","xxx/f2.jpg","xxx/f3.jpg","xxx/f4.jpg"].map(p => `data:image/jpeg;base64,${encodeImage(p)}`);
// content: [{ type: "video", video: imageDataUrls, fps: 2 }, { type: "text", text: "描述這個視頻的具體過程" }]
// messages: [{"role": "user", "content": content}]
// 再調用 openai.chat.completions.create(model: "kimi-k2.5", messages: messages)DashScope
Base 64 編碼方式
Base 64 編碼方式傳入需要構建 Data URL,構建方法請參見構建 Data URL。
Python
import base64
import os
import dashscope
from dashscope import MultiModalConversation
dashscope.base_http_api_url = "https://dashscope.aliyuncs.com/api/v1"
# 編碼函數: 將本地檔案轉換為 Base 64 編碼的字串
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# 將xxx/eagle.png替換為你本地映像的絕對路徑
base64_image = encode_image("xxx/eagle.png")
messages = [
{
"role": "user",
"content": [
{"image": f"data:image/png;base64,{base64_image}"},
{"text": "圖中描繪的是什麼景象?"},
],
},
]
response = MultiModalConversation.call(
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="kimi-k2.5",
messages=messages,
)
print(response.output.choices[0].message.content[0]["text"])
# 以下為傳入本地視頻檔案、本地映像列表示例
# 【本地視頻檔案】
# video_data_url = "data:video/mp4;base64," + base64.b64encode(open("xxx/local.mp4","rb").read()).decode("utf-8")
# content: [{"video": video_data_url, "fps": 2}, {"text": "這段視頻的內容是什麼?"}]
# 【本地映像列表】
# Base64:image_data_urls = [f"data:image/jpeg;base64,{encode_image(p)}" for p in ["xxx/f1.jpg","xxx/f2.jpg","xxx/f3.jpg","xxx/f4.jpg"]]
# content: [{"video": image_data_urls, "fps": 2}, {"text": "描述這個視頻的具體過程"}]Java
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Base64;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.alibaba.dashscope.aigc.multimodalconversation.*;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {Constants.baseHttpApiUrl="https://dashscope.aliyuncs.com/api/v1";}
private static String encodeToBase64(String imagePath) throws IOException {
Path path = Paths.get(imagePath);
byte[] imageBytes = Files.readAllBytes(path);
return Base64.getEncoder().encodeToString(imageBytes);
}
public static void callWithLocalFile(String localPath) throws ApiException, NoApiKeyException, UploadFileException, IOException {
String base64Image = encodeToBase64(localPath); // Base64編碼
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
new HashMap<String, Object>() {{ put("image", "data:image/png;base64," + base64Image); }},
new HashMap<String, Object>() {{ put("text", "圖中描繪的是什麼景象?"); }}
)).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("kimi-k2.5")
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
// 將 xxx/eagle.png 替換為你本地映像的絕對路徑
callWithLocalFile("xxx/eagle.png");
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
// 以下為傳入本地視頻檔案、本地映像列表示例
// 【本地視頻檔案】
// String base64Image = encodeToBase64(localPath);
// MultiModalConversation conv = new MultiModalConversation();
// MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
// .content(Arrays.asList(
// new HashMap<String, Object>() {{ put("video", "data:video/mp4;base64," + base64Video;}},
// new HashMap<String, Object>() {{ put("text", "這段視頻描繪的是什麼景象?"); }}
// )).build();
// 【本地映像列表】
// List<String> urls = Arrays.asList(
// "data:image/jpeg;base64,"+encodeToBase64(path/f1.jpg),
// "data:image/jpeg;base64,"+encodeToBase64(path/f2.jpg),
// "data:image/jpeg;base64,"+encodeToBase64(path/f3.jpg),
// "data:image/jpeg;base64,"+encodeToBase64(path/f4.jpg));
// MultiModalConversation conv = new MultiModalConversation();
// MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
// .content(Arrays.asList(
// new HashMap<String, Object>() {{ put("video", urls;}},
// new HashMap<String, Object>() {{ put("text", "這段視頻描繪的是什麼景象?"); }}
// )).build();
}本地檔案路徑方式
直接向模型傳入本地檔案路徑。僅 DashScope Python 和 Java SDK 支援,不支援 DashScope HTTP 和OpenAI 相容方式。請您參考下表,結合您的程式設計語言與作業系統指定檔案的路徑。
Python
import os
from dashscope import MultiModalConversation
import dashscope
dashscope.base_http_api_url = "https://dashscope.aliyuncs.com/api/v1"
# 將xxx/eagle.png替換為你本地映像的絕對路徑
local_path = "xxx/eagle.png"
image_path = f"file://{local_path}"
messages = [
{'role':'user',
'content': [{'image': image_path},
{'text': '圖中描繪的是什麼景象?'}]}]
response = MultiModalConversation.call(
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='kimi-k2.5',
messages=messages)
print(response.output.choices[0].message.content[0]["text"])
# 以下為以本地檔案路徑傳入的視訊、映像列表示例
# 【本地視頻檔案】
# video_path = "file:///path/to/local.mp4"
# content: [{"video": video_path, "fps": 2}, {"text": "這段視頻的內容是什麼?"}]
# 【本地映像列表】
# image_paths = ["file:///path/f1.jpg", "file:///path/f2.jpg", "file:///path/f3.jpg", "file:///path/f4.jpg"]
# content: [{"video": image_paths, "fps": 2}, {"text": "描述這個視頻的具體過程"}]
Java
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {Constants.baseHttpApiUrl="https://dashscope.aliyuncs.com/api/v1";}
public static void callWithLocalFile(String localPath)
throws ApiException, NoApiKeyException, UploadFileException {
String filePath = "file://"+localPath;
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(new HashMap<String, Object>(){{put("image", filePath);}},
new HashMap<String, Object>(){{put("text", "圖中描繪的是什麼景象?");}})).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("kimi-k2.5")
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));}
public static void main(String[] args) {
try {
// 將xxx/eagle.png替換為你本地映像的絕對路徑
callWithLocalFile("xxx/eagle.png");
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
// 以下為以本地檔案路徑傳入的視訊、映像列表示例
// 【本地視頻檔案】
// String filePath = "file://"+localPath;
// MultiModalConversation conv = new MultiModalConversation();
// MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
// .content(Arrays.asList(new HashMap<String, Object>(){{put("video", filePath);}},
// new HashMap<String, Object>(){{put("text", "視頻中描繪的是什麼景象?");}})).build();
// 【本地映像列表】
// MultiModalConversation conv = new MultiModalConversation();
// List<String> filePath = Arrays.asList("file:///path/f1.jpg", "file:///path/f2.jpg", "file:///path/f3.jpg", "file:///path/f4.jpg")
// MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
// .content(Arrays.asList(new HashMap<String, Object>(){{put("video", filePath);}},
// new HashMap<String, Object>(){{put("text", "視頻中描繪的是什麼景象?");}})).build();
}檔案限制
映像限制
映像解析度:
最小尺寸:映像的寬度和高度均須大於
10像素。寬高比:映像長邊與短邊的比值不得超過
200:1。像素上限:推薦將映像解析度控制在
8K(7680x4320)以內。超過此解析度的映像可能因檔案過大、網路傳輸耗時過長而導致 API 呼叫逾時。
支援的映像格式
解析度在4K
(3840x2160)以下,支援的映像格式如下:映像格式
常見副檔名
MIME Type
BMP
.bmp
image/bmp
JPEG
.jpe, .jpeg, .jpg
image/jpeg
PNG
.png
image/png
TIFF
.tif, .tiff
image/tiff
WEBP
.webp
image/webp
HEIC
.heic
image/heic
解析度處於
4K(3840x2160)到8K(7680x4320)範圍,僅支援 JPEG、JPG 、PNG 格式。
映像大小:
以公網 URL 和本地路徑傳入時:單個映像的大小不超過
10MB。以 Base 64 編碼傳入時:編碼後的字串不超過
10MB。
如需壓縮檔體積請參見如何將映像或視頻壓縮到滿足要求的大小。
支援傳入的圖片數量:傳入多張映像時,圖片數量受模型的最大輸入的限制,所有圖片和文本的總 Token 數必須小於模型的最大輸入。
視頻限制
以映像列表傳入:最少傳入 4 張圖片,最多 2000 張圖片
以視頻檔案傳入時:
視頻大小:
以公網 URL 傳入時:不超過 2GB;
以 Base 64 編碼傳入時:編碼後的字串小於 10MB;
以本地檔案路徑傳入時:視頻本身不超過 100MB。
視頻時間長度:2 秒至 1 小時;
視頻格式: MP4、AVI、MKV、MOV、FLV、WMV 等。
視頻尺寸:無特定限制,建議不超過2K,再高的解析度只會增加處理時間,也不會對模型理解的效果有提升。
音頻理解:不支援對視頻檔案的音頻進行理解。
模型功能
模型 | |||||||
kimi-k2.5 | |||||||
kimi-k2-thinking | |||||||
Moonshot-Kimi-K2-Instruct |
參數預設值
模型 | enable_thinking | temperature | top_p | presence_penalty | fps | max_frames |
kimi-k2.5 | false | 思考模式:1.0 非思考模式:0.6 | 思考/非思考模式:0.95 | 思考/非思考模式:0.0 | 2 | 2000 |
kimi-k2-thinking | - | 1.0 | - | - | - | - |
Moonshot-Kimi-K2-Instruct | - | 0.6 | 1.0 | 0 | - | - |
“-” 表示沒有預設值,也不支援設定。
錯誤碼
如果模型調用失敗並返回報錯資訊,請參見錯誤資訊進行解決。