Cline 源码浅析 - Prompt 设计
“Agent 就是如何拼出更好用的 Prompt”,虽然有点玩笑的意味,但也能说明一定的问题。本篇文章我们探讨下 Cline 里的 Prompt 设计。
System Prompt
众所周知,System Prompt 是 Agent 的核心资产😂,Github 上 system-prompts-and-models-of-ai-tools 这个仓库收集了各类 AI 应用的 System Prompt,已经有 56.6K 的 Star 了,可见一斑。
Cline 的 System Prompt 位于 src/core/prompts/system.ts
,根据上下文信息、工具以及模型信息动态生成。
You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
工具 TOOL USE
You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
我们自上而下的读一遍 System Prompt。
- 工具调用格式
首先告诉模型使用 XML 语法输出工具调用相关的内容。
<tool_name>
<parameter1_name>value1</parameter1_name>
<parameter2_name>value2</parameter2_name>
...
</tool_name>
- 工具列表
列举了 Cline 内置的工具,主要包括描述、参数以及使用 DEMO,比如 write_to_file
:
## write_to_file
Description: Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
Parameters:
- path: (required) The path of the file to write to (relative to the current working directory ${cwd.toPosix()})
- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified.
Usage:
<write_to_file>
<path>File path here</path>
<content>
Your file content here
</content>
</write_to_file>
Cline 内置了十多个工具,覆盖了命令行、文件操作、浏览器、MCP 等,这些工具极大的丰富了模型的能力。
- 工具调用 Example
展示了多个工具调用的样例给模型参考:
# Tool Use Examples
## Example 1: Requesting to execute a command
<execute_command>
<command>npm run dev</command>
<requires_approval>false</requires_approval>
</execute_command>
- 工具使用指引
这里相当于手把手教模型逐步思考如何使用工具(类似于思维链(CoT)),简单翻译如下:
1)首先,模型需要评估已经掌握的信息,使用 <thinking>
标签包裹。
2)根据任务和提供的工具描述,选择最合适的工具。
3)如果需要执行多个操作,请一次只使用一个工具,每一步都必须以前一步的结果为依据。
4)使用指定的 XML 格式来构建你的工具调用。
5)每次使用工具后,用户将回复该工具的执行结果。这个结果会为你提供继续任务或做出进一步决策所需的信息。
6)每次使用工具后,一定要等待用户的确认后再继续。
以上的操作,可以确保模型按步骤拆解任务,确认每步的成功与否,根据用户的反馈实时进行调整,保证工具使用和最终任务的正确性。
MCP Server
这部分我们在 Cline 源码浅析 - MCP 调用聊过,这里不再展开。
文件编辑 EDITING FILES
对于 Code Agent 文件编辑是非常重要的部分,这里再次强调了 write_to_file
和 replace_in_file
两个工具的使用:详细的使用时机以及重要提示。
再次以 workflow 的方式告诉模型使用文件编辑工具的最佳实践:
1. 在进行编辑之前,评估你更改的范围,并决定使用哪个工具。
2. 对于有针对性的修改,请使用 `replace_in_file` 工具,并精心编写 SEARCH/REPLACE 块。如果你需要进行多项更改,可以在一个 `replace_in_file` 调用中堆叠多个 SEARCH/REPLACE 块。
3. 对于大规模重构或初始文件创建,请依赖 `write_to_file` 工具。
4. 一旦文件通过 `write_to_file` 或 `replace_in_file` 被编辑,系统将向你提供修改后文件的最终状态。请将此更新后的内容作为后续所有 SEARCH/REPLACE 操作的参考点,因为它反映了任何自动格式化或用户手动应用的更改。
通过在 `write_to_file` 和 `replace_in_file` 之间做出深思熟虑的选择,你可以使文件编辑过程更加顺畅、安全和高效。