{"id":9094,"date":"2024-02-03T11:29:47","date_gmt":"2024-02-03T19:29:47","guid":{"rendered":"https:\/\/live-cometml.pantheonsite.io\/?p=9094"},"modified":"2025-04-24T17:03:21","modified_gmt":"2025-04-24T17:03:21","slug":"conversational-ai-with-langchain-and-comet","status":"publish","type":"post","link":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/","title":{"rendered":"Conversational AI with LangChain and\u00a0Comet"},"content":{"rendered":"\n<h3 class=\"wp-block-heading graf graf--h3\"><\/h3>\n\n\n\n<figure class=\"wp-block-image graf graf--figure\"><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/1600\/1*v4MRs216R7wf6DKQoiYJaA.png\" alt=\"\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">An Introduction to Conversational AI<\/h3>\n\n\n\n<p class=\"graf graf--p\">AI chatbots and other conversational AI offer 24\/7 availability support, minimize errors, save costs, boost sales, and engage customers effectively. Businesses are drawn to chatbots not only for the aforementioned reasons but also due to their user-friendly creation process.<\/p>\n\n\n\n<p class=\"graf graf--p\">As per <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/www.gartner.com\/en\/newsroom\/press-releases\/2022-07-27-gartner-predicts-chatbots-will-become-a-primary-customer-service-channel-within-five-years\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/www.gartner.com\/en\/newsroom\/press-releases\/2022-07-27-gartner-predicts-chatbots-will-become-a-primary-customer-service-channel-within-five-years\">Gartner<\/a>, the primary source of customer service will be AI chatbots for 25% of organizations by 2027. Additionally, <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/www.zendesk.com\/blog\/5-benefits-using-ai-bots-customer-service\/\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/www.zendesk.com\/blog\/5-benefits-using-ai-bots-customer-service\/\">Zendesk<\/a> reports that 72% of business leaders prioritize expanding AI and chatbots across the customer experience within 2024.<\/p>\n\n\n\n<p class=\"graf graf--p\">Creating a chatbot is now more accessible with many development platforms available. Among many options, LangChain stands out as a powerful library for creating chatbots because it is flexible, scalable, and open-source.<\/p>\n\n\n\n<p class=\"graf graf--p\">This article lightly touches on the history and components of chatbots. Later, it explores the s the implementation of chatbots using LangChain and the experiment tracking using <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/www.comet.com\/\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/www.comet.com\/\">Comet<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">Chatbots\u200a\u2014\u200aThen and&nbsp;Now<\/h3>\n\n\n\n<p class=\"graf graf--p\">Early chatbots could not grasp the context and nuances of language. One of the first chatbots, <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/www.chatbots.org\/chatbot\/eliza\/\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/www.chatbots.org\/chatbot\/eliza\/\">ELIZA<\/a>, was developed in 1966 to mimic human interaction and had built-in scripts to create the illusion of intelligence.<\/p>\n\n\n\n<p class=\"graf graf--p\">Later, chatbots relied on rule-based systems and simpler machine learning approaches. These chatbots had limited capabilities and responded to specific keywords and phrases. This evolution paved the way for the development of conversational AI.<\/p>\n\n\n\n<p class=\"graf graf--p\">The recent rise of Large Language Models (LLMs) has been a game changer for the ChatBot industry. These models are trained on extensive data and have been the driving force behind conversational tools like <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/bard.google.com\/\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/bard.google.com\/\">BARD<\/a> and <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/openai.com\/chatgpt\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/openai.com\/chatgpt\">ChatGPT<\/a>. These LLM-based bots have found various applications in various industries and have become the go-to information source for many people.<\/p>\n\n\n\n<p class=\"graf graf--p\">However, chatbots are not only restricted to such commercial platforms, and developers can create their custom models using frameworks like LangChain.<\/p>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">What is LangChain?<\/h3>\n\n\n\n<p class=\"graf graf--p\">LangChain is an open-source framework, available in Python and Javascript libraries, that enables users to build applications using LLMs. Fundamentally, LangChain operates as an LLM-centered framework, capable of building chatbot applications, Visual Question-Answering (VQA), summarization, and much more.<\/p>\n\n\n\n<p class=\"graf graf--p\">Think of LangChain as a toolbox for Python and Javascript that provides ready-to-use building blocks for working with language models. These building blocks, similar to functions and object classes, are essential components for creating generative AI programs. These components connect seamlessly, allowing you to build applications with less code and without requiring complicated natural language processing (NLP) tasks.<\/p>\n\n\n\n<p class=\"graf graf--p\">A distinctive feature of LangChain is its innovative Agents. They operate on the fundamental concept of utilizing a language model to decide on a sequence of actions. Agents leverage a language model as a reasoning engine to determine the actions and their order dynamically.<\/p>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">Components of Conversational AI<\/h3>\n\n\n\n<p class=\"graf graf--p\">The LangChain framework includes various modules, each of which adds to the chatbot\u2019s functionality. This section will explore each component in detail and discuss how it facilitates the creation of a functional chatbot.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Chat Model<\/h4>\n\n\n\n<p class=\"graf graf--p\">Chat models are a category of LLMs specifically trained to output human-like, conversational responses. LLMs and chat models are slightly different as LLMs are pure text completion models, and chat models are fine-tuned for having conversations.<\/p>\n\n\n\n<p class=\"graf graf--p\">Chat models utilize a distinct input interface compared to LLMs, accepting a list of chat messages labeled as System, AI, and Human. The AI chat message is then provided as the output from the chat model. LangChain provides a <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/python.langchain.com\/docs\/integrations\/chat\/\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/python.langchain.com\/docs\/integrations\/chat\/\">diverse range of chat models<\/a> and also accommodates custom chat models.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Prompt Template<\/h4>\n\n\n\n<p class=\"graf graf--p\">Prompt acts as a set of instructions or input to the language model by a user to guide model response. The purpose of prompting is to help chat models understand the context and generate relevant outputs.<\/p>\n\n\n\n<p class=\"graf graf--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/python.langchain.com\/docs\/modules\/model_io\/prompts\/prompt_templates\/\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/python.langchain.com\/docs\/modules\/model_io\/prompts\/prompt_templates\/\">Prompt templates<\/a> serve as predefined formulas for crafting and reusing prompts across multiple language models. Language models commonly anticipate prompts as a string or a list of conversational messages.<\/p>\n\n\n\n<p class=\"graf graf--p\">Since the prompts are a list of messages, we can use `ChatPromptTemplate` for it. Each chat message is associated with content and role, e.g., Human, AI, or a system role.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Chains<\/h4>\n\n\n\n<p class=\"graf graf--p\">A stand-alone LLM is great for basic tasks, but intricate applications require a complex architecture that chains multiple components with the model. LangChain-supported chains include <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/python.langchain.com\/docs\/modules\/chains\/foundational\/llm_chain\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/python.langchain.com\/docs\/modules\/chains\/foundational\/llm_chain\">LLMChain<\/a>, <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/python.langchain.com\/docs\/modules\/chains\/foundational\/router\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/python.langchain.com\/docs\/modules\/chains\/foundational\/router\">RouterChain<\/a>, and <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/python.langchain.com\/docs\/modules\/chains\/foundational\/sequential_chains\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/python.langchain.com\/docs\/modules\/chains\/foundational\/sequential_chains\">SequentialChain<\/a>. The most basic chain is the LLMChain, which combines the LLM, prompt, and optionally an output parser.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Memory<\/h4>\n\n\n\n<p class=\"graf graf--p\">A key component of natural conversation is the ability to reference prior information, which must be stored in memory for later use. In LangChain, the `memory` component solves the problem by simply keeping track of previous conversations.<\/p>\n\n\n\n<p class=\"graf graf--p\">Every chain in LangChain defines some core execution that expects certain inputs. Some inputs originate directly from the user, others are retrieved from the memory. When chains are executed, they interact with the memory system twice. First, when it receives the input from the user, it will read from the memory and augment the user inputs.<\/p>\n\n\n\n<p class=\"graf graf--p\">Additionally, prior to delivering the output, the chain will record the inputs and outputs of the ongoing execution in the memory.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Documents<\/h4>\n\n\n\n<p class=\"graf graf--p\">Chatbots are most useful to businesses when custom-trained for a specific domain. LangChain loads training data in the form of \u2018Documents\u2019, and these contain text from various sources and their respective metadata. The `Document` class provides various document loader methods to load data from sources, including PDF, HTML, JSON, and CSV.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Retriever<\/h4>\n\n\n\n<p class=\"graf graf--p\">It\u2019s essential for chat models to extract only the information from relevant documents given a query for accurate responses. Retrievers do this job of returning documents by providing a query as input and returning a list of documents.<\/p>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">Building a Conversation AI With LangChain and&nbsp;Comet<\/h3>\n\n\n\n<p class=\"graf graf--p\">The following section will guide you through the explanation and implementation of a retail chatbot. The chatbot will provide users with information about retail products, detailing specifications, prices, and reviews.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Setup<\/h4>\n\n\n\n<p class=\"graf graf--p\">The following chatbot uses OpenAI\u2019s chat model <strong class=\"markup--strong markup--p-strong\">GPT-3.5-turbo <\/strong>and, therefore, includes OpenAI\u2019s API key. Users can get the API key by creating a free account <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/platform.openai.com\/signup\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/platform.openai.com\/signup\">here<\/a>. Additionally, the application will be monitored using the <a class=\"markup--anchor markup--p-anchor\" href=\"http:\/\/comet.com\/signup?utem_source=Heartbeat&amp;utm_content=HaziqaSajid\" target=\"_blank\" rel=\"noopener\" data-href=\"http:\/\/comet.com\/signup?utem_source=Heartbeat&amp;utm_content=HaziqaSajid\">Comet<\/a> platform to keep track of all inputs and outputs. First, we will need to create a Comet account to access its API key.<\/p>\n\n\n\n<p class=\"graf graf--p\">Afterwards, we need to install the following libraries using the PIP package manager. Run the following command:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">!pip install langchain openai comet_ml comet-llm textstat tiktoken faiss-gpu```<\/span><\/pre>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Chat Models<\/h4>\n\n\n\n<p class=\"graf graf--p\">As discussed above, chat models are backed by LLMs such as GPT or Anthropic and are essential for conversational AI. They specialize in having a conversation rather than text completion. For this chatbot, we will be using GPT-3.5. There are many chat models supported in LangChain that can be found <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/python.langchain.com\/docs\/integrations\/chat\/\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/python.langchain.com\/docs\/integrations\/chat\/\">here<\/a>.<\/p>\n\n\n\n<p class=\"graf graf--p\">Here\u2019s a snippet to initialize a chat model:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">from<\/span> langchain.chat_models <span class=\"hljs-keyword\">import<\/span> ChatOpenAI\n\nllm = ChatOpenAI(temperature = <span class=\"hljs-number\">0.4<\/span>, openai_api_key=<span class=\"hljs-string\">\"...\"<\/span>)<\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">Here, the temperature parameters adjust the creativity of the response as it increases with a higher temperature.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Prompt<\/h4>\n\n\n\n<p class=\"graf graf--p\">Prompts guide chatbots in responding to queries. LangChain provides prompt templates that simplify the creation of prompts by combining default messages, user input, and chat history.<\/p>\n\n\n\n<p class=\"graf graf--p\">The following is the prompt for the chatbot:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">from<\/span> langchain.prompts <span class=\"hljs-keyword\">import<\/span> (\n   ChatPromptTemplate,\n   HumanMessagePromptTemplate,\n   MessagesPlaceholder,\n   SystemMessagePromptTemplate,\n)\n\n\ninstructions = <span class=\"hljs-string\">\"\"\"You are a friendly chatbot capable of answering questions related to products. Users can ask questions about its specifications, prices, and reviews. Be polite and redirect conversation specifically to product information when necessary.\"\"\"<\/span>\n\nhuman = <span class=\"hljs-string\">\"\"\" Chat history of the user: {chat_history} New human question: {input} \"\"\"<\/span>\n\nprompt = ChatPromptTemplate(messages=[\n\nSystemMessagePromptTemplate.from_template(instructions), <span class=\"hljs-comment\"># Guidance<\/span>\n\nHumanMessagePromptTemplate.from_template(human), <span class=\"hljs-comment\">#User query], <\/span>\n\ninput_variables=[<span class=\"hljs-string\">'chat_history'<\/span>,<span class=\"hljs-string\">'input'<\/span>] <span class=\"hljs-comment\"># variables)<\/span><\/span><\/pre>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Memory<\/h4>\n\n\n\n<p class=\"graf graf--p\">Memory is important for conversational AI, as it allows the conversation to be stored and adds it to the current query for reference of the previous conversation. There are many memories supported by LangChain, as discussed above.<\/p>\n\n\n\n<p class=\"graf graf--p\">Now, we will use ConversationBufferWindowMemory to track the last four interactions. Here\u2019s how to create it:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">from<\/span> langchain.memory <span class=\"hljs-keyword\">import<\/span> ConversationBufferWindowMemory\n\nmemory = ConversationBufferWindowMemory(memory_key = <span class=\"hljs-string\">\"chat_history\"<\/span>,k = <span class=\"hljs-number\">4<\/span>)<\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">The parameter `k` determines how many previous conversations need to go to the chat model.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Chains<\/h4>\n\n\n\n<p class=\"graf graf--p\">Chains are a simple concept of connecting different pieces, like language models, prompts, memory buffers, etc, into a single chain.<\/p>\n\n\n\n<p class=\"graf graf--p\">Here\u2019s how the previous components can be connected to make the chatbot:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">from<\/span> langchain.chains <span class=\"hljs-keyword\">import<\/span> ConversationChain\n\n\nconversation = ConversationChain(llm = llm,\n                                 prompt = prompt,\n                                 memory = memory,\n                                 verbose = <span class=\"hljs-literal\">False<\/span>) <span class=\"hljs-comment\"># LLMChain conversation<\/span>\n\nconversation.run(<span class=\"hljs-string\">\"Hi, my name is Bob.\"<\/span>)\n<span class=\"hljs-comment\">#### AI: Hey Bob, how can I help you?<\/span>\nconversation.run(<span class=\"hljs-string\">\"What is my name?\"<\/span>)\n<span class=\"hljs-comment\">#### AI: Your name is Bob. Is there anything else I can help you with?<\/span><\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">As we can see, the chatbot is using the previous conversation. `ConversationChain()` takes in multiple parameters such as LLM, prompt and memory to respond to the queries of users, but this chatbot does not have the information of the products.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Documents<\/h4>\n\n\n\n<p class=\"graf graf--p\">Our chatbot requires documents for lookup and answering product-related questions which include reviews, product specifications, and prices.<\/p>\n\n\n\n<p class=\"graf graf--p\">So, let\u2019s download the dataset from the <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/data.world\/datafiniti\/consumer-reviews-of-amazon-products\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/data.world\/datafiniti\/consumer-reviews-of-amazon-products\">data world<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">import<\/span> pandas <span class=\"hljs-keyword\">as<\/span> pd\n\ndf = pd.read_csv(\n<span class=\"hljs-string\">'https:\/\/query.data.world\/s\/76kyenosebb7rtcruaarjgnfogum66?dws=00000'<\/span>)\n\ndf.to_csv(<span class=\"hljs-string\">'product.csv'<\/span>,\n          sep=<span class=\"hljs-string\">','<\/span>,\n          index=<span class=\"hljs-literal\">False<\/span>,\n          encoding=<span class=\"hljs-string\">'utf-8'<\/span>) <span class=\"hljs-comment\">#Saving as a csv<\/span><\/span><\/pre>\n\n\n\n<ul class=\"wp-block-list postList\">\n<li><strong class=\"markup--strong markup--li-strong\">Load: <\/strong>In order to load the CSV dataset, LangChain provides <strong class=\"markup--strong markup--li-strong\">CSVLoader<\/strong>. Here\u2019s how to load the CSV file.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">from<\/span> langchain.document_loaders.csv_loader <span class=\"hljs-keyword\">import<\/span> CSVLoader\n\nloader = CSVLoader(file_path=<span class=\"hljs-string\">'product.csv'<\/span>,\n                   csv_args={ <span class=\"hljs-string\">'delimiter'<\/span>: <span class=\"hljs-string\">','<\/span>})\n\ndata = loader.load()<\/span><\/pre>\n\n\n\n<ul class=\"wp-block-list postList\">\n<li><strong class=\"markup--strong markup--li-strong\">Split:<\/strong> Here we need special care as we can not pass in data without splitting because the context that will be passed later to the LLM can exceed the token limit. Therefore, we need to split the data. Here\u2019s how:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">from<\/span> langchain.text_splitter <span class=\"hljs-keyword\">import<\/span> RecursiveCharacterTextSplitter\nSplitter = RecursiveCharacterTextSplitter(chunk_size = <span class=\"hljs-number\">1500<\/span>, chunk_overlap = <span class=\"hljs-number\">150<\/span>)\nsplits = Splitter.create_documents(<\/span><\/pre>\n\n\n<p>[datum.page_content <span class=\"hljs-keyword\">for<\/span> datum <span class=\"hljs-keyword\">in<\/span> data]<\/p>\n\n\n\n<p>                             )\n<\/p>\n\n\n\n<p class=\"graf graf--p\">In the snippet, the text splitter is splitting the document in equal 1500 characters with an overlapping chunk of 150. This will create more documents but with fewer words in each document.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Retriever<\/h4>\n\n\n\n<p class=\"graf graf--p\">Retrievers can be created very easily using vector stores. Here we will be using the FAISS vector store and using OpenAI\u2019s embeddings.<\/p>\n\n\n\n<p class=\"graf graf--p\">Let\u2019s look at a code snippet:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">from<\/span> langchain.<span class=\"hljs-property\">vectorstores<\/span> <span class=\"hljs-keyword\">import<\/span> <span class=\"hljs-variable constant_\">FAISS<\/span>\n\n<span class=\"hljs-keyword\">from<\/span> langchain.<span class=\"hljs-property\">embeddings<\/span>.<span class=\"hljs-property\">openai<\/span> <span class=\"hljs-keyword\">import<\/span> <span class=\"hljs-title class_\">OpenAIEmbeddings<\/span>\n\nembeddings = <span class=\"hljs-title class_\">OpenAIEmbeddings<\/span>( openai_api_key=<span class=\"hljs-string\">\"...\"<\/span>)\n\nvectorstore = <span class=\"hljs-variable constant_\">FAISS<\/span>.<span class=\"hljs-title function_\">from_documents<\/span>(splits, embeddings)<\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">LangChain establishes a Retriever interface that encapsulates an index capable of providing pertinent documents in response to a textual query. All retrievers uniformly implement the method `get_relevant_documents().`<\/p>\n\n\n\n<p class=\"graf graf--p\">Additionally, it is required to pass in the context to the prompt template. We can fix it by passing context as input:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">instructions = <span class=\"hljs-string\">\"\"\"...\"\"\"<\/span> <span class=\"hljs-comment\"># Same instructions as above <\/span>\n\nhuman = <span class=\"hljs-string\">\"\"\" The context is provided as: {context} New human question: {question} \"\"\"<\/span>\n\nprompt = ChatPromptTemplate( messages=[<span class=\"hljs-comment\">#same as above], input_variables=['context','question'])<\/span><\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">LangChain conversation Retrieval chain is very useful to cater memory, retriever and prompt altogether. Here\u2019s the code snippet:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">from<\/span> langchain.chains <span class=\"hljs-keyword\">import<\/span> ConversationalRetrievalChain\n\nretriever = vectorstore.as_retriever(search_type=<span class=\"hljs-string\">\"similarity\"<\/span>, search_kwargs={<span class=\"hljs-string\">\"k\"<\/span>: <span class=\"hljs-number\">5<\/span>})\n\nqa = ConversationalRetrievalChain.from_llm(llm = llm, memory=memory,  get_chat_history=<span class=\"hljs-keyword\">lambda<\/span> x : x,\nretriever=retriever,\ncombine_docs_chain_kwargs={<span class=\"hljs-string\">\"prompt\"<\/span>: prompt})<\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">The retriever is searching the similarity of the query with documents which will result in the first five relevant documents. These will be passed as a context to the chat model.<\/p>\n\n\n\n<p class=\"graf graf--p\">Now, let\u2019s create a simple function to chat with the chatbot:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title function_\">predict<\/span>(<span class=\"hljs-params\">question<\/span>):\n     ai_msg = qa({<span class=\"hljs-string\">\"question\"<\/span><span class=\"hljs-symbol\">:question<\/span>})[<span class=\"hljs-string\">'answer'<\/span>]\n     <span class=\"hljs-keyword\">return<\/span> ai_msg<\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">Here are the results from the chatbot:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">predict(<span class=\"hljs-string\">\"Hi, my name is Bob?\"<\/span>)\n\n<span class=\"hljs-comment\">### Hello Bob! How can I assist you today?<\/span>\n\npredict(<span class=\"hljs-string\">\"What can you do?\"<\/span>)\n\n<span class=\"hljs-comment\">### As a chatbot, my capabilities include answering questions about product specifications, prices, and reviews. I can provide information on a wide range of products. If you have any specific questions or need assistance with a particular product, feel free to ask!<\/span>\n\npredict(<span class=\"hljs-string\">\"What's the price kindle paperwhite?\"<\/span>)\n\n<span class=\"hljs-comment\">### The base model of the Kindle Paperwhite is priced at $99.<\/span><\/span><\/pre>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">Tracking and Monitoring Conversational AI with Comet<\/h3>\n\n\n\n<p class=\"graf graf--p\">When creating applications with LLMs, most of the time is spent on prompt engineering rather than training the models. This has introduced a new area of expertise: LLMOps.<\/p>\n\n\n\n<p class=\"graf graf--p\">Comet has a rich set of features for LLMOps:<\/p>\n\n\n\n<ul class=\"wp-block-list postList\">\n<li>LLM Projects: It is designed for analyzing prompts, responses, and chaining.<\/li>\n\n\n\n<li>LLM Panels: While working with LLMs, workflows may involve a combination of fine-tuning and prompt engineering. This can be tracked using either separate projects for each part or a single project with LLM panels.<\/li>\n<\/ul>\n\n\n\n<p class=\"graf graf--p\">After creating the <a class=\"markup--anchor markup--p-anchor\" href=\"http:\/\/comet.com\/signup?utm_source=Heartbeat&amp;utm_content=HaziqaSajid\" target=\"_blank\" rel=\"noopener\" data-href=\"http:\/\/comet.com\/signup?utm_source=Heartbeat&amp;utm_content=HaziqaSajid\">Comet<\/a> account, go to accounts settings and generate an API key. After logging in successfully, go to account settings and generate an API key.<\/p>\n\n\n\n<figure class=\"wp-block-image graf graf--figure\"><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*cddT6NcWGbjaZMR2\" alt=\"\"\/><figcaption class=\"wp-element-caption\">Comet Account&nbsp;Settings<\/figcaption><\/figure>\n\n\n\n<p class=\"graf graf--p\">Next, simply replace with the following texts:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">COMET_API_KEY = <span class=\"hljs-string\">\"COMET_API_KEY\"<\/span>\nCOMET_WORKSPACE = <span class=\"hljs-string\">\"COMET_WORKSPACE\"<\/span>\nPROJECT_NAME = <span class=\"hljs-string\">\"Product-Bot-v1\"<\/span> <span class=\"hljs-comment\"># initialize comet comet_llm.init(COMET_API_KEY, COMET_WORKSPACE, project=PROJECT_NAME)<\/span><\/span><\/pre>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Tracking Conversational AI<\/h4>\n\n\n\n<p class=\"graf graf--p\">Now, to track the outputs of the conversational AI and check whether the prompt is good for your use case, Comet has a simple function <strong class=\"markup--strong markup--p-strong\">log_prompt<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">queries = [<span class=\"hljs-string\">\"Hi,my name is Bob?\"<\/span>,\n           <span class=\"hljs-string\">\"What can you do?\"<\/span>,\n           <span class=\"hljs-string\">\"What is the best product?\"<\/span>,\n           <span class=\"hljs-string\">\"What's the price kindle paperwhite?\"<\/span>]\n\nexpected_response = [<span class=\"hljs-string\">\"Hello, how can you assist you.\"<\/span>,\n\n<span class=\"hljs-string\">\"As a chatbot, my capabilities include answering questions about product specifications, prices, and reviews. \\ I can provide information about various products and assist you in finding the information you need. \\ If you have any specific questions or need assistance with a particular product, feel free to ask.\"<\/span>,\n\n<span class=\"hljs-string\">\"Based on the information provided, there is no single clear winner among the tablets mentioned.\\ Each tablet has its own strengths and weaknesses. The Amazon HDX and Nexus are praised for their pricing, \\ while Apple and Google have more app choices. If you are heavily invested in the Apple ecosystem, \\ the iPad Mini might be a good choice. Ultimately, the best product will depend on your personal preferences and requirements.\"<\/span>,\n\n<span class=\"hljs-string\">\"The base model of the Kindle Paperwhite is priced at $99.\"<\/span>]\n\n\n<span class=\"hljs-keyword\">for<\/span> index, convo <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-built_in\">enumerate<\/span>(queries): <span class=\"hljs-comment\"># log the few-shot predictions   <\/span>\n\n  comet_llm.log_prompt(prompt=convo,\n                       prompt_template= instructions,\n                       output=predict(convo),\n                       tags = [<span class=\"hljs-string\">\"gpt-3.5-turbo\"<\/span>, <span class=\"hljs-string\">\"prompt_1\"<\/span>],\n                       metadata = { <span class=\"hljs-string\">\"expected_answer\"<\/span>:\n                                     expected_response[index]})<\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">The function <em class=\"markup--em markup--p-em\">log_prompt<\/em> requires two parameters: user query and output of the model. The rest are optional like prompt template, metadata, tags, etc.<\/p>\n\n\n\n<p class=\"graf graf--p\">After this step, the logs will be on the Comet\u2019s LLMOps dashboard:<\/p>\n\n\n\n<figure class=\"graf graf--figure\">\n<\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter graf-image\"><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*NTsmzabj3gYSp9l0\" alt=\"CometLLM, Comet LLMOps, Prompt Engineering, Conversational AI, LangChain\"\/><figcaption class=\"wp-element-caption\">Comet LLMOps dashboard<\/figcaption><\/figure>\n\n\n\n<p class=\"graf graf--p\">Each column represents necessary information like <em class=\"markup--em markup--p-em\">name<\/em> is a unique identifier, <em class=\"markup--em markup--p-em\">tags <\/em>are used for classification, <em class=\"markup--em markup--p-em\">input_prompt<\/em> represents the user query and so on<em class=\"markup--em markup--p-em\">.<\/em> Comet provides many other <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/www.comet.com\/docs\/v2?utm_source=Heartbeat&amp;utm_content=HaziqaSajid\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/www.comet.com\/docs\/v2?utm_source=Heartbeat&amp;utm_content=HaziqaSajid\">features<\/a> for LLMOps to make the development of chatbots and other conversational AI easier and more organized.<\/p>\n\n\n\n<p class=\"graf graf--p\">There are many other useful ways to represent information. For example, the group by option is used to group prompts on columns.<\/p>\n\n\n\n<figure class=\"graf graf--figure\">\n<\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter graf-image\"><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*pLWy4lRca1pC81Kj\" alt=\"CometLLM, Comet LLMOps, Prompt Engineering, LangChain, Conversational AI\"\/><figcaption class=\"wp-element-caption\">Group prompts by columns, including hyperparameters like temperature (as seen in the CometLLM dashboard)<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">Conversational AI: Key Takeaways<\/h3>\n\n\n\n<p class=\"graf graf--p\">LangChain emerges as a robust open-source framework for creating chatbots, offering flexibility and scalability. With components like Chat Models, Prompt Templates, Chains, Memory, Documents, and Retrievers, LangChain simplifies chatbot development, catering to diverse business needs.<\/p>\n\n\n\n<p class=\"graf graf--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"http:\/\/comet.com\/site?utm_source=Heartbeat&amp;utm_content=HaziqaSajid\" target=\"_blank\" rel=\"noopener\" data-href=\"http:\/\/comet.com\/site?utm_source=Heartbeat&amp;utm_content=HaziqaSajid\">Comet<\/a>, a monitoring and tracking tool, complements LangChain seamlessly. Simplifying LLMOps, Comet\u2019s features like LLM Projects and Panels aid in prompt analysis, response evaluation, and chaining visualization. Comet\u2019s platform is utilized by data science and machine learning teams to monitor, contrast and enhance models, including the leading conversational AI applications of today.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>An Introduction to Conversational AI AI chatbots and other conversational AI offer 24\/7 availability support, minimize errors, save costs, boost sales, and engage customers effectively. Businesses are drawn to chatbots not only for the aforementioned reasons but also due to their user-friendly creation process. As per Gartner, the primary source of customer service will be [&hellip;]<\/p>\n","protected":false},"author":54,"featured_media":9097,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"customer_name":"","customer_description":"","customer_industry":"","customer_technologies":"","customer_logo":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[65,7],"tags":[72,40,64,66,67,70,71,52,31,34],"coauthors":[156],"class_list":["post-9094","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-llmops","category-tutorials","tag-chatbots","tag-comet","tag-cometllm","tag-hyperparameter-optimization","tag-hyperparameter-tuning","tag-langchain","tag-language-models","tag-llm","tag-llmops","tag-prompt-engineering"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v25.9 (Yoast SEO v25.9) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Conversational AI with LangChain and\u00a0Comet - Comet<\/title>\n<meta name=\"description\" content=\"Conversational AI is more accessible than ever due to tools like LangChain + Comet that integrate seamlessly to streamline chatbot development\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Conversational AI with LangChain and\u00a0Comet\" \/>\n<meta property=\"og:description\" content=\"Conversational AI is more accessible than ever due to tools like LangChain + Comet that integrate seamlessly to streamline chatbot development\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/\" \/>\n<meta property=\"og:site_name\" content=\"Comet\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/cometdotml\" \/>\n<meta property=\"article:published_time\" content=\"2024-02-03T19:29:47+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-04-24T17:03:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2024\/02\/Screenshot-2024-02-03-at-1.39.31\u202fPM.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1854\" \/>\n\t<meta property=\"og:image:height\" content=\"1036\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Haziqa Sajid\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@Cometml\" \/>\n<meta name=\"twitter:site\" content=\"@Cometml\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Haziqa Sajid\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"12 minutes\" \/>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Conversational AI with LangChain and\u00a0Comet - Comet","description":"Conversational AI is more accessible than ever due to tools like LangChain + Comet that integrate seamlessly to streamline chatbot development","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/","og_locale":"en_US","og_type":"article","og_title":"Conversational AI with LangChain and\u00a0Comet","og_description":"Conversational AI is more accessible than ever due to tools like LangChain + Comet that integrate seamlessly to streamline chatbot development","og_url":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/","og_site_name":"Comet","article_publisher":"https:\/\/www.facebook.com\/cometdotml","article_published_time":"2024-02-03T19:29:47+00:00","article_modified_time":"2025-04-24T17:03:21+00:00","og_image":[{"width":1854,"height":1036,"url":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2024\/02\/Screenshot-2024-02-03-at-1.39.31\u202fPM.png","type":"image\/png"}],"author":"Haziqa Sajid","twitter_card":"summary_large_image","twitter_creator":"@Cometml","twitter_site":"@Cometml","twitter_misc":{"Written by":"Haziqa Sajid","Est. reading time":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/#article","isPartOf":{"@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/"},"author":{"name":"Haziqa Sajid","@id":"https:\/\/www.comet.com\/site\/#\/schema\/person\/b8e568abee61cd8fd0c5d73b672779da"},"headline":"Conversational AI with LangChain and\u00a0Comet","datePublished":"2024-02-03T19:29:47+00:00","dateModified":"2025-04-24T17:03:21+00:00","mainEntityOfPage":{"@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/"},"wordCount":1939,"publisher":{"@id":"https:\/\/www.comet.com\/site\/#organization"},"image":{"@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/#primaryimage"},"thumbnailUrl":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2024\/02\/Screenshot-2024-02-03-at-1.39.31\u202fPM.png","keywords":["Chatbots","Comet","CometLLM","Hyperparameter Optimization","Hyperparameter Tuning","LangChain","Language Models","LLM","LLMOps","Prompt Engineering"],"articleSection":["LLMOps","Tutorials"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/","url":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/","name":"Conversational AI with LangChain and\u00a0Comet - Comet","isPartOf":{"@id":"https:\/\/www.comet.com\/site\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/#primaryimage"},"image":{"@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/#primaryimage"},"thumbnailUrl":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2024\/02\/Screenshot-2024-02-03-at-1.39.31\u202fPM.png","datePublished":"2024-02-03T19:29:47+00:00","dateModified":"2025-04-24T17:03:21+00:00","description":"Conversational AI is more accessible than ever due to tools like LangChain + Comet that integrate seamlessly to streamline chatbot development","breadcrumb":{"@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/#primaryimage","url":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2024\/02\/Screenshot-2024-02-03-at-1.39.31\u202fPM.png","contentUrl":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2024\/02\/Screenshot-2024-02-03-at-1.39.31\u202fPM.png","width":1854,"height":1036,"caption":"CometLLM, Comet LLMOps, Prompt Engineering, LangChain, Conversational AI"},{"@type":"BreadcrumbList","@id":"https:\/\/www.comet.com\/site\/blog\/conversational-ai-with-langchain-and-comet\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.comet.com\/site\/"},{"@type":"ListItem","position":2,"name":"Conversational AI with LangChain and\u00a0Comet"}]},{"@type":"WebSite","@id":"https:\/\/www.comet.com\/site\/#website","url":"https:\/\/www.comet.com\/site\/","name":"Comet","description":"Build Better Models Faster","publisher":{"@id":"https:\/\/www.comet.com\/site\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.comet.com\/site\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.comet.com\/site\/#organization","name":"Comet ML, Inc.","alternateName":"Comet","url":"https:\/\/www.comet.com\/site\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.comet.com\/site\/#\/schema\/logo\/image\/","url":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2025\/01\/logo_comet_square.png","contentUrl":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2025\/01\/logo_comet_square.png","width":310,"height":310,"caption":"Comet ML, Inc."},"image":{"@id":"https:\/\/www.comet.com\/site\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/cometdotml","https:\/\/x.com\/Cometml","https:\/\/www.youtube.com\/channel\/UCmN63HKvfXSCS-UwVwmK8Hw"]},{"@type":"Person","@id":"https:\/\/www.comet.com\/site\/#\/schema\/person\/b8e568abee61cd8fd0c5d73b672779da","name":"Haziqa Sajid","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.comet.com\/site\/#\/schema\/person\/image\/817879efa0771c090195dd1888fca759","url":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2023\/07\/cropped-1585931859188-96x96.jpg","contentUrl":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2023\/07\/cropped-1585931859188-96x96.jpg","caption":"Haziqa Sajid"},"url":"https:\/\/www.comet.com\/site\/blog\/author\/haziqa5122gmail-com\/"}]}},"jetpack_featured_media_url":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2024\/02\/Screenshot-2024-02-03-at-1.39.31\u202fPM.png","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts\/9094","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/users\/54"}],"replies":[{"embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/comments?post=9094"}],"version-history":[{"count":1,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts\/9094\/revisions"}],"predecessor-version":[{"id":15394,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts\/9094\/revisions\/15394"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/media\/9097"}],"wp:attachment":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/media?parent=9094"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/categories?post=9094"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/tags?post=9094"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/coauthors?post=9094"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}