Created
September 29, 2025 16:29
-
-
Save krlohnes/4b25c05c896378937b842d8ba81777ac to your computer and use it in GitHub Desktop.
filter_tool_messages.jq
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/jq -scf | |
# Filters out tool use blocks that have no matching result so you can keep | |
# going on with your session. | |
def collect_tool_result_ids: | |
[.[] | select(.content | type == "array") | .content[] | select(.type == "tool_result" and has("tool_use_id")) | .tool_use_id]; | |
# Main filtering logic | |
collect_tool_result_ids as $tool_result_ids | | |
map( | |
# Skip messages that are API error messages | |
select(.isApiErrorMessage != true) | | |
if (.content | type) == "array" then | |
. as $message | | |
($message.content | map( | |
if type == "object" then | |
if .type == "tool_use" then | |
# Only keep tool_use blocks if their ID exists in tool_result_ids | |
select(.id as $id | $tool_result_ids | index($id) != null) | |
else | |
# Keep all other object blocks (including tool_result) | |
. | |
end | |
else | |
# Keep non-object blocks (strings, etc.) | |
. | |
end | |
)) as $filtered_blocks | | |
# Only include message if it has content after filtering | |
if $filtered_blocks | length > 0 then | |
$message | .content = $filtered_blocks | |
else | |
empty | |
end | |
elif (.message.content | type) == "array" then | |
# Handle messages with message.content structure | |
. as $message | | |
($message.message.content | map( | |
if type == "object" then | |
if .type == "text" and (.text | test("API Error: 400")) then | |
# Skip API error text blocks | |
empty | |
else | |
. | |
end | |
else | |
. | |
end | |
)) as $filtered_blocks | | |
# Only include message if it has content after filtering | |
if $filtered_blocks | length > 0 then | |
$message | .message.content = $filtered_blocks | |
else | |
empty | |
end | |
else | |
# Keep messages with non-array content as-is | |
. | |
end | |
) | .[] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment