Skip to main content
Message search utilities help you find and extract information from agent conversation histories. These functions use regular expressions to search through messages, with fine-grained control over which parts of the conversation to search.

Search Scopes

All search functions accept a scope parameter that controls where to look:
  • "user" - Search only in user message text content
  • "assistant" - Search only in assistant message text content
  • "tool_calls" - Search in tool call names and stringified arguments
  • "tool_results" - Search in tool result content (text only)
  • "all" - Search all of the above (default)
The search examines text content extracted with get_text(), not raw ContentBlock objects.

Functions

search_messages()

Find messages containing content that matches a pattern.
messages
list[PromptMessageExtended]
required
List of messages to search through
pattern
str | re.Pattern
required
String or compiled regex pattern to search for
scope
SearchScope
default:"all"
Where to search: "user", "assistant", "tool_calls", "tool_results", or "all"
Returns: list[PromptMessageExtended] - Messages that contain at least one match
from fast_agent import FastAgent, search_messages

agent = FastAgent()
await agent.run("Check the weather and book a flight")

# Find all messages mentioning errors
error_messages = search_messages(
    agent.message_history,
    r"error|failed|exception",
    scope="tool_results"
)

for msg in error_messages:
    print(f"Found error in message at {msg.timestamp}")

find_matches()

Find all pattern matches in messages, returning match objects with capture groups.
messages
list[PromptMessageExtended]
required
List of messages to search through
pattern
str | re.Pattern
required
String or compiled regex pattern to search for
scope
SearchScope
default:"all"
Where to search: "user", "assistant", "tool_calls", "tool_results", or "all"
Returns: list[tuple[PromptMessageExtended, re.Match]] - List of (message, match) tuples This function is useful when you need access to regex capture groups or match positions.
from fast_agent import FastAgent, find_matches

agent = FastAgent()
await agent.run("Process jobs 1234 and 5678")

# Extract job IDs with capture groups
matches = find_matches(
    agent.message_history,
    r"Job (\d+) started with status: (\w+)",
    scope="tool_results"
)

for msg, match in matches:
    job_id = match.group(1)
    status = match.group(2)
    print(f"Job {job_id}: {status}")

extract_first()

Extract the first match from messages. This is a convenience function for the common case of extracting a single value.
messages
list[PromptMessageExtended]
required
List of messages to search through
pattern
str | re.Pattern
required
String or compiled regex pattern to search for
scope
SearchScope
default:"all"
Where to search: "user", "assistant", "tool_calls", "tool_results", or "all"
group
int
default:0
Regex group to extract (0 = whole match, 1+ = capture groups)
Returns: str | None - Extracted string or None if no match found
from fast_agent import FastAgent, extract_first

agent = FastAgent()
await agent.run("Start processing batch ABC123")

# Extract the first batch ID
batch_id = extract_first(
    agent.message_history,
    r"Batch ([A-Z0-9]+) processing started",
    scope="tool_results",
    group=1
)

if batch_id:
    print(f"Processing batch: {batch_id}")

extract_last()

Extract the last match from messages. Useful when you want the most recent occurrence of a pattern.
messages
list[PromptMessageExtended]
required
List of messages to search through
pattern
str | re.Pattern
required
String or compiled regex pattern to search for
scope
SearchScope
default:"all"
Where to search: "user", "assistant", "tool_calls", "tool_results", or "all"
group
int
default:0
Regex group to extract (0 = whole match, 1+ = capture groups)
Returns: str | None - Extracted string or None if no match found
from fast_agent import FastAgent, extract_last

agent = FastAgent()
await agent.run("Monitor the deployment process")

# Get the most recent status update
final_status = extract_last(
    agent.message_history,
    r"Deployment status: (\w+)",
    scope="tool_results",
    group=1
)

print(f"Final deployment status: {final_status}")

Practical Examples

Monitoring Tool Execution

Track which tools were called during a conversation:
from fast_agent import FastAgent, find_matches

agent = FastAgent()
await agent.run("Research Python frameworks and create a report")

# Find all tool calls
tool_calls = find_matches(
    agent.message_history,
    r".*",  # Match any tool name
    scope="tool_calls"
)

print(f"Agent called {len(tool_calls)} tools")

Extracting Structured Data

Pull out specific data points from tool results:
from fast_agent import FastAgent, find_matches
import re

agent = FastAgent()
await agent.run("Analyze sales data for Q4")

# Extract all dollar amounts mentioned
amounts = find_matches(
    agent.message_history,
    r"\$([0-9,]+(?:\.[0-9]{2})?)",
    scope="all"
)

for msg, match in amounts:
    amount = match.group(1)
    print(f"Found amount: ${amount}")

Error Handling

Check if any errors occurred during execution:
from fast_agent import FastAgent, search_messages

agent = FastAgent()
await agent.run("Process the data files")

# Check for errors in tool results
errors = search_messages(
    agent.message_history,
    r"error|failed|exception",
    scope="tool_results"
)

if errors:
    print(f"Encountered {len(errors)} errors during processing")
    for msg in errors:
        print(f"  - Error at {msg.timestamp}")
else:
    print("All operations completed successfully")

Tracking Conversation Flow

Analyze the conversation structure:
from fast_agent import FastAgent, search_messages

agent = FastAgent()
await agent.run("Help me plan a vacation")

# Find messages where user asked questions
questions = search_messages(
    agent.message_history,
    r"\?",  # Look for question marks
    scope="user"
)

print(f"User asked {len(questions)} questions")

# Find messages where assistant provided recommendations
recommendations = search_messages(
    agent.message_history,
    r"I recommend|I suggest|You should",
    scope="assistant"
)

print(f"Agent made {len(recommendations)} recommendations")

Advanced Pattern Matching

You can use compiled regex patterns for more complex searches:
import re
from fast_agent import FastAgent, find_matches

agent = FastAgent()
await agent.run("Process customer feedback")

# Multi-line pattern with flags
pattern = re.compile(
    r"Customer ID: (\d+).*?Rating: (\d+)/5",
    re.DOTALL | re.IGNORECASE
)

matches = find_matches(
    agent.message_history,
    pattern,
    scope="tool_results"
)

for msg, match in matches:
    customer_id = match.group(1)
    rating = match.group(2)
    print(f"Customer {customer_id} rated {rating}/5")

Build docs developers (and LLMs) love