如何在Swift中格式化OpenAI API请求?

我需要使用OpenAI API,并且在格式化请求时遇到了困难。我首先参考了OpenAI API playground中列出的curl代码,并且在我的终端中运行成功。该请求如下所示:

curl https://api.openai.com/v1/chat/completions \  -H "Content-Type: application/json" \  -H "Authorization: Bearer $OPENAI_API_KEY" \  -d '{  "model": "gpt-4o",  "messages": [    {      "role": "user",      "content": [        {          "type": "text",          "text": "Write a haiku about weightlifting"        }      ]    }  ],  "temperature": 1,  "max_tokens": 2048,  "top_p": 1,  "frequency_penalty": 0,  "presence_penalty": 0,  "response_format": {    "type": "text"  }}'

然后,我开始将该请求从curl转换为Swift。我参考了一些YouTube教程,以下是我目前的代码。

let openAiUrl = URL(string: "https://api.openai.com/v1/chat/completions")!var request = URLRequest(url: openAiUrl)request.setValue("application/json", forHTTPHeaderField: "Content-Type")request.addValue("Bearer \(openAiApiKey)", forHTTPHeaderField: "Authorization")request.httpMethod = "POST"let httpBody: [String: Any] = [    "messages" : [        {            "role": "user", //Error: consecutive statements on a line must be separated by ';'            "content": "Write a haiku about weightlifting"        }    ],    "model": "gpt-4o",    "max_tokens" : 100,    "temperature": String(temperature),    "frequency_penalty": 0,    "presence_penalty": 0,    "response_format": { //Error: consecutive statements on a line must be separated by ';'        "type": "text"    }]

我在使用大括号的两行代码上收到了“Consecutive statements on a line must be separated by ‘;‘”的错误提示。

我需要做些什么来格式化API请求?温度变量是一个当前设置为1.0的Double类型。


回答:

尝试使用JSONEncoder来编码json参数,如下所示:

            let body = """{                    "messages" : [                        {                            "role": "user",                            "content": "Write a haiku about weightlifting"                        }                    ],                    "model": "gpt-4o",                    "max_tokens" : 100,                    "temperature": 1.0,                    "frequency_penalty": 0,                    "presence_penalty": 0,                    "response_format": {                         "type": "text"                    }}"""                        do {                request.httpBody = try JSONEncoder().encode(body)                let (responseData, response) = try await URLSession.shared.data(for: request)                print("-----> \n \(String(data: responseData, encoding: .utf8) as AnyObject) \n")            } catch {                print("---> error: \(error)")            }

EDIT-1

这是我使用SwiftUI的测试代码。由于我没有密钥,无法完全测试这段代码,但它可以编译并提供一些关于响应的信息。

import SwiftUIstruct ContentView: View {    let openAiApiKey = "for testing"        var body: some View {        Text("testing")            .task {                await doPost()            }    }        func doPost() async {        let openAiUrl = URL(string: "https://api.openai.com/v1/chat/completions")!                var request = URLRequest(url: openAiUrl)        request.setValue("application/json", forHTTPHeaderField: "Content-Type")        request.addValue("Bearer \(openAiApiKey)", forHTTPHeaderField: "Authorization")        request.httpMethod = "POST"                let body = """{"messages": [{"role": "user","content": "Write a haiku about weightlifting"}],"model": "gpt-4o","max_tokens" : 100,"temperature": 1.0,"frequency_penalty": 0,"presence_penalty": 0,"response_format": {     "type": "text"}}"""        do {            request.httpBody = try JSONEncoder().encode(body)                        let (responseData, response) = try await URLSession.shared.data(for: request)            print("-----> responseData \n \(String(data: responseData, encoding: .utf8) as AnyObject) \n")        }        catch { print(error) }    }}

EDIT-2

另一个替代方案,

struct ContentView: View {    let openAiApiKey = "for testing"        var body: some View {        Text("testing")            .task {                let url = URL(string: "https://api.openai.com/v1/chat/completions")!                var request = URLRequest(url: url)                request.httpMethod = "POST"                request.setValue("application/json", forHTTPHeaderField: "Content-Type")                request.setValue("Bearer \(openAiApiKey)", forHTTPHeaderField: "Authorization")                                let requestBody: [String: Any] = [                    "model": "gpt-4o",                    "messages": [                        [                            "role": "user",                            "content": [                                [                                    "type": "text",                                    "text": "Write a haiku about weightlifting"                                ]                            ]                        ]                    ],                    "temperature": 1,                    "max_tokens": 2048,                    "top_p": 1,                    "frequency_penalty": 0,                    "presence_penalty": 0,                    "response_format": [                        "type": "text"                    ]                ]                                do {                    request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)                                        let (responseData, response) = try await URLSession.shared.data(for: request)                    print("-----> responseData \n \(String(data: responseData, encoding: .utf8) as AnyObject) \n")                }                catch { print(error) }                            }    }}

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注