{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Iulia Brezeanu",
  "title_listed": "How to Cut RAG Costs by 80% Using Prompt Compression",
  "keywords": "",
  "domain": "大模型算法",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/how-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb/",
  "publish_date": "2024-01-04",
  "corpus_stage": "",
  "notes": "",
  "id": "940c3a438639",
  "collected_at": "2026-10-02T09:49:58",
  "title": "How to Cut RAG Costs by 80% Using Prompt Compression | 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[Data Science](https://towardsdatascience.com/category/data-science/)\n# How to Cut RAG Costs by 80% Using Prompt Compression\nAccelerating Inference With Prompt Compression\n[Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\nJanuary 4, 202411 min read\n![Image by the author. AI Generated.](../images/000.jpg)\nImage by the author. AI Generated.\nThe inference process is one of the things that greatly increases the money and time costs of using large language models. This problem augments considerably for longer inputs. Below, you can see the relationship between model performance and inference time.\n![Performance score vs inference throughput \\[1\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1ry6MM0kUsofErl_iD16oXw.png)\nPerformance score vs inference throughput [1]\nFast models, which generate more tokens per second, tend to score lower in the Open LLM Leaderboard. Scaling up the model size enables better performance but comes at the cost of lower inference throughput. This makes it difficult to deploy them in real-life applications [1].\nEnhancing LLMs' speed and reducing resource requirements would allow them to be more widely used by individuals or small organizations.\nDifferent solutions are proposed for increasing LLM efficiency; some focus on the model architecture or system. However, proprietary models like ChatGPT or Claude can be accessed only via APIs, so we cannot change their inner algorithm.\nWe will discuss a simple and inexpensive method that relies only on changing the input given to the model - prompt compression.\nFirst, let's clarify how LLMs understand language. The first step in making sense of natural language text is to split it into pieces. This process is called tokenization. A token can be an entire word, a syllable, or a sequence of characters frequently used in current speech.\n![Example of tokenization. Image by author.](../images/002.png)\nExample of tokenization. Image by author.\nAs a rule of thumb, the number of tokens is 33% higher than the number of words. So, 1000 words correspond to approximately 1333 tokens.\nLet's look specifically at the OpenAI pricing for the gpt-3.5-turbo model, as it's the model we will use down the line.\n![OpenAI pricing \\[3\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1V90w4PQY6MB6h4dGOE472w.png)\nOpenAI pricing [3]\nWe can see that the inference process has a cost for both the input tokens, corresponding to the prompt sent to the model, and output tokens, the text generated by the model.\nOne of the applications in which the input tokens consume the most resources is Retrieval-Augmented Generation. The input can even reach thousands of tokens. In RAG, the user query is sent to a vectorial database, where the most similar piece of information is retrieved and sent to the LLM along with the query. In the vectorial database, we can add personal documents that the model didn't see during its initial training.\n![RAG flowchart. Image by author.](../images/004.png)\nRAG flowchart. Image by author.\nThe number of tokens sent to the LLM can be significant depending on how many chunks of text are retrieved from the database.\n## Prompt Compression\n![Illustration of prompt compression \\[1\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1iPsv67TX93GTVSIrVkXphw.png)\nIllustration of prompt compression [1]\nPrompt compression shortens the original prompt while keeping the most important information. It also speeds up how quickly the language model can process the inputs to help it generate fast and accurate answers.\nThis technique uses the fact that language often includes unnecessary repetition. Research shows English has a lot of redundancy - around 75% - in texts that are paragraph or chapter length [2]. This means most of the words can be predicted from the words before them in the context.\n### Auto compressors\nThe first compression method we'll talk about is AutoCompressors. It works by summarizing long text into short vector representations called summary vectors. These compressed summary vectors then act as soft prompts for the model [4].\n![AutoCompressors flow \\[4\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1MQp_M4DqZauPWgswFI4h1Q.png)\nAutoCompressors flow [4]\nDuring soft prompting, the pre-trained model is kept frozen, and a small number of trainable tokens are added at the beginning of the input text for each specific task. These tokens are not fixed but are instead learned through training. They are optimized end-to-end in the context of the entire model to best suit the specific task.\n![RAG with AutoCompressor \\[4\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1EPrR2rN9bL9XO5x29iaLUw.png)\nRAG with AutoCompressor [4]\nFor RAG, the indexed documents can be pre-processed in order to be transformed into summary vectors. During the retrieval phase, the retrieved chunks are fused and sent to the LLM. The fusion process means that their vectorial representations are joined end-to-end to form a single, longer vector. The vectors are basically stacked on top of each other.\nIn order to create these summary vectors, you can choose to train a compressor yourself, or you can use a pre-trained one. Below is an example of how to use the API with a pre-trained compressor taken from the GitHub page of the paper [5].\n![Example use of the API with a pre-trained AutoCompressor model \\[5\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1AlVS9hw_ecpYEB2tWs0vVQ.png)\nExample use of the API with a pre-trained AutoCompressor model [5]\n_AutoCompressor-Llama-2–7b-6k_ is a fine-tuned version of the LLama-2–7B model. It was fine-tuned on a single NVIDIA A100 80GB GPU. The training data consisted of 15 billion tokens from RedPajama, split into sequences of 6,144 tokens each. The LLama-2 model itself stayed frozen during training. Only the summary token embeddings and attention weights were optimized using LoRA.\n### Selective Context\n![Example of context filtering based on the self-information score \\[6\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1N1H4E40ktukLFAg-W2BX8A.png)\nExample of context filtering based on the self-information score [6]\nIn information theory, entropy measures the unpredictability or uncertainty of a piece of information. In the context of language models, it represents the level of uncertainty in predicting the next token in a sequence. A higher entropy indicates greater unpredictability.\nWhen an LLM predicts tokens with high certainty, those tokens contribute less to the model's overall entropy. This motivated the introduction of a method for prompt compression based on removing predictable tokens from the data.\nThe idea is that if tokens with low perplexity are removed, it has a minor impact on the LLM's understanding of the context because these tokens don't add much new information to begin with. Tokens with high perplexity are said to have high self-information values.\nIn order to compress the prompt, a base language model like Llama or GPT-2 assigns a self-information value to each lexical unit (saying basically how surprised it is to see it). A lexical unit can be either a phrase, sentence, or token, depending on our choice. Then, the base model ranks the units in descending order and retains only those from the first p-th percentile, where p is a variable we can set. The authors chose a percentile-based approach instead of an absolute-value one because is more flexible.\nLet's see an example of a text compressed at different lexical units.\n![Text Compression using Selective Context at different lexical units and ratios. Image by author.](../images/010.png)\nText Compression using Selective Context at different lexical units and ratios. Image by author.\nBetween these three lexical units, sentence-level compression keeps the original sentences intact. Also, a lower _reduce ratio_ compresses the text more.\n### LongLLMLingua\n![Framework of LongLLMLingua \\[7\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/14p6DDg1NtFBA5qgQAZkLcA.png)\nFramework of LongLLMLingua [7]\nThe last compression method we'll talk about is LongLLMLingua. LongLLMLingua builds on LLMLingua, which uses a base LLM like Llama to assess the perplexity of each token in a prompt, discarding those with lower perplexities. This approach is based on information entropy, similar to Selective Context.\nHowever, instead of just removing the tokens directly, LLMLingua uses a budget controller, a token-level prompt compression algorithm, and a distribution alignment mechanism. We won't go into too much detail, but you can read more about it in the original paper [8].\nThe problem with LLMLingua is that it doesn't take into consideration the user question during the compression process, which could result in retaining information that is not relevant. LongLLMLingua claims to improve this shortcoming by incorporating the user's question into the compression process.\nThe four new components they bring to the table are a question-aware coarse-to-fine compression method, a document reordering mechanism, compression ratios, and a post-compression subsequence recovery strategy to improve LLMs' perception of the key information.\n**Question-Aware Coarse-Grained Compression** means that instead of looking at each document alone, the new method checks how each document relates to the question. If a document makes the question seem more expected or \"less surprising\" to the model, it's seen as more important.\n**Question-Aware Fine-Grained Compression**\n![Contrastive perplexity equation \\[7\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1EqFL1PqRLNt0-pQB9fSLgw.png)\nContrastive perplexity equation [7]\nFirst, we measure how surprising a word is normally (without the question being considered). This is the _perplexity(x _i | x <i)_, which means the perplexity or surprise of seeing the word x_i​ given all the words before it. Then, we measure the perplexity again, but this time including the question in the context. This is the _perplexity(x _i | x^que, x <i)_, which means the surprise of seeing the word x_i​ given the question and all the words before it.\nThe idea is to find out how much the question changes the surprise level for each word. If a word becomes a lot less surprising when you include the question, it's probably very relevant to the question.\nThen, we **reorder the documents** in descending order based on the importance scores obtained from the first step. This way, the most important documents come first.\n**Subsequence recovery**\n![Example of Subsequence Recovery, the red text represents the original text, and the blue text is the result after using the LLaMA 2–7B tokenizer \\[7\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1dNB0ty6oxSDC2ELglgGlsA.png)\nExample of Subsequence Recovery, the red text represents the original text, and the blue text is the result after using the LLaMA 2–7B tokenizer [7]\nAfter compression, it can happen that key entities like dates or names become altered. For instance, \"2009\" might become \"209,\" or \"Wilhelm Conrad Rontgen\" might turn into \"Wilhelmgen.\" In order to avoid this problem, we first identify the longest substring in the LLM's response that matches a part of the compressed prompt. This substring is considered a key entity. Next, we find the original, uncompressed subsequence corresponding to the compressed entity. Then, we replace the compressed entity with the original one.\n## RAG with LlamaIndex and prompt compression\nWe will use Nicolas Cage's Wikipedia page for a practical RAG application. Probably, the model already saw information about the actor in its training data, so we are specifying that we expect an answer **only based on the retrieved context.** We are loading the Wikipedia page using the _WikipediaReader()_ loader.\npython\n\n```\nfrom llama_index import (\n    VectorStoreIndex,\n    download_loader,\n    load_index_from_storage,\n    StorageContext,\n)\nWikipediaReader = download_loader(\"WikipediaReader\")\nloader = WikipediaReader()\ndocuments = loader.load_data(pages=['Nicolas Cage'])\n```\n\nNow, we are building a simple vector store index. It takes only one line to do the chunking, embedding, and indexing of the documents.\nThe retriever will be used to return the most relevant documents given the user query. It does so by computing the similarity between the query and various document chunks within the embedding space. We want to retrieve the top 2 most similar chunks.\npython\n\n```\nindex = VectorStoreIndex.from_documents(documents)\n\nretriever = index.as_retriever(similarity_top_k=2)\n```\n\nNow that our data is stored in the index, we launch a user query. The _retriever.retrieve(question)_ function searches the index to find the 2 chunks of data that are most similar to the query.\nini\n\n```\nquestion = \"Where did Nicolas Cage go to school?\"\n\ncontexts = retriever.retrieve(question)\n\n# Expected answer:  Beverly Hills High School\n```\n\nThe _contexts_ list carries _NodeWithScore_ data entities with metadata and relationship information with other nodes. For now, we are only interested in the content.\npython\n\n```\ncontext_list = [n.get_content() for n in contexts]\ncontext_list\n```\n\nThis is the retrieved context. Even if we choose to get only the top two documents, we still have to deal with a lot of text.\n![Retrieved text based on user query. Image by author.](../images/014.png)\nRetrieved text based on user query. Image by author.\nWe combine these relevant chunks with the original query to create a prompt. We will use a prompt template instead of just a f-string because we want to reuse it down the line.\nWe then feed this prompt into **gpt-3.5-turbo-16k** to generate a response.\npython\n\n```\n# The response from original prompt\nfrom llama_index.llms import OpenAI\nfrom llama_index.prompts import PromptTemplate\n\nllm = OpenAI(model=\"gpt-3.5-turbo-16k\")\n\ntemplate = (\n    \"We have provided context information below. n\"\n    \"---------------------n\"\n    \"{context_str}\"\n    \"n---------------------n\"\n    \"Given this information, please answer the question: {query_str}n\"\n)\n\nqa_template = PromptTemplate(template)\n\n# you can create text prompt (for completion API)\nprompt = qa_template.format(context_str=\"nn\".join(context_list), query_str=question)\n\nresponse = llm.complete(prompt)\nprint(str(response))\n```\n\nOutput:\n> Nicolas Cage attended Beverly Hills High School and later attended UCLA School of Theater, Film and Television.\nNow, let's measure the RAG performance after using different prompt compression techniques.\n### Selective Context\nWe will use a _reduce _ratio_ of 0.5 and see how the model does. If the compression keeps the information we are interested in, we will lower the value in order to compress more text.\npython\n\n```\nfrom selective_context import SelectiveContext\nsc = SelectiveContext(model_type='gpt2', lang='en')\ncontext_string = \"nn\".join(context_list)\ncontext, reduced_content = sc(context_string, reduce_ratio = 0.5,reduce_level=\"sent\")\nprompt = qa_template.format(context_str=\"nn\".join(reduced_content), query_str=question)\nresponse = llm.complete(prompt)\nprint(str(response))\n```\n\nThis is the reduced content.\n![Reduced content using selective context. Image by author.](../images/body-867825b2628d5183c093.png)\nReduced content using selective context. Image by author.\nIt was compressed at the sentence level, but unfortunately, the information about where Nicolas Cage went to school got lost. We also tried token and phrase-level compression, but the information was still absent.\nOutput:\n> The provided information does not mention where Nicolas Cage went to school.\n### LongLLMLingua\npython\n\n```\n# Setup LLMLingua\nfrom llama_index.query_engine import RetrieverQueryEngine\nfrom llama_index.response_synthesizers import CompactAndRefine\nfrom llama_index.indices.postprocessor import LongLLMLinguaPostprocessor\nnode_postprocessor = LongLLMLinguaPostprocessor(\n    instruction_str=\"Given the context, please answer the final question\",\n    target_token=300,\n    rank_method=\"longllmlingua\",\n    additional_compress_kwargs={\n        \"condition_compare\": True,\n        \"condition_in_question\": \"after\",\n        \"context_budget\": \"+100\",\n        \"reorder_context\": \"sort\",  # enable document reorder,\n        \"dynamic_context_compression_ratio\": 0.3,\n    },\n)\nretrieved_nodes = retriever.retrieve(question)\nsynthesizer = CompactAndRefine()\n```\n\nThe _postprocess _nodes_ function is the one we care about the most because it shortens the node text given the query.\ngraphql\n\n```\nfrom llama_index.indices.query.schema import QueryBundle\n\nnew_retrieved_nodes = node_postprocessor.postprocess_nodes(\n    retrieved_nodes, query_bundle=QueryBundle(query_str=question)\n)\n```\n\nNow let's see the results.\nswift\n\n```\noriginal_contexts = \"nn\".join([n.get_content() for n in retrieved_nodes])\ncompressed_contexts = \"nn\".join([n.get_content() for n in new_retrieved_nodes])\noriginal_tokens = node_postprocessor._llm_lingua.get_token_length(original_contexts)\ncompressed_tokens = node_postprocessor._llm_lingua.get_token_length(compressed_contexts)\nprint(compressed_contexts)\nprint()\nprint(\"Original Tokens:\", original_tokens)\nprint(\"Compressed Tokens:\", compressed_tokens)\nprint(\"Compressed Ratio:\", f\"{original_tokens/(compressed_tokens + 1e-5):.2f}x\")\n```\n\n**Original Tokens: 2362 Compressed Tokens: 344 Compressed Ratio: 6.87x**\nCompressed context:\n![Compressed context using LLMLingua. Image by author.](../images/body-5bb13208059319c7f34c.png)\nCompressed context using LLMLingua. Image by author.\nLet's see if the model understands the compressed context.\npython\n\n```\nresponse = synthesizer.synthesize(question, new_retrieved_nodes)\nprint(str(response))\n```\n\nOutput:\n> Nicolas Cage attended Beverly Hills High School.\nFrom the context compressed using _longllmlingua_ , it is clear where the actor went to school. We also got almost a **7x** reduction of input tokens! This translates to saving **$0.00202**. Imagine the cost reduction for 1B tokens. Normally, they would cost $1000, but with prompt compression, we're just paying around $150.\n![Cost comparison of compressed and original prompt. Image by the author.](../images/body-950df9861580843e4989.png)\nCost comparison of compressed and original prompt. Image by the author.\n## Conclusion\nOf the methods discussed, LongLLMLingua seems to be the most promising for prompt compression in RAG applications. It compresses prompts by 6–7x while still retaining key information needed for the LLM to generate accurate responses.\n. . .\n_If you enjoyed this article, join_[ _**Text Generation**_](https://textgeneration.substack.com/) _- our newsletter has two weekly posts with the latest insights on Generative AI and Large Language Models._\n_You can also find me on_[ _LinkedIn_](https://www.linkedin.com/in/ibrezeanu/) _._\n. . .\n## References\n  1. [Efficient Large Language Models: A Survey](https://arxiv.org/abs/2312.03863)\n\n\n2.[ Prediction and entropy of printed English](https://ieeexplore.ieee.org/document/6773263)\n  1. <https://openai.com/pricing>\n  2. [Adapting Language Models to Compress Contexts](https://arxiv.org/abs/2305.14788)\n  3. <https://github.com/princeton-nlp/AutoCompressors>\n  4. [Unlocking Context Constraints of LLMs: Enhancing Context Efficiency of LLMs with Self-Information-Based Content Filtering](https://arxiv.org/abs/2304.12102)\n  5. [LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models](https://arxiv.org/abs/2310.05736)\n  6. [LongLLMLingua: ACCELERATING AND ENHANCING LLMS IN LONG CONTEXT SCENARIOS VIA PROMPT COMPRESSION](https://arxiv.org/abs/2310.06839)\n\n\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-f993dd42b2e293ffbc34.png)\nWritten By\n## [Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[See all from Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[ChatGPT](https://towardsdatascience.com/tag/chatgpt/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Generative Ai Tools](https://towardsdatascience.com/tag/generative-ai-tools/)[Llm](https://towardsdatascience.com/tag/llm/)[NLP](https://towardsdatascience.com/tag/nlp/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb%2F&title=How%20to%20Cut%20RAG%20Costs%20by%2080%25%20Using%20Prompt%20Compression)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb%2F&title=How%20to%20Cut%20RAG%20Costs%20by%2080%25%20Using%20Prompt%20Compression)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb%2F&text=How%20to%20Cut%20RAG%20Costs%20by%2080%25%20Using%20Prompt%20Compression)\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/015.png)](https://towardsdatascience.com/optimizing-warehouse-operations-with-python-part-1-83d02d001845/)\n## [Improve Warehouse Productivity using Order Batching with Python](https://towardsdatascience.com/optimizing-warehouse-operations-with-python-part-1-83d02d001845/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nDesign a simulation model to estimate the impact of several Single Picker Routing Problem strategies in your Picking Productivity\n[Samir Saci](https://towardsdatascience.com/author/s-saci95/)\nAugust 5, 20207 min read\n  * [![](../images/016.jpg)](https://towardsdatascience.com/best-practices-to-become-a-good-data-scientist-or-machine-learning-engineer-ce10a92f2674/)\n## [Best Practices to become a Good Data Scientist or Machine Learning Engineer](https://towardsdatascience.com/best-practices-to-become-a-good-data-scientist-or-machine-learning-engineer-ce10a92f2674/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nLearning the important practices done by data scientists and machine learning engineers ensures that one produces work that is high quality...\n[Suhas Maddali](https://towardsdatascience.com/author/suhas-maddali007/)\nJune 22, 20226 min read\n  * [![](../images/017.jpeg)](https://towardsdatascience.com/feature-engineering-for-machine-learning-a80d3cdfede6/)\n## [Feature Engineering for Machine Learning (1/3)](https://towardsdatascience.com/feature-engineering-for-machine-learning-a80d3cdfede6/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nPart 1: Data Preprocessing\n[Wing Poon](https://towardsdatascience.com/author/wpoon/)\nMarch 14, 202214 min read\n  * [![](../images/018.jpeg)](https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c/)\n## [Top 7 Machine Learning resources I wish I knew earlier](https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nNot teaching materials, just useful websites\n[Dmytro Nikolaiev (Dimid)](https://towardsdatascience.com/author/andimid/)\nApril 30, 20228 min read\n  * [![](../images/019.jpeg)](https://towardsdatascience.com/5-methods-for-filtering-strings-with-python-pandas-ebe4746dcc74/)\n## [5 Methods for Filtering Strings with Python Pandas](https://towardsdatascience.com/5-methods-for-filtering-strings-with-python-pandas-ebe4746dcc74/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nExplained with examples\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nAugust 10, 20224 min read\n  * [![](../images/020.jpeg)](https://towardsdatascience.com/how-data-scientists-build-machine-learning-models-in-real-life-f1f333022fb7/)\n## [How Data Scientists Build Machine Learning Models in Real Life](https://towardsdatascience.com/how-data-scientists-build-machine-learning-models-in-real-life-f1f333022fb7/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nSteps for successful completion of a predictive model\n[Rahuldeb Das, Ph. D](https://towardsdatascience.com/author/rahuldeb-das/)\nSeptember 17, 202016 min read\n  * [![](../images/021.jpeg)](https://towardsdatascience.com/automation-python-scripts-connecting-to-oracle-database-using-cx-oracle-1fe1801821b5/)\n## [Automation Python Scripts: Connecting to Oracle Database using Cx Oracle](https://towardsdatascience.com/automation-python-scripts-connecting-to-oracle-database-using-cx-oracle-1fe1801821b5/)\n[Programming](https://towardsdatascience.com/category/programming/)\nI've been using cx_Oracle Python extension module to access my Oracle Database and I was able to automate most of my small tasks because...\n[Kathleen Lara](https://towardsdatascience.com/author/itskathleenlara/)\nJanuary 21, 20223 min read\n  * [![](../images/022.jpg)](https://towardsdatascience.com/becoming-a-self-taught-data-scientist-5563f546bb7b/)\n## [Becoming a Self-Taught Data Scientist](https://towardsdatascience.com/becoming-a-self-taught-data-scientist-5563f546bb7b/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWhat to do when college degree in data science just isn't an option\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nNovember 8, 20196 min read\n  * [![](../images/023.jpeg)](https://towardsdatascience.com/euclidean-distance-numpy-1b2784e966fc/)\n## [How To Compute Euclidean Distance in NumPy](https://towardsdatascience.com/euclidean-distance-numpy-1b2784e966fc/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nShowcasing how to calculate euclidean distances in NumPy arrays\n[Giorgos Myrianthous](https://towardsdatascience.com/author/gmyrianthous/)\nMay 17, 20223 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/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  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "How to Cut RAG Costs by 80% Using Prompt Compression | Towards Data Science",
    "description": "Accelerating Inference With Prompt Compression",
    "keywords": null,
    "author": "Iulia Brezeanu",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "How to Cut RAG Costs by 80% Using Prompt Compression",
    "og:description": "Accelerating Inference With Prompt Compression",
    "og:url": "https://towardsdatascience.com/how-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0Kfq432Ng_ZWwAmph.jpg",
    "og:image:width": "1024",
    "og:image:height": "1024",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Iulia Brezeanu",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "11 min read",
    "article:published_time": "2024-01-04T16:38:19.000Z",
    "article:modified_time": "2024-01-04T16:38:19.000Z",
    "article:author": "https://towardsdatascience.com/author/brezeanu.iulia/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_000.txt",
      "chars": 253
    },
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_001.txt",
      "chars": 103
    },
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_002.txt",
      "chars": 138
    },
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_003.txt",
      "chars": 64
    },
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_004.txt",
      "chars": 608
    },
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_005.txt",
      "chars": 367
    },
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_006.txt",
      "chars": 737
    },
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_007.txt",
      "chars": 186
    },
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_008.txt",
      "chars": 534
    },
    {
      "language": "txt",
      "file": "attachments/940c3a438639/code/block_009.txt",
      "chars": 86
    }
  ],
  "images": [
    {
      "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-20T18:05:35Z"
    },
    {
      "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-20T18:05:35Z"
    },
    {
      "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-20T18:05:35Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:05:35Z"
    }
  ],
  "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/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/brezeanu.iulia/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/chatgpt/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/generative-ai-tools/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/llm/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/nlp/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/optimizing-warehouse-operations-with-python-part-1-83d02d001845/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/s-saci95/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/best-practices-to-become-a-good-data-scientist-or-machine-learning-engineer-ce10a92f2674/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/suhas-maddali007/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/feature-engineering-for-machine-learning-a80d3cdfede6/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "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://textgeneration.substack.com/"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/ibrezeanu/"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/2312.03863"
    },
    {
      "type": "external",
      "href": "https://ieeexplore.ieee.org/document/6773263"
    },
    {
      "type": "external",
      "href": "https://openai.com/pricing"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/2305.14788"
    },
    {
      "type": "external",
      "href": "https://github.com/princeton-nlp/AutoCompressors"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/2304.12102"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/2310.05736"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/2310.06839"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=How+to+Cut+RAG+Costs+by+80%25+Using+Prompt+Compression&u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=How+to+Cut+RAG+Costs+by+80%25+Using+Prompt+Compression&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=How+to+Cut+RAG+Costs+by+80%25+Using+Prompt+Compression&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:32:33Z",
  "source_url": "https://towardsdatascience.com/how-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb/",
  "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[Data Science](https://towardsdatascience.com/category/data-science/)\n# How to Cut RAG Costs by 80% Using Prompt Compression\nAccelerating Inference With Prompt Compression\n[Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\nJanuary 4, 202411 min read\n![Image by the author. AI Generated.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0Kfq432Ng_ZWwAmph.jpg)\nImage by the author. AI Generated.\nThe inference process is one of the things that greatly increases the money and time costs of using large language models. This problem augments considerably for longer inputs. Below, you can see the relationship between model performance and inference time.\n![Performance score vs inference throughput \\[1\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1ry6MM0kUsofErl_iD16oXw.png)\nPerformance score vs inference throughput [1]\nFast models, which generate more tokens per second, tend to score lower in the Open LLM Leaderboard. Scaling up the model size enables better performance but comes at the cost of lower inference throughput. This makes it difficult to deploy them in real-life applications [1].\nEnhancing LLMs' speed and reducing resource requirements would allow them to be more widely used by individuals or small organizations.\nDifferent solutions are proposed for increasing LLM efficiency; some focus on the model architecture or system. However, proprietary models like ChatGPT or Claude can be accessed only via APIs, so we cannot change their inner algorithm.\nWe will discuss a simple and inexpensive method that relies only on changing the input given to the model - prompt compression.\nFirst, let's clarify how LLMs understand language. The first step in making sense of natural language text is to split it into pieces. This process is called tokenization. A token can be an entire word, a syllable, or a sequence of characters frequently used in current speech.\n![Example of tokenization. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1VE9Y0tJvo1bYtJXVAW31Cg.png)\nExample of tokenization. Image by author.\nAs a rule of thumb, the number of tokens is 33% higher than the number of words. So, 1000 words correspond to approximately 1333 tokens.\nLet's look specifically at the OpenAI pricing for the gpt-3.5-turbo model, as it's the model we will use down the line.\n![OpenAI pricing \\[3\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1V90w4PQY6MB6h4dGOE472w.png)\nOpenAI pricing [3]\nWe can see that the inference process has a cost for both the input tokens, corresponding to the prompt sent to the model, and output tokens, the text generated by the model.\nOne of the applications in which the input tokens consume the most resources is Retrieval-Augmented Generation. The input can even reach thousands of tokens. In RAG, the user query is sent to a vectorial database, where the most similar piece of information is retrieved and sent to the LLM along with the query. In the vectorial database, we can add personal documents that the model didn't see during its initial training.\n![RAG flowchart. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1TBs8I6hR62p9mlu7v-_NWg.png)\nRAG flowchart. Image by author.\nThe number of tokens sent to the LLM can be significant depending on how many chunks of text are retrieved from the database.\n## Prompt Compression\n![Illustration of prompt compression \\[1\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1iPsv67TX93GTVSIrVkXphw.png)\nIllustration of prompt compression [1]\nPrompt compression shortens the original prompt while keeping the most important information. It also speeds up how quickly the language model can process the inputs to help it generate fast and accurate answers.\nThis technique uses the fact that language often includes unnecessary repetition. Research shows English has a lot of redundancy - around 75% - in texts that are paragraph or chapter length [2]. This means most of the words can be predicted from the words before them in the context.\n### Auto compressors\nThe first compression method we'll talk about is AutoCompressors. It works by summarizing long text into short vector representations called summary vectors. These compressed summary vectors then act as soft prompts for the model [4].\n![AutoCompressors flow \\[4\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1MQp_M4DqZauPWgswFI4h1Q.png)\nAutoCompressors flow [4]\nDuring soft prompting, the pre-trained model is kept frozen, and a small number of trainable tokens are added at the beginning of the input text for each specific task. These tokens are not fixed but are instead learned through training. They are optimized end-to-end in the context of the entire model to best suit the specific task.\n![RAG with AutoCompressor \\[4\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1EPrR2rN9bL9XO5x29iaLUw.png)\nRAG with AutoCompressor [4]\nFor RAG, the indexed documents can be pre-processed in order to be transformed into summary vectors. During the retrieval phase, the retrieved chunks are fused and sent to the LLM. The fusion process means that their vectorial representations are joined end-to-end to form a single, longer vector. The vectors are basically stacked on top of each other.\nIn order to create these summary vectors, you can choose to train a compressor yourself, or you can use a pre-trained one. Below is an example of how to use the API with a pre-trained compressor taken from the GitHub page of the paper [5].\n![Example use of the API with a pre-trained AutoCompressor model \\[5\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1AlVS9hw_ecpYEB2tWs0vVQ.png)\nExample use of the API with a pre-trained AutoCompressor model [5]\n_AutoCompressor-Llama-2–7b-6k_ is a fine-tuned version of the LLama-2–7B model. It was fine-tuned on a single NVIDIA A100 80GB GPU. The training data consisted of 15 billion tokens from RedPajama, split into sequences of 6,144 tokens each. The LLama-2 model itself stayed frozen during training. Only the summary token embeddings and attention weights were optimized using LoRA.\n### Selective Context\n![Example of context filtering based on the self-information score \\[6\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1N1H4E40ktukLFAg-W2BX8A.png)\nExample of context filtering based on the self-information score [6]\nIn information theory, entropy measures the unpredictability or uncertainty of a piece of information. In the context of language models, it represents the level of uncertainty in predicting the next token in a sequence. A higher entropy indicates greater unpredictability.\nWhen an LLM predicts tokens with high certainty, those tokens contribute less to the model's overall entropy. This motivated the introduction of a method for prompt compression based on removing predictable tokens from the data.\nThe idea is that if tokens with low perplexity are removed, it has a minor impact on the LLM's understanding of the context because these tokens don't add much new information to begin with. Tokens with high perplexity are said to have high self-information values.\nIn order to compress the prompt, a base language model like Llama or GPT-2 assigns a self-information value to each lexical unit (saying basically how surprised it is to see it). A lexical unit can be either a phrase, sentence, or token, depending on our choice. Then, the base model ranks the units in descending order and retains only those from the first p-th percentile, where p is a variable we can set. The authors chose a percentile-based approach instead of an absolute-value one because is more flexible.\nLet's see an example of a text compressed at different lexical units.\n![Text Compression using Selective Context at different lexical units and ratios. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1RWDwNxUTvrNsRTQ1PQA6bA.png)\nText Compression using Selective Context at different lexical units and ratios. Image by author.\nBetween these three lexical units, sentence-level compression keeps the original sentences intact. Also, a lower _reduce ratio_ compresses the text more.\n### LongLLMLingua\n![Framework of LongLLMLingua \\[7\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/14p6DDg1NtFBA5qgQAZkLcA.png)\nFramework of LongLLMLingua [7]\nThe last compression method we'll talk about is LongLLMLingua. LongLLMLingua builds on LLMLingua, which uses a base LLM like Llama to assess the perplexity of each token in a prompt, discarding those with lower perplexities. This approach is based on information entropy, similar to Selective Context.\nHowever, instead of just removing the tokens directly, LLMLingua uses a budget controller, a token-level prompt compression algorithm, and a distribution alignment mechanism. We won't go into too much detail, but you can read more about it in the original paper [8].\nThe problem with LLMLingua is that it doesn't take into consideration the user question during the compression process, which could result in retaining information that is not relevant. LongLLMLingua claims to improve this shortcoming by incorporating the user's question into the compression process.\nThe four new components they bring to the table are a question-aware coarse-to-fine compression method, a document reordering mechanism, compression ratios, and a post-compression subsequence recovery strategy to improve LLMs' perception of the key information.\n**Question-Aware Coarse-Grained Compression** means that instead of looking at each document alone, the new method checks how each document relates to the question. If a document makes the question seem more expected or \"less surprising\" to the model, it's seen as more important.\n**Question-Aware Fine-Grained Compression**\n![Contrastive perplexity equation \\[7\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1EqFL1PqRLNt0-pQB9fSLgw.png)\nContrastive perplexity equation [7]\nFirst, we measure how surprising a word is normally (without the question being considered). This is the _perplexity(x _i | x <i)_, which means the perplexity or surprise of seeing the word x_i​ given all the words before it. Then, we measure the perplexity again, but this time including the question in the context. This is the _perplexity(x _i | x^que, x <i)_, which means the surprise of seeing the word x_i​ given the question and all the words before it.\nThe idea is to find out how much the question changes the surprise level for each word. If a word becomes a lot less surprising when you include the question, it's probably very relevant to the question.\nThen, we **reorder the documents** in descending order based on the importance scores obtained from the first step. This way, the most important documents come first.\n**Subsequence recovery**\n![Example of Subsequence Recovery, the red text represents the original text, and the blue text is the result after using the LLaMA 2–7B tokenizer \\[7\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1dNB0ty6oxSDC2ELglgGlsA.png)\nExample of Subsequence Recovery, the red text represents the original text, and the blue text is the result after using the LLaMA 2–7B tokenizer [7]\nAfter compression, it can happen that key entities like dates or names become altered. For instance, \"2009\" might become \"209,\" or \"Wilhelm Conrad Rontgen\" might turn into \"Wilhelmgen.\" In order to avoid this problem, we first identify the longest substring in the LLM's response that matches a part of the compressed prompt. This substring is considered a key entity. Next, we find the original, uncompressed subsequence corresponding to the compressed entity. Then, we replace the compressed entity with the original one.\n## RAG with LlamaIndex and prompt compression\nWe will use Nicolas Cage's Wikipedia page for a practical RAG application. Probably, the model already saw information about the actor in its training data, so we are specifying that we expect an answer **only based on the retrieved context.** We are loading the Wikipedia page using the _WikipediaReader()_ loader.\npython\n\n```\nfrom llama_index import (\n    VectorStoreIndex,\n    download_loader,\n    load_index_from_storage,\n    StorageContext,\n)\nWikipediaReader = download_loader(\"WikipediaReader\")\nloader = WikipediaReader()\ndocuments = loader.load_data(pages=['Nicolas Cage'])\n```\n\nNow, we are building a simple vector store index. It takes only one line to do the chunking, embedding, and indexing of the documents.\nThe retriever will be used to return the most relevant documents given the user query. It does so by computing the similarity between the query and various document chunks within the embedding space. We want to retrieve the top 2 most similar chunks.\npython\n\n```\nindex = VectorStoreIndex.from_documents(documents)\n\nretriever = index.as_retriever(similarity_top_k=2)\n```\n\nNow that our data is stored in the index, we launch a user query. The _retriever.retrieve(question)_ function searches the index to find the 2 chunks of data that are most similar to the query.\nini\n\n```\nquestion = \"Where did Nicolas Cage go to school?\"\n\ncontexts = retriever.retrieve(question)\n\n# Expected answer:  Beverly Hills High School\n```\n\nThe _contexts_ list carries _NodeWithScore_ data entities with metadata and relationship information with other nodes. For now, we are only interested in the content.\npython\n\n```\ncontext_list = [n.get_content() for n in contexts]\ncontext_list\n```\n\nThis is the retrieved context. Even if we choose to get only the top two documents, we still have to deal with a lot of text.\n![Retrieved text based on user query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1t__0KVVVKOnte7H2xfTW2w.png)\nRetrieved text based on user query. Image by author.\nWe combine these relevant chunks with the original query to create a prompt. We will use a prompt template instead of just a f-string because we want to reuse it down the line.\nWe then feed this prompt into **gpt-3.5-turbo-16k** to generate a response.\npython\n\n```\n# The response from original prompt\nfrom llama_index.llms import OpenAI\nfrom llama_index.prompts import PromptTemplate\n\nllm = OpenAI(model=\"gpt-3.5-turbo-16k\")\n\ntemplate = (\n    \"We have provided context information below. n\"\n    \"---------------------n\"\n    \"{context_str}\"\n    \"n---------------------n\"\n    \"Given this information, please answer the question: {query_str}n\"\n)\n\nqa_template = PromptTemplate(template)\n\n# you can create text prompt (for completion API)\nprompt = qa_template.format(context_str=\"nn\".join(context_list), query_str=question)\n\nresponse = llm.complete(prompt)\nprint(str(response))\n```\n\nOutput:\n> Nicolas Cage attended Beverly Hills High School and later attended UCLA School of Theater, Film and Television.\nNow, let's measure the RAG performance after using different prompt compression techniques.\n### Selective Context\nWe will use a _reduce _ratio_ of 0.5 and see how the model does. If the compression keeps the information we are interested in, we will lower the value in order to compress more text.\npython\n\n```\nfrom selective_context import SelectiveContext\nsc = SelectiveContext(model_type='gpt2', lang='en')\ncontext_string = \"nn\".join(context_list)\ncontext, reduced_content = sc(context_string, reduce_ratio = 0.5,reduce_level=\"sent\")\nprompt = qa_template.format(context_str=\"nn\".join(reduced_content), query_str=question)\nresponse = llm.complete(prompt)\nprint(str(response))\n```\n\nThis is the reduced content.\n![Reduced content using selective context. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1F2qy5_yBSia3uXxqGE2i5w.png)\nReduced content using selective context. Image by author.\nIt was compressed at the sentence level, but unfortunately, the information about where Nicolas Cage went to school got lost. We also tried token and phrase-level compression, but the information was still absent.\nOutput:\n> The provided information does not mention where Nicolas Cage went to school.\n### LongLLMLingua\npython\n\n```\n# Setup LLMLingua\nfrom llama_index.query_engine import RetrieverQueryEngine\nfrom llama_index.response_synthesizers import CompactAndRefine\nfrom llama_index.indices.postprocessor import LongLLMLinguaPostprocessor\nnode_postprocessor = LongLLMLinguaPostprocessor(\n    instruction_str=\"Given the context, please answer the final question\",\n    target_token=300,\n    rank_method=\"longllmlingua\",\n    additional_compress_kwargs={\n        \"condition_compare\": True,\n        \"condition_in_question\": \"after\",\n        \"context_budget\": \"+100\",\n        \"reorder_context\": \"sort\",  # enable document reorder,\n        \"dynamic_context_compression_ratio\": 0.3,\n    },\n)\nretrieved_nodes = retriever.retrieve(question)\nsynthesizer = CompactAndRefine()\n```\n\nThe _postprocess _nodes_ function is the one we care about the most because it shortens the node text given the query.\ngraphql\n\n```\nfrom llama_index.indices.query.schema import QueryBundle\n\nnew_retrieved_nodes = node_postprocessor.postprocess_nodes(\n    retrieved_nodes, query_bundle=QueryBundle(query_str=question)\n)\n```\n\nNow let's see the results.\nswift\n\n```\noriginal_contexts = \"nn\".join([n.get_content() for n in retrieved_nodes])\ncompressed_contexts = \"nn\".join([n.get_content() for n in new_retrieved_nodes])\noriginal_tokens = node_postprocessor._llm_lingua.get_token_length(original_contexts)\ncompressed_tokens = node_postprocessor._llm_lingua.get_token_length(compressed_contexts)\nprint(compressed_contexts)\nprint()\nprint(\"Original Tokens:\", original_tokens)\nprint(\"Compressed Tokens:\", compressed_tokens)\nprint(\"Compressed Ratio:\", f\"{original_tokens/(compressed_tokens + 1e-5):.2f}x\")\n```\n\n**Original Tokens: 2362 Compressed Tokens: 344 Compressed Ratio: 6.87x**\nCompressed context:\n![Compressed context using LLMLingua. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1JXJZ3gJjihq6DqYCgTP18Q.png)\nCompressed context using LLMLingua. Image by author.\nLet's see if the model understands the compressed context.\npython\n\n```\nresponse = synthesizer.synthesize(question, new_retrieved_nodes)\nprint(str(response))\n```\n\nOutput:\n> Nicolas Cage attended Beverly Hills High School.\nFrom the context compressed using _longllmlingua_ , it is clear where the actor went to school. We also got almost a **7x** reduction of input tokens! This translates to saving **$0.00202**. Imagine the cost reduction for 1B tokens. Normally, they would cost $1000, but with prompt compression, we're just paying around $150.\n![Cost comparison of compressed and original prompt. Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0yd1XpxNLHv73jM3_.png)\nCost comparison of compressed and original prompt. Image by the author.\n## Conclusion\nOf the methods discussed, LongLLMLingua seems to be the most promising for prompt compression in RAG applications. It compresses prompts by 6–7x while still retaining key information needed for the LLM to generate accurate responses.\n. . .\n_If you enjoyed this article, join_[ _**Text Generation**_](https://textgeneration.substack.com/) _- our newsletter has two weekly posts with the latest insights on Generative AI and Large Language Models._\n_You can also find me on_[ _LinkedIn_](https://www.linkedin.com/in/ibrezeanu/) _._\n. . .\n## References\n  1. [Efficient Large Language Models: A Survey](https://arxiv.org/abs/2312.03863)\n\n\n2.[ Prediction and entropy of printed English](https://ieeexplore.ieee.org/document/6773263)\n  1. <https://openai.com/pricing>\n  2. [Adapting Language Models to Compress Contexts](https://arxiv.org/abs/2305.14788)\n  3. <https://github.com/princeton-nlp/AutoCompressors>\n  4. [Unlocking Context Constraints of LLMs: Enhancing Context Efficiency of LLMs with Self-Information-Based Content Filtering](https://arxiv.org/abs/2304.12102)\n  5. [LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models](https://arxiv.org/abs/2310.05736)\n  6. [LongLLMLingua: ACCELERATING AND ENHANCING LLMS IN LONG CONTEXT SCENARIOS VIA PROMPT COMPRESSION](https://arxiv.org/abs/2310.06839)\n\n\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/1787657516549_c8nzry.png)\nWritten By\n## [Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[See all from Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[ChatGPT](https://towardsdatascience.com/tag/chatgpt/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Generative Ai Tools](https://towardsdatascience.com/tag/generative-ai-tools/)[Llm](https://towardsdatascience.com/tag/llm/)[NLP](https://towardsdatascience.com/tag/nlp/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb%2F&title=How%20to%20Cut%20RAG%20Costs%20by%2080%25%20Using%20Prompt%20Compression)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb%2F&title=How%20to%20Cut%20RAG%20Costs%20by%2080%25%20Using%20Prompt%20Compression)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-cut-rag-costs-by-80-using-prompt-compression-877a07c6bedb%2F&text=How%20to%20Cut%20RAG%20Costs%20by%2080%25%20Using%20Prompt%20Compression)\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/2020/08/1tn8vSBXDfTZ_bypVrRrJCA.png)](https://towardsdatascience.com/optimizing-warehouse-operations-with-python-part-1-83d02d001845/)\n## [Improve Warehouse Productivity using Order Batching with Python](https://towardsdatascience.com/optimizing-warehouse-operations-with-python-part-1-83d02d001845/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nDesign a simulation model to estimate the impact of several Single Picker Routing Problem strategies in your Picking Productivity\n[Samir Saci](https://towardsdatascience.com/author/s-saci95/)\nAugust 5, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/06/0jB7c_U0O5XJ9lqll-scaled.jpg)](https://towardsdatascience.com/best-practices-to-become-a-good-data-scientist-or-machine-learning-engineer-ce10a92f2674/)\n## [Best Practices to become a Good Data Scientist or Machine Learning Engineer](https://towardsdatascience.com/best-practices-to-become-a-good-data-scientist-or-machine-learning-engineer-ce10a92f2674/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nLearning the important practices done by data scientists and machine learning engineers ensures that one produces work that is high quality...\n[Suhas Maddali](https://towardsdatascience.com/author/suhas-maddali007/)\nJune 22, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/03/1B-FrsT65CzQM66ILlC9p-A.jpeg)](https://towardsdatascience.com/feature-engineering-for-machine-learning-a80d3cdfede6/)\n## [Feature Engineering for Machine Learning (1/3)](https://towardsdatascience.com/feature-engineering-for-machine-learning-a80d3cdfede6/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nPart 1: Data Preprocessing\n[Wing Poon](https://towardsdatascience.com/author/wpoon/)\nMarch 14, 202214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1WYfQvU9fEnHEnxFxZQo9Kg.jpeg)](https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c/)\n## [Top 7 Machine Learning resources I wish I knew earlier](https://towardsdatascience.com/top-7-machine-learning-resources-i-wish-i-knew-earlier-89f4b8d3364c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nNot teaching materials, just useful websites\n[Dmytro Nikolaiev (Dimid)](https://towardsdatascience.com/author/andimid/)\nApril 30, 20228 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/08/1e1p6ZFThdgGka6KE6o8uOA-scaled.jpeg)](https://towardsdatascience.com/5-methods-for-filtering-strings-with-python-pandas-ebe4746dcc74/)\n## [5 Methods for Filtering Strings with Python Pandas](https://towardsdatascience.com/5-methods-for-filtering-strings-with-python-pandas-ebe4746dcc74/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nExplained with examples\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nAugust 10, 20224 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1xTcU74Gqaqi-KTxv5up7uw-scaled.jpeg)](https://towardsdatascience.com/how-data-scientists-build-machine-learning-models-in-real-life-f1f333022fb7/)\n## [How Data Scientists Build Machine Learning Models in Real Life](https://towardsdatascience.com/how-data-scientists-build-machine-learning-models-in-real-life-f1f333022fb7/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nSteps for successful completion of a predictive model\n[Rahuldeb Das, Ph. D](https://towardsdatascience.com/author/rahuldeb-das/)\nSeptember 17, 202016 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/01/1MP3dLOP8S2vaauHxR2CGuA.jpeg)](https://towardsdatascience.com/automation-python-scripts-connecting-to-oracle-database-using-cx-oracle-1fe1801821b5/)\n## [Automation Python Scripts: Connecting to Oracle Database using Cx Oracle](https://towardsdatascience.com/automation-python-scripts-connecting-to-oracle-database-using-cx-oracle-1fe1801821b5/)\n[Programming](https://towardsdatascience.com/category/programming/)\nI've been using cx_Oracle Python extension module to access my Oracle Database and I was able to automate most of my small tasks because...\n[Kathleen Lara](https://towardsdatascience.com/author/itskathleenlara/)\nJanuary 21, 20223 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/11/0daKRpQ-ePrNsolaw-scaled.jpg)](https://towardsdatascience.com/becoming-a-self-taught-data-scientist-5563f546bb7b/)\n## [Becoming a Self-Taught Data Scientist](https://towardsdatascience.com/becoming-a-self-taught-data-scientist-5563f546bb7b/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWhat to do when college degree in data science just isn't an option\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nNovember 8, 20196 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/05/17QbYhfKhHh9tIhUmuGpFBw-scaled.jpeg)](https://towardsdatascience.com/euclidean-distance-numpy-1b2784e966fc/)\n## [How To Compute Euclidean Distance in NumPy](https://towardsdatascience.com/euclidean-distance-numpy-1b2784e966fc/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nShowcasing how to calculate euclidean distances in NumPy arrays\n[Giorgos Myrianthous](https://towardsdatascience.com/author/gmyrianthous/)\nMay 17, 20223 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/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  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/940c3a438639/pages/",
  "body_markdown_path": "attachments/940c3a438639/pages/archived-body.md",
  "local_html": "attachments/940c3a438639/pages/archived-body.html",
  "body_source": "prior_capture"
}