12-04 更新 实时
首页/ 模型选型/ 正文

OpenAI API 下 AI 智能体记忆的截断与摘要

模型选型 来源:Towards Data Science 2026-12-03 20:00 1 阅读 机器翻译
OpenAI API 下 AI 智能体记忆的截断与摘要

之所以会这样,是因为模型每次调用时基本上是只根据当前这次请求从零开始生成回复。它不记得几条消息之前聊过什么,也不记得我们已经试过它现在建议的那个办法——对于被我们称作“助手”的东西来说,这有点遗憾 🫠。

这个问题可以通过引入记忆的概念来解决。我们常常把智能体的记忆说成是模型自带的一项功能,但实际上它更像是围绕模型搭建的一套系统,由它决定保留哪些信息、把信息存在哪里,以及何时把这些信息重新放回提示中。

我们可以区分短期记忆(记住一次对话中提到过的内容)和长期记忆(记住不同对话之间聊过的内容)。在接下来的文章中,我们还会探讨长期记忆是如何工作的,甚至会亲手搭建一个带记忆的智能体。但在今天这篇文章里,我只聚焦于短期记忆。

那么,我们来看看智能体为什么会遗忘、短期记忆如何运作,以及当对话变得太长时该怎么办——全程使用纯 Python 和 OpenAI API。

在开始之前,我们先更仔细地看看记忆这个问题。一个便于理解的简单例子是连续两次调用模型:第一次我们做自我介绍,第二次问模型它知道关于我们的哪些信息。为此,我会使用 openai Python 库,以及存放在 OPENAI_API_KEY 环境变量里的 API key。我打算用 gpt-4.1-mini,不过任何模型都可以。

from openai import OpenAI client = OpenAI() # 从环境变量读取 OPENAI_API_KEY MODEL = "gpt-4.1-mini" # 步骤 1:我介绍自己 response = client.responses.create( model=MODEL, input="你好!我叫 Maria,我住在雅典。", ) print(response.output_text) # 步骤 2:我已经介绍了自己,那我是谁? response = client.responses.create( model=MODEL, input="我叫什么名字?我住在哪里?", ) print(response.output_text)

这会打印类似下面的内容:

显然,第一个回复没问题,而第二个回复表明模型完全不知道第一个请求中说了什么 😝。更准确地说,这是因为 API 默认是无状态的,意味着每个请求都被视为一个全新的、独立的调用。换句话说,模型在对话中似乎“知道”的一切,都只是请求输入中包含的内容。

较新的模型 API,比如 OpenAI 的 Responses API,实际上可以帮你跟踪对话,只要我们传入像 previous_response_id 这样的参数。不过,为了理解其底层工作原理,我们暂时不使用它,而是自己处理历史记录。

记忆的概念通常可以通过在每次新请求中纳入适当的记忆(即来自先前请求和回复的信息)来构建。根据我们要求模型记住的信息是位于当前聊天内部还是外部,创建模型记忆有更简单或更复杂的方法。

短期记忆:消息列表

正如你可能已经猜到的,对话内的记忆实现其实相当简单;我们只需要在每次向模型发起的新请求中带上之前的消息,这样它就能“记住”我们已经聊过的内容。换句话说,我们只是把用户的每个新请求和模型的回复追加到 messages 里,并在每次新请求时一并发送回去。这就是我们所说的智能体短期记忆,也叫对话历史或工作记忆。

我们可以把这一逻辑封装成一个小函数,从而为我们最初的示例中的智能体赋予短期记忆。本质上,这个函数维护一个全局的 messages 列表,并把每条用户消息和每条回复追加进去:

messages = [ {"role": "system", "content": "You are a helpful assistant."}]def chat(user_message): # 第 1 步:把用户的消息加入历史记录 messages.append({"role": "user", "content": user_message}) # 第 2 步:把完整的消息历史发送给模型 response = client.responses.create(model=MODEL, input=messages) reply = response.output_text # 第 3 步:把模型的回复加入历史记录 messages.append({"role": "assistant", "content": reply}) return replyprint(chat("Hi! My name is Maria and I live in Athens."))print(chat("What is my name and where do I live?"))print(chat("Suggest one thing I could do this weekend."))

那么这一次,输出结果是这样的:

好多了;现在我们的智能体似乎知道我们在聊什么了。

关于短期记忆的工作方式,有一点需要注意:由于我们会迭代地把每个请求和每个回复追加到 messages 中,然后在每次新请求时再把这些内容发回去,最终 messages 列表会不断增长,导致对话中每条新消息的成本实际上都更高。换句话说,带着记忆进行对话意味着,实践中我们每次请求都要重新发送整段对话,使每一次新调用都更加昂贵。

可以想见,这让事情变得稍微复杂了一些。随着对话增长,我们不可避免地会在某个时刻触及模型的上下文窗口。不过,现实地说,拥有超大上下文窗口的新模型很难被触及,尤其是对于像“雅典天气怎么样?”这样的日常对话。

但无论如何,早在我们触及上下文窗口之前,请求就已经变得越来越昂贵、越来越慢,而且答案往往还更差,因为模型需要筛选的文本更多,可能会漏掉埋藏在中间部分的细节。

所以,另一件需要担心的事是:当对话变得过长时,我们应该做什么(如果有的话)。

基本上,对于变得过长的对话,我们有两件事可以做:

裁剪(trimming):也就是只保留对话中最后几条消息,丢弃其余部分,以及

摘要(summarization):也就是用模型自己写的简短摘要替换较早的消息,只逐字保留最近的消息

这两种方法的风险都在于:对话早期提到的某些重要内容,会在我们裁剪或摘要聊天记录时被移除,导致智能体“忘记”这一重要信息。

假设我们有以下消息历史的对话:

history = [ {"role": "system", "content": "你是一个乐于助人的助手。"}, {"role": "user", "content": "嗨!我叫 Maria,我住在雅典。"}, {"role": "assistant", "content": "很高兴认识你,Maria!我能帮什么忙?"}, {"role": "user", "content": "推荐一本关于数据可视化的书。"}, {"role": "assistant", "content": "Cole Nussbaumer Knaflic 的 Storytelling with Data 是一个很好的起点。"}, {"role": "user", "content": "那关于机器学习的播客呢?"}, {"role": "assistant", "content": "试试 Practical AI,它以平易近人的方式涵盖机器学习。"}, {"role": "user", "content": "谢谢!有什么保持学习一致性的建议吗?"}, {"role": "assistant", "content": "设定每日小目标,并构建一个你关心的项目。"},]

通过修剪,我们定义要保留的最近消息数量(max_messages),所有更早的消息都会被丢弃。

def trim_messages(messages, max_messages=3): system = messages[:1] recent = messages[1:][-max_messages:] return system + recenttrimmed = trim_messages(history)trimmed.append({"role": "user", "content": "顺便问一下,我叫什么名字?"})response = client.responses.create(model=MODEL, input=trimmed)print(response.output_text)

在对话历史中,我在第 1 条消息中提到了“我叫 Maria”,而现在我们处于第 9 条消息。由于我们设置了 max_messages=3,只保留历史中最后三条消息,因此第 1 条消息被丢弃,模型对我的名字一无所知。

所以,这就是修剪的问题:重要信息可能会被遗漏在聊天之外,而我们甚至永远不会知道。

这正是摘要机制试图改善的问题。更具体地说,在这里我们不是简单地丢弃部分消息,而是要求模型把它们压缩成几句话,并明确指示要保留关于用户的事实。随后,这份摘要不会作为普通消息保存,而是作为一条系统消息,后面紧跟最近的消息。

原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。

查看英文原文(AI Agent Memory Explained: Trimming vs. Summarization With the OpenAI API)

That happens because, for every call, the model essentially generates a reply from scratch, based only on the current request. It doesn't remember what was talked about a few messages before or the fact that we already tried the thing it is now suggesting, which is a bit unfortunate for something we call an assistant 🫠.

This issue can be resolved by introducing the concept of memory. We often refer to an agent's memory as though it is a feature of the model, but in reality it is more of a system that is built around the model and decides what information to keep, where to store it, and when to bring it back into the prompt.

We may draw a distinction between short-term memory (remembering what was mentioned within a conversation), and long-term memory (remembering what was talked about across different conversations). In the posts to come, we'll also be exploring how long-term memory works, and even building an agent with memory ourselves. But in today's post, I'm going to focus only on short-term memory.

So, let's see why agents forget, how short-term memory works, and what to do when a conversation gets too long, all with plain Python using the OpenAI API.

Before anything else, let's take a better look at the memory problem. An easy example for understanding this is making two consecutive calls to a model, where we are introducing ourselves in the first one, then asking what the model knows about us in the second one. To do this, I'll use the openai Python library and my API key stored in the OPENAI_API_KEY environment variable. I'll go with gpt-4.1-mini, but any model will do.

from openai import OpenAIclient = OpenAI() # reads OPENAI_API_KEY from the environmentMODEL = "gpt-4.1-mini"# step 1: I introduce myselfresponse = client.responses.create( model=MODEL, input="Hi! My name is Maria and I live in Athens.",)print(response.output_text)# step 2: I introduced myself, so who am I?response = client.responses.create( model=MODEL, input="What is my name and where do I live?",)print(response.output_text)

This prints something along these lines:

image.png

Apparently, the first reply is fine, and the second one shows that the model has no idea what was said in the first request 😝. To put it more correctly, this happens because the API is stateless by default, meaning that each request is treated as a brand new, independent call. In other words, whatever the model seems to "know" in a conversation is only what was included in the input of the request.

Newer model APIs, like OpenAI's Responses API, can actually keep track of the conversation for you, if we pass a parameter like previous_response_id. However, for the sake of understanding how this works under the hood, we won't use it for now and will handle the history ourselves.

The concept of memory can generally be created by including the appropriate memories (that would be information from previous requests and replies) in each new request. Depending on whether the information we need the model to remember lives inside or outside the current chat, there are simpler or more complex approaches for creating the model's memory.

Short-term memory: the messages list

As you may have suspected, the memory fix within a conversation is rather simple; we just have to include previous messages in each new request we are making to the model, so it "remembers" what we've already talked about. In other words, we just append each new request of the user and reply of the model to messages and send it back with each new request. And this is what we call an agent's short-term memory, also called conversation history or working memory.

We can wrap this logic into a small function, so as to give the agent of our initial example a short-term memory. Essentially, the function keeps a global messages list and appends each user message and each reply to it:

messages = [ {"role": "system", "content": "You are a helpful assistant."}]def chat(user_message): # Step 1: Add the user's message to the history messages.append({"role": "user", "content": user_message}) # Step 2: Send the ENTIRE history to the model response = client.responses.create(model=MODEL, input=messages) reply = response.output_text # Step 3: Add the model's reply to the history messages.append({"role": "assistant", "content": reply}) return replyprint(chat("Hi! My name is Maria and I live in Athens."))print(chat("What is my name and where do I live?"))print(chat("Suggest one thing I could do this weekend."))

So, this time the output looks like this:

A lot better; now our agent seems to know what we are talking about.

One thing to notice about how the short-term memory works is that since we are iteratively appending each request and each reply to messages, and then sending this back with each new request, we end up with an ever-growing messages list, resulting in each new message in a conversation essentially costing us more. In other words, having a conversation with memory means that in practice we are resending the entire conversation with each request, making each new call pricier.

As you may imagine, this complicates things a little bit. As the conversation grows, we are going to inevitably reach the model's context window at some point. Nonetheless, newer models with vast context windows are realistically very hard to reach, in particular for everyday conversations like "what's the weather in Athens?".

But in any case, long before reaching the context window, we end up with more and more expensive and slow requests, and often even worse answers, since the model has more text to sift through and can miss details buried in the middle.

so, another thing to worry about is what we should do (if anything) as a conversation gets too long.

Basically, there are two things we can do for a conversation that gets too long:

trimming: that is, keep only the last few messages of the conversation and drop the rest, and

summarization: that is, replace the older messages with a short summary written by the model itself, and keep only the most recent messages word for word

The risk with both of these approaches is having something important mentioned early on in the conversation, and then removing it as we trim or summarize the chat, resulting in the agent "forgetting" this important information.

Let's suppose we have a conversation with the following messages history:

history = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hi! My name is Maria and I live in Athens."}, {"role": "assistant", "content": "Nice to meet you, Maria! How can I help?"}, {"role": "user", "content": "Recommend a book about data visualization."}, {"role": "assistant", "content": "Storytelling with Data by Cole Nussbaumer Knaflic is a great start."}, {"role": "user", "content": "And a podcast about machine learning?"}, {"role": "assistant", "content": "Try Practical AI, it covers ML in an approachable way."}, {"role": "user", "content": "Thanks! Any tips for staying consistent with learning?"}, {"role": "assistant", "content": "Set small daily goals and build a project you care about."},]

With trimming, we define a number of recent messages to keep (max_messages), and everything older than that is dropped.

def trim_messages(messages, max_messages=3): system = messages[:1] recent = messages[1:][-max_messages:] return system + recenttrimmed = trim_messages(history)trimmed.append({"role": "user", "content": "By the way, what is my name?"})response = client.responses.create(model=MODEL, input=trimmed)print(response.output_text)

In the conversation history, I mention 'My name is Maria' in message number 1, and now we are at message number 9. Since we've set max_messages=3, only the last three messages of the history are kept, so message number 1 is dropped and the model has no clue about my name.

So, this is the issue with trimming: important info may be left out of the chat, and we'll never even know.

This is the exact issue summarization tries to improve on. More specifically, here, instead of just dropping some of the messages, we ask the model to compress them into a few sentences, with a specific instruction to hold on to facts about the user. This summary is then kept not as regular messages, but as a system message, followed by the recent messages.

def summarize_history(messages, keep_last=4): system, rest = messages[:1], messages[1:] if len(rest) <= keep_last: return messages # Step 1: Split into old messages (to summarize) and recent ones (to keep) old, recent = rest[:-keep_last], rest[-keep_last:] # Step 2: Ask the model to summarize the old part transcript = "\n".join(f"{m['role']}: {m['content']}" for m in old) summary = client.responses.create( model=MODEL, input="Summarize this conversation in a few sentences. " "Keep any facts about the user.\n\n" + transcript, ).output_text # Step 3: Rebuild the history with the summary in place of the old messages summary_message = {"role": "system", "content": f"Summary of earlier conversation: {summary}"} return system + [summary_message] + recentsummarized = summarize_history(history)summarized.append({"role": "user", "content": "By the way, what is my name?"})response = client.responses.create(model=MODEL, input=summarized)print(response.output_text)

And then we get the following reply:

Which is actually much better. Thanks to the summarization, no messages are completely dropped and the important information is preserved, while also not carrying over a huge, costly, and slow chat. Nonetheless, summarization is not free of trade-offs, as it costs an extra model call. Again, since the summary is itself written by a model, it can omit a detail or slightly distort one 🤷‍♀️.

On the one side, trimming is significantly cheaper (no extra model calls, we just drop the old messages) and works in a predictable, deterministic way; nonetheless, there will be significant information loss at some point. On the flip side, summarization seems to be smarter, but is costly, and again there may be some loss of information (that will be unpredictable and rather stochastic) since the summaries are generated by a model. As in all things, there is no one size fits all; choosing between trimming and summarizing chat history depends on your use case, how complex and lengthy conversations are expected to be, and how much a forgotten detail is going to cost.

In any case, both trimming and summarizing will get us as far as achieving the memory effect only within a single conversation, since both are based on preserving memory in the messages variable, which is tied to a specific session. Once this session ends, the messages list is gone, and so is everything in it. As a result, to achieve memory across different sessions, we need a different approach.

What I find interesting about short-term memory is how unmagical it is: the model never remembers anything, we just hand it the whole conversation again and again every time. Even when an API like OpenAI's Responses API keeps track of the conversation for us, it is doing the exact same thing in the background. Everything else, from trimming to summarizing, is simply a decision about what to keep in that list. But the list is gone once the session ends, so making an agent remember across sessions is a story for the next post.

✨ Thank you for reading! ✨

If you made it this far, you might find pialgorithms useful, a platform we've been building that helps teams securely manage organizational knowledge in one place.

Loved this post? Join me on 💌 Substack and 💼 LinkedIn

All images by the author, except where mentioned otherwise.

From 512 to 1M+ tokens in 5 years - LLMs have rapidly expanded their context windows. Where's the limit?

April 28, 202410 min read

Inside the research that shows algorithmic price-fixing isn't a bug in the code. It's a feature of the math.

February 24, 202610 min read

The bool on when NA is not False, False is False, and NA is not Null.

January 13, 20215 min read

Learn how to perform code refactoring with LLMs

January 20, 20269 min read

You will learn how to analyse your LinkedIn connection data using R, ggplot2, and dpylr.

March 2, 20215 min read

For the purpose of obfuscation, we will be using a python package called pyarmor

January 29, 20213 min read

One-hot encode, merge, and concatenate: say hello to useful data transformations and funky data combinations.

August 23, 202211 min read

Problems and solutions of linear regression with multiple treatments

June 13, 202211 min read

Learn how to effectively present product ideas by building MVPs with coding agents

April 8, 20267 min read

原文为英文,正文由自动抓取并保留原文。

本文由采集器自动同步

原文发布于 Towards Data Science(AI Agent Memory Explained: Trimming vs. Summarization With the OpenAI API),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。

阅读原文 ↗