12. How to add a conversation history summary

Keeping a conversation record persistence One of the most common use cases. This has the advantage of making conversation easier to sustain.

But the longer the conversation, the more the conversation record accumulates context window Will take more. This is LLM Calls are more expensive and longer, and may potentially be undesirable as errors may occur. One way to solve this is to generate a summary of the conversation to date, and recently N It is used with dog messages.

In this guide, we will look at examples of how to implement this.

The following steps are required.

  • Make sure the conversation is too long (can be checked by number of messages or message length)

  • Create a summary if it's too long (requires prompt for it)

  • last N Delete the rest of the messages except the dog messages

An important part of this process is deleting old messages ( DeleteMessage ) Is doing.

Preferences

Copy

# Configuration file for managing API keys as environment variables
from dotenv import load_dotenv

# Load API key information
load_dotenv()

Copy

 True 

Copy

Copy

Summarize long conversations and save them as conversations

After creating a summary for a long conversation, delete the existing conversation and save the summary as a conversation.

Condition

  • Generate a summary if the length of the conversation exceeds 6

Copy

ask_llm Node messages Inject to llm to get an answer.

if, Summary of previous conversations If this exists, add it as a system message and include it in the conversation.

However, if the previous conversation summary does not exist, only the previous conversation content is used.

Copy

should_continue Nodes go to the summary node if the length of the conversation exceeds 6.

If not, it returns an immediate answer. ( END Go to node)

Copy

summarize_conversation The node summarizes the conversation and deletes the old message.

Copy

Copy

Visualize the graph.

Copy

Graph execution

Copy

Copy

Copy

So far, you can see that the summary hasn't been done at all-this is because there are only 6 messages in the list.

Copy

Copy

Now I'll send another message

Copy

Copy

Check the current status and you will see the last two messages with a summary of the conversation.

Copy

Copy

Copy

Copy

Now you can resume the conversation.

Even with the last two messages, you can ask about the previous conversation (because the previous one is summarized).

Copy

Copy

Copy

Copy

Last updated