Implementation Steps:
a. Token Estimation:
For Ollama models, there isn't a universal Python tokenizer like tiktoken for OpenAI.
* Approximation: A simple character count divided by 4 or 5 is a very rough estimate. Word count is better.
* Better (but complex): Some models might have their own tokenizers available (e.g., transformers library for Llama models). You'd need to load the specific tokenizer for your Ollama model.
* Practical: Start with word count. If you run into context_window_exceeded errors from Ollama, reduce your threshold.
b. Summarization Logic:
import json # For Ollama API calls
MAX_CONTEXT_TOKENS = 4096 # Adjust based on your Ollama model (e.g., Llama 2 7B is typically 4096)
SUMMARIZE_THRESHOLD = 0.75 # Summarize when context reaches 75% of max
SUMMARIZE_CHUNK_SIZE = 10 # Number of *messages* (not turns) to consider for summarization
conversation_history = [
{"role": "system", "content": "You are a helpful AI assistant. Keep responses concise."}
]
summary_history = [] # To store the running summary
def count_tokens(messages):
# A very rough approximation for local models.
# For better accuracy, use a proper tokenizer if available for your model.
return sum(len(msg['content'].split()) for msg in messages) # Count words
def get_current_context():
# Combine system, summary, and recent messages
context_messages = []
if summary_history:
context_messages.append({"role": "system", "content": "Previously, we discussed: " + summary_history[0]})
context_messages.extend(conversation_history)
return context_messages
async def generate_summary(ollama_client, messages_to_summarize):
summary_prompt = [
{"role": "system", "content": "Summarize the following conversation for future context. Be concise and capture key topics, decisions, and any outstanding questions. Do not add new information."},
{"role": "user", "content": json.dumps(messages_to_summarize)} # Send messages as a string
]
try:
# Using Ollama's Chat API
response = await ollama_client.chat(model='your_summarizer_model_name', messages=summary_prompt, stream=False)
return response['message']['content']
except Exception as e:
print(f"Error summarizing: {e}")
return "Unable to generate summary." # Fallback
async def manage_history_and_get_response(ollama_client, user_message):
global conversation_history, summary_history
conversation_history.append({"role": "user", "content": user_message})
# Check token count and summarize if necessary
current_token_count = count_tokens(get_current_context())
if current_token_count > MAX_CONTEXT_TOKENS * SUMMARIZE_THRESHOLD:
print("--- Context nearing limit. Initiating summarization. ---")
# Identify which parts to summarize. Let's summarize the oldest N user/assistant pairs.
# Skip initial system message and any existing summary
messages_to_process = list(conversation_history) # copy
if len(messages_to_process) > SUMMARIZE_CHUNK_SIZE:
# Take the oldest N messages for summarization (e.g., from index 1 after system)
# Ensure we don't try to summarize the most recent turn or system message
oldest_messages_for_summary = messages_to_process[1:SUMMARIZE_CHUNK_SIZE + 1] # Skip initial system msg
# Get the summary
new_summary_text = await generate_summary(ollama_client, oldest_messages_for_summary)
# Update summary history (could append to a list of summaries or replace a single one)
if not summary_history:
summary_history.append(new_summary_text)
else:
# You might want to summarize the *new_summary_text* with the *old_summary_history[0]*
# for a cumulative summary. For simplicity here, just replace.
summary_history[0] = new_summary_text
# Remove the summarized messages from conversation_history
# Keep the original system message, then add new summary, then remaining conversation history
conversation_history = [conversation_history[0]] + conversation_history[SUMMARIZE_CHUNK_SIZE + 1:]
print(f"--- Summarized {len(oldest_messages_for_summary)} messages. New history length: {len(conversation_history)} ---")
else:
print("--- Not enough history to summarize effectively. ---")
# Prepare messages for the LLM
final_context = get_current_context()
# Send to Ollama
try:
response = await ollama_client.chat(model='your_main_chat_model_name', messages=final_context, stream=False)
assistant_response = response['message']['content']
conversation_history.append({"role": "assistant", "content": assistant_response})
return assistant_response
except Exception as e:
print(f"Error calling Ollama: {e}")
return "I apologize, but I encountered an error."
# Example usage (needs an async loop and Ollama client setup)
# import ollama
# client = ollama.AsyncClient(host='http://localhost:11434')
# async def main():
# while True:
# user_input = input("You: ")
# if user_input.lower() == 'exit':
# break
# response = await manage_history_and_get_response(client, user_input)
# print(f"Bot: {response}")
# asyncio.run(main())