实现Google Vision PDF检测时遇google.longrunning.Operations URI模板映射错误
这个错误我之前也碰到过,核心原因是你的Operation名称格式和Google API期望的URI模板不匹配。从报错信息能看到,你的Operation名称是projects/riconoscimento-bolletta/operations/192575c87c35529b,但API只接受两种格式:
operations/{operation-id}locations/{location-id}/operations/{operation-id}
下面是具体的解决步骤:
1. 确保异步请求指定了正确的区域Parent
Vision API的异步PDF提取操作现在是区域绑定的,你必须在请求中指定有效的GCP区域(比如us-central1),否则生成的Operation名称格式会不符合API要求。
检查你的代码,确保在创建AsyncBatchAnnotateFilesRequest时,正确设置了parent参数:
// 替换成你的项目ID和区域 $projectId = 'riconoscimento-bolletta'; $location = 'us-central1'; $parent = "projects/{$projectId}/locations/{$location}"; $request = new AsyncBatchAnnotateFilesRequest([ 'parent' => $parent, // 这一行必须存在且正确 'requests' => [ // 你的请求配置(输入输出、特征设置等) ] ]);
指定区域后,生成的Operation名称会变成projects/riconoscimento-bolletta/locations/us-central1/operations/192575c87c35529b,这时候GAX库会自动匹配到locations/*/operations/*的URI模板。
2. 验证Operations客户端的Endpoint
如果你的代码手动创建了OperationsClient来轮询操作状态,需要确保它使用了对应区域的Endpoint,而不是全局Endpoint:
use Google\ApiCore\ApiException; use Google\LongRunning\OperationsClient; // 初始化区域化的Operations客户端 $operationsClient = new OperationsClient([ 'serviceName' => 'vision', 'apiEndpoint' => "{$location}-vision.googleapis.com", ]);
3. 检查依赖库版本
旧版本的google/gax或者google/cloud-vision库可能没有更新URI模板,导致无法解析新格式的Operation名称。运行以下命令检查并更新依赖:
# 查看当前依赖版本 composer show google/cloud-vision composer show google/gax # 更新到最新稳定版 composer update google/cloud-vision google/gax
临时修复:手动修正Operation名称
如果已经生成了格式错误的Operation名称,可以手动提取出Operation ID(比如192575c87c35529b),然后拼接成符合要求的格式:
// 错误的名称 $wrongName = 'projects/riconoscimento-bolletta/operations/192575c87c35529b'; // 提取ID并生成正确的名称 $operationId = explode('/', $wrongName)[3]; $correctName = "locations/us-central1/operations/{$operationId}"; // 用正确的名称轮询状态 $operation = $operationsClient->getOperation($correctName);
内容的提问来源于stack exchange,提问作者ElderTugBoat

