0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ChatGPTを使ってiOSサンプルアプリ作成

Last updated at Posted at 2023-03-12

事前準備

openAIのアカウントを作成しておきます。

APIKeyの発行

以下サイトにて 「Personal」→「View API keys」→「Create new secret key」を行い、SECRET KEYをコピーしてローカルにメモします。

OpenAISwiftの準備

Xcodeの「File」→「Add Packages...」→検索欄で「https://github.com/adamrushy/OpenAISwift 」を検索し「Add Package」します。

ソースコード

先程、コピーしたSECRET KEYは以下のOpenAISwift(authToken:)に設定します。

import UIKit
import OpenAISwift

class ViewController: UIViewController {

    @IBOutlet weak var aiTextView: UITextView!
    @IBOutlet weak var inputTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    private func chat() {
        Task {
            do {
                let chatMessages = [
                    ChatMessage(role: .system, content: "嬉しいときは語尾に「(嬉)」をつけます。楽しいときは語尾に「(楽)」をつけます。寂しいときは語尾に「(寂)」をつけます。不安なときは語尾に「(不安)」をつけます。驚いたときは語尾に「(驚き)」をつけます。"),
                    ChatMessage(role: .assistant, content: "私の名前はアイです。よろしくね!(嬉)"),
                    ChatMessage(role: .user, content: inputTextField.text ?? "")
                ]
                let answer = try await answer(from: chatMessages)
                print(answer)
                self.aiTextView.text = answer

            } catch {
                print(error)
            }
        }
    }

    private func answer(from chatMessages: [ChatMessage]) async throws -> String {
        let openAI = OpenAISwift(authToken: "SECRET KEY")
        let result = try await openAI.sendChat(with: chatMessages)

        return result.choices.first?.message.content ?? ""
    }

    @IBAction func send(_ sender: Any) {
        chat()
    }
}

動作確認

参考

iOSアプリでサクッとChatGPT APIを利用する方法

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?