deasy 21
deasy 21

Reputation: 1

i am getting a 400 error when trying to use the clarifai api form the back end

i am getting a 404 and another error when i try to run my app, it is a face recognition api from clarifai TypeError: Cannot read properties of undefined (reading '0') at App.calculateFaceLocation (App.js:82:1) at App.js:128:1 this is the second error can anyone help this is a code snippet

   onButtonSubmit = () => {
    this.setState({imageUrl: this.state.input});
    app.models.predict('face-detection', req.body.input)
    fetch('http://localhost:3000/imageurl', {
      method: 'post',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
          input: this.state.input
      })
     })
     .then(response => response.json())
       .then(response => {
        if (response) {
          fetch('http://localhost:3000/image', {
          method: 'put',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
              id: this.state.user.id
          })
         })
          .then(response => response.json())
          .then(count => {
            this.setState(Object.assign(this.state.user, { entries: count }))
          })
          .catch(console.log)
          
        }
        this.displayFaceBox(this.calculateFaceLocation(response))
      })
      .catch(err => console.log(err));
  }

in the console i get an error in the first fetch line imageurl

i tried using chat gpt but i get no errors when debugging the code i tried the old way and the new way of using the clarifai api and i get the same error

Upvotes: 0

Views: 139

Answers (2)

<!-- Chatbot API ChatGPT -->
<script>
    //Atribui os elementos do frontend as variáveis
    const inputQuestion = document.getElementById("inputQuestion");
    inputQuestion.focus();
    const result = document.getElementById("result");
    const OPENAI_API_KEY = "SUA_CHAVE_AQUI";

    //Chama a função SendQuestion() após dar ENTER no campo de perguntas
    inputQuestion.addEventListener("keypress", (e) => {
      if (inputQuestion.value && e.key === "Enter")
            if(inputQuestion.value == "CLS" || inputQuestion.value == "cls"){
                document.getElementById("result").value = "";
                document.getElementById("inputQuestion").value = "";
                inputQuestion.focus();
            } else{
                SendQuestion();
            } 
    });    

    //Função para consumir a api chatGPT
    function SendQuestion() {
      var sQuestion = inputQuestion.value.trim(); // remover espaços em branco no início e no fim
      inputQuestion.value = "Carregando...";    

      fetch('https://api.openai.com/v1/completions', {// envia uma solicitação para o endpoint
        method: 'POST',// método da solicitação é POST
        headers: {// define os cabeçalhos da solicitação
          Accept: "application/json",// indica que o cliente espera uma resposta em JSON
          "Content-Type": "application/json",// indica que o corpo da solicitação é um JSON
          Authorization: "Bearer " + OPENAI_API_KEY,// inclui a chave de API no cabeçalho da solicitação
        },
        body: JSON.stringify({// corpo da solicitação, convertido para JSON
          model: "text-davinci-003",// define o modelo de linguagem usado para gerar as respostas
          prompt: sQuestion,// define a pergunta para a qual a resposta é gerada
          max_tokens: 2048, // tamanho de caracteres máximos da resposta
          temperature: 1.0, // criatividade na resposta (maior = mais criativo)
          //n: 3, // numero maximo de respostas
          frequency_penalty: 0.5,// define a penalidade de frequência para reduzir a repetição de palavras
          presence_penalty: 0.5,// define a penalidade de presença para reduzir a geração de palavras irrelevantes
          best_of: 1 // define o número de modelos a serem avaliados, escolhendo o melhor entre eles
        }),
      })
        .then((response) => response.json())
        .then((json) => {
          if (result.value) result.value;

          if (json.error?.message) {
            result.value += `Error: ${json.error.message}`;
          } else if (json.choices?.[0].text) {
            var text = json.choices[0].text || "Sem resposta";
            result.value += `\n\n${sQuestion.toUpperCase()} ${text}`;
          }

          result.scrollTop = result.scrollHeight;
        })
        .catch((error) => console.error("Error:", error))
        .finally(() => {
          inputQuestion.value = "";
          inputQuestion.disabled = false;
          inputQuestion.focus();
        });

      if (result.value) 
        result.value += "\n\n.....................................";
        //result.value += `Eu: ${sQuestion}`;  
        inputQuestion.value = "Carregando...";
        inputQuestion.disabled = true;
        result.scrollTop = result.scrollHeight;
    }
</script>
    .content {
        display: flex;
        flex-direction: column;
        justify-content: center; /* ou flex-start ou flex-end*/
        height: -webkit-fill-available;
    }

    .text_resposta {
        border: none;
        padding: 8px;
        background-color: rgba(52,53,65,1);
        color: #d1d5db;
        outline: none;
        font-size: 16px;
        text-align: start;
        height: 100%; /* ou 60vh ou 50% ou outra medida relativa*/
    }

    .text_pergunta {
        border: none;
        padding: 8px;
        background-color: rgba(68,70,84,1);
        color: #d1d5db;
        outline: none;
        font-size: 16px;
        text-align: start;
        height: 100%; /* ou 60vh ou 50% ou outra medida relativa*/
    }

    .text_pergunta:focus {
        border: 1px solid #8257e5;
    }
<section class="content">
  <div class="container-fluid">
    <div class="row">

      <!-- Quadro esquerdo -->
      <div class="col-lg-12" style="height: CALC(100vh - 156px);">
        <div class="card" style="height: CALC(100%);">

          <!-- Ocupação Porta palete mensal -->
          <div class="card-body" style="height: CALC(100%);padding: 0rem">
            <div class="position-relative" style="height: CALC(100%);"><div class="chartjs-size-monitor"><div class="chartjs-size-monitor-expand"><div class=""></div></div><div class="chartjs-size-monitor-shrink"><div class=""></div></div></div>
              <div class="content">
                <textarea class="text_resposta" id="result" rows="10" disabled placeholder="Resposta da IA" style="height: 80%;"></textarea>
                <textarea class="text_pergunta"id="inputQuestion" placeholder="Pergunte algo aqui" style="height: 20%;"></textarea>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

Upvotes: -1

Jasoya
Jasoya

Reputation: 66

The issue seems to be unrelated with how you implement the Clarifai API. It seems you are trying to access a variable that you have not declared yet. Ensure the data from Clarifai is loaded before trying to access it.

Upvotes: 0

Related Questions