在SAS中集成ChatGPT API时遭遇Content-Type头无效错误
SAS集成ChatGPT时Content-Type错误的解决方案
错误信息
Invalid-Content Type header. Expected application/json
问题根源及修正步骤
你的代码存在3个关键问题,导致请求格式不符合ChatGPT API要求:
1. 宏变量带多余引号
定义chatgpt_api_url和chat_prompt时添加了双引号,PROC HTTP调用时会将引号带入请求,导致URL和参数格式异常,影响Content-Type头的解析。
2. Chat模型Payload格式错误
gpt-3.5-turbo属于Chat Completions接口,必须使用messages数组传递对话内容,而非prompt字段(prompt是文本补全接口的专属参数)。
3. DATA步语法错误
data null;应改为data _null_;,这是SAS中用于生成无输出数据集的关键字,拼写错误会导致数据步执行异常。
修正后的完整代码
%let chatgpt_api_token = sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; %let chatgpt_api_url = https://api.openai.com/v1/chat/completions; %let chat_prompt = Hello, how can I assist you?; /* 定义调用ChatGPT API的SAS宏 */ %macro chat_with_gpt(prompt); /* 准备API请求的JSON payload */ filename payload temp; data _null_; file payload; put '{ "messages": [{"role": "user", "content": "' &prompt '"}], "max_tokens": 50, "model": "gpt-3.5-turbo" }'; run; /* 提交API请求 */ filename response temp; proc http method="POST" url=&chatgpt_api_url in=payload out=response headerout=header; headers "Authorization" = "Bearer &chatgpt_api_token" "Content-Type" = "application/json"; run; /* 读取API响应并保存到SAS数据集 */ data chatgpt_response; length response $32767; infile response lrecl=32767; input; response = _infile_; run; /* 在日志中显示API响应 */ proc print data=chatgpt_response; run; %mend; /* 调用宏发起ChatGPT对话 */ %chat_with_gpt(&chat_prompt);
额外优化说明
- 增加
length response $32767;和lrecl=32767:确保能完整读取较长的JSON响应,避免内容截断。 - 替换
infile为_infile_:SAS中读取当前输入行的正确内置变量是_infile_,原写法会导致变量未定义错误。
内容的提问来源于stack exchange,提问作者stat
相关产品推荐
相关产品推荐

