# How to Build Your First AI Agent Loop With Kimi K3 (Exact Setup Inside)
**作者**: darkzodchi
**日期**: 2026-07-20T11:14:04.000Z
**来源**: [https://x.com/zodchiii/status/2079162921394077731](https://x.com/zodchiii/status/2079162921394077731)
---

An agent loop is the difference between asking AI for help and waking up to finished work. Most people never build one because a hundred iterations on a frontier model costs real money.
Inside: the loop pattern explained in one diagram, two exact setups (Claude Code and raw API), and the cache math that makes K3 the loop machine.
Your first loop runs tonight at about $0.39 per turn.
Here's the full setup 👇
Before we dive in, I share daily notes on AI & vibe coding in my Telegram channel: https://t.me/zodchixquant 🧠

## What a loop actually is
Strip the hype and a loop is four steps on repeat:
```
GOAL → ATTEMPT → CHECK → (better? keep : retry)
↑__________________________|
```
- Goal: a measurable finish line, not a vibe. "All tests pass", "page loads under 1s", "score above 90"
- Attempt: the model does one unit of work toward it
- Check: something verifies the result against the goal. A test suite, a linter, a second model
- Repeat: feed the check result back, go again, stop when the goal is met or the budget dies
That's it. Everything else (memory, subagents, overnight runs) is decoration on this cycle.
## Why K3 specifically: the loop economics
Loops re-read the same context every turn: the codebase, the goal, the history. On most models you pay full price for that repetition. On K3 you don't:
```
Turn cost = fresh_tokens × $3/M + cached_tokens × $0.30/M
Real shape (800K stable context + 50K fresh per turn):
K3: $0.24 + $0.15 = $0.39/turn
Fable 5: 850K × $10/M = $8.50/turn
```
A 50-turn overnight loop: about $20 on K3, about $425 on Fable 5. That's not a discount, that's the difference between "let it run" and "watch it like a hawk".
The one rule: keep your stable context as an identical prefix every turn, task at the end, so the cache actually hits.

## Setup A: Claude Code (the 5-minute path)
If you live in Claude Code, loops are built in and K3 slots underneath via Moonshot's official config:
```
export ANTHROPIC_BASE_URL=https://api.moonshot.ai/anthropic
export ANTHROPIC_AUTH_TOKEN=${YOUR_MOONSHOT_API_KEY}
export ANTHROPIC_MODEL=kimi-k3
export ANTHROPIC_DEFAULT_OPUS_MODEL=kimi-k3
export ANTHROPIC_DEFAULT_SONNET_MODEL=kimi-k3
export ANTHROPIC_DEFAULT_HAIKU_MODEL=kimi-k3
export CLAUDE_CODE_SUBAGENT_MODEL=kimi-k3
export ENABLE_TOOL_SEARCH=false
export CLAUDE_CODE_AUTO_COMPACT_WINDOW=1048576
claude
```
Then the loop is two commands:
- /goal sets the finish line: "all tests in tests/ pass and coverage stays above 80%". Claude Code keeps working toward it instead of stopping at the first answer
- /loop makes it recurring: the session re-runs on a schedule or until the goal holds
Confirm you're on K3 via /status (the /model menu won't show it). The 1M auto-compact window in the config means long loops compact rarely, which keeps iteration history alive.
## Setup B: the raw API loop (full control)
For loops outside Claude Code, here's a complete minimal loop, OpenAI-compatible:
```
from openai import OpenAI
client = OpenAI(
api_key=MOONSHOT_API_KEY,
base_url="https://api.moonshot.ai/v1",
)
# Stable prefix: identical every turn = cache hits at $0.30/M
STABLE = f"""You are a coding agent in a loop.
GOAL: make all tests pass in the project below.
PROJECT:
{project_dump}
RULES:
- One focused change per turn
- Explain what you changed and why in 2 lines
- If tests pass, reply exactly: GOAL_REACHED
"""
history = []
MAX_TURNS = 30
for turn in range(MAX_TURNS):
result = run_tests() # your check: pytest, npm test, etc.
if result.passed:
print(f"Done in {turn} turns")
break
response = client.chat.completions.create(
model="kimi-k3",
messages=[
{"role": "system", "content": STABLE},
*history[-6:], # last 3 exchanges, capped
{"role": "user", "content":
f"Turn {turn}. Test output:\n{result.output}\n"
f"Fix the next failure."},
],
)
change = response.choices[0].message.content
apply_change(change) # write the edit, commit to a branch
history += [
{"role": "user", "content": f"Turn {turn} test output given"},
{"role": "assistant", "content": change},
]
```
Three load-bearing details:
- The check is code, not vibes. run_tests() decides progress, the model never grades itself
- History is capped. Last 3 exchanges only; the stable prefix carries the durable context and stays cache-friendly
- Every change goes to a branch. The loop can be wrong 10 times as long as main never sees it
## Guardrails before you walk away
- Budget stop: count tokens per turn, kill the loop at a dollar cap. MAX_TURNS is not enough, one bloated turn can out-eat ten normal ones
- Progress stop: if the same test fails 3 turns in a row, halt and flag. Loops that can't converge burn money politely
- One K3 catch: reasoning runs at max-only for now, so every turn carries full thinking output at $15/M. Keep turns focused, one failure per turn, and the output side stays sane
## Common mistakes
- Vague goals. "Improve the code" loops forever. A loop is only as good as its finish line is checkable
- Letting the model self-grade. "Looks correct to me" is how loops ship garbage. The checker must be external: tests, linter, or a second model with a rubric
- Breaking the cache. Timestamps, random IDs, or reordered files in your prefix mean every turn bills at $3/M instead of $0.30. Identical means identical
- No branch discipline. An unsupervised loop with write access to main is a horror story with extra steps
- Starting with overnight runs. Run your first loops while watching, 10-15 turns. Earn the trust before you sleep on it
## The 15-minute setup
1. Grab a Moonshot API key, top up inside the 10-30% bonus window, live to August 11 (3 min)
2. Pick Setup A or B and wire it (5 min)
3. Write one checkable goal for a real small task: a failing test, a lint pass (2 min)
4. Run 10 supervised turns, watch the check drive the work (4 min)
5. Note the cost. Then decide how big the next loop gets (1 min)
The loop is the oldest idea in programming applied to the newest tool. K3 just made it cheap enough to actually use.
Thanks for reading!
I share daily notes on AI & vibe coding in my Telegram channel: https://t.me/zodchixquant 🧠

## 相关链接
- [darkzodchi](https://x.com/zodchiii)
- [@zodchiii](https://x.com/zodchiii)
- [3.3K](https://x.com/zodchiii/status/2079162921394077731/analytics)
- [https://t.me/zodchixquant](https://t.me/zodchixquant)
- [https://t.me/zodchixquant](https://t.me/zodchixquant)
- [Upgrade to Premium](https://x.com/i/premium_sign_up)
- [7:14 PM · Jul 20, 2026](https://x.com/zodchiii/status/2079162921394077731)
- [3,361 Views](https://x.com/zodchiii/status/2079162921394077731/analytics)
- [View quotes](https://x.com/zodchiii/status/2079162921394077731/quotes)
---
*导出时间: 2026/7/20 22:11:12*
---
## 中文翻译
# 如何用 Kimi K3 搭建你的第一个 AI Agent 循环(内含详细配置)
**作者**: darkzodchi
**日期**: 2026-07-20T11:14:04.000Z
**来源**: [https://x.com/zodchiii/status/2079162921394077731](https://x.com/zodchiii/status/2079162921394077731)
---

Agent 循环(Agent Loop)是“向 AI 寻求帮助”与“一觉醒来工作已完结”之间的区别。大多数人从未搭建过这样一个循环,因为在前沿模型上进行上百次迭代是要花真金白银的。
内含:用一张图解释循环模式,两种详细配置(Claude Code 和原生 API),以及让 K3 成为循环引擎的缓存计算原理。
你的第一个循环今晚就能跑起来,每轮成本约 0.39 美元。
完整配置如下 👇
在开始之前,我会在我的 Telegram 频道分享关于 AI & vibe coding(氛围编程)的每日笔记:https://t.me/zodchixquant 🧠

## 循环到底是什么
剥离炒作成分,循环就是四个步骤的重复:
```
GOAL → ATTEMPT → CHECK → (better? keep : retry)
↑__________________________|
```
- Goal(目标):一个可衡量的终点,而不是一种氛围。“所有测试通过”、“页面加载时间低于 1 秒”、“分数高于 90”
- Attempt(尝试):模型为此完成一个单元的工作
- Check(检查):某种机制验证结果是否符合目标。测试套件、Linter(代码检查工具)、或者第二个模型
- Repeat(重复):将检查结果反馈回去,再次执行,直到目标达成或预算耗尽
就是这样。其他所有东西(记忆、子代理、通宵运行)都是这个循环上的装饰。
## 为什么特指 K3:循环经济学
循环每一轮都要重新读取相同的上下文:代码库、目标、历史记录。在大多数模型上,你需要为这种重复支付全价。在 K3 上则不需要:
```
轮次成本 = fresh_tokens(新 token)× $3/M + cached_tokens(缓存 token)× $0.30/M
真实形态(80 万稳定上下文 + 每轮 5 万新 token):
K3: $0.24 + $0.15 = $0.39/轮
Fable 5: 850K × $10/M = $8.50/轮
```
一个 50 轮的通宵循环:在 K3 上大约 20 美元,在 Fable 5 上大约 425 美元。这不是折扣,这是“让它跑”和“像鹰一样盯着它”的区别。
一条规则:保持你的稳定上下文每一轮都作为相同的前缀,任务放在最后,这样缓存才能真正命中。

## 配置 A:Claude Code(5 分钟路径)
如果你活在 Claude Code 里,循环是内置的,K3 可以通过 Moonshot 的官方配置接入底层:
```
export ANTHROPIC_BASE_URL=https://api.moonshot.ai/anthropic
export ANTHROPIC_AUTH_TOKEN=${YOUR_MOONSHOT_API_KEY}
export ANTHROPIC_MODEL=kimi-k3
export ANTHROPIC_DEFAULT_OPUS_MODEL=kimi-k3
export ANTHROPIC_DEFAULT_SONNET_MODEL=kimi-k3
export ANTHROPIC_DEFAULT_HAIKU_MODEL=kimi-k3
export CLAUDE_CODE_SUBAGENT_MODEL=kimi-k3
export ENABLE_TOOL_SEARCH=false
export CLAUDE_CODE_AUTO_COMPACT_WINDOW=1048576
claude
```
然后循环只需两个命令:
- /goal 设定终点:“tests/ 里的所有测试通过,且覆盖率保持在 80% 以上”。Claude Code 会持续朝目标努力,而不是在给出第一个答案后就停止
- /loop 使其循环:会话按计划重新运行,直到目标达成
通过 /status 确认你使用的是 K3(/model 菜单不会显示它)。配置中的 1M 自动压缩窗口意味着长循环很少压缩,这能保留迭代历史。
## 配置 B:原生 API 循环(完全控制)
对于 Claude Code 之外的循环,这里有一个完整的最小化循环,兼容 OpenAI:
```
from openai import OpenAI
client = OpenAI(
api_key=MOONSHOT_API_KEY,
base_url="https://api.moonshot.ai/v1",
)
# 稳定前缀:每一轮都完全相同 = 缓存命中,费率 $0.30/M
STABLE = f"""You are a coding agent in a loop.
GOAL: make all tests pass in the project below.
PROJECT:
{project_dump}
RULES:
- One focused change per turn
- Explain what you changed and why in 2 lines
- If tests pass, reply exactly: GOAL_REACHED
"""
history = []
MAX_TURNS = 30
for turn in range(MAX_TURNS):
result = run_tests() # 你的检查:pytest, npm test 等
if result.passed:
print(f"Done in {turn} turns")
break
response = client.chat.completions.create(
model="kimi-k3",
messages=[
{"role": "system", "content": STABLE},
*history[-6:], # 最后 3 次交换,已封顶
{"role": "user", "content":
f"Turn {turn}. Test output:\n{result.output}\n"
f"Fix the next failure."},
],
)
change = response.choices[0].message.content
apply_change(change) # 写入编辑,提交到分支
history += [
{"role": "user", "content": f"Turn {turn} test output given"},
{"role": "assistant", "content": change},
]
```
三个承重细节:
- 检查是代码,不是氛围。run_tests() 决定进度,模型从不给自己打分
- 历史记录是封顶的。只保留最后 3 次交换;稳定前缀承载持久上下文并保持缓存友好
- 每次更改都进入分支。循环可以错 10 次,只要 main 分支永远看不到
## 转身离开前的护栏
- 预算停止:计算每轮的 token 数,在达到美元上限时终止循环。仅靠 MAX_TURNS 是不够的,一轮臃肿的执行可能吃掉十轮正常执行的费用
- 进度停止:如果同一个测试连续 3 轮失败,停止并标记。无法收敛的循环只会礼貌地烧钱
- 一个 K3 陷阱:推理目前仅以 max 模式运行,所以每一轮都会附带完整的思考输出,费率为 $15/M。保持轮次聚焦,每轮解决一个失败,输出端就能保持正常
## 常见错误
- 目标模糊。“改进代码”会无限循环。循环的好坏取决于其终点是否可检查
- 让模型自我评分。“我觉得看起来正确”是循环制造垃圾的方式。检查器必须是外部的:测试、Linter,或者带有评分标准的第二个模型
- 破坏缓存。前缀中的时间戳、随机 ID 或重新排序的文件意味着每一轮都要按 $3/M 而不是 $0.30/M 计费。完全一致就是完全一致
- 没有分支纪律。一个对 main 分支有写入权限的无监督循环就是多了几个步骤的恐怖故事
- 从通宵运行开始。第一次循环要在看着的时候跑,10-15 轮。在把它托付给睡眠之前,先赢得信任
## 15 分钟配置
1. 获取一个 Moonshot API key,在 10-30% 奖励窗口内充值,有效期至 8 月 11 日(3 分钟)
2. 选择配置 A 或 B 并完成连接(5 分钟)
3. 为一个真实的小任务写一个可检查的目标:一个失败的测试、一次 Linter 检查(2 分钟)
4. 运行 10 轮监督模式,看着检查驱动工作(4 分钟)
5. 记下成本。然后决定下一个循环要做多大(1 分钟)
循环是应用于最新工具的最古老的编程理念。K3 只是让它便宜到真正可用。
感谢阅读!
我会在我的 Telegram 频道分享关于 AI & vibe coding 的每日笔记:https://t.me/zodchixquant 🧠

## 相关链接
- [darkzodchi](https://x.com/zodchiii)
- [@zodchiii](https://x.com/zodchiii)
- [3.3K](https://x.com/zodchiii/status/2079162921394077731/analytics)
- [https://t.me/zodchixquant](https://t.me/zodchixquant)
- [https://t.me/zodchixquant](https://t.me/zodchixquant)
- [Upgrade to Premium](https://x.com/i/premium_sign_up)
- [7:14 PM · Jul 20, 2026](https://x.com/zodchiii/status/2079162921394077731)
- [3,361 Views](https://x.com/zodchiii/status/2079162921394077731/analytics)
- [View quotes](https://x.com/zodchiii/status/2079162921394077731/quotes)
---
*导出时间: 2026/7/20 22:11:12*