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?

import Foundation

struct ChatMessage: Identifiable {
    enum Role: String {
        case user
        case assistant
    }
    
    let id = UUID()
    let role: Role
    let content: String
}

class OpenAIService {
    private let apiKey = "YOUR_OPENAI_API_KEY"
    private let endpoint = "https://api.openai.com/v1/chat/completions"
    let model: String = "chatgpt-4o-latest"
    
    func sendChatRequest(messages: [ChatMessage]) async throws -> String {
        
        let messageDictionaries: [[String: String]] = messages.map { msg in
            [
                "role": msg.role.rawValue,
                "content": msg.content
            ]
        }
        
        let requestBody: [String: Any] = [
            "model": model,
            "messages": messageDictionaries,
            "temperature": 0.7
        ]
        
        guard let url = URL(string: endpoint),
              let httpBody = try? JSONSerialization.data(withJSONObject: requestBody) else {
            throw NSError(domain: "Invalid Request", code: 0, userInfo: nil)
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
        request.httpBody = httpBody
        
        let (data, _) = try await URLSession.shared.data(for: request)
        
        guard let json = try? JSONSerialization.jsonObject(with: data),
              let dict = json as? [String: Any],
              let choices = dict["choices"] as? [[String: Any]],
              let firstChoice = choices.first,
              let message = firstChoice["message"] as? [String: Any],
              let content = message["content"] as? String
        else {
            throw NSError(domain: "ChatGPT Error", code: 0, userInfo: nil)
        }
        
        return content.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}

これで答えが返ってくる。

UIをつけたサンプルアプリは以下。

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLを使ったアプリを作っています。
機械学習関連の情報を発信しています。

Twitter
Medium
GitHub

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?