Repository navigation
Expand file tree
/
Copy pathbedrock_client.py
More file actions
172 lines (158 loc) · 7.63 KB
/
Copy pathbedrock_client.py
File metadata and controls
172 lines (158 loc) · 7.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
from typing import List
from langchain.schema import HumanMessage
from langchain_aws import ChatBedrock
from logger import logger
class BedrockClient:
def __init__(
self,
model_id: str,
region_name: str = "us-west-2",
chunk_size: int = 300_000,
max_context_chars: int = 5_000_000,
):
"""
Initialize Bedrock Chat client.
:param model_id: Bedrock model ID (Claude, etc.)
:param region_name: AWS region
:param chunk_size: Max characters per chunk
:param max_context_chars: Maximum safe context length for reduce step
"""
self.client = ChatBedrock(model_id=model_id, region_name=region_name)
self.chunk_size = chunk_size
self.max_context_chars = max_context_chars
def _chunk_messages(self, messages: List[str]) -> List[str]:
"""
Break messages into character-bounded chunks.
"""
chunks = []
current_chunk = ""
for msg in messages:
if len(current_chunk) + len(msg) + 2 > self.chunk_size:
chunks.append(current_chunk)
current_chunk = msg
else:
current_chunk += ("\n\n" if current_chunk else "") + msg
if current_chunk:
chunks.append(current_chunk)
return chunks
def _analyze_chunk(self, chunk: str, idx: int, total: int) -> str:
"""
Summarize a single chunk with a strong, detailed RCA/QA prompt.
"""
prompt = (
"You are a world-class Staff SDET specializing in distributed systems, "
"database internals, control plane, infrastructure testing and reliability. "
"Analyze the following Slack thread chunk and produce a **detailed, structured analysis**.\n\n"
f"Chunk {idx}/{total}:\n{chunk}\n\n"
"Return output in the following Markdown structure:\n\n"
"### 1. Root Cause Analysis (RCA)\n"
"- Explain the precise technical causes, contributing factors, cascading effects, and context.\n"
"- Be specific and avoid vague statements.\n\n"
"### 2. Developer Learnings / Improvements / Action Items\n"
"- Provide actionable, technical improvements.\n"
"- Use a numbered Markdown list.\n\n"
"### 3. QA Learnings / Improvements / Action Items\n"
"- Provide concrete QA learnings and Action items.\n"
"- Use a numbered Markdown list.\n\n"
"⚠️ Important Instructions:\n"
"- Do not repeat points in different words.\n"
"- Output must be detailed but **crisp and high-signal only**.\n"
"- Do not summarize the Slack messages — only return analysis."
)
try:
response = self.client.invoke([HumanMessage(content=prompt)])
return getattr(response, "content", "").strip()
except Exception as e:
logger.error(f"Bedrock chunk analysis failed (chunk {idx}/{total}): {e}")
return ""
def _merge_summaries(self, summaries: List[str]) -> str:
"""
Merge multiple intermediate summaries into a final deduplicated RCA/QA report.
Uses multi-level reduce if summaries are too long.
"""
if not summaries:
return ""
# Multi-level reduce: process in batches if combined size exceeds limit
while (
sum(len(s) for s in summaries) > self.max_context_chars
and len(summaries) > 1
):
logger.info(
"Intermediate summaries too large, applying multi-level reduce..."
)
new_summaries = []
for i in range(0, len(summaries), 3): # batch reduce in groups of 3
batch = summaries[i : i + 3]
prompt = (
"You are a world-class Staff SDET. Merge the following partial analyses "
"into a single, **deduplicated** report:\n\n"
f"{chr(10).join(batch)}\n\n"
"Return output in this exact structure:\n"
"### 1. Root Cause Analysis (RCA)\n"
"### 2. Developer Learnings / Improvements / Action Items\n"
"### 3. QA Learnings / Improvements / Action Items\n\n"
"⚠️ Instructions: Eliminate redundancy, do not rephrase the same points, "
"and keep only unique, high-signal insights."
)
try:
response = self.client.invoke([HumanMessage(content=prompt)])
merged = getattr(response, "content", "").strip()
if merged:
new_summaries.append(merged)
except Exception as e:
logger.error(f"Bedrock batch reduce failed: {e}")
summaries = new_summaries or summaries # fallback to old if failed
# Final reduce
combined_prompt = (
"You are a world-class Staff SDET specializing in distributed systems, "
"database internals, control plane, infrastructure testing and reliability. "
"The following are **partial analyses** from multiple chunks of a Slack thread. "
"Your job is to produce a **final, unified, deduplicated report**.\n\n"
"Partial Summaries:\n"
f"{chr(10).join(summaries)}\n\n"
"Final output must strictly follow this Markdown structure:\n\n"
"### 1. Root Cause Analysis (RCA)\n"
"- Single, unified RCA covering all chunks.\n"
"- Include root causes, contributing factors, cascading failures, and missing safeguards.\n\n"
"### 2. Developer Learnings / Improvements / Action Items\n"
"- Deduplicated list of actionable developer improvements and/or Action items.\n"
"- Remove repeated or rephrased items.\n"
"- Use a numbered Markdown list.\n\n"
"### 3. QA Learnings / Improvements / Action Items\n"
"- Deduplicated list of QA learnings and/or Action items.\n"
"- Remove repeated or rephrased items.\n"
"- Use a numbered Markdown list.\n\n"
"⚠️ Important:\n"
"- Eliminate redundancy across chunks.\n"
"- Do not restate Slack text.\n"
"- Keep output detailed but crisp."
)
try:
response = self.client.invoke([HumanMessage(content=combined_prompt)])
return getattr(response, "content", "").strip()
except Exception as e:
logger.error(f"Bedrock final reduce failed: {e}")
return "\n".join(summaries)
def summarize(self, messages: List[str]) -> str:
"""
Main entry: Summarize messages into final RCA/QA learnings.
"""
try:
chunks = self._chunk_messages(messages)
logger.info("Processing %s chunks...", len(chunks))
intermediate_summaries = []
for i, chunk in enumerate(chunks):
logger.info("Analyzing chunk %s/%s", i + 1, len(chunks))
summary = self._analyze_chunk(chunk, i + 1, len(chunks))
if summary:
intermediate_summaries.append(summary)
if not intermediate_summaries:
logger.warning("No intermediate summaries generated.")
return ""
final_summary = self._merge_summaries(intermediate_summaries)
if not final_summary:
logger.warning("Final Bedrock summary is empty")
return final_summary
except Exception as e:
logger.error(f"Bedrock RCA generation failed: {e}")
return ""