I am working on a React app that uses the TensorFlow QnA model to generate study cards based on user input. I have implemented a form in which the user can enter a question, and upon submission, the app should use the QnA model to generate an answer and create a new study card with the question and answer.
However, when I try to submit the form, I am getting the following error: “TypeError: context.trim is not a function”. After some investigation, I determined that this error is occurring in the QnA model’s process function, which is called by the findAnswers function.
Here is the relevant code for the form submission and the use of the QnA model:
import * as qna from "@tensorflow-models/qna";
import * as tf from "@tensorflow/tfjs";
//...
const [qnaModel, setQnAModel] = useState(null);
//...
const handleInputChange = (event) => {
setInput(event.target.value.toString());
};
// ...
const handleInputSubmit = async (event) => {
event.preventDefault();
if (qnaModel) {
// Make sure that the `context` parameter is a string
let context = String(input).trim();
// model => ready
console.log(typeof context);
const answers = await qnaModel.findAnswers(context, 1);
console.log(answers[0].question);
console.log(answers[0].answer);
setCards([
...cards,
{ question: answers[0].question, answer: answers[0].answer },
]);
} else {
// The qnaModel is not ready yet, so you should not try to use it
console.error("qnaModel is not ready yet");
}
};
I have verified that the context variable is indeed a string by logging its type to the console. However, the error is still occurring.
Has anyone else encountered this error or have any ideas on how to fix it? Any help would be greatly appreciated!
Thanks in advance.
According to the documentation, the reason you're seeing that error is because you're not passing the right parameters to
findAnswers
. The format should be the following:where there first parameter is the question being asked and the second parameter is the passage from which the question is based. Right now you're passing just the number
1
as the passage.The documentation provides the following example:
Also note that the format in which you're trying to access the answer (
answers[0].question
) doesn't alight to the result you will get. The above documentation example logs the following result:Based on the way your code is written, if you want to access the answer, you would use
answers[0].text
.