Files
wheres-my-sign/lib/chatgpt/test.dart

76 lines
2.3 KiB
Dart

import 'dart:convert';
import 'package:http/http.dart' as http;
/// Represents a busy intersection.
class Intersection {
final String name;
final double latitude;
final double longitude;
Intersection(this.name, this.latitude, this.longitude);
}
/// A service that communicates with the OpenAI ChatGPT API.
class ChatGPTService {
final String apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
final String apiUrl = 'https://api.openai.com/v1/chat/completions';
/// Sends a prompt to ChatGPT to find the busiest intersections around the address.
Future<List<Intersection>> getBusyIntersections({
required String address,
required int count,
required double radiusMiles,
required String timeOfDay,
}) async {
final prompt = '''
Given the address "$address", find the $count busiest intersections within $radiusMiles miles during $timeOfDay on a weekday. Return the results in CSV format with columns: intersection_name, latitude, longitude.
''';
final response = await http.post(
Uri.parse(apiUrl),
headers: {
'Authorization': 'Bearer $apiKey',
'Content-Type': 'application/json',
},
body: jsonEncode({
"model": "gpt-4",
"messages": [
{
"role": "system",
"content": "You are a traffic and mapping expert.",
},
{"role": "user", "content": prompt},
],
}),
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final csvString = data['choices'][0]['message']['content'];
return _parseCsv(csvString);
} else {
throw Exception('Failed to get response from ChatGPT: ${response.body}');
}
}
/// Parses the CSV response into a list of [Intersection] objects.
List<Intersection> _parseCsv(String csv) {
final lines = LineSplitter().convert(csv.trim());
final intersections = <Intersection>[];
for (var i = 1; i < lines.length; i++) {
final parts = lines[i].split(',');
if (parts.length >= 3) {
final name = parts[0].trim();
final lat = double.tryParse(parts[1].trim());
final lng = double.tryParse(parts[2].trim());
if (lat != null && lng != null) {
intersections.add(Intersection(name, lat, lng));
}
}
}
return intersections;
}
}