← 研究筆記
用 code2prompt 將程式碼庫轉成單一 prompt

用 code2prompt 將程式碼庫轉成單一 prompt

記錄在封鎖網路的情況下執行 code2prompt CLI,將儲存庫的原始碼目錄樹與檔案內容轉成單一 prompt,並檢查產生的 token 數量。

本文介紹的儲存庫

mufeedvh/code2prompt

A CLI tool to convert your codebase into a single LLM prompt with source tree, prompt templating, and token counting.

7.5k Rust MIT License

向 LLM 詢問程式碼庫的問題前,得先決定要複製貼上哪些內容。您需要逐一開啟檔案、收集內容,再決定要傳送多少。這項工作不需要 LLM 推理,一個指令就能處理。code2prompt 是以 Rust 編寫的 CLI,可將指定目錄的原始碼目錄樹與檔案內容轉成單一 prompt。我編譯了這個工具,並用它處理自己的原始碼。

code2prompt 會掃描儲存庫,將原始碼目錄樹與檔案內容整理成一個文字檔。專案以 MIT 授權條款發布原始碼(*1)。

1. 編譯工具

除了 Rust 工具鏈,還需要 build-essential 和 perl,因為相依的 crate git2 會從原始碼編譯 OpenSSL。

FROM docker.io/library/rust:1.90.0-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
    pkg-config libssl-dev build-essential perl \
    && rm -rf /var/lib/apt/lists/*
WORKDIR /work
podman build -t code2prompt-sandbox .
podman run --rm --userns=keep-id \
  -v "$(pwd)":/work -w /work code2prompt-sandbox \
  cargo build --release

-v 選項讓容器可以讀寫指定目錄。請在專供實驗使用的空目錄中執行,並且不要將私密金鑰和憑證放入其中。安裝階段是唯一啟用網路的步驟:Cargo 下載相依的 crate,git2 則從原始碼編譯 OpenSSL。預設的 bridge 網路提供足夠的對外連線能力。不要啟用 --network host;它會共用主機的網路命名空間。編譯在三分鐘內完成,並在 target/release/code2prompt 產生單一執行檔。

2. 轉換自己的原始碼

我在停用網路的情況下執行編譯好的執行檔,並指定 code2prompt 核心 crate 的原始碼目錄。

podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 --userns=keep-id \
  -v "$(pwd)":/work -w /work code2prompt-sandbox \
  ./target/release/code2prompt crates/code2prompt-core/src --output-file /work/output.md

指令輸出:

[i] Using config from: /work/.c2pconfig
[i] Token count: 29K, Model info: ChatGPT models, text-embedding-ada-002
[✓] Prompt written to file: /work/output.md

輸出檔 output.md 包含 3,924 行。開頭是程式碼區塊中的原始碼目錄樹,接著以各檔案的路徑為標題,列出檔案內容。

Project Path: src

Source Tree:

┌── analysis.rs
├── builtin_templates.rs
├── configuration.rs
...

工具會回報估計的 token 數量,讓您在傳送前確認 prompt 是否符合 LLM 的輸入上限。工具預設不會跟隨符號連結,因此讀取範圍限於目標目錄。

複製貼上之前,先讓指令處理

貼上之前,手動開啟檔案並彙整內容很花時間。一個指令就能寫出原始碼目錄樹和檔案內容,讓您專心思考要向 LLM 提問什麼。將傳送資料給 LLM 前的準備視為機械性的步驟。

來源

*1 code2prompt (GitHub), https://github.com/mufeedvh/code2prompt, MIT License