Skip to content

tutorial on amplify and bedrocks do not works

0

the following example:

https://aws.amazon.com/getting-started/hands-on/build-serverless-web-app-lambda-amplify-bedrock-cognito-gen-ai/

dosn't works, the call:

const { data, errors } = await amplifyClient.queries.askBedrock({ ingredients: [formData.get("ingredients")?.toString() || ""], });

initialize errors with:

"path": [ "askBedrock" ], "data": null, "errorType": "Code", "errorInfo": null, "locations": [ { "line": 2, "column": 3, "sourceName": null } ], "message": "code.js:39:13: Uncaught TypeError: Cannot read property '0' of undefined"

It seems that the call to the function askBedrock never happen! I cannot figure out why:

This is all the code in app.ts file:

import { FormEvent, useState } from "react";
import { Loader, Placeholder } from "@aws-amplify/ui-react";
import "./App.css";
import { Amplify } from "aws-amplify";
import { Schema } from "../amplify/data/resource";
import { generateClient } from "aws-amplify/data";
import outputs from "../amplify_outputs.json";
import "@aws-amplify/ui-react/styles.css";
Amplify.configure(outputs);
const amplifyClient = generateClient<Schema>({
  authMode: "userPool",
});
function App() {
  debugger;
  console.log("app =========");
  const [result, setResult] = useState<string>("");
  const [loading, setLoading] = useState(false);
  console.log("app1 =========");
  const onSubmit = async (event: FormEvent<HTMLFormElement>) => {
    console.log("app2 =========");
    event.preventDefault();
    setLoading(true);
    try {
      console.log("app3 =========");
      const formData = new FormData(event.currentTarget);
      const { data, errors } = await amplifyClient.queries.askBedrock({
        ingredients: [formData.get("ingredients")?.toString() || ""],
      });
      if (!errors) {
        console.log("app4 =========");
        setResult(data?.body || "No data returned");
      } else {
        console.log("newLocal");
        console.log(errors);
      }
    } catch (e) {
      console.log("catch =========");
      console.log(e);
      alert(`An error occurred: ${e}`);
    } finally {
      console.log("app5 =========");
      setLoading(false);
    }
  };
  return (
    <div className="app-container">
      <div className="header-container">
        <h1 className="main-header">
          Meet Your Personal
          <br />
          <span className="highlight">Recipe AI</span>
        </h1>
        <p className="description">
          Simply type a few ingredients using the format ingredient1,
          ingredient2, etc., and Recipe AI will generate an all-new recipe on
          demand...
        </p>
      </div>
      <form onSubmit={onSubmit} className="form-container">
        <div className="search-container">
          <input
            type="text"
            className="wide-input"
            id="ingredients"
            name="ingredients"
            placeholder="Ingredient1, Ingredient2, Ingredient3,...etc"
          />
          <button type="submit" className="search-button">
            Generate
          </button>
        </div>
      </form>
      <div className="result-container">
        {loading ? (
          <div className="loader-container">
            <p>Loading...</p>
            <Loader size="large" />
            <Placeholder size="large" />
            <Placeholder size="large" />
            <Placeholder size="large" />
          </div>
        ) : (
          result && <p className="result">{result}</p>
        )}
      </div>
    </div>
  );
}
export default App;

I'm new both on react that on aplify :)

1 Answer
-1

Based on the error you're encountering, it appears there's an issue with how the askBedrock function is being called or how it's defined in your Amplify backend.

The error message "Cannot read property '0' of undefined" suggests that the function is trying to access the first element of an array that doesn't exist. This is likely happening inside the Lambda function that handles the askBedrock query.

Here are a few things to check:

  1. Make sure your Amplify configuration is correct. The error could be related to how you're configuring Amplify in your application.

  2. Check the structure of your amplify_outputs.json file to ensure it contains all the necessary configuration for connecting to your backend.

  3. Verify that the askBedrock function is properly defined in your Amplify backend. The function might be expecting a different parameter structure than what you're providing.

  4. Ensure that your Cognito authentication is set up correctly. The error could be related to authentication issues since you're using authMode: "userPool".

  5. If you're using Amplify Gen 2, make sure your tsconfig.json doesn't include the amplify directory, as this can cause module resolution issues.

A common issue with Amplify configuration is missing the proper nesting structure. For example, when configuring Auth with Cognito, you might need to nest your configuration under a "Cognito" key:

const awsExports = { 
Auth: { 
Cognito: {
region: 'your-region',
userPoolId: 'your-user-pool-id',
userPoolWebClientId: 'your-client-id',
// other auth settings
} 
},
// other configurations
};

Try adding some additional logging in your code to see what values are being passed to the askBedrock function and check your Lambda function implementation to see where it might be trying to access an undefined array.
Sources
Uncaught TypeError: Cannot read properties of undefined (reading 'loginWith') at AmplifyClass.notifyOAuthListener (Amplify.ts:63:49) | AWS re:Post
Troubleshoot "Cannot find module $amplify/env/<function-name>" - AWS Amplify Gen 2 Documentation
AWS Amplify launches the full-stack AI kit for Amazon Bedrock - AWS

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.