Skip to content

Commit 0f7ae94

Browse files
committed
Compatible with Claude API streaming output
1 parent 0bdeb6a commit 0f7ae94

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

st_engine/engine/request_processor.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,23 @@ def get_field_value(data: Dict[str, Any], path: str) -> Any:
6565
except (KeyError, IndexError, TypeError, ValueError):
6666
return ""
6767

68+
@staticmethod
69+
def is_sse_event_line(chunk_str: str) -> bool:
70+
"""Check if the line is an SSE event line (not data line) that should be skipped.
71+
Only skip event control lines, not data lines that start with 'data: '.
72+
"""
73+
chunk_str = chunk_str.strip()
74+
75+
# Check for SSE event control prefixes that should be skipped
76+
# Only 'event:', 'id:', 'retry:' are control lines, 'data:' contains actual data
77+
control_prefixes = ["event:", "event: ", "id:", "id: ", "retry:", "retry: "]
78+
79+
for prefix in control_prefixes:
80+
if chunk_str.startswith(prefix):
81+
return True
82+
83+
return False
84+
6885
@staticmethod
6986
def remove_chunk_prefix(chunk_str: str, field_mapping: FieldMapping) -> str:
7087
"""Remove prefix from chunk string based on field mapping configuration."""
@@ -120,6 +137,12 @@ def extract_metrics_from_chunk(
120137
)
121138

122139
if metrics.usage and isinstance(metrics.usage, dict):
140+
# has_prompt_tokens = any(
141+
# "prompt" in key and value not in (None, 0)
142+
# for key, value in metrics.usage.items()
143+
# if isinstance(value, (int, float))
144+
# )
145+
123146
has_completion_tokens = any(
124147
"completion" in key and value not in (None, 0)
125148
for key, value in metrics.usage.items()
@@ -131,6 +154,7 @@ def extract_metrics_from_chunk(
131154
for key, value in metrics.usage.items()
132155
if isinstance(value, (int, float))
133156
)
157+
134158
if has_completion_tokens and has_total_tokens:
135159
usage_extracted = True
136160

@@ -238,6 +262,9 @@ def process_stream_chunk(
238262
if not chunk_str:
239263
return False, None, metrics
240264

265+
if StreamProcessor.is_sse_event_line(chunk_str):
266+
return False, None, metrics
267+
241268
# Remove prefix if present
242269
processed_chunk = StreamProcessor.remove_chunk_prefix(chunk_str, field_mapping)
243270

0 commit comments

Comments
 (0)