sendMessage method
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(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);
return data['choices'][0]['message']['content'] as String;
} else {
final error = jsonDecode(response.body);
throw Exception('API Error: ${error['error']['message']}');
}
} on FormatException catch (e) {
throw Exception('Invalid response format: $e');
} on Exception {
rethrow;
} catch (e) {
throw Exception('Network error: $e');
}
}