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

React中使用TensorFlow QnA模型报错TypeError: context.trim is not a function

解决TensorFlow QnA模型的TypeError: context.trim is not a function问题

核心问题:参数顺序颠倒

TensorFlow QnA模型的findAnswers方法参数顺序是先传问题(question),再传上下文(context),你当前把用户输入的问题当成context传入,第二个参数传了数字1,导致模型内部把数字1当作context去调用trim方法,触发类型错误。

修改后的代码

调整findAnswers的参数顺序,同时补充模型所需的上下文文本(QnA是抽取式模型,必须基于给定文本提取答案,无法凭空生成):

const handleInputSubmit = async (event) => {
    event.preventDefault();
    if (qnaModel) {
      // 替换为你的实际上下文文本(比如学习材料内容)
      const context = "这里放置模型用于查找答案的上下文文本";
      const question = String(input).trim();

      console.log(typeof context, typeof question);
      // 修正参数顺序:question在前,context在后
      const answers = await qnaModel.findAnswers(question, context);
      console.log(answers[0].question); 
      console.log(answers[0].answer); 

      setCards([
        ...cards,
        { question: question, answer: answers[0].answer },
      ]);
    } else {
      console.error("qnaModel is not ready yet");
    }
  };

额外注意事项

  • QnA模型是抽取式问答,必须提供一段上下文文本作为答案来源,无法脱离文本生成答案,你之前的逻辑缺少必要的上下文传入。
  • 确保qnaModel的加载逻辑正确,调用findAnswers前模型已完全初始化完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:35:28