플러터앱에서 dart_openai 패키지를 사용하는 방법

플러터에서 OpenAI-API를 사용하기위한 dart_openai 패키지를 사용하는 경우의 순서입니다
(2023 / 11 / 27 작성)
OpenAI의 API 키를 취득하는 방법은 생략.
그러나 신용 카드를 등록하지 않으면 openAI API를 사용할 수 없습니다.

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

$ flutter create –org com.mogusatech use_dart_openai

2. 프로젝트의루트디렉토리에 .env 파일 만들기 (lib 폴더안이 아님)

sk-1OU6GxxxxxxxxxxxxxxxxxxxxxxxxxxQNkvJu 에는 자신의 API KEY 입력
‘ ’ 는 넣지 않습니다

OPEN_AI_API_KEY=sk-1OU6GxxxxxxxxxxxxxxxxxxxxxxxxxxQNkvJu   

3. lib/env/env.dart 파일 작성

//lib/env/env.dart
import 'package:envied/envied.dart';

part 'env.g.dart';

@Envied(path: ".env")
abstract class Env {
  @EnviedField(varName: 'OPEN_AI_API_KEY')
  static const String apiKey = _Env.apiKey;
}

env.dart 파일내에 에러가 생기지만 무시하고 아래4 실행

4. Terminal을 열고 프로젝트폴더내에서아래의 순서대로 실행

$ flutter pub add dart_openai
$ flutter pub add envied
$ flutter pub add –dev envied_generator
$ flutter pub add –dev build_runner

$ dart run build_runner build

============

아래의 메세지가 나오면 성공

apple@appleui-iMac use_dart_openai % dart run build_runner build
Building package executable… (8.3s)
Built build_runner:build_runner.
[INFO] Generating build script completed, took 426ms
[INFO] Precompiling build script… completed, took 7.8s
[INFO] Building new asset graph completed, took 1.1s
[INFO] Checking for unexpected pre-existing outputs. completed, took 1ms
[INFO] Generating SDK summary completed, took 5.4s
[INFO] Running build completed, took 5.9s
[INFO] Caching finalized dependency graph completed, took 73ms
[INFO] Succeeded after 6.0s with 3 outputs (8 actions)

5. main.dart의 코드를 지우고 아래를 복사합니다

import 'package:dart_openai/dart_openai.dart';
import 'package:flutter/material.dart';
import 'package:use_dart_openai/env/env.dart';

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++;
    });
  }
  @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: generateTextTemp,
        // onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Future<void> generateTextTemp() async {
    setState(() {      
      _counter++;
    });

    // Set the OpenAI API key from the .env file.
    OpenAI.apiKey = Env.apiKey;
    OpenAICompletionModel completion = await OpenAI.instance.completion.create(
      model: "text-davinci-003",
      prompt: "Dart is a program",
      maxTokens: 20,
      temperature: 0.5,
      n: 1,
      stop: ["\n"],
      echo: true,
      seed: 42,
      bestOf: 2,
    );
    print(completion.choices.first.text); // ...
    print(completion.systemFingerprint); // ...
    print(completion.id); //
  }
}  

6. 프로젝트를 실행하여아래의 출력메세지가 나오면 성공。

[OpenAI] accessing endpoint: /completions
[OpenAI] starting request to https://api.openai.com/v1/completions
[OpenAI] request to https://api.openai.com/v1/completions finished with status code 200
[OpenAI] starting decoding response body
[OpenAI] response body decoded successfully
[OpenAI] request finished successfully
flutter: Dart is a programing language
flutter: null
flutter: cmpl-8PSe0w0j5JAqhm3jFL2xONxqjHA7K

7. 여기서는、ios、android、macOS에서 실행。

8. 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
$ dart run build_runner build

플러터에서만화앱제작

참고싸이트

コメント

PAGE TOP