API Reference
This page contains the complete API reference for the chat-object library.
Core Classes
Chat
- class chat_object.chat_obj.Chat(*messages: Message | dict[Literal['role', 'content'], str] | dict[str, str])[source]
Bases:
objectA chat object containing a list of messages.
Examples
>>> from chat_object import Chat, Message, Role >>> chat = Chat() >>> len(chat) 0
>>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi there!") >>> chat = Chat(msg1, msg2) >>> len(chat) 2 >>> chat[0].content 'Hello' >>> chat[1].content 'Hi there!'
>>> # List-like operations for backward compatibility >>> chat.append({"role": "user", "content": "How are you?"}) >>> len(chat) 3 >>> chat[2]["content"] 'How are you?'
>>> # Dict-like access to messages >>> for msg in chat: ... print(f"{msg['role']}: {msg['content']}") user: Hello assistant: Hi there! user: How are you?
>>> # List operations >>> chat.pop() Message(role='user', content='How are you?') >>> len(chat) 2
- __init__(*messages: Message | dict[Literal['role', 'content'], str] | dict[str, str])[source]
Creates a chat object.
- Parameters:
*messages (MessageType) – The list of messages in the chat.
Examples
>>> from chat_object import Chat, Message, Role >>> chat = Chat() >>> len(chat) 0
>>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi!") >>> chat = Chat(msg1, msg2) >>> len(chat) 2
>>> # Test with dictionary messages >>> chat2 = Chat({"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi!"}) >>> len(chat2) 2 >>> chat2[0].role 'user'
- property messages: tuple[Message, ...]
Returns the list of messages in the chat.
Examples
>>> from chat_object import Chat, Message, Role >>> msg = Message(Role.User, "Hello") >>> chat = Chat(msg) >>> chat.messages (Message(role='user', content='Hello'),) >>> len(chat.messages) 1
- _validate_message(message: Message | dict[Literal['role', 'content'], str] | dict[str, str]) Message[source]
>>> from chat_object import Chat, Message, Role >>> chat = Chat() >>> msg = chat._validate_message(Message(Role.User, "Hello")) >>> isinstance(msg, Message) True >>> msg.role 'user'
>>> msg2 = chat._validate_message({"role": "assistant", "content": "Hi!"}) >>> isinstance(msg2, Message) True >>> msg2.role 'assistant'
- add(message: Message | dict[Literal['role', 'content'], str] | dict[str, str]) None[source]
Adds a single message to the chat.
- Parameters:
message (MessageType) – Message to add.
Examples
>>> from chat_object import Chat, Message, Role >>> chat = Chat() >>> chat.add(Message(Role.User, "Hello")) >>> len(chat) 1 >>> chat[0].content 'Hello'
>>> chat.add({"role": "assistant", "content": "Hi!"}) >>> len(chat) 2 >>> chat[1].content 'Hi!'
- get_messages() list[Message][source]
Returns the list of messages in the chat.
Examples
>>> from chat_object import Chat, Message, Role >>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi!") >>> chat = Chat(msg1, msg2) >>> messages = chat.get_messages() >>> len(messages) 2 >>> messages[0].role 'user' >>> messages[1].role 'assistant'
- extend(messages: Iterable[Message | dict[Literal['role', 'content'], str] | dict[str, str]]) None[source]
Extends the chat with multiple messages.
- Parameters:
messages (list[MessageType]) – List of messages to add.
Examples
>>> from chat_object import Chat, Message, Role >>> chat = Chat() >>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi!") >>> chat.extend([msg1, msg2]) >>> len(chat) 2
>>> chat.extend([{"role": "user", "content": "How are you?"}]) >>> len(chat) 3 >>> chat[2].content 'How are you?'
- clear() None[source]
Removes all messages from the chat.
Examples
>>> from chat_object import Chat, Message, Role >>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi!") >>> chat = Chat(msg1, msg2) >>> len(chat) 2 >>> chat.clear() >>> len(chat) 0 >>> chat.messages ()
- as_dict() list[dict[str, str]][source]
Returns a list of dictionaries representing the messages in the chat. Role values are already strings, so no conversion is needed.
Examples
>>> from chat_object import Chat, Message, Role >>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi!") >>> chat = Chat(msg1, msg2) >>> chat.as_dict() [{'role': 'user', 'content': 'Hello'}, {'role': 'assistant', 'content': 'Hi!'}]
- append(message: Message | dict[Literal['role', 'content'], str] | dict[str, str]) None[source]
List-like append method.
Examples
>>> from chat_object import Chat, Message, Role >>> chat = Chat() >>> chat.append(Message(Role.User, "Hello")) >>> len(chat) 1 >>> chat.append({"role": "assistant", "content": "Hi!"}) >>> len(chat) 2
- insert(index: int, message: Message | dict[Literal['role', 'content'], str] | dict[str, str]) None[source]
List-like insert method.
Examples
>>> from chat_object import Chat, Message, Role >>> chat = Chat(Message(Role.User, "Hello")) >>> chat.insert(0, Message(Role.System, "You are helpful")) >>> len(chat) 2 >>> chat[0].role 'system'
- pop(index: int = -1) Message[source]
List-like pop method.
Examples
>>> from chat_object import Chat, Message, Role >>> chat = Chat(Message(Role.User, "Hello"), Message(Role.Assistant, "Hi!")) >>> msg = chat.pop() >>> msg.role 'assistant' >>> len(chat) 1
- remove(message: Message | dict[Literal['role', 'content'], str] | dict[str, str]) None[source]
List-like remove method.
Examples
>>> from chat_object import Chat, Message, Role >>> msg = Message(Role.User, "Hello") >>> chat = Chat(msg, Message(Role.Assistant, "Hi!")) >>> chat.remove(msg) >>> len(chat) 1 >>> chat[0].role 'assistant'
- index(message: Message | dict[Literal['role', 'content'], str] | dict[str, str]) int[source]
List-like index method.
Examples
>>> from chat_object import Chat, Message, Role >>> msg = Message(Role.User, "Hello") >>> chat = Chat(msg, Message(Role.Assistant, "Hi!")) >>> chat.index(msg) 0
- count(message: Message | dict[Literal['role', 'content'], str] | dict[str, str]) int[source]
List-like count method.
Examples
>>> from chat_object import Chat, Message, Role >>> msg = Message(Role.User, "Hello") >>> chat = Chat(msg, msg, Message(Role.Assistant, "Hi!")) >>> chat.count(msg) 2
- reverse() None[source]
List-like reverse method.
Examples
>>> from chat_object import Chat, Message, Role >>> chat = Chat(Message(Role.User, "Hello"), Message(Role.Assistant, "Hi!")) >>> chat.reverse() >>> chat[0].role 'assistant'
- sort(key: ~typing.Callable[[~chat_object.message.Message], ~typing.Any] = <function Chat.<lambda>>, reverse: bool = False) None[source]
List-like sort method.
Examples
>>> from chat_object import Chat, Message, Role >>> chat = Chat(Message(Role.Assistant, "Hi!"), Message(Role.User, "Hello")) >>> chat.sort(key=lambda msg: msg.role) >>> chat[0].role 'assistant'
- __contains__(string: str) bool[source]
>>> from chat_object import Chat, Message, Role >>> "Hello" in Chat(Message(Role.Assistant, "Hello World!")) True >>> "Goodbye" in Chat(Message(Role.Assistant, "Hello World!")) False
- __str__() str[source]
>>> from chat_object import Chat, Message, Role >>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi there!") >>> chat = Chat(msg1, msg2) >>> str(chat) 'user: Hello\nassistant: Hi there!'
- __repr__() str[source]
>>> from chat_object import Chat, Message, Role >>> msg = Message(Role.User, "Hello") >>> chat = Chat(msg) >>> repr(chat) "Chat(messages=Message(role='user', content='Hello'))"
>>> chat2 = Chat() >>> repr(chat2) 'Chat(messages=[])'
- __eq__(other: object) bool[source]
>>> from chat_object import Chat, Message, Role >>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi!") >>> chat1 = Chat(msg1, msg2) >>> chat2 = Chat(msg1, msg2) >>> chat3 = Chat(msg2, msg1)
>>> chat1 == chat2 True >>> chat1 == chat3 False
- __hash__() int[source]
>>> from chat_object import Chat, Message, Role >>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi!") >>> chat1 = Chat(msg1, msg2) >>> chat2 = Chat(msg1, msg2) >>> hash(chat1) == hash(chat2) True
- __len__() int[source]
>>> from chat_object import Chat, Message, Role >>> chat = Chat() >>> len(chat) 0
>>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi!") >>> chat = Chat(msg1, msg2) >>> len(chat) 2
- __getitem__(index: int) Message[source]
>>> from chat_object import Chat, Message, Role >>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.Assistant, "Hi!") >>> chat = Chat(msg1, msg2) >>> chat[0].content 'Hello' >>> chat[1].content 'Hi!' >>> chat[0].role 'user'
- __setitem__(index: int, message: Message | dict[Literal['role', 'content'], str] | dict[str, str]) None[source]
>>> from chat_object import Chat, Message, Role >>> chat = Chat(Message(Role.User, "Hello")) >>> chat[0] = Message(Role.Assistant, "Hi!") >>> chat[0].role 'assistant'
Message
- class chat_object.message.Message(role: Role | str | Literal['system', 'user', 'assistant', 'tool', 'function'], content: str | Prompt)[source]
Bases:
objectA message object containing a role and content.
- Variables:
role (RoleType) – The role of the message (user, assistant, system, etc.).
content (str) – The content/body of the message.
Examples
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello, world!") >>> msg.role 'user' >>> msg.content 'Hello, world!'
>>> msg2 = Message("assistant", "Hi there!") >>> msg2.role 'assistant' >>> msg2.content 'Hi there!'
>>> # Dict-like access for backward compatibility >>> msg["role"] 'user' >>> msg["content"] 'Hello, world!' >>> msg.get("role") 'user' >>> msg.get("nonexistent", "default") 'default' >>> list(msg.keys()) ['role', 'content'] >>> list(msg.values()) ['user', 'Hello, world!'] >>> list(msg.items()) [('role', 'user'), ('content', 'Hello, world!')]
- __init__(role: Role | str | Literal['system', 'user', 'assistant', 'tool', 'function'], content: str | Prompt)[source]
Initialize a message with role and content.
- Parameters:
role (RoleType) – The role of the message.
content (str) – The content of the message.
Examples
>>> from chat_object import Message, Role >>> msg = Message(Role.System, "You are a helpful assistant.") >>> msg.role == Role.System True >>> msg.content == "You are a helpful assistant." True
>>> msg2 = Message("user", "What's the weather like?") >>> msg2.role == "user" True
- as_dict() dict[str, str][source]
Returns a dictionary representation of the message.
Examples
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello") >>> msg.as_dict() {'role': 'user', 'content': 'Hello'}
- __getitem__(key: str) str[source]
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello") >>> msg["role"] 'user' >>> msg["content"] 'Hello'
- __setitem__(key: str, value: str) None[source]
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello") >>> msg["content"] = "Goodbye" >>> msg.content 'Goodbye' >>> msg["role"] = Role.Assistant >>> msg.role 'assistant'
- get(key: str, default: str | None = None) str | None[source]
Dict-like get method with default value.
Examples
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello") >>> msg.get("role") 'user' >>> msg.get("nonexistent", "default") 'default'
- keys() tuple[str, str][source]
Dict-like keys method.
Examples
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello") >>> list(msg.keys()) ['role', 'content']
- values() tuple[str, str][source]
Dict-like values method.
Examples
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello") >>> list(msg.values()) ['user', 'Hello']
- items() list[tuple[str, str]][source]
Dict-like items method.
Examples
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello") >>> list(msg.items()) [('role', 'user'), ('content', 'Hello')]
- update(other: dict[str, str]) None[source]
Dict-like update method.
Examples
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello") >>> msg.update({"content": "Goodbye"}) >>> msg.content 'Goodbye'
- copy() Message[source]
Dict-like copy method.
Examples
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello") >>> msg_copy = msg.copy() >>> msg_copy is not msg True >>> msg_copy.role == msg.role True >>> msg_copy.content == msg.content True
- __str__() str[source]
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello!") >>> str(msg) 'user: Hello!'
- __contains__(item: str) bool[source]
>>> from chat_object import Message, Role >>> msg = Message(Role.User, "Hello World!") >>> "Hello" in msg True >>> "Goodbye" in msg False
- __repr__() str[source]
>>> from chat_object import Message, Role >>> msg = Message(Role.System, "You are helpful.") >>> repr(msg) "Message(role='system', content='You are helpful.')"
- __eq__(other: object) bool[source]
>>> from chat_object import Message, Role >>> msg1 = Message(Role.User, "Hello") >>> msg2 = Message(Role.User, "Hello") >>> msg3 = Message(Role.Assistant, "Hello")
>>> msg1 == msg2 True >>> msg1 == msg3 False
Role
- class chat_object.role.Role(*values)[source]
-
Enumeration of most common message roles.
Examples
>>> from chat_object import Role >>> Role.System 'system' >>> Role.User 'user' >>> Role.Assistant 'assistant' >>> Role.Tool 'tool' >>> Role.Function 'function'
>>> # String comparison works >>> Role.User == "user" True >>> Role.Assistant == "assistant" True
>>> # Can be used in Message objects >>> from chat_object import Message >>> msg = Message(Role.System, "You are helpful") >>> msg.role 'system'
>>> # Sorting works >>> sorted([Role.Assistant, Role.User, Role.System]) ['assistant', 'system', 'user']
>>> # String operations work directly >>> Role.User + " message" 'user message' >>> "Hello " + Role.Assistant 'Hello assistant' >>> Role.System in "system prompt" True
- System = 'system'
- User = 'user'
- Assistant = 'assistant'
- Tool = 'tool'
- Function = 'function'
Prompt
- class chat_object.prompt.Prompt(*prompt: str)[source]
Bases:
objectA class for creating prompts for chat models.
Primarily intended to be used with triple-quoted strings. The class will automatically strip the string and remove common leading whitespace from each line while preserving relative indentation.
- Variables:
content (str) – The processed prompt content with normalized indentation.
Examples
>>> prompt = Prompt(""" ... Hello ... World ... This is a test ... """) >>> print(prompt) Hello World This is a test
>>> # Multiple arguments are joined with newlines >>> prompt = Prompt("First line", "Second line", "Third line") >>> print(prompt) First line Second line Third line
>>> # Empty prompt >>> empty = Prompt("") >>> str(empty) ''
>>> # Single line >>> single = Prompt("Hello World") >>> str(single) 'Hello World'
>>> # Prompt with only whitespace >>> whitespace = Prompt(" \n \n ") >>> str(whitespace) ''
- __init__(*prompt: str)[source]
Initialize a Prompt with one or more strings.
- Parameters:
*prompt (str) – One or more strings to create the prompt from. Multiple strings will be joined with newlines.
Examples
>>> p = Prompt("Hello") >>> p.content 'Hello'
>>> p2 = Prompt("Line 1", "Line 2") >>> p2.content 'Line 1\nLine 2'
>>> # Handling indented text >>> p3 = Prompt(""" ... def function(): ... return "hello" ... ... print("world") ... """) >>> print(p3) def function(): return "hello" print("world")
- _process_text(text: str) str[source]
Process text to remove common leading whitespace while preserving relative indentation.
- Parameters:
text (str) – Raw text input.
- Returns:
Processed text with normalized indentation.
- Return type:
Examples
>>> p = Prompt("") >>> p._process_text(" Hello\n World") 'Hello\n World'
>>> p._process_text("\n Line 1\n Line 2\n ") 'Line 1\n Line 2'
>>> p._process_text(" ") ''
- append(text: str) None[source]
Append text to the existing prompt content.
- Parameters:
text (str) – Text to append.
Examples
>>> p = Prompt("Hello") >>> p.append("World") >>> str(p) 'Hello\nWorld'
>>> p.append("") >>> str(p) 'Hello\nWorld\n'
- prepend(text: str) None[source]
Prepend text to the existing prompt content.
- Parameters:
text (str) – Text to prepend.
Examples
>>> p = Prompt("World") >>> p.prepend("Hello") >>> str(p) 'Hello\nWorld'
- clear() None[source]
Clear the prompt content.
Examples
>>> p = Prompt("Some content") >>> p.clear() >>> str(p) ''
- replace(old: str, new: str) Prompt[source]
Return a new Prompt with all occurrences of old replaced with new.
- Parameters:
- Returns:
New Prompt instance with replacements made.
- Return type:
Examples
>>> p = Prompt("Hello World") >>> p2 = p.replace("World", "Universe") >>> str(p2) 'Hello Universe' >>> str(p) # Original unchanged 'Hello World'
- copy() Prompt[source]
Create a copy of the prompt.
- Returns:
A new Prompt instance with the same content.
- Return type:
Examples
>>> p1 = Prompt("Hello") >>> p2 = p1.copy() >>> p2 is p1 False >>> str(p1) == str(p2) True
- strip() Prompt[source]
Return a new Prompt with leading and trailing whitespace removed.
- Returns:
New Prompt instance with stripped content.
- Return type:
Examples
>>> p = Prompt(" Hello World ") >>> p2 = p.strip() >>> str(p2) 'Hello World'
- __str__() str[source]
Return the string representation of the prompt content.
- Returns:
The processed prompt content.
- Return type:
Examples
>>> p = Prompt("Hello") >>> str(p) 'Hello'
- __repr__() str[source]
Return the official string representation of the Prompt.
- Returns:
String representation showing the constructor call.
- Return type:
Examples
>>> p = Prompt("Hello") >>> repr(p) "Prompt('Hello')"
>>> p2 = Prompt("") >>> repr(p2) "Prompt('')"
- __eq__(other: object) bool[source]
Check equality with another Prompt or string.
- Parameters:
other – Object to compare with.
- Returns:
True if contents are equal, False otherwise.
- Return type:
Examples
>>> p1 = Prompt("Hello") >>> p2 = Prompt("Hello") >>> p1 == p2 True
>>> p1 == "Hello" True
>>> p1 == "World" False
- __len__() int[source]
Return the length of the prompt content.
- Returns:
Number of characters in the content.
- Return type:
Examples
>>> p = Prompt("Hello") >>> len(p) 5
>>> p2 = Prompt("") >>> len(p2) 0
- __bool__() bool[source]
Return True if the prompt has content, False otherwise.
- Returns:
True if content is not empty, False otherwise.
- Return type:
Examples
>>> p = Prompt("Hello") >>> bool(p) True
>>> p2 = Prompt("") >>> bool(p2) False
- __contains__(item: str) bool[source]
Check if the prompt content contains the specified string.
- Parameters:
item (str) – String to search for.
- Returns:
True if item is found in content, False otherwise.
- Return type:
Examples
>>> p = Prompt("Hello World") >>> "Hello" in p True
>>> "xyz" in p False
- __add__(other: Prompt | str) Prompt[source]
Concatenate this prompt with another prompt or string.
- Parameters:
other (Union[Prompt, str]) – Prompt or string to concatenate.
- Returns:
New Prompt with concatenated content.
- Return type:
Examples
>>> p1 = Prompt("Hello") >>> p2 = Prompt("World") >>> p3 = p1 + p2 >>> str(p3) 'Hello\nWorld'
>>> p4 = p1 + " there" >>> str(p4) 'Hello\n there'
QOL Functions
- chat_object.qol.msgs(*messages: tuple[Role | str | Literal['system', 'user', 'assistant', 'tool', 'function'], str | Prompt] | Message) list[Message][source]
Quickly create a list of Message objects from tuples or Message instances.
- Parameters:
*messages – Each message can be a tuple (role, content) or a Message object.
- Returns:
List of Message objects.
- Return type:
Examples
>>> from chat_object.qol import msgs >>> from chat_object import Message >>> msgs(("user", "Hello"), ("assistant", "Hi!")) [Message(role='user', content='Hello'), Message(role='assistant', content='Hi!')] >>> msgs(Message("user", "Hello")) [Message(role='user', content='Hello')]
- chat_object.qol.chat(*messages: tuple[Role | str | Literal['system', 'user', 'assistant', 'tool', 'function'], str | Prompt] | Message) Chat[source]
Quickly create a Chat object from tuples or Message objects.
- Parameters:
*messages – Each message can be a tuple (role, content) or a Message object.
- Returns:
A Chat object containing the provided messages.
- Return type:
Examples
>>> from chat_object.qol import chat >>> chat(("user", "Hello"), ("assistant", "Hi!")) Chat(messages=Message(role='user', content='Hello'), Message(role='assistant', content='Hi!'))
- chat_object.qol.msg(role: Role | str | Literal['system', 'user', 'assistant', 'tool', 'function'], content: str | Prompt) Message[source]
Quickly create a Message object.
- Parameters:
role (RoleType) – The role of the message (e.g., “user”, “assistant”).
content (str) – The content of the message.
- Returns:
The created Message object.
- Return type:
Examples
>>> msg("user", "Hello") Message(role='user', content='Hello')
- chat_object.qol.msg_user(content: str | Prompt) Message[source]
Quickly create a Message object with the user role.
- chat_object.qol.msg_assistant(content: str | Prompt) Message[source]
Quickly create a Message object with the assistant role.