Cloudflare Workers AI tracing with Future AGI
Trace env.AI.run calls from a Cloudflare Worker to Future AGI with a dependency-free recipe that sends its spans before the Response returns.
Trace Cloudflare Workers AI calls in Future AGI from inside your Worker. This is a recipe, not a package: you copy two small files into your Worker. The Worker records one span for the request and one for the env.AI.run call, and sends them to Future AGI as OTLP/JSON with fetch before it returns the Response. The files have no dependencies and need no nodejs_compat flag.
Use it when your Worker calls Workers AI through the env.AI binding. env.AI.run is a Workers binding, not an OpenAI-compatible base URL, so the OpenAI and Anthropic instrumentations do not apply. You need no collector of your own: the Future AGI keys are Worker secrets. One Worker sends to one project with one key pair, and the project comes from the Worker’s configuration, never from a request header. For a Cloudflare Agents SDK agent, see Cloudflare Agents. For requests that go through AI Gateway, see Cloudflare AI Gateway.
The example directory contains the Worker, its wrangler.toml and unit tests that run with node --test.
1. Configure the Worker
The [ai] block binds Workers AI as env.AI. FI_PROJECT_NAME names the Observe project. FI_BASE_URL and WORKERS_AI_MODEL are optional.
# Example Worker: Workers AI with Future AGI tracing.
# No account id here: wrangler takes it from your own login when you deploy.
# The tests do not read this file and do not run wrangler.
name = "workers-ai-futureagi-example"
main = "src/worker.mjs"
compatibility_date = "2026-10-01"
# No nodejs_compat: the Worker uses no Node built-ins.
[ai]
binding = "AI"
[vars]
# The project_name resource attribute. One Worker, one project.
FI_PROJECT_NAME = "cloudflare-workers-ai-example"
# Optional. Default https://api.futureagi.com
# FI_BASE_URL = "https://api.futureagi.com"
# Optional. Default @cf/meta/llama-3.1-8b-instruct (see src/worker.mjs).
# WORKERS_AI_MODEL = ""
# The two keys are secrets. Never put them in this file:
# npx wrangler secret put FI_API_KEY
# npx wrangler secret put FI_SECRET_KEY
| Setting | Where | Sent as |
|---|---|---|
FI_API_KEY | Worker secret | X-Api-Key header |
FI_SECRET_KEY | Worker secret | X-Secret-Key header |
FI_PROJECT_NAME | [vars] | resource attributes project_name and service.name |
| (fixed) | src/tracing.mjs | resource attribute project_type=observe |
FI_BASE_URL | optional [vars] | base URL. Spans go to FI_BASE_URL + /tracer/v1/traces, by default https://api.futureagi.com/tracer/v1/traces. |
WORKERS_AI_MODEL | optional [vars] | the model id passed to env.AI.run. Default @cf/meta/llama-3.1-8b-instruct. |
FI_BASE_URL must be https. Plain http is accepted only for localhost, 127.0.0.1 and [::1], for local testing. A URL with a user name or password is refused. Check the default model id against Cloudflare’s current Workers AI catalog before you deploy.
2. Add the two secrets
Keep both keys out of wrangler.toml and out of source:
npx wrangler secret put FI_API_KEY # your Future AGI API key
npx wrangler secret put FI_SECRET_KEY # your Future AGI secret key
3. Add the handler and the exporter
src/worker.mjs is the Worker. It reads a prompt from GET ?prompt=... or POST {"prompt": "..."}, calls env.AI.run(model, { prompt }), records the two spans, and awaits the export in finally. Its default export is createHandler().
// A Cloudflare Worker (ES module) that calls Workers AI through the env.AI
// binding and sends two spans to Future AGI before it returns the Response:
//
// worker.fetch the request: method and path only, never the query
// └ workers_ai.run one env.AI.run(model, input) call
//
// The export is awaited in the handler's finally, bounded at 2 s. It is not
// handed to ctx.waitUntil. A failed or slow export never changes the HTTP
// status, and missing keys mean no export, not an error.
import {
EXPORT_TIMEOUT_MS,
SpanKind,
StatusCode,
createRecorder,
errorType,
exportWithin,
exporterFromEnv,
} from "./tracing.mjs";
/** Used when env.WORKERS_AI_MODEL is not set. Check Cloudflare's model catalog before you deploy. */
export const DEFAULT_MODEL = "@cf/meta/llama-3.1-8b-instruct";
/** The Response status when env.AI.run throws. */
export const AI_ERROR_STATUS = 502;
/** The one provider key this recipe sets: gen_ai.provider.name, not gen_ai.system. */
export const PROVIDER_NAME = "cloudflare";
/**
* Usage counts the result may carry, mapped to the gen_ai.usage.* keys.
* Only positive integers the result reports are written; a missing count is
* left out, never written as 0.
*/
const USAGE_FIELDS = [
["gen_ai.usage.input_tokens", ["prompt_tokens", "input_tokens"]],
["gen_ai.usage.output_tokens", ["completion_tokens", "output_tokens"]],
["gen_ai.usage.total_tokens", ["total_tokens"]],
];
export function usageAttributes(result) {
const usage = result?.usage;
if (!usage || typeof usage !== "object") return {};
const attributes = {};
for (const [key, names] of USAGE_FIELDS) {
const value = names.map((name) => usage[name]).find((count) => Number.isInteger(count) && count > 0);
if (value !== undefined) attributes[key] = value;
}
return attributes;
}
/**
* env.AI.run(model, input) inside a workers_ai.run span under `parent`.
* gen_ai.request.model is the `model` argument as passed. The prompt and the
* response are recorded only with `captureContent: true`. A thrown error
* gets error.type (its code or class name); its message is not recorded,
* because it can repeat the prompt.
*/
export async function tracedRun(env, model, input, recorder, parent, { captureContent = false } = {}) {
const span = recorder.startSpan("workers_ai.run", {
kind: SpanKind.CLIENT,
parent,
attributes: {
"gen_ai.request.model": model,
"gen_ai.provider.name": PROVIDER_NAME,
"gen_ai.span.kind": "LLM",
},
});
if (captureContent && typeof input?.prompt === "string") span.setAttribute("input.value", input.prompt);
try {
const result = await env.AI.run(model, input);
span.setAttributes(usageAttributes(result));
if (captureContent && typeof result?.response === "string") span.setAttribute("output.value", result.response);
return result;
} catch (error) {
const type = errorType(error);
span.setAttribute("error.type", type);
span.setStatus(StatusCode.ERROR, type);
throw error;
} finally {
span.end();
}
}
function json(body, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json; charset=utf-8" },
});
}
/** GET ?prompt=... or POST {"prompt": "..."}. */
async function readPrompt(request, url) {
if (request.method === "GET") return url.searchParams.get("prompt") || undefined;
if (request.method === "POST") {
try {
const body = await request.json();
return typeof body?.prompt === "string" && body.prompt ? body.prompt : undefined;
} catch {
return undefined;
}
}
return undefined;
}
async function answer(request, url, env, recorder, root, { captureContent }) {
const prompt = await readPrompt(request, url);
if (prompt === undefined) {
return json({ error: 'send a prompt: GET ?prompt=... or POST {"prompt": "..."}' }, 400);
}
const model = typeof env?.WORKERS_AI_MODEL === "string" && env.WORKERS_AI_MODEL.trim()
? env.WORKERS_AI_MODEL.trim()
: DEFAULT_MODEL;
let result;
try {
result = await tracedRun(env, model, { prompt }, recorder, root, { captureContent });
} catch {
// The error is on the span as error.type. The client gets a fixed text.
return json({ error: "model call failed" }, AI_ERROR_STATUS);
}
return json(result);
}
function resolveExporter(exporter, env) {
try {
return (typeof exporter === "function" ? exporter(env) : exporter) ?? null;
} catch (error) {
console.warn(`[futureagi] tracing off: exporter setup failed (${errorType(error)})`);
return null;
}
}
/**
* Build the Worker's handler.
*
* - `exporter`: an object with `export(spans, { signal })`, or a function
* `(env) => exporter | null`. Default: exporterFromEnv, the fetch-based
* OTLP exporter configured from FI_API_KEY, FI_SECRET_KEY, FI_PROJECT_NAME
* and FI_BASE_URL.
* - `exportTimeoutMs`: how long the handler waits for the export (2000).
* - `captureContent`: record the prompt and response text (false).
*/
export function createHandler({
exporter = exporterFromEnv,
exportTimeoutMs = EXPORT_TIMEOUT_MS,
captureContent = false,
} = {}) {
return {
// ctx (waitUntil) is not used: the export is awaited below instead.
async fetch(request, env, ctx) {
const recorder = createRecorder();
const url = new URL(request.url);
// Method and path only. CF-Connecting-IP and other headers are not read.
const root = recorder.startSpan("worker.fetch", {
kind: SpanKind.SERVER,
attributes: {
"http.request.method": request.method,
"url.path": url.pathname,
"gen_ai.span.kind": "CHAIN",
},
});
let response;
let thrown;
try {
response = await answer(request, url, env, recorder, root, { captureContent });
return response;
} catch (error) {
thrown = error;
throw error;
} finally {
if (response) {
root.setAttribute("http.response.status_code", response.status);
if (response.status >= 500) {
root.setAttribute("error.type", String(response.status));
root.setStatus(StatusCode.ERROR, String(response.status));
}
} else {
const type = errorType(thrown);
root.setAttribute("error.type", type);
root.setStatus(StatusCode.ERROR, type);
}
root.end();
// Awaited before the Response is returned. Never throws.
await exportWithin(resolveExporter(exporter, env), recorder.finished(), exportTimeoutMs);
}
},
};
}
export default createHandler();
src/tracing.mjs is the span recorder and the exporter. It uses only what the Workers runtime provides: fetch, AbortController, crypto.getRandomValues and setTimeout.
// Future AGI tracing for a Cloudflare Worker that calls Workers AI through the
// env.AI binding. This is a recipe, not a package: it has no dependencies and
// uses no Node built-ins, only what the Workers runtime provides (fetch,
// AbortController, crypto.getRandomValues, setTimeout).
//
// Spans are recorded per request in memory and sent as one OTLP/JSON request
// with fetch. The handler awaits that request, bounded by EXPORT_TIMEOUT_MS,
// before it returns the Response. Nothing is batched or delayed.
/** Resource attribute names, and the project type of an Observe project. */
export const PROJECT_NAME = "project_name";
export const PROJECT_TYPE = "project_type";
export const PROJECT_TYPE_OBSERVE = "observe";
/** Same default and path as @traceai/fi-core's HTTP exporter. */
export const DEFAULT_FI_BASE_URL = "https://api.futureagi.com";
export const COLLECTOR_PATH = "/tracer/v1/traces";
/** How long the handler waits for the export before it answers anyway. */
export const EXPORT_TIMEOUT_MS = 2000;
/** Instrumentation scope name on the exported spans. */
export const SCOPE_NAME = "cloudflare-workers-ai-recipe";
/** OTLP span kinds and status codes (opentelemetry-proto trace.proto). */
export const SpanKind = Object.freeze({ INTERNAL: 1, SERVER: 2, CLIENT: 3 });
export const StatusCode = Object.freeze({ UNSET: 0, OK: 1, ERROR: 2 });
function randomHex(bytes) {
const buffer = new Uint8Array(bytes);
// An all-zero trace or span id is invalid in OTLP.
do {
crypto.getRandomValues(buffer);
} while (buffer.every((byte) => byte === 0));
return Array.from(buffer, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
// Date.now() in milliseconds, as the OTLP nanosecond string. In Workers the
// clock only advances across I/O, so a span that does no I/O has zero length.
function nowUnixNano() {
return String(BigInt(Date.now()) * 1000000n);
}
/** One span, kept in memory until the request's export. */
class RecordedSpan {
constructor({ name, kind, traceId, parentSpanId, attributes }) {
this.name = name;
this.kind = kind;
this.traceId = traceId;
this.spanId = randomHex(8);
this.parentSpanId = parentSpanId;
this.startTimeUnixNano = nowUnixNano();
this.endTimeUnixNano = undefined;
this.attributes = {};
this.status = { code: StatusCode.UNSET };
this.ended = false;
this.setAttributes(attributes);
}
/** undefined and null are dropped, never written as empty values. */
setAttribute(key, value) {
if (!this.ended && value !== undefined && value !== null) this.attributes[key] = value;
return this;
}
setAttributes(attributes) {
for (const [key, value] of Object.entries(attributes ?? {})) this.setAttribute(key, value);
return this;
}
setStatus(code, message) {
if (!this.ended) this.status = message ? { code, message } : { code };
return this;
}
end() {
if (!this.ended) {
this.endTimeUnixNano = nowUnixNano();
this.ended = true;
}
}
}
/**
* A per-request span recorder. Create one per fetch() call: a Worker isolate
* serves many requests, so nothing here is kept at module scope.
*/
export function createRecorder() {
const spans = [];
return {
startSpan(name, { kind = SpanKind.INTERNAL, parent, attributes } = {}) {
const span = new RecordedSpan({
name,
kind,
traceId: parent?.traceId ?? randomHex(16),
parentSpanId: parent?.spanId,
attributes,
});
spans.push(span);
return span;
},
/** The spans that have ended, in start order. */
finished() {
return spans.filter((span) => span.ended);
},
};
}
/** A provider error code, else the error's class name. Never its message. */
export function errorType(error) {
const code = error?.code;
if ((typeof code === "string" && code) || (typeof code === "number" && Number.isFinite(code))) {
return String(code);
}
const name = error?.name;
return typeof name === "string" && name ? name : "Error";
}
function anyValue(value) {
if (typeof value === "string") return { stringValue: value };
if (typeof value === "boolean") return { boolValue: value };
if (typeof value === "number") {
return Number.isInteger(value) ? { intValue: value } : { doubleValue: value };
}
return { stringValue: String(value) };
}
function keyValues(attributes) {
return Object.entries(attributes ?? {})
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => ({ key, value: anyValue(value) }));
}
function otlpSpan(span) {
return {
traceId: span.traceId,
spanId: span.spanId,
...(span.parentSpanId ? { parentSpanId: span.parentSpanId } : {}),
name: span.name,
kind: span.kind,
startTimeUnixNano: span.startTimeUnixNano,
endTimeUnixNano: span.endTimeUnixNano ?? span.startTimeUnixNano,
attributes: keyValues(span.attributes),
status: span.status.message
? { code: span.status.code, message: span.status.message }
: { code: span.status.code },
};
}
/**
* The OTLP/JSON ExportTraceServiceRequest for `spans` under one resource.
* OTLP/JSON with Content-Type application/json is what @traceai/fi-core's
* HTTP exporter sends to the same collector path.
*/
export function toOtlpJson(spans, resourceAttributes) {
return {
resourceSpans: [
{
resource: { attributes: keyValues(resourceAttributes) },
scopeSpans: [{ scope: { name: SCOPE_NAME }, spans: spans.map(otlpSpan) }],
},
],
};
}
function text(value) {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
/**
* Export settings from the Worker's env, or `{ ok: false, reason }`.
*
* - FI_API_KEY and FI_SECRET_KEY: both, or no export. One key alone is an
* incomplete pair (the same rule as @traceai/fi-core) and is not sent.
* - FI_PROJECT_NAME: the project_name resource attribute. This exporter sends
* no project header, so a missing name means no export, not a guess.
* - FI_BASE_URL: optional base origin, default https://api.futureagi.com.
* The keys go only over https (or to a loopback host for local testing).
*
* The project comes from env only, never from a request header: one Worker,
* one key pair, one project. Key values never appear in a reason.
*/
export function readFutureAgiConfig(env) {
const apiKey = text(env?.FI_API_KEY);
const secretKey = text(env?.FI_SECRET_KEY);
if (!apiKey || !secretKey) {
return {
ok: false,
reason: apiKey || secretKey
? `incomplete key pair: ${apiKey ? "FI_SECRET_KEY" : "FI_API_KEY"} is not set`
: "FI_API_KEY and FI_SECRET_KEY are not set",
};
}
const projectName = text(env?.FI_PROJECT_NAME);
if (!projectName) return { ok: false, reason: "FI_PROJECT_NAME is not set" };
let url;
try {
url = new URL(`${(text(env?.FI_BASE_URL) ?? DEFAULT_FI_BASE_URL).replace(/\/+$/, "")}${COLLECTOR_PATH}`);
} catch {
return { ok: false, reason: "FI_BASE_URL is not a valid URL" };
}
if (url.username || url.password) return { ok: false, reason: "FI_BASE_URL must not carry credentials" };
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname))) {
return { ok: false, reason: "FI_BASE_URL must be https" };
}
return {
ok: true,
url: url.toString(),
apiKey,
secretKey,
resourceAttributes: {
[PROJECT_NAME]: projectName,
[PROJECT_TYPE]: PROJECT_TYPE_OBSERVE,
"service.name": projectName,
},
};
}
/** Longest collector message copied into a warning. */
const MAX_REJECTION_MESSAGE = 200;
/**
* The OTLP partial success in a 2xx answer: `{ count, message }` when the
* collector reports partialSuccess.rejectedSpans above 0, else undefined. A
* 2xx answer can drop spans and say so only there. An empty, non-JSON or
* unreadable answer reports no rejection. rejectedSpans is an int64, so
* OTLP/JSON may write it as a string.
*/
async function rejectedSpans(response) {
let body;
try {
body = JSON.parse(await response.text());
} catch {
return undefined;
}
const partial = body?.partialSuccess;
const count = Number(partial?.rejectedSpans ?? 0);
if (!Number.isInteger(count) || count <= 0) return undefined;
const message = typeof partial.errorMessage === "string"
? partial.errorMessage.trim().slice(0, MAX_REJECTION_MESSAGE)
: "";
return { count, message };
}
/**
* An exporter that POSTs OTLP/JSON with fetch. export() rejects when the
* request fails, the collector does not answer 2xx, or a 2xx answer reports
* rejected spans; the handler catches that, so a failed export never changes
* the Response.
*
* `options.fetch` replaces the global fetch (tests). Without it the global
* fetch is looked up on each export and called as globalThis.fetch(...).
*/
export function createFetchExporter({ url, apiKey, secretKey, resourceAttributes }, options = {}) {
return {
async export(spans, { signal } = {}) {
const init = {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Api-Key": apiKey,
"X-Secret-Key": secretKey,
},
body: JSON.stringify(toOtlpJson(spans, resourceAttributes)),
// A redirect is not followed, so the keys go only to the configured host.
redirect: "manual",
...(signal ? { signal } : {}),
};
const response = options.fetch ? await options.fetch(url, init) : await globalThis.fetch(url, init);
if (!response.ok) {
try {
// The answer is not read: release it.
await response.body?.cancel();
} catch {
// Nothing to release.
}
throw new Error(`collector answered ${response.status}`);
}
const rejected = await rejectedSpans(response);
if (rejected) {
const detail = rejected.message ? `: ${rejected.message}` : "";
throw new Error(`collector rejected ${rejected.count} spans${detail}`);
}
},
};
}
const warned = new Set();
function warnOnce(message) {
if (warned.has(message)) return;
warned.add(message);
console.warn(`[futureagi] ${message}`);
}
/**
* The default exporter: built from env on each request, or null (no export,
* no throw) when the keys or the project name are missing.
*/
export function exporterFromEnv(env, options = {}) {
const config = readFutureAgiConfig(env);
if (!config.ok) {
warnOnce(`tracing off: ${config.reason}`);
return null;
}
return createFetchExporter(config, options);
}
function describe(error) {
const name = typeof error?.name === "string" ? error.name : "Error";
const message = typeof error?.message === "string" ? error.message : "";
return message ? `${name}: ${message}` : name;
}
/**
* Export `spans`, waiting at most `timeoutMs`. Never throws and never
* rejects. On timeout the request is aborted through the signal; an exporter
* that ignores the signal is simply no longer awaited.
* Returns "sent", "failed", "timeout" or "skipped".
*/
export async function exportWithin(exporter, spans, timeoutMs = EXPORT_TIMEOUT_MS) {
if (!exporter || spans.length === 0) return "skipped";
const controller = new AbortController();
let timer;
const timedOut = new Promise((resolve) => {
timer = setTimeout(() => {
controller.abort();
resolve("timeout");
}, timeoutMs);
});
const sent = (async () => exporter.export(spans, { signal: controller.signal }))().then(
() => "sent",
(error) => {
if (!controller.signal.aborted) console.warn(`[futureagi] span export failed: ${describe(error)}`);
return "failed";
},
);
try {
const outcome = await Promise.race([sent, timedOut]);
if (outcome === "timeout") {
console.warn(`[futureagi] span export not finished after ${timeoutMs} ms; not waiting`);
}
return outcome;
} finally {
clearTimeout(timer);
}
}
To wrap your own handler instead, call tracedRun(env, model, input, recorder, root) inside a worker.fetch span and keep the finally block from createHandler as it is.
4. Deploy and send a request
npx wrangler deploy
curl "https://<your-worker>.<your-subdomain>.workers.dev/ask?prompt=What%20is%20the%20capital%20of%20France%3F"
The Worker answers with the JSON result of env.AI.run. Open the project named in FI_PROJECT_NAME in Observe to see the trace.
What is captured
Each request is one trace with two spans:
| Span | Kind | Attributes |
|---|---|---|
worker.fetch | SERVER | http.request.method, url.path (the path only, no query string), http.response.status_code, gen_ai.span.kind=CHAIN. On a response with status 500 or above: error.type set to the status code and span status ERROR. |
workers_ai.run | CLIENT, child of worker.fetch | gen_ai.request.model (the model id passed to env.AI.run), gen_ai.provider.name=cloudflare, gen_ai.span.kind=LLM. Usage when the result reports it. When env.AI.run throws: error.type and span status ERROR. |
- Provider: one key,
gen_ai.provider.name=cloudflare.gen_ai.systemis not set. - Usage:
gen_ai.usage.input_tokens(fromprompt_tokensorinput_tokens),gen_ai.usage.output_tokens(fromcompletion_tokensoroutput_tokens) andgen_ai.usage.total_tokens(fromtotal_tokens), read from the result’susageobject. Only positive integers are written. A result without counts gets no usage attributes, not zeros. - Resource:
project_nameandservice.namefromFI_PROJECT_NAME, andproject_type=observe. The instrumentation scope iscloudflare-workers-ai-recipe. - Trace context: every request starts a new trace. An incoming
traceparentheader is not read. - Timing: span times come from
Date.now(). In Workers the clock advances only across I/O, so a span that does no I/O has zero length. - A request without a prompt gets
400and produces theworker.fetchspan only.
Flushing
The export runs in the handler’s finally block and is awaited before the Response is returned. All spans of the request go in one POST to /tracer/v1/traces. Nothing is batched or delayed. The wait is bounded at 2 seconds (EXPORT_TIMEOUT_MS; pass exportTimeoutMs to createHandler to change it). At the bound the request is aborted through its signal and the Worker answers anyway.
The recipe does not use ctx.waitUntil. It awaits the export, so by the time the Response returns the export has finished, failed or reached the 2-second bound. The example does not use or cover handing the export to waitUntil instead. The cost of awaiting is latency: each response waits for the export, up to 2 seconds.
Privacy
- Prompt and response text are off by default. To opt in, change the default export to
export default createHandler({ captureContent: true });. The Worker then records the prompt asinput.valueand the result’sresponsetext asoutput.valueonworkers_ai.run. worker.fetchrecords the method and path only. The query string, which carries theGETprompt, is not recorded.- The Worker reads no request headers for tracing. It does not read
CF-Connecting-IPand sets nouser.id. - When
env.AI.runthrows, the span records the error’s code or class name aserror.type, never its message, which can repeat the prompt. - The keys travel only in the
X-Api-KeyandX-Secret-Keyheaders, only overhttps(or to a loopback host), and a redirect from the collector is not followed.
How it behaves
- Missing keys: with
FI_API_KEYorFI_SECRET_KEYunset, or only one of them set, nothing is exported and nothing throws. The Worker logs a warning without any key value, once per reason per isolate, and answers as usual. A missingFI_PROJECT_NAME, or anFI_BASE_URLthat is not a validhttpsURL or carries a user name or password, has the same effect. - Export failure: a rejected
fetchor an answer outside 2xx (a redirect included) is logged as[futureagi] span export failed: ...and dropped. The HTTP status of the Worker’s response does not change. - Spans rejected in a 2xx answer: the exporter reads the body of a 2xx answer. When it is JSON with
partialSuccess.rejectedSpansabove 0 (a number or a numeric string), the export counts as failed and is logged as[futureagi] span export failed: Error: collector rejected N spans: <errorMessage>, withpartialSuccess.errorMessagecut to 200 characters, or without it when the answer has none. An empty, non-JSON or unreadable 2xx body counts as sent. The status does not change. - Export timeout: after 2 seconds the export is aborted,
[futureagi] span export not finished after 2000 ms; not waitingis logged, and the Worker answers. The status does not change. - Workers AI error: when
env.AI.runthrows, the Worker answers502with{"error": "model call failed"}. Both spans are exported before the response, with statusERROR.
Cloudflare’s native OTLP destination
Cloudflare’s OpenTelemetry export for Workers (page read 2026-10-04) sends a Worker’s traces to an OTLP endpoint. Its destination takes the endpoint and “Custom Headers (Optional) - Any authentication headers or other provider-required headers”. The Future AGI collector accepts an X-Project-Name header that sets the project when a resource has no project_name attribute. This page documents only the in-Worker recipe above and gives no setup steps for that path.
Limitations
scheduled,queueand other handlers: onlyfetchis shown.- Streaming (
env.AI.run(model, { stream: true })): the span ends whenrunresolves, before the stream is read, and usage is not read from a stream. - AI Gateway options on
env.AI.run, and other bindings.
Troubleshooting
- No traces. Look for a
[futureagi] tracing off: ...warning in the Worker logs: a key,FI_PROJECT_NAMEor a validhttpsFI_BASE_URLis missing. A[futureagi] span export failed: Error: collector answered 401warning means the keys are wrong. A[futureagi] span export failed: Error: collector rejected N spans: ...warning means the collector answered 2xx but dropped the spans; the text after the count, when present, is the collector’s reason. - The query string or client IP is on a span. The handler was changed.
worker.fetchshould carry the path only, inurl.path(the handler sets it fromurl.pathname). - Usage is missing. The model’s result has no
usageobject with positive integer counts. - Input and Output are empty. That is the default. See Privacy.
Questions & Discussion