このトピックでは、Alibaba Cloud Model Studio プラットフォーム上で OpenAI 互換 API または DashScope SDK を使用して Kimi シリーズのモデルを呼び出す方法について説明します。
本ドキュメントは中国 (北京) リージョンのみに適用されます。モデルを利用するには、中国 (北京) リージョンのAPI キーを使用する必要があります。
モデルの概要
Kimi シリーズのモデルは、Moonshot AI が開発した大規模言語モデル (LLM) です。
kimi-k2.5:現時点で Kimi の最も高度なモデルであり、エージェントタスク、コード生成、視覚理解、および多様な汎用知的タスクにおいてオープンソース分野で最先端 (SoTA) の性能を実現しています。また、Kimi の中でも最も多機能なモデルであり、テキストと画像の両方を入力可能なネイティブマルチモーダルアーキテクチャ、思考モードおよび非思考モードの切り替え、対話およびエージェントタスクへの対応を特徴としています。
kimi-k2-thinking:深層思考モードのみをサポートします。
reasoning_contentフィールドに推論プロセスが表示されます。このモデルは、コーディングおよびツール呼び出しに優れており、論理的分析、計画立案、あるいは深い理解を必要とするシナリオに適しています。Moonshot-Kimi-K2-Instruct:深層思考モードをサポートしません。高速な応答を実現するために、直接応答を生成します。このモデルは、迅速かつ直接的な回答を必要とするシナリオに適しています。
モデル | モード | コンテキストウィンドウ | 最大入力 | 最大 CoT | 最大応答 | 入力コスト | 出力コスト |
(トークン) | (100万トークンあたり) | ||||||
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 キーを取得し、API キーを環境変数として設定する必要があります。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
# コンテンツを受信した場合、応答の生成を開始
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応答
====================思考プロセス====================
ユーザーは「あなたは誰ですか?」と直接的な質問をしており、これは私の ID に関する質問です。私は実際の ID に基づいて正直に回答する必要があります。
私は Moonshot AI が開発した AI アシスタント「Kimi」です。以下の点を明確かつ簡潔に自己紹介する必要があります:
1. 私の ID:AI アシスタント
2. 開発者:Moonshot AI
3. 名前:Kimi
4. 主な機能:長文処理、インテリジェントな会話、ファイル処理、検索など
フレンドリーでプロフェッショナルなトーンを保ち、一般ユーザが理解しやすいよう、過度に技術的な用語を避けます。また、私は個人的な意識や感情、経験を持たない AI であることを強調し、誤解を防ぎます。
応答の構成:
- 直接的に ID を明記
- 開発者を明記
- 主な機能を簡単に紹介
- 簡潔かつ明瞭に記述
====================完全な応答====================
私は Moonshot AI が開発した AI アシスタント「Kimi」です。Mixture-of-Experts(MoE)アーキテクチャをベースとしており、長文コンテキスト理解、インテリジェントな会話、ファイル処理、コード生成、複雑なタスクに対する推論などの機能を備えています。どのようにお手伝いできますか?Node.js
サンプルコード
import OpenAI from "openai";
import process from 'process';
// OpenAI クライアントの初期化
const openai = new OpenAI({
// 環境変数が設定されていない場合は、以下を Model Studio の API キーに置き換えます: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;
}
// コンテンツを受信した場合、応答の生成を開始
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();応答
====================思考プロセス====================
ユーザーは「あなたは誰ですか?」と直接的な質問をしており、これは私の ID に関する質問です。私は実際の ID に基づいて正直に回答する必要があります。
私は Moonshot AI が開発した AI アシスタント「Kimi」です。以下の点を明確かつ簡潔に自己紹介する必要があります:
1. 私の ID:AI アシスタント
2. 開発者:Moonshot AI
3. 名前:Kimi
4. 主な機能:長文処理、インテリジェントな会話、ファイル処理、検索など
フレンドリーでプロフェッショナルなトーンを保ち、一般ユーザが容易に理解できるよう、過度に技術的な用語を避けます。また、私は個人的な意識、感情、経験を持たない AI であることを強調し、誤解を防ぎます。
応答の構成:
- 直接的に ID を明記
- 開発者を明記
- 主な機能を簡単に紹介
- 簡潔かつ明瞭に記述
====================完全な応答====================
私は Moonshot AI が開発した 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 が開発した AI アシスタント「Kimi」です。長文処理、インテリジェントな会話、ファイル分析、プログラミング支援、複雑なタスクに対する推論に優れています。質問への回答、コンテンツ作成、文書分析などを支援できます。どのようにお手伝いできますか?",
"reasoning_content": "ユーザーは「あなたは誰ですか?」と直接的な質問をしており、これは私の ID に関する質問です。私は実際の ID に基づいて正直に回答する必要があります。\n\n私は Moonshot AI が開発した AI アシスタント「Kimi」です。以下の点を明確かつ簡潔に自己紹介する必要があります:\n1. 私の ID: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(
# 環境変数が設定されていない場合は、以下を Model Studio の API キーに置き換えます: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
# コンテンツを受信した場合、応答の生成を開始
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}")応答
====================思考プロセス====================
ユーザーは「あなたは誰ですか?」と直接的な質問をしており、これは私の ID に関する質問です。私は実際の ID に基づいて正直に回答する必要があります。
私は「Kimi」という名前の AI アシスタントであり、Moonshot AI によって開発されました。これを明確かつ簡潔に述べる必要があります。
含めるべき主な情報:
1. 私の名前:Kimi
2. 開発者:Moonshot AI
3. 私の性質:人工知能アシスタント
4. 私ができること:質問への回答、コンテンツ作成など
フレンドリーで親切なトーンを保ちながら、自分の ID を正確に述べます。人間であるふりをしたり、個人的な ID を装ったりしてはいけません。
適切な応答例:
「私は Moonshot AI が開発した人工知能アシスタント『Kimi』です。質問への回答、コンテンツ作成、文書分析など、さまざまなタスクを支援できます。どのようにお手伝いできますか?」
この応答は直接的で正確であり、さらなるやり取りを促します。
====================完全な応答====================
私は Moonshot AI が開発した人工知能アシスタント『Kimi』です。質問への回答、コンテンツ作成、文書分析など、さまざまなタスクを支援できます。どのようにお手伝いできますか?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()
// 環境変数が設定されていない場合は、以下の行を Model Studio の API キーに置き換えます:.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("例外が発生しました:{}", e.getMessage());
}
System.exit(0);
}
}応答
====================思考プロセス====================
ユーザーは「あなたは誰ですか?」と直接的な質問をしており、これは私の ID に関する質問です。私は実際の ID に基づいて正直に回答する必要があります。
私は Moonshot AI が開発した AI アシスタント「Kimi」です。これを明確かつ簡潔に述べる必要があります。
応答に含めるべき情報:
1. 私の ID:AI アシスタント
2. 開発者:Moonshot AI
3. 名前:Kimi
4. 主な機能:長文処理、インテリジェントな会話、ファイル処理など
人間であるふりをしたり、過度な技術的詳細を提供したりしてはいけません。明確でフレンドリーな回答で十分です。
====================完全な応答====================
私は Moonshot AI が開発した 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": "私は Moonshot AI が開発した人工知能アシスタント『Kimi』です。質問への回答、コンテンツ作成、文書分析、コード作成を支援できます。どのようにお手伝いできますか?",
"reasoning_content": "ユーザーは「あなたは誰ですか?」と直接的な質問をしており、これは私の ID に関する質問です。私は実際の ID に基づいて正直に回答する必要があります。\n\n私は Moonshot AI が開発した 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 は、テキスト、画像、または動画の入力を同時に処理できます。
思考モードの有効化/無効化
kimi-k2.5 はハイブリッド思考モデルであり、思考プロセスを経て応答するか、または直接応答するかを選択できます。enable_thinking パラメーターを使用してこの動作を制御します:
truefalse(デフォルト)
以下のサンプルでは、画像 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'
});
// 単一の画像を渡す例(thinkingモードを有効化)
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 // thinkingモードを有効化
});
// 思考プロセスを出力
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);
// 複数の画像を渡す例(thinkingモードを有効化、使用する場合はコメントを解除)
// 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()
// 環境変数が設定されていない場合は、以下を Model Studio の API キーに置き換えます
.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 は、フレーム抽出により動画コンテンツを分析します。フレーム抽出戦略は、以下の 2 つのパラメーターで制御できます:
fps:フレーム抽出の頻度を制御します。1 秒あたり
秒ごとに 1 フレームが抽出されます。有効値: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 秒ごとに 1 フレームが抽出されることを意味します
{"video": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4","fps":2},
{"text": "この動画の内容は何ですか?"}
]
}
]
response = dashscope.MultiModalConversation.call(
# 環境変数が設定されていない場合は、以下の行を Model Studio の API キーに置き換えます: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 秒ごとに 1 フレームが抽出されることを意味します
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(
# 環境変数が設定されていない場合は、以下の行を Model Studio の API キーに置き換えます: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 互換 API は Base64 エンコーディングのみをサポートします。DashScope SDK は、Base64 エンコーディングおよびファイルパスの両方をサポートします。
OpenAI 互換
Base64 エンコードされたデータを渡すには、Data URL を構築します。手順については、「Data URL の構築」をご参照ください。
Python
from openai import OpenAI
import os
import base64
# エンコーディング関数:ローカルファイルを Base64 エンコードされた文字列に変換
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 でエンコードし、動画リストを作成します:
# 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 でエンコードし、動画リストを作成します:
# 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
Base64 エンコーディング方式
Base64 エンコーディングを使用するには、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"
# エンコーディング関数:ローカルファイルを Base64 エンコードされた文字列に変換
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(
# 環境変数が設定されていない場合は、以下の行を Model Studio の API キーに置き換えます: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 SDK および 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 (7680×4320)以内に保つことを推奨します。この解像度を超える画像は、ファイルサイズが大きくなりネットワーク転送時間が長くなるため、API 呼び出しがタイムアウトする可能性があります。
サポートされる画像形式
4K (
(3840×2160)) 未満の解像度の場合、以下の画像形式がサポートされます:画像形式
一般的なファイル拡張子
MIME タイプ
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 (3840×2160)から8K (7680×4320)の解像度の場合、JPEG、JPG、PNG 形式のみがサポートされます。
画像サイズ:
パブリック URL またはローカルパスで渡す場合:単一画像のサイズは
10 MBを超えてはいけません。Base64 エンコードされた文字列で渡す場合:エンコード後の文字列のサイズは
10 MBを超えてはいけません。
ファイルサイズを削減するには、「画像または動画を必要なサイズに圧縮する方法」をご参照ください。
サポートされる画像数:複数の画像を渡す場合、画像数はモデルの最大入力トークン数によって制限されます。すべての画像およびテキストのトークン数の合計は、この上限より小さくなければなりません。
動画の制限事項
画像リストとして渡す場合:最低 4 枚、最大 2000 枚の画像を指定できます。
動画ファイルとして渡す場合:
動画サイズ:
パブリック URL で渡す場合:最大 2 GB。
Base64 エンコードされた文字列で渡す場合:10 MB 未満。
ローカルファイルパスで渡す場合:動画自体のサイズは 100 MB を超えてはいけません。
動画再生時間: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 | ― | ― |
ハイフン (―) は、デフォルト値が存在せず、パラメーターを設定できないことを示します。
エラーコード
モデルの呼び出しが失敗し、エラーメッセージが返された場合は、「エラーメッセージ」を参照して問題をトラブルシューティングしてください。