Skip to content

You're working for a well-known car manufacturer who is looking at implementing LLMs into vehicles to provide guidance to drivers. You've been asked to experiment with integrating car manuals with an LLM to create a context-aware chatbot. They hope that this context-aware LLM can be hooked up to a text-to-speech software to read the model's response aloud.

As a proof of concept, you'll integrate several pages from a car manual that contains car warning messages and their meanings and recommended actions. This particular manual, stored as an HTML file, mg-zs-warning-messages.html, is from an MG ZS, a compact SUV. Armed with your newfound knowledge of LLMs and LangChain, you'll implement Retrieval Augmented Generation (RAG) to create the context-aware chatbot.

Before you start

In order to complete the project you will need to create a developer account with OpenAI and store your API key as a secure environment variable. Instructions for these steps are outlined below.

Create a developer account with OpenAI

  1. Go to the API signup page.

  2. Create your account (you'll need to provide your email address and your phone number).

  3. Go to the API keys page.

  4. Create a new secret key.

  1. Take a copy of it. (If you lose it, delete the key and create a new one.)

Add a payment method

OpenAI sometimes provides free credits for the API, but this can vary depending on geography. You may need to add debit/credit card details.

This project should cost much less than 1 US cents with gpt-4o-mini (but if you rerun tasks, you will be charged every time).

  1. Go to the Payment Methods page.

  2. Click Add payment method.

  1. Fill in your card details.

Add an environmental variable with your OpenAI key

  1. In the workbook, click on "Environment," in the top toolbar and select "Environment variables".

  2. Click "Add" to add environment variables.

  3. In the "Name" field, type "OPENAI_API_KEY". In the "Value" field, paste in your secret key.

  1. Click "Create", then you'll see the following pop-up window. Click "Connect," then wait 5-10 seconds for the kernel to restart, or restart it manually in the Run menu.

Update to Python 3.10

Due to how frequently the libraries required for this project are updated, you'll need to update your environment to Python 3.10:

  1. In the workbook, click on "Environment," in the top toolbar and select "Session details".

  2. In the workbook language dropdown, select "Python 3.10".

  3. Click "Confirm" and hit "Done" once the session is ready.

!pip install langchain-core
# Update your environment to Python 3.10 as described above before running this cell
import subprocess
import pkg_resources

def install_if_needed(package, version):
    '''Function to ensure that the libraries used are consistent to avoid errors.'''
    try:
        pkg = pkg_resources.get_distribution(package)
        if pkg.version != version:
            raise pkg_resources.VersionConflict(pkg, version)
    except (pkg_resources.DistributionNotFound, pkg_resources.VersionConflict):
        subprocess.check_call(["pip", "install", f"{package}=={version}"])

install_if_needed("langchain-core", "0.3.18")
install_if_needed("langchain-openai", "0.2.8")
install_if_needed("langchain-community", "0.3.7")
install_if_needed("unstructured", "0.14.4")
install_if_needed("langchain-chroma", "0.1.4")
install_if_needed("langchain-text-splitters", "0.3.2")
!pip install unstructured
# Set your API key to a variable
import os
openai_api_key = os.environ["OpenAI"]

# Import the required packages
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_community.document_loaders import UnstructuredHTMLLoader
from langchain_openai import OpenAIEmbeddings
from langchain_core.runnables import RunnablePassthrough
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_chroma import Chroma
# Load the HTML as a LangChain document loader
loader = UnstructuredHTMLLoader(file_path="data/mg-zs-warning-messages.html")
car_docs = loader.load()
separators = ["\n\n"] # Split by Paragraph
chunk_size = 400
chunk_overlap = 100

rc_splitter = RecursiveCharacterTextSplitter(
    separators=separators,
    chunk_size=chunk_size,
    chunk_overlap=chunk_overlap
)

docs = rc_splitter.split_documents(car_docs)
docs
llm=ChatOpenAI(model='gpt-3.5-turbo', api_key=openai_api_key)

question = "The Gasoline Particular Filter Full warning has appeared. What does this mean and what should I do about it?"

message = """
Help the customer solve their car-related issues using the provided car documentation to answer the question:

Documents: {docs}
"""


embedding_function = OpenAIEmbeddings(api_key=openai_api_key, model='text-embedding-3-small')
vectorstore = Chroma.from_documents(docs, embedding_function)
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k":1})

prompt_template = ChatPromptTemplate.from_messages([("human", message)])

rag_chain = ({"docs" : retriever} 
             | prompt_template 
             | llm)

answer_rag = rag_chain.invoke(question)
answer = answer_rag.content
print(answer)