building a chatbot i want to provide some kind of history, so that the llm "remembers" what where the lasr talking points. Thought of using a dict with "user:" "llm:" pairs for each talking point. After some count, may be 80, the last 20 should be summarized to prevent so accumlate too much data for the context. The chatbot is run with ollama, if this is important. Any thoughts about that, any hints or tips, guidelines, ....?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To effectively manage conversation history for your chatbot using Ollama, here's a structured approach with practical implementation tips:
1. Data Structure for History
Use a list of dictionaries to store message pairs, including roles and content:
python
history = [
{"role": "user", "content": "What's the weather like?"},
{"role": "assistant", "content": "I can't check real-time weather, but I can describe typical patterns."},
# ... more interactions ...
]
2. Token Management
Track token usage: Use a tokenizer (e.g., tiktoken for OpenAI models or Ollama's /tokens endpoint) to estimate token counts.
Context limit: Know your model's maximum context length (e.g., Llama2-70B ≈ 4096 tokens).
Threshold for pruning: Start summarizing when remaining tokens < 20% of the limit.
python
def count_tokens(text):
# Example using tiktoken (adjust for your model)
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
return len(enc.encode(text))
total_tokens = sum(count_tokens(msg["content"]) for msg in history)
3. Dynamic Summarization Strategy
Trigger: When total_tokens exceeds a threshold (e.g., 3500 tokens for a 4k model).
Action: Summarize the oldest 20% of the conversation using Ollama itself.
Summarization Prompt Example
python
summary_prompt = {
"role": "system",
"content": "Summarize the following conversation excerpts into a concise 3-5 sentence summary. Focus on key topics, decisions, and unresolved questions."
}
# Extract oldest 20% of messages
summary_messages = history[1:int(len(history)*0.2)] # Skip system message
summary_content = "\n\n".join([f"{msg['role']}: {msg['content']}" for msg in summary_messages])
# Send to Ollama for summarization (pseudo-code)
summary_response = ollama.generate(model="llama2", prompt=summary_content, system=summary_prompt)
summary_text = summary_response["response"]
# Replace summarized messages with the summary
history = [history[0]] + [{"role": "system", "content": f"Summary of prior conversation: {summary_text}"}] + history[int(len(history)*0.2):]
4. System Message for Context
Include a persistent system message to remind the LLM to use summaries:
python
history.insert(0, {
"role": "system",
"content": "You are a chatbot with conversation history. Use the 'Summary of prior conversation' to maintain context for long-term continuity."
})
5. Optimization Tips
Prioritize recent messages: Never summarize the last 5-10 messages to retain immediate context.
Token-efficient formatting: Avoid redundant metadata in history (e.g., timestamps unless critical).
6. Edge Cases to Handle
Single long messages: Truncate or warn if a message exceeds 25% of the token limit.
Empty responses: Filter out invalid/no-content messages before adding to history.
Model-specific quirks: Test summarization prompts across different Ollama models.
Example Workflow
python
while True:
user_input = get_user_input()
history.append({"role": "user", "content": user_input})
# Generate response
response = ollama.generate(model="llama2", messages=history)
history.append({"role": "assistant", "content": response["response"]})
# Prune if over limit
total_tokens = sum(count_tokens(msg["content"]) for msg in history)
if total_tokens > 3500:
summarize_old_history()
Why This Works
Efficiency: Summarization reduces token usage while preserving long-term context.
Scalability: Adapts to varying conversation lengths and model limits.
Simplicity: Leverages Ollama’s strengths (no external APIs for summarization).
Test with shorter thresholds first (e.g., summarize at 500 tokens) to debug, then scale up. Monitor token usage and adjust thresholds based on your chatbot’s typical workload.