Building Non-Interactive Agentic Coding Workflows with Moonshot AI’s Kimi CLI, JSONL Streaming, Testing, and Session Memory
In this tutorial, we configure and function Kimi CLI as a totally non-interactive AI coding agent. We set up the CLI by uv with an remoted Python 3.13 atmosphere, configure Moonshot API authentication by a TOML-based supplier and mannequin definition, and construct a reusable Python wrapper for executing non-interactive CLI instructions. We then apply Kimi to a sensible venture workflow through which we examine a codebase, determine implementation dangers, autonomously modify supply recordsdata, generate unit exams, execute validation instructions, and iterate till the venture passes its take a look at suite. We additionally discover structured JSONL occasion streams, persistent multi-turn periods, plan mode, mannequin choice, Ralph loops, MCP integrations, session export, and web-based entry, giving us a sensible basis for embedding Kimi CLI into automated growth and agentic engineering pipelines.
Environment Setup and Kimi CLI Installation
import os, subprocess, textwrap, json, getpass, pathlib, shutil
HOME = pathlib.Path.dwelling()
def sh(cmd, test=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, textual content=True)
if r.stdout: print(r.stdout)
if r.stderr: print(r.stderr[-2000:])
if test and r.returncode != 0:
increase RuntimeError(f"Command failed ({r.returncode}): {cmd}")
return r
print("=" * 70, "nPART 1: Installing uv + Kimi CLIn", "=" * 70)
sh("curl -LsSf https://astral.sh/uv/set up.sh | sh")
UV_BIN = str(HOME / ".native" / "bin")
os.environ["PATH"] = f"{UV_BIN}:{os.environ['PATH']}"
sh("uv instrument set up --python 3.13 kimi-cli")
sh("kimi --version")
We start by importing the required Python modules and defining a reusable shell-command helper for managed subprocess execution. We set up uv, add its binary listing to the atmosphere path, and use it to provision Kimi CLI with an remoted Python 3.13 runtime. We then confirm the set up by querying the put in Kimi CLI model.
Configuring Moonshot API Authentication and Model Access
print("=" * 70, "nPART 2: Configuring API accessn", "=" * 70)
strive:
from google.colab import userdata
API_KEY = userdata.get("MOONSHOT_API_KEY")
print("Loaded key from Colab Secrets.")
besides 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]
sort = "kimi"
base_url = "{BASE_URL}"
api_key = "{API_KEY}"
[models.kimi-k2]
supplier = "moonshot"
mannequin = "{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 by way of a hidden enter immediate. We outline the Moonshot API endpoint and goal Kimi mannequin, then create the required .kimi configuration listing. We write the supplier, mannequin, context window, and default mannequin settings to config.toml for non-interactive authentication.
Building a Reusable Non-Interactive Kimi Execution Wrapper
def kimi(immediate, work_dir=".", yolo=False, cont=False, quiet=True,
stream_json=False, additional="", timeout=600):
"""Run one headless Kimi CLI flip 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 additional: flags.append(additional)
cmd = f'kimi {" ".be part of(flags)} -p "{immediate}"'
print(f"n$ {cmd}n" + "-" * 60)
r = subprocess.run(cmd, shell=True, capture_output=True,
textual content=True, timeout=timeout)
out = r.stdout.strip()
print(out if out else r.stderr[-1500:])
return out
We outline a Python wrapper that executes Kimi CLI prompts programmatically with out requiring an interactive terminal session. We dynamically assemble flags for quiet output, streamed JSON occasions, autonomous instrument approval, session continuation, working-directory isolation, and step limits. We seize the command output, show the ultimate response or error particulars, and return the outcome for additional processing.
Creating and Analyzing a Realistic Sample Project
print("=" * 70, "nPART 4: Demo A — codebase Q&An", "=" * 70)
proj = pathlib.Path("/content material/demo_project")
if proj.exists(): shutil.rmtree(proj)
(proj / "app").mkdir(dad and mom=True)
(proj / "app" / "stock.py").write_text(textwrap.dedent("""
class Inventory:
def __init__(self):
self.gadgets = {}
def add(self, identify, qty):
self.gadgets[name] = self.gadgets.get(identify, 0) + qty
def take away(self, identify, qty):
# BUG: permits damaging inventory and KeyError on lacking gadgets
self.gadgets[name] = self.gadgets[name] - qty
def complete(self):
return sum(self.gadgets.values())
"""))
(proj / "app" / "most important.py").write_text(textwrap.dedent("""
from stock import Inventory
inv = Inventory()
inv.add("widget", 10)
inv.take away("widget", 3)
print("Total inventory:", inv.complete())
"""))
(proj / "README.md").write_text("# Demo: a tiny stock servicen")
kimi("Summarize this venture's construction and objective in underneath 120 phrases, "
"then listing any bugs or design dangers you'll be able to spot in stock.py.",
work_dir=str(proj))
We create a small stock administration venture that features a Python module, an executable script, and a README file. We deliberately embody implementation defects to allow Kimi to examine the repository construction and determine practical and design dangers. We then run a read-only venture evaluation immediate within the venture listing and request a concise technical evaluation.
Automating Code Repair, Testing, and Independent Validation
print("=" * 70, "nPART 5: Demo B — Kimi fixes the bug & provides testsn", "=" * 70)
kimi("Fix the bugs in app/stock.py: take away() should increase KeyError->ValueError "
"for unknown gadgets and by no means permit damaging inventory. Then create exams.py at "
"the venture root utilizing unittest overlaying add/take away/complete and edge circumstances, "
"run it with 'python -m unittest exams -v', and iterate till all exams go. "
"Finally print the take a look at outcomes.",
work_dir=str(proj), yolo=True, additional="--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 exams -v", cwd=str(proj), test=False)
We permit Kimi to switch the venture autonomously, appropriate the stock logic, generate unit exams, and execute the take a look at suite. We configure a most agent-step restrict so the mannequin can iteratively diagnose failures and refine its implementation till validation succeeds. We examine the ensuing Python recordsdata and independently rerun the exams to substantiate that the generated modifications work accurately.
Exploring Structured JSONL, Sessions, and Advanced Features
print("=" * 70, "nPART 6: Demo C — machine-readable JSONL eventsn", "=" * 70)
uncooked = kimi("In one sentence, what does app/most important.py print when run?",
work_dir=str(proj), stream_json=True, quiet=False)
print("nParsed occasion sorts:")
for line in uncooked.splitlines():
strive:
evt = json.hundreds(line)
print(" •", evt.get("sort", "?"), "-",
str(evt)[:100].exchange("n", " "))
besides json.JSONDecodeError:
go
print("=" * 70, "nPART 7: Demo D — conversational memoryn", "=" * 70)
kimi("Remember this: our launch codename is BLUE-FALCON.", work_dir=str(proj))
kimi("What is our launch codename? Answer with simply the codename.",
work_dir=str(proj), cont=True)
print("=" * 70, "nPART 8: Power-user referencen", "=" * 70)
print(textwrap.dedent("""
# Plan mode — read-only exploration, produces an implementation plan:
kimi --quiet --plan -w /content material/demo_project -p "Plan including SQLite persistence"
# Pick a distinct mannequin at runtime (should exist in config.toml):
kimi --quiet -m kimi-k2 -p "howdy"
# Thinking mode (if the mannequin helps it):
kimi --quiet --thinking -p "Prove sqrt(2) is irrational"
# Ralph loop — feed the identical immediate repeatedly for one large job
# till the agent outputs <selection>STOP</selection> or the restrict hits:
kimi --print --yolo --max-ralph-iterations 5 -w /content material/demo_project
-p "Keep enhancing take a look at protection; STOP when every part is roofed."
# MCP instruments — give Kimi additional capabilities by way of an MCP config file:
# /content material/mcp.json -> {"mcpServers": {"context7":
# {"url": "https://mcp.context7.com/mcp",
# "headers": {"CONTEXT7_API_KEY": "YOUR_KEY"}}}}
kimi --quiet --mcp-config-file /content material/mcp.json -p "Use context7 to ..."
# Export a session (context.jsonl, wire.jsonl, state.json) for debugging:
kimi export --yes
# Web UI (wants a tunnel on Colab, e.g. cloudflared/ngrok, because it
# binds regionally): kimi internet --no-open --port 5494
"""))
print("Tutorial full
— Kimi CLI is put in, authenticated, and has "
"explored, fastened, examined, and remembered an actual venture headlessly.")
We execute Kimi with streamed JSON output and parse every JSONL occasion to examine machine-readable response sorts. We show persistent multi-turn reminiscence by storing a launch codename and retrieving it throughout an ongoing session in the identical working listing. We conclude by reviewing superior instructions for planning, mannequin switching, considering mode, Ralph loops, MCP instruments, session export, and internet entry.
In conclusion, we established an end-to-end Kimi CLI workflow that runs totally with out counting on an interactive terminal session. We moved from atmosphere provisioning and API configuration to venture evaluation, autonomous code restore, take a look at technology, structured output parsing, and session continuation. We additionally independently verified the agent’s modifications, which helps us distinguish generated output from precise execution outcomes and improves the reliability of the workflow. With the reusable wrapper and reference instructions in place, we will now lengthen the identical structure to bigger repositories, CI-style validation duties, MCP-enabled toolchains, iterative software program enchancment loops, and different programmable AI-assisted growth workflows.
Check out the Full Code here. Also, be happy to comply with us on Twitter and don’t neglect to affix 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 accomplice with us for selling your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar and so forth.? Connect with us
The submit Building Non-Interactive Agentic Coding Workflows with Moonshot AI’s Kimi CLI, JSONL Streaming, Testing, and Session Memory appeared first on MarkTechPost.
