sendMessage method

Future<String> sendMessage(
  1. String message
)

Sends a message to the AI service and returns the response.

This method makes a single HTTP request to the AI API and returns the generated response as a string.

The message parameter is the user's input text.

Throws an Exception if:

  • API key is not set
  • Network request fails
  • API returns an error response

Example:

final response = await aiService.sendMessage('What is Flutter?');
print(response); // AI's response about Flutter

Implementation

Future<String> sendMessage(final String message) async {
  if (apiKey == null || apiKey!.isEmpty) {
    throw Exception('API key not set. Please configure your OpenAI API key.');
  }

  try {
    final response = await http.post(
      Uri.parse('$_baseUrl/chat/completions'),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $apiKey',
      },
      body: jsonEncode({
        'model': _model,
        'messages': [
          {'role': 'user', 'content': message},
        ],
        'max_tokens': 1000,
        'temperature': 0.7,
      }),
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body) as Map<String, dynamic>;
      final choices = data['choices'] as List<dynamic>;
      final firstChoice = choices[0] as Map<String, dynamic>;
      final message = firstChoice['message'] as Map<String, dynamic>;
      return message['content'] as String;
    } else {
      try {
        final error = jsonDecode(response.body) as Map<String, dynamic>;
        final errorObj = error['error'] as Map<String, dynamic>?;
        final errorMessage =
            (errorObj?['message'] as String?) ?? 'Unknown API error';

        // Provide more user-friendly error messages
        var userMessage = errorMessage;
        final messageLower = errorMessage.toLowerCase();
        if (messageLower.contains('quota') ||
            messageLower.contains('billing')) {
          userMessage =
              'API Quota Exceeded: $errorMessage\n\nPlease check your '
              'OpenAI account billing and usage limits.';
        } else if (messageLower.contains('invalid_api_key') ||
            messageLower.contains('authentication')) {
          userMessage =
              'Invalid API Key: Please check your OpenAI API key in '
              'settings.';
        } else if (messageLower.contains('rate_limit')) {
          userMessage =
              'Rate Limit Exceeded: Please wait a moment and try again.';
        }

        throw Exception(userMessage);
      } on FormatException {
        throw Exception(
          'API returned an invalid response. Status code: '
          '${response.statusCode}',
        );
      }
    }
  } on FormatException catch (e) {
    throw Exception('Invalid response format: $e');
  } on Exception {
    rethrow;
  } catch (e) {
    throw Exception('Network error: $e');
  }
}