Dev.to AI 🤖 Ai 👁 0 📖 4 min read

Local Means Local: Test Firebase AI Logic Fallback Before Dispatch

A button labeled “Run on this device” makes a concrete promise about where its input will be processed. A configuration named PREFER_ON_DEVICE makes a materially different promise: try the local model, then permit cloud

Local Means Local: Test Firebase AI Logic Fallback Before Dispatch

A button labeled “Run on this device” makes a concrete promise about where its input will be processed. A configuration named PREFER_ON_DEVICE makes a materially different promise: try the local model, then permit cloud inference when needed.

Both behaviors can be useful. The application needs to choose deliberately and describe the consequence before dispatching the request.

Firebase AI Logic exposes explicit inference modes for this choice. This walkthrough adds a small TypeScript policy in front of the SDK, verifies that disallowed requests never reach the provider adapter, and records the actual inference source when a live request succeeds. The key rule is simple: permission must constrain dispatch, not merely explain the response afterward.

Choose a mode that matches the interaction

The documented modes have different fallback behavior:

Mode Preference If that route is unavailable
ONLY_ON_DEVICE Local inference Error
PREFER_ON_DEVICE Local inference Cloud fallback
ONLY_IN_CLOUD Cloud inference Error
PREFER_IN_CLOUD Cloud inference Local fallback

An availability probe can improve the explanation, but it cannot substitute for a policy. Availability can change between the probe and execution. Use the mode itself to constrain the SDK’s permitted route.

Also keep the supported operation narrow. The current hybrid documentation distinguishes single-turn local generation from capabilities such as multi-turn chat and tool use. A feature supported by the cloud model does not automatically become a local capability.

Bind permission to the text being sent

The example offers local-only, local-preferred, and cloud-only choices. A cloud-capable choice requires an explicit grant for the current input. Changing that input invalidates the grant.

type Consent = { input: string; expiresAt: number };

function chooseMode(
  choice: "local-only" | "local-preferred" | "cloud-only",
  input: string,
  consent: Consent | undefined,
  now: number
) {
  if (choice === "local-only") return "ONLY_ON_DEVICE";
  if (!consent || consent.input !== input || consent.expiresAt <= now) {
    throw new Error("Cloud permission is missing or no longer valid.");
  }
  return choice === "cloud-only"
    ? "ONLY_IN_CLOUD"
    : "PREFER_ON_DEVICE";
}

This in-memory grant is an application UX rule. It is not server authorization, a legal consent record, or protection against compromised page JavaScript. A production product might bind the decision to additional context, such as the destination, attachments, and purpose.

The important implementation detail is ordering: validate the policy before constructing a provider request. Discovering the inference source after the response is too late to ask whether the input may leave the device.

A requested inference mode passes through a permission decision before reaching a local-only or cloud-capable SDK route.

Figure 1. Permission constrains dispatch. The returned inference source explains what happened afterward.

Keep the SDK adapter small

The companion pins Firebase 13.3.0 and typechecks this adapter against the installed declarations:

const ai = getAI(app, { backend: new GoogleAIBackend() });
const model = getGenerativeModel(ai, {
  mode: InferenceMode[mode],
  inCloudParams: { model: cloudModel },
});
const result = await model.generateContent(input);
return {
  text: result.response.text(),
  source: result.response.inferenceSource,
};

The imports come from firebase/ai; the complete module is supplied with the lab. Pass an explicitly selected cloud model rather than depending indefinitely on the SDK’s default. Keep an unreported source visibly unknown instead of inferring it from response speed.

There is deliberately no catch block that retries a failed local-only request using a cloud model. If the person chooses local-only and local inference fails, keep the source text and explain the failure. A subsequent cloud request is a separate user decision.

Verify the policy without provider credentials

The policy accepts an injected provider function. That lets the tests count dispatches without sending any text anywhere.

The executed tests establish that missing permission, expired permission, and permission for different text all block a cloud-capable request before the mock provider runs. A local-only provider failure propagates without a second call. A valid grant selects the intended SDK mode.

These results verify the application policy. They do not establish which route Firebase selects on a particular device or whether a generated answer is useful.

The visible policy panel is labeled as a fixture. Its “Mock provider calls” counter must not be presented as evidence of a live Firebase request. The real adapter remains available for the connected experiment.

Complete the live setup deliberately

Create or select a Firebase project, enable AI Logic, choose a provider, and configure App Check. Use its debug provider for local development and an appropriate production provider before deployment. Follow the current browser instructions for local inference, including model preparation and any required flags.

Keep Firebase configuration separate from server secrets. A Firebase web configuration is not a reason to place a Gemini provider secret in frontend code. Follow the selected Firebase provider’s credential setup rather than adapting a server-only Gemini example by exposing its key.

For the live matrix, record the requested mode, permission state, supported input type, actual source, success or error, and relevant request evidence. Run local-unavailable/cloud-allowed, local-unavailable/cloud-declined, local-ready, and disconnected cases. A cloud failure with no usable local model is a legitimate outcome.

Describe the boundary precisely

The phrase “on-device” can describe model inference without describing every request made by the application. Authentication, analytics, configuration, and model downloads have their own network behavior. Inspect them separately before making a whole-application privacy claim.

Likewise, a fixture test is valuable because it isolates the policy, but it cannot certify SDK fallback. This draft’s live Firebase matrix requires project credentials and browser execution; no provider routing or latency results are claimed.

A good fallback preserves a useful interaction while respecting the choice the person made. What should your application do when its preferred model is unavailable and the alternative changes where the input is processed?

References

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.