🦁

【Flutter】gpt-3.5-turboの使用方法

2023/05/14に公開

はじめに

FlutterでChatGPTのAPIを使う時、エンドポイントなど、GPT3(davinci)の時とは、若干異なっていて詰まったので、ここにまとめておきます。
同じ部分で詰まっている方の助けになれば嬉しいです!

GPT3(davinci)の場合

api.dart
import "dart:convert";
import "package:flutter/material.dart";
import "package:http/http.dart" as http;
import "package:dart_openai/openai.dart";

String apiKey = "APIキーを入力";

class ApiServices {
  static String baseUrl = "https://api.openai.com/v1/completions";

  static Map<String, String> header = {
    "Content-Type": "application/json",
    "Authorization": "Bearer $apiKey"
  };

  static sendMessage(String? message) async {
    var res = await http.post(
      Uri.parse(baseUrl),
      headers: header,
      body: jsonEncode(
        {
          "model": "text-davinci-003",
          "prompt": "$message",
          "max_tokens": 1000,
          "temperature": 0,
          "top_p": 1,
          "frequency_penalty": 0.0,
          "presence_penalty": 0.0,
          "stop": ["Human:", "AI:"]
        },
      ),
    );

    if (res.statusCode == 200) {
      var data = jsonDecode(res.body.toString());

      // ここに必要なデータが格納されている
      var msg = data['choices'][0]["text"];
      // 文字化け対策
      return utf8.decode(msg.runes.toList());
    } else {
      print("Feiled to fetch data");
    }
  }
}

ChatGPT(gpt-3.5-turbo)の場合

api.dart
import "dart:convert";
import "package:flutter/material.dart";
import "package:http/http.dart" as http;
import "package:dart_openai/openai.dart";

String apiKey = "APIキーを入力";

class ApiServices {
  static String baseUrl = "https://api.openai.com/v1/chat/completions";

  static Map<String, String> header = {
    "Content-Type": "application/json",
    "Authorization": "Bearer $apiKey"
  };

  static sendMessage(String? message) async {
    var res = await http.post(
      Uri.parse(baseUrl),
      headers: header,
      body: jsonEncode(
        {
          "model": "gpt-3.5-turbo",
          "messages": [
            {
              "role": "user",
              "content":
                      "$message",
            }
          ]
        },
      ),
    );

    if (res.statusCode == 200) {
      var data = jsonDecode(res.body.toString());

      // ここに返ってきた文字が格納されている
      var msg = data["choices"][0]["message"]['content'];

      // 文字化け対策
      return utf8.decode(msg.runes.toList());
    } else {
      print("Feiled to fetch data");
    }
  }
}

Discussion