Repository navigation
Expand file tree
/
Copy pathtest_mlx_server.py
More file actions
406 lines (353 loc) · 13.1 KB
/
Copy pathtest_mlx_server.py
File metadata and controls
406 lines (353 loc) · 13.1 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/usr/bin/env python3
"""
Test harness for MLX Native Server — simulates Claude Code's Anthropic API requests.
Tests multi-step tool-use tasks to verify the model can reliably emit tool calls.
"""
import json
import sys
import time
import os
import requests
# CCL_TEST_SERVER points the harness at another server (e.g. the llama.cpp
# backend on Linux/Windows). Default is unchanged: the Mac MLX server.
SERVER = os.environ.get("CCL_TEST_SERVER", "http://localhost:4000")
TIMEOUT = float(os.environ.get("CCL_TEST_TIMEOUT", "120"))
# Optional: CCL_TEST_TEMPERATURE=0 makes runs repeatable, so a before/after
# comparison of a server change is apples to apples.
TEMPERATURE = os.environ.get("CCL_TEST_TEMPERATURE")
PASS = 0
FAIL = 0
RESULTS = []
# ─── Minimal tool definitions (what Claude Code sends) ──────────────────────
TOOLS = [
{
"name": "Bash",
"description": "Execute a bash command and return output.",
"input_schema": {
"type": "object",
"properties": {
"command": {"type": "string", "description": "The bash command to execute"},
"description": {"type": "string", "description": "Description of what this command does"},
},
"required": ["command"],
},
},
{
"name": "Read",
"description": "Read a file from the filesystem.",
"input_schema": {
"type": "object",
"properties": {
"file_path": {"type": "string", "description": "Absolute path to the file"},
},
"required": ["file_path"],
},
},
{
"name": "Edit",
"description": "Edit a file by replacing text.",
"input_schema": {
"type": "object",
"properties": {
"file_path": {"type": "string", "description": "Absolute path to the file"},
"old_string": {"type": "string", "description": "Text to find"},
"new_string": {"type": "string", "description": "Replacement text"},
},
"required": ["file_path", "old_string", "new_string"],
},
},
{
"name": "Write",
"description": "Write content to a file.",
"input_schema": {
"type": "object",
"properties": {
"file_path": {"type": "string", "description": "Absolute path to the file"},
"content": {"type": "string", "description": "Content to write"},
},
"required": ["file_path", "content"],
},
},
{
"name": "Glob",
"description": "Find files matching a glob pattern.",
"input_schema": {
"type": "object",
"properties": {
"pattern": {"type": "string", "description": "Glob pattern"},
},
"required": ["pattern"],
},
},
{
"name": "Grep",
"description": "Search file contents with regex.",
"input_schema": {
"type": "object",
"properties": {
"pattern": {"type": "string", "description": "Regex pattern to search"},
"path": {"type": "string", "description": "Path to search in"},
},
"required": ["pattern"],
},
},
]
def send_message(messages, system="You are a helpful coding assistant. When asked to perform tasks, you MUST use the available tools. Always call tools using <tool_call> JSON format.", max_tokens=4096):
"""Send a request to the MLX server and return the parsed response."""
body = {
"model": "claude-sonnet-4-6",
"max_tokens": max_tokens,
"system": system,
"messages": messages,
"tools": TOOLS,
}
if TEMPERATURE is not None:
body["temperature"] = float(TEMPERATURE)
t0 = time.time()
resp = requests.post(f"{SERVER}/v1/messages", json=body, timeout=TIMEOUT)
elapsed = time.time() - t0
data = resp.json()
return data, elapsed
def extract_tool_calls(response):
"""Extract tool_use blocks from an Anthropic response."""
calls = []
for block in response.get("content", []):
if block.get("type") == "tool_use":
calls.append(block)
return calls
def extract_text(response):
"""Extract text blocks from an Anthropic response."""
parts = []
for block in response.get("content", []):
if block.get("type") == "text" and block.get("text", "").strip():
parts.append(block["text"].strip())
return "\n".join(parts)
def run_test(name, messages, expect_tool=None, expect_any_tool=True, system=None):
"""Run a single test case.
expect_tool may be a single tool name or a tuple of acceptable names, for
prompts where more than one tool is a legitimate answer.
"""
global PASS, FAIL
kwargs = {"messages": messages}
if system:
kwargs["system"] = system
print(f"\n{'='*70}")
print(f"TEST: {name}")
print(f"{'='*70}")
try:
resp, elapsed = send_message(**kwargs)
except Exception as e:
print(f" FAIL — request error: {e}")
FAIL += 1
RESULTS.append((name, "FAIL", str(e)))
return None
tool_calls = extract_tool_calls(resp)
text = extract_text(resp)
tokens_in = resp.get("usage", {}).get("input_tokens", 0)
tokens_out = resp.get("usage", {}).get("output_tokens", 0)
print(f" Time: {elapsed:.1f}s | Tokens: {tokens_in} in, {tokens_out} out")
if text:
print(f" Text: {text[:150]}...")
if tool_calls:
for tc in tool_calls:
args_preview = json.dumps(tc.get("input", {}))[:120]
print(f" Tool: {tc['name']}({args_preview})")
else:
print(f" Tool calls: NONE")
# Check expectations
passed = True
reason = ""
if expect_any_tool and not tool_calls:
passed = False
reason = "Expected a tool call but got none"
elif expect_tool and not any(
tc["name"] in (expect_tool if isinstance(expect_tool, tuple) else (expect_tool,))
for tc in tool_calls
):
passed = False
wanted = " or ".join(expect_tool) if isinstance(expect_tool, tuple) else expect_tool
reason = f"Expected tool '{wanted}' but got: {[tc['name'] for tc in tool_calls]}"
elif tool_calls:
# Verify tool calls have non-empty arguments
for tc in tool_calls:
inp = tc.get("input", {})
if not inp:
passed = False
reason = f"Tool '{tc['name']}' has empty arguments"
break
if passed:
print(f" ✓ PASS")
PASS += 1
RESULTS.append((name, "PASS", ""))
else:
print(f" ✗ FAIL — {reason}")
FAIL += 1
RESULTS.append((name, "FAIL", reason))
return resp
# ─── Test Cases ─────────────────────────────────────────────────────────────
def test_simple_bash():
"""Test: simple single bash command."""
return run_test(
"Simple Bash command",
[{"role": "user", "content": "List the files in /tmp"}],
# Glob(pattern="/tmp/*") is as correct an answer as `ls /tmp` here —
# don't fail a model for picking the more precise tool (see #41).
expect_tool=("Bash", "Glob"),
)
def test_mkdir():
"""Test: create a directory."""
return run_test(
"Create directory with mkdir",
[{"role": "user", "content": "Create a folder called /tmp/test_mlx_calendar"}],
expect_tool="Bash",
)
def test_multi_step_calendar():
"""Test: the exact calendar scenario that failed — create folders then delete some."""
# Turn 1: create the structure
print("\n" + "#"*70)
print("# MULTI-STEP TEST: Calendar folder creation + deletion")
print("#"*70)
resp1 = run_test(
"Calendar Step 1: Create month folders",
[{"role": "user", "content": "Create a folder /tmp/test_calendar and inside it create a folder for each month of the year: January through December."}],
expect_tool="Bash",
)
if not resp1:
return
# Simulate the tool result coming back
tool_calls = extract_tool_calls(resp1)
if not tool_calls:
return
tool_result_msg = {
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_calls[0]["id"],
"content": "Done. Directories created."
}
]
}
# Turn 2: now delete all months except September
resp2 = run_test(
"Calendar Step 2: Delete all months except September",
[
{"role": "user", "content": "Create a folder /tmp/test_calendar and inside it create a folder for each month of the year: January through December."},
{"role": "assistant", "content": resp1.get("content", [])},
tool_result_msg,
{"role": "user", "content": "Now delete all of the month folders except for September."},
],
expect_tool="Bash",
)
if not resp2:
return
tool_calls2 = extract_tool_calls(resp2)
if not tool_calls2:
return
tool_result_msg2 = {
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_calls2[0]["id"],
"content": "Done. Only September remains."
}
]
}
# Turn 3: verify with ls
run_test(
"Calendar Step 3: Verify remaining folders",
[
{"role": "user", "content": "Create a folder /tmp/test_calendar and inside it create a folder for each month of the year."},
{"role": "assistant", "content": resp1.get("content", [])},
tool_result_msg,
{"role": "user", "content": "Delete all of the month folders except for September."},
{"role": "assistant", "content": resp2.get("content", [])},
tool_result_msg2,
{"role": "user", "content": "Now list the contents of /tmp/test_calendar to verify only September is left."},
],
expect_tool="Bash",
)
def test_file_read():
"""Test: read a file."""
return run_test(
"Read a file",
[{"role": "user", "content": "Read the file /etc/hosts"}],
expect_tool="Read",
)
def test_multi_tool_sequence():
"""Test: a task requiring multiple different tools in sequence."""
return run_test(
"Multi-tool: find then read",
[{"role": "user", "content": "Find all .py files in /tmp and then read the first one you find. Start by searching for them."}],
expect_any_tool=True,
)
def test_edit_file():
"""Test: edit a file (requires structured arguments)."""
return run_test(
"Edit a file",
[
{"role": "user", "content": "I have a file at /tmp/test_edit.txt with the content 'hello world'. Change 'hello' to 'goodbye'."},
],
expect_any_tool=True,
)
def test_complex_bash():
"""Test: complex bash command with pipes and logic."""
return run_test(
"Complex Bash with pipes",
[{"role": "user", "content": "Count how many lines are in /etc/hosts and show me the result."}],
expect_tool="Bash",
)
def test_back_to_back_tools():
"""Simulate 5 rapid tool calls in sequence to test consistency."""
print("\n" + "#"*70)
print("# RAPID-FIRE TEST: 5 sequential Bash commands")
print("#"*70)
prompts = [
"Run: echo 'test 1'",
"Run: echo 'test 2'",
"Run: pwd",
"Run: date",
"Run: whoami",
]
for i, prompt in enumerate(prompts):
run_test(
f"Rapid-fire #{i+1}: {prompt}",
[{"role": "user", "content": prompt}],
expect_tool="Bash",
)
# ─── Main ───────────────────────────────────────────────────────────────────
if __name__ == "__main__":
print("MLX Server Test Harness")
print(f"Server: {SERVER}")
print(f"Testing tool-call reliability for multi-step tasks\n")
# Check server health
try:
r = requests.get(f"{SERVER}/health", timeout=5)
print(f"Server health: {r.json()}")
except Exception as e:
print(f"Server not reachable: {e}")
sys.exit(1)
# Run all tests
test_simple_bash()
test_mkdir()
test_file_read()
test_complex_bash()
test_edit_file()
test_multi_tool_sequence()
test_back_to_back_tools()
test_multi_step_calendar()
# Summary
print("\n" + "="*70)
print(f"RESULTS: {PASS} passed, {FAIL} failed out of {PASS+FAIL} tests")
print("="*70)
for name, status, reason in RESULTS:
icon = "✓" if status == "PASS" else "✗"
suffix = f" — {reason}" if reason else ""
print(f" {icon} {name}{suffix}")
if FAIL > 0:
print(f"\n{FAIL} test(s) FAILED — server needs more work")
sys.exit(1)
else:
print(f"\nAll {PASS} tests PASSED!")
sys.exit(0)