阶段4(下):LangChain 1.x、提示词与注入防护、模型侧(路由/vLLM/LoRA)、AI 编程工具与验证、Dify/Coze 专题
This commit is contained in:
1 parent
caaec830b3
commit
7a32d2c9a6
38 files changed
+3059
-67
No files matched your search
@@ -0,0 +1,10 @@
|
||||
---
|
||||
description: 编写或修改 FastAPI 接口时使用
|
||||
globs: app/**/*.py
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
- 路由函数只做参数校验和调用 service,业务逻辑放在 `app/services/`。
|
||||
- 错误统一抛出 `AppError(code, message)`,不要直接返回 500。
|
||||
- 数据库写操作放在事务里;涉及金额用 Decimal。
|
||||
- 新增接口时同步更新 `tests/api/` 下的测试。
|
||||
@@ -0,0 +1,21 @@
|
||||
# AGENTS.md(示例:给 AI 编程工具读的项目说明)
|
||||
|
||||
> Cursor、Codex 等工具会读取仓库根目录的 AGENTS.md;Claude Code 读取 CLAUDE.md(可以在其中引用本文件)。支持情况以各工具官方文档为准。
|
||||
|
||||
## 项目
|
||||
- 后端:Python 3.12 + FastAPI,`app/`;测试 `tests/`;依赖用 uv 管理。
|
||||
- 前端:Vue 3 + TypeScript,`web/`。
|
||||
|
||||
## 常用命令
|
||||
- 安装:`uv sync`
|
||||
- 测试:`uv run pytest -q`
|
||||
- 检查:`uv run ruff check . && uv run mypy app`
|
||||
|
||||
## 约定
|
||||
- 新接口必须有 pydantic 请求 / 响应模型和至少一个测试。
|
||||
- 不要修改 `migrations/` 中已存在的文件,新增迁移。
|
||||
- 不要在代码、测试、日志中写入真实密钥、内网地址、客户数据。
|
||||
- 每次改动后运行测试;测试不通过不要说“完成了”。
|
||||
|
||||
## 完成标准
|
||||
- `uv run pytest -q` 全部通过;新增代码有测试;说明改了哪些文件、怎么验证的。
|
||||
@@ -0,0 +1,12 @@
|
||||
"""一段“AI 生成”的代码:计算订单优惠后的金额。用于演示验证流程。"""
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
|
||||
|
||||
def final_price(amount: Decimal, coupon: Decimal, vip: bool) -> Decimal:
|
||||
"""先减优惠券(不能减到负数),VIP 再打 95 折,结果保留两位小数(四舍五入)。"""
|
||||
if amount < 0 or coupon < 0:
|
||||
raise ValueError("金额和优惠券不能为负数")
|
||||
price = max(amount - coupon, Decimal("0"))
|
||||
if vip:
|
||||
price = price * Decimal("0.95")
|
||||
return price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
@@ -0,0 +1,24 @@
|
||||
# requires: pytest
|
||||
"""人工补充的边界测试:AI 第一版代码在“优惠券大于金额”时返回了负数,这些测试把它拦了下来。"""
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from pricing import final_price
|
||||
|
||||
|
||||
def test_normal():
|
||||
assert final_price(Decimal("100"), Decimal("10"), vip=False) == Decimal("90.00")
|
||||
|
||||
|
||||
def test_vip_rounding():
|
||||
assert final_price(Decimal("10.01"), Decimal("0"), vip=True) == Decimal("9.51")
|
||||
|
||||
|
||||
def test_coupon_larger_than_amount():
|
||||
assert final_price(Decimal("5"), Decimal("10"), vip=True) == Decimal("0.00")
|
||||
|
||||
|
||||
def test_negative_rejected():
|
||||
with pytest.raises(ValueError):
|
||||
final_price(Decimal("-1"), Decimal("0"), vip=False)
|
||||
@@ -0,0 +1,22 @@
|
||||
# AI 编程会话记录(模板)
|
||||
|
||||
> 用于作品集和面试:证明“我会用 AI,而且知道怎么验证它”。**提交前务必脱敏**:删除公司名、内部系统名、内网地址、密钥、客户数据。
|
||||
|
||||
- 日期 / 工具:2026-xx-xx / Cursor(或 Claude Code、Codex)
|
||||
- 任务:一句话描述目标
|
||||
- 我给的上下文:相关文件、规则文件、需求说明
|
||||
|
||||
## 过程
|
||||
1. 让 AI 先给出计划(贴计划摘要),我调整了:……
|
||||
2. 分步实现:第 1 步……(关键提示词摘要)
|
||||
3. AI 出错的地方:……(例如边界条件、过时的 API 写法)我怎么发现的:测试 / 审查 / 运行
|
||||
|
||||
## 验证
|
||||
- 自动检查:测试、类型检查、lint 的结果(附 `verify.py` 生成的验证记录)
|
||||
- 人工审查:逐行读过的部分、发现的问题
|
||||
- 真实环境:在什么环境跑过、看到了什么结果(截图 / 日志)
|
||||
|
||||
## 结论
|
||||
- 最终改动:文件列表、提交哈希
|
||||
- 用时对比:大概节省了多少时间,哪些部分 AI 帮不上
|
||||
- 下次改进:补充到规则文件 / Skill 里的约定
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
name: add-api-endpoint
|
||||
description: 需要新增一个后端 HTTP 接口(含模型、服务、测试)时使用。
|
||||
---
|
||||
|
||||
# 新增接口的步骤
|
||||
|
||||
1. 在 `app/schemas/` 定义请求和响应模型(pydantic),字段写清楚约束。
|
||||
2. 在 `app/services/` 写业务逻辑,不依赖 FastAPI 对象,方便单测。
|
||||
3. 在 `app/api/` 注册路由,使用依赖注入获取当前用户和数据库会话。
|
||||
4. 在 `tests/` 写测试:正常、参数错误、无权限三类用例。
|
||||
5. 运行 `uv run pytest -q`,全部通过后再报告完成,并列出验证结果。
|
||||
@@ -0,0 +1,14 @@
|
||||
# requires: pytest
|
||||
import verify
|
||||
|
||||
|
||||
def test_failed_check_marks_record(tmp_path):
|
||||
(tmp_path / "test_bad.py").write_text("def test_x():\n assert 1 == 2\n")
|
||||
out = tmp_path / "v.md"
|
||||
code = verify.main(["--task", "t", "--check", "pytest -q test_bad.py", "--cwd", str(tmp_path), "--out", str(out)])
|
||||
text = out.read_text(encoding="utf-8")
|
||||
assert code == 1 and "结论:未通过" in text and "| `pytest -q test_bad.py` | 1 |" in text
|
||||
|
||||
|
||||
def test_sample_passes():
|
||||
assert verify.main(["--task", "sample"]) == 0
|
||||
@@ -0,0 +1,64 @@
|
||||
# 只用标准库
|
||||
"""对 AI 生成的改动跑一组检查,并生成一份“验证记录”(Markdown),作为提交说明 / 作品集证据。
|
||||
|
||||
用法:
|
||||
python verify.py --task "新增优惠价格计算" --check "pytest -q sample" --out verification.md
|
||||
可以多次传 --check。记录里包含:任务、时间、每条命令的退出码和耗时、输出摘要、结论。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def run_check(cmd: str, cwd: Path) -> dict:
|
||||
t0 = time.perf_counter()
|
||||
args = shlex.split(cmd)
|
||||
if args and args[0] in ("pytest", "python"):
|
||||
args = [sys.executable] + (["-m", "pytest"] + args[1:] if args[0] == "pytest" else args[1:])
|
||||
p = subprocess.run(args, cwd=cwd, capture_output=True, text=True)
|
||||
out = (p.stdout + p.stderr).strip().splitlines()
|
||||
return {"cmd": cmd, "code": p.returncode, "seconds": round(time.perf_counter() - t0, 2),
|
||||
"tail": "\n".join(out[-8:])}
|
||||
|
||||
|
||||
def render(task: str, results: list[dict], notes: list[str]) -> str:
|
||||
ok = all(r["code"] == 0 for r in results)
|
||||
now = dt.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z")
|
||||
lines = [f"# 验证记录:{task}", "", f"- 时间:{now}", f"- 结论:{'通过' if ok else '未通过'}", "",
|
||||
"| 检查 | 退出码 | 耗时(秒) |", "| --- | --- | --- |"]
|
||||
lines += [f"| `{r['cmd']}` | {r['code']} | {r['seconds']} |" for r in results]
|
||||
for r in results:
|
||||
lines += ["", f"### `{r['cmd']}` 输出摘要", "", "```text", r["tail"], "```"]
|
||||
if notes:
|
||||
lines += ["", "## 人工审查要点", ""] + [f"- {n}" for n in notes]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--task", default="AI 生成代码的验证")
|
||||
ap.add_argument("--check", action="append", default=[])
|
||||
ap.add_argument("--note", action="append", default=[])
|
||||
ap.add_argument("--out", default="")
|
||||
ap.add_argument("--cwd", default=str(Path(__file__).parent))
|
||||
a = ap.parse_args(argv)
|
||||
checks = a.check or ["pytest -q sample"]
|
||||
results = [run_check(c, Path(a.cwd)) for c in checks]
|
||||
md = render(a.task, results, a.note or [
|
||||
"金额使用 Decimal,舍入方式与产品文档一致(四舍五入到分)",
|
||||
"补充了“优惠券大于金额”的边界测试:AI 第一版在这里返回负数",
|
||||
])
|
||||
if a.out:
|
||||
Path(a.out).write_text(md, encoding="utf-8")
|
||||
print(md)
|
||||
return 0 if all(r["code"] == 0 for r in results) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user