Serverless AI with Dart

server_less_dart_ai

Cloud Functions, LangChain, & Dartantic

Bringing Full-Stack Power to Flutter Developers


🌟 The Game Changer for Flutter Devs

Why Dart in Cloud Functions?

  • Unified Language: Write frontend, backend, and AI logic entirely in Dart. No context switching to TypeScript or Python.
  • Shared Models: Share your exact data models (e.g., AiResponse, IncrementResponse) directly between your Flutter app and Firebase backend.
  • Enhanced Security: Keep your GEMINI_API_KEY and other sensitive logic on the server. Never ship API keys in your client app.
  • Type Safety: End-to-end type safety from the database to the UI.

πŸ› οΈ Step 1: The Basics

Master the Official Codelab

Before diving into AI integrations, you must understand the foundation.

πŸ‘‰ Deploy Dart on Firebase Functions

Please complete the official Google tutorial first. It covers:

  • Setting up the Dart server environment.
  • Using package:firebase_functions.
  • Deploying the initial HTTP endpoints.

🧠 The Dart AI Ecosystem

Once your Cloud Functions environment is ready, it’s time to add intelligence. We use two dominant frameworks:

  1. LangChain Dart: The heavyweight, standard pipeline adapter.
  2. Dartantic AI: The fast, typed, agent-first framework.

Let’s explore what they are and how we implemented them.


πŸ¦œπŸ”— What is LangChain Dart?

  • The Standard: A Dart port of the popular LangChain ecosystem.
  • Pipelines: Heavily focused on declarative chains (Prompt -> LLM -> Parser).
  • Versatility: Supports numerous LLM providers (Google Gemini, OpenAI, Anthropic, etc.).
  • Best For: Complex multi-step pipelines (RAG, extensive document querying).

🎯 What is Dartantic AI?

  • Agent-First: Built from the ground up for autonomous agents.
  • Native Types: Designed to map LLM outputs directly into strictly typed Dart classes.
  • Tool Calling: Seamless integration of Dart functions that the LLM can trigger autonomously.
  • Best For: Fast integrations, structured outputs, and complex tool-calling scenarios.

πŸ—οΈ What We Built: The Architecture

Our Serverless server.dart Example

In this project, we created a single, powerful Cloud Functions backend that:

  1. Initializes Firebase & dotenv: Loads the GEMINI_API_KEY securely from .env.
  2. Exposes HTTP Callable Endpoints:
    • incrementCallable: Standard database operations (Firestore).
    • dartanticCallable: AI endpoint powered by Dartantic.
    • langchainCallable: AI endpoint powered by LangChain.
  3. Uses Shared Packages: Both the Flutter client and Dart server use the exact same AiResponse model for flawless communication.

πŸ’» Inside: The Dartantic Endpoint

firebase.https.onRequest(name: dartanticCallable, (request) async {
  final promptText = request.url.queryParameters['prompt'];
  
  // 1. Initialize the Agent with Gemini
  final agent = Agent.forProvider(GoogleProvider(apiKey: geminiApiKey));
  
  // 2. Send the prompt
  final dartanticResult = await agent.send(promptText);

  // 3. Return a strongly-typed shared response
  final aiResponse = AiResponse(
    success: true,
    result: dartanticResult.output,
    framework: 'dartantic_ai',
  );
  
  return Response(200, body: jsonEncode(aiResponse.toJson()));
});

πŸ’» Inside: The LangChain Endpoint

firebase.https.onRequest(name: langchainCallable, (request) async {
  final promptText = request.url.queryParameters['prompt'];
  
  // 1. Initialize the LLM
  final llm = ChatGoogleGenerativeAI(
    apiKey: geminiApiKey,
    defaultOptions: const ChatGoogleGenerativeAIOptions(model: 'gemini-2.5-flash'),
  );
  
  // 2. Invoke the model
  final langchainResult = await llm.invoke(PromptValue.string(promptText));

  // 3. Return the exact same response shape
  final aiResponse = AiResponse(
    success: true,
    result: langchainResult.output.content,
    framework: 'langchain_dart',
  );
  
  return Response(200, body: jsonEncode(aiResponse.toJson()));
});

πŸš€ The Future is Here

One Language. One Codebase. Infinite Possibilities.

By combining Flutter, Firebase Cloud Functions for Dart, and frameworks like LangChain & Dartantic, you now have the power to build production-grade, secure, and highly intelligent AI apps without ever leaving the Dart ecosystem.


πŸ“± The Flutter Frontend

Connecting to our Cloud Functions is extremely simple on the client side using the standard http package or Firebase SDK.

// Fetching from Dartantic Cloud Function
final uri = Uri.parse('https://<YOUR-REGION>-<YOUR-PROJECT>.cloudfunctions.net/dartanticCallable');
final response = await http.get(uri.replace(queryParameters: {
  'prompt': 'Tell me a joke about Dart'
}));

// We decode using the SAME shared model!
final aiResponse = AiResponse.fromJson(jsonDecode(response.body));
print(aiResponse.result);

🎨 Output in Action (1/2)

Here is a glimpse of how this looks when integrated into a Flutter application.

Flutter UI Output 1


🎨 Output in Action (2/2)

And here is another example of the seamless AI integration.

Flutter UI Output 2


Discover more from prepNew

Subscribe to get the latest posts sent to your email.

Leave a Comment

Scroll to Top