agenthub/backend/tests/nanobot_real_stub.py

101 lines
2.8 KiB
Python

"""Serve the REAL nanobot HTTP API with a stubbed agent loop.
Interop harness: nanobot code is imported from a real install, so every
wire-level rule (single user message, model matching, bearer auth, SSE framing)
is enforced by upstream code instead of by our test double in
tests/fake_nanobot.py. Only the agent loop - the part that would call an LLM -
is faked here.
Run it with a nanobot interpreter:
.nanobot-venv/bin/python backend/tests/nanobot_real_stub.py --port 0
Once the socket is open it prints one line on stdout:
AGENTHUB_STUB {"base_url": "http://127.0.0.1:8900/v1", "model": "...", "api_key": "..."}
"""
from __future__ import annotations
import argparse
import asyncio
import json
import signal
from aiohttp import web
from nanobot.api.server import create_app
MARKER = "AGENTHUB_STUB "
class StubLoop:
"""Stand-in for nanobot.agent.loop.AgentLoop.
Implements only what nanobot.api.server calls. The reply echoes the
session key and prompt size, so a test can assert what the real server
parsed and handed down.
"""
async def process_direct(
self,
*,
content: str,
media=None,
session_key: str = "",
channel: str = "",
chat_id: str = "",
on_stream=None,
on_stream_end=None,
hooks=None,
):
if on_stream is not None:
for token in ("real-nanobot ", session_key or "anonymous", " streamed"):
await on_stream(token)
reply = "real-nanobot session=" + session_key + " chars=" + str(len(content))
return _Reply(reply)
class _Reply:
"""nanobot normalises anything with a .content attribute."""
def __init__(self, content: str) -> None:
self.content = content
async def serve(port: int, api_key: str, model: str) -> None:
app = create_app(agent_loop=StubLoop(), model_name=model, api_key=api_key)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "127.0.0.1", port)
await site.start()
bound = list(runner.addresses)[0][1]
print(
MARKER
+ json.dumps({
"base_url": "http://127.0.0.1:" + str(bound) + "/v1",
"model": model,
"api_key": api_key,
}),
flush=True,
)
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, stop.set)
await stop.wait()
await runner.cleanup()
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", type=int, default=0)
parser.add_argument("--api-key", default="")
parser.add_argument("--model", default="real-nanobot-model")
args = parser.parse_args()
asyncio.run(serve(args.port, args.api_key, args.model))
if __name__ == "__main__":
main()