needlepath-strands 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- needlepath_strands/__init__.py +29 -0
- needlepath_strands/_messages.py +516 -0
- needlepath_strands/conversation_manager.py +537 -0
- needlepath_strands/py.typed +0 -0
- needlepath_strands/version.py +3 -0
- needlepath_strands-0.1.0.dist-info/METADATA +275 -0
- needlepath_strands-0.1.0.dist-info/RECORD +9 -0
- needlepath_strands-0.1.0.dist-info/WHEEL +4 -0
- needlepath_strands-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Needlepath context selection for Strands Agents.
|
|
2
|
+
|
|
3
|
+
from strands import Agent
|
|
4
|
+
from needlepath_strands import NeedlepathConversationManager
|
|
5
|
+
|
|
6
|
+
agent = Agent(
|
|
7
|
+
model=model,
|
|
8
|
+
tools=tools,
|
|
9
|
+
conversation_manager=NeedlepathConversationManager(
|
|
10
|
+
operating_point="np-2026-08-r3",
|
|
11
|
+
),
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
One line. The accumulated tool results in ``agent.messages`` are selected against
|
|
15
|
+
the current task after every invocation (``apply_management``) and on a context-window
|
|
16
|
+
overflow (``reduce_context``), and every error path leaves the history exactly as it
|
|
17
|
+
was, with the reason recorded on ``.stats`` and on each rewritten message's
|
|
18
|
+
``metadata.custom.needlepath``.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from .conversation_manager import CORE_VERSION, USER_AGENT_SUFFIX, NeedlepathConversationManager
|
|
22
|
+
from .version import __version__
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"NeedlepathConversationManager",
|
|
26
|
+
"USER_AGENT_SUFFIX",
|
|
27
|
+
"CORE_VERSION",
|
|
28
|
+
"__version__",
|
|
29
|
+
]
|
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
"""Message/content-block <-> record mapping, and the safety rules that govern rewriting.
|
|
2
|
+
|
|
3
|
+
This is the Strands twin of ``needlepath_langchain._messages``. The host shapes differ
|
|
4
|
+
— Strands has no ``ToolMessage`` class; a tool result is a ``toolResult`` *content
|
|
5
|
+
block* inside a ``role="user"`` ``Message`` (Bedrock's wire shape, which Strands
|
|
6
|
+
models every provider onto) — but the two invariants that make rewriting safe are
|
|
7
|
+
identical, and are restated here because the sharp edges are structural, not
|
|
8
|
+
LangChain-specific:
|
|
9
|
+
|
|
10
|
+
**Invariant 1 — a message is never removed, only rewritten, and a content block is
|
|
11
|
+
never removed, only rewritten.**
|
|
12
|
+
:class:`~strands.agent.conversation_manager.SlidingWindowConversationManager` goes to
|
|
13
|
+
real lengths (``find_valid_trim_point``, ``_find_tool_pair_trim_point``) to avoid ever
|
|
14
|
+
leaving a ``toolUse`` block without its paired ``toolResult`` — every model provider
|
|
15
|
+
rejects that shape. This package never deletes a message or a content block, so it
|
|
16
|
+
cannot produce that shape at all: a ``toolResult`` keeps its ``toolUseId`` and its
|
|
17
|
+
position, only its ``content`` may shrink.
|
|
18
|
+
|
|
19
|
+
**Invariant 2 — a rewrite never grows the context and never empties a message.**
|
|
20
|
+
An excerpt longer than what it replaces, or an empty excerpt applied to non-empty
|
|
21
|
+
content, is a regression however the service arrived at it. Both are refused here
|
|
22
|
+
rather than trusted upstream.
|
|
23
|
+
|
|
24
|
+
**No local "preserve the last N messages" policy (NEXPE-517 review).** An
|
|
25
|
+
earlier version excluded a trailing window of messages from ``index_by_id``
|
|
26
|
+
(sent as records, but never installed as a rewrite) so that recent turns were
|
|
27
|
+
never touched regardless of what the engine selected. That is a real product
|
|
28
|
+
capability, and it is also, unavoidably, a client-side selection decision:
|
|
29
|
+
whichever records fall in the window are guaranteed kept, by client logic, no
|
|
30
|
+
matter what the engine says about them. Worse, because the guarantee was
|
|
31
|
+
enforced by silently narrowing which records ``apply_selection`` was allowed to
|
|
32
|
+
touch while ``NeedlepathConversationManager`` went on recording the *engine's*
|
|
33
|
+
full ``tokens_after``/``tokens_saved`` on every call, the receipt and the
|
|
34
|
+
applied result could diverge: an engine selection weighted toward the
|
|
35
|
+
protected window reported large savings while the messages the model actually
|
|
36
|
+
received barely shrank. There is no such thing as a client-side version of this
|
|
37
|
+
feature that is both honest about what happened and free of a locally-made
|
|
38
|
+
selection decision, so it is gone. If tail preservation is a real requirement,
|
|
39
|
+
it belongs to the engine (a position/recency signal it can act on, the same as
|
|
40
|
+
any other input) or to a genuinely separate, engine-blind mechanism like
|
|
41
|
+
Strands' own ``SlidingWindowConversationManager`` (composable via
|
|
42
|
+
``NeedlepathConversationManager(fallback=...)`` for the reactive-overflow case
|
|
43
|
+
— see ``conversation_manager.py``). What this package applies is the engine's
|
|
44
|
+
result, exactly as returned, over every record it sent.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
from collections.abc import Sequence
|
|
50
|
+
from typing import Any
|
|
51
|
+
|
|
52
|
+
from needlepath import ContextRecord, RecordKind
|
|
53
|
+
|
|
54
|
+
try: # pragma: no cover - exercised by the installed-strands test matrix
|
|
55
|
+
from strands.types.content import ContentBlock, Message
|
|
56
|
+
except ImportError as exc: # pragma: no cover
|
|
57
|
+
raise ImportError(
|
|
58
|
+
"needlepath-strands requires strands-agents (>=1.52.0,<2). "
|
|
59
|
+
"Install it with: pip install 'needlepath-strands'"
|
|
60
|
+
) from exc
|
|
61
|
+
|
|
62
|
+
#: Key under ``Message["metadata"]["custom"]``, mirroring what
|
|
63
|
+
#: ``needlepath_langchain`` writes to ``response_metadata``. Strands strips
|
|
64
|
+
#: ``metadata`` before every model call (``types/content.py``'s ``MessageMetadata``
|
|
65
|
+
#: docstring), so this is genuinely metadata-only: it never reaches the model, only
|
|
66
|
+
#: a trace, a session snapshot, or a caller inspecting ``agent.messages``.
|
|
67
|
+
METADATA_KEY = "needlepath"
|
|
68
|
+
|
|
69
|
+
#: What replaces a tool result the service did not select. Deliberately short and
|
|
70
|
+
#: explicit that content was withheld rather than absent.
|
|
71
|
+
DEFAULT_PLACEHOLDER = "[needlepath: this tool result was not selected for the current step]"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def approx_tokens(text: str) -> int:
|
|
75
|
+
"""A cheap, dependency-free token estimate for the engage/stand-down trigger.
|
|
76
|
+
|
|
77
|
+
Same ``len // 4`` shape as ``needlepath_langchain.approx_tokens`` and as
|
|
78
|
+
Strands' own ``_heuristic_estimate_text`` (``strands/models/model.py``) — this
|
|
79
|
+
is **never** compared against a billed quantity, only used to decide whether
|
|
80
|
+
calling is worth it at all.
|
|
81
|
+
"""
|
|
82
|
+
return len(text) // 4 + 1
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _block_text(block: ContentBlock) -> str:
|
|
86
|
+
"""The text a single ``ContentBlock`` carries, or ``""`` if it carries none.
|
|
87
|
+
|
|
88
|
+
Only ``text`` and ``toolResult`` blocks contribute: an ``image``, ``document``,
|
|
89
|
+
``reasoningContent`` or ``toolUse`` block is structure or binary, not prose, and
|
|
90
|
+
is never a record. (``toolUse`` is structure for the same reason an
|
|
91
|
+
``AIMessage`` carrying ``tool_calls`` is structure in the LangChain adapter —
|
|
92
|
+
its content is the call, not something worth excerpting.)
|
|
93
|
+
"""
|
|
94
|
+
if "text" in block:
|
|
95
|
+
return str(block["text"])
|
|
96
|
+
if "toolResult" in block:
|
|
97
|
+
return tool_result_text(block["toolResult"])
|
|
98
|
+
return ""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def tool_result_text(tool_result: Any) -> str:
|
|
102
|
+
"""The text of a ``ToolResult``, concatenating every text/json content item.
|
|
103
|
+
|
|
104
|
+
A tool result's ``content`` is a *list* of items (``{"text": ...}``,
|
|
105
|
+
``{"json": ...}``, ``{"image": ...}``, ``{"document": ...}``) because a single
|
|
106
|
+
tool call can return multiple content parts. Image and document items are
|
|
107
|
+
binary and are left out — the same choice Strands' own
|
|
108
|
+
``_count_content_block_tokens`` makes for its heuristic, and for the same
|
|
109
|
+
reason: there is no text to select over.
|
|
110
|
+
"""
|
|
111
|
+
import json as _json
|
|
112
|
+
|
|
113
|
+
parts: list[str] = []
|
|
114
|
+
for item in tool_result.get("content", []) or []:
|
|
115
|
+
if not isinstance(item, dict):
|
|
116
|
+
continue
|
|
117
|
+
if "text" in item:
|
|
118
|
+
parts.append(str(item["text"]))
|
|
119
|
+
elif "json" in item:
|
|
120
|
+
try:
|
|
121
|
+
parts.append(_json.dumps(item["json"], sort_keys=True))
|
|
122
|
+
except (TypeError, ValueError):
|
|
123
|
+
parts.append(str(item["json"]))
|
|
124
|
+
return "\n".join(parts)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def is_prunable_block(
|
|
128
|
+
role: str,
|
|
129
|
+
block: ContentBlock,
|
|
130
|
+
*,
|
|
131
|
+
include_ai_messages: bool = False,
|
|
132
|
+
include_human_messages: bool = False,
|
|
133
|
+
) -> bool:
|
|
134
|
+
"""Whether this content block's text may be rewritten.
|
|
135
|
+
|
|
136
|
+
The default is **tool results only**, matching ``needlepath_langchain``'s
|
|
137
|
+
default and for the same reason: tool results are where the tokens are, they
|
|
138
|
+
are machine-produced so replacing them with an excerpt of themselves cannot
|
|
139
|
+
silently rewrite something a human wrote or the model committed to, and they
|
|
140
|
+
carry no pairing constraint of their own (unlike the ``toolUse`` block that
|
|
141
|
+
named them, which is never touched).
|
|
142
|
+
|
|
143
|
+
A ``toolUse`` block is never prunable, on any setting: it is the call, not
|
|
144
|
+
prose, and its structure is what the pairing invariant protects.
|
|
145
|
+
|
|
146
|
+
A ``toolResult`` carrying anything other than text/json content — an
|
|
147
|
+
``image`` or ``document`` item — is never prunable either. ``rewrite_block``
|
|
148
|
+
replaces a tool result's *entire* content list with one text item, which
|
|
149
|
+
silently deletes an image or document item mixed in alongside the text.
|
|
150
|
+
Rather than teach the rewrite path to reconstruct a mixed content list,
|
|
151
|
+
excluding a mixed result from selection entirely keeps invariant 2 ("a
|
|
152
|
+
rewrite never empties a message") honest at the type level: nothing here is
|
|
153
|
+
ever eligible to lose content it did not offer to replace.
|
|
154
|
+
"""
|
|
155
|
+
if "toolResult" in block:
|
|
156
|
+
return _tool_result_is_text_only(block["toolResult"])
|
|
157
|
+
if "toolUse" in block:
|
|
158
|
+
return False
|
|
159
|
+
if "text" in block:
|
|
160
|
+
return include_ai_messages if role == "assistant" else include_human_messages
|
|
161
|
+
# image / document / reasoningContent / guardContent / citationsContent /
|
|
162
|
+
# cachePoint: never prunable. No text to excerpt, and several are binary.
|
|
163
|
+
return False
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
#: The only keys a text-eligible ``ToolResultContent`` item may carry.
|
|
167
|
+
_TEXT_ONLY_ITEM_KEYS = frozenset({"text", "json"})
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _tool_result_is_text_only(tool_result: Any) -> bool:
|
|
171
|
+
"""Whether every content item in a ``ToolResult`` carries text/json only.
|
|
172
|
+
|
|
173
|
+
"``text`` in item or ``json`` in item" is not a strong enough check: the
|
|
174
|
+
``ToolResultContent`` TypedDict is ``total=False``, so nothing stops one
|
|
175
|
+
item from carrying **both** ``text`` and ``image`` in the same dict, and
|
|
176
|
+
real providers are not obligated to keep them separate. A check that only
|
|
177
|
+
asks "is there text here" would accept such an item and then lose the
|
|
178
|
+
image anyway — ``rewrite_block`` replaces the whole item, not a field
|
|
179
|
+
inside it. The requirement is the item's key set is a **non-empty subset**
|
|
180
|
+
of ``{text, json}``: any ``image``/``document`` key present, alongside text
|
|
181
|
+
or not, fails it, and so does an item carrying no known key at all.
|
|
182
|
+
|
|
183
|
+
A tool result with any such item mixed in is left alone by this package
|
|
184
|
+
entirely — see ``is_prunable_block``.
|
|
185
|
+
"""
|
|
186
|
+
content = tool_result.get("content", []) if isinstance(tool_result, dict) else []
|
|
187
|
+
for item in content or []:
|
|
188
|
+
if not isinstance(item, dict):
|
|
189
|
+
return False
|
|
190
|
+
keys = set(item.keys())
|
|
191
|
+
if not keys or not keys <= _TEXT_ONLY_ITEM_KEYS:
|
|
192
|
+
return False
|
|
193
|
+
return True
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def kind_for(role: str, block: ContentBlock) -> str:
|
|
197
|
+
"""Map a Strands content block onto the published record-role enum."""
|
|
198
|
+
if "toolResult" in block:
|
|
199
|
+
status = block["toolResult"].get("status")
|
|
200
|
+
return RecordKind.ERROR if status == "error" else RecordKind.TOOL_RESULT
|
|
201
|
+
if role == "assistant":
|
|
202
|
+
return RecordKind.LLM_RESPONSE
|
|
203
|
+
return RecordKind.USER_INPUT
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def record_id_for(message_index: int, block_index: int) -> str:
|
|
207
|
+
"""A short, stable per-call record id: ``m<message index>b<block index>``.
|
|
208
|
+
|
|
209
|
+
Two-dimensional because one Strands message can carry several content blocks
|
|
210
|
+
— a batch of parallel tool calls comes back as one ``role="user"`` message
|
|
211
|
+
with one ``toolResult`` block per call. Positional rather than derived from
|
|
212
|
+
any content-carried id: it is guaranteed present and unique inside one
|
|
213
|
+
request, and it costs two or three bytes against the 6 MB guard rather than a
|
|
214
|
+
UUID's worth.
|
|
215
|
+
"""
|
|
216
|
+
return f"m{message_index}b{block_index}"
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def build_records(
|
|
220
|
+
messages: Sequence[Message],
|
|
221
|
+
*,
|
|
222
|
+
include_ai_messages: bool = False,
|
|
223
|
+
include_human_messages: bool = False,
|
|
224
|
+
) -> tuple[list[ContextRecord], dict[str, tuple[int, int]]]:
|
|
225
|
+
"""Records for every prunable, non-empty content block in ``messages``.
|
|
226
|
+
|
|
227
|
+
Built over the **whole** history with no positions excluded: every eligible
|
|
228
|
+
block becomes a record, the engine selects over all of them, and
|
|
229
|
+
``NeedlepathConversationManager`` applies whatever the engine returns
|
|
230
|
+
exactly as returned — see the module note on why there is no local
|
|
231
|
+
"protect the last N messages" policy (NEXPE-517 review; an earlier version
|
|
232
|
+
had one, and it made the applied result diverge from what ``.stats``
|
|
233
|
+
reported the engine did, because only part of the engine's own selection
|
|
234
|
+
was ever installed).
|
|
235
|
+
|
|
236
|
+
Returns the records and a ``record_id -> (message_index, block_index)`` map.
|
|
237
|
+
Anything not in that map is passed through untouched, by construction.
|
|
238
|
+
|
|
239
|
+
No ``importance`` (or any other relevance-adjacent field) is set on the
|
|
240
|
+
records this builds. Earlier drafts sent ``importance=(position) / (total)``
|
|
241
|
+
as a "recency prior the engine can use" — but computing a value from record
|
|
242
|
+
position and handing it to the engine to weight *is* a client-side judgment
|
|
243
|
+
about what should survive, exactly the thing the thin-client rule
|
|
244
|
+
(``test_needlepath_thin_client_guard.py``) exists to keep server-side. The
|
|
245
|
+
engine's own default (an omitted field, per ``ContextRecord.importance``'s
|
|
246
|
+
contract) is what this package sends instead.
|
|
247
|
+
"""
|
|
248
|
+
records: list[ContextRecord] = []
|
|
249
|
+
index_by_id: dict[str, tuple[int, int]] = {}
|
|
250
|
+
for m_index, message in enumerate(messages):
|
|
251
|
+
role = message.get("role", "user")
|
|
252
|
+
content = message.get("content") or []
|
|
253
|
+
for b_index, block in enumerate(content):
|
|
254
|
+
if not is_prunable_block(
|
|
255
|
+
role,
|
|
256
|
+
block,
|
|
257
|
+
include_ai_messages=include_ai_messages,
|
|
258
|
+
include_human_messages=include_human_messages,
|
|
259
|
+
):
|
|
260
|
+
continue
|
|
261
|
+
text = _block_text(block)
|
|
262
|
+
if not text.strip():
|
|
263
|
+
continue
|
|
264
|
+
record_id = record_id_for(m_index, b_index)
|
|
265
|
+
index_by_id[record_id] = (m_index, b_index)
|
|
266
|
+
records.append(
|
|
267
|
+
ContextRecord(
|
|
268
|
+
text=text,
|
|
269
|
+
kind=kind_for(role, block),
|
|
270
|
+
id=record_id,
|
|
271
|
+
title=_title_for(block),
|
|
272
|
+
)
|
|
273
|
+
)
|
|
274
|
+
return records, index_by_id
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _title_for(block: ContentBlock) -> str | None:
|
|
278
|
+
"""A short human-readable label. For a tool result, unavailable here.
|
|
279
|
+
|
|
280
|
+
Unlike LangChain's ``ToolMessage.name``, a Strands ``ToolResult`` carries only
|
|
281
|
+
``toolUseId`` — the tool's name lives on the paired ``toolUse`` block in the
|
|
282
|
+
*previous* message. Callers who want it can look it up via ``toolUseId``;
|
|
283
|
+
this function stays a pure per-block mapping rather than needing the whole
|
|
284
|
+
message list threaded through it.
|
|
285
|
+
"""
|
|
286
|
+
return None
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def latest_user_prompt(messages: Sequence[Message]) -> str:
|
|
290
|
+
"""The most recent real human turn — what the selected context has to serve.
|
|
291
|
+
|
|
292
|
+
A ``role="user"`` message is not necessarily a human turn in Strands: tool
|
|
293
|
+
results are *also* sent back as ``role="user"`` messages (Bedrock's wire
|
|
294
|
+
shape). This walks backward past tool-result-only user turns to the text a
|
|
295
|
+
person actually typed, then falls back to the last non-empty text of any kind
|
|
296
|
+
— the same two-step fallback ``needlepath_langchain.latest_user_prompt`` uses,
|
|
297
|
+
adapted to a role scheme with no dedicated "human" role.
|
|
298
|
+
"""
|
|
299
|
+
for message in reversed(messages):
|
|
300
|
+
if message.get("role") != "user":
|
|
301
|
+
continue
|
|
302
|
+
text = _plain_text(message)
|
|
303
|
+
if text.strip():
|
|
304
|
+
return text
|
|
305
|
+
for message in reversed(messages):
|
|
306
|
+
text = _plain_text(message) or _all_text(message)
|
|
307
|
+
if text.strip():
|
|
308
|
+
return text
|
|
309
|
+
return ""
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _plain_text(message: Message) -> str:
|
|
313
|
+
"""Text from a message's plain ``text`` blocks only — never ``toolResult``."""
|
|
314
|
+
return "\n".join(
|
|
315
|
+
str(block["text"]) for block in (message.get("content") or []) if "text" in block
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _all_text(message: Message) -> str:
|
|
320
|
+
"""Text from every block in a message, ``toolResult`` included. Last-resort."""
|
|
321
|
+
return "\n".join(_block_text(block) for block in (message.get("content") or []))
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def prior_user_prompts(messages: Sequence[Message], limit: int = 4) -> list[str]:
|
|
325
|
+
"""Earlier real human turns, newest first — the contract's drift signal."""
|
|
326
|
+
found: list[str] = []
|
|
327
|
+
seen_latest = False
|
|
328
|
+
for message in reversed(messages):
|
|
329
|
+
if message.get("role") != "user":
|
|
330
|
+
continue
|
|
331
|
+
text = _plain_text(message)
|
|
332
|
+
if not text.strip():
|
|
333
|
+
continue
|
|
334
|
+
if not seen_latest:
|
|
335
|
+
seen_latest = True
|
|
336
|
+
continue
|
|
337
|
+
found.append(text)
|
|
338
|
+
if len(found) >= limit:
|
|
339
|
+
break
|
|
340
|
+
return found
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def rewrite_block(block: ContentBlock, new_text: str) -> ContentBlock:
|
|
344
|
+
"""A copy of a content block with its text replaced.
|
|
345
|
+
|
|
346
|
+
For a ``toolResult`` (the default-eligible case): collapses its content
|
|
347
|
+
into a single ``{"text": new_text}`` item. ``is_prunable_block`` already
|
|
348
|
+
refuses any tool result carrying an ``image`` or ``document`` item, so this
|
|
349
|
+
never has mixed content to lose — only ever a text/json-only result whose
|
|
350
|
+
envelope (``toolUseId``, ``status``) survives untouched.
|
|
351
|
+
|
|
352
|
+
For a plain ``text`` block (only reachable with ``include_ai_messages`` /
|
|
353
|
+
``include_human_messages``): replaces ``text`` in place, leaving every
|
|
354
|
+
other key on the block (there usually are none) untouched.
|
|
355
|
+
"""
|
|
356
|
+
if "toolResult" in block:
|
|
357
|
+
tool_result = dict(block["toolResult"])
|
|
358
|
+
tool_result["content"] = [{"text": new_text}]
|
|
359
|
+
new_block: dict[str, Any] = dict(block)
|
|
360
|
+
new_block["toolResult"] = tool_result
|
|
361
|
+
return new_block # type: ignore[return-value]
|
|
362
|
+
new_block = dict(block)
|
|
363
|
+
new_block["text"] = new_text
|
|
364
|
+
return new_block # type: ignore[return-value]
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def apply_selection(
|
|
368
|
+
messages: Sequence[Message],
|
|
369
|
+
*,
|
|
370
|
+
excerpts: dict[str, str],
|
|
371
|
+
index_by_id: dict[str, tuple[int, int]],
|
|
372
|
+
placeholder: str,
|
|
373
|
+
request_id: str,
|
|
374
|
+
) -> tuple[list[Message], int, int]:
|
|
375
|
+
"""Rewrite the selected and unselected content blocks named in ``index_by_id``.
|
|
376
|
+
|
|
377
|
+
Handles both eligible shapes ``build_records``/``is_prunable_block`` can
|
|
378
|
+
produce: ``toolResult`` blocks (the default) and, when
|
|
379
|
+
``include_ai_messages``/``include_human_messages`` opted them in, plain
|
|
380
|
+
``text`` blocks — via ``_block_text``/``rewrite_block``, which both branch
|
|
381
|
+
on the block's own shape rather than assuming ``toolResult``.
|
|
382
|
+
|
|
383
|
+
Returns ``(new_messages, before_tokens, after_tokens)``. ``new_messages`` is a
|
|
384
|
+
**new list** of (mostly-shared, copy-on-write) message dicts — nothing here
|
|
385
|
+
mutates the caller's ``messages`` argument, matching ``apply_selection`` in
|
|
386
|
+
``needlepath_langchain``. The caller (``NeedlepathConversationManager``)
|
|
387
|
+
decides whether and how to install the result on ``agent.messages``.
|
|
388
|
+
|
|
389
|
+
Enforces invariant 2 block by block: an excerpt that is empty, or that would
|
|
390
|
+
make a block *longer*, is refused and the original kept.
|
|
391
|
+
"""
|
|
392
|
+
out: list[Message] = list(messages)
|
|
393
|
+
touched_messages: dict[int, list[dict[str, Any]]] = {}
|
|
394
|
+
before = 0
|
|
395
|
+
after = 0
|
|
396
|
+
for record_id, (m_index, b_index) in index_by_id.items():
|
|
397
|
+
message = out[m_index]
|
|
398
|
+
block = (message.get("content") or [])[b_index]
|
|
399
|
+
original_text = _block_text(block)
|
|
400
|
+
before += approx_tokens(original_text)
|
|
401
|
+
excerpt = excerpts.get(record_id)
|
|
402
|
+
if excerpt is None and not placeholder.strip():
|
|
403
|
+
# Invariant 2 at the mutation boundary: a blank custom placeholder
|
|
404
|
+
# would empty a non-empty tool result. Refused rather than trusted.
|
|
405
|
+
after += approx_tokens(original_text)
|
|
406
|
+
continue
|
|
407
|
+
if excerpt is None:
|
|
408
|
+
new_text = placeholder
|
|
409
|
+
reason = "not_selected"
|
|
410
|
+
elif not excerpt.strip() or len(excerpt) >= len(original_text):
|
|
411
|
+
after += approx_tokens(original_text)
|
|
412
|
+
continue
|
|
413
|
+
else:
|
|
414
|
+
new_text = excerpt
|
|
415
|
+
reason = "excerpt"
|
|
416
|
+
if len(new_text) >= len(original_text) and reason == "not_selected":
|
|
417
|
+
after += approx_tokens(original_text)
|
|
418
|
+
continue
|
|
419
|
+
|
|
420
|
+
new_content = list(message.get("content") or [])
|
|
421
|
+
new_content[b_index] = rewrite_block(block, new_text)
|
|
422
|
+
new_message: dict[str, Any] = dict(message)
|
|
423
|
+
new_message["content"] = new_content
|
|
424
|
+
out[m_index] = new_message # type: ignore[call-overload]
|
|
425
|
+
after += approx_tokens(new_text)
|
|
426
|
+
touched_messages.setdefault(m_index, []).append(
|
|
427
|
+
{
|
|
428
|
+
"block_index": b_index,
|
|
429
|
+
"record_id": record_id,
|
|
430
|
+
"rewrite_reason": reason,
|
|
431
|
+
"original_tokens": approx_tokens(original_text),
|
|
432
|
+
"new_tokens": approx_tokens(new_text),
|
|
433
|
+
}
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
for m_index, touched in touched_messages.items():
|
|
437
|
+
out[m_index] = _annotate_message(out[m_index], touched, request_id=request_id)
|
|
438
|
+
return out, before, after
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _annotate_message(
|
|
442
|
+
message: Message, touched: list[dict[str, Any]], *, request_id: str
|
|
443
|
+
) -> Message:
|
|
444
|
+
"""Attach the metadata-only rewrite marker under ``metadata.custom``.
|
|
445
|
+
|
|
446
|
+
``metadata`` is stripped before every model call (``MessageMetadata``'s own
|
|
447
|
+
docstring) and survives session save/restore, so this is the Strands
|
|
448
|
+
equivalent of writing to ``response_metadata`` in the LangChain adapter: it
|
|
449
|
+
travels with the message, into a trace or a session snapshot, without this
|
|
450
|
+
package deciding what the caller's logger is.
|
|
451
|
+
"""
|
|
452
|
+
metadata: dict[str, Any] = dict(message.get("metadata") or {})
|
|
453
|
+
custom: dict[str, Any] = dict(metadata.get("custom") or {})
|
|
454
|
+
existing = custom.get(METADATA_KEY)
|
|
455
|
+
merged = dict(existing) if isinstance(existing, dict) else {}
|
|
456
|
+
merged.update({"rewritten": True, "request_id": request_id, "blocks": touched})
|
|
457
|
+
custom[METADATA_KEY] = merged
|
|
458
|
+
metadata["custom"] = custom
|
|
459
|
+
new_message: dict[str, Any] = dict(message)
|
|
460
|
+
new_message["metadata"] = metadata
|
|
461
|
+
return new_message # type: ignore[return-value]
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def tool_call_keywords(tool_input: Any, limit: int = 6, max_len: int = 120) -> list[str]:
|
|
465
|
+
"""Short string values from a tool call's input, as selection keywords.
|
|
466
|
+
|
|
467
|
+
Mirrors ``needlepath_langchain.tool_call_keywords``: a tool call's input is
|
|
468
|
+
the closest thing to a query the service will ever see for a tool result.
|
|
469
|
+
"""
|
|
470
|
+
if not isinstance(tool_input, dict):
|
|
471
|
+
return []
|
|
472
|
+
out: list[str] = []
|
|
473
|
+
for value in tool_input.values():
|
|
474
|
+
if isinstance(value, str) and value.strip():
|
|
475
|
+
out.append(value.strip()[:max_len])
|
|
476
|
+
elif isinstance(value, (int, float, bool)):
|
|
477
|
+
out.append(str(value))
|
|
478
|
+
if len(out) >= limit:
|
|
479
|
+
break
|
|
480
|
+
return out
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def latest_tool_use(messages: Sequence[Message]) -> dict[str, Any] | None:
|
|
484
|
+
"""The most recent ``toolUse`` block, as task signal for the selection call.
|
|
485
|
+
|
|
486
|
+
There is no per-tool-call seam in ``ConversationManager`` (unlike LangChain's
|
|
487
|
+
``wrap_tool_call``): ``apply_management``/``reduce_context`` see the whole
|
|
488
|
+
history at once. The latest tool call is still worth sending as
|
|
489
|
+
``TaskSpec.tool_name`` — it is the strongest signal of what the *next* model
|
|
490
|
+
call is about.
|
|
491
|
+
"""
|
|
492
|
+
for message in reversed(messages):
|
|
493
|
+
if message.get("role") != "assistant":
|
|
494
|
+
continue
|
|
495
|
+
for block in reversed(message.get("content") or []):
|
|
496
|
+
if "toolUse" in block:
|
|
497
|
+
return dict(block["toolUse"])
|
|
498
|
+
return None
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
__all__ = [
|
|
502
|
+
"METADATA_KEY",
|
|
503
|
+
"DEFAULT_PLACEHOLDER",
|
|
504
|
+
"approx_tokens",
|
|
505
|
+
"tool_result_text",
|
|
506
|
+
"is_prunable_block",
|
|
507
|
+
"kind_for",
|
|
508
|
+
"record_id_for",
|
|
509
|
+
"build_records",
|
|
510
|
+
"latest_user_prompt",
|
|
511
|
+
"prior_user_prompts",
|
|
512
|
+
"rewrite_block",
|
|
513
|
+
"apply_selection",
|
|
514
|
+
"tool_call_keywords",
|
|
515
|
+
"latest_tool_use",
|
|
516
|
+
]
|