使用ChatGPT API上传PDF检测指定单词失败,模型未识别文件求助
问题:ChatGPT API无法识别已上传的PDF文件进行内容查询
问题描述
我尝试通过ChatGPT API上传PDF文件,查询其中是否包含指定单词,但模型未识别到已上传的文件。上传文件后能获取到有效的文件ID(例如file-lbNMtTgJHW01QZxRZXarx2Ve),但发起查询请求时,模型返回如下提示:
For me to help you determine if a file contains the expressed word you must provide the contents of the file or a file
在线版ChatGPT的文件分析功能可正常使用。
上传文件代码(PHP)
$ch = curl_init('https://api.openai.com/v1/files'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $api_key)); curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'purpose' => 'assistants', 'file' => new CURLFile($pdfFile), )); $response_upload = curl_exec($ch); $info_upload = curl_getinfo($ch); curl_close($ch);
原查询请求代码(PHP)
$file_id = 'file-lbNMtTgJHW01QZxRZXarx2Ve'; $data = array( 'model' => $model, 'messages' => array( array('role' => 'system', 'content' => 'Vous êtes un assistant'), array( 'role' => 'user', 'content' => 'Does this PDF file contain the word XXXX', 'file_ids' => [$file_id] )) ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ));
问题原因及解决方案
核心问题:请求数据结构错误
你将file_ids参数放在了用户消息的数组内部,而ChatGPT API要求file_ids是与model、messages同级的顶层参数。
修正后的查询代码
$file_id = 'file-lbNMtTgJHW01QZxRZXarx2Ve'; // 修正数据结构:file_ids移到顶层 $data = array( 'model' => $model, // 确保使用支持文件检索的模型,如gpt-4o、gpt-4-turbo 'messages' => array( array('role' => 'system', 'content' => 'Vous êtes un assistant'), array( 'role' => 'user', 'content' => 'Does this PDF file contain the word XXXX' ) ), 'file_ids' => [$file_id] // 正确位置:顶层参数 ); $ch = curl_init('https://api.openai.com/v1/chat/completions'); // 确保API地址正确为聊天补全接口 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key )); $response = curl_exec($ch); curl_close($ch);
额外注意事项
- 模型兼容性:必须使用支持文件检索的模型,比如
gpt-4o、gpt-4-turbo-2024-04-09等,gpt-3.5-turbo部分版本不支持该功能。 - 文件状态验证:上传文件后,可调用
GET /v1/files/{file_id}接口检查文件状态是否为processed,只有处理完成的文件才能被模型检索。 - API地址正确性:确保查询请求的API地址为
https://api.openai.com/v1/chat/completions(聊天补全接口),而非其他接口。
内容的提问来源于stack exchange,提问作者WebShaker
相关产品推荐
相关产品推荐

