A client module
Every request needs the key, aUser-Agent, a long timeout, and handling for 202 (poll the session) and for errors whose reason the user can act on.
Python
import json, os, time, urllib.request, urllib.error
HOST = os.environ.get("FLOPROUTER_BASE_URL", "https://api.floprouter.com").rstrip("/")
KEY = os.environ["FLOPROUTER_API_KEY"]
def _call(method, path, body=None):
req = urllib.request.Request(HOST + path, method=method,
data=None if body is None else json.dumps(body).encode(),
headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json", "User-Agent": "my-app/1.0"})
try:
with urllib.request.urlopen(req, timeout=130) as r:
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw)
except ValueError:
return e.code, {"error": {"message": raw[:200].decode(errors="replace")}}
def chat(messages, model="qwen/qwen3-8b", max_tokens=256):
status, r = _call("POST", "/v1/chat/completions", {"model": model, "messages": messages, "max_tokens": max_tokens})
if status == 202: # no verified reply within the deadline: poll, do not resend
for _ in range(60):
time.sleep(5)
status, s = _call("GET", r["poll"])
if status == 200 and s.get("reply"):
return s["reply"]["content"], s
raise TimeoutError(f"session {r['id']} has no reply yet")
if status != 200:
err = r.get("error", {})
reason = (err.get("metadata") or {}).get("reason") or err.get("code")
raise RuntimeError(f"{status} {reason}: {err.get('message')}")
return r["choices"][0]["message"]["content"], r["flop"]
Reading a stream
fetch
const res = await fetch("https://api.floprouter.com/v1/chat/completions", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.FLOPROUTER_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ model: "qwen/qwen3-8b", messages: [{ role: "user", content: "Hello" }], stream: true }),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let i;
while ((i = buffer.indexOf("\n\n")) >= 0) {
const event = buffer.slice(0, i);
buffer = buffer.slice(i + 2);
for (const line of event.split("\n")) {
if (!line.startsWith("data: ")) continue; // ": FLOPROUTER PROCESSING" keep-alives
if (line === "data: [DONE]") process.exit(0);
const chunk = JSON.parse(line.slice(6));
if (chunk.error) throw new Error(chunk.error.message);
process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
}
}
}
An agent loop without tool calls
Tool calling is not supported, so ask the model for a JSON action in plain text and run it yourself.Python
SYSTEM = (
"You can use one tool: calc(expression). To use it, reply with JSON only: "
'{"tool": "calc", "expression": "..."}. When you have the answer, reply with JSON only: {"answer": "..."}.'
)
def run(question):
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
for _ in range(5):
text, _ = chat(messages, max_tokens=128)
messages.append({"role": "assistant", "content": text})
action = json.loads(text[text.index("{"): text.rindex("}") + 1])
if "answer" in action:
return action["answer"]
result = str(eval(action["expression"], {"__builtins__": {}})) # a sandboxed calculator in real code
messages.append({"role": "user", "content": f"calc result: {result}"})
max_tokens small.