Hey folks, we're having a weird issue that may or may not be a direct result of the way we're trying

Hey folks, we're having a weird issue that may or may not be a direct result of the way we're trying to leverage the AI binding in our worker.

We're using the application context to inject the various instances of Cloudflare bindings (we've done this for KV, R2 and multiple other services and now trying for AI).

import { useContext } from '@fc/core/context';

/**
 * Injects the Ai instance into the application context.
 */
export const withAI = (ai: Ai) => {
  const context = useContext();
  if (!context) {
    throw new Error('Context not found: ensure the AI binding is attached.');
  }
  context.dependencies.set('ai', ai);
};

/**
 * Retrieves the Ai instance from the context.
 * Throws an error if Ai is not found.
 */
export const useAI = (): Ai => {
  const context = useContext();
  if (!context) {
    throw new Error('Context not found: useAI must be called within a Cloudflare Worker.');
  }
  const ai = context.dependencies.get('ai') as Ai;
  if (!ai) {
    throw new Error('AI instance not found in context. Ensure `withAI` is used.');
  }
  return ai;
};


We setup a withAI and useAI method that allows us to inject the binding instance into our workers from a core package.

We would then do something along the lines of:

 await withContext(requestId, async () => {
    const env = envSchema.parse(_env);

    // AI
    withAI(_env.AI);


Where the Env interface was generated by wrangler types.

Our _env.AI in this case is of abstract class Ai as defined in the workers-type pacakge.

But, when we try to do something similar to in a service:

const cloudflareJobOutput = (await ai.run('@cf/openai/whisper', modelInput)) as WhisperResponse;


we catch an error which is hard to debug

 undefined: undefined
Was this page helpful?