Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Kimi

Última actualización: Oct 12, 2026

Este documento describe cómo llamar al servicio de inferencia del modelo Kimi implementado en Alibaba Cloud Model Studio.

Regiones admitidas: China (Beijing), Singapur, Japón (Tokio), China (Hong Kong), Alemania (Frankfurt) y EE. UU. (Virginia).

Experiencia del modelo:

Puede probar el modelo Kimi en el

Experience Center.

Los endpoints de servicio son específicos de la región. Configure la URL base correcta para su región.

Compatible con OpenAI

EE. UU. (Virginia)

El base_url para llamadas SDK es: https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1

URL de solicitud HTTP: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Germany (Frankfurt)

El base_url para llamadas SDK es: https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1

URL de solicitud HTTP: POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Singapore

El base_url para llamadas SDK es: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1

URL de solicitud HTTP: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Japan (Tokyo)

El base_url para llamadas SDK es: https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1

URL de solicitud HTTP: POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

China (Beijing)

El base_url para llamadas SDK es: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1

URL de solicitud HTTP: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions

China (Hong Kong)

El base_url para llamadas SDK es: https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1

URL de solicitud HTTP: POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/chat/completions

DashScope

EE. UU. (Virginia)

La URL de solicitud HTTP para modelos multimodales, como kimi-k2.6 y kimi-k2.5, es POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

El base_url para llamadas SDK es:

Código Python

dashscope.base_http_api_url = 'https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1'

Código Java

  • Método 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1");
  • Método 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1";

Germany (Frankfurt)

La URL de solicitud HTTP para modelos multimodales, como kimi-k3, kimi-k2.7-code, kimi-k2.6 y kimi-k2.5, es POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

El base_url para llamadas SDK es:

Código Python

dashscope.base_http_api_url = 'https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1'

Código Java

  • Método 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1");
  • Método 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1";

Singapore

La URL de solicitud HTTP para modelos multimodales, como kimi-k3, kimi-k2.7-code, kimi-k2.6 y kimi-k2.5, es POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

El base_url para llamadas SDK es:

Código Python

# Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

Código Java

  • Opción 1:
import com.alibaba.dashscope.protocol.Protocol;
// Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
  • Opción 2:
import com.alibaba.dashscope.utils.Constants;
// Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";

Japan (Tokyo)

La URL de solicitud HTTP para modelos multimodales, como kimi-k3, kimi-k2.7-code, kimi-k2.6 y kimi-k2.5, es POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

El base_url para llamadas SDK es:

Código Python

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1'

Código Java

  • Opción 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1");
  • Opción 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1";

China (Hong Kong)

La URL de solicitud HTTP para modelos multimodales, como kimi-k3, kimi-k2.7-code, kimi-k2.6 y kimi-k2.5, es POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

El base_url para llamadas SDK es:

Código Python

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1'

Código Java

  • Método 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1");
  • Método 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1";

China (Beijing)

La URL de solicitud HTTP para modelos multimodales, como kimi-k3, kimi-k2.7-code, kimi-k2.6 y kimi-k2.5, es POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

El base_url para llamadas SDK es:

Código Python

# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

Código Java

  • Opción 1:
import com.alibaba.dashscope.protocol.Protocol;
// China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1");
  • Opción 2:
import com.alibaba.dashscope.utils.Constants;
// China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";

Compatible con Anthropic

EE. UU. (Virginia)

Configuración de llamada del SDK base_url: https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/apps/anthropic

URL de solicitud HTTP: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/apps/anthropic/v1/messages

Germany (Frankfurt)

Configuración de llamada del SDK base_url: https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/apps/anthropic

URL de solicitud HTTP: POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/apps/anthropic/v1/messages

Singapore

Configuración de llamada del SDK base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic

URL de solicitud HTTP: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages

Japan (Tokyo)

Configuración de llamada del SDK base_url: https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/apps/anthropic

URL de solicitud HTTP: POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages

China (Beijing)

Configuración de llamada del SDK base_url: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic

URL de solicitud HTTP: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic/v1/messages

La API compatible con Anthropic solo admite el endpoint Messages (/v1/messages). Para límites de protocolo y uso, consulte Messages compatible con Anthropic.

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Requisitos previos: Debe obtener una clave API y configurarla como variable de entorno. Si usa el SDK, debe instalar el SDK.

Primeros pasos

Los siguientes ejemplos usan entrada de solo texto. Para ejemplos multimodales, consulte llamada multimodal.

Compatible con OpenAI

Python

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[{"role": "user", "content": "Who are you?"}],
    stream=True,
    extra_body={"enable_thinking": True},  # Enable thinking mode to get reasoning_content
)

reasoning_content = ""  # Complete thinking process
answer_content = ""     # Complete response
is_answering = False    # Tracks if the main response has started.

print("\n" + "=" * 20 + "Thinking Process" + "=" * 20 + "\n")

for chunk in completion:
    if chunk.choices:
        delta = chunk.choices[0].delta
        # Store content from the thinking process.
        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
        # Start printing the main response once its content arrives.
        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

Respuesta

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

The user asks "Who are you?", which is a direct question about my identity. I need to answer truthfully based on my actual identity.

I am Kimi, an AI assistant developed by Moonshot AI. I should introduce myself clearly and concisely, including:
1. My identity: AI assistant
2. My developer: Moonshot AI
3. My name: Kimi
4. My core capabilities: long-text processing, intelligent conversation, file processing, search, etc.

I should maintain a friendly and professional tone, avoiding overly technical terms for clarity. I should also emphasize that I am an AI without personal consciousness, emotions, or experiences to prevent misunderstandings.

Response structure:
- Directly state my identity
- Mention my developer
- Briefly introduce core capabilities
- Keep it clear and concise
====================Complete Response====================

I am Kimi, an AI assistant developed by Moonshot AI. I am based on a Mixture-of-Experts (MoE) architecture and have capabilities such as ultra-long context understanding, intelligent conversation, file processing, code generation, and complex task reasoning. How can I help you?

Node.js

import OpenAI from "openai";
import process from 'process';

// Initialize the OpenAI client
const openai = new OpenAI({
    // If not using an environment variable, replace `process.env.DASHSCOPE_API_KEY` with your API key string (e.g., "sk-xxx").
    apiKey: process.env.DASHSCOPE_API_KEY,
    // China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    baseURL: 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1'
});

let reasoningContent = ''; // Complete thinking process
let answerContent = ''; // Complete response
let isAnswering = false; // Tracks if the main response has started.

async function main() {
    const messages = [{ role: 'user', content: 'Who are you?' }];

    const stream = await openai.chat.completions.create({
        model: 'kimi-k3',
        messages,
        stream: true,
        enable_thinking: true,  // Enable thinking mode to get reasoning_content
    });

    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;
            // Store content from the thinking process.
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // Start printing the main response once its content arrives.
            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();

Respuesta

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

The user asks "Who are you?", which is a direct question about my identity. I need to answer truthfully based on my actual identity.

I am Kimi, an AI assistant developed by Moonshot AI. I should introduce myself clearly and concisely, including:
1. My identity: AI assistant
2. My developer: Moonshot AI
3. My name: Kimi
4. My core capabilities: long-text processing, intelligent conversation, file processing, search, etc.

I should maintain a friendly and professional tone and avoid overly technical terms for clarity. I should also emphasize that I am an AI without personal consciousness, emotions, or experiences to prevent misunderstandings.

Response structure:
- Directly state my identity
- Mention my developer
- Briefly introduce core capabilities
- Keep it clear and concise
====================Complete Response====================

I am Kimi, an AI assistant developed by Moonshot AI.

I am skilled in:
- Long-text understanding and generation
- Intelligent conversation and question answering
- File processing and analysis
- Information retrieval and integration

As an AI assistant, I do not have personal consciousness, emotions, or experiences, but I am designed to provide accurate and helpful assistance. How can I help you?

HTTP

curl

# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "kimi-k3",
    "messages": [
        {
            "role": "user",
            "content": "Who are you?"
        }
    ],
    "enable_thinking": true
}'

Respuesta

{
    "choices": [
        {
            "message": {
                "content": "I am Kimi, an AI assistant developed by Moonshot AI. I am skilled in 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 assist you?",
                "reasoning_content": "The user asks \"Who are you?\", which is a direct question about my identity. I must answer truthfully based on my actual identity.\n\nI am Kimi, an AI assistant developed by Moonshot AI. I should introduce myself clearly and concisely, including:\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; 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-k3",
    "id": "chatcmpl-485ab490-90ec-48c3-85fa-1c732b683db2"
}

DashScope

Los siguientes ejemplos de DashScope usan el endpoint multimodal-generation para llamar a kimi-k3, que admite entrada de texto y multimodal. Para más ejemplos multimodales, consulte llamada multimodal.

Python

import os
import dashscope
from dashscope import MultiModalConversation
# China (Beijing) region configuration. Replace {WorkspaceId} with your actual workspace ID. For other regions, use the corresponding base URL.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

# Define the request messages.
messages = [{"role": "user", "content": "Who are you?"}]

completion = MultiModalConversation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # If not using an environment variable, provide your key directly, e.g., api_key="sk-xxx"
    model="kimi-k3",
    messages=messages,
    result_format="message",  # Set the result format to message
    stream=True,              # Enable streaming.
    incremental_output=True,  # Enable incremental output
    enable_thinking=True,     # Enable thinking mode to get reasoning_content
)

reasoning_content = ""  # Complete thinking process
answer_content = ""     # Complete response
is_answering = False    # Tracks if the main response has started.

print("\n" + "=" * 20 + "Thinking Process" + "=" * 20 + "\n")

for chunk in completion:
    message = chunk.output.choices[0].message

    # Store content from the thinking process.
    reasoning_chunk = message.get("reasoning_content")
    if reasoning_chunk:
        if not is_answering:
            print(reasoning_chunk, end="", flush=True)
        reasoning_content += reasoning_chunk

    # Start printing the main response once its content arrives. content is a list, so extract the text from it.
    if message.get("content"):
        text = message.content[0].get("text", "")
        if not is_answering:
            print("\n" + "=" * 20 + "Complete Response" + "=" * 20 + "\n")
            is_answering = True
        print(text, end="", flush=True)
        answer_content += text

Respuesta

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

The user asks "Who are you?", which is a direct question about my identity. I need to answer truthfully based on my actual identity.

I am Kimi, an AI assistant developed by Moonshot AI. I should state this clearly and concisely.

Key information to include:
1. My name: Kimi
2. My developer: Moonshot AI
3. My nature: AI assistant
4. What I can do: answer questions, assist with content creation, etc.

I should maintain a friendly and helpful tone while accurately stating my identity. I should not pretend to be human or have a personal identity.

A suitable response would be:
"I am Kimi, an AI assistant developed by Moonshot AI. I can help you with a variety of tasks such as answering questions, creating content, and analyzing documents. How can I help you?"

This response is direct, accurate, and encourages further interaction.
====================Complete Response====================

I am Kimi, an AI assistant developed by Moonshot AI. I can help you with a variety of tasks such as answering questions, creating content, and analyzing documents. How can I help you?

Java

// DashScope SDK version >= 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.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import java.util.Arrays;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        // China (Beijing) region configuration. Replace {WorkspaceId} with your actual workspace ID. For other regions, use the corresponding base URL.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        try {
            MultiModalConversation conv = new MultiModalConversation();

            MultiModalMessage userMsg = MultiModalMessage.builder()
                    .role(Role.USER.getValue())
                    .content(Arrays.asList(Collections.singletonMap("text", "Who are you?")))
                    .build();

            MultiModalConversationParam param = MultiModalConversationParam.builder()
                    // If not using an environment variable, replace the following line with your API key, e.g., .apiKey("sk-xxx")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .model("kimi-k3")
                    .messages(Arrays.asList(userMsg))
                    .build();

            MultiModalConversationResult result = conv.call(param);

            String content = (String) result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text");
            System.out.println("Response: " + content);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.err.println("An exception occurred: " + e.getMessage());
        }
        System.exit(0);
    }
}

Respuesta

Response: I am Kimi, an AI assistant developed by Moonshot AI. My skills include long-text processing, intelligent conversation, question answering, content creation, and file analysis and processing. How can I assist you?

HTTP

curl

# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "kimi-k3",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": "Who are you?"
            }
        ]
    },
    "parameters": {
        "result_format": "message",
        "enable_thinking": true
    }
}'

Respuesta

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "content": "I am Kimi, an AI 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 Kimi, an AI assistant 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: AI assistant\n4. What I can do: answer questions, assist with content creation, etc.\n\nThe response should be friendly, direct, and easy to understand.",
                    "role": "assistant"
                }
            }
        ]
    },
    "usage": {
        "input_tokens": 9,
        "output_tokens": 156,
        "total_tokens": 165
    },
    "request_id": "709a0697-ed1f-4298-82c9-a4b878da1849"
}

Compatible con Anthropic

Python

Código de ejemplo

import anthropic
import os

client = anthropic.Anthropic(
    # If the environment variable is not configured, replace the value with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # When you make a call, replace {WorkspaceId} with your actual Workspace ID.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)

message = client.messages.create(
    model="kimi-k3",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Who are you?"}
    ],
    stream=True,
)

for event in message:
    if event.type == "content_block_delta":
        if hasattr(event.delta, "thinking"):
            print(event.delta.thinking, end="", flush=True)
        if hasattr(event.delta, "text"):
            print(event.delta.text, end="", flush=True)

HTTP

Código de ejemplo

curl

# Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "anthropic-version: 2023-06-01" \
-d '{
    "model": "kimi-k3",
    "max_tokens": 1024,
    "messages": [
        {
            "role": "user",
            "content": "Who are you?"
        }
    ]
}'

Llamadas multimodales

Los modelos kimi-k2.7-code, kimi-k2.6 y kimi-k2.5 pueden procesar simultáneamente texto, imágenes o video. Use el parámetro enable_thinking para habilitar el modo de pensamiento. Los siguientes ejemplos muestran cómo usar esta capacidad.

Habilitar o deshabilitar el modo de pensamiento

kimi-k2.6 y kimi-k2.5 son modelos de pensamiento híbrido. Estos modelos pueden responder después de pensar o responder directamente. Puede usar el parámetro enable_thinking para controlar si se habilita el modo de pensamiento:

  • true: Habilitar el modo de pensamiento
  • false (predeterminado): Deshabilita el modo de pensamiento

kimi-k2.7-code es un modelo de solo pensamiento: el modo de pensamiento siempre está habilitado (enable_thinking tiene como valor predeterminado true y no se puede deshabilitar), y preserve_thinking tiene como valor predeterminado true.

kimi-k2.6 admite pasar el proceso de pensamiento en conversaciones de múltiples turnos usando el parámetro preserve_thinking. Para más información, consulte Pasar el proceso de pensamiento.

Los siguientes ejemplos muestran cómo usar una URL de imagen y habilitar el modo de pensamiento. El ejemplo principal demuestra la entrada de una sola imagen, mientras que el código comentado es un ejemplo de entrada de múltiples imágenes.

Compatible con OpenAI

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

# Single-image input example (thinking mode enabled)
completion = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What scene is depicted in the image?"},
                {
                    "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}  # Enable thinking mode
)

# Print the thinking process
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 the complete response
print("\n" + "=" * 20 + "Complete Response" + "=" * 20 + "\n")
print(completion.choices[0].message.content)

# Multi-image input example (thinking mode enabled, uncomment to use)
# completion = client.chat.completions.create(
#     model="kimi-k2.6",
#     messages=[
#         {
#             "role": "user",
#             "content": [
#                 {"type": "text", "text": "What do these images depict?"},
#                 {
#                     "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}
# )
#
# # Print the thinking process and complete response
# 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)
import OpenAI from "openai";
import process from 'process';

const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    baseURL: 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1'
});

// Single-image input example (thinking mode enabled)
const completion = await openai.chat.completions.create({
    model: 'kimi-k2.6',
    messages: [
        {
            role: 'user',
            content: [
                { type: 'text', text: 'What scene is depicted in the image?' },
                {
                    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  // Enable thinking mode
});

// Print the thinking process
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);
}

// Print the complete response
console.log('\n' + '='.repeat(20) + 'Complete Response' + '='.repeat(20) + '\n');
console.log(completion.choices[0].message.content);

// Multi-image input example (thinking mode enabled, uncomment to use)
// const multiCompletion = await openai.chat.completions.create({
//     model: 'kimi-k2.6',
//     messages: [
//         {
//             role: 'user',
//             content: [
//                 { type: 'text', text: 'What do these images depict?' },
//                 {
//                     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
// });
//
// // Print the thinking process and complete response
// 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);
# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "kimi-k2.6",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What scene is depicted in the image?"
                },
                {
                    "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
}'

# Multi-image input example (uncomment to use)
# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
# curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
# -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
# -H "Content-Type: application/json" \
# -d '{
#     "model": "kimi-k2.6",
#     "messages": [
#         {
#             "role": "user",
#             "content": [
#                 {
#                     "type": "text",
#                     "text": "What do these images depict?"
#                 },
#                 {
#                     "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

import os
import dashscope
from dashscope import MultiModalConversation
# China (Beijing) region configuration. Replace {WorkspaceId} with your actual workspace ID. For other regions, use the corresponding base URL.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

# Single-image input example (thinking mode enabled)
response = MultiModalConversation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="kimi-k2.6",
    messages=[
        {
            "role": "user",
            "content": [
                {"text": "What scene is depicted in the image?"},
                {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"}
            ]
        }
    ],
    enable_thinking=True  # Enable thinking mode
)

# Print the thinking process
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 the complete response
print("\n" + "=" * 20 + "Complete Response" + "=" * 20 + "\n")
print(response.output.choices[0].message.content[0]["text"])

# Multi-image input example (thinking mode enabled, uncomment to use)
# response = MultiModalConversation.call(
#     api_key=os.getenv("DASHSCOPE_API_KEY"),
#     model="kimi-k2.6",
#     messages=[
#         {
#             "role": "user",
#             "content": [
#                 {"text": "What do these images depict?"},
#                 {"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
# )
#
# # Print the thinking process and complete response
# 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"])
// Requires DashScope SDK v2.22.24 or later.
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;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class KimiK26MultiModalExample {
    public static void main(String[] args) {
        // China (Beijing) region configuration. Replace {WorkspaceId} with your actual workspace ID. For other regions, use the corresponding base URL.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        try {
            // Single-image input example (thinking mode enabled)
            MultiModalConversation conv = new MultiModalConversation();

            // Build the message content
            Map<String, Object> textContent = new HashMap<>();
            textContent.put("text", "What scene is depicted in the image?");

            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();

            // Build the request parameters
            MultiModalConversationParam param = MultiModalConversationParam.builder()
                    // If the environment variable is not set, replace this with your API key from Model Studio.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .model("kimi-k2.6")
                    .messages(Arrays.asList(userMessage))
                    .enableThinking(true)  // Enable thinking mode
                    .build();

            // Call the model
            MultiModalConversationResult result = conv.call(param);

            // Print the response
            String content = (String) result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text");
            System.out.println("Response: " + content);

            // If thinking mode is enabled, print the thinking process
            if (result.getOutput().getChoices().get(0).getMessage().getReasoningContent() != null) {
                System.out.println("\nThinking Process: " +
                    result.getOutput().getChoices().get(0).getMessage().getReasoningContent());
            }

            // Multi-image input example (uncomment to use)
            // 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", "What do these images depict?");
            //
            // 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.6")
            //         .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 | UploadFileException e) {
            System.err.println("Call failed: " + e.getMessage());
        }
    }
}
# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "kimi-k2.6",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "text": "What scene is depicted in the image?"
                    },
                    {
                        "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
                    }
                ]
            }
        ]
    },
    "parameters": {
        "enable_thinking": true
    }
}'

# Multi-image input example (uncomment to use)
# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
# curl -X POST "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
# -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
# -H "Content-Type: application/json" \
# -d '{
#     "model": "kimi-k2.6",
#     "input": {
#         "messages": [
#             {
#                 "role": "user",
#                 "content": [
#                     {
#                         "text": "What do these images depict?"
#                     },
#                     {
#                         "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
#     }
# }'

Comprensión de video

Notakimi-k3 actualmente no admite entrada de video (solo admite entrada de texto e imagen), por lo que los ejemplos de comprensión de video en esta sección no se aplican a kimi-k3.

Archivo de video

Los modelos kimi-k2.7-code, kimi-k2.6 y kimi-k2.5 analizan videos extrayendo una secuencia de fotogramas. Puede controlar la estrategia de extracción de fotogramas con los siguientes parámetros:

  • fps: Controla la frecuencia de extracción de fotogramas. El intervalo entre fotogramas extraídos es f p s 1 segundos. El valor debe estar en el rango de [0.1, 10]. El valor predeterminado es 2.0.

    • Para escenas con mucho movimiento: Establezca un valor de fps más alto para capturar más detalles.
    • Para videos estáticos o largos: Establezca un valor de fps más bajo para mejorar la eficiencia del procesamiento.
  • max_frames: Especifica el número máximo de fotogramas a extraer de un video. El valor predeterminado y máximo es 2000.

    Si el número de fotogramas calculado a partir del valor de fps excede este límite, el sistema extrae automáticamente fotogramas uniformemente para mantenerse dentro del límite de max_frames. Este parámetro está disponible solo cuando usa el SDK de DashScope.

Compatible con OpenAI

Al pasar un archivo de video al modelo usando el SDK de OpenAI o una solicitud HTTP, establezca el parámetro "type" en el mensaje de usuario en "video_url".

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[
        {
            "role": "user",
            "content": [
                # When passing a video file directly, set the "type" parameter to "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": "What is the content of this video?"
                }
            ]
        }
    ]
)

print(completion.choices[0].message.content)
import OpenAI from "openai";

const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
});

async function main() {
    const response = await openai.chat.completions.create({
        model: "kimi-k2.6",
        messages: [
            {
                role: "user",
                content: [
                    // When passing a video file directly, set the "type" parameter to "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: "What is the content of this video?"
                    }
                ]
            }
        ]
    });

    console.log(response.choices[0].message.content);
}

main();
# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "kimi-k2.6",
    "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": "What is the content of this video?"
          }
        ]
      }
    ]
  }'

DashScope

import dashscope
import os

# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

messages = [
    {"role": "user",
        "content": [
            # The fps parameter sets the frame extraction frequency; the interval between frames is 1/fps seconds.
            {"video": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4","fps":2},
            {"text": "What is the content of this video?"}
        ]
    }
]

response = dashscope.MultiModalConversation.call(
    # If the DASHSCOPE_API_KEY environment variable is not set, replace this line with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='kimi-k2.6',
    messages=messages
)

print(response.output.choices[0].message.content[0]["text"])
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 {
    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        // The fps parameter sets the frame extraction frequency; the interval between frames is 1/fps seconds.
        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", "What is the content of this video?"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("kimi-k2.6")
                .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) {
        // China (Beijing) region configuration. Replace {WorkspaceId} with your actual workspace ID. For other regions, use the corresponding base URL.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "kimi-k2.6",
    "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": "What is the content of this video?"}]}]}
}'

Lista de imágenes

Cuando proporcione un video como una lista de imágenes (fotogramas preextraídos), utilice el parámetro fps para especificar la tasa de extracción de fotogramas del video original. Este valor indica que los fotogramas se extrajeron cada f p s 1 segundos, lo que permite al modelo comprender mejor la secuencia de eventos, la duración y los cambios dinámicos.

Compatible con OpenAI

Al pasar un video como una lista de imágenes usando el SDK de OpenAI o una solicitud HTTP, establezca el parámetro "type" en el mensaje de usuario en "video".

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[{"role": "user","content": [
        # When passing an image list, set the "type" parameter in the user message to "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": "Describe the action in this video."},
    ]}]
)

print(completion.choices[0].message.content)
import OpenAI from "openai";

const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
});

async function main() {
    const response = await openai.chat.completions.create({
        model: "kimi-k2.6",
        messages: [{
            role: "user",
            content: [
                {
                    // When passing an image list, set the "type" parameter in the user message to "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: "Describe the action in this video."
                }
            ]
        }]
    });
    console.log(response.choices[0].message.content);
}

main();
# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "kimi-k2.6",
    "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": "Describe the action in this video."}]}]
}'

DashScope

import os
import dashscope

# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.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": "Describe the action in this video."}]}]
response = dashscope.MultiModalConversation.call(
    # If the DASHSCOPE_API_KEY environment variable is not set, replace this line with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model='kimi-k2.6',
    messages=messages
)
print(response.output.choices[0].message.content[0]["text"])
// Requires DashScope SDK v2.21.10 or later.
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 {
    // China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    private static final String MODEL_NAME = "kimi-k2.6";
    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", "Describe the action in this video.")))
                .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);
    }
}
# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "kimi-k2.6",
  "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": "Describe the action in this video."
          }
        ]
      }
    ]
  }
}'

Pasar un archivo local

Los siguientes ejemplos muestran cómo pasar un archivo local. La API compatible con OpenAI solo admite codificación Base64, mientras que DashScope admite tanto codificación Base64 como rutas de archivo.

Compatible con OpenAI

Para pasar un archivo local usando codificación Base64, construya una Data URL. Para instrucciones, consulte Construir una Data URL.

from openai import OpenAI
import os
import base64

# Encoding function: Converts a local file to a Base64-encoded string.
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# Replace "xxx/eagle.png" with the absolute path to your local image.
base64_image = encode_image("xxx/eagle.png")

client = OpenAI(
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    # China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/png;base64,{base64_image}"},
                },
                {"type": "text", "text": "What scene is depicted in the image?"},
            ],
        }
    ],
)
print(completion.choices[0].message.content)

# The following examples show how to pass a local video file and a local image list.

# [Local video file] Encode the local video as a Data URL and pass it to the video_url parameter:
#   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": "What is the content of this video?"}]

# [Local image list] Encode multiple local images with Base64 and pass them as a list to the video parameter:
#   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": "Describe the sequence of events in this video."}]
import OpenAI from "openai";
import { readFileSync } from 'fs';

const openai = new OpenAI(
    {
        apiKey: process.env.DASHSCOPE_API_KEY,
        // China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);

const encodeImage = (imagePath) => {
    const imageFile = readFileSync(imagePath);
    return imageFile.toString('base64');
  };
// Replace "xxx/eagle.png" with the absolute path to your local image.
const base64Image = encodeImage("xxx/eagle.png")
async function main() {
    const completion = await openai.chat.completions.create({
        model: "kimi-k2.6",
        messages: [
            {"role": "user",
             "content": [{"type": "image_url",
                        "image_url": {"url": `data:image/png;base64,${base64Image}`},},
                        {"type": "text", "text": "What scene is depicted in the image?"}]}]
    });
    console.log(completion.choices[0].message.content);
}

main();

// The following examples show how to pass a local video file and a local image list.

// [Local video file] Encode the local video as a Data URL and pass it to the video_url parameter:
//   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: "What is the content of this video?" }]

// [Local image list] Encode multiple local images with Base64 and pass them as a list to the video parameter:
//   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: "Describe the sequence of events in this video." }]

//   messages: [{"role": "user", "content": content}]
//   Then call openai.chat.completions.create({model: "kimi-k2.6", messages: messages})

DashScope

Codificación Base64

Para pasar un archivo local usando codificación Base64, construya una Data URL. Para instrucciones, consulte Construir una Data URL.

import base64
import os
import dashscope
from dashscope import MultiModalConversation

# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

# Encoding function: Converts a local file to a Base64-encoded string.
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# Replace "xxx/eagle.png" with the absolute path to your local image.
base64_image = encode_image("xxx/eagle.png")

messages = [
    {
        "role": "user",
        "content": [
            {"image": f"data:image/png;base64,{base64_image}"},
            {"text": "What scene is depicted in the image?"},
        ],
    },
]
response = MultiModalConversation.call(
    # If the DASHSCOPE_API_KEY environment variable is not set, pass your Model Studio API key directly, for example: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="kimi-k2.6",
    messages=messages,
)
print(response.output.choices[0].message.content[0]["text"])

# The following examples show how to pass a local video file and a local image list.

# [Local video file]
#   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": "What is the content of this video?"}]

# [Local image list]
#   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": "Describe the sequence of events in this video."}]
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 {

   // China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
   static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.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);

        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", "What scene is depicted in the image?"); }}
                )).build();

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("kimi-k2.6")
                .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 {
            // Replace "xxx/eagle.png" with the absolute path to your local image.
            callWithLocalFile("xxx/eagle.png");
        } catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }

    // The following examples show how to pass a local video file and a local image list.
    // [Local video file]
    // String base64Video = 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", "What scene is depicted in this video?"); }}
   //             )).build();

    // [Local image list]
    // 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", "What scene is depicted in this video?"); }}
   //             )).build();

}

Ruta de archivo

Puede pasar una ruta de archivo local directamente al modelo. Este método solo es compatible con los SDK de Python y Java de DashScope; no está disponible para DashScope HTTP ni para la API compatible con OpenAI. La siguiente tabla muestra el formato de ruta de archivo requerido para cada lenguaje de programación y sistema operativo.

Especificar una ruta de archivo (ejemplo de imagen)

System

SDK

Formato de ruta

Ejemplo

Linux o macOS

SDK de Python

file://{ruta absoluta del archivo}

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

SDK de Java

Windows

SDK de Python

file://{ruta absoluta del archivo}

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

SDK de Java

file:///{ruta absoluta del archivo}

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

import os
from dashscope import MultiModalConversation
import dashscope

# China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

# Replace "xxx/eagle.png" with the absolute path to your local image.
local_path = "xxx/eagle.png"
image_path = f"file://{local_path}"
messages = [
                {'role':'user',
                'content': [{'image': image_path},
                            {'text': 'What scene is depicted in the image?'}]}]
response = MultiModalConversation.call(
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='kimi-k2.6',
    messages=messages)
print(response.output.choices[0].message.content[0]["text"])

# The following examples show how to pass a local video and a list of local images using file paths.
# [Local video file]
#  video_path = "file:///path/to/local.mp4"
#  content: [{"video": video_path, "fps": 2}, {"text": "What is the content of this video?"}]

# [Local image list]
# 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": "Describe the sequence of events in this video."}]
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 {
    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", "What scene is depicted in the image?");}})).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("kimi-k2.6")
                .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) {
        // China (Beijing) region configuration. Replace {WorkspaceId} with your actual workspace ID. For other regions, use the corresponding base URL.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        try {
            // Replace "xxx/eagle.png" with the absolute path to your local image.
            callWithLocalFile("xxx/eagle.png");
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }

    // The following examples show how to pass a local video and a list of local images using file paths.

    // [Local video file]
    //  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", "What scene is depicted in the video?");}})).build();

    // [Local image list]

    //    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", "What scene is depicted in the video?");}})).build();
}

Limitaciones de archivos

Limitaciones de imagen

  • Resolución de imagen:
    • Tamaño mínimo: El ancho y el alto deben exceder cada uno 10 píxeles.
    • Relación de aspecto: La relación entre el lado más largo y el más corto no debe exceder 200:1.
    • Resolución máxima: El máximo recomendado es 8K(7680x4320). Resoluciones más altas pueden causar tiempos de espera en llamadas a la API debido a tamaños de archivo grandes o transferencias de red lentas.
  • Formatos de imagen compatibles
    • Los siguientes formatos son compatibles para resoluciones inferiores a 4K(3840x2160):

      Formato de imagen

      Extensión de archivo

      Tipo 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

    • Para resoluciones entre 4K(3840x2160) y 8K(7680x4320), solo se admiten JPEG, JPG y PNG.

  • Tamaño de imagen:
    • Al proporcionar una imagen mediante una URL pública o ruta local, su tamaño no debe exceder 10 MB.
    • Al usar la codificación Base64, la cadena codificada no debe exceder 10 MB.

    Para comprimir un archivo, consulte Cómo comprimir una imagen o video para cumplir con el límite de tamaño.

  • Número de imágenes admitidas: Al proporcionar múltiples imágenes, el número total de tokens para todas las imágenes y texto no debe exceder el límite máximo de entrada del modelo.

Limitaciones de video

  • Como lista de imágenes: De 4 a 2,000 imágenes.

  • Como archivo de video:
    • Tamaño de video:
      • Mediante URL pública: Hasta 2 GB.
      • Mediante codificación Base64: la cadena codificada debe ser menor que 10 MB.
      • Mediante ruta de archivo local: Hasta 100 MB.
    • Duración del video: De 2 segundos a 1 hora.

  • Formato de video: Los formatos compatibles incluyen MP4, AVI, MKV, MOV, FLV y WMV.

  • Resolución de video: Aunque no hay un límite estricto de resolución, use 2K o inferior para obtener mejores resultados. Resoluciones más altas aumentan el tiempo de procesamiento sin mejorar la comprensión del modelo.

  • Comprensión de audio: El modelo no procesa la pista de audio en los archivos de video.

Otras funciones

Modelo

Conversación multironda

Pensamiento profundo

Llamada de función

Salida estructurada

Búsqueda web

Completado de prefijo

Caché de contexto

kimi-k3

Compatible

Compatible

Compatible

Compatible

No compatible

Compatible

Compatible

kimi-k2.7-code

Compatible

Compatible

Compatible

No compatible

No compatible

No compatible

Compatible

kimi-k2.6

Compatible

Compatible

Compatible

No compatible

No compatible

No compatible

Compatible

kimi-k2.5

Compatible

Compatible

Compatible

No compatible

No compatible

No compatible

Compatible

Herramientas cargadas dinámicamente (Kimi K3)

Cuando una aplicación necesita montar una gran cantidad de herramientas, colocar todas las declaraciones de herramientas en el campo tools de nivel superior de la solicitud a la vez provoca una Inflación de Definiciones de Herramientas: cada solicitud debe llevar la descripción y el esquema de parámetros de todas las herramientas, lo que aumenta el consumo de tokens; y cuantas más herramientas candidatas haya, mayor será la probabilidad de que el modelo elija la herramienta incorrecta y construya argumentos de llamada erróneos.

Las Herramientas Cargadas Dinámicamente le permiten inyectar herramientas bajo demanda durante una conversación: monte primero solo unas pocas herramientas principales y, cuando la conversación llegue a un punto donde se necesite una herramienta específica, insértela dinámicamente en messages, reduciendo así el consumo de tokens y mejorando la precisión en la selección de herramientas.

NotaLas herramientas cargadas dinámicamente actualmente solo son compatibles con kimi-k3; solicitarlas en otros modelos (como kimi-k2.6) devuelve un error de tokenization failed.

Inyectar declaraciones de herramientas en mensajes

Inserte un mensaje con role establecido en system en messages y declare las herramientas que se cargarán mediante el campo tools de dicho mensaje. El formato es idéntico al del campo tools de nivel superior de la solicitud, y debe proporcionar la información completa de la herramienta (name, description, parameters).

  • Un mensaje system que lleva tools tiene el mismo estado que un mensaje ordinario: las herramientas se vuelven visibles para el modelo a partir de la posición donde aparece ese mensaje en la lista messages.
  • Las herramientas cargadas dinámicamente coexisten con las herramientas globales declaradas en el campo tools de nivel superior de la solicitud; el modelo puede ver ambos tipos de herramientas al mismo tiempo.
  • Una declaración de herramienta inyectada dinámicamente debe ser una definición completa de herramienta; no puede pasar solo un nombre de herramienta ni hacer referencia a una herramienta declarada globalmente.
  • Un mensaje system que lleva tools no debe llevar también un campo content, de lo contrario la solicitud fallará con un error 400. Al usar el SDK de OpenAI, puede pasar el campo tools directamente en messages.
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID; URLs vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Please calculate 23 * 47 for me."},
        # Dynamically load a tool: insert a system message carrying a tools field into the conversation
        {
            "role": "system",
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "Calculator",
                        "description": "Calculator; evaluates a single arithmetic expression only",
                        "parameters": {
                            "type": "object",
                            "properties": {
                                "expr": {
                                    "type": "string",
                                    "description": "Arithmetic expression supporting basic operations, exponentiation, logarithms, and trigonometric functions, in JavaScript syntax",
                                }
                            },
                            "required": ["expr"],
                        },
                    },
                }
            ],
        },
    ],
)

print(completion.choices[0].message.tool_calls)
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID; URLs vary by region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-d '{
    "model": "kimi-k3",
    "messages": [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Please calculate 23 * 47 for me."},
        {
            "role": "system",
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "Calculator",
                        "description": "Calculator; evaluates a single arithmetic expression only",
                        "parameters": {
                            "type": "object",
                            "properties": {
                                "expr": {
                                    "type": "string",
                                    "description": "Arithmetic expression supporting basic operations, exponentiation, logarithms, and trigonometric functions, in JavaScript syntax"
                                }
                            },
                            "required": ["expr"]
                        }
                    }
                }
            ]
        }
    ]
}'

Carga bajo demanda combinada con una herramienta de búsqueda

No hay una API dedicada de búsqueda de herramientas. Cuando hay muchas herramientas, puede combinar una herramienta de búsqueda personalizada con herramientas cargadas dinámicamente para cargar herramientas bajo demanda:

  1. Al inicio de la sesión, declare en el nivel superior de tools solo una herramienta search_tools implementada por el backend de su aplicación (devuelve nombres de herramientas coincidentes y resúmenes por palabra clave), además de algunas herramientas principales que pueden usarse en cada turno.
  2. Declare las palabras clave buscables (como un catálogo de herramientas o etiquetas de dominio) en el prompt del sistema para guiar al modelo a llamar primero a search_tools cuando necesite una herramienta. Puede establecer tool_choice: "required" en la primera solicitud para forzar al modelo a buscar antes de responder, y luego restaurar tool_choice a "auto" después de la búsqueda. Cambiar tool_choice no rompe la caché de prefijos.
  3. Basándose en los resultados devueltos por search_tools, la aplicación inserta dinámicamente las declaraciones completas de las herramientas correspondientes en messages mediante un mensaje system que lleva tools.
  4. El modelo puede entonces llamar a estas herramientas recién cargadas directamente en la generación subsiguiente.

De esta manera, sin importar cuán grande sea el número total de herramientas, solo unas pocas declaraciones de herramientas están realmente presentes en cada solicitud, manteniendo bajo control la ventana de contexto y la presión de selección del modelo.

Notas

  • Las declaraciones de herramientas dinámicas surten efecto por solicitud y no son recordadas por el servidor. Si se siguen incluyendo en la siguiente solicitud depende del integrador: si se siguen incluyendo, las herramientas permanecen disponibles (lo que también ayuda a acertar en la caché de prefijos); si se deja de incluirlas, la declaración caduca; si la herramienta no se declara en otro lugar, el modelo no puede llamarla y la caché de prefijos después del punto de cambio podría fallar.
  • Agregar una declaración de herramienta dinámica al final de messages no afecta la caché del prefijo existente; eliminar o modificar declaraciones de herramientas anteriores puede afectar los aciertos de caché después del punto de cambio. Declarar herramientas globales en el campo tools de nivel superior de la solicitud tampoco afecta los aciertos de caché.
  • Un mensaje system que lleva tools también consume longitud de contexto, así que inyecte solo las herramientas realmente necesarias para la conversación actual.
  • Las declaraciones de herramientas dinámicas usan exactamente el mismo formato que las declaraciones globales de tools, por lo que los integradores no necesitan mantener dos esquemas.

Parámetros predeterminados

Modelo

enable_thinking

temperature

top_p

presence_penalty

fps

max_frames

kimi-k3

true (solo modo de pensamiento, no se puede deshabilitar)

1.0

0.95

0.0

-

-

kimi-k2.7-code

true (solo modo de pensamiento)

1.0

0.95

0.0

2

2000

kimi-k2.6

false

modo de pensamiento: 1.0

modo sin pensamiento: 0.6

Ambos modos: 0.95

Ambos modos: 0.0

2

2000

kimi-k2.5

false

modo de pensamiento: 1.0

modo sin pensamiento: 0.6

Ambos modos: 0.95

Ambos modos: 0.0

2

2000

Un guion (-) indica que el parámetro no es aplicable.

Modelos y facturación

La serie Kimi consiste en modelos de lenguaje grande de Moonshot AI.

  • kimi-k3: El modelo insignia más capaz de Kimi hasta la fecha. Siempre razona y usa pensamiento preservado (modo de solo pensamiento). Admite entrada de texto e imagen (no se admite entrada de video), tareas de conversación y de agente, y carga dinámica de herramientas.
  • kimi-k2.7-code: El modelo Kimi más capaz para programación. Sigue instrucciones de contexto largo de manera más confiable y logra mayores tasas de éxito en tareas de programación. Admite entrada de texto, imagen y video, modo de pensamiento, conversación y tareas de agente.
  • kimi-k2.6: El modelo más nuevo y capaz de la serie Kimi. Ofrece un rendimiento mejorado en programación de largo alcance, seguimiento de instrucciones y autocorrección. Admite entrada de texto, imagen y video, modos de pensamiento y sin pensamiento, conversación y tareas de agente.
  • kimi-k2.5: Logra un rendimiento de vanguardia (SOTA) en benchmarks de código abierto para tareas de agente, generación de código, comprensión visual y otras tareas de inteligencia general. Admite entrada de imagen, video y texto, modos de pensamiento y sin pensamiento, conversación y tareas de agente.

Notakimi-k3 no admite el parámetro thinking_budget. No puede usar este parámetro para limitar la longitud del pensamiento.

kimi-k3 aún no admite la API de Responses compatible con OpenAI (próximamente). Use la API de Chat Completions compatible con OpenAI en su lugar.

Para precios, consulte facturación de invocación de modelos.

Para detalles sobre precios y ventana de contexto, consulte la consola de Model Studio.

La facturación se basa en los recuentos de tokens de entrada y salida.

En el modo de pensamiento, la cadena de pensamiento cuenta como tokens de salida.

Códigos de error

Si una llamada al modelo falla y devuelve un mensaje de error, consulte Códigos de error.