Skip to content

Basic Usage

Amayyas edited this page Dec 5, 2025 · 2 revisions

Basic Usage

This guide covers the fundamental usage patterns of Flutter AI SDK.

Initialization

Simple Setup

import 'package:flutter_ai_sdk/flutter_ai_sdk.dart';

final ai = FlutterAI(
  provider: AIProvider.openai,
  config: AIConfig(
    apiKey: 'your-api-key',
  ),
);

With Full Configuration

final ai = FlutterAI(
  provider: AIProvider.openai,
  config: AIConfig(
    apiKey: 'your-api-key',
    model: 'gpt-4-turbo',
    temperature: 0.7,
    maxTokens: 1000,
    systemPrompt: 'You are a helpful assistant.',
  ),
);

Sending Messages

Simple Chat

final response = await ai.chat('Hello! How are you?');
print(response.text);

Accessing Response Properties

final response = await ai.chat('What is Flutter?');

// Text content
print(response.text);

// Finish reason
print(response.finishReason); // FinishReason.stop

// Token usage
if (response.usage != null) {
  print('Input tokens: ${response.usage!.promptTokens}');
  print('Output tokens: ${response.usage!.completionTokens}');
  print('Total tokens: ${response.usage!.totalTokens}');
}

// Model used
print(response.model);

Multi-Turn Conversations

Context is maintained automatically:

// First message
await ai.chat('My name is Alice.');

// Second message - AI remembers the name
await ai.chat('I live in Paris.');

// Third message - AI remembers everything
final response = await ai.chat('What do you know about me?');
print(response.text);
// "You told me your name is Alice and you live in Paris."

System Prompts

Set the AI's behavior with a system prompt:

final ai = FlutterAI(
  provider: AIProvider.anthropic,
  config: AIConfig(
    apiKey: 'your-key',
    systemPrompt: '''
You are a friendly coding assistant.
- Always provide working code examples
- Explain concepts clearly
- Use Dart/Flutter when possible
''',
  ),
);

final response = await ai.chat('How do I create a button?');
// Response will follow the system prompt guidelines

Without Context

For stateless requests:

// This message won't be added to history
final response = await ai.chat(
  'What is 2 + 2?',
  addToContext: false,
);

Managing Conversation

Clear Context

// Start fresh conversation
ai.clearContext();

Access Conversation

// Get conversation history
final conversation = ai.conversation;
print('Messages: ${conversation.length}');

// Iterate messages
for (final message in conversation.messages) {
  print('${message.role}: ${message.textContent}');
}

Export/Import Conversation

// Export to JSON
final json = ai.conversation.toJson();
await saveToStorage(json);

// Import later
final savedJson = await loadFromStorage();
final conversation = Conversation.fromJson(savedJson);

Complete Example

import 'package:flutter_ai_sdk/flutter_ai_sdk.dart';

Future<void> main() async {
  // Initialize
  final ai = FlutterAI(
    provider: AIProvider.openai,
    config: AIConfig(
      apiKey: 'your-api-key',
      model: 'gpt-4-turbo',
      temperature: 0.7,
      systemPrompt: 'You are a helpful assistant.',
    ),
  );

  try {
    // First message
    print('User: Hello!');
    var response = await ai.chat('Hello!');
    print('AI: ${response.text}\n');

    // Second message
    print('User: What can you help me with?');
    response = await ai.chat('What can you help me with?');
    print('AI: ${response.text}\n');

    // Check token usage
    print('Total tokens used: ${response.usage?.totalTokens}');

    // Clear for new conversation
    ai.clearContext();
    print('\nContext cleared. Starting fresh conversation.\n');

    // New conversation
    print('User: Tell me about Dart.');
    response = await ai.chat('Tell me about Dart.');
    print('AI: ${response.text}');

  } catch (e) {
    print('Error: $e');
  } finally {
    // Always dispose
    ai.dispose();
  }
}

Next Steps

Clone this wiki locally