Designing a ReAct Loop from Scratch in FastAPI or Express
Expose a framework-free ReAct loop as an HTTP API: accept a user goal, run a bounded model-and-tool cycle, return the final answer plus stop metadata.
This page is a recipe for FastAPI (Python) with an Express (TypeScript) twin for teams on Node.
Build a POST /v1/agent/runs endpoint that owns max turns, tool dispatch, and structured stop reasons. Keep tools pure, the model client swappable, and the HTTP layer free of business side effects.
Should the loop live in the web process or a worker?
Short interactive runs can live in the web process with tight timeouts. Anything that regularly exceeds ~30-60s belongs in a worker with a run status API.
How do I test the endpoint without burning tokens?
Unit-test run_react_loop with a fake model client that returns scripted tool_calls. Integration-test the HTTP schema with that fake. Reserve live-model tests for a small CI job.
Can I support multiple models per request?
Yes via a model field validated against an allowlist. Keep routing policy in your code, not in free-form client strings without checks.
How does this relate to conceptual ReAct?
This is ReAct as a control loop on an API. Thoughts may be latent in tool choice rather than verbose "Thought:" prose. See the architectures section for the pattern itself.
Do I need WebSockets?
Not for most agents. SSE or chunked HTTP streaming is enough for tokens and tool events. WebSockets help when clients push mid-run cancels or multimodal streams.
Where do plugins fit?
Register tools at app startup from a plugin registry; the loop only sees TOOLS_SPEC and DISPATCH. See the plugin architecture article in this section.
How do I cancel a run?
For in-request loops, abort when the client disconnects if your stack signals it. For workers, store a cancel flag checked each turn.
Is Express production-ready for agents?
Yes if you add the same budgets, auth, and observability you would in Python. Language is not the reliability bottleneck; missing stop conditions are.
Should I expose tool traces to end users?
Usually no raw traces. Offer user-safe progress events and keep full traces for operators with redaction.
When should I stop custom and adopt a framework?
When you need durable resume, complex joins, or you are reinventing a graph engine. Use the maintenance cheatsheet in this section.