astonishing-gpu-67869
09/08/2025, 6:38 PMtall-airline-16756
09/08/2025, 6:38 PMtall-airline-16756
09/08/2025, 6:39 PMtruncate method from the ChatContext class or create your own custom truncation logic. Here’s how:
1. Using the ChatContext.truncate Method:
# 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:
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