技巧精选

用 Claude Code 构建你的第一个 agentic loop

Here is how to build your first agentic loop with …

精选理由

Claude Code 这个命令模板非常实用,能让你零基础跑通第一个智能体循环,省去手动写代码和测试的重复劳动。

AI 摘要

这篇教程展示了如何用 Claude Code 的非交互模式(-p 标志)构建 agentic loop。通过一个例子:在空文件夹中运行命令,让 Claude 用 Python 实现 Fibonacci 函数并编写 pytest 测试,每步改动后自动运行测试直到全部通过。核心有三个参数:-p 非交互运行、--allowedTools 预授权工具(Read, Write, Edit, Bash)、--max-turns 15 限制最大轮次。最终会输出 Fibonacci 代码和通过的测试结果。

原文 · Ate-a-Pi

Here is how to build your first agentic loop with …

Here is how to build your first agentic loop with Claude Code:

1. Open your terminal. 2. Create an empty folder and move into it. 3. Run the following command:

************************* claude -p "Write fibonnacy(n) in a Python file. Write tests for it, including edge cases. Run pytest after every change. Don't stop until every test passes." \ --allowedTools "Read,Write,Edit,Bash(python3 -m pytest:*),Bash(pytest:*)"\ --max-turns 15 *************************

That's it. If you have Python and pytest installed on your system, Claude will implement the Fibonacci function and test it.

There are 3 things you need to know about this command:

First, it uses the -p flag to run Claude Code non-interactively. It takes a prompt, runs the full agent loop, prints the result, and exits.

Second, the --allowedTools flag pre-approves exactly what the agent can touch, so Claude doesn't need to ask you every time.

Third, the --max-turns flag caps the number of agentic turns the loop can run. When it hits the cap, the run exits with an error instead of grinding forever.

This is just a simple "Hello World"-type example to get you started.

The key on every loop is the verification step: how does the agent know it is done?

Coming up with the evaluation criteria is probably the most important step in building a loop. In this example, I'm asking Claude to write unit tests and use them to evaluate the code. This works for something simple, but you'll need a much more robust evaluation for anything more complex.

Something worth mentioning: building the verification step is where a ton of my time is going right now. The agent is writing the code, and the agent is verifying that the code (and the product) work as intended. My job has become defining what "works" looks like.

用 Claude Code 构建你的第一个 agentic loop · AI 热点