[Gemma 2]Using With LangChain
Copyright 2024 Google LLC.
Using Gemma with LangChain
This notebook demonstrates how to use Gemma (2B) model with LangChain library.
Setup
Select the Colab runtime
To complete this tutorial, you'll need to have a Colab runtime with sufficient resources to run the Gemma model. In this case, you can use a T4 GPU:
- In the upper-right of the Colab window, select ▾ (Additional connection options).
- Select Change runtime type.
- Under Hardware accelerator, select T4 GPU.
Gemma setup
To complete this tutorial, you'll first need to complete the setup instructions at Gemma setup. The Gemma setup instructions show you how to do the following:
- Get access to Gemma on kaggle.com.
- Select a Colab runtime with sufficient resources to run the Gemma 2B model.
- Generate and configure a Kaggle username and an API key as Colab secrets.
After you've completed the Gemma setup, move on to the next section, where you'll set environment variables for your Colab environment.
Configure your credentials
Add your your Kaggle credentials to the Colab Secrets manager to securely store it.
- Open your Google Colab notebook and click on the 🔑 Secrets tab in the left panel.

- Create new secrets:
KAGGLE_USERNAMEandKAGGLE_KEY - Copy/paste your username into
KAGGLE_USERNAME - Copy/paste your key into
KAGGLE_KEY - Toggle the buttons on the left to allow notebook access to the secrets.
Install dependencies
Run the cell below to install all the required dependencies.
Gemma
About Gemma
Gemma is a family of lightweight, state-of-the-art open models from Google, built from the same research and technology used to create the Gemini models. They are text-to-text, decoder-only large language models, available in English, with open weights, pre-trained variants, and instruction-tuned variants. Gemma models are well-suited for a variety of text generation tasks, including question answering, summarization, and reasoning. Their relatively small size makes it possible to deploy them in environments with limited resources such as a laptop, desktop or your own cloud infrastructure, democratizing access to state of the art AI models and helping foster innovation for everyone.
Prompt formatting
Instruction-tuned (IT) models are trained with a specific formatter that annotates all instruction tuning examples with extra information, both at training and inference time. The formatter has two purposes:
- Indicating roles in a conversation, such as the system, user, or assistant roles.
- Delineating turns in a conversation, especially in a multi-turn conversation.
Below is the control tokens used by Gemma and their use cases. Note that the control tokens are reserved in and specific to our tokenizer.
- Token to indicate a user turn:
user - Token to indicate a model turn:
model - Token to indicate the beginning of dialogue turn:
<start_of_turn> - Token to indicate the end of dialogue turn:
<end_of_turn>
Here's the official documentation regarding prompting instruction-tuned models.
QA with RAG
Retrieval-Augmented Generation (RAG) is a key advancement for Large Language Models (LLMs) for a couple of reasons:
-
Boosts Factual Accuracy: LLMs are trained on massive amounts of text data, but this data can be outdated or incomplete. RAG tackles this by allowing the LLM to access and incorporate relevant information from external sources during generation. This external fact-checking helps reduce made-up information, or "hallucinations," in the LLM's outputs, making them more trustworthy.
-
Enhances Relevance and Depth: RAG provides LLMs with a wider range of knowledge to draw on. When responding to a prompt or question, the LLM can not only use its internal knowledge but also supplement it with specific details retrieved from external data sources. This leads to more comprehensive and informative responses that are precisely tailored to the situation.
Overall, RAG elevates the credibility and usefulness of LLMs by ensuring their outputs are grounded in factual information and highly relevant to the context. This is crucial for applications like chatbots, educational tools, and even creative writing where factual grounding and rich detail are important.
WARNING:langchain_community.utils.user_agent:USER_AGENT environment variable not set, consider setting it to identify your requests.
Creating vector store
You will use this blog post as a data source for our application. In this section you will fetch the data, chunk it and load it into our vector store.
/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_deprecation.py:131: FutureWarning: 'cached_download' (from 'huggingface_hub.file_download') is deprecated and will be removed from version '0.26'. Use `hf_hub_download` instead. warnings.warn(warning_message, FutureWarning)
.gitattributes: 0%| | 0.00/1.23k [00:00<?, ?B/s]
1_Pooling/config.json: 0%| | 0.00/190 [00:00<?, ?B/s]
README.md: 0%| | 0.00/10.6k [00:00<?, ?B/s]
config.json: 0%| | 0.00/571 [00:00<?, ?B/s]
config_sentence_transformers.json: 0%| | 0.00/116 [00:00<?, ?B/s]
data_config.json: 0%| | 0.00/39.3k [00:00<?, ?B/s]
model.safetensors: 0%| | 0.00/438M [00:00<?, ?B/s]
pytorch_model.bin: 0%| | 0.00/438M [00:00<?, ?B/s]
sentence_bert_config.json: 0%| | 0.00/53.0 [00:00<?, ?B/s]
special_tokens_map.json: 0%| | 0.00/239 [00:00<?, ?B/s]
tokenizer.json: 0%| | 0.00/466k [00:00<?, ?B/s]
tokenizer_config.json: 0%| | 0.00/363 [00:00<?, ?B/s]
train_script.py: 0%| | 0.00/13.1k [00:00<?, ?B/s]
vocab.txt: 0%| | 0.00/232k [00:00<?, ?B/s]
modules.json: 0%| | 0.00/349 [00:00<?, ?B/s]
Creating a RAG Chain
Here's a resource to learn more about the LCEL paradigm: the official documentation
Prompt:
You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.
Question: {question}
Context: {context}
Answer:
Let's try it out!
'Transformers are a state-of-the-art architecture for language modeling, designed around the concept of attention. They consist of an encoder and a decoder that convert input text into useful text, focusing on the most important parts of the input. Transformers are highly effective at various language tasks, including translation and text generation. \n<end_of_turn>'
Extracting structured output (JSON)
Traditionally, information extraction involved complex systems with hand-written rules and custom models, which were costly to maintain.
Large Language Models (LLMs) offer a new approach. They can be instructed and given examples to perform specific extraction tasks, making them quicker to adapt and use.
The following section will show you to use Gemma to extract information from a query using LangChain.
Implementing required steps
Schema passed to the LLM:
{
name: <person's name>
age: <person's age>
}
Let's try it out!
{'name': 'Kate', 'age': 26} {'name': 'Ben', 'age': 33} Using tools
There are two main reasons why tools are beneficial for LLMs (Large Language Models):
-
Enhanced Capabilities: LLMs are incredibly knowledgeable, but they can't access and process information in real-time the way a human can. Tools like search engines and databases provide LLMs with a way to find and integrate up-to-date information, effectively extending their knowledge and abilities. For instance, an LLM could be writing a report, but it might need to access specific statistics or research papers to complete the task. By using search tools, the LLM can find this information and incorporate it into the report.
-
Real-World Interaction: LLMs themselves can't directly interact with the physical world. However, tools like programming interfaces (APIs) allow LLMs to connect with and control various applications and devices. This opens doors to a much wider range of applications, like controlling smart home devices or generating code.
In essence, tools bridge the gap between the vast knowledge stored within an LLM and the ability to use that knowledge in a practical way.
Implementing required steps
Available tools:
add(first_int: int, second_int: int) -> int - Add two integers.
(operators: plus, added, +)
exponentiate(base: int, exponent: int) -> int - Returns the value of `base` to the power of `exponent`
(operators: power to, **, exp)
multiply(first_int: int, second_int: int) -> int - Multiply two integers together.
(operators: mulitplied, *, times, etc.)
Let's try it out!
(tool called: add)
1326
(tool called: exponentiate)
64
(tool called: multiply)
25
Run in Google Colab