OpenAI API调用Python转R代码时stop参数类型错误的解决求助
解决R调用OpenAI API时的stop参数类型错误问题
问题说明
将Python版OpenAI API调用代码转译为R代码后,运行出现以下错误:
"error": {
"message": "Invalid type for 'stop': expected one of a string or array of strings, but got an obje...
"type": "invalid_request_error",
"param": "stop",
"code": "invalid_type" }
错误根源在于R代码中stop参数的序列化结果不符合API要求:Python里的None会被序列化为JSON的null,但R中直接使用NULL并配合auto_unbox=TRUE时,jsonlite会将其转为空对象{},而OpenAI API仅接受字符串、字符串数组,或不传递该参数(即JSON的null)。
修改方案
方案1:直接移除stop参数(推荐)
如果不需要自定义停止序列,直接省略stop = NULL这一行即可,API会使用默认行为。修改后的payload代码如下:
payload <- toJSON(list( messages = list( list( role = "system", content = "You are an AI assistant named Genie the Genious that helps people find information from enterprise documents." ), list( role = "user", content = "how many faces does a cube have?" ), list( role = "assistant", content = "A cube has six faces." ), list( role = "user", content = "What is your name?" ), list( role = "assistant", content = "" ) ), temperature = 0.8, top_p = 1, frequency_penalty = 0, presence_penalty = 0, max_tokens = 60 ), auto_unbox = TRUE)
方案2:使用jsonlite::null()生成合法的JSON null
如果需要明确传递null(对应Python的None),用jsonlite::null()替代NULL,这样序列化后会生成符合要求的JSON null。修改后的payload代码如下:
payload <- toJSON(list( messages = list( list( role = "system", content = "You are an AI assistant named Genie the Genious that helps people find information from enterprise documents." ), list( role = "user", content = "how many faces does a cube have?" ), list( role = "assistant", content = "A cube has six faces." ), list( role = "user", content = "What is your name?" ), list( role = "assistant", content = "" ) ), temperature = 0.8, top_p = 1, frequency_penalty = 0, presence_penalty = 0, max_tokens = 60, stop = jsonlite::null() ), auto_unbox = TRUE)
内容的提问来源于stack exchange,提问作者Steve S
相关产品推荐
相关产品推荐

