You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Cloud Function中通过操作ID查询Speech API的longRunningRecognize状态

用官方SDK优雅查询Speech API长时操作状态

我帮你梳理下更简洁的实现方式,完全不用再手动构造HTTP请求——Google Cloud的Node.js SDK已经提供了现成的工具来处理长时运行操作的状态查询,这才是官方推荐的最佳实践!

1. 先搞定依赖

首先确认你的Cloud Function项目里已经装了这两个包:

npm install @google-cloud/speech @google-cloud/longrunning

@google-cloud/longrunning就是专门处理这类异步操作状态的核心库,和Speech API完美兼容。

2. 用OperationsClient查询状态

你之前困惑的longrunning.operationsClient()在Node.js里是这样正确引入和使用的,而且在Cloud Function里不需要手动传API Key——因为函数会自动用项目的默认服务账号做身份验证,安全又省心。

完整代码示例

const functions = require('firebase-functions');
const speech = require('@google-cloud/speech');
const {OperationsClient} = require('@google-cloud/longrunning');

// 初始化客户端
const speechClient = new speech.SpeechClient({
  projectId: 'my-project-id'
});
const operationsClient = new OperationsClient({
  projectId: 'my-project-id'
});

exports.transcribe = functions.storage.object().onFinalize(async (object) => {
  // 构造转写请求参数
  const payload = {
    audio: {
      uri: `gs://${object.bucket}/${object.name}` // 直接用存储对象的URI,不用硬编码
    },
    config: {
      encoding: 'FLAC',
      languageCode: 'en-US'
    }
  };

  try {
    // 发起长时转写请求
    const [operation] = await speechClient.longRunningRecognize(payload);
    console.log(`生成的操作ID:${operation.name}`);

    // 方式一:在同一个函数里等待操作完成(自动轮询)
    const [finalResult] = await operation.pollUntilComplete();
    console.log('转写结果:', finalResult.results);

    // 方式二:单独查询状态(适合后续在其他函数/流程中查询)
    const [operationStatus] = await operationsClient.getOperation({
      name: operation.name
    });
    console.log('当前操作状态:', operationStatus);
    if (operationStatus.done) {
      console.log('操作完成,结果:', operationStatus.response);
    }
  } catch (err) {
    console.error('出错啦:', err);
  }
});

额外小技巧:直接用SpeechClient的操作对象

其实从longRunningRecognize返回的operation对象本身就带了查询方法,如果你只是要查某个已保存的操作ID,也可以这样写:

// 传入之前保存的操作名称
const [existingOperation] = await speechClient.longRunningRecognizeOperation('your-operation-name');
const metadata = await existingOperation.getMetadata();
console.log('当前状态详情:', metadata);

这样就彻底告别手动拼HTTP请求的麻烦了,代码更简洁也更符合Google Cloud的开发规范。

内容的提问来源于stack exchange,提问作者Peter Gerasimenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:06:20