Step-by-Step Guide: Build a Generative AI Text Completion App using AWS Amplify
Prerequisites
- AWS Account
- Basic knowledge of React.js, AWS Amplify, and Lambda functions
- OpenAI API Key (Signup at OpenAI and get your API key)
Step 1: Set Up AWS Amplify Project
- Install AWS Amplify CLI: Open your terminal and install the Amplify CLI if you haven’t already:
npm install -g @aws-amplify/cli
Configure Amplify CLI: Run the following command to configure Amplify CLI with your AWS credentials:
amplify configure
- Follow the prompts to sign in to your AWS account and set up your CLI access.
3. Initialize a New Amplify Project: Navigate to your project directory and initialize the Amplify project:
amplify init
Choose the following options:
- Name: generative-ai-app
- Environment: dev
- Editor: Select your editor (e.g., Visual Studio Code)
- Frontend framework: JavaScript
- Framework: React
- Hosting: No for now
4. Install Required Dependencies: Initialize a React project if you don’t have one already:
npx create-react-app generative-ai-app
cd generative-ai-app
npm install aws-amplify
Step 2: Add a Lambda Function via Amplify
- Add Lambda Function: Now, let’s create a Lambda function that will interact with the OpenAI API.
amplify add function
- Choose Lambda function.
- Name: openaiFunction
- Lambda template: Hello World
- Runtime: Node.js
- Lambda Layers: No
- S3 permissions: No
- API Gateway trigger: No (We will add this later)
2. Modify the Lambda Function Code: After adding the function, Amplify will create a folder in your project called amplify/backend/function/openaiFunction/src
. Navigate to this folder and open index.js
. Replace the content with the following code:
const axios = require('axios');
exports.handler = async (event) => {
const prompt = event.arguments.prompt; // This gets the prompt from API input
const apiKey = process.env.OPENAI_API_KEY; // Fetch API key from environment variables
try {
const response = await axios.post('https://api.openai.com/v1/completions', {
model: 'gpt-4',
prompt: prompt,
max_tokens: 50,
}, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
}
});
return response.data.choices[0].text;
} catch (error) {
console.error("Error calling OpenAI API:", error);
throw new Error("Could not generate text completion");
}
};
3. Store the OpenAI API Key in Environment Variables: To securely store your OpenAI API key, set an environment variable in your Lambda function.
- Run the following command
amplify update function
- Select your function (
openaiFunction
). - Choose Environment variables.
- Add a new variable:
- Key:
OPENAI_API_KEY
- Value:
<Your OpenAI API Key>
4. Push the Function to AWS: Push the newly created function to AWS.
amplify push
Step 3: Add GraphQL API for Frontend Communication
- Add an API: Next, we’ll add an API so our React frontend can communicate with the Lambda function.
amplify add api
- API Type: GraphQL
- Authorization Type: API key
- Schema template: Blank schema
2. Update the GraphQL Schema: After adding the API, Amplify creates a file amplify/backend/api/<api-name>/schema.graphql
. Replace the contents with the following:
type Query {
generateText(prompt: String!): String
}
- This schema defines a query (
generateText
) that takes a string input (prompt
) and returns a string output.
3. Connect API to Lambda: Now, connect the GraphQL query to the Lambda function:
amplify update api
- Choose GraphQL.
- Choose Add another function.
- Select your Lambda function (
openaiFunction
) and map it to thegenerateText
query.
4. Push Changes: Push the changes to AWS:
amplify push
Step 4: Build the Frontend with React
- Set Up Amplify in React App: Open the
src/index.js
file and importAmplify
at the top:
import Amplify from 'aws-amplify';
import config from './aws-exports';
Amplify.configure(config);
Create the Text Completion UI: In src/App.js
, replace the content with the following code to create a simple text box, button, and display area for the generated text:
import React, { useState } from 'react';
import { API } from 'aws-amplify';
function App() {
const [prompt, setPrompt] = useState('');
const [result, setResult] = useState('');
const generateText = async () => {
try {
const data = await API.graphql({
query: `query GenerateText($prompt: String!) {
generateText(prompt: $prompt)
}`,
variables: { prompt }
});
setResult(data.data.generateText);
} catch (error) {
console.error("Error generating text:", error);
}
};
return (
<div className="App">
<h1>Generative AI Text Completion</h1>
<input
type="text"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="Enter a prompt"
/>
<button onClick={generateText}>Generate Text</button>
<p>{result}</p>
</div>
);
}
export default App;
3. Install Amplify GraphQL API Library: To ensure GraphQL works in your app, install the following package:
npm install @aws-amplify/api-graphql
Step 5: Deploy the App Using AWS Amplify Hosting
- Add Hosting to Your Project: Run the following command to add Amplify Hosting:
amplify add hosting
- Type: Amazon CloudFront and S3
- Deploy: Yes, build and deploy
- Push Your Code: Deploy your app by running:
amplify publish
Once completed, Amplify will provide a URL where your app is hosted.
Step 6: Test and Demonstrate
- Test the App:
- Open the Amplify-provided URL in your browser.
- Enter a prompt (e.g., “Once upon a time…”) and click “Generate Text”.
- The app will generate a completion using OpenAI’s GPT-4 model.
2. Enhancements (Optional):
- Add styling: Improve UI with CSS or frameworks like Material UI.
- Save prompts: Use Amplify Datastore to save and display previous prompts and completions.
- Add real-time updates: Use AWS AppSync for real-time prompt generation.
Key Takeaways
- Amplify simplifies full-stack development with a quick setup of backend services (API, Lambda).
- The GraphQL API allows seamless communication between the frontend and backend.
- Integrating Generative AI with OpenAI adds an exciting layer of functionality to your app.
- Amplify Hosting makes it easy to deploy and share your app with the world.