arrow_back

Create Text Embeddings for a Vector Store using LangChain

Sign in Join
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

Create Text Embeddings for a Vector Store using LangChain

Lab 1 hour 30 minutes universal_currency_alt 5 Credits show_chart Intermediate
info This lab may incorporate AI tools to support your learning.
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

GSP1233

Google Cloud self-paced labs logo

Overview

LangChain is a powerful open-source Python framework designed to make the development of applications leveraging large language models (LLMs) dramatically easier and more efficient. LangChain abstracts away much of the complexity in working with LLMs. This results in cleaner code, quicker development, and easier maintainability.

In this lab, you learn how to use LangChain to store documents as embeddings in a vector store. You use the LangChain framework to split a set of documents into chunks, vectorize (embed) each chunk and then store the embeddings in a vector database.

Once documents are stored, you query the vector database for results using a nearest neighbor search.

Objectives

In this lab, you learn how to:

  • Store documents into a vector store database using LangChain.
  • Understand the various classes LangChain provides to split, chunk and embed documents.
  • Use LangChain to query a vector store using Retrievers.

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left. Navigation menu icon

Embedding Documents using LangChain

In order to add textual data to a vector store, it must first be converted into its vector format, a process known as embedding.

A vector embedding is a numerical representation of data that captures semantic relationships and similarities, making it possible to perform mathematical operations and comparisons on the data for various tasks like text analysis, search and recommendation systems.

LangChain offers a few libraries to aid in embedding text for an AI application and storing it in a vector store. A vector store is a specialized database designed to store and manage large collections of embeddings.

In a real world scenario, data comes from multiple disparate sources. Each source likely follows a different schema. LangChain offers a Document object as a way to normalize data coming from multiple sources in a standard retreival format. In a LangChain Document, data can easily be passed between different chains in a very structured way.

Data Sources to Store

Document Loading using LangChain

Langchain provides classes to load data from different sources as Documents. Some useful data loaders are:

Once embeddings are created they can be indexed by a vector store for retrieval with various benefits.

  • Semantic Search: Vector stores, combined with embeddings, go beyond keyword matching. You can retrieve items based on meaning, even if they don't share exact words. Think finding documents related to "artificial intelligence" even if they use terms like "machine learning" and "neural networks."
  • Clustering and Recommendations: Because embeddings capture relationships between items, vector stores can cluster similar items together or recommend content based on a user's interests. This is much more powerful than simple keyword-based systems.
  • Handling Complex Data: Embeddings turn images, audio, code, and almost any data type into comparable vectors. This allows vector stores to power searches or analyses across diverse data previously very difficult to search.
  • Speed and Scalability: Vector stores excel at 'nearest neighbor' searches in massive datasets. This means lightning-fast results when comparing embeddings to find the most similar items.

Typical use cases for vector stores include:

  • Search Engines: Retrieve search results based on actual understanding and not just keyword matches.
  • Recommenedation Systems: Generate more personalized and accurate product, media, or content recommendations.
  • Image and Video Similarity Search: Find images or videos related to a query image, even without any textual tags.
  • Fraud Detection: Identify patterns and anomalies in complex data streams using embeddings.

embeddings

You now explore a jupyter notebook to understand how to leverage LangChain with a Large Language Model to index embeddings in a vector store. For this lab, an open source vector store, Chroma has been utilized. In a real world scenario it is highly recommended to use a scalable, enterprise-grade vector database such as Vertex AI Vector Search.

Task 1. Vertex AI Workbench

In your Google Cloud project, navigate to Vertex AI Workbench. In the top search bar, enter Vertex AI Workbench of the Google Cloud console.

Use search to locate Vertex AI workbench
  1. Go to User-managed-notebooks.
  2. Click Open JupyterLab for generative-ai-jupyterlab.
  3. The JupyterLab runs in a new tab.
Open Notebook action

Task 2. Open the Jupyter Notebook

You use a pre-installed Jupyter notebook to run the steps of this lab.

  1. Click on the create_text_embeddings_using_langchain.ipynb file in the left file explorer.
  2. Follow the steps in the notebook and run each cell one at a time.
Tip: To run the current cell, click the cell and press SHIFT+ENTER. Other cell commands are listed in the notebook UI under Run.

Click Check my progress to verify the objective. Install Vertex AI SDK for Python and import libraries

Click Check my progress to verify the objective. Split text into chunks

Click Check my progress to verify the objective. Vectorize/Embed Document Chunks

Click Check my progress to verify the objective. Print the responses

Congratulations!

In this lab, you successfully explored components of LangChain's python SDK used to embed textual data into a vector store and submitted queries to the vector store using a nearest neighbor search to enhance responses retrieved by a Large Language Model (LLM), in this case, PaLM 2 for Text.

Next steps / learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated June 28, 2024

Lab Last Tested June 28, 2024

Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

This content is not currently available

We will notify you via email when it becomes available

Great!

We will contact you via email if it becomes available