Skip to main content

flutter_ai_operator 0.1.1 copy "flutter_ai_operator: ^0.1.1" to clipboard
flutter_ai_operator: ^0.1.1 copied to clipboard

discontinuedreplaced by: flutter_app_copilot

Build in-app AI agents in Flutter with one chat API for Gemini, OpenAI, and Claude - function calling, typed errors, and optional GoRouter navigation context.

Flutter AI Operator #

This package lets your app's users prompt AI so it can execute actions and operations inside your app, such as:

  • "Turn on dark mode" → change an app setting.
  • "Change my name to Maya" → update a profile.
  • "Take me to my orders" → navigate to a screen.

You define the actions your app exposes. The package connects to Gemini, OpenAI, or Claude, runs model-requested actions through your handler, and returns the model's final reply. Your app keeps control of its business rules, data, and UI.

Features #

Feature What it provides
One provider interface Use AIService with Gemini, OpenAI, or Claude.
Function calling Connect model requests to your existing app logic.
Typed failures Distinguish invalid input, request errors, and unusable replies.
Optional navigation context Describe the current GoRouter stack and available routes.

How it works #

  1. Your app sends a message through AIService.send().
  2. The model requests a function, such as add_numbers, with JSON arguments.
  3. Your AiActionHandler validates the arguments and calls the matching action.
  4. The package sends the action's result back to the model.
  5. This repeats until the model returns its final text reply, with a limit of 12 tool rounds per request.

Installation #

Requires Flutter with Dart >=3.13.7 <4.0.0. Dependencies may impose additional platform requirements.

flutter pub add flutter_ai_operator

For a local copy, use a path: dependency instead. Import the public API:

import 'package:flutter_ai_operator/flutter_ai_operator.dart';

Quick start #

Your integration has three pieces:

Piece Your responsibility
FunctionDefinition Describe each tool's name, purpose, and expected arguments.
AiExecutableAction Implement the operation using your app's logic.
AiActionHandler Match the function name, parse its arguments, and execute the action.

The complete calculator example defines functionDefinitionList, AddNumbersAction, and CalculatorActionHandler. After defining those pieces in your app, connect and call them like this:

final ai = AIServiceFactory.create(
  provider: AIProvider.openAI,
  apiKey: apiKey,
  modelName: modelName,
  configuration: AIConfiguration(
    systemPrompt: 'Use add_numbers for addition. Reply with the result.',
    functionDefinitions: functionDefinitionList,
  ),
  actionHandler: CalculatorActionHandler([AddNumbersAction()]),
);

final messages = [ChatMessage.user('What is 12 plus 30?')];
final reply = await ai.send(messages);
messages.add(ChatMessage.model(reply));

Supply your provider's API key and a model ID available to your account. For Gemini, complete the Firebase setup below before creating the service. See the example guide for the flow and customization notes.

Implementing actions #

Actions receive a typed input and return Either<Failure, Output>:

class AddNumbersAction implements AiExecutableAction<AddNumbersInput, num, Error> {
  @override
  Future<Either<Error, num>> execute(AddNumbersInput input) async =>
      Right(input.numbers.fold<num>(0, (sum, number) => sum + number));
}

AddNumbersInput is defined by the example, not the package. Its fromJson method parses the actual values in response.functionArgs into a typed input. FunctionDefinition describes the schema the model uses to produce those values.

In your handler, match the function name and select the registered action, then:

final input = AddNumbersInput.fromJson(response.functionArgs);
if (input.isLeft) {
  return Left(input.left);
}

final result = await action.execute(input.right);
return result.map((sum) => sum.toString());

Return Right(result) on success or Left(error) for expected action failures. The package sends either result back to the model so it can continue or explain what went wrong. Adding an action to actions alone does not register its function definition or dispatch its calls; implement both explicitly.

Providers #

Provider Factory value Setup
OpenAI AIProvider.openAI Supply a non-empty API key.
Claude AIProvider.claude Supply a non-empty API key.
Gemini AIProvider.gemini Complete Firebase setup below; omit apiKey.

modelName is optional. Omitting it or passing a blank value uses the provider's packaged default, available through AIProvider.defaultModelName. To switch providers, change the factory value and supply the matching credentials and model ID. All providers ship together, so Firebase remains a dependency even when using OpenAI or Claude.

Set up Gemini (Firebase) #

Complete these steps before creating the Gemini service:

  1. Initialize Firebase in your Flutter app.
  2. Enable Firebase AI Logic.
  3. Configure Firebase App Check.
  4. For local development, configure the App Check debug provider.

Add go_router as a direct dependency and import it alongside this package:

import 'package:go_router/go_router.dart';

final reply = await ai.send(messages, appContext: router.getRouterContext());

The exported GoRouterStateContext extension provides currentStack(), routeTree(), and getRouterContext(). This supplies route information as text; your app still implements any navigation action exposed to the model. You can also pass your own context string without GoRouter. Context is appended only to the outgoing copy of the final user message.

Handling failures #

Catch AIProviderFailure at your application's logic boundary and convert it into a failure result or presentation state:

Future<Either<AIProviderFailure, String>> sendSafely(
  AIService ai,
  List<ChatMessage> messages,
) async {
  try {
    return Right(await ai.send(messages));
  } on AIProviderFailure catch (failure) {
    return Left(failure);
  }
}
Failure Meaning
AIProviderInvalidInputFailure Empty conversation, blank user text, or an assistant message at the end.
AIProviderRequestFailure A network or provider request failed.
AIProviderTooManyCallsFailure The model reached the tool-round limit.
AIProviderMalformedToolCallFailure A tool call had missing or unreadable fields.
AIProviderEmptyResponseFailure The model returned no usable text.
AIProviderInvalidResponseFailure The provider response had an unexpected shape.

Failures expose code, a stable reason, and an optional diagnostic message. Branch on the failure type or stable fields rather than its human-readable text. Validate setup separately: missing OpenAI/Claude keys throw StateError during creation. Firebase setup errors and errors thrown by your own action handler also need handling at your app boundary.

Responsibilities and scope #

The package owns Your app owns
Provider requests and response parsing Provider selection, credentials, and Firebase setup
Tool-call continuation and provider failures Function definitions, argument validation, and actions
Chat models and route-context formatting Conversation state, storage, and UI

The API returns complete text replies. Streaming, request cancellation, conversation persistence, offline replies, and cache fallback are not included. Import supported types from flutter_ai_operator.dart; lib/src/ contains implementation details.

License #

MIT. Copyright © 2026 Yousef Shams.

0
likes
140
points
0
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Build in-app AI agents in Flutter with one chat API for Gemini, OpenAI, and Claude - function calling, typed errors, and optional GoRouter navigation context.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

dio, either_dart, firebase_ai, firebase_core, flutter, go_router

More

Packages that depend on flutter_ai_operator