LoginSignup
4
5

More than 1 year has passed since last update.

ChatGPTのAPIが使えるようになったので、早速試してみた!

Last updated at Posted at 2023-03-01

ChatGPTのAPIが使えるようになったので、早速試してみました!

import Foundation
import Alamofire

struct Message: Codable, Identifiable {
    let id = UUID()
    let role: String
    let content: String
    
    private enum CodingKeys: String, CodingKey {
        case role, content
    }
}

struct ChatGPTRequest: Encodable {
    let model: String
    let messages: [Message]
}

struct ChatGPTResponse: Decodable {
    let id: String?
    let object: String?
    let created: Int?
    let model: String?
    let usage: Usage?
    let choices: [Choice]
    
    struct Usage: Decodable {
        let prompt_tokens: Int
        let completion_tokens: Int
        let total_tokens: Int
    }
    
    struct Choice: Decodable {
        let message: Message
        let finish_reason: String
        let index: Int
    }
}

final class ChatGPT {
    let baseUrl = "https://api.openai.com/v1/chat/"
    let openAIAPIKey = ""
    
    func send(messages: [Message]) async throws -> ChatGPTResponse {
        let body = ChatGPTRequest(
            model: "gpt-3.5-turbo",
            messages: messages
        )
        
        let headers: HTTPHeaders = [
            "Authorization": "Bearer \(openAIAPIKey)"
        ]
        
        let response = await AF
            .request(
                baseUrl + "completions",
                method: .post,
                parameters: body,
                encoder: .json,
                headers: headers
            )
            .serializingDecodable(ChatGPTResponse.self)
            .response
        
        switch response.result {
        case .success(let data):
            return data
        case .failure(let error):
            throw error
        }
    }
}


ご覧いただきありがとうございました。

🐦 Twitter: @shota_appdev

📱 個人アプリ: Symbols Explorer

4
5
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
4
5