executePrompt method

  1. @override
Future executePrompt(
  1. String userPromptContent, {
  2. String? effectiveSystemPrompt,
})
override

Implementation

@override
Future<dynamic> executePrompt(
  String userPromptContent, {
  String? effectiveSystemPrompt,
}) async {
  if (config.apiKey == "YOUR_OPENAI_API_KEY_HERE" || config.apiKey.isEmpty) {
    throw Exception("OpenAI API Key not configured in FluenticConfig.");
  }
  final String endpoint =
      config.baseUrl.endsWith('/chat/completions')
          ? config.baseUrl
          : '${config.baseUrl}/chat/completions';
  final uri = Uri.parse(endpoint);
  final headers = {
    /* ... same ... */ "Content-Type": "application/json",
    "Authorization": "Bearer ${config.apiKey}",
  };

  // Construct messages array
  final List<Map<String, String>> messages = [];
  final String? finalSystemPrompt =
      effectiveSystemPrompt ??
      config.defaultSystemPrompt; // Use effective or config's default

  if (finalSystemPrompt != null && finalSystemPrompt.isNotEmpty) {
    messages.add({"role": "system", "content": finalSystemPrompt});
  }
  messages.add({"role": "user", "content": userPromptContent});

  final Map<String, dynamic> requestBody = {
    "model": config.model,
    "messages": messages,
    "response_format": {"type": "json_object"},
  };

  final promptStart =
      userPromptContent.length > 100
          ? userPromptContent.substring(0, 100)
          : userPromptContent;
  dev.log(
    "Sending to OpenAI: Model=${config.model}, SystemPrompt='${finalSystemPrompt ?? "None"}', UserPrompt(start)='$promptStart...'",
  );

  try {
    // ... (HTTP post and response handling - same as before) ...
    final response = await http.post(
      uri,
      headers: headers,
      body: jsonEncode(requestBody),
    );
    if (response.statusCode == 200) {
      final Map<String, dynamic> responseData = jsonDecode(response.body);
      if (responseData['choices'] != null &&
          responseData['choices'].isNotEmpty) {
        final message = responseData['choices'][0]['message'];
        if (message != null && message['content'] != null) {
          String content = message['content'];
          try {
            return jsonDecode(content);
          } catch (e) {
            throw Exception(
              "OpenAI API Error: Model content not valid JSON. Content: '$content'. Error: $e",
            );
          }
        }
      }
      throw Exception(
        "OpenAI API Error: Response structure missing 'choices[0].message.content'. Response: ${response.body}",
      );
    } else {
      throw Exception(
        "OpenAI API Error ${response.statusCode}: ${response.body}",
      );
    }
  } catch (e) {
    dev.log("Error in OpenAiApiClient: $e");
    rethrow;
  }
}