let headers: HTTPHeaders = [
    'Authorization': 'Bearer '+'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',
    'Content-Type': 'application/json'
]

let message : [[String: String]] = [
    ['role': 'system',
    'content': self.requestStr],
    ['role': 'system',
    'content': '我理解你的感受。'],
    ['role': 'system',
    'content': '你做得很好,继续保持积极的态度。']
]

let parameters: Parameters = [
    'model': 'gpt-3.5-turbo',
    'messages': message,
]
print(parameters)
showLoad()
AF.request('https://api.openai.com/v1/chat/completions',method: .post,parameters:parameters,encoding: JSONEncoding.default,headers: headers).response(completionHandler: {response  in
    hidLoad()
    if let data = response.data {
        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
                self.resultLabel.alpha = 1;
                let arr = isArray(json['choices'])
                if(arr.count>0)
                {
                    let data = isDic(arr[0])
                    let lastDic = isDic(data['message']);
                    self.resultLabel.text = isString(lastDic['content'])
                    self.resultLabel.width = SCREEN_WIDTH-wid(20)
                    self.resultLabel.sizeToFit()
                }
                // 转换成功,可以使用json进行操作
                print(json);
            }
        } catch {
            // 转换失败,处理错误
        }
    }
    print('ttt=(response)')
})

上述代码示例展示了如何使用 OpenAI API 实现一个聊天机器人,该机器人能够根据用户输入生成三段式积极回应,包括理解用户的感受、积极鼓励和提供建设性建议。您可以根据需要调整每段回复的字符数,并根据实际情况进行修改。

使用 OpenAI API 实现三段式积极回应的聊天机器人

原文地址: https://www.cveoy.top/t/topic/qqQl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录