|
6 | 6 | that combines the final result with the full conversation history. |
7 | 7 | """ |
8 | 8 |
|
| 9 | +import hashlib |
9 | 10 | import json |
10 | 11 | import sys |
11 | 12 |
|
| 13 | +_CONTENT_TRUNCATE = 2000 # chars to keep before truncating |
| 14 | + |
12 | 15 |
|
13 | 16 | def _extract_tool_uses(content): |
14 | 17 | """Extract tool_use entries from assistant message content.""" |
@@ -36,26 +39,39 @@ def _extract_text(content): |
36 | 39 | return out |
37 | 40 |
|
38 | 41 |
|
| 42 | +def _truncate_content(text: str) -> dict: |
| 43 | + """Return content dict, truncating if over limit with sha256 + length.""" |
| 44 | + if len(text) <= _CONTENT_TRUNCATE: |
| 45 | + return {"content": text} |
| 46 | + sha = hashlib.sha256(text.encode()).hexdigest() |
| 47 | + return { |
| 48 | + "content": text[:_CONTENT_TRUNCATE], |
| 49 | + "truncated": True, |
| 50 | + "total_length": len(text), |
| 51 | + "sha256": sha, |
| 52 | + } |
| 53 | + |
| 54 | + |
39 | 55 | def _extract_tool_results(content): |
40 | 56 | """Extract tool_result entries from user message content.""" |
41 | 57 | out = [] |
42 | 58 | for block in content: |
43 | 59 | if block.get("type") != "tool_result": |
44 | 60 | continue |
45 | | - entry = { |
46 | | - "type": "tool_result", |
47 | | - "tool_use_id": block.get("tool_use_id", ""), |
48 | | - "is_error": block.get("is_error", False), |
49 | | - } |
50 | 61 | raw = block.get("content", "") |
51 | 62 | if isinstance(raw, str): |
52 | | - entry["content"] = raw |
| 63 | + text = raw |
53 | 64 | elif isinstance(raw, list): |
54 | | - # content can be a list of blocks |
55 | 65 | texts = [b.get("text", "") for b in raw if b.get("type") == "text"] |
56 | | - entry["content"] = "\n".join(texts) if texts else str(raw) |
| 66 | + text = "\n".join(texts) if texts else str(raw) |
57 | 67 | else: |
58 | | - entry["content"] = str(raw) |
| 68 | + text = str(raw) |
| 69 | + entry = { |
| 70 | + "type": "tool_result", |
| 71 | + "tool_use_id": block.get("tool_use_id", ""), |
| 72 | + "is_error": block.get("is_error", False), |
| 73 | + **_truncate_content(text), |
| 74 | + } |
59 | 75 | out.append(entry) |
60 | 76 | return out |
61 | 77 |
|
|
0 commit comments