How it is recognised
By navigator.userAgent, checked before the browser test. A Worker has neither process nor window.document, so neither of the other two checks would find it.
The session is not persistent
capabilities.persistentStorage is false. A cold isolate exchanges the key again — one extra round trip, not an error. On a busy Worker the isolate is reused and the exchange does not repeat.
export default {
async fetch(request, env) {
const api = new IaGenify({
apiKey: env.IAGENIFY_API_KEY,
baseUrl: "https://api.iagenify.com",
});
const assistant = await api.models.create({ model: "gemini-3.5-flash", memory: false });
const result = await assistant.generate({
inputs: [{ type: "text", content: await request.text() }],
});
return new Response(result.outputs[0].content);
},
};# A Python web handler (FastAPI) doing what the Worker does
import os
from fastapi import FastAPI, Request
from fastapi.concurrency import run_in_threadpool
from iagenify import IaGenify
app = FastAPI()
api = IaGenify(api_key=os.environ["IAGENIFY_API_KEY"], base_url="https://api.iagenify.com")
@app.post("/")
async def answer(request: Request):
prompt = (await request.body()).decode()
def generate():
assistant = api.models.create(model="gemini-3.5-flash", memory=False)
return assistant.generate(inputs=[{"type": "text", "content": prompt}])
result = await run_in_threadpool(generate) # the SDK is synchronous
return result["outputs"][0]["content"]Giving it somewhere to persist
Pass your own storage: three async methods, read, write and clear. Backed by a KV namespace, the session survives isolate recycling and the key is exchanged once rather than once per cold start.
const sessionStore = (kv) => ({
storageType: "memory",
async read() { return JSON.parse((await kv.get("iagenify")) || "null"); },
async write(data) { await kv.put("iagenify", JSON.stringify(data)); },
async clear() { await kv.delete("iagenify"); },
});
const api = new IaGenify({
apiKey: env.IAGENIFY_API_KEY,
baseUrl: "https://api.iagenify.com",
storage: sessionStore(env.SESSIONS),
});import json
class SessionStore:
"""Any object with read(), write(data) and clear() keeps the session."""
def __init__(self, kv): self.kv = kv
def read(self): return json.loads(self.kv.get("iagenify") or "null")
def write(self, data): self.kv.set("iagenify", json.dumps(data))
def clear(self): self.kv.delete("iagenify")
api = IaGenify(
api_key=os.environ["IAGENIFY_API_KEY"],
base_url="https://api.iagenify.com",
storage=SessionStore(sessions),
)A shared store with two different keys means two identities writing over each other. Key the entry by tenant if a single Worker serves several.
Finishing what you started
A response can return before a call finishes, and the isolate may be torn down with it. Hold the Worker open for work that must complete.
export default {
async fetch(request, env, ctx) {
const api = new IaGenify({ apiKey: env.IAGENIFY_API_KEY, baseUrl: API });
// Answer now, finish the write afterwards
ctx.waitUntil(
api.memory.save({ name: "last-seen", content: new Date().toISOString() }),
);
return new Response("ok");
},
};# FastAPI: answer now, finish the write afterwards
from datetime import datetime, timezone
from fastapi import BackgroundTasks
@app.get("/")
def seen(background: BackgroundTasks):
background.add_task(api.memory.save, name="last-seen", content=datetime.now(timezone.utc).isoformat())
return "ok"Streaming through a Worker
Text deltas arrive as they are produced, so a Worker can forward them instead of waiting for the whole answer.
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();
const encode = new TextEncoder();
api.models.turn({
model: "gemini-3.5-flash",
messages: [{ role: "user", content: prompt }],
onText: (delta) => writer.write(encode.encode(delta)),
}).finally(() => writer.close());
return new Response(readable, { headers: { "content-type": "text/plain; charset=utf-8" } });# FastAPI: stream the model's text to the browser as it arrives
import queue, threading
from fastapi.responses import StreamingResponse
@app.get("/stream")
def stream(prompt: str):
chunks = queue.Queue()
def run():
try:
api.models.turn(
model="gemini-3.5-flash",
messages=[{"role": "user", "content": prompt}],
on_text=chunks.put,
)
finally:
chunks.put(None)
threading.Thread(target=run, daemon=True).start()
return StreamingResponse(iter(chunks.get, None), media_type="text/plain; charset=utf-8")What is not here
- No filesystem —
storage.filesthrows. - No terminals.
- No
bash, unless you supplyshell. - An agent needs a
filesbridge, exactly as in a browser. - Mind the CPU limit: an agent run is many turns, and nearly all of that time is spent waiting on the network rather than on CPU.