หน่วยความจำบัฟเฟอร์การสนทนา
นำหน่วยความจำการสนทนาพื้นฐานมาใช้เพื่อจัดเก็บและเรียกคืนการโต้ตอบก่อนหน้าในบริบทของเอเจนต์
หน่วยความจำบัฟเฟอร์การสนทนา เป็นบทเรียน AI Agents with LangChain & Autonomous Workflows ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents with LangChain & Autonomous Workflows และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Agents Need Memory
Imagine having a conversation where you instantly forget everything said just a moment ago. That's what happens to an AI agent without memory!
Agents often need to recall past interactions to maintain context. Without memory, each turn is a fresh start, leading to repetitive or nonsensical conversations.
What is Buffer Memory?
ConversationBufferMemory is LangChain's simplest memory type. It stores the raw, unsummarized conversation history directly.
Think of it like keeping a full transcript of everything said, in the exact order it was said. It's straightforward and easy to use for basic conversational recall.
Initializing Buffer Memory
To use ConversationBufferMemory, you simply import it and create an instance. It's often integrated into a Chain, but we can explore it standalone first.
Let's initialize a memory object and peek at its initial (empty) state:
from langchain.memory import ConversationBufferMemory
# Initialize the memory
memory = ConversationBufferMemory()
print("Memory initialized!")
# You can see its content (it will be empty at first)
print(memory.load_memory_variables({}))Saving Conversation Context
The save_context method is how you add new user inputs and AI outputs to the memory. It takes two dictionaries: one for inputs and one for outputs.
This method is crucial because it's how the memory 'learns' from the ongoing conversation and builds its history.
Code Demo: Saving Context
Let's add a simple interaction to our memory object and see how it stores the conversation turn.
Notice how the 'input' and 'output' are paired and stored as 'Human' and 'AI' messages.
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
# Simulate a user input and an AI response
memory.save_context(
{"input": "Hi there!"},
{"output": "Hello! How can I help you?"}
)
print("Memory after one turn:")
print(memory.load_memory_variables({}))Retrieving Stored History
To access the stored conversation history, you use the load_memory_variables method. It returns a dictionary containing the memory content.
By default, the conversation history is stored under the key 'history'. This key is what you'll typically pass into your LLM's prompt template.
Customizing the Memory Key
By default, ConversationBufferMemory stores history under the key 'history'. However, your prompt template might expect a different variable name, like 'chat_history'.
You can change this using the memory_key parameter during initialization:
from langchain.memory import ConversationBufferMemory
# Initialize with a custom memory_key
memory = ConversationBufferMemory(memory_key="my_chat_history")
memory.save_context(
{"input": "What's up?"},
{"output": "Not much, just coding!"}
)
print("Memory with custom key:")
print(memory.load_memory_variables({}))Integrating with an LLM Chain
Here's how you integrate ConversationBufferMemory into an LLMChain. The memory_key in the ConversationBufferMemory must match the variable name in your PromptTemplate (e.g., chat_history).
Remember to replace 'YOUR_API_KEY' with your actual OpenAI key if you want to run this example fully.
from langchain.memory import ConversationBufferMemory
from langchain.chains import LLMChain
from langchain_openai import OpenAI
from langchain.prompts import PromptTemplate
import os
# Set your OpenAI API key (replace with your actual key or env var)
# os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
# Initialize LLM (using a dummy if API key not set)
llm = OpenAI(temperature=0) # You might need to set openai_api_key=os.environ.get("OPENAI_API_KEY")
# Initialize memory with a key matching the prompt template
memory = ConversationBufferMemory(memory_key="chat_history")
# Define a prompt template that expects 'chat_history'
template = """You are a friendly chatbot.
{chat_history}
Human: {human_input}
AI:"""
prompt = PromptTemplate(
input_variables=["chat_history", "human_input"],
template=template
)
# Create an LLMChain with the memory
conversation = LLMChain(
llm=llm,
prompt=prompt,
verbose=False,
memory=memory
)
# First turn
print("Human: What is your capital?")
response1 = conversation.predict(human_input="What is your capital?")
print(f"AI: {response1}")
# Second turn - the AI should remember the context
print("\nHuman: And what about its population?")
response2 = conversation.predict(human_input="And what about its population?")
print(f"AI: {response2}")When to Use Buffer Memory
ConversationBufferMemory is excellent for short, direct conversations where you need exact recall of recent turns.
- Pros: Simple to implement, stores full, unedited conversation details.
- Cons: Can quickly exceed the LLM's context window for longer chats, no summarization or filtering, leading to higher token usage and costs.
Quick Check
Let's test your understanding of ConversationBufferMemory.
Buffer Memory Summary
We've successfully explored ConversationBufferMemory, LangChain's simplest way to give agents a basic form of memory:
- It stores raw conversation history.
- You use
save_contextto add turns andload_memory_variablesto retrieve them. - It's ideal for short, direct conversations but can quickly hit LLM context limits with longer chats.
- Remember to set
memory_keyif your prompt expects a different variable name for history.
Next, we'll dive into more advanced memory solutions that handle longer conversations better!
คำถามที่พบบ่อย
บทเรียน “หน่วยความจำบัฟเฟอร์การสนทนา” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “หน่วยความจำบัฟเฟอร์การสนทนา” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents with LangChain & Autonomous Workflows ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “หน่วยความจำบัฟเฟอร์การสนทนา”
นำหน่วยความจำการสนทนาพื้นฐานมาใช้เพื่อจัดเก็บและเรียกคืนการโต้ตอบก่อนหน้าในบริบทของเอเจนต์ คุณปฏิบัติ AI Agents with LangChain & Autonomous Workflows ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents with LangChain & Autonomous Workflows หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents with LangChain & Autonomous Workflows บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “หน่วยความจำบัฟเฟอร์การสนทนา” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents with LangChain & Autonomous Workflows นี้ได้ไหม
ได้ บทเรียน AI Agents with LangChain & Autonomous Workflows ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- แนวคิดเรื่องหน่วยความจำของเอเจนต์
- หน่วยความจำบัฟเฟอร์การสนทนา
- โซลูชันหน่วยความจำขั้นสูง
- กลยุทธ์ความจำเกี่ยวกับเอนทิตีและสรุปความ