Share via


ChatHistoryAgentThread Class

A specialized AgentThread class that stores and manages ChatHistory for a ChatCompletionAgent. In addition to thread lifecycle, this class provides methods to add and clear conversation history, retrieve existing messages asynchronously, and optionally reduce or compress the conversation history if supported by the underlying ChatHistory.

Constructor

ChatHistoryAgentThread(
  chat_history: ChatHistory | None = None,
  thread_id: str | None = None
)

Parameters

Name Description
chat_history

The chat history to associate with this thread. If None, a new ChatHistory is used.

Default value: None
thread_id

The optional thread ID. A new one will be generated if None is provided.

Default value: None

Methods

__len__

Returns the length of the chat history.

_create

(Abstract override) Internal hook to start the thread and return its ID.

_delete

(Abstract override) Clears the chat history upon thread deletion.

_on_new_message

(Abstract override) Invoked when a new message is added to the thread. If the message doesn't already have a thread_id matching this instance, it is appended to the ChatHistory.

get_messages

Retrieve the entire conversation as an async iterable of ChatMessageContent.

reduce

Conditionally reduce the chat history if it is an instance supporting ChatHistoryReducer.

__len__

Returns the length of the chat history.

__len__() -> int

Returns

Type Description

The number of messages currently in the chat history.

_create

(Abstract override) Internal hook to start the thread and return its ID.

async _create() -> str

Returns

Type Description

The newly assigned thread ID.

_delete

(Abstract override) Clears the chat history upon thread deletion.

async _delete() -> None

_on_new_message

(Abstract override) Invoked when a new message is added to the thread. If the message doesn't already have a thread_id matching this instance, it is appended to the ChatHistory.

async _on_new_message(new_message: str | ChatMessageContent) -> None

Parameters

Name Description
new_message
Required

The newly contributed message or content snippet.

get_messages

Retrieve the entire conversation as an async iterable of ChatMessageContent.

async get_messages() -> AsyncIterable[ChatMessageContent]

Returns

Type Description

An async iterable of ChatMessageContent in chronological order.

reduce

Conditionally reduce the chat history if it is an instance supporting ChatHistoryReducer.

async reduce() -> ChatHistory | None

Returns

Type Description

The reduced ChatHistory or None if reduction was not applicable.

Attributes

_chat_history

The underlying ChatHistory instance managed by this thread.

_chat_history: ChatHistory

_thread_id

A unique identifier for the conversation thread.

_thread_id: str

_is_deleted

Indicates whether this thread is deleted/ended.

_is_deleted: bool