Este documento descreve como chamar o service de inferência do modelo Kimi implantado no Alibaba Cloud Model Studio.
ImportanteOs modelos Moonshot-Kimi-K2-Instruct e kimi-k2-thinking foram descontinuados em 9 de julho de 2026. Recomendamos a migração para qwen3.7-plus, qwen3.8-max ou qwen3.8-flash.
Regiões suportadas: China (Beijing), Singapore, Japan (Tokyo), China (Hong Kong), Germany (Frankfurt) e US (Virginia).
Experiência com o modelo: Experimente o modelo Kimi no centro de testes de modelos.
Os endpoints de service são específicos por região. Configure a URL base correta para sua região.
OpenAI compatible
US (Virginia)
O parâmetro base_url para chamadas SDK é: https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1
URL da requisição HTTP: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Germany (Frankfurt)
O parâmetro base_url para chamadas SDK é: https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1
URL da requisição HTTP: POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Singapore
O parâmetro base_url para chamadas SDK é: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
URL da requisição HTTP: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Japan (Tokyo)
O parâmetro base_url para chamadas SDK é: https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1
URL da requisição HTTP: POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
China (Beijing)
O parâmetro base_url para chamadas SDK é: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
URL da requisição HTTP: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions
China (Hong Kong)
O parâmetro base_url para chamadas SDK é: https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1
URL da requisição HTTP: POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/chat/completions
DashScope
US (Virginia)
A URL da requisição HTTP para modelos de texto, como kimi-k2-thinking, é POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
A URL da requisição HTTP para modelos multimodais, como kimi-k2.6 e kimi-k2.5, é POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
O parâmetro base_url para chamadas SDK é:
Python code
dashscope.base_http_api_url = 'https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1'
Java code
- 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)
A URL da requisição HTTP para modelos de texto, como kimi-k2-thinking, é POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
A URL da requisição HTTP para modelos multimodais, como kimi-k2.7-code, kimi-k2.6 e kimi-k2.5, é POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
O parâmetro base_url para chamadas SDK é:
Python code
dashscope.base_http_api_url = 'https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1'
Java code
- 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
A URL da requisição HTTP para modelos de texto, como kimi-k2-thinking, é POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
A URL da requisição HTTP para modelos multimodais, como kimi-k2.7-code, kimi-k2.6 e kimi-k2.5, é POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
O parâmetro base_url para chamadas SDK é:
Python code
# 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'
Java code
- Opção 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");
- Opção 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)
A URL da requisição HTTP para modelos de texto, como kimi-k2-thinking, é POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
A URL da requisição HTTP para modelos multimodais, como kimi-k2.7-code, kimi-k2.6 e kimi-k2.5, é POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
O parâmetro base_url para chamadas SDK é:
Python code
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1'
Java code
- Opção 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1");
- Opção 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1";
China (Hong Kong)
A URL da requisição HTTP para modelos de texto, como kimi-k2-thinking, é POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
A URL da requisição HTTP para modelos multimodais, como kimi-k2.7-code, kimi-k2.6 e kimi-k2.5, é POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
O parâmetro base_url para chamadas SDK é:
Python code
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1'
Java code
- 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)
A URL da requisição HTTP para modelos de texto, como kimi-k2-thinking, é POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
A URL da requisição HTTP para modelos multimodais, como kimi-k2.7-code, kimi-k2.6 e kimi-k2.5, é POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
O parâmetro base_url para chamadas SDK é:
Python code
# 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'
Java code
- Opção 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");
- Opção 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";
Substitua {WorkspaceId} pelo seu workspace ID real.
Pré-requisitos: Você deve get an API key e set it as an environment variable. Se usar o SDK, você deve install the SDK.
Primeiros passos
Os exemplos a seguir usam apenas entrada de texto. Para exemplos multimodais, consulte chamada multimodal.
OpenAI compatible
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-k2.6",
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
Resposta
====================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-k2.6',
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();
Resposta
====================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-k2.6",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"enable_thinking": true
}'
Resposta
{
"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-k2.6",
"id": "chatcmpl-485ab490-90ec-48c3-85fa-1c732b683db2"
}
DashScope
Os exemplos do DashScope a seguir usam o endpoint
multimodal-generationpara chamar o kimi-k2.6, que suporta entrada de texto e multimodal. Para mais exemplos multimodais, consulte chamada 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-k2.6",
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
Resposta
====================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-k2.6")
.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);
}
}
Resposta
====================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.
The response should include:
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, etc.
I should not pretend to be human or provide excessive technical details. A clear and friendly answer is sufficient.
====================Complete 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-k2.6",
"input":{
"messages":[
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters": {
"result_format": "message",
"enable_thinking": true
}
}'
Resposta
{
"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"
}
Anthropic compatible
Python
Código de exemplo
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-k2.6",
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 exemplo
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-k2.6",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "Who are you?"
}
]
}'
Chamadas multimodais
Os modelos kimi-k2.7-code, kimi-k2.6 e kimi-k2.5 processam simultaneamente texto, imagens ou vídeo. Use o parâmetro enable_thinking para ativar o modo de raciocínio. Os exemplos a seguir mostram como utilizar esse recurso.
Ativar ou desativar o modo de raciocínio
Os modelos kimi-k2.6 e kimi-k2.5 são híbridos de raciocínio. Eles podem responder após raciocinar ou responder diretamente. Utilize o parâmetro enable_thinking para controlar a ativação do modo de raciocínio:
true: Ativa o modo de raciocíniofalse(padrão): Desativa o modo de raciocínio
O modelo kimi-k2.7-code opera exclusivamente com raciocínio: o modo de raciocínio está sempre ativado (enable_thinking tem como padrão true e não pode ser desativado), e preserve_thinking tem como padrão true.
O kimi-k2.6 permite transmitir o processo de raciocínio em conversas de múltiplas turnos por meio do parâmetro preserve_thinking. Para mais informações, consulte Pass the thinking process.
Os exemplos abaixo demonstram como usar uma URL de imagem e ativar o modo de raciocínio. O exemplo principal ilustra a entrada de uma única imagem, enquanto o código comentado serve como exemplo para entrada de múltiplas imagens.
OpenAI compatible
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
# }
# }'
Compreensão de vídeo
Video file
Os modelos kimi-k2.7-code, kimi-k2.6 e kimi-k2.5 analisam vídeos extraindo uma sequência de quadros. Controle a estratégia de extração de quadros com os seguintes parâmetros:
-
fps: Controla a frequência de extração de quadros. O intervalo entre os quadros extraídos é de \frac 1 {fps} segundos. O valor deve estar no intervalo de [0,1, 10]. O valor padrão é 2,0.
- Para cenas com muito movimento: Defina um valor de fps mais alto para capturar mais detalhes.
- Para vídeos estáticos ou longos: Defina um valor de fps mais baixo para melhorar a eficiência do processamento.
-
max_frames: Especifica o número máximo de quadros a serem extraídos de um vídeo. O valor padrão e máximo é 2000.
Se o número de quadros calculado a partir do valor de fps exceder esse limite, o sistema extrairá quadros uniformemente para permanecer dentro do limite de max_frames. Este parâmetro está disponível apenas quando você usa o DashScope SDK.
OpenAI compatible
Ao passar um arquivo de vídeo para o modelo usando o OpenAI SDK ou uma requisição HTTP, defina o parâmetro
"type"na mensagem do usuário como"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?"}]}]}
}'
Image list
Ao fornecer um vídeo como uma lista de imagens (quadros pré-extraídos), use o parâmetro fps para especificar a taxa de extração de quadros do vídeo original. Esse valor indica que os quadros foram extraídos a cada \frac 1 {fps} segundos, permitindo que o modelo compreenda melhor a sequência de eventos, a duração e as mudanças dinâmicas.
OpenAI compatible
Ao passar um vídeo como uma lista de imagens usando o OpenAI SDK ou uma requisição HTTP, defina o parâmetro
"type"na mensagem do usuário como"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."
}
]
}
]
}
}'
Passar um arquivo local
Os exemplos a seguir mostram como passar um arquivo local. A API compatível com OpenAI suporta apenas codificação Base64, enquanto o DashScope suporta tanto codificação Base64 quanto caminhos de arquivo.
OpenAI compatible
Para passar um arquivo local usando codificação Base64, construa uma Data URL. Para instruções, consulte Construct a 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
Base64 encoding
Para passar um arquivo local usando codificação Base64, construa uma Data URL. Para instruções, consulte Construct a 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();
}
File path
É possível passar um caminho de arquivo local diretamente para o modelo. Este método é suportado apenas pelos SDKs Python e Java do DashScope; não está disponível para DashScope HTTP ou para a API compatível com OpenAI. A tabela abaixo mostra o formato de caminho de arquivo necessário para cada linguagem de programação e sistema operacional.
Especificar um caminho de arquivo (exemplo de imagem)
Sistema | SDK | Formato do caminho | Exemplo |
|---|---|---|---|
Linux ou macOS | Python SDK | file://{caminho absoluto do arquivo} | file:///home/images/test.png |
Java SDK | |||
Windows | Python SDK | file://{caminho absoluto do arquivo} | file://D:/images/test.png |
Java SDK | file:///{caminho absoluto do arquivo} | 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();
}
Limitações de arquivos
Image limitations
-
Resolução da imagem:
- Tamanho mínimo: Largura e altura devem exceder
10pixels cada. - Proporção: A razão entre o lado mais longo e o mais curto não deve exceder
200:1. - Resolução máxima: O máximo recomendado é
8K(7680x4320). Resoluções maiores podem causar timeouts na chamada da API devido ao tamanho grande dos arquivos ou transferências de rede lentas.
- Tamanho mínimo: Largura e altura devem exceder
-
Formatos de imagem suportados
-
Os seguintes formatos são suportados para resoluções abaixo de 4K
(3840x2160):Formato de imagem
Extensão de arquivo
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 resoluções entre
4K(3840x2160)e8K(7680x4320), apenas JPEG, JPG e PNG são suportados.
-
-
Tamanho da imagem:
- Ao fornecer uma imagem via URL pública ou caminho local, seu tamanho não deve exceder
10 MB. - Ao usar codificação Base64, a string codificada não deve exceder
10 MB.
Para compactar um arquivo, consulte How to compress an image or video to meet the size limit .
- Ao fornecer uma imagem via URL pública ou caminho local, seu tamanho não deve exceder
-
Número de imagens suportadas: Ao fornecer várias imagens, o número total de tokens para todas as imagens e texto não deve exceder o limite máximo de entrada do modelo.
Video limitations
-
Como lista de imagens: De 4 a 2.000 imagens.
-
Como arquivo de vídeo:
-
Tamanho do vídeo:
- Via URL pública: Até 2 GB.
- Via codificação Base64: a string codificada deve ter menos de 10 MB.
- Via caminho de arquivo local: Até 100 MB.
-
Duração do vídeo: De 2 segundos a 1 hora.
-
Tamanho do vídeo:
-
Formato de vídeo: Os formatos suportados incluem MP4, AVI, MKV, MOV, FLV e WMV.
-
Resolução do vídeo: Embora não haja um limite estrito de resolução, use 2K ou inferior para obter melhores resultados. Resoluções mais altas aumentam o tempo de processamento sem melhorar a compreensão do modelo.
-
Compreensão de áudio: O modelo não processa a faixa de áudio em arquivos de vídeo.
Outros recursos
Modelo | |||||||
|---|---|---|---|---|---|---|---|
kimi-k2.7-code | Suportado | Suportado | Suportado | Não suportado | Não suportado | Não suportado | Suportado |
kimi-k2.6 | Suportado | Suportado | Suportado | Não suportado | Não suportado | Não suportado | Suportado |
kimi-k2.5 | Suportado | Suportado | Suportado | Não suportado | Não suportado | Não suportado | Suportado |
kimi-k2-thinking | Suportado | Suportado | Suportado | Suportado | Não suportado | Não suportado | Suportado |
Moonshot-Kimi-K2-Instruct | Suportado | Não suportado | Suportado | Não suportado | Suportado | Não suportado | Suportado |
Parâmetros padrão
Modelo | enable_thinking | temperature | top_p | presence_penalty | fps | max_frames |
|---|---|---|---|---|---|---|
kimi-k2.7-code | true (apenas modo de raciocínio) | 1.0 | 0.95 | 0.0 | 2 | 2000 |
kimi-k2.6 | false | modo de raciocínio: 1.0 modo sem raciocínio: 0.6 | Ambos os modos: 0.95 | Ambos os modos: 0.0 | 2 | 2000 |
kimi-k2.5 | false | modo de raciocínio: 1.0 modo sem raciocínio: 0.6 | Ambos os modos: 0.95 | Ambos os modos: 0.0 | 2 | 2000 |
kimi-k2-thinking | - | 1.0 | - | - | - | - |
Moonshot-Kimi-K2-Instruct | - | 0.6 | 1.0 | 0 | - | - |
Um hífen (-) indica que o parâmetro não se aplica.
Modelos e faturamento
A série Kimi consiste em grandes modelos de linguagem da Moonshot AI.
- kimi-k2.7-code: O modelo Kimi mais capaz para codificação. Segue instruções de contexto longo com mais confiabilidade e alcança taxas de sucesso mais altas em tarefas de programação. Suporta entrada de texto, imagem e vídeo, modo de raciocínio, conversação e tarefas de agente.
- kimi-k2.6: O modelo mais novo e capaz da série Kimi. Oferece desempenho aprimorado em codificação de longo horizonte, seguimento de instruções e autocorreção. Suporta entrada de texto, imagem e vídeo, modos de raciocínio e sem raciocínio, conversação e tarefas de agente.
- kimi-k2.5: Alcança desempenho de última geração (SOTA) em benchmarks de código aberto para tarefas de agente, geração de código, compreensão visual e outras tarefas de inteligência geral. Suporta entrada de imagem, vídeo e texto, modos de raciocínio e sem raciocínio, conversação e tarefas de agente.
- kimi-k2-thinking: Suporta apenas o modo de raciocínio profundo. Expõe o processo de raciocínio através do campo
reasoning_content. Destaca-se em codificação e chamada de ferramentas, sendo adequado para casos de uso que exigem análise lógica, planejamento ou compreensão profunda. - Moonshot-Kimi-K2-Instruct: Não suporta raciocínio profundo. Gera respostas com menor latência, sendo adequado para casos de uso que precisam de respostas rápidas e diretas.
Para preços do kimi-k2.7-code, consulte model invocation billing .
Para detalhes sobre preços e janela de contexto, consulte o console do Model Studio.
O faturamento é baseado nas contagens de tokens de entrada e saída.
No modo de raciocínio, a cadeia de pensamento conta como tokens de saída.
Códigos de erro
Se uma chamada de modelo falhar e retornar uma mensagem de erro, consulte Error codes.