Learn about Gadget's built-in AI features such as the OpenAI connection, vector databases, and cosine similarity search, and use them to build a chatbot that generates custom movie scenes.
You can fork this Gadget project and try it out yourself.
Create a new Gadget app
Before we get started we need to create a new Gadget app. We can do this at gadget.new. When selecting an app template, make sure you select the Web app type.
Now that we have a new Gadget app, let's start building!
Step 1: Create a movie model
The first thing we need to do is store some movie quotes in our Gadget app. We're going to make use of Gadget's data models, which are similar to tables in a Postgres database, to store this information.
Start by creating a new model in Gadget:
Click the + button in the api/models folder of the sidebar
Enter movie as the model's API identifier
Now add some fields to your model. Fields are similar to columns in a database table, and allow you to define what kind of data is stored in your model. For our movie model, we'll add the following fields:
Select schema in the api/models/movie folder
Click + in the FIELDS section
Enter title as the field's API identifier
Click on the + Add Validations drop-down and select Required to make the title field Required
Adding a Required validation to title means that an error will be thrown if a movie is added without a title. Now let's add a field to store the movie's quotes:
Select schema in the movie model's folder
Click + in the FIELDS section
Enter quote as the field's API identifier
Click on the + Add Validations drop-down and select Required to make the quote field Required
Now we have a place to store movie quotes! We also need a field used to store vector embeddings. Vector embeddings are a way of representing text as a vector of numbers. To learn more about vector embeddings, check out our docs on building AI apps.
Select schema in the movie model's folder
Click + in the FIELDS section
Enter embedding as the field's API identifier
Select vector as the field's type
That is all that we need to store data for our app! Now we need a way to generate embeddings. Luckily, OpenAI has an API that we can use to pass in text and get back a vector embedding.
Step 2: Add the OpenAI connection
Gadget has built-in connections to popular APIs, including OpenAI. You can use these connections to interact with external services in your app.
Click on Settings in the sidebar
Click on Plugins
Select OpenAI from the list of plugins
Use the Gadget development keys so you can start using the OpenAI API without an API key
We need some test data for our app. We're going to use a globally-scoped action to fetch an open data source hosted on Hugging Face. We will then use the OpenAI connection to generate embeddings for our movie quotes.
Click the + next to the api/actions folder to create a new globally-scoped action
Name the action file fetchMovies.js
Our OpenAI connection is already set up for us using Gadget-managed credentials. To learn more about how to set up your own OpenAI connection, check out our OpenAI connection docs.
Free OpenAI credits to get you started
Teams in Gadget get free OpenAI credits to use for experimenting during development! Using Gadget-managed OpenAI credentials automatically
draws from this credit pool.
Enter the following code in the generated code file (replace the entire file):
api/actions/fetchMovies.js
JavaScript
import type { GadgetRecord, Movie } from "@gadget-client/your-app-url-here"; // Replace with your app package
type HuggingFaceMovie = {
row: {
movie: string;
quote: string;
type: string;
year: number;
};
row_idx: number;
truncated_cells: any[];
embedding: number[];
};
export const run: ActionRun = async ({ params, logger, api, connections }) => {
const response = await fetch(
"https://datasets-server.huggingface.co/first-rows?dataset=ygorgeurts%2Fmovie-quotes&config=default&split=train",
{
method: "GET",
headers: { "Content-Type": "application/json" },
}
);
const responseJson = await response.json();
if (responseJson?.rows) {
// get the data in our record's format
const movies: GadgetRecord<Movie>[] = responseJson.rows.map(
(movie: HuggingFaceMovie) => ({
title: movie.row.movie,
quote: movie.row.quote,
embedding: [],
})
);
// also get input data for the OpenAI embeddings API
const input: string[] = responseJson.rows.map(
(movie: HuggingFaceMovie) =>
`${movie.row.quote}, from the movie ${movie.row.movie}`
);
const embeddings = await connections.openai.embeddings.create({
input,
model: "text-embedding-ada-002",
});
// append embeddings to movies
embeddings.data.forEach((movieEmbedding, i) => {
movies[i].embedding = movieEmbedding.embedding;
});
// use the internal API to bulk create movie records
await api.internal.movie.bulkCreate(movies);
}
};
import type { GadgetRecord, Movie } from "@gadget-client/your-app-url-here"; // Replace with your app package
type HuggingFaceMovie = {
row: {
movie: string;
quote: string;
type: string;
year: number;
};
row_idx: number;
truncated_cells: any[];
embedding: number[];
};
export const run: ActionRun = async ({ params, logger, api, connections }) => {
const response = await fetch(
"https://datasets-server.huggingface.co/first-rows?dataset=ygorgeurts%2Fmovie-quotes&config=default&split=train",
{
method: "GET",
headers: { "Content-Type": "application/json" },
}
);
const responseJson = await response.json();
if (responseJson?.rows) {
// get the data in our record's format
const movies: GadgetRecord<Movie>[] = responseJson.rows.map(
(movie: HuggingFaceMovie) => ({
title: movie.row.movie,
quote: movie.row.quote,
embedding: [],
})
);
// also get input data for the OpenAI embeddings API
const input: string[] = responseJson.rows.map(
(movie: HuggingFaceMovie) =>
`${movie.row.quote}, from the movie ${movie.row.movie}`
);
const embeddings = await connections.openai.embeddings.create({
input,
model: "text-embedding-ada-002",
});
// append embeddings to movies
embeddings.data.forEach((movieEmbedding, i) => {
movies[i].embedding = movieEmbedding.embedding;
});
// use the internal API to bulk create movie records
await api.internal.movie.bulkCreate(movies);
}
};
This code:
uses fetch to pull in a small sample dataset that stores movie quotes hosted on Hugging Face
loops through the returned data and creates a new movie record for each movie quotes
uses the OpenAI connection (connections.openai) to generate embeddings for each movie quote
uses your Gadget app's internal API to bulk create movie records with the generated embeddings
Now we can run our globally-scoped action to ingest the data:
Click on the Run Action button to open your action in the API Playground
Run the action
The action will be run and a success message is returned once data has been added to the database.
We can also see the data in our Gadget database by:
Clicking on api/models/movie/data
You should see movie records, complete with title, quote, and embedding data!
Now that we have data in our database, we are ready to build the user-facing portion of our app.
Step 4: Use a globally-scoped action to find similar movie quotes
Our app will allow users to enter a fake movie quote and find movie quotes that are similar to the entered text using a similarity search on the embeddings. We will use a global action to find the top 4 most similar movie quotes, and then present these movies to the user.
We can create a new globally-scoped action:
Click the + next to the api/actions folder to create a new globally-scoped action
Name the action file findSimilarMovies.js
Enter the following code in the generated code file (replace the entire file):
api/actions/findSimilarMovies.js
JavaScript
export const run: ActionRun = async ({ params, logger, api, connections }) => {
const { quote } = params;
// throw an error if a quote wasn't passed in
if (!quote) {
throw new Error("Missing quote!");
}
// create an embedding from the entered quote
const response = await connections.openai.embeddings.create({
input: quote,
model: "text-embedding-ada-002",
});
// get the 4 most similar movies that match your quote, and return them to the frontend
const movies = await api.movie.findMany({
sort: {
embedding: {
cosineSimilarityTo: response.data[0].embedding,
},
},
first: 4,
select: {
id: true,
title: true,
},
});
// remove duplicates
const options = movies.filter(
(movie, index) => movies.findIndex((m) => m.title === movie.title) === index
);
return { options, quote };
};
export const params = {
quote: { type: "string" },
};
export const run: ActionRun = async ({ params, logger, api, connections }) => {
const { quote } = params;
// throw an error if a quote wasn't passed in
if (!quote) {
throw new Error("Missing quote!");
}
// create an embedding from the entered quote
const response = await connections.openai.embeddings.create({
input: quote,
model: "text-embedding-ada-002",
});
// get the 4 most similar movies that match your quote, and return them to the frontend
const movies = await api.movie.findMany({
sort: {
embedding: {
cosineSimilarityTo: response.data[0].embedding,
},
},
first: 4,
select: {
id: true,
title: true,
},
});
// remove duplicates
const options = movies.filter(
(movie, index) => movies.findIndex((m) => m.title === movie.title) === index
);
return { options, quote };
};
export const params = {
quote: { type: "string" },
};
Finding similar vectors with cosine similarity
This api.movie.findMany call from the above function is the key to finding similar movies:
JavaScript
// get the 4 most similar movies that match your quote, and return them to the frontend
const movies = await api.movie.findMany({
sort: {
embedding: {
cosineSimilarityTo: response.data[0].embedding,
},
},
first: 4,
select: {
id: true,
title: true,
},
});
// get the 4 most similar movies that match your quote, and return them to the frontend
const movies = await api.movie.findMany({
sort: {
embedding: {
cosineSimilarityTo: response.data[0].embedding,
},
},
first: 4,
select: {
id: true,
title: true,
},
});
Gadget has built-in vector distance sorting which we use to get the most similar vectors to the user's entered text. We use the cosineSimilarityTo operator to find the cosine similarity between the user's entered text and the movie quotes in our database.
Step 5: Add a route to generate a scene
Now for the final backend development step: adding an HTTP route to our Gadget app that will be called by the frontend to generate a scene. We make use of Gadget's OpenAI connection to generate a scene using the user's entered text and a movie quote.
Why not use a globally-scoped action?
We used a globally-scoped action to ingest data and find similar movies, but we're using a route to generate a scene. You might be asking yourself why?
There are two main reasons:
Globally-scoped actions do not support streaming responses, and we want to stream the text returned from OpenAI to the frontend
The openAIResponseStream helper we are using integrates seamlessly with HTTP routes
In general, we suggest you use globally-scoped actions over HTTP routes whenever possible. But when streaming or integrating with external systems or packages, HTTP routes can be a better choice. To read more about when to use each, see the Actions guide.
Add a api/routes/POST-chat.js HTTP route file to your app and paste the following code:
api/routes/POST-chat.js
JavaScript
import { RouteHandler } from "gadget-server";
import { openAIResponseStream } from "gadget-server/ai";
/**
* Route handler for POST chat
*
* See: https://docs.gadget.dev/guides/http-routes/route-configuration#route-context
*/
const route: RouteHandler<{
Body: {
quote: string;
movie: string;
};
}> = async ({ request, reply, api, logger, connections }) => {
const { quote, movie } = request.body;
const prompt = `Here is a fake movie quote: "${quote}" and a movie selected by a user: "${movie}". Write a fake scene for that movie that makes use of the quote. Use a maximum of 150 words.`;
// get streamed response from OpenAI
const stream = await connections.openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: `You are an expert, hilarious AI screenwriter tasked with generating funny, quirky movie scripts.`,
},
{ role: "user", content: prompt },
],
stream: true,
});
await reply.send(openAIResponseStream(stream));
};
export default route;
import { RouteHandler } from "gadget-server";
import { openAIResponseStream } from "gadget-server/ai";
/**
* Route handler for POST chat
*
* See: https://docs.gadget.dev/guides/http-routes/route-configuration#route-context
*/
const route: RouteHandler<{
Body: {
quote: string;
movie: string;
};
}> = async ({ request, reply, api, logger, connections }) => {
const { quote, movie } = request.body;
const prompt = `Here is a fake movie quote: "${quote}" and a movie selected by a user: "${movie}". Write a fake scene for that movie that makes use of the quote. Use a maximum of 150 words.`;
// get streamed response from OpenAI
const stream = await connections.openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: `You are an expert, hilarious AI screenwriter tasked with generating funny, quirky movie scripts.`,
},
{ role: "user", content: prompt },
],
stream: true,
});
await reply.send(openAIResponseStream(stream));
};
export default route;
The OpenAI connection is used to call the chat completions endpoint, which generates a scene from the user's selected movie and entered quote.
Now we can call this route from our frontend to generate a scene!
Step 6: Build the frontend
Now that we have defined our globally-scoped actions and HTTP route, we can add support to call them from the frontend.
Gadget's React frontends are built on top of Vite, and include support for email/password auth as well as Google Auth. Our frontend code lives in the web folder. We will only be making changes to a single frontend route, web/routes/_public._index.jsx, which is the route accessed when a user is signed in to our app.
Paste the following code into web/routes/_public._index.jsx:
The frontend has 3 components: the default export for the route, the AutoForm component, and the /chat HTTP route. These 3 components all make use of different @gadgetinc/react hooks that help us make requests and manage our form state. The hooks simplify the management of response and form state, and let us interact with responses and forms in a React-ful way through the returned data, fetching, and error objects.
the route's default export contains an <AutoButton /> which is an AutoComponent that calls the fetchMovies globally-scoped action (if you haven't already done so!) (more info on AutoButton)
the AutoFormAutoComponent manages and submits the input form for the entered quote, and calls the findSimilarMovies globally-scoped action (more info on AutoForm) which then allows users to select a movie from the returned actionData
the index page makes a request to the /chat HTTP route using the useFetch hook (more info on useFetch) and displays a streamed response
Test your screenwriter
We are done building! Let's test out the AI screenwriter.
Click Preview in the top right corner of the Gadget UI
Sign-up and sign-in to your app, enter a fake movie quote, select a recommended movie, and watch as the AI screenwriter generates a new scene!
The final step is deploying to production.
Step 7 (Optional): Deploy to Production
If you want to deploy a Production version of your app, you can do so in just a couple of clicks!
First, you need to use your own OpenAI API key in the OpenAI connection:
Click on the Settings section in the left sidebar
Click on the Plugins tab
Select the OpenAI connection
Edit the connection and use your API key for the Production environment
Now, deploy your app to Production:
Click on the Deploy button in the top right corner of the Gadget UI
Click Deploy Changes
That's it! Your app will be built, optimized, and deployed!
You can preview your Production app:
Click on the app name at the top of the left sidebar
Click the environment selector in the left corner and from the dropdown click on Production
Alternatively, you can remove --development from the domain of the window you were using to preview your frontend changes while developing.
Next steps
Congrats! You've built a full-stack web app that makes use of generative AI and vector embeddings! 🎉
In this tutorial, we learned:
How to create and store vector fields in Gadget
How to stream chat responses from OpenAI to a Gadget frontend using Vercel's AI SDK
When to use globally-scoped actions vs routes in Gadget
Questions?
If you have any questions, feel free to reach out to us on Discord to ask Gadget employees or the Gadget developer community!