-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-message-formatting.ts
More file actions
313 lines (272 loc) · 8.83 KB
/
Copy pathtest-message-formatting.ts
File metadata and controls
313 lines (272 loc) · 8.83 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/**
* Test to verify message formatting fixes for Cerebras API
* This test ensures we don't send null content which causes 400 errors
*/
import { AssistantMessage, UserMessage } from './core/messages.js';
import { randomUUID } from 'crypto';
/**
* Simulate the message formatting logic from llm/cerebras.ts
*/
function formatMessagesForCerebras(messages: (UserMessage | AssistantMessage)[]) {
const apiMessages: any[] = [];
for (const msg of messages) {
if (msg.message.role === 'user') {
const content = msg.message.content;
// Handle user message content - could be string or structured content
let userContent: string;
if (typeof content === 'string') {
userContent = content;
} else if (Array.isArray(content)) {
// Extract text from structured content (e.g., tool results)
userContent = content
.map((item: any) => {
if (typeof item === 'string') return item;
if (item.type === 'text') return item.text;
if (item.type === 'tool_result') {
return `Tool result: ${typeof item.content === 'string' ? item.content : JSON.stringify(item.content)}`;
}
return JSON.stringify(item);
})
.join('\n');
} else {
userContent = JSON.stringify(content);
}
apiMessages.push({
role: 'user',
content: userContent,
});
} else if (msg.message.role === 'assistant') {
const content = msg.message.content;
// Check if there are tool calls in the message
const contentArray = Array.isArray(content) ? content : [];
const toolCalls = contentArray
.filter((c: any) => c.type === 'tool_use')
.map((c: any) => ({
id: c.id,
type: 'function' as const,
function: {
name: c.name,
arguments: JSON.stringify(c.input),
},
}));
// Extract text content
const textContent = contentArray
.filter((c: any) => c.type === 'text')
.map((c: any) => c.text)
.join('\n');
if (toolCalls.length > 0) {
// FIXED: When there are tool calls, content should be either text or empty string (not null)
apiMessages.push({
role: 'assistant',
content: textContent || '', // This was: textContent || null (CAUSED 400 ERROR)
tool_calls: toolCalls,
});
} else {
apiMessages.push({
role: 'assistant',
content: textContent || 'No response',
});
}
}
}
return apiMessages;
}
/**
* Test case 1: Assistant message with tool calls and no text content
* This would have caused a 400 error before the fix (null content)
*/
function testAssistantMessageWithToolCallsNoText() {
console.log('\n=== Test 1: Assistant message with tool calls and NO text content ===');
const messages: AssistantMessage[] = [
{
type: 'assistant',
uuid: randomUUID(),
message: {
id: 'msg-1',
model: 'qwen-3-coder-480b',
role: 'assistant',
content: [
{
type: 'tool_use',
id: 'tool-1',
name: 'bash',
input: { command: 'ls' },
},
],
stop_reason: 'tool_use',
stop_sequence: '',
type: 'message',
usage: {
input_tokens: 100,
output_tokens: 50,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
cache_creation: null,
server_tool_use: null,
service_tier: null,
},
} as any,
costUSD: 0,
durationMs: 0,
},
];
const formatted = formatMessagesForCerebras(messages);
const assistantMsg = formatted[0];
console.log('Formatted message:', JSON.stringify(assistantMsg, null, 2));
// CRITICAL CHECKS
if (assistantMsg.content === null) {
console.error('❌ FAIL: content is null (would cause 400 error)');
return false;
} else if (assistantMsg.content === '') {
console.log('✅ PASS: content is empty string (valid for Cerebras API)');
} else {
console.log('✅ PASS: content has text');
}
if (!assistantMsg.tool_calls || assistantMsg.tool_calls.length === 0) {
console.error('❌ FAIL: tool_calls missing');
return false;
}
console.log('✅ PASS: tool_calls present');
return true;
}
/**
* Test case 2: Assistant message with tool calls AND text content
*/
function testAssistantMessageWithToolCallsAndText() {
console.log('\n=== Test 2: Assistant message with tool calls AND text content ===');
const messages: AssistantMessage[] = [
{
type: 'assistant',
uuid: randomUUID(),
message: {
id: 'msg-2',
model: 'qwen-3-coder-480b',
role: 'assistant',
content: [
{
type: 'text',
text: 'Let me check the files',
},
{
type: 'tool_use',
id: 'tool-2',
name: 'bash',
input: { command: 'ls -la' },
},
],
stop_reason: 'tool_use',
stop_sequence: '',
type: 'message',
usage: {
input_tokens: 100,
output_tokens: 50,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
cache_creation: null,
server_tool_use: null,
service_tier: null,
},
} as any,
costUSD: 0,
durationMs: 0,
},
];
const formatted = formatMessagesForCerebras(messages);
const assistantMsg = formatted[0];
console.log('Formatted message:', JSON.stringify(assistantMsg, null, 2));
if (assistantMsg.content === 'Let me check the files') {
console.log('✅ PASS: content has correct text');
} else {
console.error('❌ FAIL: content incorrect');
return false;
}
if (!assistantMsg.tool_calls || assistantMsg.tool_calls.length === 0) {
console.error('❌ FAIL: tool_calls missing');
return false;
}
console.log('✅ PASS: tool_calls present');
return true;
}
/**
* Test case 3: User message with structured content (tool results)
*/
function testUserMessageWithToolResults() {
console.log('\n=== Test 3: User message with structured content (tool results) ===');
const messages: UserMessage[] = [
{
type: 'user',
uuid: randomUUID(),
message: {
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: 'tool-1',
content: 'file1.txt\nfile2.txt\nfile3.txt',
is_error: false,
},
],
} as any,
},
];
const formatted = formatMessagesForCerebras(messages);
const userMsg = formatted[0];
console.log('Formatted message:', JSON.stringify(userMsg, null, 2));
if (typeof userMsg.content === 'string' && userMsg.content.includes('Tool result:')) {
console.log('✅ PASS: tool result properly converted to string');
} else {
console.error('❌ FAIL: tool result not properly formatted');
return false;
}
return true;
}
/**
* Test case 4: Demonstrate the OLD BEHAVIOR (what would cause 400)
*/
function demonstrateOldBehavior() {
console.log('\n=== Test 4: Demonstrating OLD behavior (would cause 400) ===');
const textContent = ''; // Empty text content
// OLD CODE (BROKEN):
const oldFormatted = {
role: 'assistant',
content: textContent || null, // THIS CAUSES 400 ERROR
tool_calls: [{ id: 'tool-1', type: 'function', function: { name: 'bash', arguments: '{}' } }],
};
// NEW CODE (FIXED):
const newFormatted = {
role: 'assistant',
content: textContent || '', // THIS WORKS
tool_calls: [{ id: 'tool-1', type: 'function', function: { name: 'bash', arguments: '{}' } }],
};
console.log('OLD (broken) format:', JSON.stringify(oldFormatted, null, 2));
console.log('NEW (fixed) format:', JSON.stringify(newFormatted, null, 2));
if (oldFormatted.content === null) {
console.log('❌ OLD: content is null (causes 400 Bad Request from Cerebras)');
}
if (newFormatted.content === '') {
console.log('✅ NEW: content is empty string (accepted by Cerebras)');
}
return true;
}
// Run all tests
console.log('='.repeat(70));
console.log('MESSAGE FORMATTING FIX VERIFICATION TEST');
console.log('Testing fix for 400 Bad Request errors from Cerebras API');
console.log('='.repeat(70));
const results = [
testAssistantMessageWithToolCallsNoText(),
testAssistantMessageWithToolCallsAndText(),
testUserMessageWithToolResults(),
demonstrateOldBehavior(),
];
console.log('\n' + '='.repeat(70));
const passCount = results.filter(r => r).length;
const totalCount = results.length;
if (passCount === totalCount) {
console.log(`✅ ALL TESTS PASSED (${passCount}/${totalCount})`);
console.log('✅ The fix prevents null content from being sent to Cerebras');
process.exit(0);
} else {
console.log(`❌ SOME TESTS FAILED (${passCount}/${totalCount} passed)`);
process.exit(1);
}