-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathconstructMessages.ts
224 lines (188 loc) · 7.08 KB
/
constructMessages.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import {
BrowserSerializedContinueConfig,
ChatHistoryItem,
ChatMessage,
MessagePart,
ModelDescription,
} from "../";
import { normalizeToMessageParts } from "../util/messageContent";
import { modelSupportsTools } from "./autodetect";
const TOOL_USE_RULES = `When using tools, follow the following guidelines:
- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`;
const CODE_BLOCK_INSTRUCTIONS = "Always include the language and file name in the info string when you write code blocks, for example '```python file.py'."
// Helper function to strip whitespace
function stripWhitespace(text: string, stripLeading = false, stripTrailing = false): string {
let result = text;
if (stripLeading) {
result = result.replace(/^[\s\n]+/, '');
}
if (stripTrailing) {
result = result.replace(/[\s\n]+$/, '');
}
return result;
}
// Helper function for placeholder replacement with whitespace handling
function replacePlaceholder(
text: string,
placeholder: string,
replacement: string
): string {
if (!text.includes(placeholder)) {
return text;
}
const placeholderIndex = text.indexOf(placeholder);
const placeholderLength = placeholder.length;
// Check surroundings to determine whitespace needs
const isAtBeginning = placeholderIndex === 0;
const isAtEnd = placeholderIndex + placeholderLength === text.length;
if (!replacement) {
// No replacement to add - just replace with empty string and clean up
let processed = text.replace(placeholder, "");
return stripWhitespace(processed, isAtBeginning, isAtEnd);
} else {
// Add replacement with appropriate whitespace
let formattedReplacement = replacement;
if (!isAtBeginning && !(/[\n\s]$/.test(text.substring(0, placeholderIndex)))) {
formattedReplacement = "\n\n" + formattedReplacement;
};
if (!isAtEnd && !(/^[\n\s]/.test(text.substring(placeholderIndex + placeholderLength)))) {
formattedReplacement = formattedReplacement + "\n\n";
};
return text.replace(placeholder, formattedReplacement);
}
}
function constructSystemPrompt(
modelDescription: ModelDescription,
useTools: boolean,
continueConfig: BrowserSerializedContinueConfig
): string | null {
let systemMessage = "";
// We we have no access to the LLM class, we final systemMessage have to be the same as in core/llm/index.ts
const userSystemMessage = modelDescription.systemMessage ?? continueConfig.systemMessage;
// Get templates from model description or use defaults
const codeBlockTemplate = modelDescription.promptTemplates?.codeBlockInstructions ?? CODE_BLOCK_INSTRUCTIONS;
const toolUseTemplate = modelDescription.promptTemplates?.toolUseRules ?? TOOL_USE_RULES;
// Determine which instructions to include
const codeBlockInstructions = codeBlockTemplate;
const toolUseInstructions = useTools && modelSupportsTools(modelDescription) ? toolUseTemplate : "";
switch ((continueConfig.experimental?.systemMessageComposition || "legacy")) {
case "prepend":
// Put user system message first, then default instructions
systemMessage = userSystemMessage || "";
if (systemMessage && codeBlockInstructions) {
systemMessage += "\n\n" + codeBlockInstructions;
} else if (codeBlockInstructions) {
systemMessage = codeBlockInstructions;
}
if (systemMessage && toolUseInstructions) {
systemMessage += "\n\n" + toolUseInstructions;
} else if (toolUseInstructions) {
systemMessage = toolUseInstructions;
}
break;
case "placeholders":
case "placeholders":
if (userSystemMessage) {
// Define placeholders
const allDefaultInstructions = [
codeBlockInstructions,
toolUseInstructions
].filter(Boolean).join("\n\n");
// Replace placeholders in user system message
let processedMessage = userSystemMessage;
// Replace all placeholders using our helper function
processedMessage = replacePlaceholder(
processedMessage,
"{DEFAULT_INSTRUCTIONS}",
allDefaultInstructions
);
processedMessage = replacePlaceholder(
processedMessage,
"{CODE_BLOCK_INSTRUCTIONS}",
codeBlockInstructions
);
processedMessage = replacePlaceholder(
processedMessage,
"{TOOL_USE_RULES}",
toolUseInstructions
);
systemMessage = processedMessage;
} else {
// Fall back to legacy behavior if no user system message
systemMessage = codeBlockInstructions;
if (toolUseInstructions) {
systemMessage += "\n\n" + toolUseInstructions;
}
}
break;
case "legacy":
case "append":
default:
systemMessage = codeBlockInstructions;
if (useTools && modelSupportsTools(modelDescription)) {
systemMessage += "\n\n" + toolUseTemplate;
}
// logic moved from core/llm/countTokens.ts
if (userSystemMessage && userSystemMessage.trim() !== "") {
const shouldAddNewLines = systemMessage !== "";
if (shouldAddNewLines) {
systemMessage += "\n\n";
}
systemMessage += userSystemMessage;
}
if (userSystemMessage === "") {
// Used defined explicit empty system message will be forced
systemMessage = "";
}
break;
}
return systemMessage;
}
const CANCELED_TOOL_CALL_MESSAGE =
"This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool.";
export function constructMessages(
history: ChatHistoryItem[],
modelDescription: ModelDescription,
useTools: boolean,
continueConfig: BrowserSerializedContinueConfig,
): ChatMessage[] {
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
);
const msgs: ChatMessage[] = [];
const systemMessage = constructSystemPrompt(modelDescription, useTools, continueConfig);
if (systemMessage) {
msgs.push({
role: "system",
content: systemMessage,
});
}
for (let i = 0; i < filteredHistory.length; i++) {
const historyItem = filteredHistory[i];
if (historyItem.message.role === "user") {
// Gather context items for user messages
let content = normalizeToMessageParts(historyItem.message);
const ctxItems = historyItem.contextItems.map((ctxItem) => {
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
});
content = [...ctxItems, ...content];
msgs.push({
...historyItem.message,
content,
});
} else if (historyItem.toolCallState?.status === "canceled") {
// Canceled tool call
msgs.push({
...historyItem.message,
content: CANCELED_TOOL_CALL_MESSAGE,
});
} else {
msgs.push(historyItem.message);
}
}
// Remove the "id" from all of the messages
return msgs.map((msg) => {
const { id, ...rest } = msg as any;
return rest;
});
}