玩具:一行代码实现AI Agent

2026-08-06 05:57

游玩规则:



来试试代码高尔夫,不借助claude code等外部agent,调用纯文字的ai api,执行可被称之为agent的最简单功能,import和api不计入行数。一行代码实现。

递归,问模型要执行什么命令,然后抽出命令来执行,执行结果返回给模型;没跑完就续上新的命令和运行结果,继续返回去问,完成了就停止。



# 不计入行数

import subprocess

from openai import OpenAI

c = OpenAI(base_url="https://openrouter.ai/api/v1", api_key="sk-or-v1-填入api")

M = "qwen/qwen3-235b-a22b-2507" # slug 去 openrouter.ai/models 现查,会变,不要用推理模型

S = "You are a shell agent. Reply with ONE bash command only, no markdown, no explanation. Reply exactly DONE when the task is finished."



# 一行agent

(f:=lambda m:not (r:=c.chat.completions.create(model=M,max_tokens=200,messages=m).choices[0].message.content.strip().strip("`").removeprefix("bash").strip()).startswith("DONE") and f(m+[{"role":"assistant","content":r},{"role":"user","content":print("$",r) or subprocess.getoutput(r)[-2000:] or "(empty)"}]))([{"role":"system","content":S},{"role":"user","content":input("task> ")}])

浏览 102
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报