Flutter ChatGPT-API http 使用方法

フラッターでOpenAI-APIを使用するためにhttpを使用する場合の手順です。
(2023 / 11 / 29 作成)
OpenAIのAPIキーの取得方法は割愛。
但し、クレジットカードを登録しないと、openAI APIを使用することはできません

  1. VS CODEでプロジェクトを作成

$ flutter create –org com.mogusatech flutter_http_openai_api
$ flutter pub add http

2. main.dartのコードを削除し、下のコードを入れます

下の // Input API Key  部分に 自分の Api Key を 入れてください。

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title}); 

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  int _counter = 0;
  void _incrementCounter() {
    setState(() {      
      _counter++;
    });
  }

//  https://platform.openai.com/docs/api-reference/making-requests
////////////////     Making requests
  Future<void> generateChatCompletion() async {

    setState(() {      
      _counter++;
    });

    //  Input API Key
    String apiKey = "sk-1OU6xxxxxxxxxxxxxxxxxxxxxxxxxxxxxNkvJu";
    String model = "gpt-3.5-turbo";

    var response = await http.post(
      Uri.parse('https://api.openai.com/v1/chat/completions'),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $apiKey',
      },
      body: jsonEncode({
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": "Say this is a test!"}],
        "temperature": 0.7
      }),
    );

    if (response.statusCode == 200) {
      final Map<String, dynamic> data = jsonDecode(response.body);

      print('===========================');
      print(data);
      print('===========================');

    } else {
      print("Error: ${response.reasonPhrase}");
    }
  }

  @override
  Widget build(BuildContext context) {
   
    return Scaffold(
      appBar: AppBar(
       
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        
        title: Text(widget.title),
      ),
      body: Center(
        
        child: Column(
          
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // onPressed: _incrementCounter,
        onPressed: generateChatCompletion,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

3. プロジェクトを実行して以下の出力メッセージが出れば成功です。

flutter: ===========================
flutter: {id: chatcmpl-8QDxFhnXpXSk3XA9JjvIEKzuk90WK, object: chat.completion, created: 1701260861, model: gpt-3.5-turbo-0613, choices: [{index: 0, message: {role: assistant, content: This is a test!}, finish_reason: stop}], usage: {prompt_tokens: 13, completion_tokens: 5, total_tokens: 18}}
flutter: ===========================

4. ここでは、ios、android、macOS、Webで実行した結果です。

5. macOSで次のようなエラーが発生した場合。

_ClientSocketException (ClientException with SocketException: Connection failed (OS Error: Operation not permitted, errno = 1), address = api.openai.com, port = 443, uri=https://api.openai.com/v1/completions)

ここのファイル中に

macos/Runner/DebugProfile.entitlements

以下の内容を追加してください。

<key>com.apple.security.network.client</key>
<true/>

プロジェクトのダウンロード

ダウンロードして解凍し、自分のAPI KEYを挿入して以下のコマンドを実行してください。
$ flutter pub get

フラッターで漫画アプリを作る

参考サイト

コメント

PAGE TOP