Repository navigation
feat(serve): add agent.serve() for instant REST API endpoints - #1076
Conversation
AmitoVrito
left a comment
There was a problem hiding this comment.
Hey @ramashishmaurya, thanks for this — agent.serve() is a genuinely useful addition and the core shape is right. A few blockers before it can go in, plus some design and scope cleanups.
Blockers
1. Branch is way behind main (~40 commits). GitHub can't compute a clean merge and the diff is full of phantom changes from the stale base. Please rebase onto latest main first so we can review the real delta.
2. sys.exit(1) in library code. In serve_agent, a missing fastapi/uvicorn hard-exits the host process:
except ImportError:
logger.error(...)
sys.exit(1)A library must never kill the caller's process. Raise ImportError (with the same install hint) and let the caller handle it.
3. Default host="0.0.0.0". This binds the agent — along with its tools and whatever keys/prompts flow through it — to every network interface by default. Please default to 127.0.0.1 and make 0.0.0.0 an explicit opt-in.
4. Tests use mocks. tests/test_serve.py uses unittest.mock.patch, @patch("uvicorn.run"), and a MockAgent — all banned by our testing standards (no Mock/MagicMock/mocker.patch anywhere; use real impls or hand-written fakes). It also never actually exercises the endpoint — it only asserts uvicorn.run was called. Please rewrite with a hand-written FakeAgent and a FastAPI TestClient that POSTs to /chat and asserts the SSE and JSON bodies.
Design / should-fix
5. Import-time monkey-patching of agent classes. patch_agents() runs on import synapsekit and assigns ReActAgent.serve = ... for three agents. This forces eager import of all three agent modules on every import synapsekit (defeating the _LAZY_IMPORTS mechanism the same diff adds an entry to — the eager top-level from .serve import ... also makes that lazy entry dead), and .serve() is invisible to type checkers/IDEs. Prefer a public serve(agent, ...) function, or a real method on the agent base class.
6. Sync blocking .serve() on an async-first framework. It won't trip the async-blocking gate (that only scans inside async def), but a blocking public method cuts against our async-first principle. At minimum document it; ideally offer an async entrypoint.
7. SSE assumes .stream() yields JSON-serializable strings. True for ReActAgent, but the generic hasattr(agent, "stream") path will json.dumps({"token": chunk}) on whatever any agent yields — a structured-event stream turns every token into an error frame. Worth guarding/documenting the contract.
8. except Exception returns HTTP 200 with {"error": ...} on the run() fallback — that should be a real 500.
9. Scope creep. The PR also carries unrelated ruff autofixes across benchmarks/, examples/, and scripts/. A few are sloppy — examples/reasoning_models.py and benchmarks/cag_vs_rag_bench.py leave bare os.environ.get(...) / KVCacheStore(...) dead expression statements, and edge_local_vs_cloud_bench.py drops a # noqa: BLE001 along with its rationale comment. Please split these into a separate PR — one concern per PR.
Nits
print()+ emoji startup banner instead oflogger.- New feature should publish
serve.*events to the EventBus so SynapseKit Live sees it. test_patch_agents's comment is confusing.- Docs page + CHANGELOG can come at merge time, no action needed now.
The headline asks: rebase, replace sys.exit with a raised error, default host to localhost, rewrite the tests to the no-mock standard with a real endpoint test, and split out the lint churn. Happy to help once the rebase is done.
…#1076) serve_agent(agent) and a native agent.serve(port=8000) expose any agent as a FastAPI POST /chat endpoint — SSE streaming when the agent implements stream(), plain-JSON {"response": ...} otherwise. build_agent_app() is exposed separately for mounting/testing. FastAPI and uvicorn stay in the serve extra and import lazily, so a core install is unaffected. Integration hardening over the original PR: - native ServeMixin inherited by ReActAgent/FunctionCallingAgent/ReasoningAgent instead of an import-time monkeypatch that eagerly imported the agent modules and swallowed failures silently; - raise ImportError with the extras hint instead of sys.exit() in library code; - bind 127.0.0.1 by default (was 0.0.0.0); - return generic errors and log the real exception server-side instead of leaking exception strings to HTTP clients; - coerce non-str stream chunks so a custom agent can't truncate the stream; - real fastapi.testclient.TestClient tests (no mocks), 100% module coverage. Co-authored-by: Ashish Maurya <[email protected]> Co-authored-by: Dhruv Garg <[email protected]>
213abdc to
0758a5e
Compare
Overview
This PR introduces the highly requested
agent.serve()functionality, instantly transforming any terminal-based agent into a production-ready FastAPI REST endpoint.Features
agent.serve(port=8000)to their agent scripts.StreamingResponseif the agent supports the.stream()async generator method. This gives a real-time ChatGPT-like typing experience to the frontend.ReActAgent,FunctionCallingAgent,ReasoningAgent) are dynamically patched upon importingsynapsekitso the API feels native and elegant..stream()is not implemented by an agent, it seamlessly falls back to.run()and returns a standard JSON response.Why this matters
Similar to LangServe, this fundamentally lowers the barrier of entry for deploying SynapseKit agents into real-world applications (React apps, chat interfaces, mobile backends) without requiring developers to write boilerplate FastAPI and WebSocket code.
Testing
.serve()correctly initializes a FastAPI instance and invokesuvicorn.runwith proper arguments.ruffformatting and CI lint rules.