forked from coffeegrind123/gemini-for-claude-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·1565 lines (1308 loc) · 60.6 KB
/
Copy pathserver.py
File metadata and controls
executable file
·1565 lines (1308 loc) · 60.6 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
import asyncio
import json
import logging
import os
import sys
import time
import uuid
from datetime import datetime
from typing import Any, Dict, List, Literal, Optional, Union
import litellm
import uvicorn
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, field_validator
# Load environment variables early
load_dotenv()
# Basic LiteLLM Configuration - conservative settings to avoid hanging
litellm.drop_params = True
litellm.set_verbose = False
litellm.request_timeout = 90
# Constants for better maintainability
class Constants:
ROLE_USER = "user"
ROLE_ASSISTANT = "assistant"
ROLE_SYSTEM = "system"
ROLE_TOOL = "tool"
CONTENT_TEXT = "text"
CONTENT_IMAGE = "image"
CONTENT_TOOL_USE = "tool_use"
CONTENT_TOOL_RESULT = "tool_result"
TOOL_FUNCTION = "function"
STOP_END_TURN = "end_turn"
STOP_MAX_TOKENS = "max_tokens"
STOP_TOOL_USE = "tool_use"
STOP_ERROR = "error"
EVENT_MESSAGE_START = "message_start"
EVENT_MESSAGE_STOP = "message_stop"
EVENT_MESSAGE_DELTA = "message_delta"
EVENT_CONTENT_BLOCK_START = "content_block_start"
EVENT_CONTENT_BLOCK_STOP = "content_block_stop"
EVENT_CONTENT_BLOCK_DELTA = "content_block_delta"
EVENT_PING = "ping"
DELTA_TEXT = "text_delta"
DELTA_INPUT_JSON = "input_json_delta"
# Simple Configuration
class Config:
def __init__(self):
self.gemini_api_key = os.environ.get("GEMINI_API_KEY")
if not self.gemini_api_key:
raise ValueError("GEMINI_API_KEY not found in environment variables")
self.big_model = os.environ.get("BIG_MODEL", "gemini-1.5-pro-latest")
self.small_model = os.environ.get("SMALL_MODEL", "gemini-1.5-flash-latest")
self.host = os.environ.get("HOST", "0.0.0.0")
self.port = int(os.environ.get("PORT", "8082"))
self.log_level = os.environ.get("LOG_LEVEL", "WARNING")
self.max_tokens_limit = int(os.environ.get("MAX_TOKENS_LIMIT", "8192"))
# Connection settings - conservative defaults
self.request_timeout = int(os.environ.get("REQUEST_TIMEOUT", "90"))
self.max_retries = int(os.environ.get("MAX_RETRIES", "2"))
# Streaming settings
self.max_streaming_retries = int(os.environ.get("MAX_STREAMING_RETRIES", "12"))
self.force_disable_streaming = os.environ.get("FORCE_DISABLE_STREAMING", "false").lower() == "true"
self.emergency_disable_streaming = os.environ.get("EMERGENCY_DISABLE_STREAMING", "false").lower() == "true"
def validate_api_key(self):
"""Basic API key validation"""
if not self.gemini_api_key:
return False
# Basic format check for Google API keys
if not (self.gemini_api_key.startswith("AIza") and len(self.gemini_api_key) == 39):
return False
return True
try:
config = Config()
print(
f"✅ Configuration loaded: API_KEY={'*' * 20}..., BIG_MODEL='{config.big_model}', SMALL_MODEL='{config.small_model}'"
)
except Exception as e:
print(f"🔴 Configuration Error: {e}")
sys.exit(1)
# Apply connection settings to LiteLLM
litellm.request_timeout = config.request_timeout
litellm.num_retries = config.max_retries
# Model Management
class ModelManager:
def __init__(self, config):
self.config = config
self.base_gemini_models = [
"gemini-1.5-pro-latest",
"gemini-1.5-pro-preview-0514",
"gemini-1.5-flash-latest",
"gemini-1.5-flash-preview-0514",
"gemini-pro",
"gemini-2.5-pro-preview-05-06",
"gemini-2.5-flash-preview-04-17",
"gemini-2.0-flash-exp",
"gemini-exp-1206",
]
self._gemini_models = set(self.base_gemini_models)
self._add_env_models()
def _add_env_models(self):
for model in [self.config.big_model, self.config.small_model]:
if model.startswith("gemini") and model not in self._gemini_models:
self._gemini_models.add(model)
@property
def gemini_models(self) -> List[str]:
return sorted(self._gemini_models)
def validate_and_map_model(self, original_model: str) -> tuple[str, bool]:
clean_model = self._clean_model_name(original_model)
mapped_model = self._map_model_alias(clean_model)
if mapped_model != clean_model:
return f"gemini/{mapped_model}", True
elif clean_model in self._gemini_models:
return f"gemini/{clean_model}", True
elif not original_model.startswith("gemini/"):
return f"gemini/{original_model}", False
else:
return original_model, False
def _clean_model_name(self, model: str) -> str:
if model.startswith("gemini/"):
return model[7:]
elif model.startswith("anthropic/"):
return model[10:]
elif model.startswith("openai/"):
return model[7:]
return model
def _map_model_alias(self, clean_model: str) -> str:
model_lower = clean_model.lower()
if "haiku" in model_lower:
return self.config.small_model
elif "sonnet" in model_lower or "opus" in model_lower:
return self.config.big_model
return clean_model
model_manager = ModelManager(config)
# Logging Configuration
logging.basicConfig(
level=getattr(logging, config.log_level.upper()),
format="%(asctime)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
# Simple message filter
class SimpleMessageFilter(logging.Filter):
def filter(self, record):
blocked_phrases = ["LiteLLM completion()", "HTTP Request:", "cost_calculator"]
if hasattr(record, "msg") and isinstance(record.msg, str):
return not any(phrase in record.msg for phrase in blocked_phrases)
return True
root_logger = logging.getLogger()
root_logger.addFilter(SimpleMessageFilter())
# Configure uvicorn to be quieter
for uvicorn_logger in ["uvicorn", "uvicorn.access", "uvicorn.error"]:
logging.getLogger(uvicorn_logger).setLevel(logging.WARNING)
app = FastAPI(title="Gemini-to-Claude API Proxy", version="2.5.0")
# Enhanced error classification
def classify_gemini_error(error_msg: str) -> str:
"""Provide specific error guidance for common Gemini issues."""
error_lower = error_msg.lower()
# Streaming/parsing errors
if "error parsing chunk" in error_lower and "expecting property name" in error_lower:
return "Gemini streaming parsing error (malformed JSON chunk). This is a known intermittent Gemini API issue. Please try again or disable streaming by setting stream=false."
# Tool schema validation errors
if "function_declarations" in error_lower and "format" in error_lower:
if "only 'enum' and 'date-time' are supported" in error_lower:
return "Tool schema error: Gemini only supports 'enum' and 'date-time' formats for string parameters. Remove other format types like 'url', 'email', 'uri', etc."
else:
return "Tool schema validation error. Check your tool parameter definitions for unsupported format types or properties."
# Rate limiting
elif "rate limit" in error_lower or "quota" in error_lower:
return "Rate limit or quota exceeded. Please wait a moment and try again. Check your Google Cloud Console for quota limits."
# Authentication issues
elif "api key" in error_lower or "authentication" in error_lower or "unauthorized" in error_lower:
return "API key error. Please check that your GEMINI_API_KEY is valid and has the necessary permissions."
# Parsing/streaming issues
elif "parsing" in error_lower or "json" in error_lower or "malformed" in error_lower:
return "Response parsing error. This is often a temporary Gemini API issue - please retry your request."
# Connection issues
elif "connection" in error_lower or "timeout" in error_lower:
return "Connection or timeout error. Please check your internet connection and try again."
# Safety/content filtering
elif "safety" in error_lower or "content" in error_lower and "filter" in error_lower:
return (
"Content filtered by Gemini's safety systems. Please modify your request to comply with content policies."
)
# Token/length issues
elif "token" in error_lower and ("limit" in error_lower or "exceed" in error_lower):
return "Token limit exceeded. Please reduce the length of your request or increase the max_tokens parameter."
# Default: return original message
return error_msg
# Enhanced schema cleaner
def clean_gemini_schema(schema: Any) -> Any:
"""Recursively removes unsupported fields from a JSON schema for Gemini compatibility."""
if isinstance(schema, dict):
# Remove fields unsupported by Gemini
schema.pop("additionalProperties", None)
schema.pop("default", None)
# Handle string format restrictions
if schema.get("type") == "string" and "format" in schema:
allowed_formats = {"enum", "date-time"}
if schema["format"] not in allowed_formats:
logger.debug(f"Removing unsupported format '{schema['format']}' for string type in Gemini schema")
schema.pop("format")
# Recursively clean nested schemas
for key, value in list(schema.items()):
schema[key] = clean_gemini_schema(value)
elif isinstance(schema, list):
return [clean_gemini_schema(item) for item in schema]
return schema
# Pydantic Models
class ContentBlockThinking(BaseModel):
type: Literal["thinking"]
thinking: str
class ContentBlockText(BaseModel):
type: Literal["text"]
text: str
class ContentBlockImage(BaseModel):
type: Literal["image"]
source: Dict[str, Any]
class ContentBlockToolUse(BaseModel):
type: Literal["tool_use"]
id: str
name: str
input: Dict[str, Any]
class ContentBlockToolResult(BaseModel):
type: Literal["tool_result"]
tool_use_id: str
content: Union[str, List[Dict[str, Any]], Dict[str, Any]]
class SystemContent(BaseModel):
type: Literal["text"]
text: str
class Message(BaseModel):
role: Literal["user", "assistant"]
content: Union[
str,
List[
Union[
ContentBlockText,
ContentBlockImage,
ContentBlockToolUse,
ContentBlockToolResult,
ContentBlockThinking,
]
],
]
class Tool(BaseModel):
name: str
description: Optional[str] = None
input_schema: Dict[str, Any]
class ThinkingConfig(BaseModel):
enabled: bool = True
class MessagesRequest(BaseModel):
model: str
max_tokens: int
messages: List[Message]
system: Optional[Union[str, List[SystemContent]]] = None
stop_sequences: Optional[List[str]] = None
stream: Optional[bool] = False
temperature: Optional[float] = 1.0
top_p: Optional[float] = None
top_k: Optional[int] = None
metadata: Optional[Dict[str, Any]] = None
tools: Optional[List[Tool]] = None
tool_choice: Optional[Dict[str, Any]] = None
thinking: Optional[ThinkingConfig] = None
original_model: Optional[str] = None
@field_validator("model")
@classmethod
def validate_model_field(cls, v, info):
original_model = v
mapped_model, was_mapped = model_manager.validate_and_map_model(v)
logger.debug(
f"📋 MODEL VALIDATION: Original='{original_model}', Big='{config.big_model}', Small='{config.small_model}'"
)
if was_mapped:
logger.debug(f"📌 MODEL MAPPING: '{original_model}' ➡️ '{mapped_model}'")
if info and hasattr(info, "data") and isinstance(info.data, dict):
info.data["original_model"] = original_model
return mapped_model
class TokenCountRequest(BaseModel):
model: str
messages: List[Message]
system: Optional[Union[str, List[SystemContent]]] = None
tools: Optional[List[Tool]] = None
thinking: Optional[ThinkingConfig] = None
tool_choice: Optional[Dict[str, Any]] = None
original_model: Optional[str] = None
@field_validator("model")
@classmethod
def validate_model_token_count(cls, v, info):
mapped_model, _ = model_manager.validate_and_map_model(v)
if info and hasattr(info, "data") and isinstance(info.data, dict):
info.data["original_model"] = v
return mapped_model
class TokenCountResponse(BaseModel):
input_tokens: int
class Usage(BaseModel):
input_tokens: int
output_tokens: int
cache_creation_input_tokens: int = 0
cache_read_input_tokens: int = 0
class MessagesResponse(BaseModel):
id: str
model: str
role: Literal["assistant"] = Constants.ROLE_ASSISTANT
content: List[Union[ContentBlockText, ContentBlockToolUse]]
type: Literal["message"] = "message"
stop_reason: Optional[Literal["end_turn", "max_tokens", "stop_sequence", "tool_use", "error"]] = None
stop_sequence: Optional[str] = None
usage: Usage
# Tool result parsing
def parse_tool_result_content(content):
"""Parse and normalize tool result content into a string format."""
if content is None:
return "No content provided"
if isinstance(content, str):
return content
if isinstance(content, list):
result_parts = []
for item in content:
if isinstance(item, dict) and item.get("type") == Constants.CONTENT_TEXT:
result_parts.append(item.get("text", ""))
elif isinstance(item, str):
result_parts.append(item)
elif isinstance(item, dict):
if "text" in item:
result_parts.append(item.get("text", ""))
else:
try:
result_parts.append(json.dumps(item))
except:
result_parts.append(str(item))
return "\n".join(result_parts).strip()
if isinstance(content, dict):
if content.get("type") == Constants.CONTENT_TEXT:
return content.get("text", "")
try:
return json.dumps(content)
except:
return str(content)
try:
return str(content)
except:
return "Unparseable content"
# Enhanced message conversion
def convert_anthropic_to_litellm(anthropic_request: MessagesRequest) -> Dict[str, Any]:
"""Convert Anthropic API request format to LiteLLM format for Gemini."""
litellm_messages = []
# System message handling
if anthropic_request.system:
system_text = ""
if isinstance(anthropic_request.system, str):
system_text = anthropic_request.system
elif isinstance(anthropic_request.system, list):
text_parts = []
for block in anthropic_request.system:
if hasattr(block, "type") and block.type == Constants.CONTENT_TEXT:
text_parts.append(block.text)
elif isinstance(block, dict) and block.get("type") == Constants.CONTENT_TEXT:
text_parts.append(block.get("text", ""))
system_text = "\n\n".join(text_parts)
if system_text.strip():
litellm_messages.append({"role": Constants.ROLE_SYSTEM, "content": system_text.strip()})
# Process messages
for msg in anthropic_request.messages:
if isinstance(msg.content, str):
litellm_messages.append({"role": msg.role, "content": msg.content})
continue
# Process content blocks - accumulate different types
text_parts = []
image_parts = []
tool_calls = []
pending_tool_messages = []
for block in msg.content:
if block.type == Constants.CONTENT_TEXT:
text_parts.append(block.text)
elif block.type == Constants.CONTENT_IMAGE:
if (
isinstance(block.source, dict)
and block.source.get("type") == "base64"
and "media_type" in block.source
and "data" in block.source
):
image_parts.append(
{
"type": "image_url",
"image_url": {"url": f"data:{block.source['media_type']};base64,{block.source['data']}"},
}
)
elif block.type == Constants.CONTENT_TOOL_USE and msg.role == Constants.ROLE_ASSISTANT:
tool_calls.append(
{
"id": block.id,
"type": Constants.TOOL_FUNCTION,
Constants.TOOL_FUNCTION: {
"name": block.name,
"arguments": json.dumps(block.input),
},
}
)
elif block.type == Constants.CONTENT_TOOL_RESULT and msg.role == Constants.ROLE_USER:
# CRITICAL: Split user message when tool_result is encountered
if text_parts or image_parts:
content_parts = []
text_content = "".join(text_parts).strip()
if text_content:
content_parts.append({"type": Constants.CONTENT_TEXT, "text": text_content})
content_parts.extend(image_parts)
litellm_messages.append(
{
"role": Constants.ROLE_USER,
"content": content_parts[0]["text"]
if len(content_parts) == 1 and content_parts[0]["type"] == Constants.CONTENT_TEXT
else content_parts,
}
)
text_parts.clear()
image_parts.clear()
# Add tool result as separate "tool" role message
parsed_content = parse_tool_result_content(block.content)
pending_tool_messages.append(
{
"role": Constants.ROLE_TOOL,
"tool_call_id": block.tool_use_id,
"content": parsed_content,
}
)
# Finalize message based on role
if msg.role == Constants.ROLE_USER:
# Add any remaining text/image content
if text_parts or image_parts:
content_parts = []
text_content = "".join(text_parts).strip()
if text_content:
content_parts.append({"type": Constants.CONTENT_TEXT, "text": text_content})
content_parts.extend(image_parts)
litellm_messages.append(
{
"role": Constants.ROLE_USER,
"content": content_parts[0]["text"]
if len(content_parts) == 1 and content_parts[0]["type"] == Constants.CONTENT_TEXT
else content_parts,
}
)
# Add any pending tool messages
litellm_messages.extend(pending_tool_messages)
elif msg.role == Constants.ROLE_ASSISTANT:
assistant_msg = {"role": Constants.ROLE_ASSISTANT}
# Handle content for assistant messages
content_parts = []
text_content = "".join(text_parts).strip()
if text_content:
content_parts.append({"type": Constants.CONTENT_TEXT, "text": text_content})
content_parts.extend(image_parts)
# FIXED: Don't set content to None - let LiteLLM handle missing content
if content_parts:
assistant_msg["content"] = (
content_parts[0]["text"]
if len(content_parts) == 1 and content_parts[0]["type"] == Constants.CONTENT_TEXT
else content_parts
)
else:
assistant_msg["content"] = None
if tool_calls:
assistant_msg["tool_calls"] = tool_calls
# Only add message if it has actual content or tool calls
if assistant_msg.get("content") or assistant_msg.get("tool_calls"):
litellm_messages.append(assistant_msg)
# Build final LiteLLM request
litellm_request = {
"model": anthropic_request.model,
"messages": litellm_messages,
"max_tokens": min(anthropic_request.max_tokens, config.max_tokens_limit),
"temperature": anthropic_request.temperature,
"stream": anthropic_request.stream,
}
# Add optional parameters
if anthropic_request.stop_sequences:
litellm_request["stop"] = anthropic_request.stop_sequences
if anthropic_request.top_p is not None:
litellm_request["top_p"] = anthropic_request.top_p
if anthropic_request.top_k is not None:
litellm_request["topK"] = anthropic_request.top_k
# Add tools with schema cleaning
if anthropic_request.tools:
valid_tools = []
for tool in anthropic_request.tools:
if tool.name and tool.name.strip():
cleaned_schema = clean_gemini_schema(tool.input_schema)
valid_tools.append(
{
"type": Constants.TOOL_FUNCTION,
Constants.TOOL_FUNCTION: {
"name": tool.name,
"description": tool.description or "",
"parameters": cleaned_schema,
},
}
)
if valid_tools:
litellm_request["tools"] = valid_tools
# Add tool choice configuration
if anthropic_request.tool_choice:
choice_type = anthropic_request.tool_choice.get("type")
if choice_type == "auto":
litellm_request["tool_choice"] = "auto"
elif choice_type == "any":
litellm_request["tool_choice"] = "auto"
elif choice_type == "tool" and "name" in anthropic_request.tool_choice:
litellm_request["tool_choice"] = {
"type": Constants.TOOL_FUNCTION,
Constants.TOOL_FUNCTION: {"name": anthropic_request.tool_choice["name"]},
}
else:
litellm_request["tool_choice"] = "auto"
# Add thinking configuration (Gemini specific)
if anthropic_request.thinking is not None:
if anthropic_request.thinking.enabled:
litellm_request["thinkingConfig"] = {"thinkingBudget": 24576}
else:
litellm_request["thinkingConfig"] = {"thinkingBudget": 0}
# Add user metadata if provided
if (
anthropic_request.metadata
and "user_id" in anthropic_request.metadata
and isinstance(anthropic_request.metadata["user_id"], str)
):
litellm_request["user"] = anthropic_request.metadata["user_id"]
return litellm_request
# Response conversion
def convert_litellm_to_anthropic(litellm_response, original_request: MessagesRequest) -> MessagesResponse:
"""Convert LiteLLM (Gemini) response back to Anthropic API format."""
try:
# Extract response data safely
response_id = f"msg_{uuid.uuid4()}"
content_text = ""
tool_calls = None
finish_reason = "stop"
prompt_tokens = 0
completion_tokens = 0
# Handle LiteLLM ModelResponse object format
if hasattr(litellm_response, "choices") and hasattr(litellm_response, "usage"):
choices = litellm_response.choices
message = choices[0].message if choices else None
content_text = getattr(message, "content", "") or ""
tool_calls = getattr(message, "tool_calls", None)
finish_reason = choices[0].finish_reason if choices else "stop"
response_id = getattr(litellm_response, "id", response_id)
if hasattr(litellm_response, "usage"):
usage = litellm_response.usage
prompt_tokens = getattr(usage, "prompt_tokens", 0)
completion_tokens = getattr(usage, "completion_tokens", 0)
# Handle dictionary response format
elif isinstance(litellm_response, dict):
choices = litellm_response.get("choices", [])
message = choices[0].get("message", {}) if choices else {}
content_text = message.get("content", "") or ""
tool_calls = message.get("tool_calls")
finish_reason = choices[0].get("finish_reason", "stop") if choices else "stop"
usage = litellm_response.get("usage", {})
prompt_tokens = usage.get("prompt_tokens", 0)
completion_tokens = usage.get("completion_tokens", 0)
response_id = litellm_response.get("id", response_id)
# Build content blocks
content_blocks = []
# Add text content if present
if content_text:
content_blocks.append(ContentBlockText(type=Constants.CONTENT_TEXT, text=content_text))
# Process tool calls
if tool_calls:
if not isinstance(tool_calls, list):
tool_calls = [tool_calls]
for tool_call in tool_calls:
try:
# Extract tool call data from different formats
if isinstance(tool_call, dict):
tool_id = tool_call.get("id", f"tool_{uuid.uuid4()}")
function_data = tool_call.get(Constants.TOOL_FUNCTION, {})
name = function_data.get("name", "")
arguments_str = function_data.get("arguments", "{}")
elif hasattr(tool_call, "id") and hasattr(tool_call, Constants.TOOL_FUNCTION):
tool_id = tool_call.id
name = tool_call.function.name
arguments_str = tool_call.function.arguments
else:
continue
if not name:
continue
# Parse tool arguments safely
try:
arguments_dict = json.loads(arguments_str)
except json.JSONDecodeError:
arguments_dict = {"raw_arguments": arguments_str}
content_blocks.append(
ContentBlockToolUse(
type=Constants.CONTENT_TOOL_USE,
id=tool_id,
name=name,
input=arguments_dict,
)
)
except Exception as e:
logger.warning(f"Error processing tool call: {e}")
continue
# Ensure at least one content block
if not content_blocks:
content_blocks.append(ContentBlockText(type=Constants.CONTENT_TEXT, text=""))
# Map finish reason to Anthropic format
if finish_reason == "length":
stop_reason = Constants.STOP_MAX_TOKENS
elif finish_reason == "tool_calls":
stop_reason = Constants.STOP_TOOL_USE
elif finish_reason is None and tool_calls:
stop_reason = Constants.STOP_TOOL_USE
else:
stop_reason = Constants.STOP_END_TURN
return MessagesResponse(
id=response_id,
model=original_request.original_model or original_request.model,
role=Constants.ROLE_ASSISTANT,
content=content_blocks,
stop_reason=stop_reason,
stop_sequence=None,
usage=Usage(input_tokens=prompt_tokens, output_tokens=completion_tokens),
)
except Exception as e:
logger.error(f"Error converting response: {e}")
return MessagesResponse(
id=f"msg_error_{uuid.uuid4()}",
model=original_request.original_model or original_request.model,
role=Constants.ROLE_ASSISTANT,
content=[ContentBlockText(type=Constants.CONTENT_TEXT, text="Response conversion error")],
stop_reason=Constants.STOP_ERROR,
usage=Usage(input_tokens=0, output_tokens=0),
)
# Enhanced streaming handler with more robust error recovery
async def handle_streaming_with_recovery(response_generator, original_request: MessagesRequest, input_tokens: int):
"""Enhanced streaming handler with robust error recovery for malformed chunks."""
message_id = f"msg_{uuid.uuid4().hex[:24]}"
# Send initial SSE events
yield f"event: {Constants.EVENT_MESSAGE_START}\ndata: {json.dumps({'type': Constants.EVENT_MESSAGE_START, 'message': {'id': message_id, 'type': 'message', 'role': Constants.ROLE_ASSISTANT, 'model': original_request.original_model or original_request.model, 'content': [], 'stop_reason': None, 'stop_sequence': None, 'usage': {'input_tokens': input_tokens, 'output_tokens': 0}}})}\n\n"
yield f"event: {Constants.EVENT_CONTENT_BLOCK_START}\ndata: {json.dumps({'type': Constants.EVENT_CONTENT_BLOCK_START, 'index': 0, 'content_block': {'type': Constants.CONTENT_TEXT, 'text': ''}})}\n\n"
yield f"event: {Constants.EVENT_PING}\ndata: {json.dumps({'type': Constants.EVENT_PING})}\n\n"
# Streaming state management
all_chunks = []
accumulated_text = ""
text_block_index = 0
tool_block_counter = 0
current_tool_calls = {}
input_tokens = 0
output_tokens = 0
final_stop_reason = Constants.STOP_END_TURN
# Enhanced error recovery tracking
consecutive_errors = 0
max_consecutive_errors = 10 # Increased from 5
stream_terminated_early = False
malformed_chunks_count = 0
max_malformed_chunks = 20 # Allow more malformed chunks before giving up
# Buffer for incomplete chunks
chunk_buffer = ""
def is_malformed_chunk(chunk_str: str) -> bool:
"""Enhanced malformed chunk detection."""
if not chunk_str or not isinstance(chunk_str, str):
return True
chunk_stripped = chunk_str.strip()
# Empty or whitespace
if not chunk_stripped:
return True
# Single characters that indicate malformed JSON
malformed_singles = ["{", "}", "[", "]", ",", ":", '"', "'"]
if chunk_stripped in malformed_singles:
return True
# Common malformed patterns
malformed_patterns = [
'{"',
'"}',
"[{",
"}]",
"{}",
"[]",
"null",
'""',
"''",
" ",
"",
"{,",
",}",
"[,",
",]",
]
if chunk_stripped in malformed_patterns:
return True
# Incomplete JSON structures
if chunk_stripped.startswith("{") and not chunk_stripped.endswith("}"):
if len(chunk_stripped) < 15: # Very short incomplete JSON
return True
if chunk_stripped.startswith("[") and not chunk_stripped.endswith("]"):
if len(chunk_stripped) < 10:
return True
# Check for obviously broken JSON patterns
if chunk_stripped.count("{") != chunk_stripped.count("}"):
if len(chunk_stripped) < 20: # Only for short chunks
return True
if chunk_stripped.count("[") != chunk_stripped.count("]"):
if len(chunk_stripped) < 20:
return True
return False
def try_parse_buffered_chunk(buffer: str) -> tuple[dict, str]:
"""Try to parse buffered chunks, return parsed chunk and remaining buffer."""
if not buffer.strip():
return None, ""
# Try to find complete JSON objects in the buffer
brace_count = 0
start_pos = -1
for i, char in enumerate(buffer):
if char == "{":
if start_pos == -1:
start_pos = i
brace_count += 1
elif char == "}":
brace_count -= 1
if brace_count == 0 and start_pos != -1:
# Found complete JSON object
json_str = buffer[start_pos : i + 1]
try:
parsed = json.loads(json_str)
remaining_buffer = buffer[i + 1 :]
return parsed, remaining_buffer
except json.JSONDecodeError:
continue
# No complete JSON found
return None, buffer
try:
# Wrap the entire streaming process in comprehensive error handling
stream_iterator = aiter(response_generator)
while True:
try:
# Get next chunk with timeout
try:
chunk = await asyncio.wait_for(anext(stream_iterator), timeout=90.0)
except StopAsyncIteration:
break
except asyncio.TimeoutError:
logger.warning("Streaming timeout, terminating")
stream_terminated_early = True
break
# Reset consecutive error counter on successful chunk retrieval
consecutive_errors = 0
all_chunks.append(chunk)
# Handle string chunks with enhanced validation
if isinstance(chunk, str):
if chunk.strip() == "[DONE]":
break
# Check for malformed chunks
if is_malformed_chunk(chunk):
malformed_chunks_count += 1
logger.debug(
f"Skipping malformed chunk #{malformed_chunks_count}: '{chunk[:50]}{'...' if len(chunk) > 50 else ''}'"
)
if malformed_chunks_count > max_malformed_chunks:
logger.error(f"Too many malformed chunks ({malformed_chunks_count}), terminating stream")
stream_terminated_early = True
break
continue
# Add to buffer and try to parse
chunk_buffer += chunk
parsed_chunk, chunk_buffer = try_parse_buffered_chunk(chunk_buffer)
if parsed_chunk is None:
# Keep buffering if we don't have a complete chunk yet
if len(chunk_buffer) > 10000: # Prevent buffer from growing too large
logger.warning("Chunk buffer too large, clearing")
chunk_buffer = ""
continue
chunk = parsed_chunk
# If we have a dictionary at this point, process it
if isinstance(chunk, dict):
# Process the chunk normally (existing logic)
pass
elif hasattr(chunk, "choices"):
# Process ModelResponse object normally (existing logic)
pass
else:
# Try one more JSON parse attempt
try:
if isinstance(chunk, str):
chunk = json.loads(chunk)
else:
logger.debug(f"Skipping unprocessable chunk type: {type(chunk)}")
continue
except json.JSONDecodeError as parse_error:
logger.debug(f"Failed to parse chunk as JSON: {parse_error}")
continue
# Extract chunk data (your existing logic here)
delta_content_text = None
delta_tool_calls = None
chunk_finish_reason = None
if hasattr(chunk, "choices") and chunk.choices:
choice = chunk.choices[0]
if hasattr(choice, "delta") and choice.delta:
delta = choice.delta
delta_content_text = getattr(delta, "content", None)
if hasattr(delta, "tool_calls"):
delta_tool_calls = delta.tool_calls
chunk_finish_reason = getattr(choice, "finish_reason", None)
elif isinstance(chunk, dict):
choices = chunk.get("choices", [])
if choices:
choice = choices[0]
delta = choice.get("delta", {})
delta_content_text = delta.get("content")
delta_tool_calls = delta.get("tool_calls")
chunk_finish_reason = choice.get("finish_reason")
if hasattr(chunk, "usage") and chunk.usage:
input_tokens = getattr(chunk.usage, "prompt_tokens", 0)
output_tokens = getattr(chunk.usage, "completion_tokens", 0)
elif isinstance(chunk, dict) and "usage" in chunk:
usage = chunk["usage"]
input_tokens = usage.get("prompt_tokens", 0)
output_tokens = usage.get("completion_tokens", 0)
# Handle text delta
if delta_content_text:
accumulated_text += delta_content_text
yield f"event: {Constants.EVENT_CONTENT_BLOCK_DELTA}\ndata: {json.dumps({'type': Constants.EVENT_CONTENT_BLOCK_DELTA, 'index': text_block_index, 'delta': {'type': Constants.DELTA_TEXT, 'text': delta_content_text}})}\n\n"
# Handle tool call deltas (your existing logic)
if delta_tool_calls:
for tc_chunk in delta_tool_calls:
if not (
hasattr(tc_chunk, "function")
and tc_chunk.function
and hasattr(tc_chunk.function, "name")
and tc_chunk.function.name