Kimi K2.7 Code 原生支持基于 MoonViT 视觉编码器的图像与视频输入,在 Agent 工具循环中能够自主调用本地 ffmpeg 切片工具并接收多模态 Base64 回传块,实现高精度的时序视频分析与代码生成。
适合的任务:视频内容时序定位分析、UI 动效/交互录屏审查、视觉 Bug 定位、基于设计稿与视频演示的自动化前端代码编写。
不适合的任务:视频分辨率超过 FHD (1920×1080) 的非压缩大文件直接传输(会导致 Token 膨胀及传输超时)、关闭思维链的轻量调用。
适用的模型版本:kimi-k2.7-code。
适用的客户端、Agent 或 API:OpenAI Python SDK (openai>=1.0)、Kimi 官方 API 端点 (https://api.moonshot.ai/v1)。
推荐的推理档位和参数:tool_choice="auto",视频分辨率推荐最高 FHD (1080p),单次请求 Body 需小于 100MB。
import base64
import json
import os
import subprocess
import tempfile
from pathlib import Path
from openai import OpenAI
# 1. 定义多模态视频切片工具
tools = [{
"type": "function",
"function": {
"name": "watch_video_clip",
"description": "Watch a video file or a sub-clip of it. If start_time and end_time are not provided, the entire video will be returned.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The path to the video file to watch"
},
"start_time": {
"type": "number",
"description": "The start time of the clip in seconds (optional, defaults to 0)"
},
"end_time": {
"type": "number",
"description": "The end time of the clip in seconds (optional, defaults to end of video)"
}
},
"required": ["path"]
}
}
}]
def watch_video_clip(path: str, start_time: float | None = None, end_time: float | None = None) -> list[dict]:
"""截取指定时间段的视频片段并编码为 Base64 多模态块回传。"""
video_path = Path(path)
if not video_path.exists():
raise FileNotFoundError(f"Video file not found: {path}")
# 若未指定时间范围,直接返回完整视频
if start_time is None and end_time is None:
with open(path, "rb") as f:
video_base64 = base64.b64encode(f.read()).decode("utf-8")
return [
{"type": "video_url", "video_url": {"url": f"data:video/mp4;base64,{video_base64}"}},
{"type": "text", "text": f"Full video: {video_path.name}"}
]
# 获取视频时长
probe = subprocess.run(
["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", path],
capture_output=True, text=True
)
duration = float(json.loads(probe.stdout)["format"]["duration"])
start_time = start_time or 0
end_time = end_time or duration
clip_duration = end_time - start_time
# 使用 ffmpeg 提取切片
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
tmp_path = tmp.name
try:
subprocess.run([
"ffmpeg", "-y", "-ss", str(start_time), "-i", path,
"-t", str(clip_duration), "-c:v", "libx264", "-c:a", "aac",
"-preset", "fast", "-crf", "23", "-movflags", "+faststart",
"-loglevel", "error", tmp_path
], check=True)
with open(tmp_path, "rb") as f:
video_base64 = base64.b64encode(f.read()).decode("utf-8")
return [
{"type": "video_url", "video_url": {"url": f"data:video/mp4;base64,{video_base64}"}},
{"type": "text", "text": f"Clip from {video_path.name}: {start_time}s - {end_time}s"}
]
finally:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
# 2. 初始化 OpenAI SDK 客户端
client = OpenAI(
api_key=os.environ.get("MOONSHOT_API_KEY"),
base_url="https://api.moonshot.ai/v1"
)
# 3. 运行多模态 Agent 循环
def agent_loop(user_message: str):
messages = [
{"role": "system", "content": "You are an expert video analysis and engineering assistant. Use watch_video_clip to examine specific portions of videos."},
{"role": "user", "content": user_message}
]
while True:
response = client.chat.completions.create(
model="kimi-k2.7-code",
messages=messages,
tools=tools,
tool_choice="auto"
)
message = response.choices[0].message
messages.append(message.model_dump())
# 若模型没有发起工具调用,说明已生成最终分析/代码
if not message.tool_calls:
return message.content
# 遍历执行工具调用
for tool_call in message.tool_calls:
if tool_call.function.name == "watch_video_clip":
args = json.loads(tool_call.function.arguments)
result = watch_video_clip(
path=args["path"],
start_time=args.get("start_time"),
end_time=args.get("end_time")
)
# 回传多模态工具结果
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
# 示例调用
if __name__ == "__main__":
answer = agent_loop("请分析 ~/Downloads/test_video.mp4 中 8 秒到 13 秒之间的 UI 动画逻辑,并用 Tailwind CSS 实现复刻。")
print(answer)环境准备:安装 openai>=1.0 及系统级依赖 ffmpeg、ffprobe。
配置鉴权:设置环境变量 export MOONSHOT_API_KEY="sk-..."。
注册多模态工具:将工具定义中返回格式设为多模态 Content Block 列表(包含 video_url 或 image_url)。
启动 Agent 循环:模型在思维链中自主推导需要截取的视频时间段,输出 watch_video_clip 工具调用。
多模态结果回传:本地执行 ffmpeg 切片,将 Base64 编码的视频块作为 tool 角色的 content 回传给模型。
最终输出:模型结合视觉帧与时间轴信息完成代码编写与逻辑复核。
多模态架构:Kimi K2.7 Code 搭载原生 MoonViT(400M 参数)视觉编码器,原生支持文本、图像与视频的联合嵌入。
格式支持:
图像格式:PNG, JPEG, WebP, GIF(分辨率建议 $\le 4K$)。
视频格式:MP4, MPEG, MOV, AVI, X-FLV, MPG, WebM, WMV, 3GPP(分辨率建议 $\le FHD$ 1920×1080)。
限制约束:请求体上限 100MB;不支持公网 URL 直传图片/视频,必须使用 Base64 编码或文件上传接口;重复引用的多媒体素材官方建议使用 File Upload API。
视频 Token 计算取决于关键帧数量与分辨率,高分辨率长视频会快速消耗上下文与计费 Token。
vLLM / SGLang 自建部署时,视频多模态对话为实验性功能,需确保推理引擎镜像版本与 MoonViT 算子支持。
官方文档说明:“Image and video token usage is dynamically calculated... For videos, the number of tokens depends on the number of keyframes and their resolution.”
官方建议:“We recommend that image resolution should not exceed 4k... and video resolution should not exceed FHD (1920×1080).”
Kimi K2.7 Code