Description
The TextNode class is an immutable data container that represents a single conversational message. Each instance stores the message's role, content, owner, token count, and creation date.
- Immutability: Defined with @dataclass(frozen=True), so its fields cannot be modified after creation.
- Conversation Element: Each TextNode encapsulates one message; a list of nodes forms the conversation history.
Attributes
| Attribute | Type | Description |
|---|---|---|
| role | str | Role of the message, typically "assistant" or "user". |
| content | str | The actual text content of the message. |
| owner | str | Name or identifier of the message owner (e.g., 'AI Bot', 'User'). |
| tokens | int | Token count for this message, useful for cost/length tracking. |
| date | str | Timestamp of when the message was created (e.g., '2025-01-01 09:15:00'). |
Example
Code
from chatweaver import TextNode
# Create a TextNode representing a user's message
user_message = TextNode(
role="user",
content="What's the weather like today?",
owner="Alice",
tokens=8,
date="2025-01-01 09:15:00"
)
# Print the node in a JSON-like string representation
print(str(user_message))
# {
# 'role': 'user',
# 'content': "What's the weather like today?",
# 'owner': 'Alice',
# 'tokens': 8,
# 'date': '2025-01-01 09:15:00'
# }
# Convert the TextNode to a dictionary for further processing
node_dict = dict(user_message)
print(node_dict["content"]) # "What's the weather like today?"