| 209 | |
| 210 | |
| 211 | async def compose_messages_semantic( |
| 212 | messages: list[dict[str, Any]], |
| 213 | artifact_store: ArtifactStore, |
| 214 | policy: CompositionPolicy | None = None, |
| 215 | *, |
| 216 | semantic_compressor: SemanticCompressor | None = None, |
| 217 | session_id: str | None = None, |
| 218 | request: Any = None, |
| 219 | step_type: str = "general", |
| 220 | is_agentic: bool = False, |
| 221 | ) -> CompositionResult: |
| 222 | policy = policy or CompositionPolicy() |
| 223 | base = _compose_deterministic(messages, artifact_store, policy) |
| 224 | rewritten = [dict(msg) if isinstance(msg, dict) else msg for msg in base.messages] |
| 225 | artifact_ids = list(base.artifact_ids) |
| 226 | compacted_messages = base.compacted_messages |
| 227 | offloaded_messages = base.offloaded_messages |
| 228 | semantic_summaries = 0 |
| 229 | checkpoint_created = False |
| 230 | rehydrated_artifacts = 0 |
| 231 | semantic_calls = 0 |
| 232 | semantic_failures = 0 |
| 233 | semantic_quality_fallbacks = 0 |
| 234 | semantic_estimated_cost = 0.0 |
| 235 | semantic_actual_cost = 0.0 |
| 236 | |
| 237 | latest_user_prompt = _latest_user_text(rewritten) |
| 238 | |
| 239 | if semantic_compressor: |
| 240 | for idx, msg in enumerate(rewritten): |
| 241 | if not isinstance(msg, dict) or msg.get("role") != "tool": |
| 242 | continue |
| 243 | content = msg.get("content") |
| 244 | if not isinstance(content, str) or "artifact://" not in content: |
| 245 | continue |
| 246 | artifact_id = _extract_artifact_id(content) |
| 247 | if not artifact_id: |
| 248 | continue |
| 249 | artifact = artifact_store.get(artifact_id) |
| 250 | if artifact is None: |
| 251 | continue |
| 252 | if artifact.get("token_estimate", 0) < policy.semantic_tool_summary_threshold_tokens: |
| 253 | continue |
| 254 | summary = artifact.get("summary", "") |
| 255 | if not summary: |
| 256 | tool_name = str(artifact.get("tool_name", "")) |
| 257 | call = await semantic_compressor.summarize_tool_result( |
| 258 | artifact["content"], |
| 259 | tool_name=tool_name, |
| 260 | latest_user_prompt=latest_user_prompt, |
| 261 | request=request, |
| 262 | ) |
| 263 | semantic_calls += 1 |
| 264 | if call is None: |
| 265 | semantic_failures += 1 |
| 266 | else: |
| 267 | summary = call.text.strip() |
| 268 | semantic_estimated_cost += call.estimated_cost |