/ archive / python / 3_conversational_memory.py
3_conversational_memory.py
 1  """
 2  Conversational Memory Example.
 3  This demonstrates how to build a chatbot that remembers conversation history.
 4  """
 5  
 6  from langchain_community.llms import Ollama
 7  from langchain.chains import ConversationChain
 8  from langchain.memory import ConversationBufferMemory, ConversationSummaryMemory
 9  
10  # Initialize Ollama
11  llm = Ollama(
12      model="gpt-oss:120b",
13      base_url="http://192.222.50.154:11434"
14  )
15  
16  def create_chatbot_with_memory():
17      """
18      Create a conversational chatbot that remembers the conversation.
19      """
20      # Use buffer memory to store entire conversation
21      memory = ConversationBufferMemory()
22  
23      # Create conversation chain
24      conversation = ConversationChain(
25          llm=llm,
26          memory=memory,
27          verbose=True  # Shows the chain's thought process
28      )
29  
30      return conversation
31  
32  def create_chatbot_with_summary_memory():
33      """
34      Create a chatbot that summarizes conversation history (better for long conversations).
35      """
36      memory = ConversationSummaryMemory(llm=llm)
37  
38      conversation = ConversationChain(
39          llm=llm,
40          memory=memory,
41          verbose=True
42      )
43  
44      return conversation
45  
46  if __name__ == "__main__":
47      print("=" * 60)
48      print("Conversational Chatbot with Memory")
49      print("=" * 60)
50  
51      # Create chatbot
52      chatbot = create_chatbot_with_memory()
53  
54      # Simulate a conversation
55      conversations = [
56          "Hi! My name is Alice and I'm a software engineer.",
57          "What's my name?",
58          "What do I do for work?",
59          "Can you write a Python function for me that calculates the area of a circle?"
60      ]
61  
62      for user_input in conversations:
63          print(f"\n{'User:':<10} {user_input}")
64          response = chatbot.predict(input=user_input)
65          print(f"{'Assistant:':<10} {response}")
66  
67      print("\n" + "=" * 60)
68      print("Conversation History")
69      print("=" * 60)
70      print(chatbot.memory.buffer)
71  
72      # Example with summary memory for long conversations
73      print("\n\n" + "=" * 60)
74      print("Chatbot with Summary Memory (for long conversations)")
75      print("=" * 60)
76  
77      summary_chatbot = create_chatbot_with_summary_memory()
78  
79      # Simulate a longer conversation
80      long_conversation = [
81          "I'm planning a trip to Japan next month.",
82          "I want to visit Tokyo, Kyoto, and Osaka.",
83          "What's the best way to travel between these cities?",
84          "How many days should I spend in each city?",
85          "What are some must-see attractions in Tokyo?"
86      ]
87  
88      for user_input in long_conversation:
89          print(f"\n{'User:':<10} {user_input}")
90          response = summary_chatbot.predict(input=user_input)
91          print(f"{'Assistant:':<10} {response[:200]}...")  # Truncate for readability
92  
93      print("\n" + "=" * 60)
94      print("Conversation Summary")
95      print("=" * 60)
96      print(summary_chatbot.memory.buffer)