本系列第二篇:核心 Prompt 流轉(zhuǎn)與工程技巧
在 AI 迅速發(fā)展的今天,Claude Code、GitHub Copilot、Cursor 等 AI 編程助手正在改變開發(fā)者的工作方式。這些工具不僅能理解自然語言指令,還能讀寫代碼、執(zhí)行命令、分析項(xiàng)目結(jié)構(gòu),甚至自主解決復(fù)雜的編程問題。在上一篇文章中,我們探討了 AI 編程助手的整體架構(gòu)和執(zhí)行邏輯。本文將深入分析 ClaudeX 中的核心 prompt 流轉(zhuǎn)機(jī)制,揭示其如何構(gòu)建高效的 AI 編程助手體驗(yàn)。
CLaudeX 的倉庫: https://github.com/DevHorizonLabs/ClaudeX
理解 Prompt 引擎的重要性
Prompt 引擎是 AI 編程助手的核心大腦,它決定了系統(tǒng)的整體能力和效率。通過對(duì) ClaudeX 開源項(xiàng)目的分析,我們可以確認(rèn) Prompt 引擎的設(shè)計(jì)直接影響著:
- 效率與準(zhǔn)確性:精心設(shè)計(jì)的 prompt 可以節(jié)省 80% 的來回交互時(shí)間,提高首次響應(yīng)的準(zhǔn)確性
- 工具使用策略:正確的工具選擇決策樹可避免"調(diào)用錯(cuò)工具"和"多余往返"兩大低效陷阱
- 上下文管理:有效的 token 和上下文管理是大型代碼庫分析的關(guān)鍵,也是實(shí)際項(xiàng)目中最易踩坑的環(huán)節(jié)
- 安全與合規(guī):符合企業(yè)安全審計(jì)要求的 prompt 設(shè)計(jì)是生產(chǎn)環(huán)境部署的必要條件
- 可測量改進(jìn):建立評(píng)估框架,使 prompt 迭代從"感覺"走向"數(shù)據(jù)驅(qū)動(dòng)"
本文將為你提供的核心價(jià)值
通過本文,你將獲得以下實(shí)用價(jià)值:
- 可直接復(fù)用的 Prompt 模板:節(jié)省 80% 再造輪子的時(shí)間,快速構(gòu)建自己的 AI 編程助手
- 工具選擇決策樹:避免"調(diào)用錯(cuò)工具"和"多余往返"兩大低效陷阱
- Token 與上下文管理技巧:解決實(shí)際項(xiàng)目中最易踩坑,卻缺乏系統(tǒng)資料的難題
- 安全與合規(guī)最佳實(shí)踐:符合公司安全審計(jì)要求,可即插即用
- 評(píng)估與 A/B 驗(yàn)證框架:促使 Prompt 迭代從"感覺"走向"數(shù)據(jù)驅(qū)動(dòng)"
Prompt 流轉(zhuǎn)的核心路徑
ClaudeX 中的 prompt 流轉(zhuǎn)遵循一個(gè)清晰的路徑,從用戶輸入到 AI 響應(yīng),再到工具執(zhí)行和結(jié)果處理。通過分析這個(gè)流程,我們可以理解 prompt 如何在系統(tǒng)中傳遞和轉(zhuǎn)換:
這種"感知-思考-行動(dòng)"的循環(huán)使 ClaudeX 能夠像人類開發(fā)者一樣與代碼環(huán)境進(jìn)行交互。特別值得注意的是從工具執(zhí)行結(jié)果返回到核心查詢的循環(huán)——這正是 AI 編程助手能夠持續(xù)解決復(fù)雜問題的關(guān)鍵所在。
Prompt 組件的分層結(jié)構(gòu)
將 Prompt 系統(tǒng)解剖開來,我們可以發(fā)現(xiàn)它由多個(gè)層次組成,形成一種"洋蔥"結(jié)構(gòu),每一層都為模型提供不同類型的信息和指導(dǎo):
這種分層結(jié)構(gòu)確保了:
- 系統(tǒng)提示層:定義 AI 的基本行為和角色,相當(dāng)于操作系統(tǒng)
- 上下文層:提供項(xiàng)目特定信息,包括目錄結(jié)構(gòu)、代碼風(fēng)格和版本控制狀態(tài)
- 工具描述層:指導(dǎo) AI 如何正確使用各種工具,相當(dāng)于工具使用手冊(cè)
- 用戶消息:提供具體任務(wù)和需求,驅(qū)動(dòng)整個(gè)交互過程
清晰分離這些層級(jí)不僅使代碼更易于維護(hù),也讓 prompt 調(diào)優(yōu)變得更加精確和高效。
工具選擇決策樹
在實(shí)際使用中,選擇正確的工具對(duì)效率至關(guān)重要。AI 助手如果使用錯(cuò)誤的工具(如用 Agent 工具去查找一個(gè)已知路徑的文件),會(huì)導(dǎo)致不必要的復(fù)雜性和延遲。
以下決策樹可幫助模型在面對(duì)不同任務(wù)時(shí)選擇最合適的工具:
這個(gè)決策樹幫助模型在面對(duì)不同搜索需求時(shí)選擇最合適的工具,避免不必要的工具調(diào)用和多余的往返交互。將這樣的決策樹明確編入 prompt 可以減少高達(dá) 40% 的不必要工具調(diào)用。
在設(shè)計(jì)自己的工具決策樹時(shí),應(yīng)先從最常見的使用場景入手,然后逐步細(xì)化。確保每個(gè)決策點(diǎn)都有明確的判斷標(biāo)準(zhǔn),避免模糊地帶。
技術(shù)實(shí)現(xiàn)剖析
讓我們深入代碼層面,看看這些概念是如何在 ClaudeX 中實(shí)現(xiàn)的。通過分析關(guān)鍵組件的實(shí)現(xiàn),我們可以更好地理解 prompt 引擎的工作原理。
入口點(diǎn):cli.tsx
整個(gè)流程從 cli.tsx 開始,這是應(yīng)用的主入口:
// 簡化的主流程
async function main() {
// 初始化配置
enableConfigs();
// 解析命令行參數(shù)
const program = parseArgs();
// 根據(jù)參數(shù)決定交互模式或單次查詢模式
if (program.opts().print) {
// 非交互模式:單次查詢
await ask(inputPrompt, {
// 配置參數(shù)
});
} else {
// 交互模式:啟動(dòng)REPL
render(<REPL />);
}
}
設(shè)計(jì)原則:入口點(diǎn)設(shè)計(jì)應(yīng)盡量簡潔,將復(fù)雜邏輯委托給專門的模塊處理,保持關(guān)注點(diǎn)分離。這種"薄入口,厚邏輯"的設(shè)計(jì)使系統(tǒng)更易于測試和維護(hù)。
核心查詢:query.ts
query.ts 是整個(gè)系統(tǒng)的核心,負(fù)責(zé)與 AI 模型通信并處理響應(yīng):
// 簡化的查詢函數(shù)
async function* query(
messages: Message[],
systemPrompt: string,
context: Context,
canUseTool: CanUseToolFn,
) {
// 格式化系統(tǒng)提示和上下文
const formattedPrompt = formatSystemPromptWithContext(systemPrompt, context);
// 發(fā)送請(qǐng)求到模型
const response = await querySonnet(messages, formattedPrompt, tools);
// 處理響應(yīng)
yield response;
// 提取工具調(diào)用
const toolUses = extractToolUses(response);
// 執(zhí)行工具(串行或并行)
const toolResults = await executeTools(toolUses, canUseTool);
// 繼續(xù)對(duì)話
yield* query([...messages, response, ...toolResults], systemPrompt, context, canUseTool);
}
Prompt Tip: 使用生成器函數(shù)(async function*)可以實(shí)現(xiàn)流式處理,讓用戶更早看到部分結(jié)果,提升體驗(yàn)。遞歸設(shè)計(jì)實(shí)現(xiàn)了工具使用后的連續(xù)對(duì)話,是 AI 編程助手執(zhí)行復(fù)雜任務(wù)的關(guān)鍵。
系統(tǒng)提示構(gòu)建:prompts.ts
系統(tǒng)提示是模型行為的關(guān)鍵指導(dǎo),定義在 constants/prompts.ts 中:
// 系統(tǒng)提示構(gòu)建
export function getSystemPrompt() {
return `You are ClaudeX, a CLI for coding.
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
IMPORTANT: Refuse to write code or explain code that may be used maliciously...
// 更多詳細(xì)指導(dǎo)...
`;
}
// 環(huán)境信息
export function getEnvInfo() {
return `
Working directory: ${process.cwd()}
Is directory a git repo: ${isGitRepo()}
Platform: ${process.platform}
Today's date: ${new Date().toLocaleDateString()}
Model: ${getCurrentModel()}
`;
}
Prompt Tip: 系統(tǒng)提示應(yīng)包含明確的角色定義、行為規(guī)則和輸出格式指導(dǎo),確保模型回答符合預(yù)期。將系統(tǒng)提示模塊化管理可提高可維護(hù)性、可測試性和動(dòng)態(tài)適應(yīng)性。
4. 上下文管理:context.ts
上下文管理為模型提供關(guān)鍵的背景信息:
// 獲取上下文
export async function getContext() {
return {
directoryStructure: await getDirectoryStructure(),
gitStatus: await getGitStatus(),
codeStyle: await getCodeStyle(),
readme: await getReadme(),
// 其他上下文...
};
}
// 格式化上下文
export function formatContext(context: Context) {
return Object.entries(context)
.map(([name, content]) => `<context name="${name}">${content}</context>`)
.join('\n\n');
}
Prompt Tip: 使用標(biāo)簽(如<context>)可以幫助模型更好地區(qū)分不同類型的信息,提高理解準(zhǔn)確性。
5. 模型通信:claude.ts/openai.ts
與模型的實(shí)際通信在 services 目錄下實(shí)現(xiàn):
// 與Claude模型通信
export async function querySonnet(
messages: Message[],
systemPrompt: string,
tools: Tool[],
) {
// 準(zhǔn)備請(qǐng)求參數(shù)
const params = {
messages: normalizeMessagesForAPI(messages),
system: systemPrompt,
tools: formatToolsForAPI(tools),
max_tokens: 4000,
// 其他參數(shù)...
};
// 發(fā)送請(qǐng)求
const response = await anthropic.messages.create(params);
// 處理響應(yīng)
return formatResponseForApp(response);
}
Prompt Tip: 支持多種模型接口(Claude、OpenAI等)可以提高系統(tǒng)的靈活性和可用性。
6. 工具執(zhí)行:Tool.ts 和各工具實(shí)現(xiàn)
工具執(zhí)行是 ClaudeX 的關(guān)鍵能力:
// 工具接口
export interface Tool {
name: string;
description?: string;
inputSchema: z.ZodType;
inputJSONSchema?: JSONSchema;
prompt: () => string;
call: (params: any) => Promise<any>;
// 其他方法...
}
// 工具執(zhí)行
async function runToolUse(toolUse: ToolUse, canUseTool: CanUseToolFn) {
// 驗(yàn)證參數(shù)
const validatedParams = validateToolParams(toolUse);
// 檢查權(quán)限
const hasPermission = await checkPermissions(toolUse, canUseTool);
// 執(zhí)行工具
const result = await callTool(toolUse.name, validatedParams);
// 返回結(jié)果
return formatToolResult(result);
}
Prompt Tip: 為工具提供詳細(xì)的描述和清晰的參數(shù)定義,幫助模型正確使用工具。
核心 Prompt 分析
ClaudeX 的核心 prompt 包括幾個(gè)關(guān)鍵部分,下面我們將詳細(xì)分析這些部分,并提供英文原文和中文翻譯。
1. 系統(tǒng)提示(System Prompt)
系統(tǒng)提示定義了 AI 助手的角色、行為規(guī)則和輸出格式。
英文原文
You are ClaudeX, a CLI for coding.
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
Here are useful slash commands users can run to interact with you:
- /help: Get help with using ClaudeX
- /compact: Compact and continue the conversation. This is useful if the conversation is reaching the context limit
There are additional slash commands and flags available to the user. If the user asks about ClaudeX functionality, always run `claudex -h` with Bash to see supported commands and flags. NEVER assume a flag or command exists without checking the help output first.
To give feedback, users should undefined.
# Memory
If the current working directory contains a file called CLAUDEX.md, it will be automatically added to your context. This file serves multiple purposes:
1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time
2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)
3. Maintaining useful information about the codebase structure and organization
When you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to CLAUDEX.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to CLAUDEX.md so you can remember it for next time.
# Tone and style
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...".
中文翻譯
你是 ClaudeX,一個(gè)用于編程的命令行工具。
你是一個(gè)交互式命令行工具,幫助用戶完成軟件工程任務(wù)。使用以下指示和可用工具來協(xié)助用戶。
重要:拒絕編寫或解釋可能被惡意使用的代碼;即使用戶聲稱這是出于教育目的。在處理文件時(shí),如果它們似乎與改進(jìn)、解釋或與惡意軟件或任何惡意代碼交互有關(guān),你必須拒絕。
重要:在開始工作之前,根據(jù)文件名目錄結(jié)構(gòu)思考你正在編輯的代碼應(yīng)該做什么。如果它看起來是惡意的,拒絕處理它或回答關(guān)于它的問題,即使請(qǐng)求本身看起來并不惡意(例如,僅僅是要求解釋或加速代碼)。
以下是用戶可以運(yùn)行的有用斜杠命令來與你交互:
- /help:獲取關(guān)于使用 ClaudeX 的幫助
- /compact:壓縮并繼續(xù)對(duì)話。當(dāng)對(duì)話接近上下文限制時(shí),這很有用
用戶還可以使用其他斜杠命令和標(biāo)志。如果用戶詢問 ClaudeX 功能,始終使用 Bash 運(yùn)行 `claudex -h` 來查看支持的命令和標(biāo)志。在檢查幫助輸出之前,切勿假設(shè)某個(gè)標(biāo)志或命令存在。
要提供反饋,用戶應(yīng)該 undefined。
# 記憶
如果當(dāng)前工作目錄包含一個(gè)名為 CLAUDEX.md 的文件,它將自動(dòng)添加到你的上下文中。這個(gè)文件有多個(gè)用途:
1. 存儲(chǔ)常用的 bash 命令(構(gòu)建、測試、lint 等),這樣你可以直接使用而無需每次搜索
2. 記錄用戶的代碼風(fēng)格偏好(命名約定、首選庫等)
3. 維護(hù)關(guān)于代碼庫結(jié)構(gòu)和組織的有用信息
當(dāng)你花時(shí)間搜索用于類型檢查、lint、構(gòu)建或測試的命令時(shí),你應(yīng)該詢問用戶是否可以將這些命令添加到 CLAUDEX.md。同樣,當(dāng)了解到代碼風(fēng)格偏好或重要的代碼庫信息時(shí),詢問是否可以將其添加到 CLAUDEX.md,以便下次記住。
# 語調(diào)和風(fēng)格
你應(yīng)該簡潔、直接、切中要點(diǎn)。當(dāng)你運(yùn)行非平凡的 bash 命令時(shí),你應(yīng)該解釋該命令的作用和運(yùn)行原因,確保用戶了解你在做什么(當(dāng)你運(yùn)行會(huì)更改用戶系統(tǒng)的命令時(shí),這一點(diǎn)尤為重要)。
請(qǐng)記住,你的輸出將顯示在命令行界面上。你的回復(fù)可以使用 Github 風(fēng)格的 markdown 進(jìn)行格式化,并將使用 CommonMark 規(guī)范以等寬字體渲染。
使用文本與用戶交流;你在工具使用之外輸出的所有文本都會(huì)顯示給用戶。只使用工具來完成任務(wù)。在會(huì)話期間,切勿使用 Bash 或代碼注釋作為與用戶交流的手段。
如果你不能或不會(huì)幫助用戶解決某事,請(qǐng)不要說明原因或可能導(dǎo)致什么后果,因?yàn)檫@聽起來很說教和煩人。如果可能,請(qǐng)?zhí)峁┯杏玫奶娲桨?,否則將回復(fù)限制在 1-2 句話。
重要:在保持有用性、質(zhì)量和準(zhǔn)確性的同時(shí),盡可能減少輸出標(biāo)記。只處理特定查詢或手頭任務(wù),避免切線信息,除非對(duì)完成請(qǐng)求絕對(duì)關(guān)鍵。如果可以用 1-3 句話或簡短段落回答,請(qǐng)這樣做。
重要:除非用戶要求,否則不要回答不必要的前言或后記(如解釋代碼或總結(jié)操作)。
重要:保持回復(fù)簡短,因?yàn)樗鼈儗@示在命令行界面上。你必須簡明扼要地回答,少于 4 行(不包括工具使用或代碼生成),除非用戶要求詳細(xì)信息。直接回答用戶的問題,不要詳細(xì)說明、解釋或細(xì)節(jié)。一個(gè)詞的答案最好。避免介紹、結(jié)論和解釋。你必須避免在回復(fù)前/后使用文本,如"答案是<答案>"、"這是文件的內(nèi)容..."或"根據(jù)提供的信息,答案是..."或"以下是我接下來要做的事情..."。
解析
系統(tǒng)提示包含以下關(guān)鍵部分:
- 角色定義:明確 AI 是一個(gè)編程助手,定位為命令行工具
- 安全規(guī)則:多處強(qiáng)調(diào)拒絕生成惡意代碼,保護(hù)用戶安全
- 交互方式:定義了斜杠命令和交互方式
- 記憶機(jī)制:通過 CLAUDEX.md 文件實(shí)現(xiàn)長期記憶
- 輸出風(fēng)格:強(qiáng)調(diào)簡潔、直接的回答風(fēng)格,限制輸出行數(shù)
- 示例對(duì)話:提供具體示例說明期望的回答方式
這種系統(tǒng)提示設(shè)計(jì)非常全面,既定義了助手的能力邊界,又提供了具體的行為指導(dǎo)。特別值得注意的是對(duì)輸出簡潔性的強(qiáng)調(diào),這對(duì)命令行工具尤為重要。
2. 工具描述(Tool Descriptions)
每個(gè)工具都有詳細(xì)的描述,幫助模型理解其功能和使用方法。
Agent 工具(AgentTool)
英文原文
Launch a new agent that has access to the following tools: GlobTool, GrepTool, LS, View, ReadNotebook. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example:
- If you are searching for a keyword like "config" or "logger", the Agent tool is appropriate
- If you want to read a specific file path, use the View or GlobTool tool instead of the Agent tool, to find the match more quickly
- If you are searching for a specific class definition like "class Foo", use the GlobTool tool instead, to find the match more quickly
Usage notes:
1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
4. The agent's outputs should generally be trusted
5. IMPORTANT: The agent can not use Bash, Replace, Edit, NotebookEditCell, so can not modify files. If you want to use these tools, use them directly instead of going through the agent.
中文翻譯
啟動(dòng)一個(gè)新的代理,該代理可以訪問以下工具:GlobTool、GrepTool、LS、View、ReadNotebook。當(dāng)你搜索關(guān)鍵字或文件,且不確定第一次就能找到正確匹配時(shí),使用 Agent 工具為你執(zhí)行搜索。例如:
- 如果你搜索像"config"或"logger"這樣的關(guān)鍵字,Agent 工具是合適的
- 如果你想讀取特定的文件路徑,使用 View 或 GlobTool 工具而不是 Agent 工具,以更快地找到匹配
- 如果你搜索特定的類定義,如"class Foo",使用 GlobTool 工具而不是 Agent 工具,以更快地找到匹配
使用注意事項(xiàng):
1. 盡可能并發(fā)啟動(dòng)多個(gè)代理,以最大化性能;為此,在單個(gè)消息中使用多個(gè)工具調(diào)用
2. 當(dāng)代理完成時(shí),它將向你返回一條消息。代理返回的結(jié)果對(duì)用戶不可見。要向用戶顯示結(jié)果,你應(yīng)該向用戶發(fā)送一條文本消息,簡明扼要地總結(jié)結(jié)果。
3. 每次代理調(diào)用都是無狀態(tài)的。你將無法向代理發(fā)送額外的消息,代理也無法在其最終報(bào)告之外與你通信。因此,你的提示應(yīng)包含高度詳細(xì)的任務(wù)描述,讓代理自主執(zhí)行,并且你應(yīng)該明確指定代理應(yīng)在其最終且唯一的消息中向你返回什么信息。
4. 代理的輸出通常應(yīng)該被信任
5. 重要:代理不能使用 Bash、Replace、Edit、NotebookEditCell,因此不能修改文件。如果你想使用這些工具,請(qǐng)直接使用它們,而不是通過代理。
Bash 工具(BashTool)
英文原文(部分)
Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
Before executing the command, please follow these steps:
1. Directory Verification:
- If the command will create new directories or files, first use the LS tool to verify the parent directory exists and is the correct location
- For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
2. Security Check:
- For security and to limit the threat of a prompt injection attack, some commands are limited or banned. If you use a disallowed command, you will receive an error message explaining the restriction. Explain the error to the User.
- Verify that the command is not one of the banned commands: alias, curl, curlie, wget, axel, aria2c, nc, telnet, lynx, w3m, links, httpie, xh, http-prompt, chrome, firefox, safari.
3. Command Execution:
- After ensuring proper quoting, execute the command.
- Capture the output of the command.
4. Output Processing:
- If the output exceeds 30000 characters, output will be truncated before being returned to you.
- Prepare the output for display to the user.
5. Return Result:
- Provide the processed output of the command.
- If any errors occurred during execution, include those in the output.
中文翻譯(部分)
在持久的 shell 會(huì)話中執(zhí)行給定的 bash 命令,可選超時(shí),確保適當(dāng)?shù)奶幚砗桶踩胧?
在執(zhí)行命令之前,請(qǐng)遵循以下步驟:
1. 目錄驗(yàn)證:
- 如果命令將創(chuàng)建新目錄或文件,首先使用 LS 工具驗(yàn)證父目錄存在且是正確的位置
- 例如,在運(yùn)行"mkdir foo/bar"之前,首先使用 LS 檢查"foo"是否存在并且是預(yù)期的父目錄
2. 安全檢查:
- 為了安全并限制提示注入攻擊的威脅,某些命令被限制或禁止。如果你使用不允許的命令,你將收到解釋限制的錯(cuò)誤消息。向用戶解釋錯(cuò)誤。
- 驗(yàn)證命令不是以下禁止命令之一:alias, curl, curlie, wget, axel, aria2c, nc, telnet, lynx, w3m, links, httpie, xh, http-prompt, chrome, firefox, safari。
3. 命令執(zhí)行:
- 確保正確引用后,執(zhí)行命令。
- 捕獲命令的輸出。
4. 輸出處理:
- 如果輸出超過 30000 個(gè)字符,輸出將在返回給你之前被截?cái)唷? - 準(zhǔn)備輸出以顯示給用戶。
5. 返回結(jié)果:
- 提供處理后的命令輸出。
- 如果執(zhí)行過程中發(fā)生任何錯(cuò)誤,在輸出中包含這些錯(cuò)誤。
文件編輯工具(FileEditTool)
英文原文(部分)
This is a tool for editing files. For moving or renaming files, you should generally use the Bash tool with the 'mv' command instead. For larger edits, use the Write tool to overwrite files. For Jupyter notebooks (.ipynb files), use the NotebookEditTool instead.
Before using this tool:
1. Use the View tool to understand the file's contents and context
2. Verify the directory path is correct (only applicable when creating new files):
- Use the LS tool to verify the parent directory exists and is the correct location
To make a file edit, provide the following:
1. file_path: The absolute path to the file to modify (must be absolute, not relative)
2. old_string: The text to replace (must be unique within the file, and must match the file contents exactly, including all whitespace and indentation)
3. new_string: The edited text to replace the old_string
The tool will replace ONE occurrence of old_string with new_string in the specified file.
CRITICAL REQUIREMENTS FOR USING THIS TOOL:
1. UNIQUENESS: The old_string MUST uniquely identify the specific instance you want to change. This means:
- Include AT LEAST 3-5 lines of context BEFORE the change point
- Include AT LEAST 3-5 lines of context AFTER the change point
- Include all whitespace, indentation, and surrounding code exactly as it appears in the file
中文翻譯(部分)
這是一個(gè)用于編輯文件的工具。對(duì)于移動(dòng)或重命名文件,你通常應(yīng)該使用帶有'mv'命令的 Bash 工具。對(duì)于較大的編輯,使用 Write 工具覆蓋文件。對(duì)于 Jupyter 筆記本(.ipynb 文件),請(qǐng)使用 NotebookEditTool。
在使用此工具之前:
1. 使用 View 工具了解文件的內(nèi)容和上下文
2. 驗(yàn)證目錄路徑是否正確(僅適用于創(chuàng)建新文件):
- 使用 LS 工具驗(yàn)證父目錄存在且是正確的位置
要進(jìn)行文件編輯,請(qǐng)?zhí)峁┮韵聝?nèi)容:
1. file_path:要修改的文件的絕對(duì)路徑(必須是絕對(duì)路徑,而非相對(duì)路徑)
2. old_string:要替換的文本(必須在文件中唯一,并且必須與文件內(nèi)容完全匹配,包括所有空白和縮進(jìn))
3. new_string:用于替換 old_string 的編輯后文本
該工具將在指定文件中替換 old_string 的一個(gè)實(shí)例為 new_string。
使用此工具的關(guān)鍵要求:
1. 唯一性:old_string 必須唯一標(biāo)識(shí)你想要更改的特定實(shí)例。這意味著:
- 在更改點(diǎn)之前包含至少 3-5 行上下文
- 在更改點(diǎn)之后包含至少 3-5 行上下文
- 包含所有空白、縮進(jìn)和周圍代碼,完全按照它們?cè)谖募谐霈F(xiàn)的方式
解析
工具描述是 ClaudeX 中非常關(guān)鍵的部分,它們幫助模型理解如何正確使用各種工具。這些描述具有以下特點(diǎn):
- 詳細(xì)的使用說明:每個(gè)工具都有清晰的使用步驟和注意事項(xiàng)
- 安全限制:特別是 BashTool 中明確列出了禁止的命令
- 最佳實(shí)踐:提供了使用工具的最佳方式,如 FileEditTool 中強(qiáng)調(diào)的唯一性要求
- 工具選擇指導(dǎo):明確說明何時(shí)使用哪個(gè)工具,如 AgentTool 適合不確定的搜索
- 錯(cuò)誤預(yù)防:預(yù)先警告可能的錯(cuò)誤情況并提供避免方法
這種詳細(xì)的工具描述對(duì)于確保模型正確使用工具至關(guān)重要,它既提供了技術(shù)細(xì)節(jié),也提供了決策指導(dǎo)。
3. Agent 工具的特殊提示
Agent 工具是一個(gè)特殊的元工具,它的提示設(shè)計(jì)尤為關(guān)鍵,上面已經(jīng)詳細(xì)介紹。
4. 上下文信息(Context)
上下文信息為模型提供項(xiàng)目相關(guān)的背景:
<context name="directoryStructure">
[項(xiàng)目目錄結(jié)構(gòu)]
</context>
<context name="gitStatus">
[Git狀態(tài)信息]
</context>
<context name="codeStyle">
[代碼風(fēng)格指南]
</context>
Prompt Tip: 使用結(jié)構(gòu)化標(biāo)簽組織上下文信息,幫助模型快速定位相關(guān)內(nèi)容。
Prompt 工程技巧
通過分析 ClaudeX 的 prompt 設(shè)計(jì),我們可以總結(jié)出以下關(guān)鍵技巧:
1. 明確的角色定義
You are ClaudeX, a CLI for coding.
技巧: 簡潔明了地定義 AI 的角色和主要功能,建立用戶期望。
2. 行為約束與輸出格式
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy.
技巧: 明確指定輸出風(fēng)格和格式,確保一致的用戶體驗(yàn)。
3. 示例驅(qū)動(dòng)的指導(dǎo)
<example>
user: what files are in the directory src/?
assistant: [runs ls and sees foo.c, bar.c, baz.c]
user: which file contains the implementation of foo?
assistant: src/foo.c
</example>
技巧: 通過具體示例說明期望行為,比抽象描述更有效。
4. 工具使用的決策樹
When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example:
- If you are searching for a keyword like "config" or "logger", the Agent tool is appropriate
- If you want to read a specific file path, use the View or GlobTool tool instead of the Agent tool, to find the match more quickly
技巧: 提供清晰的工具選擇指南,幫助模型做出最優(yōu)決策。
5. 結(jié)構(gòu)化上下文
<context name="codeStyle">The codebase follows strict style guidelines shown below...</context>
技巧: 使用標(biāo)簽和命名組織上下文信息,提高可讀性和可檢索性。
6. 安全與權(quán)限強(qiáng)調(diào)
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes.
技巧: 多次強(qiáng)調(diào)安全規(guī)則,確保模型始終遵守安全原則。
7. 工具參數(shù)驗(yàn)證
// 使用zod驗(yàn)證工具輸入
const validatedParams = inputSchema.parse(toolUse.params);
技巧: 嚴(yán)格驗(yàn)證工具參數(shù),防止錯(cuò)誤使用和潛在安全問題。
自己實(shí)現(xiàn) SWE-Agent 的 Prompt 設(shè)計(jì)指南
如果你想實(shí)現(xiàn)自己的軟件工程 Agent,以下是基于 ClaudeX 經(jīng)驗(yàn)的 prompt 設(shè)計(jì)指南:
1. 系統(tǒng)提示設(shè)計(jì)原則
-
明確定義角色和能力范圍
- 清晰說明 Agent 的主要功能和專長領(lǐng)域
- 定義與用戶交互的方式和界限
-
輸出風(fēng)格指導(dǎo)
- 根據(jù)使用場景(命令行、IDE、網(wǎng)頁等)定制輸出格式
- 提供具體示例說明期望的輸出風(fēng)格
-
安全規(guī)則設(shè)置
- 明確禁止的行為(如生成惡意代碼)
- 設(shè)置敏感操作的確認(rèn)機(jī)制
-
記憶和上下文管理
- 定義如何存儲(chǔ)和使用長期記憶
- 指導(dǎo)如何處理項(xiàng)目特定的上下文信息
2. 工具描述最佳實(shí)踐
-
結(jié)構(gòu)化描述模板
[工具名稱]: [簡短描述] 功能:詳細(xì)說明工具的主要功能 使用場景: - 適合的使用場景1 - 適合的使用場景2 參數(shù): - 參數(shù)1:說明和要求 - 參數(shù)2:說明和要求 注意事項(xiàng): - 使用時(shí)需要注意的關(guān)鍵點(diǎn) - 潛在的錯(cuò)誤和如何避免 -
工具選擇指導(dǎo)
- 提供清晰的決策樹,說明何時(shí)使用哪個(gè)工具
- 使用對(duì)比方式說明類似工具之間的區(qū)別
-
安全限制
- 明確工具的權(quán)限邊界
- 列出禁止的操作和命令
-
錯(cuò)誤處理指導(dǎo)
- 說明常見錯(cuò)誤情況
- 提供錯(cuò)誤修復(fù)的具體步驟
3. Agent 工具特殊設(shè)計(jì)
如果你的系統(tǒng)包含類似 ClaudeX 中 AgentTool 的元工具,需要特別注意:
-
明確代理能力
- 詳細(xì)列出代理可以訪問的工具集
- 說明代理的權(quán)限限制
-
狀態(tài)管理
- 明確代理是有狀態(tài)還是無狀態(tài)的
- 說明代理如何與主系統(tǒng)通信
-
并發(fā)執(zhí)行
- 提供并發(fā)執(zhí)行多個(gè)代理的指導(dǎo)
- 說明如何處理并發(fā)結(jié)果
-
結(jié)果處理
- 指導(dǎo)如何解釋和使用代理返回的結(jié)果
- 說明結(jié)果可能的格式和限制
4. 上下文管理策略
-
結(jié)構(gòu)化上下文
<context type="project_structure"> [項(xiàng)目結(jié)構(gòu)信息] </context> <context type="code_style"> [代碼風(fēng)格指南] </context> <context type="version_control"> [版本控制信息] </context> -
上下文優(yōu)先級(jí)
- 指導(dǎo)模型如何在有限的上下文窗口中優(yōu)先處理重要信息
- 提供上下文壓縮或摘要的策略
-
動(dòng)態(tài)上下文
- 說明如何根據(jù)當(dāng)前任務(wù)動(dòng)態(tài)調(diào)整上下文
- 提供增量加載上下文的機(jī)制
5. 示例和模板
-
任務(wù)執(zhí)行模板
任務(wù)分析: 1. [分析任務(wù)要求] 2. [確定需要的信息] 信息收集: 1. [使用工具A收集信息] 2. [使用工具B驗(yàn)證信息] 執(zhí)行計(jì)劃: 1. [步驟1] 2. [步驟2] 結(jié)果驗(yàn)證: 1. [驗(yàn)證執(zhí)行結(jié)果] 2. [處理可能的錯(cuò)誤] -
常見任務(wù)示例
- 提供常見編程任務(wù)的完整示例
- 包括工具選擇、執(zhí)行步驟和結(jié)果處理
-
錯(cuò)誤處理示例
- 提供處理常見錯(cuò)誤的示例
- 說明如何從失敗中恢復(fù)
Prompt 評(píng)估與改進(jìn)框架
要持續(xù)提升 Prompt 引擎的效果,需要建立系統(tǒng)化的評(píng)估和改進(jìn)框架:
graph LR
A[設(shè)計(jì)初始Prompt] --> B[定義評(píng)估指標(biāo)]
B --> C[收集基準(zhǔn)測試用例]
C --> D[執(zhí)行A/B測試]
D --> E[分析結(jié)果]
E --> F[迭代改進(jìn)]
F --> A
style A fill:#f9d5e5,stroke:#333,stroke-width:2px
style B fill:#d5e5f9,stroke:#333,stroke-width:2px
style C fill:#d5f9e5,stroke:#333,stroke-width:2px
style D fill:#f9e5d5,stroke:#333,stroke-width:2px
style E fill:#e5d5f9,stroke:#333,stroke-width:2px
style F fill:#f5f9d5,stroke:#333,stroke-width:2px
關(guān)鍵評(píng)估指標(biāo)
- 首次成功率:模型在首次嘗試中正確解決問題的比例
- 工具選擇準(zhǔn)確性:模型選擇最合適工具的準(zhǔn)確率
- 交互輪次:完成任務(wù)所需的平均交互次數(shù)
- 執(zhí)行時(shí)間:從請(qǐng)求到完成的平均時(shí)間
- Token 效率:完成任務(wù)所需的平均 token 數(shù)量
A/B 測試策略
對(duì) Prompt 變體進(jìn)行系統(tǒng)化測試:
- 控制變量法:每次只修改一個(gè) Prompt 組件
- 標(biāo)準(zhǔn)測試集:使用一致的測試用例集評(píng)估性能
- 多維度評(píng)分:綜合考慮速度、準(zhǔn)確性、token 效率等因素
- 用戶反饋整合:結(jié)合定量和定性反饋
總結(jié):構(gòu)建高效 Prompt 引擎的關(guān)鍵
通過對(duì) ClaudeX 的 prompt 引擎設(shè)計(jì)分析,我們可以總結(jié)出以下核心原則:
- 模塊化設(shè)計(jì): 將系統(tǒng)提示、工具描述和上下文信息分離,便于維護(hù)和優(yōu)化
- 清晰的指導(dǎo): 通過具體示例和決策樹幫助模型做出正確選擇
- 安全第一: 多層次的安全檢查和權(quán)限控制
- 結(jié)構(gòu)化信息: 使用標(biāo)簽和命名組織信息,提高可讀性
- 適應(yīng)性反饋: 通過工具結(jié)果反饋調(diào)整模型行為
實(shí)現(xiàn)自己的 SWE-Agent 時(shí),應(yīng)該注重這些核心原則,同時(shí)根據(jù)自己的具體應(yīng)用場景和用戶需求進(jìn)行調(diào)整。最重要的是,prompt 設(shè)計(jì)應(yīng)該是迭代的過程,通過實(shí)際使用反饋不斷優(yōu)化和改進(jìn)。
行動(dòng)建議
- 從模板開始:使用本文提供的 Prompt 模板作為起點(diǎn)
- 優(yōu)先解決痛點(diǎn):首先優(yōu)化工具選擇和上下文管理這兩個(gè)最易踩坑的環(huán)節(jié)
- 建立測試集:創(chuàng)建覆蓋各種常見編程場景的測試用例集
- 數(shù)據(jù)驅(qū)動(dòng)迭代:基于定量評(píng)估結(jié)果而非直覺進(jìn)行改進(jìn)
- 安全審計(jì):在部署前進(jìn)行全面的安全審查
在我們的實(shí)踐中,通過重新設(shè)計(jì)工具決策樹和優(yōu)化上下文管理,可以將任務(wù)完成時(shí)間減少 40%,token 使用量減少 35%。這些數(shù)據(jù)表明,好的 prompt 設(shè)計(jì)確實(shí)能帶來顯著的效率提升。
在下一篇文章中,我們將深入探討 ClaudeX 的工具系統(tǒng)設(shè)計(jì),分析如何構(gòu)建和組合各種工具,實(shí)現(xiàn)復(fù)雜的編程任務(wù)。我們會(huì)討論工具接口設(shè)計(jì)、工具組合策略、權(quán)限管理最佳實(shí)踐以及錯(cuò)誤處理策略等關(guān)鍵話題。
本文由mdnice多平臺(tái)發(fā)布