โซลูชันหน่วยความจำขั้นสูง
สำรวจประเภทหน่วยความจำที่ซับซ้อนยิ่งขึ้น เช่น หน่วยความจำสรุปและหน่วยความจำเอนทิตี รวมถึงวิธีเก็บประวัติการสนทนาให้คงอยู่
โซลูชันหน่วยความจำขั้นสูง เป็นบทเรียน AI Agents with LangChain & Autonomous Workflows ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents with LangChain & Autonomous Workflows และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Deeper Agent Memory
In previous lessons, we learned about basic conversational memory. But what if conversations get very long or involve many specific details?
Advanced memory solutions help agents manage complex interactions by summarizing or tracking entities.
Introducing Summary Memory
Summary Memory condenses past conversations into a concise summary.
- It prevents context windows from overflowing.
- The agent still "remembers" the gist without storing every single message.
- Useful for long-running chats where initial details become less important.
Summary Memory in Action
LangChain's ConversationSummaryBufferMemory uses an LLM to create summaries. It keeps a buffer of recent messages, then summarizes older ones as needed.
Try this example:
from langchain.memory import ConversationSummaryBufferMemory
from langchain_openai import OpenAI
# For demonstration, we'll use a mock LLM
# In a real scenario, you'd use your actual LLM (e.g., OpenAI, HuggingFace)
# from langchain.llms import OpenAI
# llm = OpenAI(temperature=0)
class MockLLM:
def __init__(self):
pass
def invoke(self, prompt):
if "summarize" in prompt.lower():
return "A short summary of the conversation."
return "Mock LLM response to: " + prompt
llm = MockLLM()
# max_token_limit ensures summary happens before context window is full
memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=100)
def run_interaction(user_input, ai_output):
memory.save_context({"input": user_input}, {"output": ai_output})
print(f"Memory buffer: {memory.load_memory_variables({})['history']}")
if __name__ == "__main__":
print("--- Summary Buffer Memory Demo ---")
run_interaction("Hi there!", "Hello! How can I help?")
run_interaction("My name is Alice.", "Nice to meet you, Alice.")
run_interaction("I want to discuss project Alpha.", "Okay, tell me more.")
run_interaction("Project Alpha is about AI agents.", "Interesting! What aspects?")
# After more interactions, older messages would be summarized
print("\nFinal memory (after potential summarization):")
print(memory.load_memory_variables({})['history'])
Tracking Specific Entities
Entity Memory is designed to remember specific "entities" (like people, places, or topics) and facts about them throughout a conversation.
- It maintains a knowledge base of entities.
- Useful when an agent needs to recall specific details about named things.
- Example: "Alice likes coffee" -> agent remembers "Alice" and "likes coffee".
Using ConversationEntityMemory
ConversationEntityMemory uses an LLM to extract entities and their attributes from messages. It builds up a profile for each entity.
Let's see it work:
from langchain.memory import ConversationEntityMemory
from langchain_openai import OpenAI
# Using the same MockLLM for consistency
class MockLLM:
def __init__(self):
pass
def invoke(self, prompt):
if "extract entities" in prompt.lower():
if "Alice" in prompt:
return "{'Alice': 'Alice is a person. She likes coffee and project Alpha.'}"
return "{}"
if "summarize" in prompt.lower():
return "A short summary of the conversation."
return "Mock LLM response to: " + prompt
llm = MockLLM()
memory = ConversationEntityMemory(llm=llm)
def run_entity_interaction(user_input, ai_output):
memory.save_context({"input": user_input}, {"output": ai_output})
print(f"Entities: {memory.load_memory_variables({})['entities']}")
if __name__ == "__main__":
print("--- Entity Memory Demo ---")
run_entity_interaction("My name is Alice and I like coffee.", "Nice to meet you, Alice!")
run_entity_interaction("I am working on project Alpha.", "That sounds interesting.")
run_entity_interaction("My colleague Bob will join later.", "Okay, I'll remember Bob.")
print("\nFinal entities stored:")
print(memory.load_memory_variables({})['entities'])
Hybrid Memory Approaches
For even more robust agents, you can combine different memory types.
- Use Summary Memory for general conversation flow.
- Use Entity Memory to track specific facts about key subjects.
- This creates a rich, layered understanding without overwhelming the LLM's context window.
Remembering Across Sessions
By default, an agent's memory is lost when the program ends. But what if you want an agent to remember a user over days or weeks?
Persistent Memory allows you to save and load an agent's memory, enabling long-term conversations and continuity.
Saving & Loading Memory
A simple way to persist memory is to save its state to a file, like JSON. When the agent restarts, it can load this file to restore its memory.
This example shows how to serialize (save) and deserialize (load) memory:
import json
from langchain.memory import ConversationBufferMemory
# Example of a simple buffer memory
memory = ConversationBufferMemory()
if __name__ == "__main__":
print("--- Memory Persistence Demo ---")
# 1. Save context
memory.save_context({"input": "Hello!"}, {"output": "Hi there!"})
memory.save_context({"input": "How are you?"}, {"output": "I'm good!"})
# 2. Extract and save memory variables
memory_data = memory.load_memory_variables({})
print(f"Memory before saving: {memory_data}")
# Convert to JSON string and save to a file
with open("agent_memory.json", "w") as f:
json.dump(memory_data, f, indent=2)
print("\nMemory saved to agent_memory.json")
# 3. Create new memory and load from file
new_memory = ConversationBufferMemory()
with open("agent_memory.json", "r") as f:
loaded_data = json.load(f)
# For ConversationBufferMemory, you can set the buffer directly
# More complex memories might have specific load methods
new_memory.buffer = loaded_data.get('history', '')
print(f"\nMemory loaded into new agent: {new_memory.load_memory_variables({})['history']}")
Robust Persistence Options
For production-grade applications, simple file persistence isn't enough. Consider these options:
- Databases: SQL (SQLite, PostgreSQL) or NoSQL (MongoDB, Redis) for structured and scalable storage.
- Vector Stores: For persisting embeddings of conversational history, useful for more advanced retrieval.
- LangChain integrates with many databases for seamless memory persistence.
Memory Types Quiz
Which memory type would be best suited for an agent that needs to remember specific details about named clients (e.g., their preferences, project names) over a very long conversation?
Recap: Advanced Memory Solutions
Today, we explored advanced memory solutions for AI agents:
- Summary Memory: Condenses long conversations.
- Entity Memory: Tracks specific facts about named entities.
- Persistence: Saving and loading memory to maintain context across sessions, using files or databases.
These techniques help build more intelligent and context-aware agents!
คำถามที่พบบ่อย
บทเรียน “โซลูชันหน่วยความจำขั้นสูง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “โซลูชันหน่วยความจำขั้นสูง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ 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 ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “โซลูชันหน่วยความจำขั้นสูง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents with LangChain & Autonomous Workflows นี้ได้ไหม
ได้ บทเรียน AI Agents with LangChain & Autonomous Workflows ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- แนวคิดเรื่องหน่วยความจำของเอเจนต์
- หน่วยความจำบัฟเฟอร์การสนทนา
- โซลูชันหน่วยความจำขั้นสูง
- กลยุทธ์ความจำเกี่ยวกับเอนทิตีและสรุปความ