tuul_ai 0.0.2 copy "tuul_ai: ^0.0.2" to clipboard
tuul_ai: ^0.0.2 copied to clipboard

A Flutter plugin for integrating applications with the Tuul AI platform, providing access to Gen, LiteGen, and History services through a unified SDK.

tuul_ai: Flutter Plugin for Tuul AI Integration #

tuul_ai is a powerful Flutter plugin that provides seamless integration with Tuul AI services, enabling your applications to leverage advanced AI capabilities for content generation, real-time streaming, and conversation history management,.

Features #

The tuul_ai plugin offers comprehensive functionality tailored for building sophisticated AI-powered applications in Flutter:

  • AI Content Generation: Interact with the specialized Gen and LiteGen services for diverse content generation needs,.
  • Non-Streaming: Obtain immediate, complete responses for single-turn generation requests,.
  • Streaming (Callbacks): Provides tokens as they are generated, which is ideal for real-time UI updates,.
  • Streaming (Stream API): Offers a functional approach for processing generated content as a standard Dart stream,.
  • Conversation History: Use the dedicated History service to manage and retrieve conversation history and individual messages,.
  • Intuitive API: Features a simple and intuitive API designed specifically for Flutter developers,.
  • Robust Error Handling: Ensures better control and management over API errors through the use of TuulException,.

Getting Started #

This section guides you through installation and initial setup. For general assistance with Flutter development, please view the [online documentation],.

Installation #

Add tuul_ai to your project's pubspec.yaml file under dependencies:

dependencies:
  tuul_ai: ^latest_version # Use the latest version

After updating the file, run flutter pub get to install the package,.

Usage #

First, import the necessary components, including the core library and associated models and exceptions,,,:

import 'package:tuul_ai/tuul_ai.dart';
import 'package:tuul_ai/core/tuul_client.dart'; // Import TuulClient,
import 'package:tuul_ai/core/models/tuul_options.dart';
import 'package:tuul_ai/core/models/app_response.dart';
import 'package:tuul_ai/core/exceptions/tuul_exception.dart';
import 'package:flutter/material.dart'; // For Flutter UI examples,

It is recommended to initialize the Tuul AI client early in your application lifecycle.

Method 1: Using the TuulAi Wrapper

Initialize the TuulClient with your API key, and then pass this client to the TuulAi wrapper:

import 'package:tuul_ai/core/tuul_client.dart'; 
import 'package:tuul_ai/tuul_ai.dart';

void main() {
  // Initialize TuulClient with your API key
  final tuulClient = TuulClient('YOUR_API_KEY');

  // Pass the initialized TuulClient to TuulAi
  final tuulAi = TuulAi(tuulClient);

  runApp(const MyApp());
}

Method 2: Initializing Service Singletons

Alternatively, you can initialize the singleton instances for the core services (Gen, LiteGen, History) directly with your API key, typically in your main function,:

import 'package:tuul_ai/core/gen/gen.dart';
import 'package:tuul_ai/core/gen/history.dart';
import 'package:tuul_ai/core/gen/lite_gen.dart';

void main() {
  const String apiKey = 'YOUR_API_KEY'; // Replace with your actual API key

  // Initialize the singleton instances for each service
  Gen.instance.initialize(apiKey);
  LiteGen.instance.initialize(apiKey);
  History.instance.initialize(apiKey);

  runApp(const MyApp());
}

Core Services #

1. Gen Service #

The Gen service provides access to powerful content generation models, supporting both non-streaming and streaming interactions,.

Non-Streaming Generation

Use the run method when you require the complete response in a single API call,:

/// Example: Basic non-streaming generation,
void basicGenExample() async {
  final gen = Gen.instance;,
  try {
    final response = await gen.run(
      tuulOptions: TuulOptions(
        prompt: 'Explain event-driven architecture',
        maxTokens: 200,
      ),
    );

    // Handle different response types (Success, Action, Error)
    switch (response) {
      case SuccessResponse(:final data):
        print('Result: ${data.output}');,
        break;
      case ActionResponse(:final action):
        print('Action required: $action');,
        break;
      case ErrorResponse(:final error):
        print('Error: $error');,
        break;
    }
  } on TuulException catch (e) {
    print('Tuul error: ${e.message}');,
  }
}

Streaming with Callbacks (UI Friendly)

This method is ideal for updating the Flutter UI in real-time as tokens are generated,:

/// Example: Streaming with callbacks (Best for Flutter UI),
void streamGenWithCallbackExample() async {
  final gen = Gen.instance;
  String buffer = '';

  await gen.runStreamWithCallback(
    tuulOptions: TuulOptions(
      prompt: 'Write a long technical article',
      maxTokens: 800,
    ),
    onEvent: (event) {
      if (event.type == 'token') {
        buffer += event.data;,
        print('Token: ${event.data}');,
      }
      if (event.type == 'done') {
        print('Completed!');,
        print('Full output: $buffer');,
      }
    },
    onError: (error, stackTrace) {
      print('Stream error: $error'); // Handles stream-specific errors,
    },
  );
}

Streaming with Stream API (Functional Style)

For a functional approach to handling streaming data, use the gen.stream method with an await for loop:

/// Example: Streaming with Stream API (Functional style)
void streamGenWithAwaitForExample() async {
  final gen = Gen.instance;
  String buffer = '';

  try {
    await for (final event in gen.stream(
      tuulOptions: TuulOptions(
        prompt: 'Write a backend architecture guide',
        maxTokens: 600,
      ),
    )) {
      if (event.type == 'token') {
        buffer += event.data;
        print(event.data);
      }

      if (event.type == 'done') {
        print('Completed!');
      }
    }
    print('Final output: $buffer');
  } on TuulException catch (e) {
    print('Stream error: ${e.message}');
  }
}

2. LiteGen Service #

The LiteGen service provides a simplified approach to content generation.

/// Example: Non-streaming request with LiteGen
void basicLiteGenExample() async {
  final liteGen = LiteGen.instance;
  try {
    final response = await liteGen.run(
      liteOptions: LiteOption(
        prompt: 'Write a poem about Dart',
        maxTokens: 100,
      ),
    );

    // Handle different response types
    switch (response) {
      case SuccessResponse(:final data):
        print('Generated content: ${data.content}');
        print('Status: ${response.statusCode}');
        break;
      case ErrorResponse(:final error, :final statusCode):
        print('Error ($statusCode): $error');,
        break;
      case ActionResponse(:final action, :final code):
        print('Action required: $action (code: $code)');
        break;
    }
  } on TuulException catch (e) {
    print('Tuul Exception: ${e.message} (${e.code})');
  }
}

3. History Service #

The History service allows applications to manage and retrieve conversation history and individual messages,,.

Fetching Conversations Example

/// Example: Fetching conversations
void fetchConversationsExample() async {
  final history = History.instance;
  try {
    final response = await history.conversations(
      sessionId: 'session-123', // Replace with your session ID
    );

    if (response is SuccessResponse) {
      print('Success: ${response.data}');
      print('Message: ${response.message}');
    } else if (response is ErrorResponse) {
      print('Error: ${response.error}');
      print('Status Code: ${response.statusCode}');
    } else if (response is ActionResponse) {
      print('Action: ${response.action}');
      print('Code: ${response.code}');
    }
  } on TuulException catch (e) {
    print('Exception: ${e.message}');
    print('Code: ${e.code}');
  }
}

Fetching Messages Example

/// Example: Fetching messages for a conversation
void fetchMessagesExample() async {
  final history = History.instance;

  try {
    final messagesResponse = await history.messages(
      conversationId: 'conv-456', // Replace with your conversation ID
    );

    if (messagesResponse is SuccessResponse) {
      print('Messages: ${messagesResponse.data}');
    }
  } on TuulException catch (e) {
    print('Exception: ${e.message}');
  }
}

Error Handling #

The plugin provides robust error handling. All API-related errors are encapsulated in TuulException, which allows developers to catch specific errors and access structured details,.

try {
  // ... your tuul_ai call ...
} on TuulException catch (e) {
  print('A Tuul AI specific error occurred: ${e.code} - ${e.message}');
} catch (e) {
  print('An unexpected error occurred: $e');
}

Understanding the Tuul Platform #

Tuul is an AI integration and automation platform designed to bring intelligence into existing software systems without requiring rewrites or disruptions. Built within the Digitwhale ecosystem, Tuul acts as a plug-and-use layer and AI middleware, bridging the gap between legacy and modern systems by embedding intelligence instantly.

Our Mission #

Tuul focuses on one core mission: to democratize access to artificial intelligence by making it effortless to integrate into any system,. Tuul empowers developers and organizations to evolve seamlessly, allowing them to transform workflows into callable APIs or microservices rapidly without managing complex infrastructure.

Core Architecture and Conceptual Model #

Tuul's architecture is hierarchical and developer-friendly, designed to ensure modularity, governance, and secure execution across AI applications,. The conceptual hierarchy is: Organization → Project → Agent → Instance → Tool.

Key components of the Tuul platform include:

Component Description
Organization The top-level secure workspace encompassing all billing, team, and security settings,.
Project A high-level container for a specific AI Agent application.
Agent (AI Identity) The intelligent core, or "brain," defined by its persona, voice, tone, and specific capabilities,. Your application interacts with a deployed Agent.
Instance A specific, versioned snapshot of an Agent,. Instances can be either Test Instances (for development) or Production Instances (for live traffic).
Tool (Function) Custom, server-side functions written in the Tuul IDE that the Agent can execute to extend its capabilities (e.g., calling an API or querying a database),.

This hierarchy enforces operational boundaries and governance, ensuring a specialized agent only executes actions within its assigned project or instance.

Secure Integration via MCP #

At its technical core, Tuul leverages the Model Context Protocol (MCP).

  • The MCP is an open standard that defines how AI models securely communicate and interact with external data and tools,.
  • Your Tuul Agent acts as an MCP Client, which "shops" for tools to solve a problem,.
  • The Tools (external data sources or functions) act as MCP Servers, providing standardized and scalable capabilities to the AI,.

The Development Environment (Playground) #

Tuul provides a complete development environment, known as the Playground,, where developers design, build, test, and deploy AI agents.

  • Interactive Testing: The Playground is an interactive chat and debugging environment used to test the agent's Test Instance safely and see real-time responses,.
  • Customization: Developers use the Settings Panel to define the AI's Persona and Behavior (tone, creativity) and integrate Knowledge Sources (APIs, databases).
  • Version Control: Developers can track changes to their project using the Commit section, which saves the current agent configuration to an Instance,,.

Contributing #

We welcome contributions! Please open issues or submit pull requests on our GitHub repository.

License #

This project is licensed under the terms specified in the LICENSE file.

0
likes
140
points
151
downloads

Publisher

unverified uploader

Weekly Downloads

A Flutter plugin for integrating applications with the Tuul AI platform, providing access to Gen, LiteGen, and History services through a unified SDK.

Homepage

Documentation

Documentation
API reference

License

unknown (license)

Dependencies

flutter, http, plugin_platform_interface

More

Packages that depend on tuul_ai

Packages that implement tuul_ai