관리 메뉴

꿀맛코딩

How to call chat gpt api (Chat gpt API 호출 방법 Flutter 사용) 본문

공부방/Chat GPT

How to call chat gpt api (Chat gpt API 호출 방법 Flutter 사용)

soycrab 2023. 2. 26. 02:13

이번 시간에는 Chat gpt API 를 이용해서 프로그램을 만들어 볼거에요. 

Chat gpt가 스스로 만들어준 소스에요. 

저는 요즘 Flutter 로 놀고 있어서 Flutter 를 기준으로 만들어 볼게요. 

사실 언어만 다르지 사용방법은 전부 같으니까 

대충 이렇게 API를 사용하는구나 정도만 알아가면 좋을 것 같아요. 

 

1. Response 를 요청하는 코드에요 . 

Future<String> getResponse(String inputText) async {
    final String apiKey = 'API Key';
    final String endpointUrl = 'https://api.openai.com/v1/completions';

    final Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $apiKey',
    };

    final Map<String, dynamic> data = {
      "model":"text-davinci-003",  //Engine id
      'prompt': '$inputText\nQ:', 
      'temperature': 0.7,
      'max_tokens': 50,
      'n': 1,
      'stop': 'A:',
    };

    final response = await http.post(Uri.parse(endpointUrl), headers: headers, body: json.encode(data));
    if (response.statusCode == 200) {
      final responseData = json.decode(response.body)['choices'][0]['text'];
      return responseData;
    } else {
      throw Exception('Failed to load data');
    }
  }

 

순서대로 코드를 살펴 볼게요. 

  • 먼저 apiKey 부분은 이전 포스팅에서 작성한 Chat gpt api key 를 넣어줘요.
    이렇게 넣어준 api key는 Request시 헤더에 들어갈 거에요.
  • 다음은 body에 들어갈 데이터 들을 살표보아요.
    model 에 들어가는 text-davinci-003 은 우리가 이전 포스팅에서 요청한 engine id중 하나를 사용 한 것이에요.
    2023.2.26 01:55 분 기준으로  정상 동작하는 모델이에요. 
  • prompt : 질문할 텍스트 값이에요
  • max_tokens: 완료 시 생성할 최대 토큰 수에요, 질문의 응답 길이가 이 토큰을 초과할 수 없다고 해요. 
  • temperature: 샘플링에 대한 온도라고 하네요. 온도의 높낮이에 따라 질문에 대한 응답 차이가 있어요.
    • 창의적인 대답을 원하면 수치를 높여요 ex ) 0.8 .. 0.9.. 
    • 정의된 답이 있는 경우를 상정하면 0을 사용해요.
  • n : 정수, 프롬포트에 대한 완료 여부에 대한 제어 매개변수에요. 저는 그냥 1로 했어요. 
    다음에 여기에 대해서 자세히 다뤄볼게요.
  • stop : API가 토큰 생성을 중지하는 정지 값이에요. 해당 내용도 자세히는 나중에 정리해 볼게요.

 

여기서 잠깐  

Text-Davinci 엔진은 대규모 자연어 처리(NLP)기술을 활용하여 다양한 자연어 작업을 수행할수 있어요. 

단점으로는 성능이 가장 좋은 모델이여서 API 호출 제한이 있어요. 

 

2. 이제 위의 Response 를 이용해서 API 호출및 응답 결과를 UI에 보여주는 코드를 작성해 볼게요. 

String _inputText = '';
String _responseText = '';

  void _getResponse() async {
    final response = await getResponse(_inputText);
    setState(() {
      _responseText = response;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter FAQ'),
      ),
      body: Column(
        children: [
          TextField(
            onChanged: (value) => _inputText = value,
          ),
          ElevatedButton(
            onPressed: () => _getResponse(),
            child: Text('Get Response'),
          ),
          Text(_responseText),
        ],
      ),
    );
  }

 

3. 전체 코드 에요  (https://github.com/JeonGuKang/flutter_chatgpt_API_test)

http 는 외부 패키지 이므로 pubspec.yaml에 따로 추가해주세요.

http: ^0.13.5
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(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  String _inputText = '';
  String _responseText = '';

  void _getResponse() async {
    final response = await getResponse(_inputText);
    setState(() {
      _responseText = response;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter FAQ'),
      ),
      body: Column(
        children: [
          TextField(
            onChanged: (value) => _inputText = value,
          ),
          ElevatedButton(
            onPressed: () => _getResponse(),
            child: Text('Get Response'),
          ),
          Text(_responseText),
        ],
      ),
    );
  }


  Future<String> getResponse(String inputText) async {
    final String apiKey = 'your API Key';
    final String endpointUrl = 'https://api.openai.com/v1/completions';

    final Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $apiKey',
    };

    final Map<String, dynamic> data = {
      "model":"text-davinci-003",
      'prompt': '$inputText\nQ:',
      'temperature': 0.7,
      'max_tokens': 50,
      'n': 1,
      'stop': 'A:',
    };

    final response = await http.post(Uri.parse(endpointUrl), headers: headers, body: json.encode(data));
    if (response.statusCode == 200) {
      final responseData = json.decode(response.body)['choices'][0]['text'];
      return responseData;
    } else {
      throw Exception('Failed to load data');
    }
  }
}

 

 

4. 실행 결과 

 

보시는 것처럼 대화 내용을 입력하고 Get Response 를 누르면 

바로 하단에 Chat GPT 의 응답이 보여요. 

참고로 각 언어별로 샘플 코드들이 있어요. 

- python

import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

start_sequence = "\nA:"
restart_sequence = "\n\nQ: "

response = openai.Completion.create(
  model="text-davinci-003",
  prompt="I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: What is human life expectancy in the United States?\nA: Human life expectancy in the United States is 78 years.\n\nQ: Who was president of the United States in 1955?\nA: Dwight D. Eisenhower was president of the United States in 1955.\n\nQ: Which party did he belong to?\nA: He belonged to the Republican Party.\n\nQ: What is the square root of banana?\nA: Unknown\n\nQ: How does a telescope work?\nA: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n\nQ: Where were the 1992 Olympics held?\nA: The 1992 Olympics were held in Barcelona, Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\nQ:",
  temperature=0,
  max_tokens=100,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0,
  stop=["\n"]
)

 

- node.js

const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

const response = await openai.createCompletion({
  model: "text-davinci-003",
  prompt: "I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: What is human life expectancy in the United States?\nA: Human life expectancy in the United States is 78 years.\n\nQ: Who was president of the United States in 1955?\nA: Dwight D. Eisenhower was president of the United States in 1955.\n\nQ: Which party did he belong to?\nA: He belonged to the Republican Party.\n\nQ: What is the square root of banana?\nA: Unknown\n\nQ: How does a telescope work?\nA: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n\nQ: Where were the 1992 Olympics held?\nA: The 1992 Olympics were held in Barcelona, Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\nQ:",
  temperature: 0,
  max_tokens: 100,
  top_p: 1,
  frequency_penalty: 0,
  presence_penalty: 0,
  stop: ["\n"],
});

 

-curl 

curl https://api.openai.com/v1/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
  "model": "text-davinci-003",
  "prompt": "I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: What is human life expectancy in the United States?\nA: Human life expectancy in the United States is 78 years.\n\nQ: Who was president of the United States in 1955?\nA: Dwight D. Eisenhower was president of the United States in 1955.\n\nQ: Which party did he belong to?\nA: He belonged to the Republican Party.\n\nQ: What is the square root of banana?\nA: Unknown\n\nQ: How does a telescope work?\nA: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n\nQ: Where were the 1992 Olympics held?\nA: The 1992 Olympics were held in Barcelona, Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\nQ:",
  "temperature": 0,
  "max_tokens": 100,
  "top_p": 1,
  "frequency_penalty": 0,
  "presence_penalty": 0,
  "stop": ["\n"]
}'

 

- json

{
  "model": "text-davinci-003",
  "prompt": "I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: What is human life expectancy in the United States?\nA: Human life expectancy in the United States is 78 years.\n\nQ: Who was president of the United States in 1955?\nA: Dwight D. Eisenhower was president of the United States in 1955.\n\nQ: Which party did he belong to?\nA: He belonged to the Republican Party.\n\nQ: What is the square root of banana?\nA: Unknown\n\nQ: How does a telescope work?\nA: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n\nQ: Where were the 1992 Olympics held?\nA: The 1992 Olympics were held in Barcelona, Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\nQ:",
  "temperature": 0,
  "max_tokens": 100,
  "top_p": 1,
  "frequency_penalty": 0,
  "presence_penalty": 0,
  "stop": ["\n"]
}

 

해당 샘플 코드는 아래 Playground 에서 받으실수 있고, 

여기서 각종 Chat gpt test 가 가능해요. 

알아두면 좋은 사이드에요!!

https://platform.openai.com/playground/

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

 

 

저는 이제 본격적으로 Chat GPT를 활용한 프로젝트 들을 만들어 볼거에요. 

갑자기 새벽에 Chat GPT API사용 방법이 궁금해져서 

직접 사용해보고 글을 작성해 보았어요. 

졸려서 박카스를 마시면서 3개의 포스팅을 작성해 놓았는데,

조금 부족하더라도 누군가에게 도움이 되었으면 좋겠어요. 

 

우리 같이 새로운 인공지능 시대를 위해 도약해 보아요. 

 

반응형
Comments