# Manage LLM Message History

```json metadata
{
  "title": "Manage LLM Message History",
  "description": "",
  "categories": null,
  "tableOfContents": {"sections":[{"id":"prerequisites","title":"Prerequisites"},{"id":"what-youll-learn","title":"What You'll Learn"},{"id":"managing-multiple-users-and-conversations","title":"Managing multiple users and conversations"},{"id":"semantic-message-history","title":"Semantic message history"},{"id":"conversation-control","title":"Conversation control"},{"id":"retrieving-message-counts","title":"Retrieving message counts"},{"id":"next-steps","title":"Next Steps"},{"id":"cleanup","title":"Cleanup"}]}

,
  "codeExamples": []
}
```

Large Language Models are inherently stateless with no knowledge of previous interactions. This becomes a challenge when engaging in long conversations that rely on context. The solution is to store and retrieve conversation history with each LLM call.

This guide demonstrates how to use Redis to structure, store, and retrieve conversational message history.

## Prerequisites

Before you begin, ensure you have:
- Installed RedisVL: `pip install redisvl`
- A running Redis instance ([Redis 8+](https://redis.io/downloads/) or [Redis Cloud](https://redis.io/cloud))

## What You'll Learn

By the end of this guide, you will be able to:
- Store and retrieve conversation messages with `MessageHistory`
- Manage multiple users and conversations with session tags
- Use `SemanticMessageHistory` for relevance-based context retrieval
- Prune incorrect or unwanted messages from conversation history


```python
from redisvl.extensions.message_history import MessageHistory

chat_history = MessageHistory(name='student tutor')
```

To align with common LLM APIs, Redis stores messages with `role` and `content` fields.
The supported roles are "system", "user" and "llm".

You can store messages one at a time or all at once.


```python
chat_history.add_message({"role":"system", "content":"You are a helpful geography tutor, giving simple and short answers to questions about European countries."})
chat_history.add_messages([
    {"role":"user", "content":"What is the capital of France?"},
    {"role":"llm", "content":"The capital is Paris."},
    {"role":"user", "content":"And what is the capital of Spain?"},
    {"role":"llm", "content":"The capital is Madrid."},
    {"role":"user", "content":"What is the population of Great Britain?"},
    {"role":"llm", "content":"As of 2023 the population of Great Britain is approximately 67 million people."},]
    )
```

At any point we can retrieve the recent history of the conversation. It will be ordered by entry time.


```python
context = chat_history.get_recent()
for message in context:
    print(message)
```

    {'role': 'llm', 'content': 'The capital is Paris.'}
    {'role': 'user', 'content': 'And what is the capital of Spain?'}
    {'role': 'llm', 'content': 'The capital is Madrid.'}
    {'role': 'user', 'content': 'What is the population of Great Britain?'}
    {'role': 'llm', 'content': 'As of 2023 the population of Great Britain is approximately 67 million people.'}


In many LLM flows, conversations progress through a series of prompt and response pairs. MessageHistory provides a `store()` convenience function to add these efficiently.


```python
prompt = "what is the size of England compared to Portugal?"
response = "England is larger in land area than Portal by about 15000 square miles."
chat_history.store(prompt, response)

context = chat_history.get_recent(top_k=6)
for message in context:
    print(message)
```

    {'role': 'user', 'content': 'And what is the capital of Spain?'}
    {'role': 'llm', 'content': 'The capital is Madrid.'}
    {'role': 'user', 'content': 'What is the population of Great Britain?'}
    {'role': 'llm', 'content': 'As of 2023 the population of Great Britain is approximately 67 million people.'}
    {'role': 'user', 'content': 'what is the size of England compared to Portugal?'}
    {'role': 'llm', 'content': 'England is larger in land area than Portal by about 15000 square miles.'}


## Managing multiple users and conversations

For applications that need to handle multiple conversations concurrently, Redis supports tagging messages to keep conversations separated.


```python
chat_history.add_message({"role":"system", "content":"You are a helpful algebra tutor, giving simple answers to math problems."}, session_tag='student two')
chat_history.add_messages([
    {"role":"user", "content":"What is the value of x in the equation 2x + 3 = 7?"},
    {"role":"llm", "content":"The value of x is 2."},
    {"role":"user", "content":"What is the value of y in the equation 3y - 5 = 7?"},
    {"role":"llm", "content":"The value of y is 4."}],
    session_tag='student two'
    )

for math_message in chat_history.get_recent(session_tag='student two'):
    print(math_message)
```

    {'role': 'system', 'content': 'You are a helpful algebra tutor, giving simple answers to math problems.'}
    {'role': 'user', 'content': 'What is the value of x in the equation 2x + 3 = 7?'}
    {'role': 'llm', 'content': 'The value of x is 2.'}
    {'role': 'user', 'content': 'What is the value of y in the equation 3y - 5 = 7?'}
    {'role': 'llm', 'content': 'The value of y is 4.'}


## Semantic message history
For longer conversations our list of messages keeps growing. Since LLMs are stateless we have to continue to pass this conversation history on each subsequent call to ensure the LLM has the correct context.

A typical flow looks like this:
```
while True:
    prompt = input('enter your next question')
    context = chat_history.get_recent()
    response = LLM_api_call(prompt=prompt, context=context)
    chat_history.store(prompt, response)
```

This works, but as context keeps growing so too does our LLM token count, which increases latency and cost.

Conversation histories can be truncated, but that can lead to losing relevant information that appeared early on.

A better solution is to pass only the relevant conversational context on each subsequent call.

For this, RedisVL has the `SemanticMessageHistory`, which uses vector similarity search to return only semantically relevant sections of the conversation.


```python
from redisvl.extensions.message_history import SemanticMessageHistory
semantic_history = SemanticMessageHistory(name='tutor')

semantic_history.add_messages(chat_history.get_recent(top_k=8))
```


```python
prompt = "what have I learned about the size of England?"
semantic_history.set_distance_threshold(0.35)
context = semantic_history.get_relevant(prompt)
for message in context:
    print(message)
```

    {'role': 'user', 'content': 'what is the size of England compared to Portugal?'}


You can adjust the degree of semantic similarity needed to be included in your context.

Setting a distance threshold close to 0.0 will require an exact semantic match, while a distance threshold of 2.0 will include everything (Redis COSINE distance range is [0-2]).


```python
semantic_history.set_distance_threshold(0.7)

larger_context = semantic_history.get_relevant(prompt)
for message in larger_context:
    print(message)
```

    {'role': 'user', 'content': 'what is the size of England compared to Portugal?'}
    {'role': 'llm', 'content': 'England is larger in land area than Portal by about 15000 square miles.'}
    {'role': 'user', 'content': 'What is the population of Great Britain?'}
    {'role': 'llm', 'content': 'As of 2023 the population of Great Britain is approximately 67 million people.'}
    {'role': 'user', 'content': 'And what is the capital of Spain?'}


## Conversation control

LLMs can hallucinate on occasion and when this happens it can be useful to prune incorrect information from conversational histories so this incorrect information doesn't continue to be passed as context.


```python
semantic_history.store(
    prompt="what is the smallest country in Europe?",
    response="Monaco is the smallest country in Europe at 0.78 square miles." # Incorrect. Vatican City is the smallest country in Europe
)

# get the key of the incorrect message
context = semantic_history.get_recent(top_k=1, raw=True)
bad_key = context[0]['entry_id']
semantic_history.drop(bad_key)

corrected_context = semantic_history.get_recent()
for message in corrected_context:
    print(message)
```

    {'role': 'user', 'content': 'What is the population of Great Britain?'}
    {'role': 'llm', 'content': 'As of 2023 the population of Great Britain is approximately 67 million people.'}
    {'role': 'user', 'content': 'what is the size of England compared to Portugal?'}
    {'role': 'llm', 'content': 'England is larger in land area than Portal by about 15000 square miles.'}
    {'role': 'user', 'content': 'what is the smallest country in Europe?'}


## Retrieving message counts

To get the total number of  messages stored in a session, use the `.count()` method.  
You can optionally pass a `session_tag` argument to retrieve the count for a different conversation session.


```python
print(f"Total messages in the session: {chat_history.count()}")
```

    Total messages in the session: 7


## Next Steps

Now that you understand message history management, explore these related guides:

- [Cache LLM Responses](03_llmcache.ipynb) - Reduce API costs with semantic caching
- [Route Queries with SemanticRouter](08_semantic_router.ipynb) - Classify user queries to routes
- [Create Embeddings with Vectorizers](04_vectorizers.ipynb) - Use different embedding providers

## Cleanup


```python
chat_history.clear()
semantic_history.clear()
```

