0Pricing
Prompt Engineering & LLM Optimization for Developers · 课时

智能体的记忆与状态管理

为 LLM 智能体实现持久化记忆和状态管理技术,以支持长期对话和复杂的任务序列。

智能体的记忆与状态管理 是 CoddyKit 上的免费 Prompt Engineering & LLM Optimization for Developers 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Prompt Engineering & LLM Optimization for Developers 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Prompt Engineering & LLM Optimization for Developers 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Agents Need Memory

LLM agents are designed to perform complex tasks. But by default, LLMs are stateless! This means they don't "remember" past interactions.

For an agent to have a meaningful conversation or complete multi-step tasks, it needs a way to recall previous information. This is where memory comes in.

Short & Long-Term Memory

Agent memory can be categorized into two main types:

  • Short-Term Memory: This is like a human's working memory. It holds recent, relevant information for immediate use, often the raw conversation history.
  • Long-Term Memory: Stores information over extended periods, like past conversations or learned facts. It helps agents retain knowledge beyond the current interaction.

Conversational Buffer Memory

The simplest form of short-term memory for an agent is a conversational buffer. It stores the raw exchange of messages between the user and the agent.

When generating a new response, the agent is prompted with the entire buffer, allowing it to maintain context for the current turn.

Basic Chat Buffer Demo

Here's a simple Python example simulating a conversational buffer. Each new message is added to a list that represents the agent's memory.

class AgentMemory:
    def __init__(self):
        self.history = []

    def add_message(self, role, content):
        self.history.append(f"{role}: {content}")

    def get_history(self):
        return "\n".join(self.history)

# Simulate agent interaction
memory = AgentMemory()
memory.add_message("User", "Hi, what's the weather like?")
memory.add_message("Agent", "It's sunny today.")
memory.add_message("User", "What about tomorrow?")

print("Current conversation history:")
print(memory.get_history())

Summarizing for Long-Term

Raw conversation buffers grow quickly, hitting LLM context window limits and increasing costs. Summarization is a key technique for long-term memory.

Instead of sending the full history, we periodically summarize older parts of the conversation, keeping the key points while discarding verbose details.

Summarized Memory Concept

This example shows how a summary might be generated and used. In a real application, an LLM would create the summary, but here we simulate it.

class AgentMemory:
    def __init__(self):
        self.buffer = []
        self.summary = "No previous conversation."

    def add_message(self, role, content):
        self.buffer.append(f"{role}: {content}")
        # In a real app, trigger LLM summarization here
        if len(self.buffer) > 4: # Example threshold
            self.summarize_buffer()

    def summarize_buffer(self):
        # Simulate LLM summarizing the buffer
        old_messages = "\n".join(self.buffer[:-2])
        new_summary = f"Summary of past: {old_messages[:30]}..."
        self.summary = new_summary
        self.buffer = self.buffer[-2:] # Keep recent messages

    def get_full_context(self):
        return f"Previous summary: {self.summary}\n" + \
               "\n".join(self.buffer)

memory = AgentMemory()
memory.add_message("User", "Tell me about your capabilities.")
memory.add_message("Agent", "I can answer questions.")
memory.add_message("User", "Can you write code?")
memory.add_message("Agent", "Yes, in Python.")
memory.add_message("User", "What about Java?") # This triggers summary
memory.add_message("Agent", "I can try some Java.")

print("Agent's current context:")
print(memory.get_full_context())

Agent Task State

Beyond just remembering conversation, agents need to manage state to complete multi-step tasks. This means tracking progress, decisions made, and information collected.

Think of it like a checklist or a finite state machine for the agent's goal. For example, booking a flight requires knowing source, destination, and dates.

Flight Booking State Example

Consider an agent helping book a flight. Its internal state might include:

  • Status: "collecting_info", "searching_flights", "booking_confirmed"
  • Departure City: "London"
  • Destination City: "Paris"
  • Departure Date: "2024-12-25"
  • Number of Passengers: "1"

The agent updates this state as it gathers information from the user.

Memory & State Challenges

Managing agent memory and state introduces several key challenges:

  • Context Window Limits: How much information can the LLM process at once?
  • Cost: Longer contexts mean more tokens and higher API costs.
  • Retrieval: For very long-term memory (e.g., a knowledge base), how does the agent efficiently find the most relevant past information?
  • Consistency: Ensuring the agent's state accurately reflects the task's progress and collected data.

Memory Check

Let's check your understanding of agent memory and state management techniques.

Recap: Memory & State

In this lesson, we explored how memory and state are essential for LLM agents to engage in long-term conversations and complete complex tasks.

  • We covered short-term conversational buffers and long-term summarization techniques.
  • We also looked at how state management helps agents track progress through multi-step processes.

These techniques are fundamental for building truly capable and persistent AI agents.

常见问题解答

「智能体的记忆与状态管理」课时是免费的吗?

是的 — 「智能体的记忆与状态管理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Prompt Engineering & LLM Optimization for Developers 课程的其余内容,请升级到 CoddyKit PRO。 Prompt Engineering & LLM Optimization for Developers 课程共包含 4 节课。

「智能体的记忆与状态管理」这节课中我会学到什么?

为 LLM 智能体实现持久化记忆和状态管理技术,以支持长期对话和复杂的任务序列。 你通过在浏览器中直接运行的动手代码来练习 Prompt Engineering & LLM Optimization for Developers,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Prompt Engineering & LLM Optimization for Developers 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Prompt Engineering & LLM Optimization for Developers 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「智能体的记忆与状态管理」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Prompt Engineering & LLM Optimization for Developers 课中编写并运行代码吗?

能。每节 Prompt Engineering & LLM Optimization for Developers 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设计多智能体系统
  2. 智能体的记忆与状态管理
  3. 自主工作流自动化
  4. 智能体反思与自我纠正循环
← 返回 Prompt Engineering & LLM Optimization for Developers