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

使用输入Schema验证时Firebase Function onFlow抛出ZodError: invalid_type

解决Genkit onFlow Zod验证输入未定义问题

我使用Firebase Cloud Functions结合@genkit-ai库,通过onFlow创建了名为menuSuggestionFlow的流程,并使用Zod schema做输入验证。但调用流程时,无论用哪种传参方式,都收到ZodError提示输入未定义。

相关代码

import { z } from '@genkit-ai/core/schema';
import { onFlow, noAuth } from '@genkit-ai/firebase/functions';

// 定义输入Schema
export const ChatSessionInputSchema = z.object({
  question: z.string(),
});

export const menuSuggestionFlow = onFlow(
  {
    name: "menuSuggestionFlow",
    inputSchema: ChatSessionInputSchema, // 应用验证Schema
    authPolicy: noAuth(),
  },
  async (subject) => {
    console.log(`Validated subject: ${JSON.stringify(subject)}`);

    if (!subject || !subject.question) {
      throw new Error("The 'question' field is required.");
    }

    const answer = `This is the answer to your question: ${subject.question}`;
    return { answer };
  }
);

尝试过的错误调用方式

// 方式1:用data字段包裹
menuSuggestionFlow({ data: { question: "What is the menu suggestion for today?" } })
// 方式2:直接传对象
menuSuggestionFlow( { question: "What is the menu suggestion for today?" } )

问题原因

Genkit的onFlow流程在调用时,会从传入参数的input属性中读取待验证的数据,而不是直接读取参数本身或data字段。之前的两种调用方式都没有符合这个结构要求,导致Zod验证时拿到的输入是undefined,从而抛出错误。

解决方案

调用流程时,必须将输入数据放在input字段中,正确的调用方式如下:

// 正确调用方式:用input字段包裹输入数据
menuSuggestionFlow({ 
  input: { question: "What is the menu suggestion for today?" } 
})

如果是通过HTTP请求触发Firebase Cloud Function来调用该流程,请求体也需要遵循同样的结构:

{
  "input": {
    "question": "What is the menu suggestion for today?"
  }
}

验证说明

修改调用方式后,Zod会正确读取input中的question字段完成验证,流程会正常执行,subject参数也会拿到验证后的{ question: "xxx" }对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:12:39