Files
splinter/tests/fake_openai_tool.py

38 lines
1.4 KiB
Python

# fake OpenAI endpoint: the first request of a turn asks for the `run` tool,
# the next one answers with what the tool returned ("obs: ...").
# argv: port, file the command would create.
import http.server, json, sys
def ev(d):
return ("data: " + json.dumps(d) + "\n\n").encode()
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_POST(self):
n = int(self.headers.get("Content-Length", 0))
req = json.loads(self.rfile.read(n))
last = req["messages"][-1]
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
w = self.wfile.write
if last["role"] == "user" and "pointers" in str(last.get("content")):
w(ev({"choices": [{"delta": {"content":
"void *ctx, const char *name -- **bold** and *it*"}}]}))
elif last["role"] == "tool":
w(ev({"choices": [{"delta": {"content":
"obs: " + str(last.get("content", ""))[:300]}}]}))
else:
w(ev({"choices": [{"delta": {"tool_calls": [{"index": 0,
"id": "c1", "type": "function", "function": {
"name": "run", "arguments": json.dumps(
{"command": "touch " + sys.argv[2]})}}]}}]}))
w(b"data: [DONE]\n\n")
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()