• bitcoinBitcoin(BTC)$78,388.000.85%
  • ethereumEthereum(ETH)$2,292.831.22%
  • tetherTether(USDT)$1.00-0.05%
  • binancecoinBNB(BNB)$710.340.73%
  • rippleXRP(XRP)$1.250.08%
  • usd-coinUSDC(USDC)$1.00-0.05%
  • solanaSolana(SOL)$94.95-0.54%
  • tronTRON(TRX)$0.3140521.04%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.081.11%
  • zcashZcash(ZEC)$1,275.982.50%
  • HyperliquidHyperliquid(HYPE)$87.72-0.18%
  • dogecoinDogecoin(DOGE)$0.0759580.25%
  • moneroMonero(XMR)$608.820.54%
  • USDSUSDS(USDS)$1.00-0.06%
  • whitebitWhiteBIT Coin(WBT)$75.300.84%
  • chainlinkChainlink(LINK)$11.39-2.19%
  • leo-tokenLEO Token(LEO)$9.39-0.10%
  • cardanoCardano(ADA)$0.192608-0.31%
  • stellarStellar(XLM)$0.168909-0.07%
  • bitcoin-cashBitcoin Cash(BCH)$283.33-0.68%
  • nearNEAR Protocol(NEAR)$4.26-2.59%
  • daiDai(DAI)$1.00-0.06%
  • uniswapUniswap(UNI)$7.261.05%
  • Ethena USDeEthena USDe(USDE)$1.00-0.05%
  • litecoinLitecoin(LTC)$55.60-0.93%
  • RainRain(RAIN)$0.005611-8.72%
  • USD1USD1(USD1)$1.00-0.02%
  • CantonCanton(CC)$0.096185-1.41%
  • avalanche-2Avalanche(AVAX)$8.66-3.02%
  • suiSui(SUI)$0.90-0.49%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.21-0.75%
  • hedera-hashgraphHedera(HBAR)$0.071355-0.98%
  • tether-goldTether Gold(XAUT)$3,909.671.05%
  • Global DollarGlobal Dollar(USDG)$1.00-0.04%
  • quant-networkQuant(QNT)$199.17-0.42%
  • paypal-usdPayPal USD(PYUSD)$1.00-0.03%
  • shiba-inuShiba Inu(SHIB)$0.000005-0.43%
  • BittensorBittensor(TAO)$232.49-2.07%
  • crypto-com-chainCronos(CRO)$0.051076-0.24%
  • EthenaEthena(ENA)$0.181798-3.13%
  • Ripple USDRipple USD(RLUSD)$1.00-0.05%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.15-0.10%
  • okbOKB(OKB)$113.722.59%
  • Circle USYCCircle USYC(USYC)$1.140.00%
  • pepePepe(PEPE)$0.000005-1.67%
  • aaveAave(AAVE)$133.77-4.04%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • MemeCoreMemeCore(M)$0.85-6.05%
  • OndoOndo(ONDO)$0.400481-3.12%
  • Pump.funPump.fun(PUMP)$0.004152-1.60%
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 Long Is A New Apple TV Actually Supposed To Last?

6 Google Maps Features That Work Better On Android Auto Vs. CarPlay

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 Long Is A New Apple TV Actually Supposed To Last?
AI & Technology

How Long Is A New Apple TV Actually Supposed To Last?

November 2, 2026
6 Google Maps Features That Work Better On Android Auto Vs. CarPlay
AI & Technology

6 Google Maps Features That Work Better On Android Auto Vs. CarPlay

November 2, 2026
This Is The Right Way To Clean Your Vinyl Records
AI & Technology

This Is The Right Way To Clean Your Vinyl Records

November 1, 2026
Aramco Acquires 49% HUMAIN Stake With .6B Cash, AI Assets – Unite.AI
AI & Technology

Aramco Acquires 49% HUMAIN Stake With $2.6B Cash, AI Assets – Unite.AI

November 1, 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
Fan Fiction Website AO3 Is Down, And It Could Take Weeks To Recover

Fan Fiction Website AO3 Is Down, And It Could Take Weeks To Recover

October 29, 2026
Latina scientist works to save endangered manatees in Florida

Latina scientist works to save endangered manatees in Florida

October 27, 2026
Doctor says Pope Leo has ‘one of the more treatable’ cancers

Doctor says Pope Leo has ‘one of the more treatable’ cancers

October 26, 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!