How can I reduce the chat context to the last 3 tu...
# ask-ai
a
How can I reduce the chat context to the last 3 turns (6 messages) at every turn
t
Thanks for reaching out, Anthony. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To keep the chat context to just the last 3 turns (6 messages), you’ve got a couple of easy options! You can either use the
truncate
method from the
ChatContext
class or create your own custom truncation logic. Here’s how: 1. Using the
ChatContext.truncate
Method:
Copy code
# Truncate chat context to last 6 messages (3 turns)
chat_ctx.truncate(max_items=6)
This handy method takes care of removing extra stuff like partial function executions and keeps the first system message if you have one. 2. Custom Truncation Logic:
Copy code
def _truncate_chat_ctx(
    items: list,
    keep_last_n_messages: int = 6,
    keep_system_message: bool = False,
    keep_function_call: bool = False,
) -> list:
    """Custom truncation with filtering options"""
    def _valid_item(item) -> bool:
        if not keep_system_message and item.type == "message" and item.role == "system":
            return False
        if not keep_function_call and item.type in ["function_call", "function_call_output"]:
            return False
        return True

    new_items = []
    for item in reversed(items):
        if _valid_item(item):
            new_items.append(item)
        if len(new_items) >= keep_last_n_messages:
            break
    new_items = new_items[::-1]

    # Remove orphaned function calls at the beginning
    while new_items and new_items[0].type in ["function_call", "function_call_output"]:
        new_items.pop(0)

    return new_items
This way, you get more control — like deciding whether to keep system messages or function calls in the mix. If you want a hand setting this up or have any questions, just let me know. I’m here to help! Sources: complex-agents/role-playing/agents/base_agent.py | examples/voice_agents/fast-preresponse.py | VoicePipelineAgent | LiveKit Docs