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
|
#!/usr/bin/env python3
"""A fake OpenAI-compatible server that makes a model struggle on purpose,
to see mm's struggle signals (ticket 153) without waiting for a real model
to misbehave.
FAKE=loop python3 fake-llm.py # listens on 127.0.0.1:8765
Scenarios (FAKE=...):
loop always calls bash with the same failing command → ⚠ loop … then ✖ stuck
unknown calls a tool that does not exist → ✖ unknown tool: run_python
empty answers nothing → ⚠ empty answer
context answers, reporting 900 prompt tokens (window 1000)→ ⚠ context 90% full
broken tool-call arguments that are not JSON → ⚠ broken tool call …
runaway tool-call arguments that repeat forever → ✖ runaway tool call
silent accepts the request and never answers → ✖ stalled
failing calls bash with a new failing command every time → ⚠ failing: 3 tool calls in a row (ticket 160)
turns calls bash with a new command every time → ✖ max turns reached (after maxTurns calls)
"""
import json
import os
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
SCENARIO = os.environ.get("FAKE", "loop")
PORT = int(os.environ.get("PORT", "8765"))
calls = 0
def chunk(delta, finish=None, usage=None):
body = {"id": "fake", "object": "chat.completion.chunk", "created": 0, "model": "fake",
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
if usage:
body["usage"] = usage
return "data: " + json.dumps(body) + "\n\n"
def tool_call(name, arguments):
return [chunk({"role": "assistant", "tool_calls": [{"index": 0, "id": "call_%d" % calls, "type": "function",
"function": {"name": name, "arguments": ""}}]}),
chunk({"tool_calls": [{"index": 0, "function": {"arguments": arguments}}]}),
chunk({}, "tool_calls")]
def text(content, usage=None):
return [chunk({"role": "assistant", "content": content}), chunk({}, "stop", usage)]
def reply():
"""The SSE events of one answer, for the scenario."""
if SCENARIO == "loop":
return tool_call("bash", json.dumps({"command": "cat /no/such/file"}))
if SCENARIO == "unknown":
return tool_call("run_python", json.dumps({"code": "print(1)"}))
if SCENARIO == "empty":
return text("")
if SCENARIO == "context":
return text("Done.", {"prompt_tokens": 900, "completion_tokens": 2, "total_tokens": 902})
if SCENARIO == "broken":
return tool_call("bash", '{"command": "ls')
if SCENARIO == "failing":
return tool_call("bash", json.dumps({"command": "cat /no/such/file-%d" % calls}))
if SCENARIO == "turns":
return tool_call("bash", json.dumps({"command": "echo step %d" % calls}))
raise ValueError(SCENARIO)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self): # /v1/models
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"data": [{"id": "fake", "object": "model"}]}).encode())
def do_POST(self):
global calls
calls += 1
request = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
if SCENARIO == "silent":
time.sleep(3600)
return
if not request.get("stream"): # mm's retry without streaming
self.answer_once()
return
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
if SCENARIO == "runaway":
for event in tool_call("bash", "")[:1]:
self.wfile.write(event.encode())
for _ in range(200): # "abcd" forever, until mm stops reading
try:
self.wfile.write(chunk({"tool_calls": [{"index": 0, "function": {"arguments": "abcdefgh"}}]}).encode())
self.wfile.flush()
except BrokenPipeError:
return
time.sleep(0.01)
return
for event in reply():
self.wfile.write(event.encode())
self.wfile.write(b"data: [DONE]\n\n")
def answer_once(self):
"""The same scenario as one JSON completion (stream: false)."""
message, finish = {"role": "assistant", "content": ""}, "stop"
for event in reply():
delta = json.loads(event[len("data: "):])["choices"][0]["delta"]
message["content"] += delta.get("content") or ""
for call in delta.get("tool_calls") or []:
if "id" in call:
message["tool_calls"] = [call]
finish = "tool_calls"
else:
message["tool_calls"][0]["function"]["arguments"] += call["function"]["arguments"]
body = {"id": "fake", "object": "chat.completion", "created": 0, "model": "fake",
"choices": [{"index": 0, "message": message, "finish_reason": finish}]}
data = json.dumps(body).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
print("fake LLM (%s) on http://127.0.0.1:%d/v1" % (SCENARIO, PORT), flush=True)
ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
|