Loading...
Official Rax AI SDK for Flutter & Dart applications
Choose your preferred method
flutter pub add rax_aidependencies:
rax_ai: ^1.0.0Requirements: Flutter 3.0+ and Dart 3.0+. The SDK uses null safety and modern Dart features.
Get up and running in minutes
import 'package:rax_ai/rax_ai.dart';
void main() async {
// Initialize the client
final rax = RaxAI(apiKey: 'rax_your_api_key');
// Make your first request
final response = await rax.chat(
model: 'rax-4.0',
messages: [
ChatMessage.user('Hello, how are you?'),
],
);
print(response.choices.first.message.content);
}Send messages and receive AI responses
import 'package:rax_ai/rax_ai.dart';
final rax = RaxAI(apiKey: 'rax_your_api_key');
// Simple chat completion
final response = await rax.chat(
model: 'rax-4.0',
messages: [
ChatMessage.system('You are a helpful assistant.'),
ChatMessage.user('What is the capital of France?'),
],
temperature: 0.7,
maxTokens: 1000,
);
// Get the response
print(response.choices.first.message.content);
// Output: "The capital of France is Paris."
// Access usage information
print('Tokens used: ${response.usage.totalTokens}');Get responses in real-time using Dart Streams
import 'package:rax_ai/rax_ai.dart';
final rax = RaxAI(apiKey: 'rax_your_api_key');
// Stream responses in real-time
final stream = rax.chatStream(
model: 'rax-4.5',
messages: [
ChatMessage.user('Write a short poem about Flutter.'),
],
);
// Listen to the stream
await for (final chunk in stream) {
final content = chunk.choices.first.delta.content;
if (content != null) {
stdout.write(content);
}
}
print(); // New line at the endBuild a chat service with history management
import 'package:rax_ai/rax_ai.dart';
class ChatService {
final RaxAI _rax;
final List<ChatMessage> _messages = [
ChatMessage.system('You are a helpful assistant.'),
];
ChatService(String apiKey) : _rax = RaxAI(apiKey: apiKey);
Future<String> sendMessage(String userMessage) async {
// Add user message
_messages.add(ChatMessage.user(userMessage));
// Get response
final response = await _rax.chat(
model: 'rax-4.5',
messages: _messages,
);
final assistantMessage = response.choices.first.message.content;
// Add to history for context
_messages.add(ChatMessage.assistant(assistantMessage));
return assistantMessage;
}
void clearHistory() {
_messages.clear();
_messages.add(ChatMessage.system('You are a helpful assistant.'));
}
}
// Usage
final chatService = ChatService('rax_your_api_key');
print(await chatService.sendMessage('Hello!'));
print(await chatService.sendMessage('How are you?'));A complete Flutter chat screen with streaming support
import 'package:flutter/material.dart';
import 'package:rax_ai/rax_ai.dart';
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final _rax = RaxAI(apiKey: 'rax_your_api_key');
final _controller = TextEditingController();
final _messages = <Map<String, String>>[];
bool _isLoading = false;
String _streamingResponse = '';
Future<void> _sendMessage() async {
final userMessage = _controller.text.trim();
if (userMessage.isEmpty) return;
setState(() {
_messages.add({'role': 'user', 'content': userMessage});
_controller.clear();
_isLoading = true;
_streamingResponse = '';
});
try {
// Use streaming for real-time response
final stream = _rax.chatStream(
model: 'rax-4.0',
messages: _messages.map((m) =>
m['role'] == 'user'
? ChatMessage.user(m['content']!)
: ChatMessage.assistant(m['content']!)
).toList(),
);
await for (final chunk in stream) {
final content = chunk.choices.first.delta.content;
if (content != null) {
setState(() {
_streamingResponse += content;
});
}
}
setState(() {
_messages.add({'role': 'assistant', 'content': _streamingResponse});
_streamingResponse = '';
});
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error: $e')),
);
} finally {
setState(() => _isLoading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Rax AI Chat')),
body: Column(
children: [
Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: _messages.length + (_streamingResponse.isNotEmpty ? 1 : 0),
itemBuilder: (context, index) {
if (index == _messages.length && _streamingResponse.isNotEmpty) {
return _MessageBubble(
isUser: false,
content: _streamingResponse,
);
}
final message = _messages[index];
return _MessageBubble(
isUser: message['role'] == 'user',
content: message['content']!,
);
},
),
),
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Type a message...',
border: OutlineInputBorder(),
),
onSubmitted: (_) => _sendMessage(),
),
),
const SizedBox(width: 8),
IconButton.filled(
onPressed: _isLoading ? null : _sendMessage,
icon: _isLoading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.send),
),
],
),
),
],
),
);
}
}
class _MessageBubble extends StatelessWidget {
final bool isUser;
final String content;
const _MessageBubble({required this.isUser, required this.content});
@override
Widget build(BuildContext context) {
return Align(
alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.all(12),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.75,
),
decoration: BoxDecoration(
color: isUser
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.surfaceVariant,
borderRadius: BorderRadius.circular(16),
),
child: Text(
content,
style: TextStyle(
color: isUser
? Theme.of(context).colorScheme.onPrimary
: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
);
}
}Features: This example includes real-time streaming, message history, loading states, and a clean Material Design UI. Customize the colors and styling to match your app's theme.
Built-in exception classes for easy handling
import 'package:rax_ai/rax_ai.dart';
final rax = RaxAI(apiKey: 'rax_your_api_key');
try {
final response = await rax.chat(
model: 'rax-4.0',
messages: [ChatMessage.user('Hello!')],
);
print(response.choices.first.message.content);
} on RateLimitException catch (e) {
print('Rate limited. Retry after ${e.retryAfter} seconds');
// Implement exponential backoff
} on AuthException catch (e) {
print('Invalid API key. Please check your credentials.');
} on ValidationException catch (e) {
print('Invalid request: ${e.message}');
} on RaxAIException catch (e) {
// Catch all Rax AI errors
print('API Error: ${e.message}');
print('Status: ${e.statusCode}');
print('Code: ${e.errorCode}');
} catch (e) {
// Network or other errors
print('Unexpected error: $e');
}ValidationExceptionInvalid requestAuthExceptionInvalid API keyRateLimitExceptionToo many requestsServerExceptionServer errorFast and efficient for everyday tasks
rax-4.0Enhanced reasoning for complex tasks
rax-4.5Complete API reference
import 'package:rax_ai/rax_ai.dart';
// Initialize Client
final rax = RaxAI(
apiKey: 'rax_your_api_key', // Required
baseUrl: null, // Custom API URL (optional)
timeout: Duration(seconds: 30), // Request timeout
);
// Chat Completion
Future<ChatResponse> chat({
required String model,
required List<ChatMessage> messages,
double? temperature,
int? maxTokens,
double? topP,
List<String>? stop,
});
// Streaming Chat
Stream<ChatChunk> chatStream({
required String model,
required List<ChatMessage> messages,
double? temperature,
int? maxTokens,
double? topP,
List<String>? stop,
});
// List Models
Future<List<Model>> models();
// Get Usage
Future<UsageStats> usage();
// Message Constructors
ChatMessage.system(String content);
ChatMessage.user(String content);
ChatMessage.assistant(String content);Get your API key and start building with Rax AI in Flutter today.