agenthub/backend/tests/fake_nanobot.py

182 lines
6.9 KiB
Python

"""A stand-in for the real nanobot HTTP API that enforces the same rules.
Contract source: soucecode/nanobot/nanobot/api/server.py
GET /health -> {"status": "ok"}, never authenticated
GET /v1/models -> exactly one model: the only id it answers for
POST /v1/chat/completions -> 401 without the Bearer key when one is set;
400 "Only a single user message is supported"
for any other shape, because nanobot keeps the
conversation itself (keyed by session_id);
400 "Only configured model ..." on a mismatch;
SSE deltas + finish chunk + data: [DONE] when
asked to stream.
"""
from __future__ import annotations
import json
import socketserver
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
class FakeNanobot:
"""Runs in a background thread; ``base_url`` is what an agent row would hold."""
def __init__(
self,
model: str = "claude-sonnet-4.5",
api_key: str = "",
models_endpoint: bool = True,
reply: str = "nanobot here",
) -> None:
self.model = model
self.api_key = api_key
self.models_endpoint = models_endpoint
self.reply = reply
self.bodies: list[dict[str, Any]] = []
self.sessions: list[str] = []
self._server = _Server(("127.0.0.1", 0), _handler(self))
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
def __enter__(self) -> "FakeNanobot":
self._thread.start()
return self
def __exit__(self, *_exc: Any) -> None:
self._server.shutdown()
self._server.server_close()
@property
def base_url(self) -> str:
host, port = self._server.server_address[:2]
return f"http://{host}:{port}/v1"
@property
def origin(self) -> str:
"""The same server without the /v1 suffix, as an agent row often spells it."""
host, port = self._server.server_address[:2]
return f"http://{host}:{port}"
@property
def last_body(self) -> dict[str, Any]:
return self.bodies[-1]
NL = chr(10)
def _frame(payload: dict[str, Any]) -> bytes:
return ("data: " + json.dumps(payload) + NL + NL).encode()
def _text_of(content: Any) -> str:
if isinstance(content, str):
return content
if isinstance(content, list):
return " ".join(str(part.get("text", "")) for part in content if isinstance(part, dict))
return str(content)
def _shape_error(body: dict[str, Any], model: str) -> str:
"""The two rejections the real endpoint performs, with its wording."""
messages = body.get("messages")
if not isinstance(messages, list) or len(messages) != 1 or not isinstance(messages[0], dict):
return "Only a single user message is supported"
if messages[0].get("role") != "user":
return "Only a single user message is supported"
requested = body.get("model")
if requested and requested != model:
return "Only configured model " + repr(model) + " is available"
return ""
class _Server(ThreadingHTTPServer):
"""Same server, minus the reverse lookup ``HTTPServer.server_bind`` performs:
resolving a freshly bound 127.0.0.1 port costs seconds on a cold resolver."""
daemon_threads = True
def server_bind(self) -> None:
socketserver.TCPServer.server_bind(self)
self.server_name, self.server_port = self.server_address[:2]
def _handler(owner: FakeNanobot):
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_args: Any) -> None:
return None
def _json(self, status: int, payload: dict[str, Any]) -> None:
raw = json.dumps(payload).encode()
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_GET(self) -> None:
if self.path == "/health":
return self._json(200, {"status": "ok"})
if self.path == "/v1/models":
if not owner.models_endpoint:
return self._json(404, {"error": {"message": "no models endpoint"}})
return self._json(
200,
{"object": "list", "data": [{"id": owner.model, "object": "model", "owned_by": "nanobot"}]},
)
self._json(404, {"error": {"message": "not found"}})
def do_POST(self) -> None:
if self.path != "/v1/chat/completions":
return self._json(404, {"error": {"message": "not found"}})
if owner.api_key and self.headers.get("Authorization") != "Bearer " + owner.api_key:
return self._json(
401,
{"error": {"message": "Missing Authorization header. Use: Bearer <api_key>"}},
)
length = int(self.headers.get("content-length") or 0)
body = json.loads(self.rfile.read(length) or b"{}")
owner.bodies.append(body)
session = str(body.get("session_id") or "")
if session:
owner.sessions.append(session)
problem = _shape_error(body, owner.model)
if problem:
return self._json(400, {"error": {"message": problem}})
answer = owner.reply + " :: " + _text_of(body["messages"][0]["content"])[:48]
if session:
answer += " :: " + session
if body.get("stream"):
return self._sse(answer)
self._json(
200,
{
"id": "chatcmpl-fake",
"object": "chat.completion",
"model": owner.model,
"choices": [
{"index": 0, "message": {"role": "assistant", "content": answer}, "finish_reason": "stop"}
],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
},
)
def _sse(self, answer: str) -> None:
self.send_response(200)
self.send_header("content-type", "text/event-stream")
self.close_connection = True
self.end_headers()
for start in range(0, len(answer), 12):
piece = answer[start : start + 12]
chunk = {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": piece}}]}
self.wfile.write(_frame(chunk))
self.wfile.flush()
end = {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}
self.wfile.write(_frame(end) + b"data: [DONE]" + NL.encode() * 2)
self.wfile.flush()
return Handler