{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "John Leung",
  "title_listed": "Performing Customer Analytics with LangChain and LLMs",
  "keywords": "",
  "domain": "大模型算法",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/performing-customer-analytics-with-langchain-and-llms-0af4ea38f7b5/",
  "publish_date": "2024-02-14",
  "corpus_stage": "",
  "notes": "",
  "id": "4e8481b879e7",
  "collected_at": "2026-10-02T04:31:13",
  "title": "Performing Customer Analytics with LangChain and LLMs | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# Performing Customer Analytics with LangChain and LLMs\nDiscover the potentials and constraints of LangChain for customer analytics, accompanied by practical implementation codes\n[John Leung](https://towardsdatascience.com/author/johnleungtj/)\nFebruary 13, 202411 min read\n### Discover the potentials and constraints of LangChain in calculating statistics, insight generation, visualization, and making conversation for customer analytics - with implementation codes\nMany businesses possess a lot of proprietary data stored in their databases. However, the data is complex and unapproachable for users, so they often struggle to identify trends and extract actionable insights. That's where business intelligence (BI) dashboards play an essential role, which is the starting point for users to interact with the consolidated view of data at a glance.\n### The bottleneck of the BI dashboards\n[An effective BI dashboard](https://towardsdatascience.com/how-to-build-effective-and-useful-dashboards-711759534639) should be designed to contain only the relevant information for the target audience and avoid picking cluttered visual elements into one. But this does not well address a challenge. Sometimes users suddenly have additional inquiries or wish to explore new analytical perspectives beyond what is displayed in the dashboard. If they do not have any technical background to dynamically tailor the underlying logic of visualization, it may fail to meet their needs.\n![Photo by Emily Morter on Unsplash](../images/000.jpg)\nPhoto by [Emily Morter](https://unsplash.com/@emilymorter?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\nThe recent framework [LangChain](https://www.langchain.com/) reduces the technical barrier of interacting with data due to its advanced language processing capabilities, it thus potentially presents new opportunities for businesses. Let's explore the basics of how it works.\n### How LangChain works\nLarge-language models (LLMs), such as [ChatGPT](https://towardsdatascience.com/how-chatgpt-works-the-models-behind-the-bot-1ce5fca96286) and [Llama](https://towardsdatascience.com/mistral-ai-vs-meta-comparing-top-open-source-llms-565c1bc1516e), have high abilities in language comprehension and text generation. As an open-source library, LangChain integrates LLMs into the applications. It provides multiple modules for efficient interaction and streamlining the workflow, such as:\n  * [**Document loader:**](https://python.langchain.com/docs/modules/data_connection/document_loaders/) Facilitate the data loading from various sources, including CSV files, SQL databases, and public datasets like Wikipedia.\n  * [**Agent:**](https://python.langchain.com/docs/modules/agents/) Use the language model as a reasoning engine to determine which actions to take and in which order. It repeats through a continuous cycle of thought-action-observation until the task is completed.\n  * [**Chain:**](https://python.langchain.com/docs/modules/chains) Different from agents, they consist of predetermined sequences of actions, which are hard coded. It addresses complex and well-defined tasks by guiding multiple tools with high-level directions.\n  * **Memory** : Currently the beta version supports accessing windows of past messages, this provides the application with a conversational interface\n\n\n* * *\nUsing these modules as the foundation, we will start coding a simple application that utilizes the LLM. In this hands-on journey, we will assume the roles of business users and experiment to see if we can conduct exploratory data analysis simply by inputting natural language inquiries.\n![The flows that LLM-based application works \\(Image by author\\)](../images/001.png)\nThe flows that LLM-based application works (Image by author)\nConsider a scenario where you plan to conduct customer analytics for a retail shop, so you have collected sales data over the past 12 months. Your goal is to understand better diverse aspects such as customer demographics, spending behaviors, and product categories.\nThe [dataset](https://www.kaggle.com/datasets/mohammadtalib786/retail-sales-dataset/data) [with license as [CC0: Public domain](https://creativecommons.org/publicdomain/zero/1.0/)] obtained from Kaggle contains several fields, including transaction ID, transaction date, customer ID, gender, age, product category, the number of units of the products purchased, the price per unit, and the total amount of transactions. We can begin our analysis now.\n### The initial setup\nWe need to set up the environment and configurations properly to use LangChain in Python.\n  1. Prepare the Python environment with LangChain library alongside other necessary dependencies like [SQLite](https://docs.python.org/3/library/sqlite3.html) and Pandas\n  2. [Configure an OpenAI Key](https://platform.openai.com/docs/quickstart?context=python) to query GPT models\n  3. Import a CSV file 'retail_sales_dataset.csv' into a table within the SQLite database\n\n\npython\n\n```\n# Import necessary libraries and modules\nfrom langchain.chat_models import ChatOpenAI\nimport sqlite3\nimport pandas as pd\n\n# Set the OpenAI API key\nOPENAI_API_KEY = \"<OpenAI API key>\"\n\n# Initialize the Langchain ChatOpenAI model\nllm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, model_name=\"gpt-3.5-turbo-1106\")\n\n# Connect to the SQLite database\nconnection = sqlite3.connect(\"customer.db\")\n\n# Convert DataFrame to a SQLite table named \"RetailSalesTable\"\ndf.to_sql(\"RetailSalesTable\", connection, if_exists='replace')\n```\n\n### Create a LangChain Application\n### 1 Generate basic statistics\n> What is the number of transactions **per year and month**?\nTo inquire about basic statistics related to the sales SQL table, we use the `create_sql_agent` agent helper. Both parameters `verbose` and `return_intermediate_steps` are set as True so that the internal states and steps during the execution process can be shown. This will be effective for us to iteratively evaluate and refine the approach to communicating with the agent.\npython\n\n```\n# Import necessary libraries and modules\nfrom langchain.agents import create_sql_agent\nfrom langchain.agents.agent_toolkits import SQLDatabaseToolkit\nfrom langchain.agents.agent_types import AgentType\nfrom langchain.sql_database import SQLDatabase\n\n# Create an instance of SQLDatabase using the 'customer.db' SQLite database\ndb = SQLDatabase.from_uri('sqlite:///customer.db')\n\n# Create an SQL agent executor with specified parameters\nagent_executor = create_sql_agent(\n    llm=llm,\n    toolkit=SQLDatabaseToolkit(db=db, llm=llm),\n    agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n    handle_parsing_errors=True,\n    verbose=True,\n    return_intermediate_steps=True\n)\n\n# Define user input\nuser_inquiry = \"What is the number of transactions per year and month?\"\n\n# Run the agent to generate a response\nagent_executor.run(user_inquiry)\n```\n\nThe complete content of the outputs is provided below.\n![Agent&#039;s output steps - basic statistics \\(1/2\\) \\(Image by author\\)](../images/002.png)\nAgent's output steps - basic statistics (1/2) (Image by author)\n![Agent&#039;s output steps - basic statistics \\(2/2\\) \\(Image by author\\)](../images/003.png)\nAgent's output steps - basic statistics (2/2) (Image by author)\nThe agent writes the query which includes rectifying the formatting of the 'Date' column and producing the correct results. It successfully presents the breakdown of transaction counts from Jan 2023 to Jan 2024.\n### 2 Perform feature engineering\n> What is the number of transactions across different **age groups** of customers?\nThis time, we slightly modified the inquiries to focus on the dimension 'age groups'. This aims to evaluate the agent's ability to generate new features that do not directly originate from the dataset. Applied with a similar concept, you can additionally explore statistics across dimensions like transaction dates categorized by weekdays/ weekends, purchasing frequency, etc.\n![A portion of agent&#039;s output steps -feature engineering \\(Image by author\\)](../images/004.png)\nA portion of agent's output steps -feature engineering (Image by author)\nThe agent attempts to write the query but unfortunately gives the wrong answer. It seems that the agent oversimplifies the concept of 'age group', so it is not classified as a distinct dimension, and considers it as just 'age'.\n**Improvement: Use a prompt template with background context**\nWhen we find that the model misunderstood our intended meaning, or lacks certain knowledge, we can use class `PromptTemplate` to create parametrized [prompts](https://python.langchain.com/docs/modules/model_io/prompts/) for language models. In this case, I have supplemented additional context about examples of extra features in customer analytics as background information, right before showing the user inquiry. This aims to provide the model with clearer guidelines and deliver our human intent for generating appropriate machine-generated responses.\npython\n\n```\nfrom langchain_core.prompts import PromptTemplate\n\n# Create the prompt template\ntemplate = PromptTemplate(\n    input_variables=[\"user_inquiry\", \"background_info\"],\n    template=\"\"\"{background_info}\n    Question: {user_inquiry}\n    \"\"\"\n)\n\n# Define the background information\nbackground_info = \"\"\"\nAs the customer analyst, my role is to analyze the transaction patterns of customers. The feature engineering in table 'RetailSalesTable' is crucial for statistical exploration. For example:\n- column 'Age' can be grouped into bins of age ranges, such as 21-25, 26-30, and so on.\nUnderstanding the data in these columns helps us gain insights about our customers, enabling us to offer personalized services and develop effective marketing strategies.\n\"\"\"\n\n# Define user input\nuser_inquiry = \"What is the number of transactions across different age ranges of customers?\"\n\n# Run the agent with the formatted template\nagent_executor.run(template.format(background_info=background_info, user_inquiry=user_inquiry))\n```\n\nHere are the key highlights from the corresponding outputs.\n![Agent&#039;s improved output - feature engineering \\(Image by author\\)](../images/005.png)\nAgent's improved output - feature engineering (Image by author)\nWith the aid of the prompt, the agent now successfully categorizes the transactions into multiple age groups. It is worth mentioning that there are potentially other ways to achieve the same goal, such as using few-shot examples to demonstrate the question-answer pairs.\n### 3 Plot chart for multi-dimensional features\nWe used the `create_sql_agent` agent to calculate basic statistics and generate insights. With the art of prompt design, the agent is consequently fit to perform the tasks. To support asking new inquiries that cannot be achieved solely by SQL query, we need to develop our [custom tool](https://python.langchain.com/docs/modules/agents/tools/custom_tools).\n> Show a **grouped bar graph** visualizing the answer to the following question: What are the relationships between product category, average total amount, and gender?\nIn this example, the inquiry involves data exploration and visualization. We will create our agent based on `create_sql_agent`, and will add the tool `PythonREPLTool` for executing Python commands, such as using `Matplotlib` for visualization.\nLet's see how the tools are implemented in practice.\npython\n\n```\nfrom langchain import LLMChain\nfrom langchain.agents import (AgentExecutor, Tool, ZeroShotAgent)\nfrom langchain_experimental.tools import PythonREPLTool\n\n# Define a description to suggest how to determine the choice of tool\ndescription = (\n    \"Useful when you require to answer analytical questions about customers. \"\n    \"Use this more than the Python REPL tool if the question is about customer analytics,\"\n    \"like 'How many customers are there?' or 'count the number of transactions by age group'. \"\n    \"Try not to use clause in the SQL.\"\n)\n\n# Create a Tool object for customer data with the previously defined agent executor 'create_sql_agent' and description\ncustomer_data_tool = Tool(\n    name=\"Customer\",\n    func=agent_executor.run,\n    description=description,\n)\n\n# Create the whole list of tools\ntools = [PythonREPLTool()]\ntools.append(customer_data_tool)\n\n# Define the prefix and suffix for the prompt\nprefix = \"Below are tools that you can access:\"\nsuffix = (\n    \"Pass the relevant part of the request directly to the Customer tool.nn\"\n    \"Request: {input}n\"\n    \"{agent_scratchpad}\"\n)\n\n# Create the prompt using ZeroShotAgent\n# Use agent_scratchpad to store the actions previously used, guiding the subsequent responses.\nagent_prompt = ZeroShotAgent.create_prompt(\n    tools, prefix=prefix, suffix=suffix, input_variables=[\"input\", \"agent_scratchpad\"]\n)\n\n# Create an instance of ZeroShotAgent with the LLMChain and the allowed tool names\nzero_shot_agent = ZeroShotAgent(\n    llm_chain=LLMChain(llm=llm, prompt=agent_prompt),\n    allowed_tools=[tool.name for tool in tools]\n)\n\n# Create an AgentExecutor which enables verbose mode and handling parsing errors\nagent_executor = AgentExecutor.from_agent_and_tools(\n    agent=zero_shot_agent, tools=tools, verbose=True, handle_parsing_errors=True\n)\n\n# Define user input\nuser_inquiry = \"Use a grouped bar graph to visualize the result of the following inquiry: \" \n          \"What are the relationships between product category, average total amount, and gender?\"\n\n# Run the agent to generate a response\nagent_executor.run(user_inquiry)\n```\n\nThe flow of SQL agent output is similar to the previous examples we went through above, so it is omitted here. The subsequent output from the Python REPL tool is presented below.\n![Agent&#039;s output - plot chart \\(1/2\\) \\(Image by author\\)](../images/006.png)\nAgent's output - plot chart (1/2) (Image by author)\n![Agent&#039;s output - plot chart \\(2/2\\) \\(Image by author\\)](../images/007.png)\nAgent's output - plot chart (2/2) (Image by author)\nThe customized tool combination successfully translates the natural language inquiry into an SQL query. The summarized query results are then used to generate a grouped bar chart, which clearly and effectively illustrates the relationships through the x-axis, y-axis, and legend.\nWhile the overall design and execution process look smooth, there are indeed some limitations in the current design. For example, suppose we want to generate a scatter plot with most of the transaction data points. In that case, the execution process should generate a long query output that covers all the respective information. However, the agent's output may not be ideal, due to the occasional use of the `LIMIT` clause by the agent (that sets an upper limit on the number of tuples), or query result larger than the maximum token limit (in our case, 4096 tokens). The variety of visualizations that can be generated may thus be limited.\n### 4 Make coherent conversation\nIn reality, business users often have follow-up questions once they receive the results of a customer analysis. To address these situations, we need to enhance the existing basic LLM application to become more chat-like. We add memory buffers to retain past interactions, allowing the LLM to generate responses for the ongoing conversation's context. This works by constantly storing LLM outputs and referencing the memory storage before generating a response.\n> Initial question: How do customers adapt their shopping habits during different seasons?\n> Follow-up question: Can you elaborate more?\nWe supplement and rectify the customized tools combination below:\npython\n\n```\nfrom langchain.memory import ConversationBufferMemory\n\n# Skipped here - Define your own prefix, suffix, and description with \"chat_history\" for the prompt\n# Keep the original list of tools\n\n# Create the prompt using ZeroShotAgent with additonal \"chat_history\" as input variables\nagent_prompt = ZeroShotAgent.create_prompt(\n    tools, prefix=prefix, suffix=suffix, input_variables=[\"input\", \"chat_history\", \"agent_scratchpad\"],\n)\n\n# Create an instance of ZeroShotAgent with the LLMChain and the allowed tool names\nzero_shot_agent = ZeroShotAgent(\n    llm_chain=LLMChain(llm=llm, prompt=agent_prompt),\n    allowed_tools=[tool.name for tool in tools]\n)\n\n# Initiate memory which allows for storing and extracting messages\nmemory = ConversationBufferMemory(memory_key=\"chat_history\")\n\n# Create an AgentExecutor with memory parameter\nagent_chain = AgentExecutor.from_agent_and_tools(\n    agent=zero_shot_agent, tools=tools, verbose=True, handle_parsing_errors=True, memory=memory\n)\n\n# Define initial question as user input\nuser_inquiry = \"How do customers adapt their shopping habits during different seasons?\"\n\n# Run the agent to generate a response\nagent_executor.run(user_inquiry)\n\n# Define follow-up question as user input\nuser_inquiry = \"Can you elaborate more?\"\n\n# Run the agent to generate another response\nagent_executor.run(user_inquiry)\n```\n\nAgent's responses:\n![Agent&#039;s output - initial question \\(1/2\\) \\(Image by author\\)](../images/008.png)\nAgent's output - initial question (1/2) (Image by author)\n![Agent&#039;s output - follow-up question \\(2/2\\) \\(Image by author\\)](../images/009.png)\nAgent's output - follow-up question (2/2) (Image by author)\nIn the follow-up question \"Can you elaborate more?\", we intentionally did not provide any hints/ keywords about what we were asking, but the agent demonstrated its ability to continue the analysis of shopping habits in various seasons. This indicates the effectiveness of using memory and shows its advantage by providing a more in-depth description across product categories and seasons.\n### Wrapping it up\nWe conducted experiments to explore the key functionalities and potential approaches of LangChain in developing a customer analytics application based on LLM:\n  * Calculating statistics, by using an `create_sql_agent` agent to query the database and retrieve relevant statistical information.\n  * Insight generation, by applying the prompt template to define the key data features.\n  * Visualization, by using the combination of a custom agent and tool `PythonREPLTool`.\n  * Conversation capabilities, by adding the memory buffer to store and retrieve the chat history.\n\n\nThe choices of wordings in natural language inquiry often do not align precisely with those in the database schema. It was observed that the LangChain executor sometimes does not work as expected, and may even [hallucinate](https://www.pinecone.io/learn/series/langchain/langchain-retrieval-augmentation/), particularly when identifying the data relationships to generate a graph. Therefore, the development of codes requires iterative troubleshooting. While the LangChain framework may only be somewhat reliable and effective in handling diverse customer analytics tasks, it can still offer users with marginal advantage when they have a compelling need to discover insights beyond the traditional analysis dashboards.\nThe design of this application is only the initial stage, and there are further possibilities to discover. For example, customer data is sometimes available in text format, such as customer reviews or product descriptions. LangChain provides the [tagging function](https://python.langchain.com/docs/use_cases/tagging) so that we can conduct a comprehensive analysis by labeling the sentiments, language, style, and more.\n* * *\n### Before you go\nIf you enjoy this reading, I invite you to **** follow my [Medium page](https://medium.com/@johnleungTJ) and [LinkedIn page](https://www.linkedin.com/in/john-leung-639800115/). By doing so, you can stay updated with exciting content related to data science side projects, Machine Learning Operations (MLOps) demonstrations, and project management methodologies.\n> [**Managing the Technical Debts of Machine Learning Systems**](https://towardsdatascience.com/managing-the-technical-debts-of-machine-learning-systems-5b85d420ab9d)\n> [**Monitoring Machine Learning Models in Production: Why and How?**](https://towardsdatascience.com/monitoring-machine-learning-models-in-production-why-and-how-13d07a5ff0c6)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-4766f66da8cde6940868.jpeg)\nWritten By\n## [John Leung](https://towardsdatascience.com/author/johnleungtj/)\n[See all from John Leung](https://towardsdatascience.com/author/johnleungtj/)\n[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Business Intelligence](https://towardsdatascience.com/tag/business-intelligence/)[Langchain](https://towardsdatascience.com/tag/langchain/)[Llm](https://towardsdatascience.com/tag/llm/)[Python](https://towardsdatascience.com/tag/python/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fperforming-customer-analytics-with-langchain-and-llms-0af4ea38f7b5%2F&title=Performing%20Customer%20Analytics%20with%20LangChain%20and%20LLMs)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fperforming-customer-analytics-with-langchain-and-llms-0af4ea38f7b5%2F&title=Performing%20Customer%20Analytics%20with%20LangChain%20and%20LLMs)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fperforming-customer-analytics-with-langchain-and-llms-0af4ea38f7b5%2F&text=Performing%20Customer%20Analytics%20with%20LangChain%20and%20LLMs)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/010.jpg)](https://towardsdatascience.com/eda-in-public-part-3-rfm-analysis-for-customer-segmentation-in-pandas/)\n## [EDA in Public (Part 3): RFM Analysis for Customer Segmentation in Pandas](https://towardsdatascience.com/eda-in-public-part-3-rfm-analysis-for-customer-segmentation-in-pandas/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHow to build, score, and interpret RFM segments step by step\n[Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\nJanuary 1, 202612 min read\n  * [![](../images/011.jpg)](https://towardsdatascience.com/expected-value-analysis-in-ai-product-management/)\n## [Expected Value Analysis in AI Product Management](https://towardsdatascience.com/expected-value-analysis-in-ai-product-management/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAn introduction to key concepts and practical applications\n[Chinmay Kakatkar](https://towardsdatascience.com/author/kcpub21/)\nNovember 6, 202515 min read\n  * [![](../images/012.png)](https://towardsdatascience.com/extending-context-length-in-large-language-models-74e59201b51f/)\n## [Extending Context Length in Large Language Models](https://towardsdatascience.com/extending-context-length-in-large-language-models-74e59201b51f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHow to turn your Llama into a Giraffe\n[Donato Riccio](https://towardsdatascience.com/author/donatoriccio/)\nOctober 15, 20239 min read\n  * [![](../images/013.jpg)](https://towardsdatascience.com/custom-named-entity-recognition-with-bert-cf1fd4510804/)\n## [Custom Named Entity Recognition with BERT](https://towardsdatascience.com/custom-named-entity-recognition-with-bert-cf1fd4510804/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHow to use PyTorch and Hugging Face to classify named entities in a text\n[Marcello Politi](https://towardsdatascience.com/author/marcellopoliti/)\nJuly 7, 20222 min read\n  * [![](../images/014.jpg)](https://towardsdatascience.com/ai-in-practice-how-to-choose-and-deploy-the-right-strategy-bcda1ed5c1c3/)\n## [AI in Practice: How to Choose and Deploy the Right Strategy](https://towardsdatascience.com/ai-in-practice-how-to-choose-and-deploy-the-right-strategy-bcda1ed5c1c3/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nOur weekly selection of must-read Editors' Picks and original features\n[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)\nOctober 24, 20244 min read\n  * [![](../images/015.jpeg)](https://towardsdatascience.com/plotly-front-to-back-bar-charts-line-charts-2b591d29c6ba/)\n## [Plotly Front to Back: Bar Charts & Line Charts](https://towardsdatascience.com/plotly-front-to-back-bar-charts-line-charts-2b591d29c6ba/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLet's get the basics covered. Source code included.\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nMarch 26, 20206 min read\n  * [![](../images/016.png)](https://towardsdatascience.com/15-things-you-should-know-about-lists-in-python-c566792eca98/)\n## [15 things you should know about Lists in Python](https://towardsdatascience.com/15-things-you-should-know-about-lists-in-python-c566792eca98/)\n[Programming](https://towardsdatascience.com/category/programming/)\nGuidelines to use lists in Python\n[Amanda Iglesias Moreno](https://towardsdatascience.com/author/amandaiglesiasmoreno/)\nApril 20, 20205 min read\n  * [![](../images/017.jpeg)](https://towardsdatascience.com/predicting-imdb-movie-ratings-using-supervised-machine-learning-f3b126ab2ddb/)\n## [Predicting IMDb Movie Ratings using Supervised Machine Learning](https://towardsdatascience.com/predicting-imdb-movie-ratings-using-supervised-machine-learning-f3b126ab2ddb/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe process behind my first individual project at Metis\n[Joe Cowell](https://towardsdatascience.com/author/josephpcowell/)\nOctober 14, 20207 min read\n  * [![](../images/018.jpg)](https://towardsdatascience.com/quick-start-from-mongodb-to-pandas-3f777dcbfb6e/)\n## [A Quick Start for Taking MongoDB Collections into Pandas DataFrames](https://towardsdatascience.com/quick-start-from-mongodb-to-pandas-3f777dcbfb6e/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nGet you on your way to data analysis and model building quickly by pulling MongoDB data into Pandas\n[Brian Roepke](https://towardsdatascience.com/author/broepke/)\nSeptember 17, 20227 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "Performing Customer Analytics with LangChain and LLMs | Towards Data Science",
    "description": "Discover the potentials and constraints of LangChain for customer analytics, accompanied by practical implementation codes",
    "keywords": null,
    "author": "John Leung",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Performing Customer Analytics with LangChain and LLMs",
    "og:description": "Discover the potentials and constraints of LangChain for customer analytics, accompanied by practical implementation codes",
    "og:url": "https://towardsdatascience.com/performing-customer-analytics-with-langchain-and-llms-0af4ea38f7b5/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/03AaYkJoAe7U6FAkW-scaled.jpg",
    "og:image:width": "2560",
    "og:image:height": "1707",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "John Leung",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "11 min read",
    "article:published_time": "2024-02-13T19:34:16.000Z",
    "article:modified_time": "2024-02-13T19:34:16.000Z",
    "article:author": "https://towardsdatascience.com/author/johnleungtj/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/4e8481b879e7/code/block_000.txt",
      "chars": 514
    },
    {
      "language": "txt",
      "file": "attachments/4e8481b879e7/code/block_001.txt",
      "chars": 837
    },
    {
      "language": "txt",
      "file": "attachments/4e8481b879e7/code/block_002.txt",
      "chars": 1006
    },
    {
      "language": "txt",
      "file": "attachments/4e8481b879e7/code/block_003.txt",
      "chars": 2098
    },
    {
      "language": "txt",
      "file": "attachments/4e8481b879e7/code/block_004.txt",
      "chars": 1341
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:50:42Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:50:43Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:50:43Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:50:43Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/johnleungtj/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-to-build-effective-and-useful-dashboards-711759534639"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-chatgpt-works-the-models-behind-the-bot-1ce5fca96286"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/mistral-ai-vs-meta-comparing-top-open-source-llms-565c1bc1516e"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/managing-the-technical-debts-of-machine-learning-systems-5b85d420ab9d"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/monitoring-machine-learning-models-in-production-why-and-how-13d07a5ff0c6"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/business-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/langchain/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/llm/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/python/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/eda-in-public-part-3-rfm-analysis-for-customer-segmentation-in-pandas/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@emilymorter"
    },
    {
      "type": "external",
      "href": "https://unsplash.com"
    },
    {
      "type": "external",
      "href": "https://www.langchain.com/"
    },
    {
      "type": "external",
      "href": "https://python.langchain.com/docs/modules/data_connection/document_loaders/"
    },
    {
      "type": "external",
      "href": "https://python.langchain.com/docs/modules/agents/"
    },
    {
      "type": "external",
      "href": "https://python.langchain.com/docs/modules/chains"
    },
    {
      "type": "external",
      "href": "https://www.kaggle.com/datasets/mohammadtalib786/retail-sales-dataset/data"
    },
    {
      "type": "external",
      "href": "https://creativecommons.org/publicdomain/zero/1.0/"
    },
    {
      "type": "external",
      "href": "https://docs.python.org/3/library/sqlite3.html"
    },
    {
      "type": "external",
      "href": "https://platform.openai.com/docs/quickstart?context=python"
    },
    {
      "type": "external",
      "href": "https://python.langchain.com/docs/modules/model_io/prompts/"
    },
    {
      "type": "external",
      "href": "https://python.langchain.com/docs/modules/agents/tools/custom_tools"
    },
    {
      "type": "external",
      "href": "https://www.pinecone.io/learn/series/langchain/langchain-retrieval-augmentation/"
    },
    {
      "type": "external",
      "href": "https://python.langchain.com/docs/use_cases/tagging"
    },
    {
      "type": "external",
      "href": "https://medium.com/@johnleungTJ"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/john-leung-639800115/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Performing+Customer+Analytics+with+LangChain+and+LLMs&u=https%3A%2F%2Ftowardsdatascience.com%2Fperforming-customer-analytics-with-langchain-and-llms-0af4ea38f7b5%2F"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:27:06Z",
  "source_url": "https://towardsdatascience.com/performing-customer-analytics-with-langchain-and-llms-0af4ea38f7b5/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# Performing Customer Analytics with LangChain and LLMs\nDiscover the potentials and constraints of LangChain for customer analytics, accompanied by practical implementation codes\n[John Leung](https://towardsdatascience.com/author/johnleungtj/)\nFebruary 13, 202411 min read\n### Discover the potentials and constraints of LangChain in calculating statistics, insight generation, visualization, and making conversation for customer analytics - with implementation codes\nMany businesses possess a lot of proprietary data stored in their databases. However, the data is complex and unapproachable for users, so they often struggle to identify trends and extract actionable insights. That's where business intelligence (BI) dashboards play an essential role, which is the starting point for users to interact with the consolidated view of data at a glance.\n### The bottleneck of the BI dashboards\n[An effective BI dashboard](https://towardsdatascience.com/how-to-build-effective-and-useful-dashboards-711759534639) should be designed to contain only the relevant information for the target audience and avoid picking cluttered visual elements into one. But this does not well address a challenge. Sometimes users suddenly have additional inquiries or wish to explore new analytical perspectives beyond what is displayed in the dashboard. If they do not have any technical background to dynamically tailor the underlying logic of visualization, it may fail to meet their needs.\n![Photo by Emily Morter on Unsplash](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/03AaYkJoAe7U6FAkW-scaled.jpg)\nPhoto by [Emily Morter](https://unsplash.com/@emilymorter?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\nThe recent framework [LangChain](https://www.langchain.com/) reduces the technical barrier of interacting with data due to its advanced language processing capabilities, it thus potentially presents new opportunities for businesses. Let's explore the basics of how it works.\n### How LangChain works\nLarge-language models (LLMs), such as [ChatGPT](https://towardsdatascience.com/how-chatgpt-works-the-models-behind-the-bot-1ce5fca96286) and [Llama](https://towardsdatascience.com/mistral-ai-vs-meta-comparing-top-open-source-llms-565c1bc1516e), have high abilities in language comprehension and text generation. As an open-source library, LangChain integrates LLMs into the applications. It provides multiple modules for efficient interaction and streamlining the workflow, such as:\n  * [**Document loader:**](https://python.langchain.com/docs/modules/data_connection/document_loaders/) Facilitate the data loading from various sources, including CSV files, SQL databases, and public datasets like Wikipedia.\n  * [**Agent:**](https://python.langchain.com/docs/modules/agents/) Use the language model as a reasoning engine to determine which actions to take and in which order. It repeats through a continuous cycle of thought-action-observation until the task is completed.\n  * [**Chain:**](https://python.langchain.com/docs/modules/chains) Different from agents, they consist of predetermined sequences of actions, which are hard coded. It addresses complex and well-defined tasks by guiding multiple tools with high-level directions.\n  * **Memory** : Currently the beta version supports accessing windows of past messages, this provides the application with a conversational interface\n\n\n* * *\nUsing these modules as the foundation, we will start coding a simple application that utilizes the LLM. In this hands-on journey, we will assume the roles of business users and experiment to see if we can conduct exploratory data analysis simply by inputting natural language inquiries.\n![The flows that LLM-based application works \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1axYsoEghgkK-8PaKtmXYsA.png)\nThe flows that LLM-based application works (Image by author)\nConsider a scenario where you plan to conduct customer analytics for a retail shop, so you have collected sales data over the past 12 months. Your goal is to understand better diverse aspects such as customer demographics, spending behaviors, and product categories.\nThe [dataset](https://www.kaggle.com/datasets/mohammadtalib786/retail-sales-dataset/data) [with license as [CC0: Public domain](https://creativecommons.org/publicdomain/zero/1.0/)] obtained from Kaggle contains several fields, including transaction ID, transaction date, customer ID, gender, age, product category, the number of units of the products purchased, the price per unit, and the total amount of transactions. We can begin our analysis now.\n### The initial setup\nWe need to set up the environment and configurations properly to use LangChain in Python.\n  1. Prepare the Python environment with LangChain library alongside other necessary dependencies like [SQLite](https://docs.python.org/3/library/sqlite3.html) and Pandas\n  2. [Configure an OpenAI Key](https://platform.openai.com/docs/quickstart?context=python) to query GPT models\n  3. Import a CSV file 'retail_sales_dataset.csv' into a table within the SQLite database\n\n\npython\n\n```\n# Import necessary libraries and modules\nfrom langchain.chat_models import ChatOpenAI\nimport sqlite3\nimport pandas as pd\n\n# Set the OpenAI API key\nOPENAI_API_KEY = \"<OpenAI API key>\"\n\n# Initialize the Langchain ChatOpenAI model\nllm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, model_name=\"gpt-3.5-turbo-1106\")\n\n# Connect to the SQLite database\nconnection = sqlite3.connect(\"customer.db\")\n\n# Convert DataFrame to a SQLite table named \"RetailSalesTable\"\ndf.to_sql(\"RetailSalesTable\", connection, if_exists='replace')\n```\n\n### Create a LangChain Application\n### 1 Generate basic statistics\n> What is the number of transactions **per year and month**?\nTo inquire about basic statistics related to the sales SQL table, we use the `create_sql_agent` agent helper. Both parameters `verbose` and `return_intermediate_steps` are set as True so that the internal states and steps during the execution process can be shown. This will be effective for us to iteratively evaluate and refine the approach to communicating with the agent.\npython\n\n```\n# Import necessary libraries and modules\nfrom langchain.agents import create_sql_agent\nfrom langchain.agents.agent_toolkits import SQLDatabaseToolkit\nfrom langchain.agents.agent_types import AgentType\nfrom langchain.sql_database import SQLDatabase\n\n# Create an instance of SQLDatabase using the 'customer.db' SQLite database\ndb = SQLDatabase.from_uri('sqlite:///customer.db')\n\n# Create an SQL agent executor with specified parameters\nagent_executor = create_sql_agent(\n    llm=llm,\n    toolkit=SQLDatabaseToolkit(db=db, llm=llm),\n    agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n    handle_parsing_errors=True,\n    verbose=True,\n    return_intermediate_steps=True\n)\n\n# Define user input\nuser_inquiry = \"What is the number of transactions per year and month?\"\n\n# Run the agent to generate a response\nagent_executor.run(user_inquiry)\n```\n\nThe complete content of the outputs is provided below.\n![Agent&#039;s output steps - basic statistics \\(1/2\\) \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1ACL_4GEvuggpR6AXwH9HtQ.png)\nAgent's output steps - basic statistics (1/2) (Image by author)\n![Agent&#039;s output steps - basic statistics \\(2/2\\) \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1s51LKfOEcJmmIg-OuQ3wXQ.png)\nAgent's output steps - basic statistics (2/2) (Image by author)\nThe agent writes the query which includes rectifying the formatting of the 'Date' column and producing the correct results. It successfully presents the breakdown of transaction counts from Jan 2023 to Jan 2024.\n### 2 Perform feature engineering\n> What is the number of transactions across different **age groups** of customers?\nThis time, we slightly modified the inquiries to focus on the dimension 'age groups'. This aims to evaluate the agent's ability to generate new features that do not directly originate from the dataset. Applied with a similar concept, you can additionally explore statistics across dimensions like transaction dates categorized by weekdays/ weekends, purchasing frequency, etc.\n![A portion of agent&#039;s output steps -feature engineering \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1Ggme5Bc4HNAREaeYbimchg.png)\nA portion of agent's output steps -feature engineering (Image by author)\nThe agent attempts to write the query but unfortunately gives the wrong answer. It seems that the agent oversimplifies the concept of 'age group', so it is not classified as a distinct dimension, and considers it as just 'age'.\n**Improvement: Use a prompt template with background context**\nWhen we find that the model misunderstood our intended meaning, or lacks certain knowledge, we can use class `PromptTemplate` to create parametrized [prompts](https://python.langchain.com/docs/modules/model_io/prompts/) for language models. In this case, I have supplemented additional context about examples of extra features in customer analytics as background information, right before showing the user inquiry. This aims to provide the model with clearer guidelines and deliver our human intent for generating appropriate machine-generated responses.\npython\n\n```\nfrom langchain_core.prompts import PromptTemplate\n\n# Create the prompt template\ntemplate = PromptTemplate(\n    input_variables=[\"user_inquiry\", \"background_info\"],\n    template=\"\"\"{background_info}\n    Question: {user_inquiry}\n    \"\"\"\n)\n\n# Define the background information\nbackground_info = \"\"\"\nAs the customer analyst, my role is to analyze the transaction patterns of customers. The feature engineering in table 'RetailSalesTable' is crucial for statistical exploration. For example:\n- column 'Age' can be grouped into bins of age ranges, such as 21-25, 26-30, and so on.\nUnderstanding the data in these columns helps us gain insights about our customers, enabling us to offer personalized services and develop effective marketing strategies.\n\"\"\"\n\n# Define user input\nuser_inquiry = \"What is the number of transactions across different age ranges of customers?\"\n\n# Run the agent with the formatted template\nagent_executor.run(template.format(background_info=background_info, user_inquiry=user_inquiry))\n```\n\nHere are the key highlights from the corresponding outputs.\n![Agent&#039;s improved output - feature engineering \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/17OTlYjaklSJYprhTX_Plbg.png)\nAgent's improved output - feature engineering (Image by author)\nWith the aid of the prompt, the agent now successfully categorizes the transactions into multiple age groups. It is worth mentioning that there are potentially other ways to achieve the same goal, such as using few-shot examples to demonstrate the question-answer pairs.\n### 3 Plot chart for multi-dimensional features\nWe used the `create_sql_agent` agent to calculate basic statistics and generate insights. With the art of prompt design, the agent is consequently fit to perform the tasks. To support asking new inquiries that cannot be achieved solely by SQL query, we need to develop our [custom tool](https://python.langchain.com/docs/modules/agents/tools/custom_tools).\n> Show a **grouped bar graph** visualizing the answer to the following question: What are the relationships between product category, average total amount, and gender?\nIn this example, the inquiry involves data exploration and visualization. We will create our agent based on `create_sql_agent`, and will add the tool `PythonREPLTool` for executing Python commands, such as using `Matplotlib` for visualization.\nLet's see how the tools are implemented in practice.\npython\n\n```\nfrom langchain import LLMChain\nfrom langchain.agents import (AgentExecutor, Tool, ZeroShotAgent)\nfrom langchain_experimental.tools import PythonREPLTool\n\n# Define a description to suggest how to determine the choice of tool\ndescription = (\n    \"Useful when you require to answer analytical questions about customers. \"\n    \"Use this more than the Python REPL tool if the question is about customer analytics,\"\n    \"like 'How many customers are there?' or 'count the number of transactions by age group'. \"\n    \"Try not to use clause in the SQL.\"\n)\n\n# Create a Tool object for customer data with the previously defined agent executor 'create_sql_agent' and description\ncustomer_data_tool = Tool(\n    name=\"Customer\",\n    func=agent_executor.run,\n    description=description,\n)\n\n# Create the whole list of tools\ntools = [PythonREPLTool()]\ntools.append(customer_data_tool)\n\n# Define the prefix and suffix for the prompt\nprefix = \"Below are tools that you can access:\"\nsuffix = (\n    \"Pass the relevant part of the request directly to the Customer tool.nn\"\n    \"Request: {input}n\"\n    \"{agent_scratchpad}\"\n)\n\n# Create the prompt using ZeroShotAgent\n# Use agent_scratchpad to store the actions previously used, guiding the subsequent responses.\nagent_prompt = ZeroShotAgent.create_prompt(\n    tools, prefix=prefix, suffix=suffix, input_variables=[\"input\", \"agent_scratchpad\"]\n)\n\n# Create an instance of ZeroShotAgent with the LLMChain and the allowed tool names\nzero_shot_agent = ZeroShotAgent(\n    llm_chain=LLMChain(llm=llm, prompt=agent_prompt),\n    allowed_tools=[tool.name for tool in tools]\n)\n\n# Create an AgentExecutor which enables verbose mode and handling parsing errors\nagent_executor = AgentExecutor.from_agent_and_tools(\n    agent=zero_shot_agent, tools=tools, verbose=True, handle_parsing_errors=True\n)\n\n# Define user input\nuser_inquiry = \"Use a grouped bar graph to visualize the result of the following inquiry: \" \n          \"What are the relationships between product category, average total amount, and gender?\"\n\n# Run the agent to generate a response\nagent_executor.run(user_inquiry)\n```\n\nThe flow of SQL agent output is similar to the previous examples we went through above, so it is omitted here. The subsequent output from the Python REPL tool is presented below.\n![Agent&#039;s output - plot chart \\(1/2\\) \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1KQS11F8sgkwX3-DcKWeS2A.png)\nAgent's output - plot chart (1/2) (Image by author)\n![Agent&#039;s output - plot chart \\(2/2\\) \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1k-HlUbWHtm71QMVuueyUBQ.png)\nAgent's output - plot chart (2/2) (Image by author)\nThe customized tool combination successfully translates the natural language inquiry into an SQL query. The summarized query results are then used to generate a grouped bar chart, which clearly and effectively illustrates the relationships through the x-axis, y-axis, and legend.\nWhile the overall design and execution process look smooth, there are indeed some limitations in the current design. For example, suppose we want to generate a scatter plot with most of the transaction data points. In that case, the execution process should generate a long query output that covers all the respective information. However, the agent's output may not be ideal, due to the occasional use of the `LIMIT` clause by the agent (that sets an upper limit on the number of tuples), or query result larger than the maximum token limit (in our case, 4096 tokens). The variety of visualizations that can be generated may thus be limited.\n### 4 Make coherent conversation\nIn reality, business users often have follow-up questions once they receive the results of a customer analysis. To address these situations, we need to enhance the existing basic LLM application to become more chat-like. We add memory buffers to retain past interactions, allowing the LLM to generate responses for the ongoing conversation's context. This works by constantly storing LLM outputs and referencing the memory storage before generating a response.\n> Initial question: How do customers adapt their shopping habits during different seasons?\n> Follow-up question: Can you elaborate more?\nWe supplement and rectify the customized tools combination below:\npython\n\n```\nfrom langchain.memory import ConversationBufferMemory\n\n# Skipped here - Define your own prefix, suffix, and description with \"chat_history\" for the prompt\n# Keep the original list of tools\n\n# Create the prompt using ZeroShotAgent with additonal \"chat_history\" as input variables\nagent_prompt = ZeroShotAgent.create_prompt(\n    tools, prefix=prefix, suffix=suffix, input_variables=[\"input\", \"chat_history\", \"agent_scratchpad\"],\n)\n\n# Create an instance of ZeroShotAgent with the LLMChain and the allowed tool names\nzero_shot_agent = ZeroShotAgent(\n    llm_chain=LLMChain(llm=llm, prompt=agent_prompt),\n    allowed_tools=[tool.name for tool in tools]\n)\n\n# Initiate memory which allows for storing and extracting messages\nmemory = ConversationBufferMemory(memory_key=\"chat_history\")\n\n# Create an AgentExecutor with memory parameter\nagent_chain = AgentExecutor.from_agent_and_tools(\n    agent=zero_shot_agent, tools=tools, verbose=True, handle_parsing_errors=True, memory=memory\n)\n\n# Define initial question as user input\nuser_inquiry = \"How do customers adapt their shopping habits during different seasons?\"\n\n# Run the agent to generate a response\nagent_executor.run(user_inquiry)\n\n# Define follow-up question as user input\nuser_inquiry = \"Can you elaborate more?\"\n\n# Run the agent to generate another response\nagent_executor.run(user_inquiry)\n```\n\nAgent's responses:\n![Agent&#039;s output - initial question \\(1/2\\) \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1qhLnrRfQIPu52aconUZS0w.png)\nAgent's output - initial question (1/2) (Image by author)\n![Agent&#039;s output - follow-up question \\(2/2\\) \\(Image by author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1ITlla9g0C1woJGK2iUKbZQ.png)\nAgent's output - follow-up question (2/2) (Image by author)\nIn the follow-up question \"Can you elaborate more?\", we intentionally did not provide any hints/ keywords about what we were asking, but the agent demonstrated its ability to continue the analysis of shopping habits in various seasons. This indicates the effectiveness of using memory and shows its advantage by providing a more in-depth description across product categories and seasons.\n### Wrapping it up\nWe conducted experiments to explore the key functionalities and potential approaches of LangChain in developing a customer analytics application based on LLM:\n  * Calculating statistics, by using an `create_sql_agent` agent to query the database and retrieve relevant statistical information.\n  * Insight generation, by applying the prompt template to define the key data features.\n  * Visualization, by using the combination of a custom agent and tool `PythonREPLTool`.\n  * Conversation capabilities, by adding the memory buffer to store and retrieve the chat history.\n\n\nThe choices of wordings in natural language inquiry often do not align precisely with those in the database schema. It was observed that the LangChain executor sometimes does not work as expected, and may even [hallucinate](https://www.pinecone.io/learn/series/langchain/langchain-retrieval-augmentation/), particularly when identifying the data relationships to generate a graph. Therefore, the development of codes requires iterative troubleshooting. While the LangChain framework may only be somewhat reliable and effective in handling diverse customer analytics tasks, it can still offer users with marginal advantage when they have a compelling need to discover insights beyond the traditional analysis dashboards.\nThe design of this application is only the initial stage, and there are further possibilities to discover. For example, customer data is sometimes available in text format, such as customer reviews or product descriptions. LangChain provides the [tagging function](https://python.langchain.com/docs/use_cases/tagging) so that we can conduct a comprehensive analysis by labeling the sentiments, language, style, and more.\n* * *\n### Before you go\nIf you enjoy this reading, I invite you to **** follow my [Medium page](https://medium.com/@johnleungTJ) and [LinkedIn page](https://www.linkedin.com/in/john-leung-639800115/). By doing so, you can stay updated with exciting content related to data science side projects, Machine Learning Operations (MLOps) demonstrations, and project management methodologies.\n> [**Managing the Technical Debts of Machine Learning Systems**](https://towardsdatascience.com/managing-the-technical-debts-of-machine-learning-systems-5b85d420ab9d)\n> [**Monitoring Machine Learning Models in Production: Why and How?**](https://towardsdatascience.com/monitoring-machine-learning-models-in-production-why-and-how-13d07a5ff0c6)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657188043_vu8s9b.jpeg)\nWritten By\n## [John Leung](https://towardsdatascience.com/author/johnleungtj/)\n[See all from John Leung](https://towardsdatascience.com/author/johnleungtj/)\n[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Business Intelligence](https://towardsdatascience.com/tag/business-intelligence/)[Langchain](https://towardsdatascience.com/tag/langchain/)[Llm](https://towardsdatascience.com/tag/llm/)[Python](https://towardsdatascience.com/tag/python/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fperforming-customer-analytics-with-langchain-and-llms-0af4ea38f7b5%2F&title=Performing%20Customer%20Analytics%20with%20LangChain%20and%20LLMs)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fperforming-customer-analytics-with-langchain-and-llms-0af4ea38f7b5%2F&title=Performing%20Customer%20Analytics%20with%20LangChain%20and%20LLMs)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fperforming-customer-analytics-with-langchain-and-llms-0af4ea38f7b5%2F&text=Performing%20Customer%20Analytics%20with%20LangChain%20and%20LLMs)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/12/EDA-with-Pandas-img.jpg)](https://towardsdatascience.com/eda-in-public-part-3-rfm-analysis-for-customer-segmentation-in-pandas/)\n## [EDA in Public (Part 3): RFM Analysis for Customer Segmentation in Pandas](https://towardsdatascience.com/eda-in-public-part-3-rfm-analysis-for-customer-segmentation-in-pandas/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHow to build, score, and interpret RFM segments step by step\n[Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\nJanuary 1, 202612 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/11/jonathan-petersson-W8V3G-Nk8FE-unsplash-scaled-1.jpg)](https://towardsdatascience.com/expected-value-analysis-in-ai-product-management/)\n## [Expected Value Analysis in AI Product Management](https://towardsdatascience.com/expected-value-analysis-in-ai-product-management/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAn introduction to key concepts and practical applications\n[Chinmay Kakatkar](https://towardsdatascience.com/author/kcpub21/)\nNovember 6, 202515 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/10xySt8rSH3BQ2yIwvyGMqA.png)](https://towardsdatascience.com/extending-context-length-in-large-language-models-74e59201b51f/)\n## [Extending Context Length in Large Language Models](https://towardsdatascience.com/extending-context-length-in-large-language-models-74e59201b51f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHow to turn your Llama into a Giraffe\n[Donato Riccio](https://towardsdatascience.com/author/donatoriccio/)\nOctober 15, 20239 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/07/0s9l1e0Xwj7gbz7KX-scaled.jpg)](https://towardsdatascience.com/custom-named-entity-recognition-with-bert-cf1fd4510804/)\n## [Custom Named Entity Recognition with BERT](https://towardsdatascience.com/custom-named-entity-recognition-with-bert-cf1fd4510804/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHow to use PyTorch and Hugging Face to classify named entities in a text\n[Marcello Politi](https://towardsdatascience.com/author/marcellopoliti/)\nJuly 7, 20222 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/0FcnGazdgcGMZzyfD-scaled.jpg)](https://towardsdatascience.com/ai-in-practice-how-to-choose-and-deploy-the-right-strategy-bcda1ed5c1c3/)\n## [AI in Practice: How to Choose and Deploy the Right Strategy](https://towardsdatascience.com/ai-in-practice-how-to-choose-and-deploy-the-right-strategy-bcda1ed5c1c3/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nOur weekly selection of must-read Editors' Picks and original features\n[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)\nOctober 24, 20244 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/03/1spYk3imo6rGXUf4yC9RtNg.jpeg)](https://towardsdatascience.com/plotly-front-to-back-bar-charts-line-charts-2b591d29c6ba/)\n## [Plotly Front to Back: Bar Charts & Line Charts](https://towardsdatascience.com/plotly-front-to-back-bar-charts-line-charts-2b591d29c6ba/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLet's get the basics covered. Source code included.\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nMarch 26, 20206 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/04/1S0aEMQO1N9cduJ17Y94pQg.png)](https://towardsdatascience.com/15-things-you-should-know-about-lists-in-python-c566792eca98/)\n## [15 things you should know about Lists in Python](https://towardsdatascience.com/15-things-you-should-know-about-lists-in-python-c566792eca98/)\n[Programming](https://towardsdatascience.com/category/programming/)\nGuidelines to use lists in Python\n[Amanda Iglesias Moreno](https://towardsdatascience.com/author/amandaiglesiasmoreno/)\nApril 20, 20205 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/13Ar99Uvf17CcXsRHMpu_Hw-scaled.jpeg)](https://towardsdatascience.com/predicting-imdb-movie-ratings-using-supervised-machine-learning-f3b126ab2ddb/)\n## [Predicting IMDb Movie Ratings using Supervised Machine Learning](https://towardsdatascience.com/predicting-imdb-movie-ratings-using-supervised-machine-learning-f3b126ab2ddb/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe process behind my first individual project at Metis\n[Joe Cowell](https://towardsdatascience.com/author/josephpcowell/)\nOctober 14, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/09/0jzhGf7Pvx7xd_v8H-scaled.jpg)](https://towardsdatascience.com/quick-start-from-mongodb-to-pandas-3f777dcbfb6e/)\n## [A Quick Start for Taking MongoDB Collections into Pandas DataFrames](https://towardsdatascience.com/quick-start-from-mongodb-to-pandas-3f777dcbfb6e/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nGet you on your way to data analysis and model building quickly by pulling MongoDB data into Pandas\n[Brian Roepke](https://towardsdatascience.com/author/broepke/)\nSeptember 17, 20227 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "body_base_path": "attachments/4e8481b879e7/pages/",
  "body_markdown_path": "attachments/4e8481b879e7/pages/archived-body.md",
  "local_html": "attachments/4e8481b879e7/pages/archived-body.html",
  "body_source": "prior_capture"
}