すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:Kimi

最終更新日:Mar 10, 2026

Alibaba Cloud Model Studio を使用して Kimi モデルを呼び出します。

重要

このドキュメントは、中国 (北京) リージョンにのみ適用されます。モデルを利用するには、中国 (北京) リージョンの Model Studio API キー を使用する必要があります。

モデル概要

Kimi は、Moonshot AI が開発した大規模言語モデルシリーズです。

  • kimi-k2.5:現時点で Kimi の最も高度なモデルであり、エージェント、コード生成、視覚理解、および多様な汎用知能タスクにおいて、オープンソース分野で最先端(SoTA)の性能を実現しています。また、Kimi の中でも最も汎用性の高いモデルであり、テキストと画像の両方を入力として受け付けるネイティブマルチモーダルアーキテクチャを備え、思考モードおよびノンシンキングモードの両方に対応し、対話およびエージェントタスクをサポートします。

  • kimi-k2-thinking:深層思考モードのみをサポートします。reasoning_content フィールドに推論プロセスが表示されます。このモデルは、コーディングおよびツール呼び出しに優れており、論理的分析、計画立案、または深い理解を必要とするシナリオに適しています。

  • Moonshot-Kimi-K2-Instruct:深層思考モードをサポートしません。高速な応答を実現するために、直接応答を生成します。このモデルは、迅速かつ直接的な回答を必要とするシナリオに適しています。

モデル

モード

コンテキストウィンドウ

最大入力

最大 CoT

最大応答

入力コスト

出力コスト

(トークン)

(100 万トークンあたり)

kimi-k2.5

思考モード

262,144

258,048

81,920

98,304

$0.574

$3.011

kimi-k2.5

ノンシンキングモード

262,144

260,096

-

98,304

$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

上記のモデルはサードパーティのサービスではなく、すべて Model Studio サーバー上で展開されています。

テキスト生成のサンプル

API を利用する前に、Model Studio 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": "Who are you?"}],
    stream=True,
)

reasoning_content = ""  # 完全な思考プロセス
answer_content = ""     # 完全な応答
is_answering = False    # モデルが応答の生成を開始したかどうかを示すフラグ

print("\n" + "=" * 20 + "Thinking Process" + "=" * 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 + "Complete Response" + "=" * 20 + "\n")
                is_answering = True
            print(delta.content, end="", flush=True)
            answer_content += delta.content

応答

====================Thinking Process====================

ユーザーは「あなたは誰ですか?」と尋ねており、これは自分の ID に関する直接的な質問です。私は実際の ID に基づいて正直に回答する必要があります。

私は Moonshot AI が開発した AI アシスタント「Kimi」です。以下の点を明確かつ簡潔に自己紹介する必要があります。
1. 私の ID:AI アシスタント
2. 開発者:Moonshot AI
3. 名前:Kimi
4. 主な機能:長文処理、インテリジェントな会話、ファイル処理、検索など

フレンドリーで専門的なトーンを保ち、一般ユーザーが理解できるよう、過度に技術的な用語は避けます。また、私は個人的な意識、感情、経験を持たない AI であることを強調し、誤解を防ぐ必要があります。

応答構成:
- 自分の ID を直接明示
- 開発者を明記
- 主な機能を簡単に紹介
- 簡潔かつ明瞭に記述
====================Complete Response====================

私は 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: 'Who are you?' }];

    const stream = await openai.chat.completions.create({
        model: 'kimi-k2-thinking',
        messages,
        stream: true,
    });

    console.log('\n' + '='.repeat(20) + 'Thinking Process' + '='.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) + 'Complete Response' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    }
}

main();

応答

====================Thinking Process====================

ユーザーは「あなたは誰ですか?」と尋ねており、これは自分の ID に関する直接的な質問です。私は実際の ID に基づいて正直に回答する必要があります。

私は Moonshot AI が開発した AI アシスタント「Kimi」です。以下の点を明確かつ簡潔に自己紹介する必要があります:
1. 私の ID:AI アシスタント
2. 開発者:Moonshot AI
3. 名前:Kimi
4. 主な機能:長文処理、インテリジェントな会話、ファイル処理、検索など

一般ユーザーが容易に理解できるよう、フレンドリーで専門的なトーンを保ち、過度に技術的な用語は避けます。また、誤解を防ぐため、私は個人的な意識、感情、経験を持たない AI であることを強調する必要があります。

応答構成:
- 自分の ID を直接明示
- 開発者を明記
- 主な機能を簡単に紹介
- 簡潔かつ明瞭に記述
====================Complete Response====================

私は Moonshot AI が開発した AI アシスタント「Kimi」です。

私の主な機能は以下のとおりです:
- 長文の理解および生成
- インテリジェントな会話および質問応答(Q&A)
- ファイルの処理および分析
- 情報の検索および統合

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": "Who are you?"
        }
    ]
}'

応答

{
    "choices": [
        {
            "message": {
                "content": "I am an AI assistant named Kimi, developed by Moonshot AI. I am skilled at long-text processing, intelligent conversation, file analysis, programming assistance, and complex task reasoning. I can help you answer questions, create content, and analyze documents. How can I help you?",
                "reasoning_content": "The user asks \"Who are you?\", which is a direct question about my identity. I need to answer truthfully based on my actual identity.\n\nI am an AI assistant named Kimi, developed by Moonshot AI. I should introduce myself clearly and concisely, including the following:\n1. My identity: AI assistant\n2. My developer: Moonshot AI\n3. My name: Kimi\n4. My core capabilities: long-text processing, intelligent conversation, file processing, search, etc.\n\nI should maintain a friendly and professional tone while providing useful information. No need to overcomplicate it; a direct answer is sufficient.",
                "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": "Who are you?"}]

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 + "Thinking Process" + "=" * 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 + "Complete Response" + "=" * 20 + "\n")
            is_answering = True
        print(message.content, end="", flush=True)
        answer_content += message.content

# ループ終了後、reasoning_content および answer_content 変数には完全なコンテンツが格納されます。
# 必要に応じて、ここでさらに処理を行ってください。
# print(f"\n\nComplete thinking process:\n{reasoning_content}")
# print(f"\nComplete response:\n{answer_content}")

応答

====================Thinking Process====================

ユーザーは「あなたは誰ですか?」と尋ねており、これは自分の ID に関する直接的な質問です。私は実際の ID に基づいて正直に回答する必要があります。

私は Moonshot AI が開発した AI アシスタント「Kimi」です。これを明確かつ簡潔に述べる必要があります。

含めるべき主要情報:
1. 私の名前:Kimi
2. 開発者:Moonshot AI
3. 私の性質:人工知能アシスタント
4. 私ができること:質問への回答、コンテンツ作成、ドキュメント分析など

フレンドリーで役立つトーンを保ちながら、自分の ID を正確に述べる必要があります。人間であるふりをしたり、個人的な ID を装ったりしてはいけません。

適切な応答例:
「私は Moonshot AI が開発した人工知能アシスタント『Kimi』です。質問への回答、コンテンツ作成、ドキュメント分析など、さまざまなタスクをお手伝いできます。何かお手伝いできることはありますか?」

この応答は直接的で正確であり、さらなるやり取りを促します。
====================Complete Response====================

私は 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("====================Thinking Process====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }

        if (content!= null&&!content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================Complete Response====================");
                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("Who are you?").build();
            streamCallWithMessage(gen, userMsg);
            // 最終結果を出力
            // if (reasoningContent.length() > 0) {
            //     System.out.println("\n====================Complete Response====================");
            //     System.out.println(finalContent.toString());
            // }
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            logger.error("例外が発生しました:{}", e.getMessage());
        }
        System.exit(0);
    }
}

応答

====================Thinking Process====================
ユーザーは「あなたは誰ですか?」と尋ねており、これは自分の ID に関する直接的な質問です。私は実際の ID に基づいて正直に回答する必要があります。

私は Moonshot AI が開発した AI アシスタント「Kimi」です。これを明確かつ簡潔に述べる必要があります。

応答に含めるべき内容:
1. 私の ID:AI アシスタント
2. 開発者:Moonshot AI
3. 私の名前:Kimi
4. 私の主な機能:長文処理、インテリジェントな会話、ファイル処理など

人間であるふりをしたり、過度な技術的詳細を提供したりしてはいけません。明確でフレンドリーな回答で十分です。
====================Complete Response====================
私は 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": "Who are you?"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

応答

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "content": "I am Kimi, an artificial intelligence assistant developed by Moonshot AI. I can help you answer questions, create content, analyze documents, and write code. How can I help you?",
                    "reasoning_content": "The user asks \"Who are you?\", which is a direct question about my identity. I need to answer truthfully based on my actual identity.\n\nI am an AI assistant named Kimi, developed by Moonshot AI. I should state this clearly and concisely.\n\nKey information to include:\n1. My name: Kimi\n2. My developer: Moonshot AI\n3. My nature: Artificial intelligence assistant\n4. What I can do: Answer questions, assist with creation, etc.\n\nI should respond in a friendly and direct manner that is easy for the user to understand.",
                    "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 パラメーターを使用してこの動作を制御します:

  • 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 + "Thinking Process" + "=" * 20 + "\n")
    print(completion.choices[0].message.reasoning_content)

# 応答コンテンツを出力
print("\n" + "=" * 20 + "Complete Response" + "=" * 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("\nThinking Process:\n" + completion.choices[0].message.reasoning_content)
# print("\nComplete Response:\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) + 'Thinking Process' + '='.repeat(20) + '\n');
    console.log(completion.choices[0].message.reasoning_content);
}

// 応答コンテンツを出力
console.log('\n' + '='.repeat(20) + 'Complete Response' + '='.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('\nThinking Process:\n' + multiCompletion.choices[0].message.reasoning_content);
// }
// console.log('\nComplete Response:\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 + "Thinking Process" + "=" * 20 + "\n")
    print(response.output.choices[0].message.reasoning_content)

# 応答コンテンツを出力
print("\n" + "=" * 20 + "Complete Response" + "=" * 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("\nThinking Process:\n" + response.output.choices[0].message.reasoning_content)
# print("\nComplete Response:\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 互換方式ではサポートされていません。プログラミング言語およびオペレーティングシステムに応じて、下記の表を参照してファイルパスを指定してください。

ファイルパスの指定方法(画像の例)

システム

SDK

指定するファイルパス

Linux または macOS システム

Python SDK

file://{ファイルの絶対パス}

file:///home/images/test.png

Java SDK

Windows システム

Python SDK

file://{ファイルの絶対パス}

file://D:/images/test.png

Java SDK

file:///{ファイルの絶対パス}

file:///D:/images/test.png

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 以下に保つことを推奨します。より高い解像度では、モデルの理解向上には寄与せず、処理時間が増加します。

  • 音声理解:動画ファイル内の音声はサポートされていません。

モデルの特徴

モデル

マルチターン会話

深層思考

関数呼び出し

構造化出力

Web 検索

部分モード

コンテキストキャッシュ

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

-

-

ハイフン(-)は、デフォルト値がなく、そのパラメーターを設定できないことを示します。

エラーコード

モデル呼び出しが失敗し、エラーメッセージが返された場合、「エラーメッセージ」をご参照いただき、問題をトラブルシューティングしてください。