Daily Tech Briefing
AI 科技速览
每天 5 分钟内学习 AI。获取最新的人工智能新闻,理解其重要性,并学习如何将其应用于您的工作。
MarkTechPost · 2026/7/28 23:04:44
Building Non-Interactive Agentic Coding Workflows with Moonshot AI’s Kimi CLI, JSONL Streaming, Testing, and Session Memory
AI 中文解读
Kimi CLI来了!这次Moonshot AI把AI编程助手变成了全自动的“幕后工作者”,再也不用一边写代码一边跟AI反复对话了。你只需要给它一个任务,它就能自己分析代码库、找出潜在问题、修改源文件、生成单元测试、反复运行验证,直到所有测试通过——全程不需要人工干预。为了让这一切更高效,它还支持结构化的JSONL事件流、持久化的多轮会话记忆,甚至能和MCP工具链深度集成。对开发者来说,这意味着一键式的自动化开发和工程流水线不再是梦想,可以把大量繁琐的代码调试和测试工作交给AI,自己专注于更核心的设计和创新。虽然普通用户看不到背后这些工具,但未来你用到的软件更新肯定会更快、Bug更少,因为AI编码代理正在成为程序员的新标配。
In this tutorial, we configure and operate Kimi CLI as a fully non-interactive AI coding agent. We install the CLI through uv with an isolated Python 3.13 environment, configure Moonshot API authentication through a TOML-based provider and model definition, and build a reusable Python wrapper for executing non-interactive CLI commands. We then apply Kimi to a realistic project workflow in which we inspect a codebase, identify implementation risks, autonomously modify source files, generate unit tests, execute validation commands, and iterate until the project passes its test suite. We also explore structured JSONL event streams, persistent multi-turn sessions, plan mode, model selection, Ralph loops, MCP integrations, session export, and web-based access, giving us a practical foundation for embedding Kimi CLI into automated development and agentic engineering pipelines.
Environment Setup and Kimi CLI Installation
Copy CodeCopiedUse a different Browserimport os, subprocess, textwrap, json, getpass, pathlib, shutil
HOME = pathlib.Path.home()
def sh(cmd, check=True, env=None, cwd=None):
"""Run a shell command, stream its output, return CompletedProcess."""
print(f"\n$ {cmd}")
e = {**os.environ, **(env or {})}
r = subprocess.run(cmd, shell=True, env=e, cwd=cwd,
capture_output=True, text=True)
if r.stdout: print(r.stdout)
if r.stderr: print(r.stderr[-2000:])
if check and r.returncode != 0:
raise RuntimeError(f"Command failed ({r.returncode}): {cmd}")
return r
print("=" * 70, "\nPART 1: Installing uv + Kimi CLI\n", "=" * 70)
sh("curl -LsSf https://astral.sh/uv/install.sh | sh")
UV_BIN = str(HOME / ".local" / "bin")
os.environ["PATH"] = f"{UV_BIN}:{os.environ['PATH']}"
sh("uv tool install --python 3.13 kimi-cli")
sh("kimi --version")
We begin by importing the required Python modules and defining a reusable shell-command helper for controlled subprocess execution. We install uv, add its binary directory to the environment path, and use it to provision Kimi CLI with an isolated Python 3.13 runtime. We then verify the installation by querying the installed Kimi CLI version.
Configuring Moonshot API Authentication and Model Access
Copy CodeCopiedUse a different Browserprint("=" * 70, "\nPART 2: Configuring API access\n", "=" * 70)
try:
from google.colab import userdata
API_KEY = userdata.get("MOONSHOT_API_KEY")
print("Loaded key from Colab Secrets.")
except Exception:
API_KEY = getpass.getpass("Paste your Moonshot API key (hidden): ")
BASE_URL = "https://api.moonshot.ai/v1"
MODEL_NAME = "kimi-k2-0711-preview"
kimi_dir = HOME / ".kimi"
kimi_dir.mkdir(exist_ok=True)
(kimi_dir / "config.toml").write_text(textwrap.dedent(f"""\
default_model = "kimi-k2"
[providers.moonshot]
type = "kimi"
base_url = "{BASE_URL}"
api_key = "{API_KEY}"
[models.kimi-k2]
provider = "moonshot"
model = "{MODEL_NAME}"
max_context_size = 131072
"""))
print("Wrote ~/.kimi/config.toml")
We securely retrieve the Moonshot API key from Google Colab Secrets or request it via a hidden input prompt. We define the Moonshot API endpoint and target Kimi model, then create the required .kimi configuration directory. We write the provider, model, context window, and default model settings to config.toml for non-interactive authentication.
Building a Reusable Non-Interactive Kimi Execution Wrapper
Copy CodeCopiedUse a different Browserdef kimi(prompt, work_dir=".", yolo=False, cont=False, quiet=True,
stream_json=False, extra="", timeout=600):
"""Run one headless Kimi CLI turn and return its stdout."""
flags = []
if stream_json:
flags.append("--print --output-format stream-json")
elif quiet:
flags.append("--quiet")
else:
flags.append("--print")
if yolo: flags.append("--yolo")
if cont: flags.append("--continue")
flags.append(f'-w "{work_dir}"')
if extra: flags.append(extra)
cmd = f'kimi {" ".join(flags)} -p
分享
阅读原文 ↗