Messages¶
Message querying, filtering, analytics, and export for conversation histories.
Quick Example¶
from mamba_agents import Agent
agent = Agent("gpt-4o")
agent.run_sync("Hello!")
agent.run_sync("What tools do you have?")
# Access the query interface
query = agent.messages
# Filter messages
user_msgs = query.filter(role="user")
tool_msgs = query.filter(tool_name="read_file")
# Get analytics
stats = query.stats()
print(f"Total: {stats.total_messages} messages, {stats.total_tokens} tokens")
# View timeline
for turn in query.timeline():
print(f"Turn {turn.index}: {turn.user_content}")
# Export
json_str = query.export(format="json")
Classes¶
| Class | Description |
|---|---|
MessageQuery |
Stateless query interface for filtering and analyzing messages |
MessageStats |
Token and message count statistics |
ToolCallInfo |
Summary of a tool's usage across a conversation |
Turn |
A logical conversation turn grouping related messages |
Imports¶
from mamba_agents import MessageQuery, MessageStats, ToolCallInfo, Turn
from mamba_agents.agent.messages import MessageQuery, MessageStats, ToolCallInfo, Turn
API Reference¶
MessageQuery¶
MessageQuery
¶
MessageQuery(
messages: list[dict[str, Any]],
token_counter: TokenCounter | None = None,
)
Stateless query interface for filtering and slicing message histories.
MessageQuery operates on a provided list of message dicts (OpenAI
compatible format) without copying or caching between calls. All filter
methods return list[dict[str, Any]].
| PARAMETER | DESCRIPTION |
|---|---|
messages
|
List of message dicts to query.
TYPE:
|
token_counter
|
Optional
TYPE:
|
Example::
query = MessageQuery(messages)
tool_msgs = query.filter(role="tool")
recent = query.last(n=5)
Source code in src/mamba_agents/agent/messages.py
filter
¶
filter(
*,
role: str | None = None,
tool_name: str | None = None,
content: str | None = None,
regex: bool = False,
) -> list[dict[str, Any]]
Filter messages by role, tool name, and/or content.
Multiple keyword arguments combine with AND logic. Calling with no arguments returns all messages.
| PARAMETER | DESCRIPTION |
|---|---|
role
|
Filter by message role (user, assistant, tool, system).
TYPE:
|
tool_name
|
Filter for messages related to a specific tool. Checks
TYPE:
|
content
|
Search message content. Case-insensitive plain text match by default; interpreted as a regex pattern when regex is True.
TYPE:
|
regex
|
When True, treat content as a regular expression pattern.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[dict[str, Any]]
|
List of matching message dicts. Empty list if no matches. |
| RAISES | DESCRIPTION |
|---|---|
error
|
If regex is True and content is not a valid regex. |
Source code in src/mamba_agents/agent/messages.py
slice
¶
Return messages at indices start through end-1.
Uses standard Python slice semantics so out-of-range indices are handled gracefully.
| PARAMETER | DESCRIPTION |
|---|---|
start
|
Start index (inclusive). Defaults to 0.
TYPE:
|
end
|
End index (exclusive). Defaults to None (end of list).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[dict[str, Any]]
|
Sliced list of message dicts. |
Source code in src/mamba_agents/agent/messages.py
first
¶
Return the first n messages.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of messages to return. Defaults to 1.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[dict[str, Any]]
|
List of the first n message dicts (or all if fewer exist). |
Source code in src/mamba_agents/agent/messages.py
last
¶
Return the last n messages.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of messages to return. Defaults to 1.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[dict[str, Any]]
|
List of the last n message dicts (or all if fewer exist). |
Source code in src/mamba_agents/agent/messages.py
all
¶
Return all messages.
Equivalent to get_messages() on the Agent.
| RETURNS | DESCRIPTION |
|---|---|
list[dict[str, Any]]
|
Complete list of message dicts. |
stats
¶
stats() -> MessageStats
Compute token and message count statistics.
Counts messages by role and computes token totals using the
Agent's configured TokenCounter. Token counts are computed
on demand and cached within this single call to avoid redundant
computation. When no TokenCounter is available, all token
fields default to zero.
| RETURNS | DESCRIPTION |
|---|---|
MessageStats
|
A |
Source code in src/mamba_agents/agent/messages.py
tool_summary
¶
tool_summary() -> list[ToolCallInfo]
Compute tool call analytics grouped by tool name.
Scans all messages for tool calls (from assistant messages with
tool_calls arrays) and tool results (from tool role messages),
groups them by tool name, and links calls to their results via
tool_call_id.
| RETURNS | DESCRIPTION |
|---|---|
list[ToolCallInfo]
|
A list of |
list[ToolCallInfo]
|
Returns an empty list if no tool calls are found. |
Source code in src/mamba_agents/agent/messages.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | |
timeline
¶
timeline() -> list[Turn]
Parse the message list into a structured conversation timeline.
Groups messages into logical turns. Each turn contains a user prompt, the assistant's response, and any tool call/result pairs that occurred during the exchange. System prompts at the start of the conversation are attached as context on the first turn rather than appearing as separate turns.
Turn grouping logic:
- Start a new turn on each user message.
- Associate the following assistant message with that turn.
- If the assistant message has
tool_calls, group subsequent tool result messages into the turn'stool_interactions. - If the next message after tool results is another assistant message, it is part of the same turn (tool loop continuation).
- Consecutive assistant messages without a preceding user message each get their own turn.
- System messages at the start attach to the first turn as context.
| RETURNS | DESCRIPTION |
|---|---|
list[Turn]
|
A list of |
list[Turn]
|
empty list if there are no messages. |
Source code in src/mamba_agents/agent/messages.py
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 | |
export
¶
export(
format: str = "json",
messages: list[dict[str, Any]] | None = None,
**kwargs: Any,
) -> str | list[dict[str, Any]]
Export messages in the specified format.
| PARAMETER | DESCRIPTION |
|---|---|
format
|
Export format. One of
TYPE:
|
messages
|
Optional subset of messages to export. When None, all messages held by this query instance are exported.
TYPE:
|
**kwargs
|
Format-specific options forwarded to the underlying exporter.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str | list[dict[str, Any]]
|
A JSON, Markdown, or CSV string for string-based formats, |
str | list[dict[str, Any]]
|
or |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If format is not one of the supported formats. |
Source code in src/mamba_agents/agent/messages.py
print_stats
¶
print_stats(
*,
preset: str = "detailed",
format: str = "rich",
console: Console | None = None,
**options: Any,
) -> str
Render message statistics as a formatted table.
Computes statistics via :meth:stats and delegates to the
standalone :func:~mamba_agents.agent.display.print_stats function
for rendering. All parameters are forwarded directly.
| PARAMETER | DESCRIPTION |
|---|---|
preset
|
Named preset (
TYPE:
|
format
|
Output format (
TYPE:
|
console
|
Optional Rich
TYPE:
|
**options
|
Keyword overrides applied to the resolved preset
(e.g.,
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The rendered string. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If preset or format is not recognised. |
Example::
agent.messages.print_stats() # Rich table to terminal
agent.messages.print_stats(format="plain") # ASCII table
agent.messages.print_stats(preset="compact", show_tokens=True)
Source code in src/mamba_agents/agent/messages.py
print_timeline
¶
print_timeline(
*,
preset: str = "detailed",
format: str = "rich",
console: Console | None = None,
**options: Any,
) -> str
Render the conversation timeline as a formatted display.
Parses messages into turns via :meth:timeline and delegates to the
standalone :func:~mamba_agents.agent.display.print_timeline function
for rendering. All parameters are forwarded directly.
| PARAMETER | DESCRIPTION |
|---|---|
preset
|
Named preset (
TYPE:
|
format
|
Output format (
TYPE:
|
console
|
Optional Rich
TYPE:
|
**options
|
Keyword overrides applied to the resolved preset
(e.g.,
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The rendered string. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If preset or format is not recognised. |
Example::
agent.messages.print_timeline() # Rich panels to terminal
agent.messages.print_timeline(format="plain") # ASCII timeline
agent.messages.print_timeline(preset="compact", limit=5)
Source code in src/mamba_agents/agent/messages.py
print_tools
¶
print_tools(
*,
preset: str = "detailed",
format: str = "rich",
console: Console | None = None,
**options: Any,
) -> str
Render a tool usage summary as a formatted table.
Computes tool call summaries via :meth:tool_summary and delegates to
the standalone :func:~mamba_agents.agent.display.print_tools function
for rendering. All parameters are forwarded directly.
| PARAMETER | DESCRIPTION |
|---|---|
preset
|
Named preset (
TYPE:
|
format
|
Output format (
TYPE:
|
console
|
Optional Rich
TYPE:
|
**options
|
Keyword overrides applied to the resolved preset
(e.g.,
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The rendered string. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If preset or format is not recognised. |
Example::
agent.messages.print_tools() # Rich table to terminal
agent.messages.print_tools(format="plain") # ASCII table
agent.messages.print_tools(preset="verbose", show_tool_details=True)
Source code in src/mamba_agents/agent/messages.py
MessageStats¶
MessageStats
dataclass
¶
MessageStats(
total_messages: int = 0,
messages_by_role: dict[str, int] = dict(),
total_tokens: int = 0,
tokens_by_role: dict[str, int] = dict(),
)
Token and message count statistics for a conversation.
| ATTRIBUTE | DESCRIPTION |
|---|---|
total_messages |
Total number of messages in the conversation.
TYPE:
|
messages_by_role |
Count of messages grouped by role (user, assistant, tool, system).
TYPE:
|
total_tokens |
Total estimated token count across all messages.
TYPE:
|
tokens_by_role |
Token counts grouped by role.
TYPE:
|
ToolCallInfo¶
ToolCallInfo
dataclass
¶
ToolCallInfo(
tool_name: str,
call_count: int = 0,
arguments: list[dict[str, Any]] = list(),
results: list[str] = list(),
tool_call_ids: list[str] = list(),
)
Summary of a single tool's usage across a conversation.
| ATTRIBUTE | DESCRIPTION |
|---|---|
tool_name |
Name of the tool.
TYPE:
|
call_count |
Number of times the tool was called.
TYPE:
|
arguments |
List of argument dicts passed to each invocation.
TYPE:
|
results |
List of result summary strings from each invocation.
TYPE:
|
tool_call_ids |
List of tool_call_id strings linking calls to results.
TYPE:
|
Turn¶
Turn
dataclass
¶
Turn(
index: int = 0,
user_content: str | None = None,
assistant_content: str | None = None,
tool_interactions: list[dict[str, Any]] = list(),
system_context: str | None = None,
)
A logical conversation turn grouping related messages.
A turn represents one exchange cycle: a user prompt, the assistant's response, and any tool call/result pairs that occurred.
| ATTRIBUTE | DESCRIPTION |
|---|---|
index |
Zero-based position of this turn in the conversation.
TYPE:
|
user_content |
The user's message content, or None if absent.
TYPE:
|
assistant_content |
The assistant's text response, or None if absent.
TYPE:
|
tool_interactions |
List of dicts, each containing tool call and result pairs.
TYPE:
|
system_context |
System prompt content attached to this turn, or None.
TYPE:
|