We are going to use AWS Amplify to build a serverless web application powered by Generative AI using Amazon Bedrock and the Claude 3 Sonnet foundation. Where user can enter a list of ingredients, and the application will generate delicious recipes based on the input ingredients. The application includes an HTML-based user interface for ingredient submission and a backend web app to request AI generated recipes.
APPLICATION ARCHITECTURE
IMPLEMENTATION
STEP 1: Create a new React application or you can use Vite to create a React application.
To create it you these command.
npm create vite@latest ai-recipe-generator -- --template react-ts -y
cd ai-recipe-generator
npm install
npm run dev
STEP 2: Initialize a GitHub repository name it as ai-recipe-generator and make the repository as public. Then push of the application to the repository(ai-recipe-generator) by using these commands.
git init
git add .
git commit -m "first commit"
git remote add origin git@github.com:/ai-recipe-generator.git
git branch -M main
git push -u origin main
STEP 3: Install the Amplify packages, go to the terminal and the run the command.
npm create amplify@latest -y
After installing amplify package push the changes to the GitHub repository by using
git add .
git commit -m 'installing amplify'
git push origin main
STEP 5: Deploy your app with AWS Amplify.
Go to AWS Amplify in the AWS console and press the create app in the top right corner.
Select GitHub and click Next.
Next, choose the repository and main branch you created earlier. Then select Next.
Leave the default build settings, and select Next.
Review the inputs selected, and choose Save and deploy.
AWS Amplify will now build your source code and deploy your app at https://...amplifyapp.com, and on every git push your deployment instance will update. It may take up to 5 minutes to deploy your app.
Once the build completes, select the Visit deployed URL button to see your web app up and running live.
STEP 6: Setup your Amplifu Auth
On your local machine, navigate to the ai-generated-recipes/amplify/auth/resource.ts file and update it with the following code. Then, save the file.
import { defineAuth } from "@aws-amplify/backend";
export const auth = defineAuth({
loginWith: {
email: {
verificationEmailStyle: "CODE",
verificationEmailSubject: "Welcome to the AI-Powered Recipe Generator!",
verificationEmailBody: (createCode) =>
Use this code to confirm your account: ${createCode()}
,
},
},
});
STEP 7: Setup the Amazon Bedrock Model Access
Sign in to the AWS Management console in a new browser window, and open the AWS Amazon Bedrock console at https://console.aws.amazon.com/bedrock/. Verify that you are in the N. Virginia us-east-1 region, and choose Get started.
In the Foundation models section, choose the Claude model.
Scroll down to the Claude models section, and choose the Claude 3 Sonnet tab, and select Request model access.
In the Base models section, for Claude 3 Sonnet, choose Available to request, and select Request model access.
On the Edit model access page, choose Next.
On the Review and Submit page, choose Submit.
STEP 7: Create a Lambda function for handling requests.
On your local machine, navigate to the ai-recipe-generator/amplify/data folder, and create a file named bedrock.js.
Then, update the file with the following code:
export function request(ctx) {
const { ingredients = [] } = ctx.args;
const prompt = Suggest a recipe idea using these ingredients: ${ingredients.join(", ")}.
;
return {
resourcePath: /model/anthropic.claude-3-sonnet-20240229-v1:0/invoke
,
method: "POST",
params: {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
anthropic_version: "bedrock-2023-05-31",
max_tokens: 1000,
messages: [
{
role: "user",
content: [
{
type: "text",
text: \n\nHuman: ${prompt}\n\nAssistant:
,
},
],
},
],
}),
},
};
}
export function response(ctx) {
const parsedBody = JSON.parse(ctx.result.body);
const res = {
body: parsedBody.content[0].text,
};
return res;
}
STEP 8: Add Amazon Bedrock as a data source.
Update the amplify/backend.ts file with the following code. Then, save the file.
import { defineBackend } from "@aws-amplify/backend";
import { data } from "./data/resource";
import { PolicyStatement } from "aws-cdk-lib/aws-iam";
import { auth } from "./auth/resource";
const backend = defineBackend({
auth,
data,
});
const bedrockDataSource =
backend.data.resources.graphqlApi.addHttpDataSource(
"bedrockDS",
"https://bedrock-runtime.us-east-1.amazonaws.com",
{
authorizationConfig: {
signingRegion: "us-east-1",
signingServiceName: "bedrock",
},
}
);
bedrockDataSource.grantPrincipal.addToPrincipalPolicy(
new PolicyStatement({
resources: [
"arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3- sonnet-20240229-v1:0",
],
actions: ["bedrock:InvokeModel"],
})
);
STEP 9: Setup Amplify Data.
- On your local machine, navigate to the ai-recipe-generator/amplify/data/resource.ts file, and update it with the following code. Then, save the file.
import { type ClientSchema, a, defineData } from "@aws-amplify/backend";
const schema = a.schema({
BedrockResponse: a.customType({
body: a.string(),
error: a.string(),
}),
askBedrock: a
.query()
.arguments({ ingredients: a.string().array() })
.returns(a.ref("BedrockResponse"))
.authorization((allow) => [allow.authenticated()])
.handler(
a.handler.custom({ entry: "./bedrock.js", dataSource: "bedrockDS" })
),
});
export type Schema = ClientSchema;
export const data = defineData({
schema,
authorizationModes: {
defaultAuthorizationMode: "apiKey",
apiKeyAuthorizationMode: {
expiresInDays: 30,
},
},
});
- Open a new terminal window, navigate to your apps project folder (ai-recipe-generator), and run the following command to deploy cloud resources into an isolated development space so you can iterate fast.
npx ampx sandbox
- Once the cloud sandbox has been fully deployed, your terminal will display a confirmation message and the amplify_outputs.json file will be generated and added to your project.
STEP 10: Install the Amplify libraries
Open a new terminal window, navigate to your projects root folder (ai-recipe-generator), and run the following command to install the libraries.
npm install aws-amplify @aws-amplify/ui-react
STEP 11: Style the App UI.
On your local machine, navigate to the ai-recipe-generator/src/index.css file, and update it with the following code to center the App UI. Then, save the file.
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color: rgba(255, 255, 255, 0.87);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
.box:nth-child(3n + 1) {
grid-column: 1;
}
.box:nth-child(3n + 2) {
grid-column: 2;
}
.box:nth-child(3n + 3) {
grid-column: 3;
}
Update the src/App.css file with the following code to style the ingredients form. Then, save the file.
.app-container {
margin: 0 auto;
padding: 20px;
text-align: center;
}
.header-container {
padding-bottom: 2.5rem;
margin: auto;
text-align: center;
align-items: center;
max-width: 48rem;
}
.main-header {
font-size: 2.25rem;
font-weight: bold;
color: #1a202c;
}
.main-header .highlight {
color: #2563eb;
}
@media (min-width: 640px) {
.main-header {
font-size: 3.75rem;
}
}
STEP 12: Implement the UI.
- On your local machine, navigate to the ai-recipe-generator/src/main.tsx file, and update it with the following code. Then, save the file.
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
import { Authenticator } from "@aws-amplify/ui-react";
ReactDOM.createRoot(document.getElementById("root")!).render(
React.StrictMode
Authenticator
App
/Authenticator
/React.StrictMode
);
- Open the ai-recipe-generator/src/App.tsx file, and update it with the following code. Then, save the 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({
authMode: "userPool",
});
function App() {
const [result, setResult] = useState("");
const [loading, setLoading] = useState(false);
const onSubmit = async (event: FormEvent) => {
event.preventDefault();
setLoading(true);
try {
const formData = new FormData(event.currentTarget);
const { data, errors } = await amplifyClient.queries.askBedrock({
ingredients: [formData.get("ingredients")?.toString() || ""],
});
if (!errors) {
setResult(data?.body || "No data returned");
} else {
console.log(errors);
}
} catch (e) {
alert(An error occurred: ${e}
);
} finally {
setLoading(false);
}
};
return (
div className="app-container"
div className="header-container"
h1 className="main-header"
Meet Your Personal
br
span className="highlight">Recipe AI
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"
Generate
button
form
div className="result-container"
{loading ? (
div className="loader-container"
Loading...
Loader size="large"
Placeholder size="large"
Placeholder size="large"
Placeholder size="large"
div
) : (
result &&
{result}
)}
);
}
export default App;
- Open a new terminal window, navigate to your projects root directory (ai-recipe-generator), and run the following command to launch the app:
npm run dev
Select the Local host link to open the Vite + React application.
Choose the Create Account tab, and use the authentication flow to create a new user by entering your email address and a password. Then, choose Create Account.
You will get a verification code sent to your email. Enter the verification code to log in to the app.
When signed in, you can start inputting ingredients and generating recipes.
In the open terminal window, run the following command to push the changes to GitHub:
git add .
git commit -m 'connect to bedrock'
git push origin main
Sign in to the AWS Management console in a new browser window, and open the AWS Amplify console at https://console.aws.amazon.com/amplify/apps.
AWS Amplify automatically builds your source code and deployed your app at https://...amplifyapp.com, and on every git push your deployment instance will update. Select the Visit deployed URL button to see your web app up and running live.
STEP 12: Clean up all resources.
Top comments (0)