Tabbit
活动资源博客模型
Tabbit LogoTabbit

Tabbit — 为你工作的 AI 浏览器

主题资源

  • AI Browser Resources
  • Agentic Browser Resources
  • Browser Downloads and Install Guides
  • Browser Comparisons
  • AI Browser Alternatives
  • Browser Productivity Resources

热门指南

  • AI Browser
  • Agentic Browser Download
  • Best AI Browser 2026: Top 9 Tested & Ranked
  • AI Browser Download
  • Free AI Browser
  • Best AI Browser 2026
  • AI Browser Comparison 2026
  • AI Browser for Windows
  • AI Browser for Mac
  • Chrome Alternative 2026

活动

  • 别装了,你在《牛来》里早有原型
  • Tabbit 妙招大赛
  • KPOP SBTI 饭圈人格测试
  • Tabbit 校园共创者计划
  • fifi 的论文文献妙招精选
  • 用户问卷

关于

  • Tabbit 博客
  • 媒体报道
提示词
媒体Kimi K2.7 Code

Kimi K2.7 Code:多模态视频工具调用与 Agent 循环实现

原始来源

Kimi API Platform 官方文档 / Hugging Face Model Card

作者Moonshot AI / Kimi

原文日期2026-06-12

Tabbit 整理2026-08-20

查看原文

一句话结论

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)

测试/工作流步骤

  1. 环境准备:安装 openai>=1.0 及系统级依赖 ffmpeg、ffprobe。

  2. 配置鉴权:设置环境变量 export MOONSHOT_API_KEY="sk-..."。

  3. 注册多模态工具:将工具定义中返回格式设为多模态 Content Block 列表(包含 video_url 或 image_url)。

  4. 启动 Agent 循环:模型在思维链中自主推导需要截取的视频时间段,输出 watch_video_clip 工具调用。

  5. 多模态结果回传:本地执行 ffmpeg 切片,将 Base64 编码的视频块作为 tool 角色的 content 回传给模型。

  6. 最终输出:模型结合视觉帧与时间轴信息完成代码编写与逻辑复核。

原始证据与数据

  • 多模态架构: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).”

Tabbit 小编提醒

提示词内容来自公开资料与 Tabbit 编辑整理。引用前请查看原文授权与适用范围。

Kimi K2.7 Code

在 Tabbit 中使用

Kimi K2.7 Code

相关提示词

媒体Kimi API Platform 官方文档

Kimi K2.7 Code 官方接入与长程编码提示工作流

媒体Kimi API Platform 官方文档

Kimi K2.7 Code:Claude Code 官方接入配置与多层级模型映射

社区GitHub Blog Changelog2026-07-01

Kimi K2.7 Code:GitHub Copilot 官方集成与企业策略配置

社区Unsiloed AI Engineering Blog / Reddit r/LangChain2026-07-20

Unsiloed 评测:从零构建 FastAPI 项目完整提示词与架构标准

Kimi K2.7 Code

相关测评

社区Reddit,r/kimi

Reddit 社区:Kimi K2.7 Code 与 K2.6/K2.5 的选型边界

媒体Hugging Face / Moonshot AI 官方 Model Card2026-06-12

Kimi K2.7 Code:Hugging Face 官方模型规格与全量基准数据

社区Unsiloed AI Engineering Blog / Reddit r/LangChain2026-07-20

Unsiloed 评测:Kimi K2.7 Code 与 GLM 5.2 真实代码生成与大型仓库分析受控对比

社区Reddit r/windsurf / Devin.ai (Cognition)2026-06-24

Devin 团队:FrontierCode Extended 基准与长程工程任务实测表现