skantravels/Mobile/lib/services/openaiservice.dart

55 lines
2.2 KiB
Dart
Raw Normal View History

2024-09-13 08:59:21 +01:00
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter_dotenv/flutter_dotenv.dart';
class OpenAIService {
2024-09-16 15:33:37 +01:00
static Future<String> getGuideBook(String country) async {
2024-09-13 08:59:21 +01:00
final apiKey = dotenv.env['OPENAI_API_KEY'];
final uri = Uri.parse('https://api.openai.com/v1/chat/completions');
final requestBody = jsonEncode({
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "You are a Tourist-guide book that makes a guidebook over a given country and further instructions in the message."
},
{
"role": "user",
2024-09-16 15:33:37 +01:00
"content": "Make a tourist guide book over $country. The topics should be: A little introduction to how the people of the country is like and what to expect from the environment, famous tourist attractions in the country(amusement park always included), Basic words that would be nice to learn in the country's language(should always be from English to the country's language) and transportation. These topics should be in a Json-Object format in this form: {Country: {introduction: {people: , environment: }, tourist_attractions: {famous_sites: [{name: , description: }]}, basic_words: {}, transportation: {overview: , public_transport: {buses: , trains: , taxis: }}}}"
2024-09-13 08:59:21 +01:00
}
],
2024-09-16 15:33:37 +01:00
"max_tokens": 1500
2024-09-13 08:59:21 +01:00
});
final response = await http.post(
uri,
headers: {
'Authorization': 'Bearer $apiKey',
'Content-Type': 'application/json',
},
body: requestBody,
);
2024-09-16 15:33:37 +01:00
if (response.statusCode == 200) {
final decodedBody = utf8.decode(response.bodyBytes);
final data = jsonDecode(decodedBody);
var content = data['choices'][0]['message']['content'];
content = content.replaceAll('```json', '').replaceAll('```', '').trim();
return _extractDescription(content);
2024-09-13 08:59:21 +01:00
} else {
2024-09-16 15:33:37 +01:00
throw Exception('Fejl ved billedanalyse: ${response.statusCode}');
2024-09-13 08:59:21 +01:00
}
}
2024-09-16 15:33:37 +01:00
static String _extractDescription(String content) {
final lines = content.split('\n');
final startIndex = lines.indexWhere((line) => line.startsWith('**Beskrivelse:**'));
if (startIndex == -1) return content;
return lines.skip(startIndex).join('\n').trim();
}
2024-09-13 08:59:21 +01:00
}