-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function_alb.py
More file actions
1060 lines (898 loc) · 39.8 KB
/
Copy pathlambda_function_alb.py
File metadata and controls
1060 lines (898 loc) · 39.8 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
AWS Lambda function entry point for Bedrock API service
"""
import json
import logging
import time
import uuid
from datetime import datetime
from typing import Dict, Any, Iterator
from services.authentication_handler import AuthenticationHandler
from services.request_parser import RequestParser
from services.image_processor import ImageProcessor
from services.bedrock_client import BedrockClient
from services.response_formatter import ResponseFormatter
from services.stream_handler import StreamHandler
from services.error_handler import ErrorHandler
from utils.logging_utils import setup_logging, StructuredLogger, MonitoringCollector
from config import Config
# 设置结构化日志记录
setup_logging(Config.LOG_LEVEL)
# 创建结构化日志记录器
logger = StructuredLogger("lambda_handler")
# 创建监控收集器(全局实例,在Lambda容器重用时保持状态)
monitoring_collector = MonitoringCollector() if Config.ENABLE_METRICS_COLLECTION else None
# Initialize service components (reuse across invocations)
auth_handler = AuthenticationHandler(
secret_name=Config.API_KEYS_SECRET_NAME,
region_name=Config.AWS_REGION
)
request_parser = RequestParser()
image_processor = ImageProcessor(bucket_name=Config.S3_BUCKET)
bedrock_client = BedrockClient(region=Config.BEDROCK_REGION)
response_formatter = ResponseFormatter()
stream_handler = StreamHandler()
error_handler = ErrorHandler()
def parse_event_format(event):
"""
解析事件格式,支持ALB、API Gateway v1.0和v2.0
"""
# API Gateway v2.0 format
if 'requestContext' in event and 'http' in event.get('requestContext', {}):
return {
'http_method': event['requestContext']['http']['method'],
'path': event.get('rawPath', ''),
'headers': event.get('headers', {}),
'body': event.get('body', ''),
'is_base64_encoded': event.get('isBase64Encoded', False),
'source_ip': event.get('requestContext', {}).get('http', {}).get('sourceIp', 'unknown'),
'user_agent': event.get('headers', {}).get('user-agent', 'unknown')
}
# ALB or API Gateway v1.0 format
else:
return {
'http_method': event.get('httpMethod', ''),
'path': event.get('path', ''),
'headers': event.get('headers', {}),
'body': event.get('body', ''),
'is_base64_encoded': event.get('isBase64Encoded', False),
'source_ip': event.get('requestContext', {}).get('identity', {}).get('sourceIp', 'unknown'),
'user_agent': event.get('headers', {}).get('User-Agent', 'unknown')
}
def lambda_handler(event: Dict[str, Any], context: Any) -> Dict[str, Any]:
"""
Lambda function entry point for handling HTTP requests
Args:
event: Lambda event containing HTTP request data
context: Lambda context object
Returns:
HTTP response dictionary or streaming response
"""
# 生成请求ID用于跟踪
request_id = str(uuid.uuid4())
start_time = time.time()
# 解析事件格式
parsed_event = parse_event_format(event)
# 确定是否为流式请求(用于性能跟踪)
is_streaming = False
try:
body = json.loads(event.get('body', '{}')) if event.get('body') else {}
is_streaming = body.get('stream', False)
except:
pass
# 开始请求跟踪
metrics = logger.start_request_tracking(
request_id=request_id,
is_streaming=is_streaming,
model_name=Config.BEDROCK_MODEL_ID
)
try:
# 记录请求信息
logger.log_request(
event=event,
request_id=request_id,
enable_request_logging=Config.ENABLE_REQUEST_LOGGING
)
# 1. Handle CORS preflight requests
if event.get('httpMethod') == 'OPTIONS':
response = _create_cors_response()
logger.log_response(
status_code=response['statusCode'],
response_size=len(response.get('body', '')),
request_id=request_id
)
return response
# 2. Handle health check endpoint
# Use parsed event data
path = parsed_event['path']
http_method = parsed_event['http_method']
# Health check endpoint for ALB and API Gateway
if path == '/health' or path.endswith('/health'):
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
},
'body': json.dumps({
'status': 'healthy',
'timestamp': datetime.utcnow().isoformat() + 'Z',
'service': 'bedrock-api-service'
})
}
# 3. Validate HTTP method and path for API endpoints
if http_method != 'POST':
error_response = error_handler.handle_validation_error("Only POST method is supported")
logger.log_error(
error=ValueError("Invalid HTTP method"),
context={"method": http_method},
request_id=request_id,
error_phase="method_validation"
)
return error_response
if not path.endswith('/v1/mllm/completions'):
error_response = error_handler.handle_validation_error("Invalid endpoint. Use /v1/mllm/completions")
logger.log_error(
error=ValueError("Invalid endpoint"),
context={"path": path},
request_id=request_id,
error_phase="path_validation"
)
return error_response
# 3. API Key authentication
auth_start = time.time()
auth_header = event.get('headers', {}).get('Authorization') or event.get('headers', {}).get('authorization')
auth_result = auth_handler.validate_api_key(auth_header)
auth_duration = (time.time() - auth_start) * 1000
logger.log_performance_phase(
phase="auth",
duration_ms=auth_duration,
request_id=request_id,
additional_info={"success": auth_result.is_valid}
)
if not auth_result.is_valid:
logger.log_authentication(
success=False,
error_message=auth_result.error_message,
request_id=request_id
)
error_response = error_handler.handle_authentication_error(auth_result.error_message)
return error_response
logger.log_authentication(
success=True,
api_key_id=auth_result.api_key_id,
request_id=request_id
)
# 4. Parse and validate request
parsing_start = time.time()
try:
parsed_request = request_parser.parse_request(event)
except ValueError as e:
logger.log_error(
error=e,
context={"body": event.get('body', '')[:500]}, # 限制日志大小
request_id=request_id,
error_phase="request_parsing"
)
return error_handler.handle_validation_error(str(e))
validation_result = request_parser.validate_request(parsed_request)
parsing_duration = (time.time() - parsing_start) * 1000
logger.log_performance_phase(
phase="parsing",
duration_ms=parsing_duration,
request_id=request_id,
additional_info={
"model": parsed_request.model,
"stream": parsed_request.stream,
"message_count": len(parsed_request.messages)
}
)
if not validation_result.is_valid:
logger.log_error(
error=ValueError(validation_result.error_message),
context={"validation_errors": validation_result.error_message},
request_id=request_id,
error_phase="request_validation"
)
return error_handler.handle_validation_error(validation_result.error_message)
# 5. Process images in messages
image_processing_start = time.time()
image_count = 0
total_image_size = 0
try:
processed_request = _process_images_in_request(parsed_request, request_id)
# 统计图像信息
for message in processed_request.messages:
for content in message.content:
if content.type == 'image' and content.image_base64:
image_count += 1
# 估算base64图像大小
total_image_size += len(content.image_base64) * 3 // 4 # base64解码后的大小
except Exception as e:
logger.log_error(
error=e,
context={"image_count": image_count},
request_id=request_id,
error_phase="image_processing"
)
return error_handler.handle_validation_error(f"Image processing failed: {str(e)}")
image_processing_duration = (time.time() - image_processing_start) * 1000
if image_count > 0:
logger.log_image_processing(
image_count=image_count,
total_size_bytes=total_image_size,
processing_duration_ms=image_processing_duration,
request_id=request_id
)
logger.log_performance_phase(
phase="image_processing",
duration_ms=image_processing_duration,
request_id=request_id,
additional_info={
"image_count": image_count,
"total_image_size_bytes": total_image_size
}
)
# 6. Convert to Bedrock format
try:
bedrock_request = bedrock_client.format_bedrock_request(processed_request)
except Exception as e:
logger.log_error(
error=e,
context={"model": parsed_request.model},
request_id=request_id,
error_phase="bedrock_formatting"
)
return error_handler.handle_internal_error(e)
# 7. Route to streaming or non-streaming processing using ALB handler
from services.alb_response_handler import ALBResponseHandler
if parsed_request.stream:
return ALBResponseHandler.handle_streaming_request(bedrock_request, parsed_request.meta, start_time, request_id)
else:
return ALBResponseHandler.handle_non_streaming_request(bedrock_request, parsed_request.meta, start_time, request_id)
except Exception as e:
logger.log_error(
error=e,
context={"event_path": event.get('path'), "event_method": event.get('httpMethod')},
request_id=request_id,
error_phase="lambda_handler"
)
return error_handler.handle_internal_error(e)
finally:
# 完成请求跟踪并收集指标
final_metrics = logger.finish_request_tracking(request_id)
if final_metrics and monitoring_collector:
monitoring_collector.add_metrics(final_metrics)
# 定期记录汇总统计
if len(monitoring_collector.metrics) % Config.METRICS_SUMMARY_INTERVAL == 0:
monitoring_collector.log_periodic_summary()
def _create_cors_response() -> Dict[str, Any]:
"""Create CORS preflight response"""
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400'
},
'body': ''
}
def _process_images_in_request(parsed_request, request_id: str):
"""Process images in the request messages"""
processed_messages = []
for message in parsed_request.messages:
processed_content = []
for content in message.content:
if content.type == 'image':
# Process image content
try:
# Determine if this is a path or base64 data
image_data = content.image_base64
# More robust detection using multiple heuristics
def is_base64_data(data):
"""Check if data appears to be base64 encoded"""
if len(data) < 50: # Base64 images are typically much longer
return False
# Check for base64 characteristics
import re
# Base64 pattern: only contains A-Z, a-z, 0-9, +, /, = and proper padding
base64_pattern = re.compile(r'^[A-Za-z0-9+/]*={0,2}$')
if not base64_pattern.match(data):
return False
# Check length is multiple of 4 (base64 requirement)
if len(data) % 4 != 0:
return False
# Try to decode a small portion to verify it's valid base64
try:
import base64
base64.b64decode(data[:100]) # Test first 100 chars
return True
except:
return False
def is_file_path(data):
"""Check if data appears to be a file path"""
if len(data) > 500: # File paths are typically short
return False
# Check for path characteristics
path_indicators = [
data.startswith('/'),
data.startswith('./'),
data.startswith('../'),
data.startswith('~'),
(len(data) > 2 and data[1] == ':'), # Windows paths
'.' in data and data.count('.') <= 3, # Has extension
]
return any(path_indicators) and not is_base64_data(data)
if is_file_path(image_data):
# This looks like a file path
logger.log_structured("image_processing", {
"request_id": request_id,
"type": "file_path",
"path_length": len(image_data)
})
processed_image = image_processor.process_image_content({
'image_path': image_data
})
else:
# This is base64 data
logger.log_structured("image_processing", {
"request_id": request_id,
"type": "base64",
"data_length": len(image_data)
})
processed_image = image_processor.process_image_content({
'image_base64': image_data
})
# Update content with processed image data
content.image_base64 = processed_image.base64_data
# 使用结构化日志记录图像处理详情
logger.log_structured("image_processed", {
"request_id": request_id,
"media_type": processed_image.media_type,
"size_bytes": processed_image.size_bytes,
"width": processed_image.width,
"height": processed_image.height
})
except Exception as e:
raise ValueError(f"Image processing failed: {str(e)}")
processed_content.append(content)
message.content = processed_content
processed_messages.append(message)
parsed_request.messages = processed_messages
return parsed_request
def _handle_non_streaming_request(bedrock_request, meta, start_time, request_id: str) -> Dict[str, Any]:
"""
Handle non-streaming request processing
完整的非流式请求处理管道:
1. 调用Bedrock API获取响应
2. 格式化响应为目标API格式
3. 计算性能指标
4. 返回JSON响应
5. 处理各种错误情况并返回适当的HTTP状态码
Args:
bedrock_request: 格式化后的Bedrock请求
meta: 请求元数据
start_time: 请求开始时间(用于性能计算)
Returns:
HTTP响应字典,包含状态码、头部和响应体
"""
try:
logger.log_structured("non_streaming_request_start", {
"request_id": request_id,
"model": getattr(bedrock_request, 'model', 'unknown')
})
# 调用Bedrock API
bedrock_start = time.time()
bedrock_response = bedrock_client.invoke_model(bedrock_request)
bedrock_duration = (time.time() - bedrock_start) * 1000
# 提取响应内容用于统计
response_content = response_formatter.extract_content_from_bedrock_response(bedrock_response)
response_tokens = len(response_content.split()) if response_content else 0
# 记录Bedrock调用信息
logger.log_bedrock_call(
model_name=Config.BEDROCK_MODEL_ID,
response_tokens=response_tokens,
duration_ms=bedrock_duration,
request_id=request_id,
is_streaming=False
)
logger.log_performance_phase(
phase="bedrock_call",
duration_ms=bedrock_duration,
request_id=request_id,
additional_info={
"response_length": len(response_content),
"estimated_tokens": response_tokens
}
)
# 格式化响应
formatting_start = time.time()
formatted_response = response_formatter.format_non_streaming_response(
bedrock_response=bedrock_response,
meta=meta,
start_time=start_time
)
formatting_duration = (time.time() - formatting_start) * 1000
logger.log_performance_phase(
phase="response_formatting",
duration_ms=formatting_duration,
request_id=request_id
)
# 计算总处理时间
total_time = time.time() - start_time
# 准备响应
response_body = json.dumps(formatted_response, ensure_ascii=False)
response_size = len(response_body.encode('utf-8'))
# 记录响应信息
logger.log_response(
status_code=200,
response_size=response_size,
request_id=request_id,
is_streaming=False
)
logger.log_structured("non_streaming_request_completed", {
"request_id": request_id,
"total_duration_ms": round(total_time * 1000, 2),
"response_size_bytes": response_size,
"response_tokens": response_tokens
})
# 返回成功响应
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Cache-Control': 'no-cache'
},
'body': response_body
}
except Exception as e:
logger.log_error(
error=e,
context={"model": getattr(bedrock_request, 'model', 'unknown')},
request_id=request_id,
error_phase="non_streaming_processing"
)
# 详细的错误分类和处理
return _handle_non_streaming_error(e, start_time, request_id)
def _handle_non_streaming_error(error: Exception, start_time: float, request_id: str) -> Dict[str, Any]:
"""
处理非流式请求的错误情况
根据错误类型返回适当的HTTP状态码和错误信息:
- Bedrock服务错误: 502 Bad Gateway
- 超时错误: 504 Gateway Timeout
- 速率限制: 429 Too Many Requests
- 访问拒绝: 403 Forbidden
- 其他错误: 500 Internal Server Error
Args:
error: 发生的异常
start_time: 请求开始时间
Returns:
HTTP错误响应字典
"""
error_str = str(error).lower()
total_time = time.time() - start_time
# 根据错误内容确定错误类型和状态码
if any(keyword in error_str for keyword in ['bedrock', 'invoke_model', 'anthropic']):
status_code = 502
error_type = 'bedrock_error'
error_message = 'Bedrock服务暂时不可用,请稍后重试'
elif any(keyword in error_str for keyword in ['timeout', 'timed out', 'deadline']):
status_code = 504
error_type = 'timeout_error'
error_message = '请求超时,请稍后重试'
elif any(keyword in error_str for keyword in ['throttling', 'rate limit', 'too many requests']):
status_code = 429
error_type = 'rate_limit_error'
error_message = '请求频率过高,请稍后重试'
elif any(keyword in error_str for keyword in ['access denied', 'unauthorized', 'forbidden']):
status_code = 403
error_type = 'access_denied_error'
error_message = '访问被拒绝,请检查权限配置'
elif any(keyword in error_str for keyword in ['validation', 'invalid', 'bad request']):
status_code = 400
error_type = 'validation_error'
error_message = f'请求验证失败: {str(error)}'
else:
status_code = 500
error_type = 'internal_error'
error_message = '内部服务器错误,请稍后重试'
# 记录错误详情
logger.log_structured("non_streaming_error", {
"request_id": request_id,
"error_type": error_type,
"status_code": status_code,
"processing_time_ms": round(total_time * 1000, 2),
"error_message": str(error)
}, level="error")
# 构建错误响应
error_response = {
'error': {
'type': error_type,
'message': error_message,
'code': status_code,
'timestamp': int(time.time()),
'processing_time_ms': round(total_time * 1000, 2),
'request_id': request_id
}
}
response_body = json.dumps(error_response, ensure_ascii=False)
response_size = len(response_body.encode('utf-8'))
# 记录错误响应
logger.log_response(
status_code=status_code,
response_size=response_size,
request_id=request_id,
is_streaming=False
)
return {
'statusCode': status_code,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Cache-Control': 'no-cache'
},
'body': response_body
}
def _handle_streaming_request(bedrock_request, meta, start_time, request_id: str) -> Dict[str, Any]:
"""
Handle streaming request processing
完整的流式请求处理管道:
1. 调用Bedrock API获取流式响应
2. 集成SSE流式响应生成
3. 处理流式响应的错误情况和中断
4. 返回Server-Sent Events格式的流式响应
Args:
bedrock_request: 格式化后的Bedrock请求
meta: 请求元数据
start_time: 请求开始时间(用于性能计算)
Returns:
HTTP流式响应字典,包含状态码、头部和流式响应生成器
"""
try:
logger.log_structured("streaming_request_start", {
"request_id": request_id,
"model": getattr(bedrock_request, 'model', 'unknown')
})
# 记录流式请求详情
logger.log_structured("streaming_generator_setup", {
"request_id": request_id
})
# 创建流式响应生成器
def stream_generator():
"""
流式响应生成器
生成Server-Sent Events格式的流式响应:
1. 发送初始流开始标记
2. 处理Bedrock流式响应块
3. 格式化为SSE格式
4. 处理错误和中断情况
5. 发送流结束标记
"""
chunk_count = 0
total_content_length = 0
try:
logger.log_structured("streaming_generation_start", {
"request_id": request_id
})
# 发送流开始标记
start_chunk = stream_handler.create_stream_start_chunk(
model=Config.BEDROCK_MODEL_ID,
meta=meta
)
yield start_chunk
logger.log_structured("stream_start_sent", {
"request_id": request_id
})
# 获取Bedrock流式响应
bedrock_stream_start = time.time()
bedrock_stream = bedrock_client.invoke_model_stream(bedrock_request)
logger.log_structured("bedrock_stream_started", {
"request_id": request_id,
"setup_duration_ms": round((time.time() - bedrock_stream_start) * 1000, 2)
})
# 创建格式化的流生成器
formatted_stream = stream_handler.create_streaming_response_generator(
bedrock_stream=bedrock_stream,
response_formatter=response_formatter,
meta=meta,
model=Config.BEDROCK_MODEL_ID,
start_time=start_time
)
# 处理每个流式响应块
for formatted_chunk in formatted_stream:
chunk_count += 1
# 统计内容长度
if 'choices' in formatted_chunk and formatted_chunk['choices']:
content = formatted_chunk['choices'][0].get('delta', {}).get('content', '')
total_content_length += len(content)
# 转换为SSE格式并发送
sse_chunk = stream_handler.format_sse_chunk(formatted_chunk)
yield sse_chunk
# 定期记录进度
if chunk_count % 20 == 0: # 减少日志频率
logger.log_structured("streaming_progress", {
"request_id": request_id,
"chunks_processed": chunk_count,
"content_length": total_content_length,
"elapsed_ms": round((time.time() - start_time) * 1000, 2)
})
# 发送流结束标记
yield stream_handler.create_stream_end_chunk()
# 记录流式处理完成
total_time = time.time() - start_time
estimated_tokens = total_content_length // 4 # 粗略估算令牌数
# 记录Bedrock流式调用信息
logger.log_bedrock_call(
model_name=Config.BEDROCK_MODEL_ID,
response_tokens=estimated_tokens,
duration_ms=total_time * 1000,
request_id=request_id,
is_streaming=True
)
logger.log_structured("streaming_completed", {
"request_id": request_id,
"chunk_count": chunk_count,
"content_length": total_content_length,
"estimated_tokens": estimated_tokens,
"total_duration_ms": round(total_time * 1000, 2)
})
# 记录响应信息
logger.log_response(
status_code=200,
response_size=total_content_length,
request_id=request_id,
is_streaming=True,
chunk_count=chunk_count
)
except Exception as e:
logger.log_error(
error=e,
context={
"chunks_processed": chunk_count,
"content_length": total_content_length
},
request_id=request_id,
error_phase="streaming_generation"
)
# 通过流发送错误信息
try:
for error_chunk in stream_handler.handle_stream_error(
error=e,
model=Config.BEDROCK_MODEL_ID,
meta=meta
):
yield error_chunk
# 记录错误处理完成
total_time = time.time() - start_time
logger.log_structured("streaming_error_handled", {
"request_id": request_id,
"chunks_processed": chunk_count,
"total_duration_ms": round(total_time * 1000, 2),
"error_type": type(e).__name__
}, level="error")
except Exception as error_handling_error:
logger.log_error(
error=error_handling_error,
context={"original_error": str(e)},
request_id=request_id,
error_phase="streaming_error_handling"
)
# 发送最基本的错误响应
yield stream_handler.create_error_sse_chunk(
error_message="流式响应处理失败",
error_code=500
)
yield stream_handler.create_stream_end_chunk()
# 返回流式响应
logger.log_structured("streaming_response_configured", {
"request_id": request_id
})
return {
'statusCode': 200,
'headers': {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'X-Accel-Buffering': 'no' # 禁用nginx缓冲以支持真正的流式传输
},
'body': _generate_pseudo_streaming_response(bedrock_request, meta, start_time, request_id),
'isBase64Encoded': False
}
except Exception as e:
logger.log_error(
error=e,
context={"model": getattr(bedrock_request, 'model', 'unknown')},
request_id=request_id,
error_phase="streaming_setup"
)
# 如果流式设置失败,返回标准错误响应
return _handle_streaming_setup_error(e, start_time, request_id)
def _handle_streaming_setup_error(error: Exception, start_time: float, request_id: str) -> Dict[str, Any]:
"""
处理流式请求设置阶段的错误
当流式响应设置失败时,返回标准的JSON错误响应而不是流式响应
Args:
error: 发生的异常
start_time: 请求开始时间
Returns:
HTTP错误响应字典
"""
error_str = str(error).lower()
total_time = time.time() - start_time
# 根据错误内容确定错误类型和状态码
if any(keyword in error_str for keyword in ['bedrock', 'invoke_model_stream', 'anthropic']):
status_code = 502
error_type = 'bedrock_streaming_error'
error_message = 'Bedrock流式服务暂时不可用,请稍后重试'
elif any(keyword in error_str for keyword in ['timeout', 'timed out', 'deadline']):
status_code = 504
error_type = 'streaming_timeout_error'
error_message = '流式请求超时,请稍后重试'
elif any(keyword in error_str for keyword in ['throttling', 'rate limit', 'too many requests']):
status_code = 429
error_type = 'streaming_rate_limit_error'
error_message = '流式请求频率过高,请稍后重试'
elif any(keyword in error_str for keyword in ['access denied', 'unauthorized', 'forbidden']):
status_code = 403
error_type = 'streaming_access_denied_error'
error_message = '流式服务访问被拒绝,请检查权限配置'
else:
status_code = 500
error_type = 'streaming_internal_error'
error_message = '流式服务内部错误,请稍后重试'
# 记录错误详情
logger.log_structured("streaming_setup_error", {
"request_id": request_id,
"error_type": error_type,
"status_code": status_code,
"processing_time_ms": round(total_time * 1000, 2),
"error_message": str(error)
}, level="error")
# 构建错误响应
error_response = {
'error': {
'type': error_type,
'message': error_message,
'code': status_code,
'timestamp': int(time.time()),
'processing_time_ms': round(total_time * 1000, 2),
'stream_support': False,
'request_id': request_id
}
}
response_body = json.dumps(error_response, ensure_ascii=False)
response_size = len(response_body.encode('utf-8'))
# 记录错误响应
logger.log_response(
status_code=status_code,
response_size=response_size,
request_id=request_id,
is_streaming=False
)
return {
'statusCode': status_code,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Cache-Control': 'no-cache'
},
'body': response_body
}
def _generate_pseudo_streaming_response(bedrock_request, meta, start_time, request_id: str) -> str:
"""
生成伪流式响应内容
这个函数会:
1. 调用Bedrock获取完整响应
2. 将响应内容分解成多个块
3. 格式化为SSE格式
4. 模拟流式输出体验
Args:
bedrock_request: Bedrock请求对象
meta: 请求元数据
start_time: 请求开始时间
request_id: 请求ID
Returns:
完整的SSE格式响应字符串
"""
try:
logger.log_structured("pseudo_streaming_generation_start", {
"request_id": request_id,
"note": "Generating pseudo-streaming response for ALB"
})
# 1. 获取Bedrock完整响应
bedrock_response = bedrock_client.invoke_model(bedrock_request)
# 2. 提取响应内容
content = ""
try:
# Bedrock响应是一个特殊对象,需要正确访问
response_body = bedrock_response.get('body')
if response_body:
response_data = json.loads(response_body.read())
if 'content' in response_data:
for content_block in response_data['content']:
if content_block.get('type') == 'text':
content += content_block.get('text', '')
elif 'completion' in response_data:
content = response_data['completion']
except Exception as parse_error:
logger.log_error(
error=parse_error,
context={"request_id": request_id},
error_phase="bedrock_response_parsing"
)
content = "响应解析失败,使用默认内容进行测试。"
if not content:
content = "抱歉,无法生成响应内容。"
logger.log_structured("pseudo_streaming_content_extracted", {
"request_id": request_id,
"content_length": len(content),
"estimated_tokens": len(content) // 4
})
# 3. 构建SSE响应块列表
sse_chunks = []
# 添加流开始标记
start_chunk = stream_handler.create_stream_start_chunk(