1
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../constants/api_constant.dart';

class ApiService{
  static Future<String> sendMessage ({required String prompt}) async {
      var response = await http.post(Uri.parse("https://api.openai.com/v1/chat/completions"),
      headers: {
        'Authorization': 'Bearer $API_KEY',
        "Content-Type": "application/json"},
        body: jsonEncode({
          "model": "gpt-3.5-turbo",
          "message":
          [{"role": "user", "content": prompt}]

        })
      );
      if(response.statusCode == 200){
        final String content = jsonDecode(response.body)["choices"][0]["message"]["content"];
        content.trim();
        return content;
      }
      return "Something went Wrong";

    }
  }

This is my API file. I am using the GPT turbo 3.5.

void sendTextMessage(String prompt) async {
    addToChatList(prompt, true, DateTime.now().toString());
    final response = await ApiService.sendMessage(prompt: prompt);
    addToChatList(response , false, DateTime.now().toString());
  }

  void addToChatList(String prompt, bool isMe, String id) {
    final chats = ref.read(chatsProvider.notifier);
    chats.add(ChatModel(
      id: id,
      prompt: prompt,
      isMe: isMe,
    ));

enter image description here

The problem is that I am not getting the required output. I checked my API key my app is making request and using the API but its not displaying the outoput.

  • Add an `else` to your `response.statusCode == 200` check, and print what statusCode you are receiving. Then compare the status code against what the API is defined to return https://help.openai.com/en/articles/6891839-api-error-code-guidance – Wh1t3rabbit Jul 26 '23 at 03:21

0 Answers0