(
messages: list[dict[str, Any]],
artifact_store: ArtifactStore,
policy: CompositionPolicy,
)
| 344 | |
| 345 | |
| 346 | def _compose_deterministic( |
| 347 | messages: list[dict[str, Any]], |
| 348 | artifact_store: ArtifactStore, |
| 349 | policy: CompositionPolicy, |
| 350 | ) -> CompositionResult: |
| 351 | rewritten: list[dict[str, Any]] = [] |
| 352 | artifact_ids: list[str] = [] |
| 353 | compacted_messages = 0 |
| 354 | offloaded_messages = 0 |
| 355 | input_before = 0 |
| 356 | |
| 357 | for idx, msg in enumerate(messages): |
| 358 | if not isinstance(msg, dict): |
| 359 | rewritten.append(msg) |
| 360 | continue |
| 361 | |
| 362 | content = msg.get("content") |
| 363 | text = _content_to_text(content) |
| 364 | if text is None: |
| 365 | rewritten.append(dict(msg)) |
| 366 | continue |
| 367 | |
| 368 | input_before += estimate_tokens(text) |
| 369 | new_msg = dict(msg) |
| 370 | compacted = _safe_compact_text(text) |
| 371 | |
| 372 | if msg.get("role") == "tool" and estimate_tokens(compacted) >= policy.tool_offload_threshold_tokens: |
| 373 | tool_call_id = str(msg.get("tool_call_id", "")) |
| 374 | tool_name = _infer_tool_name(messages, idx, tool_call_id) |
| 375 | content_type = "application/json" if _looks_like_json(compacted) else "text/plain" |
| 376 | record = artifact_store.store_text( |
| 377 | text, |
| 378 | kind="tool-result", |
| 379 | role="tool", |
| 380 | tool_name=tool_name, |
| 381 | tool_call_id=tool_call_id, |
| 382 | content_type=content_type, |
| 383 | ) |
| 384 | new_msg["content"] = _build_artifact_stub(compacted, record, policy) |
| 385 | artifact_ids.append(record.id) |
| 386 | offloaded_messages += 1 |
| 387 | elif msg.get("role") == "tool" and compacted != text: |
| 388 | new_msg["content"] = compacted |
| 389 | compacted_messages += 1 |
| 390 | elif isinstance(content, str): |
| 391 | if len(content) >= policy.inline_compact_threshold_chars and compacted != content: |
| 392 | new_msg["content"] = compacted |
| 393 | compacted_messages += 1 |
| 394 | |
| 395 | rewritten.append(new_msg) |
| 396 | |
| 397 | input_after = _estimate_messages_tokens(rewritten) |
| 398 | return CompositionResult( |
| 399 | messages=rewritten, |
| 400 | input_tokens_before=input_before, |
| 401 | input_tokens_after=input_after, |
| 402 | artifact_ids=artifact_ids, |
| 403 | compacted_messages=compacted_messages, |
no test coverage detected