一直知道各种 Agent 本质上就是 loop,用户提问 -> agent 查询上下文、调用工具 -> 回答,这个过程不断的循环。

眼高手低,今天才参考 pi-agent 的实现,手写实现了一个极简的 loop 循环 + bash 工具:

export async function runAgentLoop({ systemPrompt, history, input, model, tools, emit = () => { }, signal, maxTurns = MAX_TURNS }: RunOptions): Promise<Message[]> {
const messages: Message[] = [...history, { role: "user", text: input }];
// Internal vars ...

await emit({ type: "agent_start" });
await emit({ type: "message_end", message: newMessages[0]! });

for (let turn = 0; turn < maxTurns; turn++) {
if (signal?.aborted) break;
await emit({ type: "turn_start" });

const assistant = await model.respond({ systemPrompt, messages, tools: toolSpecs }, signal);
await emit({ type: "message_end", message: assistant });

// Error handle

const toolResults: ToolResultMessage[] = [];
for (const call of assistant.calls) {
const result = assistant.stopReason === "length" ? truncatedToolResult(call) :
await executeTool(call, tools, signal, emit);
toolResults.push(result);
messages.push(result);
newMessages.push(result);
await emit({ type: "message_end", message: result });
}

await emit({ type: "turn_end", message: assistant, toolResults });
}
await emit({ type: "agent_end", messages: newMessages });
return newMessages;
}

async function executeTool(...): Promise<ToolResultMessage> {
// 工具调用等...
return { role: "tool", callId: call.id, name: call.name, isError, text }
}

核心代码就是这个loop, 加上 模型、工具调用、类型定义等就能运行起来一个单论对话函数,单论对话中也AI也可以循环调用工具完成一个问题的回答。

进一步,加入一个TUI的循环,那么就可以循环问答:

✗ bun run tui.ts
Pi MVP TUI started. Commands: /clear, /exit

hi

Hi! How can I help you today?

阅读一下文件夹中的文件有多少个?

[tool:start] bash {
command: "pwd && ls -la",
}
[tool:end] bash -> /home/jialuan/pi-mvp
total 88

令我比较开心的是,TUI这一层代码就是通过调用一次loop,让AI给我加进去的,也就是说实现了一个基本的bashTool之后,就可以让AI通过bash写代码自我迭代了。

后续在tui基础上加上beforeToolCall/afterToolCall钩子、read/write工具、流式输出、上下文管理、会话持久化等,就会变成一个稍微可用的agent了。

说实话,很久很久没有手写代码了,哪怕是抄AI给出的示例;小demo跑起来后还怪开心的。