• bitcoinBitcoin(BTC)$76,765.00-2.03%
  • ethereumEthereum(ETH)$2,444.20-1.24%
  • tetherTether(USDT)$1.000.00%
  • binancecoinBNB(BNB)$710.88-1.83%
  • rippleXRP(XRP)$1.34-3.78%
  • usd-coinUSDC(USDC)$1.000.02%
  • solanaSolana(SOL)$99.10-2.70%
  • tronTRON(TRX)$0.3400930.15%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.040.98%
  • zcashZcash(ZEC)$1,062.21-14.48%
  • HyperliquidHyperliquid(HYPE)$78.68-6.51%
  • dogecoinDogecoin(DOGE)$0.083408-3.08%
  • RainRain(RAIN)$0.015700-3.95%
  • USDSUSDS(USDS)$1.000.01%
  • moneroMonero(XMR)$506.92-1.52%
  • whitebitWhiteBIT Coin(WBT)$79.44-1.73%
  • chainlinkChainlink(LINK)$11.47-3.19%
  • leo-tokenLEO Token(LEO)$9.10-1.10%
  • cardanoCardano(ADA)$0.206343-3.21%
  • stellarStellar(XLM)$0.175235-2.80%
  • daiDai(DAI)$1.00-0.01%
  • bitcoin-cashBitcoin Cash(BCH)$225.86-10.26%
  • Ethena USDeEthena USDe(USDE)$1.000.00%
  • USD1USD1(USD1)$1.00-0.01%
  • litecoinLitecoin(LTC)$52.73-0.40%
  • CantonCanton(CC)$0.097754-6.05%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.35-1.93%
  • uniswapUniswap(UNI)$5.98-1.17%
  • Global DollarGlobal Dollar(USDG)$1.000.00%
  • hedera-hashgraphHedera(HBAR)$0.074983-2.62%
  • avalanche-2Avalanche(AVAX)$7.44-4.60%
  • nearNEAR Protocol(NEAR)$2.38-5.30%
  • suiSui(SUI)$0.73-4.72%
  • shiba-inuShiba Inu(SHIB)$0.000005-3.20%
  • paypal-usdPayPal USD(PYUSD)$1.000.01%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • crypto-com-chainCronos(CRO)$0.056414-2.53%
  • tether-goldTether Gold(XAUT)$4,319.97-2.02%
  • Circle USYCCircle USYC(USYC)$1.140.01%
  • MemeCoreMemeCore(M)$1.14-6.65%
  • Ripple USDRipple USD(RLUSD)$1.00-0.02%
  • okbOKB(OKB)$109.13-3.55%
  • BittensorBittensor(TAO)$234.42-8.05%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.150.02%
  • polkadotPolkadot(DOT)$1.110.78%
  • mantleMantle(MNT)$0.57-4.39%
  • AsterAster(ASTER)$0.70-3.44%
  • aaveAave(AAVE)$121.42-3.06%
  • pax-goldPAX Gold(PAXG)$4,326.34-1.96%
  • World Liberty FinancialWorld Liberty Financial(WLFI)$0.056194-0.39%
TradePoint.io
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop
No Result
View All Result
TradePoint.io
No Result
View All Result

Using LangChain: How to Add Conversational Memory to an LLM?

December 24, 2023
in AI & Technology
Reading Time: 5 mins read
A A
Using LangChain: How to Add Conversational Memory to an LLM?
ShareShareShareShareShare

Recognizing the need for continuity in user interactions, LangChain, a versatile software framework designed for building applications around LLMs, introduces a pivotal feature known as Conversational Memory. This feature empowers developers to seamlessly integrate memory capabilities into LLMs, enabling them to retain information from previous interactions and respond contextually.

Conversational Memory is a fundamental aspect of LangChain that proves instrumental in creating applications, particularly chatbots. Unlike stateless conversations, where each interaction is treated in isolation, Conversational Memory allows LLMs to remember and leverage information from prior exchanges. This breakthrough feature transforms the user experience, ensuring a more natural and coherent flow of conversation.

  1. Initialize the LLM and ConversationChain

Let’s start by initializing the large language model and the conversational chain using langchain. This will set the stage for implementing conversational memory.

from langchain import OpenAI

from langchain.chains import ConversationChain

# first initialize the large language model

llm = OpenAI(

    temperature=0,

    openai_api_key="OPENAI_API_KEY",

    model_name="text-davinci-003"

)

# now initialize the conversation chain

conversation_chain = ConversationChain(llm)
  1. ConversationBufferMemory

The ConversationBufferMemory in LangChain stores past interactions between the user and AI in its raw form, preserving the complete history. This enables the model to understand and respond contextually by considering the entire conversation flow during subsequent interactions.

from langchain.chains.conversation.memory import ConversationBufferMemory

# Assuming you have already initialized the OpenAI model (llm) elsewhere

# Initialize the ConversationChain with ConversationBufferMemory

conversation_buf = ConversationChain(

    llm=llm,

    memory=ConversationBufferMemory()

)
  1. Counting the Tokens

We have added a count_tokens function so that we can keep a count of the tokens used in each interaction.

from langchain.callbacks import get_openai_callback

def count_tokens(chain, query):

    # Using the get_openai_callback to track token usage

    with get_openai_callback() as cb:

        # Run the query through the conversation chain

        result = chain.run(query)

        # Print the total number of tokens used

        print(f'Spent a total of {cb.total_tokens} tokens')

    return result
  1. Checking the history

To check if the ConversationBufferMemory has saved the history or not, we can print the conversation history just as shown below. This will show that the buffer saves every interaction in the chat history.

  1. ConversationSummaryMemory

When using ConversationSummaryMemory in LangChain, the conversation history is summarized before being provided to the history parameter. This helps control token usage, preventing the quick exhaustion of tokens and overcoming context window limits in advanced LLMs. 

from langchain.chains.conversation.memory import ConversationSummaryMemory

# Assuming you have already initialized the OpenAI model (llm)

conversation = ConversationChain(

    llm=llm,

    memory=ConversationSummaryMemory(llm=llm)

)

# Access and print the template attribute from ConversationSummaryMemory

print(conversation.memory.prompt.template)

Using ConversationSummaryMemory in LangChain offers an advantage for longer conversations as it initially consumes more tokens but grows more slowly as the conversation progresses. This summarization approach is beneficial for cases with extended interactions, providing more efficient use of tokens compared to ConversationBufferMemory, which grows linearly with the number of tokens in the chat. However, it is important to note that even with summarization, there are still inherent limitations due to token constraints over time.

  1. ConversationBufferWindowMemory

We initialize the ConversationChain with ConversationBufferWindowMemory, setting the parameter `k` to 1. This indicates that we are using a windowed buffer memory approach with a window size of 1. This means that only the most recent interaction is retained in memory, discarding previous conversations beyond the most recent exchange. This windowed buffer memory is beneficial when you want to maintain contextual understanding with a limited history.

from langchain.chains.conversation.memory import ConversationBufferWindowMemory

# Assuming you have already initialized llm

# Initialize ConversationChain with ConversationBufferWindowMemory

conversation = ConversationChain(

    llm=llm,

    memory=ConversationBufferWindowMemory(k=1)

)
  1. ConversationSummaryBufferMemory

Here, a ConversationChain named conversation_sum_bufw is initialized with the ConversationSummaryBufferMemory. This memory type utilizes summarization and buffer window techniques to remember essential early interactions while maintaining recent tokens, with a specified token limit of 650 to control memory usage.

In conclusion, using conversational memory in LangChain offers a variety of options to manage the state of conversations with Large Language Models. The examples provided demonstrate different ways to tailor the conversation memory based on specific scenarios. Apart from the ones listed above, we have some more options like ConversationKnowledgeGraphMemory and ConversationEntityMemory.

Whether it’s sending the entire history, utilizing summaries, tracking token counts, or combining these methods, exploring the available options and selecting the appropriate pattern for the use case is key. LangChain provides flexibility, allowing users to implement custom memory modules, combine multiple memory types within the same chain, integrate them with agents, and more.

References


YOU MAY ALSO LIKE

How These XL Phones Compete

CA Governor Signs ‘Landmark’ Laws On Youth Use Of Social Media And AI Chatbots

Manya Goyal is an AI and Research consulting intern at MarktechPost. She is currently pursuing her B.Tech from the Guru Gobind Singh Indraprastha University(Bhagwan Parshuram Institute of Technology). She is a Data Science enthusiast and has a keen interest in the scope of application of artificial intelligence in various fields. She is a podcaster on Spotify and is passionate about exploring.


🚀 Boost your LinkedIn presence with Taplio: AI-driven content creation, easy scheduling, in-depth analytics, and networking with top creators – Try it free now!.

Credit: Source link

ShareTweetSendSharePin

Related Posts

How These XL Phones Compete
AI & Technology

How These XL Phones Compete

September 10, 2026
CA Governor Signs ‘Landmark’ Laws On Youth Use Of Social Media And AI Chatbots
AI & Technology

CA Governor Signs ‘Landmark’ Laws On Youth Use Of Social Media And AI Chatbots

September 10, 2026
Meet Redis LangCache: A Managed Semantic Cache That Cuts LLM API Costs by Up to 90% and Returns Cache Hits Up to 15x Faster
AI & Technology

Meet Redis LangCache: A Managed Semantic Cache That Cuts LLM API Costs by Up to 90% and Returns Cache Hits Up to 15x Faster

September 10, 2026
Meta Is Testing Community Notes In Latin America. Fact Checkers Are Worried.
AI & Technology

Meta Is Testing Community Notes In Latin America. Fact Checkers Are Worried.

September 10, 2026
Next Post
Trump Asks Appeals Court to Toss Election Case on Immunity Grounds

Trump Asks Appeals Court to Toss Election Case on Immunity Grounds

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

No Result
View All Result
French modeling scout linked to Epstein found dead

French modeling scout linked to Epstein found dead

September 7, 2026
Marmalade Cafe files for Bankruptcy after closing Calabasas location

Marmalade Cafe files for Bankruptcy after closing Calabasas location

September 5, 2026
IDScan Is Offering Free Credit Monitoring And ID Protection After Leaking Driver’s Licenses

IDScan Is Offering Free Credit Monitoring And ID Protection After Leaking Driver’s Licenses

September 10, 2026

About

Learn more

Our Services

Legal

Privacy Policy

Terms of Use

Bloggers

Learn more

Article Links

Contact

Advertise

Ask us anything

©2020- TradePoint.io - All rights reserved!

Tradepoint.io, being just a publishing and technology platform, is not a registered broker-dealer or investment adviser. So we do not provide investment advice. Rather, brokerage services are provided to clients of Tradepoint.io by independent SEC-registered broker-dealers and members of FINRA/SIPC. Every form of investing carries some risk and past performance is not a guarantee of future results. “Tradepoint.io“, “Instant Investing” and “My Trading Tools” are registered trademarks of Apperbuild, LLC.

This website is operated by Apperbuild, LLC. We have no link to any brokerage firm and we do not provide investment advice. Every information and resource we provide is solely for the education of our readers. © 2020 Apperbuild, LLC. All rights reserved.

No Result
View All Result
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop

© 2023 - TradePoint.io - All Rights Reserved!