Moonshot AI の Kimi CLI を用いた非対話型コーディングワークフローの構築方法
MarkTechPost は、Moonshot AI の Kimi CLI を非対話型エージェントとして構成し、コードベースの分析からテスト実行までの自動化ワークフローを実装する具体的なチュートリアルを公開した。
AI深層分析を開く2026年7月29日 08:08
AI深層分析
キーポイント
非対話型エージェント環境の構築
uv を用いて Python 3.13 の隔離環境で Kimi CLI をインストールし、TOML ベースの設定で Moonshot API 認証を確立する手順が示されている。
自動化された開発ワークフローの実装
コードベースのリスク特定、ソースファイルの自律的な修正、単体テストの生成と実行、そしてテストスイートの合格までの反復プロセスを Python ラッパーで実装している。
高度な機能と統合への言及
構造化 JSONL イベントストリーム、永続的なマルチターンセッション、プランモード、Ralph ループ、MCP 統合などの機能活用について触れられている。
非対話型実行ラッパーの構築
Python ラッパー関数により Kimi CLI をプログラムから呼び出し、インタラクティブなセッションを必要とせずにフラグを動的に組み合わせて実行する。
サンプルプロジェクトでのデモ
バグを含む在庫管理コードを持つ仮想的なプロジェクトを作成し、その構造の要約とリスクの特定を実行する。
重要な引用
configure Kimi CLI as a fully non-interactive AI coding agent
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 define a Python wrapper that executes Kimi CLI prompts programmatically without requiring an interactive terminal session.
kimi("Summarize this project's structure and purpose in under 120 words, " "then list any bugs or design risks you can spot in inventory.py.", work_dir=str(proj))
編集コメントを表示
編集コメント
この記事は、LLM を活用した自律的なコーディングエージェントの実現に向けた具体的な技術的アプローチを提示しており、実務レベルでの応用可能性が高い。Moonshot AI の Kimi CLI が提供する機能を実装言語で詳細に解説している点も評価できる。
Source Article
元記事を日本語で読む
本文に関係しない購読案内、埋め込み通知、サイト内プロモーションは除いています。
本チュートリアルでは、Kimi CLI を完全に非対話型の AI コーディングエージェントとして設定・運用する方法を解説します。まず、uv を用いて孤立した Python 3.13 環境で CLI をインストールし、TOML ベースのプロバイダーとモデル定義を通じて Moonshot API の認証を設定します。さらに、非対話型 CLI コマンドを実行するための再利用可能な Python ラッパーを作成します。
次に、Kimi を現実的なプロジェクトワークフローに適用します。具体的には、コードベースの調査から始まり、実装リスクの特定、ソースファイルの自律的な修正、単体テストの生成、検証コマンドの実行を行います。そして、プロジェクトがテストスイートをパスするまで反復処理を繰り返す流れを実践します。
さらに、構造化された JSONL イベントストリーム、永続的な多ターンセッション、プランモード、モデル選択、Ralph ループ、MCP 統合、セッションのエクスポート、Web ベースでのアクセスなどについても探求します。これにより、Kimi CLI を自動化された開発やエージェントエンジニアリングのパイラインに組み込むための実用的な基盤が得られます。
環境構築と Kimi CLI のインストール
Copy CodeCopiedUse a different Browser
まず、必要な Python モジュールをインポートし、制御されたサブプロセス実行のための再利用可能なシェルコマンドヘルパー関数 sh を定義します。この関数は、指定したコマンドを実行してその出力をストリーム形式で表示し、完了したプロセスオブジェクトを返します。
次に、パッケージ管理ツール「uv」をインストールし、そのバイナリディレクトリを環境パスに追加します。その後、孤立した Python 3.13 ランタイムを使用して Kimi CLI をプロビジョニング(準備)します。最後に、インストールされた Kimi CLI のバージョンを確認することで、セットアップが正常に行われたことを検証します。
Moonshot API の認証設定とモデルアクセス権限の取得については、以下の手順に従ってください。
Copy CodeCopiedUse a different Browser
======================================================================
PART 2: API アクセスの設定
======================================================================
def 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 "{prompt}"'
print(f"\n$ {cmd}\n" + "-" * 60)
r = subprocess.run(cmd, shell=True, capture_output=True,
text=True, timeout=timeout)
out = r.stdout.strip()
print(out if out else r.stderr[-1500:])
return out
この Python ラッパー関数は、対話型ターミナルセッションを必要とせず、プログラムから Kimi CLI のプロンプトを実行できるように設計されています。静かな出力やストリーミング JSON イベントの取得、自律的なツール承認、セッションの継続、作業ディレクトリの隔離、ステップ数の制限など、必要なフラグを動的に組み立てます。そしてコマンドの実行結果を取得し、最終レスポンスまたはエラー詳細を表示して、後続処理のために結果を返します。
現実的なサンプルプロジェクトの作成と分析
Copy CodeCopiedUse a different Browser
print("=" * 70, "\nPART 4: Demo A — codebase Q&A\n", "=" * 70)
proj = pathlib.Path("/content/demo_project")
if proj.exists(): shutil.rmtree(proj)
(proj / "app").mkdir(parents=True)
(proj / "app" / "inventory.py").write_text(textwrap.dedent("""\
class Inventory:
def __init__(self):
self.items = {}
def add(self, name, qty):
self.items[name] = self.items.get(name, 0) + qty
def remove(self, name, qty):
# BUG: allows negative stock and KeyError on missing items
self.items[name] = self.items[name] - qty
def total(self):
return sum(self.items.values())
"""))
(proj / "app" / "main.py").write_text(textwrap.dedent("""\
from inventory import Inventory
inv = Inventory()
inv.add("widget", 10)
inv.remove("widget", 3)
print("Total stock:", inv.total())
"""))
(proj / "README.md").write_text("# Demo: a tiny inventory service\n")
kimi("Summarize this project's structure and purpose in under 120 words, "
"then list any bugs or design risks you can spot in inventory.py.",
work_dir=str(proj))
小さな在庫管理プロジェクトを作成します。Python モジュール、実行スクリプト、README ファイルが含まれています。ここでは意図的に実装上の欠陥を盛り込み、Kimi に対してリポジトリ構造を検索させ、機能面や設計上のリスクを特定させることにします。その後、プロジェクトディレクトリ内で読み取り専用の分析プロンプトを実行し、簡潔な技術評価を求めます。
コードの自動修復、テスト、独立した検証の実行
Kimi を用いてバグを修正し、テストを追加するデモ(パート 5)を実行します。まず、app/inventory.py のバグを修正します。具体的には、存在しないアイテムに対する remove() メソッドが KeyError ではなく ValueError を送出するようにし、負の在庫数を許可しないようにします。次に、プロジェクトルートに tests.py を作成し、unittest を用いて add、remove、total の各メソッドとエッジケースを網羅したテストを実装します。その後、「python -m unittest tests -v」でテストを実行し、すべてのテストがパスするまで反復して改善を行います。最後にテスト結果を表示します。
Kimi にはプロジェクトの自律的な修正、在庫ロジックの正誤修正、ユニットテストの生成、そしてテストスイートの実行を許可します。モデルが失敗の原因を診断し、実装を改良して検証に成功するまで反復できるよう、エージェントステップ数の上限を設定しています。生成された Python ファイルを確認し、独立してテストを再実行することで、生成された変更が正しく機能するかを検証します。
構造化された JSONL ストリーミング、セッション管理、そして高度な機能について探求します。
print("=" * 70, "\nPART 6: Demo C — machine-readable JSONL events\n", "=" * 70)
raw = kimi("In one sentence, what does app/main.py print when run?",
work_dir=str(proj), stream_json=True, quiet=False)
print("\nParsed event types:")
for line in raw.splitlines():
try:
evt = json.loads(line)
print(" •", evt.get("type", "?"), "-",
str(evt)[:100].replace("\n", " "))
except json.JSONDecodeError:
pass
print("=" * 70, "\nPART 7: Demo D — conversational memory\n", "=" * 70)
kimi("Remember this: our release codename is BLUE-FALCON.", work_dir=str(proj))
kimi("What is our release codename? Answer with just the codename.",
work_dir=str(proj), cont=True)
print("=" * 70, "\nPART 8: Power-user reference\n", "=" * 70)
print(textwrap.dedent("""
# Plan mode — read-only exploration, produces an implementation plan:
kimi --quiet --plan -w /content/demo_project -p "Plan adding SQLite persistence"
# Pick a different model at runtime (must exist in config.toml):
kimi --quiet -m kimi-k2 -p "hello"
# Thinking mode (if the model supports it):
kimi --quiet --thinking -p "Prove sqrt(2) is irrational"
# Ralph loop — feed the same prompt repeatedly for one big task
# until the agent outputs STOP or the limit hits:
kimi --print --yolo --max-ralph-iterations 5 -w /content/demo_project \\
-p "Keep improving test coverage; STOP when everything is covered."
# MCP tools — give Kimi extra capabilities via an MCP config file:
/content/mcp.json -> {"mcpServers": {"context7":
# {"url": "https://mcp.context7.com/mcp",
# "headers": {"CONTEXT7_API_KEY": "YOUR_KEY"}}}}
kimi --quiet --mcp-config-file /content/mcp.json -p "Use context7 to ..."
# Export a session (context.jsonl, wire.jsonl, state.json) for debugging:
kimi export --yes
# Web UI (needs a tunnel on Colab, e.g. cloudflared/ngrok, since it
# binds locally): kimi web --no-open --port 5494
"""
)
print("Tutorial complete
image — Kimi CLI is installed, authenticated, and has "
"explored, fixed, tested, and remembered a real project headlessly.")
Kimi を実行してストリーミングされた JSON 出力を取得し、JSONL イベントを解析することで機械可読なレスポンスタイプを確認します。また、同じ作業ディレクトリ内でセッション中にリリースコードネームを保存・取得する機能により、複数回の対話でも情報を保持できることを実証しました。最後に、プランニングやモデルの切り替え、思考モード、Ralph ループ、MCP ツールの利用、セッションのエクスポート、Web へのアクセスといった高度なコマンドについて解説します。
結論として、インタラクティブなターミナルセッションに依存しないエンドツーエンドのKimi CLIワークフローを確立しました。環境の用意やAPI設定から始まり、プロジェクト分析、自律的なコード修復、テスト生成、構造化出力の解析、そしてセッションの継続までを一貫して処理できる仕組みを作りました。
また、エージェントによる変更点を独立して検証することで、生成された出力と実際の実行結果を明確に区別し、ワークフロー全体の信頼性を高めています。再利用可能なラッパー関数や参照コマンドを整備したおかげで、このアーキテクチャはより大規模なリポジトリへの適用、CIスタイルの検証タスク、MCP対応ツールチェーンとの連携、ソフトウェア改善のための反復ループ、そして他のプログラム可能なAI支援開発ワークフローなどへも拡張可能です。
詳細なコードはこちらでご覧ください。Twitterでフォローしていただくと幸いです。また、15万人以上のMLエンジニアが参加するRedditコミュニティにご参加ください。ニュースレターへの登録もお忘れなく!
Telegramをご利用の方にも好消息です。今ならTelegramでも私たちに参加いただけます。
本記事「Moonshot AIのKimi CLIを用いた非対話型エージェントコーディングワークフロー:JSONLストリーミング、テスト、セッションメモリ」はMarkTechPostで公開されています。
原文を表示
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 Browser
import 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 Browser
print("=" * 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 Browser
def 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 "{prompt}"'
print(f"\n$ {cmd}\n" + "-" * 60)
r = subprocess.run(cmd, shell=True, capture_output=True,
text=True, timeout=timeout)
out = r.stdout.strip()
print(out if out else r.stderr[-1500:])
return out
We define a Python wrapper that executes Kimi CLI prompts programmatically without requiring an interactive terminal session. We dynamically assemble flags for quiet output, streamed JSON events, autonomous tool approval, session continuation, working-directory isolation, and step limits. We capture the command output, display the final response or error details, and return the result for further processing.
Creating and Analyzing a Realistic Sample Project
Copy CodeCopiedUse a different Browser
print("=" * 70, "\nPART 4: Demo A — codebase Q&A\n", "=" * 70)
proj = pathlib.Path("/content/demo_project")
if proj.exists(): shutil.rmtree(proj)
(proj / "app").mkdir(parents=True)
(proj / "app" / "inventory.py").write_text(textwrap.dedent("""\
class Inventory:
def __init__(self):
self.items = {}
def add(self, name, qty):
self.items[name] = self.items.get(name, 0) + qty
def remove(self, name, qty):
# BUG: allows negative stock and KeyError on missing items
self.items[name] = self.items[name] - qty
def total(self):
return sum(self.items.values())
"""))
(proj / "app" / "main.py").write_text(textwrap.dedent("""\
from inventory import Inventory
inv = Inventory()
inv.add("widget", 10)
inv.remove("widget", 3)
print("Total stock:", inv.total())
"""))
(proj / "README.md").write_text("# Demo: a tiny inventory service\n")
kimi("Summarize this project's structure and purpose in under 120 words, "
"then list any bugs or design risks you can spot in inventory.py.",
work_dir=str(proj))
We create a small inventory management project that includes a Python module, an executable script, and a README file. We intentionally include implementation defects to enable Kimi to inspect the repository structure and identify functional and design risks. We then run a read-only project analysis prompt in the project directory and request a concise technical assessment.
Automating Code Repair, Testing, and Independent Validation
Copy CodeCopiedUse a different Browser
print("=" * 70, "\nPART 5: Demo B — Kimi fixes the bug & adds tests\n", "=" * 70)
kimi("Fix the bugs in app/inventory.py: remove() must raise KeyError->ValueError "
"for unknown items and never allow negative stock. Then create tests.py at "
"the project root using unittest covering add/remove/total and edge cases, "
"run it with 'python -m unittest tests -v', and iterate until all tests pass. "
"Finally print the test results.",
work_dir=str(proj), yolo=True, extra="--max-steps-per-turn 30")
print("\n--- Files after Kimi's edits ---")
for f in sorted(proj.rglob("*.py")):
print(f"\n### {f.relative_to(proj)} ###\n{f.read_text()}")
sh("python -m unittest tests -v", cwd=str(proj), check=False)
We allow Kimi to modify the project autonomously, correct the inventory logic, generate unit tests, and execute the test suite. We configure a maximum agent-step limit so the model can iteratively diagnose failures and refine its implementation until validation succeeds. We inspect the resulting Python files and independently rerun the tests to confirm that the generated changes work correctly.
Exploring Structured JSONL, Sessions, and Advanced Features
Copy CodeCopiedUse a different Browser
print("=" * 70, "\nPART 6: Demo C — machine-readable JSONL events\n", "=" * 70)
raw = kimi("In one sentence, what does app/main.py print when run?",
work_dir=str(proj), stream_json=True, quiet=False)
print("\nParsed event types:")
for line in raw.splitlines():
try:
evt = json.loads(line)
print(" •", evt.get("type", "?"), "-",
str(evt)[:100].replace("\n", " "))
except json.JSONDecodeError:
pass
print("=" * 70, "\nPART 7: Demo D — conversational memory\n", "=" * 70)
kimi("Remember this: our release codename is BLUE-FALCON.", work_dir=str(proj))
kimi("What is our release codename? Answer with just the codename.",
work_dir=str(proj), cont=True)
print("=" * 70, "\nPART 8: Power-user reference\n", "=" * 70)
print(textwrap.dedent("""
# Plan mode — read-only exploration, produces an implementation plan:
kimi --quiet --plan -w /content/demo_project -p "Plan adding SQLite persistence"
# Pick a different model at runtime (must exist in config.toml):
kimi --quiet -m kimi-k2 -p "hello"
# Thinking mode (if the model supports it):
kimi --quiet --thinking -p "Prove sqrt(2) is irrational"
# Ralph loop — feed the same prompt repeatedly for one big task
# until the agent outputs <choice>STOP</choice> or the limit hits:
kimi --print --yolo --max-ralph-iterations 5 -w /content/demo_project \\
-p "Keep improving test coverage; STOP when everything is covered."
# MCP tools — give Kimi extra capabilities via an MCP config file:
# /content/mcp.json -> {"mcpServers": {"context7":
# {"url": "https://mcp.context7.com/mcp",
# "headers": {"CONTEXT7_API_KEY": "YOUR_KEY"}}}}
kimi --quiet --mcp-config-file /content/mcp.json -p "Use context7 to ..."
# Export a session (context.jsonl, wire.jsonl, state.json) for debugging:
kimi export --yes
# Web UI (needs a tunnel on Colab, e.g. cloudflared/ngrok, since it
# binds locally): kimi web --no-open --port 5494
"""))
print("Tutorial complete
image — Kimi CLI is installed, authenticated, and has "
"explored, fixed, tested, and remembered a real project headlessly.")
We execute Kimi with streamed JSON output and parse each JSONL event to inspect machine-readable response types. We demonstrate persistent multi-turn memory by storing a release codename and retrieving it during an ongoing session in the same working directory. We conclude by reviewing advanced commands for planning, model switching, thinking mode, Ralph loops, MCP tools, session export, and web access.
In conclusion, we established an end-to-end Kimi CLI workflow that runs entirely without relying on an interactive terminal session. We moved from environment provisioning and API configuration to project analysis, autonomous code repair, test generation, structured output parsing, and session continuation. We also independently verified the agent’s changes, which helps us distinguish generated output from actual execution results and improves the reliability of the workflow. With the reusable wrapper and reference commands in place, we can now extend the same architecture to larger repositories, CI-style validation tasks, MCP-enabled toolchains, iterative software improvement loops, and other programmable AI-assisted development workflows.
Check out the Full Code here. Also, feel free to follow us on Twitter and don’t forget to join our 150k+ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.
Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us
The post Building Non-Interactive Agentic Coding Workflows with Moonshot AI’s Kimi CLI, JSONL Streaming, Testing, and Session Memory appeared first on MarkTechPost.
AI算出
技術分析ainew評価標準
記事は Moonshot AI の Kimi CLI という特定のツールを用いた、再現可能な非対話型コーディングワークフローの構築方法を技術的に詳述しており、AI エージェントの実運用という点で高い関連性と新規性を持つ。ただし、対象が中国発のツールであり日本固有の事情や企業事例に言及がないため、日本の読者への直接的な付加価値は限定的である。
6つの評価軸を見る
- AI関連度
- 90
- 情報源の信頼性
- 25
- 新規性
- 75
- 調べる価値
- 75
- 重複の少なさ
- 100
- 日本での有用性
- 25
関連記事
今日のまとめ
AIデイリーブリーフで今日の重要ニュースをまとめ読み