728x90
    
    
  반응형
    
    
    
  SMALL
    먼저 api key 를 만들어야합니다요.
https://platform.openai.com/ 여기서 로그인하고


아주 쉽게 만들 수 있습니다.
그리고 Alamofire가 필요한데!!
*** Alamofire란? ***
Swift로 작성된 HTTP 클라이언트 라이브러리로, API 호출 및 JSON 파싱 등의 작업을 쉽게 수행할 수 있도록 지원합니다.
따라서, iOS 프로젝트에서 OpenAI API를 사용하려면, Alamofire 라이브러리를 사용하여 API 호출 및 JSON 파싱을 구현하면 됩니다. Podfile에는 다음과 같이 Alamofire를 추가할 수 있습니다.

그리고 Pod install 이후 확장자 .xcodeproj 이 아니라 .xcworkspace로 프로젝트를 열어서
API를 핸들링 할 소스 코드를 만드시면 됩니다.
관련 문서 - https://platform.openai.com/docs/api-reference/making-requests
//
//  APIHandler.swift
//  chatGPTtest
//
//  Created by Byeon jinha on 2023/04/12.
//
import Alamofire
struct ChatCompletion: 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
        
        struct Message: Decodable {
            let role: String
            let content: String
        }
    }
}
func callAPI(userInput: String, completion: @escaping (String) -> Void) {
    if let apiKey = Bundle.main.infoDictionary?["API_KEY"] as? String {
        let headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Authorization": "Bearer \(apiKey)"
        ]
        
        let parameters: [String: Any] = [
            "model": "gpt-3.5-turbo",
            "messages": [
                ["role": "user", "content": userInput]
            ],
            "temperature": 0.7
        ]
        
        AF.request("https://api.openai.com/v1/chat/completions", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
            .validate(statusCode: 200..<300)
            .responseDecodable(of: ChatCompletion.self) { response in
                switch response.result {
                case .success(let chatCompletion):
                    if let text = chatCompletion.choices.first?.message.content {
                        completion(text)
                    }
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
    }
}
그리고 API KEY를 관리할 Configuration Settings File을 만드신 다음


이렇게 api key를 저장해 주시면 됩니다.
그리고 빌드 페이지에서 API_KEY 파일 설정 해주시면 됩니다.

그리고 메인 뷰에서 API를 호출하면
//
//  ContentView.swift
//  chatGPTtest
//
//  Created by Byeon jinha on 2023/04/12.
//
import SwiftUI
struct ContentView: View {
    @State private var userInput: String = ""
    @State private var chatResponse: String = ""
    
    var body: some View {
        NavigationView {
            VStack {
                TextField("메시지를 입력하세요", text: $userInput)
                    .padding()
                Button(action: {
                    callAPI(userInput: userInput) { text in
                        chatResponse = text
                    }
                }) {
                    Text("API 호출하기")
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .font(.headline)
                        .cornerRadius(10)
                }
                Text(chatResponse)
                    .padding()
            }
            .navigationBarTitle("ChatGPT")
        }
    }
}
짜잔!!! 버튼을 눌리면 ChatGPT 가 답변해줍니다!!! :) 화이팅!!

이미지 호출까지 실험해본 결과!!! 잘 뜹니다!!!
나머진 시간날 때 한번씩 써봐도 재밌을 것 같아요. :)

728x90
    
    
  반응형
    
    
    
  LIST
    'iOS' 카테고리의 다른 글
| Content hugging과 Compression resistance (0) | 2023.04.12 | 
|---|---|
| intrinsicContentSize (0) | 2023.04.12 | 
| 컬렉션 뷰에서 데이터를 사용할 때 struct?, class? (0) | 2023.04.11 | 
| Static dispatch, Dynamic dispatch (0) | 2023.04.11 | 
| iOS APP 화면 구성 (0) | 2023.04.11 |