solution: metadata: id: data-connect-grounded-agents title: Grounded AI agents with Firebase Data Connect and your SQL database description: Explore a full-stack architecture that combines a Next.JS frontend with a SQL database and Firebase Data Connect backend, using a Genkit agent, vector search and Retrieval-Augmented Generation (RAG) for intelligent, data-driven responses. fallbackCta: title: Launch in Firebase Studio icon: firebase-studio url: https://studio.firebase.google.com/import?url=https%3A%2F%2Fgithub.com%2FFirebaseExtended%2Fsolution-data-connect-movies accentColor: foreground: "white" background: "#141e2a" sections: - type: watch youtubeId: bcslEXK_uws title: Grounded AI agents with Firebase Data Connect and your SQL database description: Explore a full-stack architecture that combines a Next.JS frontend with a SQL database and Firebase Data Connect backend, using a Genkit agent, vector search and Retrieval-Augmented Generation (RAG) for intelligent, data-driven responses. technologies: - icon: /external-assets/firebase-connect.svg label: Firebase Data Connect url: https://firebase.google.com/docs/data-connect - icon: /external-assets/cloud-sql.svg label: CloudSQL url: https://cloud.google.com/sql - icon: /external-assets/firebase-genkit.svg label: Genkit url: https://firebase.google.com/docs/genkit - icon: /external-assets/vertex-ai.svg label: Vertex AI with Gemini Models url: https://cloud.google.com/vertex-ai - icon: /external-assets/firebase.svg label: Firebase url: https://firebase.google.com - icon: /external-assets/nextjs.svg label: Next.JS - type: explore mode: video subsections: - id: video-1 title: Get a movie recommendation from the agent description: | Interact with the agent to get a personalized movie recommendation. videoPath: external-assets/data-connect-movie/explore/Agent.mp4 orientation: landscape frame: laptop layout: sidebyside logs: - timestamp: 1800 summary: Call Genkit flow 'recommender' detail: '{"messages": ... "I''m not sure."}' file: src/ai/recommender.ts sequence: - nextjs - genkit - timestamp: 2500 summary: Get watch history detail: "" file: lib/get-watch-history.ts sequence: - genkit - dc - sql inspect: dataconnect-vertexai - timestamp: 4000 summary: Execute 'recommender' prompt detail: '{"watchHistory": [history], now: [current time]}, messages: {.. "I''m not sure"} }' file: src/ai/recommender.ts sequence: - genkit - timestamp: 6000 summary: "Tool call 'askQuestion' interrupt" detail: '{ "question": "What kind of movie are you in the mood for?", "type": "MULTIPLE_CHOICE", "choices": ["Comedy", "Drama", "Action", "Sci-Fi", "Horror", "Family"] }' file: src/ai/genkit.ts sequence: - genkit - nextjs inspect: null - timestamp: 9050 summary: Call Genkit flow 'recommender' detail: '{"messages": [{ "role": "tool", "content": [{ "toolResponse": {"name": "askQuestion", "output": "Action"}}], ...] }' file: src/ai/recommender.ts sequence: - nextjs - genkit inspect: null - timestamp: 10500 summary: "Data Connect generated tool call: 'SearchMovies'" detail: '{"minRating": 6, "query": "action"}' file: dataconnect/tools/tools.gql sequence: - genkit - dc - sql inspect: genkit-dataconnect - timestamp: 14250 summary: "Tool call 'recommendMovies' interrupt" detail: '{ "recommendedMovies": [ { "id": "digital-uprising", "reason": "A hacker fighting a government conspiracy in a dystopian future..." }, ...]}' file: src/ai/genkit.ts sequence: - genkit - nextjs inspect: null - timestamp: 25000 summary: Call Genkit flow 'recommender' detail: '{"messages": ... "Something fun with animals"}' file: src/ai/recommender.ts sequence: - nextjs - genkit inspect: null - timestamp: 27000 summary: "Data Connect generated tool call: 'SearchMovies'" detail: '{"ratings": ["G", "PG", "PG-13"], "minRating": 5, "query": "fun with animals"}' file: dataconnect/tools/tools.gql sequence: - genkit - dc - sql inspect: genkit-dataconnect - timestamp: 31000 summary: "Tool call 'recommendMovies' interrupt" detail: '{ "recommendedMovies": [ { "id": "animal-antics", "reason": "I think you''ll enjoy this one! A man who can talk to animals teams..." }, ...]}' file: src/ai/genkit.ts sequence: - genkit - nextjs inspect: null - id: video-2 title: Review a movie description: | Mark a movie as watched and add a review. videoPath: external-assets/data-connect-movie/explore/Review.mp4 orientation: landscape frame: laptop layout: sidebyside logs: - timestamp: 9260 summary: Execute `addReview` hook detail: '{movieId: "the-swans-ascent", rating: 4, review: "Inspiring story and enjoyable to watch - recommended!"}' file: components/watch-dialog.tsx sequence: - nextjs inspect: nextjs-dataconnect - timestamp: 9460 summary: Execute Mutation `AddReview` detail: 'review: data: { userUid_expr: "1234", movieId: "the-swans-ascent", reviewTime_expr: "request.time", rating: 4, review: "Inspiring story and enjoyable to watch - recommended!"}' file: dataconnect/connector/mutations.gql sequence: - nextjs - dc inspect: nextjs-dataconnect - timestamp: 9660 summary: Run query detail: "" sequence: - dc - sql inspect: dataconnect-sql - timestamp: 10000 summary: Execute `addWatch` hook detail: '{movieId: "the-swans-ascent", format: "theater", watchDate: [current date], reviewId: 875 }' file: components/watch-dialog.tsx sequence: - nextjs inspect: nextjs-dataconnect - timestamp: 10200 summary: Execute Mutation `AddWatch` detail: 'watch: data: { userUid_expr: "1234", movieId: "the-swans-ascent", format: "theater", watchDate: [current date], reviewId: 875 }' file: dataconnect/connector/mutations.gql sequence: - nextjs - dc inspect: nextjs-dataconnect - timestamp: 10400 summary: Run query detail: "" sequence: - dc - sql inspect: dataconnect-sql - id: video-3 title: Explore movies and search description: | Browse the movie database and do a search backed by Data Connect. videoPath: external-assets/data-connect-movie/explore/Search.mp4 orientation: landscape frame: laptop layout: sidebyside logs: - timestamp: 1250 summary: Execute `useBrowseMovies` hook detail: "" file: app/browse/page.tsx sequence: - nextjs inspect: nextjs-dataconnect - timestamp: 1350 summary: Execute Query `BrowseMovies` detail: "" file: dataconnect/connector/queries.gql sequence: - nextjs - dc inspect: nextjs-dataconnect - timestamp: 1400 summary: Run query detail: "" sequence: - dc - sql inspect: dataconnect-sql - timestamp: 3500 summary: Execute `useBrowseMovies` hook detail: '{ genres: ["Action"] }' file: app/browse/page.tsx sequence: - nextjs inspect: nextjs-dataconnect - timestamp: 3575 summary: Execute Query `BrowseMovies` detail: '{ genres: ["Action"] }' file: dataconnect/connector/queries.gql sequence: - nextjs - dc inspect: nextjs-dataconnect - timestamp: 3650 summary: Run query detail: "" sequence: - dc - sql inspect: dataconnect-sql - timestamp: 6100 summary: Execute `useBrowseMovies` hook detail: '{ genres: ["Action"], partialTitle: "Iron" }' file: app/browse/page.tsx sequence: - nextjs inspect: nextjs-dataconnect - timestamp: 6400 summary: Execute Query `BrowseMovies` detail: '{ genres: ["Action"], partialTitle: "Iron" }' file: dataconnect/connector/queries.gql sequence: - nextjs - dc inspect: nextjs-dataconnect - timestamp: 6700 summary: Run query detail: "" sequence: - dc - sql inspect: dataconnect-sql - timestamp: 9900 summary: Call `moviePage` function detail: '{ movieId: "iron-will" }' file: app/movies/page.tsx sequence: - nextjs inspect: nextjs-dataconnect - timestamp: 11300 summary: Execute Query `MoviePage` detail: '{ movieId: "iron-will" }' file: dataconnect/connector/queries.gql sequence: - nextjs - dc inspect: nextjs-dataconnect - timestamp: 11500 summary: Run query detail: "" sequence: - dc - sql inspect: dataconnect-sql - type: inspect title: Inspect subsections: - id: genkit-dataconnect title: Building agents with Genkit and Data Connect mode: markdown examples: - title: Define AI tools backed by Data Connect icons: - /external-assets/firebase-connect.svg - /external-assets/firebase-genkit.svg mode: markdown info: | Firebase Data Connect can expose defined GraphQL queries and mutations as "tools" for AI frameworks like Genkit. A Data Connect connector generates these tool definitions in a structured JSON format, detailing their names, descriptions and parameter schemas. This output is then registered in Genkit, making them available to AI models and enabling agents and flows to call them directly. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/dataconnect/tools/connector.yaml code: language: yaml content: | connectorId: tools generate: llmTools: outputFile: ../../generated/tools.json - title: Integrate Data Connect tools in Genkit icons: - /external-assets/firebase-connect.svg - /external-assets/firebase-genkit.svg mode: markdown info: | Tool definitions generated by Data Connect can be referenced in Genkit and made available to prompts as callable functions. When initializing Genkit, include the `dataConnectTools` plugin and provide the path to the generated JSON file containing the operation definitions. This registration makes the Data Connect operations available as callable tools within Genkit flows, enabling AI models to interact with the database in a structured and grounded manner. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/src/ai/genkit.ts code: language: typescript content: | export const ai = genkit({ plugins: [ vertexAI( /* ... */), dataConnectTools({ name: "db", configFile: "generated/tools.json", firebaseApp: app, }), ], model: gemini20Flash, promptDir: "src/ai/prompts", }); - title: Write agent prompts with tool calling icons: - /external-assets/firebase-genkit.svg mode: markdown info: | When building an AI agent, the prompt is crucial in guiding the model. The Genkit prompt directly references the tools generated by Data Connect and instructs the model on how and when to call them. For these tools to be effective, their definitions must clearly explain the purpose and its parameters. The recommendation agent in the movie review application uses these tools to search for movies and reviews directly from the application's data, ensuring the response is grounded in real data. The prompt includes detailed examples that help the model leverage these Data Connect tools in fulfilling its objective based on user input and watch history. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/src/ai/prompts/recommender.prompt code: language: plaintext content: | --- input: schema: watchHistory?(array): any, toolChoice: required tools: [db/SearchMovies, db/SearchReviews, db/FilterMovies, askQuestion, recommendMovies] maxTurns: 10 --- {{role "system"}} You are a movie recommendation assistant for the website FriendlyMovies. You are in charge of a feature called "NextWatch" that helps the user find an excellent movie to watch. ... === Example Queries and Searches Here are some examples of queries and how you should approach researching them: Query: a 90s buddy comedy Function: SearchMovies({minAvgRating: 6, minDate: "1990-01-01", maxDate: "1999-12-31", query: "buddies"}) - title: Define a Genkit flow for AI-Powered recommendations icons: - /external-assets/firebase-genkit.svg - /external-assets/firebase-connect.svg - /external-assets/nextjs.svg mode: markdown info: | Genkit workflows provide the structure for AI-powered features by orchestrating the steps involved in generating a response. They provide a type-safe way to interact with the AI model, incorporating the user's context and input, and can be deployed directly as web API endpoints. The recommender agent is defined as a flow that processes the on-going conversation and responds with a new message. It also incorporates the user's watch history and the current date and time as additional context. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/src/ai/recommender.ts code: language: typescript content: | export const recommenderFlow = ai.defineFlow( { name: "recommender", inputSchema: z.object({ messages: z.array(MessageSchema), }), outputSchema: z.array(MessageSchema), }, async (input, { context }) => { const { messages } = await recommenderPrompt( { watchHistory: await getWatchHistory(context?.auth?.uid), now: new Date().toISOString(), }, { messages: input.messages } ); // only return new messages since the last call return messages.slice(input.messages.length + 1); } ); - title: Deploy and call Genkit flows icons: - /external-assets/firebase-genkit.svg - /external-assets/nextjs.svg mode: markdown info: | Genkit flows can be deployed as web endpoints. This makes them accessible to different client applications, including web and mobile apps. In the movie review app, the `recommender` flow is deployed as a backend endpoint exposed at `/api/recommender`. When a user requests a recommendation, the frontend calls this URL, sending the user's authentication token and message to execute the flow. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/src/components/movie-recommender.tsx - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/src/app/api/recommender/route.ts - label: Authorization and integrity for Genkit flows url: https://firebase.google.com/docs/genkit/auth type: other - label: Deploy Genkit flows url: https://firebase.google.com/docs/genkit/deploy-node type: other code: language: typescript content: | // Consolidated function to send messages to the recommender API async function sendMessages(newMessages: MessageData[]) { try { // Get auth token const token = await auth.currentUser?.getIdToken(); // Call the agent const response = await runFlow({ url: "/api/recommender", input: { messages: newMessages }, headers: token ? { authorization: `Bearer ${token}`, } : undefined, }); // Update messages with agent response setMessages((prev) = [...prev, ...response]); } catch (error) { console.error("Error calling recommender:", error); } } - id: nextjs-dataconnect title: Next.JS and Data Connect mode: markdown examples: - title: Define the data model in GraphQL icons: - /external-assets/firebase-connect.svg - /external-assets/cloud-sql.svg mode: markdown info: | Define your data model in Firebase Data Connect by creating tables within GraphQL schema files. These definitions outline the structure of your data and its mapping to the underlying Cloud SQL for PostgreSQL database. In the movie review application, the primary data structures (like `Movie`, `Actor` and `User`) are defined in the GraphQL file `schema.gql`. This includes the fields, their column types and other directives like default values, computed server values or reference fields that establish relationships with other tables. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/dataconnect/schema/schema.gql - label: Understand GraphQL schemas, queries, and mutations url: https://firebase.google.com/docs/data-connect/schemas-queries-mutations type: other code: language: graphql content: | type Movie @table { id: String! title: String! "MPAA Rating (G, PG, PG-13, R)" rating: String! @default(value: "PG") posterUrl: String! releaseDate: Date! genre: String! # … } - title: Define Queries and Operations in GraphQL icons: - /external-assets/firebase-connect.svg - /external-assets/cloud-sql.svg mode: markdown info: | Firebase Data Connect uses the GraphQL query language to define how applications read and modify data in the CloudSQL for PostgreSQL database. Queries define how data is fetched and mutations describe how data is created, updated or deleted. When a query or mutation is executed, Data Connect translates the GraphQL operation into the appropriate SQL statements and runs them against the underlying CloudSQL for PostgreSQL database. The movie review application defines several queries for key use cases like browsing movies, loading watch history, or displaying movie details. Its mutations handle updates such as changing user details, marking a movie as watched, and adding reviews. The Gemini assistant in the Firebase console helps write these operations. You can use natural language to describe the query and notation and the assistant generates corresponding GraphQL code for you to review. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/dataconnect/connector/mutations.gql - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/dataconnect/connector/queries.gql - label: Understand GraphQL schemas, queries, and mutations url: https://firebase.google.com/docs/data-connect/schemas-queries-mutations type: other - label: Use AI assistance for Firebase Data Connect queries and mutations url: https://firebase.google.com/docs/data-connect/ai-assistance type: other code: language: graphql content: | # Return a filtered list of movies based on a set of arguments. # These variables are used in the 'where' clause for the query. query BrowseMovies( # Partial title to match - omit for all titles $partialTitle: String # Earliest acceptable release date - omit for no lower bound $minDate: Date # Latest acceptable release date - omit for no upper bound $maxDate: Date # Lowest acceptable average rating for the movie, on a scale from 0.0 to 10.0 $minRating: Float # Array of acceptable ratings for the movie, such as ["G", "PG"] for family-friendly movies. omit for all ratings $ratings: [String!] # Genres to allow results from. omit for all genres $genres: [String!] # This query can be executed by anyone with or without authentication ) @auth(level: PUBLIC) { # Fetch data from the 'movies' table movies( # Apply the filters defined by the variables in this query where: { title: { contains: $partialTitle } releaseDate: { ge: $minDate, le: $maxDate } rating: { in: $ratings } genre: { in: $genres } movieStats_on_movie: { avgRating: { ge: $minRating } } } limit: 30 orderBy: [{releaseDate: DESC}] ) { # Return the data as a set of fields that are defined in the file as a reusable fragment called "MovieOverview" # This fragment includes the id, title, genre, etc. ...MovieOverview } } - title: Generate the Web SDK icons: - /external-assets/firebase-connect.svg - /external-assets/nextjs.svg mode: markdown info: | Firebase Data Connect automatically generates type-safe client SDKs based on the GraphQL schema and operations. This generated SDK enables frontend applications to directly call deployed queries and mutations as functions. Data Connect generates and packages the SDK into the specified `outputDir` directory, ready for referencing in the application. It includes a README file that contains usage instructions, examples, and reference documentation. When configured to generate a JavaScript SDK (`javascriptSdk`) with the `react: true` property, the SDK includes bindings for React. For Next.JS applications, like the movie review app, these React specific hooks integrate seamlessly with the TanStack Query library. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/dataconnect/connector/connector.yaml - label: Generate web SDKs for Data Connect url: https://firebase.google.com/docs/data-connect/web-sdk#generate-react-angular type: other code: language: yaml content: | connectorId: connector generate: javascriptSdk: outputDir: ../../generated/data package: "@app/data" packageJsonDir: ../.. react: true - title: Use the TanStack Query SDK to call Data Connect icons: - /external-assets/firebase-connect.svg - /external-assets/nextjs.svg mode: markdown info: | For React applications, the TanStack Query Firebase library simplifies managing asynchronous operations, caching and state operations within components. The Data Connect generated SDK uses TanStack to provide React hooks, making it handle asynchronous tasks like fetching or mutating data. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/src/app/watches/page.tsx - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/dataconnect/connector/queries.gql - label: Use queries and mutations in your React or Angular client url: https://firebase.google.com/docs/data-connect/web-sdk#operations-react-angular type: other - label: Learn more about TanStack Query Firebase url: https://react-query-firebase.invertase.dev/ type: other code: language: typescript content: | import { useWatchHistoryPage } from "@app/data/react"; // ... export default function WatchHistoryPage() { // Fetch watch history data const { data, isLoading, refetch } = useWatchHistoryPage(dc); if (isLoading) { // Data is being loaded. // ... return ; } // Data has been loaded and is available. const { watches } = data; // ... } - id: dataconnect-sql title: Data Connect and Cloud SQL mode: markdown examples: - title: Get started with Gemini AI Assist icons: - /external-assets/firebase-connect.svg - /external-assets/cloud-sql.svg mode: markdown info: | Gemini AI assistance, available in the Firebase console, and the Google Code Assist extension in VSCode helps you get started with Firebase Data Connect. Describe your application using natural language, and Gemini help you create the GraphQL schema. You can then deploy this schema directly from the console and provision a Cloud SQL for PostgreSQL instance, ready for your application. After defining the schema, the assistant can also help you create GraphQL queries and mutations for your application. Describe your data operations in natural language, and work with the assistant to define them. links: - label: Get started with Firebase Data Connect url: https://firebase.google.com/docs/data-connect/quickstart?userflow=automatic type: other - label: Use AI assistance for Firebase Data Connect queries and mutations url: https://firebase.google.com/docs/data-connect/ai-assistance type: other code: language: plaintext content: | Return the top five movies of 2022, in descending order by rating. Create a movie based on user input. List all movies from 2024 that include all of these tags: 'space travel', 'comedy'. List all movie reviews, based on user-configurable genre and ratings. - title: Data Connect and Cloud SQL for PostgreSQL Backend icons: - /external-assets/firebase-connect.svg - /external-assets/cloud-sql.svg mode: markdown info: | Firebase Data Connect uses Cloud SQL for PostgreSQL as its relational database foundation for data storage. This Cloud SQL instance is a fully managed database and can be administered independently as needed, for tasks like backups or monitoring. Data Connect acts as the primary interface, handling direct data interactions and abstracting some of underlying SQL database complexities. The data model is defined using a GraphQL schema. Data Connect takes these GraphQL definitions and translates them into the corresponding SQL schema (including tables, columns and corresponding data types) for the Cloud SQL database. When an application executes queries through data connect, it translates these GraphQL operations into appropriate SQL statements and runs them against the Cloud SQL database. You can also integrate an existing Cloud SQL for PostgreSQL database into a Data Connect project. This is useful if you have established workflows and processes for managing schemas, but would like to use Data Connect for its native SDK generation, query-based authorization or client connection management. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/dataconnect/schema/schema.gql - label: Manage Data Connect services and databases url: https://firebase.google.com/docs/data-connect/manage-services-and-databases type: other - label: Integrate existing Cloud SQL for PostgreSQL databases url: https://firebase.google.com/docs/data-connect/manage-services-and-databases#integrate-existing-databases type: other - label: Learn more about Data Connect schemas, queries, and mutations url: https://firebase.google.com/docs/data-connect/schemas-queries-mutations type: other - label: Learn more about Cloud SQL for PostgreSQL url: https://cloud.google.com/sql/docs/postgres type: other code: language: graphql content: | type Review @table { user: User! movie: Movie! "Integer between 0-10 corresponding to a star rating (0 = 0 stars, 5 = 2.5 stars, 10 = 5 stars)" rating: Int! review: String reviewTime: Timestamp! @default(expr: "request.time") embedding: Vector @col(size: 768) } - id: dataconnect-vertexai title: Vector search with Data Connect and Vertex AI mode: markdown examples: - title: Understand Vector Search icons: - /external-assets/firebase-connect.svg - /external-assets/vertex-ai.svg - /external-assets/cloud-sql.svg mode: markdown info: | Vector embeddings are numerical representations that capture the semantic meaning of content, such as text or other media. Using nearest neighbor search, systems can then identify and retrieve items with similar meanings or themes based on these representations, enabling semantic search. This allows apps to find conceptually similar content rather than relying on exact keyword matches. This is a key component in building grounded, retrieval-augmented generation (RAG) AI flows. In the movie review application, vector search enhances the agent's ability to provide intelligent movie recommendations. Firebase Data Connect integrates vector search using Vertex AI to automatically generate vector embeddings, which are then stored alongside data in Cloud SQL. links: - label: Perform vector similarity search in Data Connect with Vertex AI url: https://firebase.google.com/docs/data-connect/solutions-vector-similarity-search type: other - label: Learn more about retrieval-augmented generation (RAG) url: https://developers.google.com/machine-learning/glossary#retrieval-augmented-generation-rag type: other code: language: plaintext content: | // Vector embeddings group semantically similar items: // [⛄️, ⛰️] and [🏝️, 🏄] represent closely related concepts. // // However, they are distinct conceptual groups and are positioned // far apart in the vector space. | ⛄️ ⛰️ | | | 🏝️ 🏄 |________________ - title: Design a Schema for Vector Search icons: - /external-assets/firebase-connect.svg - /external-assets/vertex-ai.svg mode: markdown info: | Firebase Data Connect provides a special `Vector` data type for storing vector embeddings and performing vector similarity searches. This type can be used directly in the application's GraphQL schema definition alongside other fields. In the movie review application, this pattern enables semantic search based on movie descriptions. The `Movie` table definition includes a `descriptionEmbedding` field of type `Vector`, which stores vector embeddings generated from each movie's `description`. The vector embedding dimension (`@col(size: X)`) must be consistent to enable searches across fields and should match the number of dimensions used by the model that generated them. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/dataconnect/schema/schema.gql - label: Perform vector similarity search with Vertex AI url: https://firebase.google.com/docs/data-connect/solutions-vector-similarity-search type: other code: language: graphql content: | type Movie @table { id: String! title: String! "MPAA Rating (G, PG, PG-13, R)" rating: String! @default(value: "PG") posterUrl: String! releaseDate: Date! genre: String! description: String tags: [String] embedding: Vector @col(size: 768) # Enables vector search } - title: Generate and store Vector Embeddings icons: - /external-assets/firebase-connect.svg - /external-assets/vertex-ai.svg mode: markdown info: | Firebase Data Connect simplifies the process of generating and storing vector embeddings through integrated support for a special server value (`_embed`). When referenced in a GraphQL mutation, Data Connect automatically generates a vector embedding by calling Vertex AI's embedding APIs. This is useful when adding or updating database records, as it allows Data Connect to generate and store vector embeddings alongside the data itself in a single operation. In the movie review demo application, embeddings are generated when the app is populated with sample data. Refer to the documentation linked below for examples on how this can be implemented using mutations. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/scripts/ingest.ts - label: "Examples: Generate and store an embedding through Data Connect" url: https://firebase.google.com/docs/data-connect/solutions-vector-similarity-search#mutations type: other code: language: typescript content: | const moviesData = movies.map((movie: any) = ({ id: movie.id, rating: movie.rating, title: movie.title, releaseDate: movie.releaseDate, genre: movie.genre, posterUrl: `...`, description: movie.description, tags: movie.tags, embedding_embed: { model: "text-embedding-005", text: `${movie.title}: ${movie.description}`, }, })); - title: Execute semantic similarity searches icons: [] mode: markdown info: | For each `Vector` field in the schema, Firebase Data Connect automatically generates a GraphQL function (following a well-defined naming convention) that implements similarity search. Alternatively, queries can reference the `_embed` value, which directs Data Connect to generate vector embeddings for the given parameter using Vertex AI's Embedding API, which are then compared against the stored embeddings Both methods return a list of records semantically closest to the query, sorted by distance. In the movie review application, queries such as `SearchMovies` use this vector search capability through the generated `movies_embedding_similarity` function. The user's search text, provided as the `$query` parameter, is automatically converted by Data Connect into a vector representation using the specified model. Then, a search for these embeddings across the `Movies` table returns entries with the most similar embedding vectors, meaning movies that are semantically similar to the given input query. Such a Data Connect query, which performs powerful semantic search, can also be configured and exported as a LLM tool for use by Genkit. This enables Augmented Generation (RAG) by allowing the AI model to fetch contextually relevant movie data to ground its responses and recommendations. Learn more about this in the "Building agents with Genkit and Data Connect" section. links: - type: github url: https://github.com/FirebaseExtended/solution-data-connect-movies/blob/main/dataconnect/connector/queries.gql - label: Perform vector similarity search with Data Connect and Vertex AI url: https://firebase.google.com/docs/data-connect/solutions-vector-similarity-search#performing-similarity type: other code: language: graphql content: | query SearchMovies($query: String!) @auth(level: PUBLIC) { movies: movies_embedding_similarity( compare_embed: { text: $query, model: "text-embedding-005" } limit: 10 ) { ...MovieOverview description } } - type: video youtubeId: nZhkjSFB6UA navigationTitle: Google I/O 2025 title: Build AI agents grounded with your data using Firebase Data Connect description: Learn how to ground your AI with relevant data, with RAG from Firebase Data Connect. Firebase Data Connect brings rapid development and intelligent context from your Cloud SQL database to your generative AI experiences. Data Connect makes it easy to connect your app, data, and AI all together, and seamlessly integrates Vertex and Cloud SQL to make RAG easy and ready for AI agents. - type: quiz questions: - title: What is the primary role of GraphQL schema files in Firebase Data Connect when building a data model? answers: - answer: To directly execute SQL commands on the database. - answer: To define the visual layout of the Next.JS application. - answer: To outline the structure of your data and how it maps to the underlying Cloud SQL for PostgreSQL database correct: true - answer: To manage user authentication and authorization rules. - title: What does Firebase Data Connect automatically generate based on the GraphQL schema and operations for a Next.JS app? answers: - answer: A complete backend server in Node.js. - answer: Type-safe client SDKs, including React specific hooks that integrate with TanStack Query. correct: true - answer: Pre-built UI components for displaying data. - answer: Automated database backup scripts. - title: Where do you define primary data structures (like `Movie`, `Actor` and `User`) for use with Firebase Data Connect? answers: - answer: In a `dataconnect.yaml` configuration file. - answer: Within JavaScript files in the source code directory. - answer: In a GraphQL file (e.g. `/dataconnect/schema/schema.gql`). correct: true - answer: Directly within the Cloud SQL database schema using SQL DDL. - title: How can Firebase Data Connect expose defined GraphQL queries and mutations for AI frameworks like Genkit? answers: - answer: As "tools" in a structured JSON format, including names, descriptions, and parameter schemas. correct: true - answer: By generating REST API endpoints for each operation. - answer: Through a direct gRPC connection. - answer: By embedding them as comments within the Genkit flow code. - title: What tool can assist developers in getting started with Firebase Data Connect by helping to create a GraphQL schema from a natural language description of an application? answers: - answer: The Firebase CLI's `dataconnect:init` command. - answer: The Cloud SQL query editor. - answer: The GraphQL Playground interface. - answer: Gemini AI assistance in the Firebase console and in the Google Code Assist extension in VSCode. correct: true - title: What special data type does Firebase Data Connect provide to store vector embeddings in the GraphQL schema? answers: - answer: EmbeddingArray - answer: SemanticVector - answer: Vector correct: true - answer: FloatList - type: build promoType: firebase-studio links: - url: https://github.com/FirebaseExtended/solution-data-connect-movies label: Open on GitHub - url: https://developers.google.com/solutions label: Explore more Solutions architecture: entities: - id: nextjs icon: /external-assets/nextjs.svg label: Next.js React Application x: 0 y: 2 connections: - from: nextjs to: dc inspect: nextjs-dataconnect - from: nextjs to: genkit - id: firebase icon: /external-assets/firebase.svg label: Firebase x: 0 y: 4 connections: - from: firebase to: nextjs - id: dc icon: /external-assets/firebase-connect.svg label: Firebase Data Connect x: 4 y: 2 connections: - from: dc to: sql inspect: dataconnect-sql - from: dc to: vertex-ai inspect: dataconnect-vertexai - from: dc to: genkit inspect: genkit-dataconnect - id: genkit icon: /external-assets/firebase-genkit.svg label: Genkit x: 2 y: 4 connections: - from: genkit to: vertex-ai - id: vertex-ai icon: /external-assets/vertex-ai.svg label: Vertex AI x: 7 y: 4 - id: sql icon: /external-assets/cloud-sql.svg label: Cloud SQL x: 7 y: 2 badges: startBadge: https://developers.google.com/profile/badges/playlists/solutions/data-connect-grounded-agents/view exploreBadge: https://developers.google.com/profile/badges/playlists/solutions/data-connect-grounded-agents/learn quizBadge: https://developers.google.com/profile/badges/playlists/solutions/data-connect-grounded-agents/quiz buildBadge: https://developers.google.com/profile/badges/playlists/solutions/data-connect-grounded-agents/action