Fix SSE parsing: read data: prefix + contentBlockDelta.delta.text

This commit is contained in:
daniel
2026-05-07 16:45:58 -05:00
parent cc3b448291
commit beb8dfc969
2 changed files with 131 additions and 18 deletions

View File

@@ -204,26 +204,38 @@ def handler(event, context):
body = response.get('response')
text_buffer = ''
leftover = ''
if body is not None:
for chunk in body.iter_chunks():
if not chunk:
for raw_chunk in body.iter_chunks():
if not raw_chunk:
continue
try:
event = json.loads(chunk.decode('utf-8'))
# Strands streaming event: 'data' field contains text delta
delta = event.get('data', '') or event.get('text', '')
if delta:
text_buffer += delta
# Flush on paragraph or sentence break, or if buffer is large
flush = (
text_buffer.rstrip().endswith(('\n\n', '.\n', '!\n', '?\n'))
or len(text_buffer) > 800
)
if flush and text_buffer.strip():
send_telegram_direct(str(chat_id), bot_token, text_buffer.strip())
text_buffer = ''
except (json.JSONDecodeError, UnicodeDecodeError):
pass
# AgentCore streams SSE format: "data: {...}\n\n"
text = leftover + raw_chunk.decode('utf-8', errors='replace')
parts = text.split('\n\n')
leftover = parts[-1]
for part in parts[:-1]:
for line in part.splitlines():
if not line.startswith('data: '):
continue
data = line[6:].strip()
if not data or data == '[DONE]':
continue
try:
event = json.loads(data)
except (json.JSONDecodeError, ValueError):
continue
# Extract text delta from contentBlockDelta
delta = event.get('event', {}).get('contentBlockDelta', {}).get('delta', {})
token = delta.get('text', '') or event.get('data', '')
if token:
text_buffer += token
flush = (
text_buffer.rstrip().endswith(('\n\n', '.\n', '!\n', '?\n'))
or len(text_buffer) > 800
)
if flush and text_buffer.strip():
send_telegram_direct(str(chat_id), bot_token, text_buffer.strip())
text_buffer = ''
# Flush any remaining text
if text_buffer.strip() and bot_token: