askGPT method
Implementation
Future<Map<String, dynamic>> askGPT(
String text, List<String> languages, String api) async {
var uri = Uri.parse('https://api.openai.com/v1/chat/completions');
String body = '''
{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": "You are a translator."},
{"role": "system", "content": "The output will be as JSON lang code with text like this: {en: 'Hello World'} it has to be JSON always"},
{"role": "user", "content": "Translate the following text to ${languages.join(', ')}, en: '$text'"}
]
}''';
var headers = {
"Authorization": "Bearer $api",
"content-type": "application/json; charset=utf-8"
};
final response = await http.post(uri, headers: headers, body: body);
int statusCode = response.statusCode;
if (statusCode >= 200 && statusCode < 300) {
var responseBody = utf8.decode(response.bodyBytes);
try {
var data = jsonDecode(responseBody);
var result = jsonDecode(data['choices'][0]['message']['content']);
return result;
} catch (e) {
askGPT(text, languages, api);
print('Error parsing response body: $e'.red());
return {};
}
} else {
// askGPT(text, languages, api);
print('Error Status Code: $statusCode'.red());
print('Error Response Body: ${response.body}'.red());
return {};
}
}