import json
import os
import subprocess
import sys
from pathlib import Path
from openai import OpenAI
client = OpenAI(base_url=os.environ["LLM_BASE_URL"], api_key=os.environ["LLM_API_KEY"], timeout=30.0, max_retries=1)
MODEL = os.environ["LLM_MODEL"]
WORKSPACE = Path("coding-lab").resolve()
WORKSPACE.mkdir(exist_ok=True)
def checked_path(path):
target = (WORKSPACE / path).resolve()
if not target.is_relative_to(WORKSPACE):
raise ValueError("只能访问练习目录")
return target
def read_file(path):
target = checked_path(path)
if target.stat().st_size > 1_000_000:
raise ValueError("文件过大,请先缩小范围")
return target.read_text(encoding="utf-8")
def write_file(path, content):
target = checked_path(path)
if len(content.encode("utf-8")) > 1_000_000:
raise ValueError("写入内容过大")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
return "ok"
def run(cmd):
allowed = {"pytest": [sys.executable, "-m", "pytest", "-q"]}
if cmd not in allowed:
raise ValueError("只允许预先登记的pytest命令")
result = subprocess.run(allowed[cmd], cwd=WORKSPACE, timeout=30, shell=False,
capture_output=True, text=True,
env={"PATH": os.environ.get("PATH", ""), "PYTHONIOENCODING": "utf-8"})
return json.dumps({"returncode": result.returncode, "stdout": result.stdout[-2000:],
"stderr": result.stderr[-2000:]}, ensure_ascii=False)
TOOLS = {"read_file": read_file, "write_file": write_file, "run": run}
def tool_schema(name, description, names):
return {"type": "function", "function": {"name": name, "description": description,
"parameters": {"type": "object", "properties": {key: {"type": "string"} for key in names},
"required": names, "additionalProperties": False}}}
tools_schema = [
tool_schema("read_file", "读取练习目录内的UTF-8文件", ["path"]),
tool_schema("write_file", "写入练习目录内的UTF-8文件", ["path", "content"]),
tool_schema("run", "运行登记的pytest命令,cmd只能是pytest", ["cmd"]),
]
def coding_agent(task, max_steps=15):
messages = [
{"role": "system", "content": "你是工程师。读代码→改代码→跑测试验证,通过了再结束。"},
{"role": "user", "content": task},
]
tests_passed = False
for _ in range(max_steps):
msg = client.chat.completions.create(model=MODEL, messages=messages, tools=tools_schema).choices[0].message
messages.append(msg.model_dump(exclude_none=True))
if not msg.tool_calls:
if tests_passed:
return msg.content
messages.append({
"role": "user",
"content": "验收未通过:还没有在最后一次修改后取得 pytest 成功结果。请继续检查并调用登记的测试工具。",
})
continue
for call in msg.tool_calls:
tool_name = call.function.name
try:
args = json.loads(call.function.arguments)
result = TOOLS[tool_name](**args)
if tool_name == "write_file":
tests_passed = False
elif tool_name == "run":
tests_passed = json.loads(result)["returncode"] == 0
except Exception as e:
tests_passed = False
result = f"工具出错: {e}"
messages.append({"role": "tool", "tool_call_id": call.id, "content": str(result)[:4000]})
return "达到步数上限,且没有取得最后一次修改后的测试成功证据"