Skip to content
ImagineWorld

Customizing Contextual LLMs

node_idnode-book_llms-in-enterprise_chapter-05-customizing-contextual-llms
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleCustomizing Contextual LLMs
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In the rapidly evolving landscape of artificial intelligence, LLMs stand out as one of the most transformative technologies of our time. They have the potential to drive innovation across numerous sectors, from automating customer service interactions to aiding complex decision-making processes in areas like healthcare and finance. However, as the application domains of LLMs expand, the need for more sophisticated, context-aware systems becomes apparent. This chapter delves deep into the advanced techniques that enable LLMs to operate with enhanced recognition of context and specificity, thereby pushing the boundaries of what these powerful tools can achieve.

The effectiveness of LLMs in real-world applications often hinges on their ability to recognize and generate responses based on a rich understanding of context, a challenge that standard models sometimes struggle with due to their generic training processes. To address this, innovative solutions such as retrieval-augmented generation (RAG) are starting to be widely applied across different businesses. RAG solutions enhance the contextual awareness of LLMs, improving their ability to produce not only relevant and accurate output but also to adapt dynamically to new information and complex user requirements. While the previous chapter introduced the concepts behind RAG, this chapter will go deeper into its practical applications.

In addition to RAG, prompt engineering is a critical technique that can significantly influence an LLM’s performance. By carefully designing and refining the prompts given to the model, users can guide the LLM to generate more accurate and contextually relevant responses. This process involves understanding how to frame questions and instructions effectively, ensuring that the model’s capabilities are leveraged to their fullest potential. Together, RAG and prompt engineering create a more robust framework for optimizing LLMs in various applications.

day-mode Bookmark

To follow along with the examples and code in this chapter, readers should have the following technical setup:

  • Python (3.8 or later): Many examples use Python-based libraries for LLM interaction and data retrieval.
  • Jupyter Notebook or VS Code: Recommended for running and modifying code snippets.
  • LangChain (latest version): Required for implementing RAG-based retrieval methods. Install it using:
  • FAISS or ChromaDB: Necessary for efficient vector search and embedding retrieval. Install with:
  • Hugging Face models: Some examples use open-source models from Hugging Face. Ensure you have API access or a local LLM setup.

You can find the code examples in this chapter in the book’s accompanying GitHub repository: https://github.com/PacktPublishing/LLMs-in-Enterprise

day-mode Bookmark

The importance of contextual customization

Section titled “The importance of contextual customization”

The customization of LLMs to incorporate contextual understanding is not only a technical enhancement; it represents a paradigm shift in how we envision the role of AI in industry and society. With these advancements, LLMs can be fine-tuned to recognize the nuances of language and information in specific fields, leading to better-informed models that can recognize patterns and formulate more grounded responses.

For businesses, the ability to customize LLMs means the potential to vastly improve efficiency and accuracy in tasks that require a deep understanding of specialized data or operations. For consumers, it means interacting with AI systems that understand their queries more deeply, providing more accurate and contextually appropriate responses. In fields like mission-critical medicine or law, where precision and relevance are paramount, these improvements can be revolutionary, transforming vast amounts of data into actionable insights that can provide essential services to people and reduce the burden on public infrastructure.

Utilizing external memory for context management

Section titled “Utilizing external memory for context management”

As the demands on LLMs increase, particularly in tasks that require complex decision-making or continuous interactions with domain-specific knowledge over time, the integration of external memory systems, specifically vector stores, has become pivotal. These systems serve as external memory for LLMs, enhancing their ability to manage context by storing and retrieving embeddings of domain-specific data efficiently. This section explores the strategic incorporation of vector storage solutions into LLM frameworks, discussing both the benefits and operationalization challenges of this approach.

Extending LLMs with an external memory, as shown in Figure 5.1, significantly enhances their contextual awareness. These systems allow LLMs to retain and access vast amounts of detailed information that exceeds their immediate processing capacity. For instance, in customer service applications, an LLM can maintain a coherent and informed conversation across multiple interactions, significantly improving the user experience. Specifically, consider a scenario where a customer inquires about a specific product SKU. By leveraging a vector store integrated with an LLM model, the application can instantly retrieve detailed product information and pricing from domain-specific data.

Figure 5.1: High-level block diagram of different components involved in the RAG setup

Figure 5.1: High-level block diagram of different components involved in the RAG setup

Additionally, the use of external memory systems creates a dynamic knowledge base for LLMs. Unlike static models, an LLM equipped with an external vector store can be dynamically updated with a knowledge base without the need for complete retraining. This capability is critical in fast-evolving fields like legal, medical, or financial services, where staying current with the latest information is essential. By continuously integrating new data, these models can provide accurate and up-to-date responses, ensuring their relevance and reliability in real-time applications.

Moreover, the scalability and efficiency of LLMs are substantially improved by offloading the storage of embeddings to specialized external systems. Vector stores are designed to handle large-scale data efficiently, facilitating quicker retrieval of information and reducing the computational load on the core model. This separation of storage and generation functions allows LLMs to operate more efficiently, enabling them to handle larger volumes of data and more complex queries at scale. Overall, integrating external memory with LLMs not only boosts their contextual and dynamic generation capabilities but also enhances their operational efficiency and scalability.

day-mode Bookmark

Using fine-tuned LLMs or foundational models in enterprises with strict accuracy constraints presents significant challenges. Non-RAG approaches often suffer from much higher levels of hallucination, generating incorrect information without clear attribution, making it difficult for organizations to comply with AI regulations that require transparency and explainability. Additionally, these models tend to become stale over time, and retraining them when new data arises is challenging and expensive. Handling revisions, such as removing individuals who opt out of specific services and ensuring their data is deleted, further complicates the retraining process. Customizing non-RAG models with domain-specific data presents several challenges. First, these models often encounter context window limitations, restricting the amount of information they can process effectively. As a result, critical context may be lost, leading to less accurate outputs.

Moreover, dumping extensive domain data into a prompt can create a “needle-in-a-haystack” problem, making it difficult for the model to identify relevant information amid the irrelevant data. This highlights the need for structured approaches like RAG, which manage domain-specific information better.

RAG models mitigate many of these issues by grounding the LLM’s output in retrievable, accurate data sources. They have been observed to reduce hallucination, improve factual recall, and allow enterprises to trace back to the sources or contexts used for generation, enhancing understanding and compliance.

Additionally, RAG models effectively address challenges like data staleness, revisions, and customization. By decoupling the retrieval framework from the generation process, updates to the underlying data can occur without necessitating changes to the LLM itself. This flexibility allows enterprises to maintain accurate and current information while leveraging the generative capabilities of LLMs.

This section provides some real-world examples where RAGs can provide significant value by utilizing an organization’s unstructured data to recognize patterns and formulate answers based on domain expertise.

For legal professionals, an LLM with access to a vector store containing embeddings of legal documents can significantly streamline the process of research and document review. When a lawyer queries specific case law or precedents, the LLM can instantly pull relevant documents from the external memory. This reduces the time spent on manual searches and increases the accuracy of legal research, making the process more efficient and thorough. Some real-world examples are:

  • CaseText’s CoCounsel: Provides AI-driven legal research and document drafting assistance.
  • Harvey.ai’s Legal Copilot: Assists with legal research, drafting, and workflow automation.

In a healthcare setting, an LLM equipped with external memory can access a patient’s entire medical history stored as embeddings in a vector store. When a patient interacts with a virtual health assistant, the LLM can quickly retrieve the patient’s past medical records, current medication, and prior interactions. This capability allows the LLM to provide personalized advice and reminders, enhancing patient care and ensuring consistency across interactions. Some real-world examples are:

  • IBM Watson Health: Uses AI to assist with medical research, diagnostics, and patient care.
  • PathAI: Utilizes AI for pathology image analysis to assist in diagnostics and treatment planning.

In the finance sector, AI-powered solutions are transforming market analysis, risk assessment, and investment strategies. Large Language Models (LLMs) with external memory capabilities enable financial institutions to access vast amounts of historical and real-time data, enhancing decision-making and predictive analytics. These technologies streamline financial research, automate insights, and improve efficiency in market intelligence. Some real-world examples are:

  • Kensho Technologies: Offers AI-driven analytics and insights for financial markets and investment strategies.
  • AlphaSense: Uses AI for financial research and market intelligence, leveraging RAG techniques for deeper insights.

AI-powered virtual assistants and chatbots are redefining customer service by offering instant, intelligent responses to user inquiries. With the ability to retrieve relevant past interactions and contextual information, LLMs improve response accuracy and reduce wait times, leading to enhanced customer satisfaction and operational efficiency. Some real-world examples are:

  • Zendesk’s Answer Bot: Employs AI to provide automated responses and improve customer service efficiency. Zendesk Answer Bot.
  • Ada: Uses AI for automated customer support and query resolution.

AI is playing a crucial role in personalizing education by adapting learning experiences to individual students’ needs. LLMs can retrieve contextual knowledge, generate real-time explanations, and offer interactive tutoring, making education more accessible and effective. Some real-world examples are:

  • Socratic by Google: An educational app that uses AI to help students with homework by providing explanations and relevant resources.
  • Khan Academy’s Khanmigo: An AI-driven tutor that provides personalized learning experiences and support.

AI-driven insights are revolutionizing the real estate sector by providing accurate property valuations, predictive market trends, and data-driven investment analysis. LLMs enhance decision-making by retrieving comprehensive property data and market insights. Some real-world examples are:

  • Zillow’s Zestimate: Uses AI to provide real estate valuation estimates and insights.
  • Reonomy: Employs AI to offer data-driven insights and property analysis for commercial real estate.

Integrating RAGs into enterprise applications presents a set of unique challenges and limitations, some of which are shown in Figure 5.2. While RAG models can significantly enhance the capabilities of LLMs by providing access to a vast repository of external knowledge, their implementation and maintenance require careful consideration. From the complexity of integration and latency issues to the significant costs involved and the persistent problem of factual inaccuracies, enterprises must navigate various hurdles to leverage RAGs effectively.

Figure 5.2: High-level block diagram of different components involved in the RAG setup and their respective operationalization challenges

Figure 5.2: High-level block diagram of different components involved in the RAG setup and their respective operationalization challenges

In the subsections below, we’ll cover some of these challenges in a bit more detail, providing insights into both the technical and operational aspects of deploying RAG systems in production environments.

Integrating external memory with LLMs introduces complexity into the AI system architecture, necessitating careful planning and robust engineering to ensure seamless interaction between the model and the memory system. This process involves managing dependencies, ensuring compatibility, and maintaining system stability.

While vector stores are generally efficient, retrieving information can introduce latency, which can be significant if the data volume is vast or the network infrastructure is not optimized. These latency issues can impact the responsiveness of applications that require real-time processing.

Implementing and maintaining an external memory system can incur significant costs, as the infrastructure—both hardware and software—needed to support large-scale vector storage solutions can be substantial. Additionally, ongoing costs include storage, maintenance, and potentially higher processing power requirements.

Despite advancements, state-of-the-art LLMs often suffer from factual incorrectness and hallucinations of knowledge. RAG methods reduce hallucination but require careful implementation and tuning to be effective. Ensuring models retrieve and use accurate information without introducing errors remains a significant challenge.

Implementing an AI system with RAG or external memory involves several technical challenges that impact performance, efficiency, and accuracy. Below are key considerations that must be addressed to optimize document encoding and retrieval mechanisms:

  • Document encoding: Deciding how to encode documents is crucial; it involves selecting appropriate embedding models that capture the nuances of domain-specific knowledge. During the encoding step, documents must be chunked effectively to ensure that the embeddings accurately represent the content.
  • Retrieval mechanisms: Selecting when and how to retrieve documents is essential for efficiency and accuracy. The query encoder must be capable of translating user queries into embeddings that can be matched with stored documents.

The query encoder must be capable of translating user queries into embeddings that can be matched with stored documents. However, it is more critical at this stage to ensure strong retrieval quality, which relies on selecting the right search algorithm and similarity function tailored to the specific use case. These elements are essential for accurately matching queries to the most relevant documents, thus optimizing the overall performance of the system.

  • Preprocessing inputs: Input preprocessing is critical to ensure that the data fed into the model is clean and formatted correctly. This step includes the tokenization, normalization, and possibly the enrichment of data to enhance the model’s understanding.
  • Prompt design: Designing prompts that guide the LLM effectively is crucial for generating accurate and relevant responses. Prompts need to provide sufficient context and direction without overwhelming the model or introducing ambiguity.
  • Context management: Passing context effectively involves maintaining coherence and relevance throughout the interaction. Context management techniques ensure that the LLM retains important information across multiple turns of dialogue.
  • Post-processing outputs: Post-processing involves refining the generated output to meet quality standards. This step includes verifying factual accuracy, correcting errors, and ensuring the response is appropriate and safe for the given context.
  • Scaling and optimization: Scaling the system to handle large volumes of data and queries efficiently is a major challenge. Continuous training and optimization are required to keep the system up to date with new data and to improve performance.
  • Dynamic data integration: Dynamically adding new data to the external memory requires a robust process for embedding and integrating new information. The system must support incremental updates to ensure that it remains current and accurate as the domain-specific data evolves.

Understanding the “retrieval” aspect of RAG

Section titled “Understanding the “retrieval” aspect of RAG”

A common misconception is that AI, through RAG, will automatically understand and fetch the most relevant information for any query. However, the retrieval process still faces classical information retrieval challenges, such as ranking results based on relevance, authority, freshness, and specific keywords.

Consider a scenario where a user queries about coffee production in Kenya during the first quarter of the year. A naive similarity-based retrieval might return information about Ethiopian coffee production from a different year because the vector representations of African coffee-producing countries are similar. This becomes problematic when the retrieved Ethiopian report is outdated compared to more relevant, updated Kenyan data, leading to inaccurate or misleading results. To address this and similar challenges, we can explore hybrid search methods that enhance retrieval accuracy and relevance.

One of the ways to address this challenge is to use hybrid search. The concept of hybrid search represents a significant advancement in the field of information retrieval. It combines traditional keyword-based searches with modern semantic search techniques to provide more accurate and contextually relevant results. In this framework, BM25 plays a crucial role by handling the keyword-based component, while semantic search techniques manage the contextual and meaning-based aspects. This approach is particularly effective in handling complex queries where both explicit keywords and the underlying meaning play crucial roles in finding the right information.

BM25 stands for Best Matching 25, and it’s a ranking function used in traditional search engines to rank documents based on the query terms appearing in each document. Here’s a simplified breakdown of how BM25 works:

  • Term frequency (TF): This measures how frequently a term appears in a document. The more times a term appears in a document, the higher its term frequency.
  • Inverse document frequency (IDF): This measures the importance of a term. Common terms like “the” appear in many documents and are not very informative, so they get a low IDF score. Conversely, rare terms contribute more to the uniqueness of a document and receive a high IDF score.
  • Normalization: Documents of different lengths are treated in a manner that prevents long documents from dominating the relevance score. BM25 adjusts for document length, so both short and long documents are treated fairly.
  • Relevance score calculation**:** BM25 combines these elements to compute a score that indicates how relevant a document is to a given search query. The formula is:

Where:

  • is the query term
  • is a document
  • is the length of a document
  • is the average document length in the text collection
  • and are free parameters, usually set to 1.2 and 0.75, respectively

Vector search uses semantic meaning to enhance the search process. Unlike keyword search, vector search transforms both the query and the documents into vectors in a high-dimensional space. The semantic relationships between words are captured in this space, so even if the exact words don’t match, documents that are contextually related to the query can be retrieved. Let’s break this down a little further.

How it works: Words are converted into vectors using models like BERT or GPT, which capture the contextual meaning of the words rather than just their literal definitions. This allows the search system to understand queries in a context-aware manner, enabling it to fetch documents that are semantically similar even if they don’t contain the exact query terms. For instance, if a user searches for “how to fix a bike,” the system might also retrieve documents related to “bicycle repair instructions,” as the semantic meanings of these phrases are closely related.

Importance: This approach is crucial for handling nuanced queries where the intent behind the search is just as important as the search terms used. By understanding the underlying meaning of the query, the system can provide more accurate and relevant results, ensuring that users find the information they need even when their queries are phrased differently from the content in the documents.

Combining BM25 and vector search allows us to leverage the strengths of both approaches: the precision of keyword search and the contextual awareness of semantic search. Here’s how you can implement a basic hybrid search:

  1. Use BM25 to retrieve initial results: Start by using BM25 to quickly fetch a set of documents that contain the query terms. This step ensures that the results are at least somewhat relevant to the query.
  2. Apply vector search to refine results: Take the top documents from the BM25 results and then rerank them using vector search. By doing this, you refine the results based on semantic similarity, improving the overall relevance.
  3. Combine and rerank: Finally, combine the scores from both BM25 and vector search to rerank the documents. This can be done by assigning weights to each score and summing them to obtain a final score for each document. As a hyperparameter, the weight can be adjusted based on the importance of each method; for instance, you might set a higher weight on BM25 if exact keyword matching is more crucial, or on vector search if semantic relevance is prioritized. Experimenting with different weights allows you to find a balance that best suits your retrieval needs.

The example below demonstrates how to integrate keyword-based and semantic search techniques to enhance document retrieval from a PDF using LangChain and LanceDB.

Before we deep dive into the example, we will give a brief intro about LangChain and LanceDB.

LangChain is a framework designed to help developers build applications that integrate with large language models (LLMs) like GPT. It simplifies the process of chaining together different natural language processing (NLP) tasks, such as prompt engineering, context management, and RAG. LangChain enables the creation of complex pipelines where the output of one task can seamlessly feed into another, making it easier to build sophisticated AI-driven applications. It supports various use cases, including chatbots, automated content generation, and advanced search systems.

LanceDB is a specialized vector database optimized for managing and querying large-scale embeddings. It is designed to efficiently store, index, and retrieve high-dimensional vectors that represent data like text, images, or other complex features. LanceDB is particularly useful in scenarios where you need to perform similarity searches, such as finding documents or images that are semantically close to a given query. By integrating with tools like LangChain, LanceDB can enhance the retrieval performance in applications that rely on LLMs, ensuring faster and more accurate search results.

The process involves loading and splitting a PDF document, setting up both a BM25 retriever for keyword-based search and a LanceDB vector store for semantic search, and then combining these approaches using an ensemble retriever.

This hybrid search method ensures that the retrieved documents are not only relevant based on keyword matches but also contextually aligned with the query’s intent, significantly improving retrieval accuracy and user experience.

Note

The module installation requirements for the following code can be found in the book’s GitHub repository.

The example below queries for information about food for building strong bones and teeth, showcasing how this method effectively surfaces pertinent information from the document:

from langchain.vectorstores import LanceDB
import lancedb
from langchain.retrievers import BM25Retriever, EnsembleRetriever
from langchain.schema import Document
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.document_loaders import PyPDFLoader
# Initialize embeddings for semantic search
embedding = OpenAIEmbeddings(openai_api_key=openai_api_key)
  • Use PyPDFLoader to load and split the PDF into pages:

    from langchain.document_loaders import PyPDFLoader
    # Load documents
    loader = PyPDFLoader("Food_and_Nutrition.pdf")
    pages = loader.load_and_split()
  • Initialize the BM25 retriever and set it to fetch the top results:

    from langchain.retrievers import BM25Retriever
    # Initialize the BM25 retriever
    bm25_retriever = BM25Retriever.from_documents(pages)
    bm25_retriever.k = 2 # Retrieve top 2 results using BM25
  • Create a LanceDB vector store for semantic search. Connect to LanceDB and create a table for storing embeddings:

    import lancedb
    # Create lancedb vector store for semantic search
    db = lancedb.connect('/tmp/lancedb')
    table = db.create_table("pandas_docs", data=[
    {"vector": embedding.embed_query("Hello World"),
    "text": "Hello World", "id": "1"}

    ], mode=“overwrite”)

    db = lancedb.connect('lancedb')
    table = db.create_table("pandas_docs",
    data=[ {"vector": embedding.embed_query("Hello World"),
    "text": "Hello World", "id": "1"} ], mode="overwrite")
  • Set up the LanceDB retriever for semantic search:

    from langchain.vectorstores import LanceDB
    # Initialize LanceDB retriever
    # `k` specifies the number of search results to return
    docsearch = LanceDB.from_documents(
    pages, embedding, connection=table
    )
    retriever_lancedb = docsearch.as_retriever(search_kwargs={"k": 2})
    from langchain.vectorstores import LanceDB
    from lancedb.db import LanceDBConnection
    from langchain.embeddings.openai import OpenAIEmbeddings
    from langchain.document_loaders import PyPDFLoader # Initialize embeddings for semantic search # Establish connection to the LanceDB database # Replace 'your_database_path' with the actual path to your LanceDB database
    connection = LanceDBConnection('lancedb') # Assume `pages` is a list of Document objects loaded previously # Initialize LanceDB retriever
    docsearch = LanceDB.from_documents(
    pages, embedding, connection=connection

    ) # Create a retriever using the LanceDB vector store retriever_lancedb = docsearch.as_retriever(search_kwargs={“k”: 2})

  • The BM25 and LanceDB retrievers with specified weights:

    from langchain.retrievers import EnsembleRetriever
    # Initialize the ensemble retriever with weights
    ensemble_retriever = EnsembleRetriever(
    retrievers=[bm25_retriever, retriever_lancedb],
    weights=[0.4, 0.6]
    )
  • Perform a query and retrieve relevant documents using the ensemble retriever:

    # Example query
    query = "which food needed for building strong bones and teeth?"
    # Retrieve relevant documents
    docs = ensemble_retriever.get_relevant_documents(query)
    # Print retrieved documents
    print(doc.page_content)

To summarize the preceding example:

  • The BM25 retriever fetches documents based on keyword matches.
  • The LanceDB vector retriever refines these documents by semantic similarity.
  • The Ensemble Retriever combines these approaches to provide a balanced and nuanced set of search results.

By using hybrid search, you improve the likelihood of retrieving documents that are both explicitly relevant to the keywords and contextually similar to the query’s intent. This method is especially powerful in large datasets where understanding the deeper meaning of a query can significantly enhance the user experience.

day-mode Bookmark

Crafting a universal prompt that works well for diverse queries is challenging. Overfitting a prompt to specific types of queries can degrade the performance of others, necessitating the use of multiple tailored prompts.

Overfitting a prompt to specific types of queries can degrade the performance of others. For instance, fine-tuning a model like ChatGPT to excel in answering technical questions might inadvertently cause it to perform worse on creative writing tasks. This phenomenon is not just theoretical; real-life examples have shown that model weight or checkpoint updates in models like ChatGPT can lead to improvements in some benchmarks while degrading performance in others. This highlights a significant challenge in AI development: monitoring and navigating these trade-offs during retraining to ensure that overall performance is improved without negatively impacting other critical areas.

As another example, if a user asks about accounting jobs in London, the system might need to boost job-related content. Conversely, a question like “Which African country produces the most coffee?” might require breaking down the query into subqueries for individual countries, which a single prompt structure might not support effectively.

Instead, developing several specialized prompts for different types of queries and using an initial selection step to choose the most appropriate one for each query might be better.

Alternatively, for complex query handling, you can employ Intelligent Agent Frameworks that orchestrate multiple steps and prompts to provide accurate responses.

Addressing the prompt engineering challenge

Section titled “Addressing the prompt engineering challenge”

Prompt engineering is the way of designing prompts to improve the performance and accuracy of LLMs. The goal is to design prompts that generate relevant and accurate responses. To address the prompt engineering challenge for implementing RAG systems effectively, especially within enterprise contexts where specificity and reliability are paramount, I’ll detail each step of the process, adapting the provided notebook into a practical guide for prompt design using LangChain.

Below, we delve into best practices for prompt engineering using the LangChain library step by step:

  • Import the required classes and functions from the transformers library:

    • AutoModelForCausalLM: This class automatically identifies and loads the appropriate model architecture for causal language modeling tasks based on the model name.

      • AutoTokenizer: This class automatically loads the appropriate tokenizer for the specified model, converting input text into numerical tokens that the model can understand.
      from transformers import AutoModelForCausalLM, AutoTokenizer
  • Load the pre-trained DeepSeek model and tokenizer:

    • model_name = 'deepseek-ai/deepseek-coder-6.7b-base': Specifies the DeepSeek Coder 6.7B base model. You can replace this with other DeepSeek variants like 'deepseek-ai/deepseek-coder-1.3b-base' or 'deepseek-ai/deepseek-llm-7b-base', depending on your needs for model size and capability.

      • tokenizer = AutoTokenizer.from_pretrained(model_name): Initializes the tokenizer corresponding to the chosen DeepSeek model variant.
      • generation_model = AutoModelForCausalLM.from_pretrained(model_name): Loads the DeepSeek model for generating text.
      model_name = 'deepseek-ai/deepseek-coder-6.7b-base'
      tokenizer = AutoTokenizer.from_pretrained(model_name)
      generation_model = AutoModelForCausalLM.from_pretrained(
      model_name)
  • Create a dictionary of prompts: Define a dictionary where each key represents a category of prompts (e.g., “verbose,” “concise,” “generic,” “specific,” and “multi”) and each value is a list of prompts corresponding to that category.

This dictionary will help you organize and easily access different types of prompts based on the nature of the question or input you need:

prompts = {
"verbose": "What might be a creative name for a shop that specializes in dried flower arrangements and bouquets?",
"concise": "Suggest a name for a dried flower boutique",
"generic": "Describe the planet Earth",
"specific": "List unique characteristics of Earth compared to other planets",
"multi": "What's the best way to boil water and why are sunsets red?",
"boiling_water": "What's the most efficient way to boil water?",
"sunset_color": "Why do sunsets appear red?",
"zero_shot": """Determine the sentiment of this message: positive, neutral, or negative.\n\nMessage: Your latest video was fantastic!\nSentiment:""",
"one_shot": """Determine the sentiment of this message: positive, neutral, or negative.\n\nMessage: Your latest video was fantastic!\nSentiment: positive\n\nMessage: That was disappointing and dull \nSentiment:""",
"few_shot": """Determine the sentiment of this message: positive, neutral, or negative.\n\nMessage: Your latest video was fantastic!\nSentiment: positive\n\nMessage: That was disappointing and dull \nSentiment: negative\n\nMessage: This video surprised me; it was genuinely insightful and unique. I recommend giving it a watch.\nSentiment:""",
}
}
- **Generating responses:**

This stage will comprise the following:

  • Iterate through each prompt in the prompts dictionary and generate responses using the DeepSeek model.
  • Tokenization: Convert each prompt into numerical tokens (input_ids) using the tokenizer.
  • Model generation: Call generation_model.generate() to generate text based on the encoded input_ids.
  • Model parameters like max_new_tokens (maximum number of new tokens to generate), num_return_sequences (number of different sequences to generate), and others control the generation process.
  • Decoding and printing: Decode the generated output (output) into readable text (generated_text) using the tokenizer’s decode() method. Print the generated response for each prompt along with its label (verbose, concise, etc.).

Note:

DeepSeek models may require specific generation parameters to produce optimal results. The parameters like temperature, top_p, and repetition_penalty can significantly influence the output quality and creativity. Adjust these parameters based on your specific use case and requirements.

You can read the full output on the book’s accompanying GitHub repository here: https://github.com/PacktPublishing/LLMs-in-Enterprise

To build a robust system capable of handling complex queries and enhancing model interactions, we’ll need to utilize a range of specialized tools. By leveraging key modules from the LangChain library, as well as other essential libraries, we can extend the functionality of our project and streamline the steps required for efficient data handling, model control, and user interaction.

Let’s start by importing the foundational modules that will support these advanced capabilities.

  • Import the necessary modules: To extend our capabilities and integrate additional functionalities into our project, we will import some essential modules from the LangChain library, along with other relevant libraries. These modules will be used in the subsequent steps to enhance our ability to handle complex queries and manage interactions with the model more effectively.

Here’s how to import these modules:

from langchain.language_models import TextGenerationModel
from langchain.language_models import ChatModel
from langchain.llms import HuggingFacePipeline
  • Using LangChain, load a pre-trained DeepSeek model. Adjust the model path according to your specific use case and computational resources:

    from transformers import (
    AutoModelForCausalLM, AutoTokenizer, pipeline
    )
    import torch
    # Load a pre-trained DeepSeek model
    model_name = "deepseek-ai/deepseek-llm-7b-base"
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.float16, # Use half-precision for efficiency
    device_map="auto" # Automatically distribute model across available devices
    )
    # Create a pipeline
    pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    max_new_tokens=256,
    temperature=0.7,
    top_p=0.9,
    repetition_penalty=1.1
    )
    # Create a LangChain wrapper for the model
    generation_model = HuggingFacePipeline(pipeline=pipe)
  • Handling hallucinations: Be aware of model hallucinations and consider using methods like Do A Reflective Exploration (DARE) and off-topic prompting, which focus on safety and compliance with a mission before answering questions. Let’s look at an example of using the DARE method next to illustrate how these principles can be applied in practice.

  • Importing libraries and initializing a text generation pipeline: The following code imports the necessary libraries and initializes a text generation pipeline using a pre-trained DeepSeek model. Let’s explore what each part of the code does:

    • transformers: Imports the necessary components from the transformers library, which makes it easy to use pre-trained models for various tasks.

      • torch: Imports PyTorch for tensor operations and model handling.
      • text_generator: Initializes a text generation pipeline using the DeepSeek model. This setup allows the pipeline to generate text based on prompts:
      from transformers import pipeline
      # Load a text generation pipeline using a pre-trained model
      text_generator = pipeline("text-generation", model="gpt2")
      from transformers import (
      AutoModelForCausalLM, AutoTokenizer, pipeline
      )
      import torch
      # Load a text generation pipeline using a pre-trained DeepSeek model
      text_generator = pipeline(
      "text-generation",
      model="deepseek-ai/deepseek-llm-7b-base",
      torch_dtype=torch.float16,
      device_map="auto"
      )
  • Define prompt constants: Before generating and processing text, we need to establish some constants that will be used as prompts for the text generation model. These constants represent different types of prompts that guide the model’s behavior and ensure it aligns with guidelines or handles certain scenarios appropriately.

  • Define dare_prompt: This prompt emphasizes the importance of safety and compliance with a mission before answering questions. It is used to guide the model to provide responses that are reflective and adhere to certain standards or constraints.

  • Define off_topic_prompt: This prompt is used to handle off-topic or irrelevant questions. It helps guide the model to recognize when a question does not fit within the intended scope and respond accordingly.

    # Define your DARE prompt
    dare_prompt = """Remember that before you answer a question, you must check to see if it complies with your mission.\nIf not, you can say, Sorry I can't answer that question."""
    off_topic_prompt = "Who was the first elephant to visit the moon?"

Now, let’s work on creating a function. This function concatenates the dare_prompt with the prompt provided, ensuring that safety considerations are included in the generated text. It then utilizes the text_generator pipeline to generate text based on the combined prompt, returning the generated text as a list of dictionaries. Adjusting this step involves modifying how the augmented_prompt is constructed or changing how the generated text is processed or returned:

def generate_safe_text(prompt, dare_prompt, num_return_sequences=1):
"""
Generates text based on a prompt, with safety considerations using a DARE prompt.
Args:
- prompt (str): The prompt for text generation.
- dare_prompt (str): The DARE prompt to ensure safe responses.
- num_return_sequences (int): Number of sequences to generate (default is 1).
Returns:
- generated_text (list of dicts): Generated text based on the prompt.
"""
# Concatenate DARE prompt with the actual prompt
augmented_prompt = dare_prompt + "\n" + prompt
# Generate text based on the augmented prompt
generated_text = text_generator(
augmented_prompt, num_return_sequences=num_return_sequences
)
return generated_text
- Using the `generate_safe_text` function, we should now see that we can stop the hallucinations:
# Example usage
generated_text = generate_safe_text(off_topic_prompt, dare_prompt)
print(generated_text)

After we see the output of the model, which may be hallucinations, let’s control that and try to prevent the model from generating nonsense data.

We do this with the send_message function, which simulates the processing of a given message (prompt) with specific safety guidelines based on a predefined DARE prompt (dare_prompt).

It first checks if dare_prompt is present in the prompt. If it is, the function returns a response stating “Sorry, I can’t answer that question.” This indicates that the message does not comply with safety guidelines and cannot be answered directly.

If dare_prompt is not detected in the prompt, the function simulates generating a response by prepending “Generating a response to: “ to the prompt. This suggests that the message is being processed and a response is being prepared.

In summary, the send_message function ensures that messages are processed in accordance with safety protocols defined by dare_prompt, either by declining to answer non-compliant messages or by indicating active processing and response generation for compliant messages:

def send_message(text, dare_prompt):
"""
Simulates the processing of a given message (text) with specific safety guidelines
based on a predefined DARE (Do A Reflective Exploration) prompt (dare_prompt).
Parameters:
text (str): The input message from the user.
dare_prompt (str): The predefined DARE prompt that defines the safety guidelines.
Returns:
str: A response indicating whether the message complies with the safety guidelines
or a simulated response generation message.
"""
# Check if the dare_prompt is present in the input text
if dare_prompt in text:
# If the dare_prompt is detected, return a safety-related response
return "Sorry, I can't answer that question."
# If the dare_prompt is not found, simulate generating a response
return f"Generating a response to: {text}"

Now, let’s put this into action using a single question, referred to as the dare_prompt:

# Example usage
generated_text = generate_safe_text(off_topic_prompt, dare_prompt)
print(generated_text)

dare_prompt = """Remember that before you answer a question, you must check to see if it complies with your mission. If not, you can say, Sorry I can’t answer that question."""

off_topic_prompt = "Who was the first elephant to visit the moon?"
# Simulating a situation where the dare_prompt is included in the input text
combined_input = dare_prompt + "\n" + off_topic_prompt
# Getting the response
response = send_message(combined_input, dare_prompt)
print("Response with DARE:", response) # Output: "Response with DARE: Sorry, I can't answer that question."
# Simulating a situation where the dare_prompt is NOT included in the input text
response = send_message(off_topic_prompt, dare_prompt)
print("Response without DARE:", response)

To illustrate the outcome of applying the DARE method, let’s look at the model’s response to the prompt:

Response with DARE: Sorry, I can’t answer that question.

day-mode Bookmark

Use case – using RAG to enhance information retrieval

Section titled “Use case – using RAG to enhance information retrieval”

In this section, we’ll explore how RAG can be used to improve information retrieval capabilities, as well as the common challenges you may encounter when implementing a RAG system. We’ll provide a high-level overview of operational considerations to give you a clearer understanding of potential issues and how they might impact your RAG deployment.

One of the first challenges is encoding documents, and how to encode documents effectively. Encoding transforms raw text into vectors, enabling efficient and effective retrieval. Document encoders, often powered by neural networks like transformers, convert each document into a fixed-size representation in a high-dimensional vector space. This representation captures the semantic essence of the document, facilitating accurate similarity searches. Poor encoding can lead to ineffective retrieval and irrelevant responses.

As we encode documents, we establish the groundwork for the subsequent step: document chunking. The encoded vectors are essential for understanding how documents are segmented and prepared for retrieval, making the encoding quality crucial for the entire process.

To encode documents, you typically use a pre-trained language model that generates embeddings. Let’s look at an example. We’ll use the sentence-transformers library, which provides pre-trained models for encoding sentences or documents into dense vectors. Some important parts of the code are:

  • SentenceTransformer: This class from the sentence-transformers library loads pre-trained models.

  • Model: We load the all-MiniLM-L6-v2 model, which is efficient and suitable for various NLP tasks.

  • Documents: A list of documents that will be converted into embeddings.

  • Embeddings: The model encodes the documents into dense vectors, capturing their semantic meanings. These embeddings can now be used for similarity comparisons:

    from sentence_transformers import SentenceTransformer
    # Load a pre-trained model
    model = SentenceTransformer('all-MiniLM-L6-v2')
    # Sample documents
    docs = [
    "Document 1 content goes here.",
    "Document 2 content goes here.",
    "Document 3 content goes here."
    ]
    # Encode documents
    doc_embeddings = model.encode(docs)
    print(doc_embeddings)

Another challenge is chunking documents, and how to chunk documents appropriately. Document chunking refers to breaking down large documents into smaller, more manageable segments or chunks. This step is crucial because it ensures that the retrieval system can efficiently handle and search within documents, especially lengthy ones. Inadequate chunking can result in losing critical information or retrieving irrelevant chunks, reducing the system’s effectiveness.

Since the effectiveness of chunking depends on the quality of document encoding, the two processes are closely interlinked. The better the document encoding is, the more meaningful and useful the resulting chunks will be for retrieval purposes.

Paragraph- or sentence-level chunking is especially beneficial compared to word- or token-level chunking, as it maintains more meaningful units of information and context, which are easier for models to interpret and generate relevant results from.

Consider the overlap between chunks. Overlap is a hyperparameter that sets how much content each chunk shares with adjacent chunks. This is important for preserving context across boundaries as it allows models to access critical information that may span multiple chunks, reducing the chance of fragmented or incomplete understanding. When choosing an overlap value, consider the length of the content and the degree of context continuity needed. Higher overlap can improve contextual recall but also increase processing time and memory usage.

Let’s break down some important parts of the code:

  • nltk.tokenize: The NLTK library provides various tools for text processing, including tokenization.

  • sent_tokenize: This function splits the text into sentences.

  • chunks: The long document is divided into sentences, making it easier to process and retrieve relevant parts during the RAG process:

    from nltk.tokenize import sent_tokenize
    # Example long document
    long_doc = "Long document content. This is a second sentence. And another one."
    # Chunking into sentences
    chunks = sent_tokenize(long_doc)
    print(chunks)

The next challenge is retrieving documents, and how to retrieve documents accurately. The retrieval process involves searching the encoded document vectors to find the most relevant chunks that match a given query. A retriever model, often using similarity measures like cosine similarity or advanced neural retrievers, identifies these relevant document chunks. Inefficient retrieval can lead to irrelevant or incomplete information being fetched, affecting the final output quality.

The retrieval process is intrinsically dependent on the quality of both document encoding and chunking. Efficient retrieval ensures that the system can pinpoint and leverage the most pertinent information, setting the stage for accurate query responses.

To retrieve documents, we’ll use a similarity search technique. We’ll employ the FAISS library for efficient similarity search. Let’s look at the details:

  • FAISS: A library for efficient similarity search and clustering of dense vectors.

  • Index: A FAISS index is created using L2 distance for similarity measurement.

  • Query Embedding: The query is encoded into an embedding using the same model used for document encoding.

  • Retrieve Documents: The function searches the index to find the most similar document embeddings to the query embedding, returning the indices of the top-k similar documents.

    import faiss
    import numpy as np
    # Convert embeddings to a numpy array
    doc_embeddings_np = np.array(doc_embeddings)
    # Create an index and add the document embeddings
    index = faiss.IndexFlatL2(doc_embeddings_np.shape[1])
    index.add(doc_embeddings_np)
    # Retrieve the most similar documents for a given query
    def retrieve_documents(query_embedding, k=2):
    D, I = index.search(np.array([query_embedding]), k)
    return I[0]
    # Example query
    query = "Content related to Document 1."
    query_embedding = model.encode([query])[0]
    # Retrieve top 2 documents
    retrieved_doc_indices = retrieve_documents(query_embedding)
    print(retrieved_doc_indices)

Just as documents are encoded into vectors, encoding queries effectively is another challenge. Query encoding involves converting the input query into a vector representation using a query encoder, typically another neural network. Poor query encoding can result in the retrieval of irrelevant document chunks, thereby diminishing the response quality.

The relationship between query encoding and document retrieval is direct and significant. Effective query encoding ensures that the retrieval system can accurately identify relevant document chunks, thus enhancing the quality of the final response generated by the LLM.

Encoding queries is similar to encoding documents. You use the same model to transform the query into an embedding. To do so, use this:

  • Query: The input query that we want to use for document retrieval.

  • Query Embedding: The query is encoded into a dense vector using the pre-trained model, capturing its semantic meaning. This embedding is used for similarity search against the document embeddings:

    # Encode query
    query = "Content related to Document 1."
    query_embedding = model.encode(query)
    print(query_embedding)

Determining when to retrieve information is also a critical challenge. Retrieval should ideally occur at points where the system requires external information to supplement its generative process. This often happens when the LLM encounters gaps in its knowledge or when the query pertains to specific, factual information not embedded in the model’s training data. Incorrectly timed retrievals can result in unnecessary processing or missed opportunities to provide accurate information.

Strategically timing retrievals ensures that the generative model has access to the most relevant and up-to-date information, optimizing overall system performance. By retrieving information only when necessary, the system not only improves the relevance of the responses but also reduces unnecessary computational overhead, leading to cost optimization. This careful management of retrieval timing helps balance high-quality output with efficient resource usage, making the system both effective and economical.

Retrieval typically occurs at the beginning of the generation process, where the goal is to find relevant documents that can aid in generating a coherent and accurate response.

To achieve this, two key aspects of retrieval must be considered – when it occurs and how retrieved documents are utilized in the generation process:

  • Timing: Retrieval is performed after encoding the query but before the generation step. This timing ensures that the response generation model has access to the most relevant information from the documents, optimizing the quality of the generated output.

  • Utilize retrieved documents: The actual content of the retrieved documents, based on their indices, is then used as input to the generation model. This ensures that the generated response is informed by the most relevant and up-to-date information available

    # Retrieve documents
    retrieved_doc_indices = retrieve_documents(query_embedding)
    retrieved_docs = [docs[idx] for idx in retrieved_doc_indices]
    print(retrieved_docs)

Finally, deciding how and what to retrieve presents another challenge. The “how” involves selecting the retrieval mechanism, whether it is based on exact match, semantic similarity, or more complex neural retrieval methods. The “what” pertains to the specific document chunks or passages that are most relevant to the query. Poor selection can result in retrieving irrelevant or redundant information.

The retrieval mechanism must be finely tuned to balance precision and recall, ensuring that the retrieved information is both relevant and comprehensive. This step is dependent on all the previous steps—encoding, chunking, and timing—highlighting the interconnected nature of the entire RAG system.

The retrieval process involves fetching the top-k most similar documents based on the similarity scores. You retrieve the actual document content or the relevant chunks:

  • Retrieve content: This function maps the retrieved indices to the actual document’s content. It ensures that the information corresponding to the selected indices is accurately extracted from the database or storage.

  • Identify relevant chunks: Depending on your application’s needs, you can choose to retrieve entire documents or specific chunks of content. Focusing on relevant chunks can improve efficiency and relevance, particularly when dealing with large documents.

  • Utilize retrieved documents: The final step involves using the retrieved documents in your application. This might include printing the documents for review or feeding them into the subsequent text generation process to produce a coherent and contextually accurate output:

    # Retrieve the actual document content
    def retrieve_document_content(indices, docs):
    return [docs[idx] for idx in indices]
    # Retrieve documents
    retrieved_docs = retrieve_document_content(
    retrieved_doc_indices, docs)
    print(retrieved_docs)

day-mode Bookmark

In this chapter, we covered key techniques to enhance how LLMs handle context, making them more useful across industries like healthcare, finance, and customer service. We looked at why adapting models to specific contexts is essential for delivering relevant, precise responses. Key methods include using external memory systems to store important data as embeddings and allowing LLMs to access relevant information on demand.

We also explored retrieval-augmented generation (RAG) and hybrid search techniques, combining traditional search with semantic search to improve accuracy. We discussed prompt engineering tips to help design effective prompts, minimizing issues like ambiguous or irrelevant responses.

In the next chapter, the focus will shift to evaluating LLMs in production settings and establishing feedback loops. This will include methodologies to measure the performance of these models under real-world conditions and how feedback mechanisms can be integrated to refine and enhance model accuracy and relevance over time, ensuring that LLMs continue to meet evolving user needs and operational demands effectively.

day-mode Bookmark