-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathapi_requests.py
1923 lines (1612 loc) · 73.7 KB
/
api_requests.py
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
# Standard library
from abc import ABC, abstractmethod
import time
import json
import re
from enum import Enum
from typing import Callable, Any, Optional, Type, List, Tuple
from urllib.parse import urlparse, urlunparse
# Third-party libraries
import torch
import requests
import openai
import anthropic
#import google.generativeai as genai
try:
from google import genai
except ImportError:
import google.generativeai as genai
from google.genai import types
#from google.generativeai.types import GenerationConfig
# Local modules
try:
from .mng_json import json_manager, TroubleSgltn
from .fetch_models import RequestMode
from .utils import ImageUtils, CommUtils
except ImportError:
from mng_json import json_manager, TroubleSgltn
from fetch_models import RequestMode
from utils import ImageUtils, CommUtils
class ImportedSgltn:
"""
This class is temporary to prevent circular imports between style_prompt
and api_requests modules.
"""
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(ImportedSgltn, cls).__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self):
if not self._initialized: #pylint: disable=access-member-before-definition
self._initialized = True
self._cfig = None
self.get_imports()
def get_imports(self):
"""Import and initialize singleton instances from style_prompt"""
# Guard against re-importing if already done
if self._cfig is None:
try:
from .style_prompt import cFigSingleton
except ImportError:
from style_prompt import cFigSingleton
self._cfig = cFigSingleton
@property
def cfig(self):
"""Returns the cFigSingleton instance"""
if self._cfig is None:
self.get_imports()
return self._cfig()
class RetryConfig:
"""Configuration for retry behavior"""
def __init__(
self,
max_retries: int = 3,
base_delay: float = 1.0,
max_delay: float = 10.0,
exponential_base: float = 2.0,
retryable_exceptions: Optional[List[Type[Exception]]] = None,
retryable_http_status_codes: Optional[List[int]] = None
):
self.max_retries = max_retries
self.base_delay = base_delay
self.max_delay = max_delay
self.exponential_base = exponential_base
self.retryable_exceptions = retryable_exceptions
self.retryable_http_status_codes = retryable_http_status_codes or [
408, # Request Timeout
429, # Too Many Requests
500, # Internal Server Error
502, # Bad Gateway
503, # Service Unavailable
504 # Gateway Timeout
]
class ErrorParser:
"""Extracts standardized error information from various API responses"""
@staticmethod
def get_error_code(response: Any) -> Optional[int]:
"""
Extracts error code from various response formats.
Returns error code if found, None otherwise.
"""
# Handle HTTP Response objects
if isinstance(response, requests.Response):
return response.status_code
# OpenAI-style errors (and compatible services like OpenRouter)
if hasattr(response, 'error'):
error = response.error
if isinstance(error, dict):
# Direct error code
if 'code' in error and isinstance(error['code'], int):
return error['code']
if 'status' in error and isinstance(error['status'], int):
return error['status']
if 'status_code' in error and isinstance(error['status_code'], int):
return error['status_code']
# Nested in metadata (like OpenRouter/Google)
metadata = error.get('metadata', {})
if metadata and isinstance(metadata.get('raw'), str):
try:
raw_error = json.loads(metadata['raw'])
code = raw_error.get('error', {}).get('code')
if isinstance(code, int):
return code
except (json.JSONDecodeError, AttributeError):
pass
# Anthropic-style responses
if hasattr(response, 'status_code'):
return response.status_code
# Handle raw JSON responses (some services return direct JSON)
if isinstance(response, dict):
# Try common error code paths
paths = [
['error', 'code'],
['error', 'status_code'],
['error', 'status'],
['code'],
['status_code'],
['status']
]
for path in paths:
value = response
for key in path:
if isinstance(value, dict) and key in value:
value = value[key]
else:
value = None
break
if isinstance(value, int):
return value
if 'error' in response:
error = response['error']
if isinstance(error, dict):
# Google-specific string error codes mapping
google_error_map = {
"RESOURCE_EXHAUSTED": 429,
"UNAVAILABLE": 503,
"DEADLINE_EXCEEDED": 504,
"INTERNAL": 500,
"UNKNOWN": 500
}
if 'code' in error and isinstance(error['code'], str):
return google_error_map.get(error['code'], 400)
return None
class RetryHandler:
"""Handles retry logic for API calls"""
def __init__(self, config: RetryConfig, logger: Any):
self.config = config
self.logger = logger
self.error_parser = ErrorParser()
def calculate_delay(self, attempt: int) -> float:
"""Calculate delay with exponential backoff"""
delay = min(
self.config.base_delay * (self.config.exponential_base ** attempt),
self.config.max_delay
)
return delay
def should_retry(self, response: Any) -> bool:
"""Determine if the response is retryable"""
error_code = self.error_parser.get_error_code(response)
if error_code:
# Check if it's a retryable code
return error_code in self.config.retryable_http_status_codes
# Handle standard exceptions
if isinstance(response, Exception) and self.config.retryable_exceptions:
return any(isinstance(response, exc) for exc in self.config.retryable_exceptions)
return False
def execute_with_retry(self, func: Callable, *args, **kwargs) -> Any:
"""Execute function with retry logic"""
last_exception = None
last_error_info = None # Track the last error information
self.logger.log_events(f"Maximum tries set to: {self.config.max_retries}",
is_trouble=True)
for attempt in range(self.config.max_retries):
try:
response = func(*args, **kwargs)
# For HTTP responses
if isinstance(response, requests.Response):
try:
response_json = response.json()
if 'error' in response_json:
error_code = self.error_parser.get_error_code(response_json)
if error_code in self.config.retryable_http_status_codes:
last_error_info = response_json['error'] # Store error info
delay = self.calculate_delay(attempt)
self.logger.log_events(
f"Retryable error detected in response content ({error_code}), "
f"retrying in {delay:.2f} seconds...",
TroubleSgltn.Severity.WARNING,
True
)
time.sleep(delay)
continue
except ValueError:
pass
# Then check status codes
if 200 <= response.status_code < 300:
return response
elif self.should_retry(response):
last_error_info = {'status': response.status_code, 'text': response.text}
delay = self.calculate_delay(attempt)
self.logger.log_events(
f"Rate limit or server error {response.status_code}, "
f"retrying in {delay:.2f} seconds...",
TroubleSgltn.Severity.WARNING,
True
)
time.sleep(delay)
continue
else:
return response
# For OpenAI/API responses with embedded errors
error_code = self.error_parser.get_error_code(response)
if error_code and error_code in self.config.retryable_http_status_codes:
last_error_info = response.error if hasattr(response, 'error') else str(response)
delay = self.calculate_delay(attempt)
self.logger.log_events(
f"Rate limit or error detected in API response ({error_code}), "
f"retrying in {delay:.2f} seconds...",
TroubleSgltn.Severity.WARNING,
True
)
time.sleep(delay)
continue
return response
except Exception as e:
last_exception = e
last_error_info = str(e) # Store exception info
if not self.should_retry(e):
self.logger.log_events(
f"Non-retryable error occurred: {str(e)}",
TroubleSgltn.Severity.ERROR,
True
)
raise
delay = self.calculate_delay(attempt)
self.logger.log_events(
f"Attempt {attempt + 1}/{self.config.max_retries} failed. "
f"Retrying in {delay:.2f} seconds. Error: {str(e)}",
TroubleSgltn.Severity.WARNING,
True
)
time.sleep(delay)
# Create a meaningful exception with the last error information
error_message = f"Maximum retry attempts ({self.config.max_retries}) exceeded. "
if last_error_info:
error_message += f"Last error: {last_error_info}"
# Raise the original exception if we have one, otherwise raise a RuntimeError
if last_exception:
raise last_exception
raise RuntimeError(error_message)
class RetryConfigFactory:
"""Factory for creating retry configurations based on request type"""
@staticmethod
def create_config(request_type: RequestMode) -> RetryConfig:
web_exceptions = [
requests.exceptions.Timeout,
requests.exceptions.ConnectionError,
requests.exceptions.RequestException,
ConnectionError,
TimeoutError
]
api_exceptions = [
openai.APIConnectionError,
openai.RateLimitError,
openai.APIStatusError
]
anthropic_exceptions = [
anthropic.APIConnectionError,
anthropic.RateLimitError,
anthropic.APIStatusError,
anthropic.APIError
]
configs = {
RequestMode.OPENAI: RetryConfig(
max_retries=3,
base_delay=1.0,
max_delay=10.0,
retryable_exceptions=api_exceptions
),
RequestMode.CLAUDE: RetryConfig(
max_retries=2,
base_delay=2.0,
max_delay=8.0,
retryable_exceptions=anthropic_exceptions
),
RequestMode.OPENSOURCE: RetryConfig(
max_retries=3,
base_delay=1.0,
max_delay=8.0,
retryable_exceptions=web_exceptions,
retryable_http_status_codes=[408, 429, 500, 502, 503, 504]
),
RequestMode.OSSIMPLE: RetryConfig(
max_retries=3,
base_delay=1.0,
max_delay=8.0,
retryable_exceptions=web_exceptions,
retryable_http_status_codes=[408, 429, 500, 502, 503, 504]
),
RequestMode.LMSTUDIO: RetryConfig(
max_retries=2,
base_delay=0.5,
max_delay=4.0,
retryable_exceptions=web_exceptions,
retryable_http_status_codes=[408, 429, 500, 502, 503, 504]
),
RequestMode.GROQ: RetryConfig(
max_retries=3,
base_delay=1.0,
max_delay=6.0,
retryable_exceptions=api_exceptions
),
RequestMode.OOBABOOGA: RetryConfig(
max_retries=2,
base_delay=1.0,
max_delay=6.0,
retryable_exceptions=web_exceptions,
retryable_http_status_codes=[408, 429, 500, 502, 503, 504]
),
# DALL-E specific configuration
RequestMode.DALLE: RetryConfig(
max_retries=3,
base_delay=2.0,
max_delay=15.0,
retryable_http_status_codes=[400,429],
retryable_exceptions=[
openai.APIConnectionError,
openai.RateLimitError,
openai.APIStatusError
]
),
RequestMode.GEMINI: RetryConfig(
max_retries=2, # As recommended in the docs ("retrying no more than two times")
base_delay=1.0, # "The minimum delay is one second"
max_delay=8.0, # Allow for exponential backoff
retryable_exceptions=[
# Google API common exceptions
ConnectionError,
TimeoutError
],
# Based on the documentation, these are the retryable HTTP status codes
retryable_http_status_codes=[
429, # RESOURCE_EXHAUSTED - quota limits, server overload
500, # INTERNAL - server error/overload
503, # UNAVAILABLE - service temporarily unavailable
504 # DEADLINE_EXCEEDED - request timeout
]
)
}
return configs.get(request_type, RetryConfig())
class Request(ABC):
"""Abstract base class for all request types"""
class RequestType(Enum):
COMPLETION = "completion"
POST = "post"
IMAGE = "image"
ANTHROPIC = "claude"
def __init__(self):
self.imps = ImportedSgltn()
self.utils = request_utils()
self.cFig = self.imps.cfig
self.mode = RequestMode
self.j_mngr = json_manager()
self.img_u = ImageUtils()
# Initialize retry configuration and handler
retry_config = RetryConfigFactory.create_config(self.cFig.lm_request_mode)
self.retry_handler = RetryHandler(retry_config, self.j_mngr)
def _initialize_retry_handler(self, **kwargs):
"""Initialize retry handler with optional override from kwargs"""
# Get base configuration
retry_config = RetryConfigFactory.create_config(self.cFig.lm_request_mode)
# Override max_retries if provided in kwargs otherwise use default
if 'tries' in kwargs and kwargs['tries']:
tries = kwargs['tries']
if isinstance(tries, str) and tries != "default":
retry_config.max_retries = int(tries)
self.retry_handler = RetryHandler(retry_config, self.j_mngr)
def _make_request(self, request_type: RequestType, *args) -> Any:
"""Unified request method handling different request types"""
if request_type == self.RequestType.COMPLETION:
client, params = args
return client.chat.completions.create(**params)
elif request_type == self.RequestType.ANTHROPIC:
client, params = args
return client.messages.create(**params)
elif request_type == self.RequestType.POST:
url, headers, params = args
return requests.post(url, headers=headers, json=params, timeout=(12, 120))
elif request_type == self.RequestType.IMAGE:
client, params = args
return client.images.generate(**params)
else:
raise ValueError(f"Unsupported request type: {request_type}")
@abstractmethod
def request_completion(self, **kwargs) -> Any:
pass
def _log_completion_metrics(self, response: Any, response_type: str = "standard"):
"""Common logging for completion metrics"""
try:
if response_type == "standard":
if getattr(response, 'model', None):
self.j_mngr.log_events(
f"Using LLM: {response.model}",
is_trouble=True
)
if getattr(response, 'usage', None):
self.j_mngr.log_events(
f"Tokens Used: {response.usage}",
TroubleSgltn.Severity.INFO,
True
)
elif response_type == "json":
if response.get('model'):
self.j_mngr.log_events(
f"Using LLM: {response['model']}",
is_trouble=True
)
if response.get('usage'):
self.j_mngr.log_events(
f"Tokens Used: {response['usage']}",
TroubleSgltn.Severity.INFO,
True
)
except Exception as e:
self.j_mngr.log_events(
f"Unable to report completion metrics: {e}",
TroubleSgltn.Severity.INFO,
True
)
class oai_object_request(Request):
"""Concrete class for OpenAI API object-based requests"""
# def _make_completion_request(self, client, params):
# """Wrapped completion request for retry handling"""
# return client.chat.completions.create(**params)
def _get_client(self) -> Optional[Any]:
"""Get appropriate client based on request type"""
request_type = self.cFig.lm_request_mode
client = None
error_message = None
if request_type in [self.mode.OPENSOURCE, self.mode.OLLAMA]:
if self.cFig.lm_url:
self.j_mngr.log_events(
"Setting client to OpenAI Open Source LLM object",
is_trouble=True
)
client = self.cFig.lm_client
else:
error_message = "Open Source api object is not ready for use, no URL provided."
elif request_type == self.mode.GROQ:
if self.cFig.lm_url:
self.j_mngr.log_events(
"Setting client to OpenAI Groq LLM object",
is_trouble=True
)
client = self.cFig.lm_client
else:
error_message = "Groq OpenAI api object is not ready for use, no URL provided."
elif request_type == self.mode.GEMINI:
if self.cFig.lm_url:
self.j_mngr.log_events(
"Setting client to OpenAI Gemini LLM object",
is_trouble=True
)
client = self.cFig.lm_client
else:
error_message = "Groq OpenAI api object is not ready for use, no URL provided."
elif request_type == self.mode.OPENAI:
if self.cFig.key:
self.j_mngr.log_events(
"Setting client to OpenAI ChatGPT object",
is_trouble=True
)
client = self.cFig.openaiClient
else:
error_message = "Invalid or missing OpenAI API key. Keys must be stored in an environment variable."
if error_message:
self.j_mngr.log_events(
error_message,
TroubleSgltn.Severity.WARNING,
True
)
return client
def request_completion(self, **kwargs) -> str:
"""Execute completion request with retry handling"""
GPTmodel = kwargs.get('model')
creative_latitude = kwargs.get('creative_latitude', 0.7)
tokens = kwargs.get('tokens', 500)
prompt = kwargs.get('prompt', "")
instruction = kwargs.get('instruction', "")
#file = kwargs.get('file', "").strip()
image = kwargs.get('image', None)
example_list = kwargs.get('example_list', [])
add_params = kwargs.get('add_params', None)
CGPT_response = ""
client = self._get_client()
self._initialize_retry_handler(**kwargs)
if not client:
return "Unable to process request, client initialization failed"
# Build messages based on presence of image
if image is not None:
messages = self.utils.build_data_multi(prompt, instruction, example_list, image)
else:
messages = self.utils.build_data_basic(prompt, example_list, instruction)
# Handle empty input case
if not any([prompt, instruction, example_list]) and image is None:
return "Photograph of a stained empty box with 'NOTHING' printed on its side in bold letters"
params = {
"model": GPTmodel,
"messages": messages,
"temperature": creative_latitude,
"max_tokens": tokens
}
# Certain models have parameter restrictions
if self.cFig.lm_request_mode != RequestMode.GEMINI:
params = self.utils.model_param_adjust(params, self.cFig.lm_request_mode)
if add_params:
self.j_mngr.append_params(params, add_params, ['param', 'value'])
try:
response = self.retry_handler.execute_with_retry(
self._make_request,
self.RequestType.COMPLETION,
client,
params
) #_make_request is passed as a wrapped function, the arguments that follow are passed into
#args which is unpacked as a tuple in _make_request()
if response and response.choices and 'error' not in response:
self._log_completion_metrics(response)
CGPT_response = self.utils.clean_response_text(
response.choices[0].message.content
)
else:
err_mess = getattr(response, 'error', "Error message missing")
self.j_mngr.log_events(
f"Server was unable to process this request. Error: {err_mess}",
TroubleSgltn.Severity.ERROR,
True
)
CGPT_response = "Server was unable to process the request"
except Exception as e:
self.j_mngr.log_events(
f"Request failed: {str(e)}",
TroubleSgltn.Severity.ERROR,
True
)
CGPT_response = "Server was unable to process the request"
return CGPT_response
class claude_request(Request):
"""Concrete class for Claude/Anthropic API requests"""
def request_completion(self, **kwargs) -> str:
claude_model = kwargs.get('model')
creative_latitude = kwargs.get('creative_latitude', 0.7)
tokens = kwargs.get('tokens', 500)
prompt = kwargs.get('prompt', "")
instruction = kwargs.get('instruction', "")
image = kwargs.get('image', None)
example_list = kwargs.get('example_list', [])
add_params = kwargs.get('add_params', None)
claude_response = ""
client = self.cFig.anthropic_client
self._initialize_retry_handler(**kwargs)
if not client:
self.j_mngr.log_events(
"Invalid or missing Anthropic API key. Keys must be stored in an environment variable.",
TroubleSgltn.Severity.ERROR,
True
)
return "Invalid or missing Anthropic API key"
# Build messages
messages = self.utils.build_data_claude(prompt, example_list, image)
# Handle empty input case
if not any([prompt, instruction, example_list]) and image is None:
return "Empty request, no input provided"
# Prepare request parameters
params = {
"model": claude_model,
"messages": messages,
"temperature": creative_latitude,
"system": instruction,
"max_tokens": tokens
}
if add_params:
self.j_mngr.append_params(params, add_params, ['param', 'value'])
try:
response = self.retry_handler.execute_with_retry(
self._make_request,
self.RequestType.ANTHROPIC,
client,
params
)
if response and 'error' not in response:
self._log_completion_metrics(response)
try:
claude_response = response.content[0].text
claude_response = self.utils.clean_response_text(claude_response)
except (IndexError, AttributeError):
claude_response = "No valid data was returned"
self.j_mngr.log_events(
"Claude response was not valid data",
TroubleSgltn.Severity.WARNING,
True
)
else:
claude_response = "Server was unable to process the request"
self.j_mngr.log_events(
'Server was unable to process this request.',
TroubleSgltn.Severity.ERROR,
True
)
except Exception as e:
error_msg = self.utils.parse_anthropic_error(e)
self.j_mngr.log_events(
f"Request failed: {error_msg}",
TroubleSgltn.Severity.ERROR,
True
)
claude_response = "Server was unable to process the request"
return claude_response
class genaiRequest(Request):
class CompletionMode(Enum):
TEXT = ['text',] # Standard text completion
TEXT_IMAGE = ['text','image',] # Multimodal completion that can return text and/or images
class CompletionAction(Enum):
CLIENT = 1
POST = 2
@property
def blank_tensor(self):
return torch.zeros(1, 1024, 1024, 3, dtype=torch.float32)
def adapt_gemini_to_openai_format(self, gemini_response, model="gemini-pro"):
"""
Adapts a Google Gemini API response to match the structure of an OpenAI API response.
This allows existing OpenAI-compatible methods to work with Gemini responses.
Args:
gemini_response: The response object from the Google Generative AI client
model: The model name used in the request (fallback if not in response)
Returns:
A dictionary structured like an OpenAI response
"""
# Create a base structure that mimics OpenAI response format
openai_format = {
"id": getattr(gemini_response, "response_id", "unknown"),
"object": "chat.completion",
"created": int(time.time()),
"model": getattr(gemini_response, "model_version", model),
"choices": [],
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0
},
"images": [] # Add images array for multimodal responses
}
image_tensors = []
message_content =""
# Extract text content and images from candidates
if hasattr(gemini_response, "candidates") and gemini_response.candidates:
for i, candidate in enumerate(gemini_response.candidates):
if hasattr(candidate, "content") and candidate.content:
# Extract text from content parts
if hasattr(candidate.content, "parts"):
for part in candidate.content.parts:
if hasattr(part, "text") and part.text:
message_content += part.text
# Check for image data
elif hasattr(part, "inline_data") and part.inline_data:
inline_data = part.inline_data
if (hasattr(inline_data, "data") and inline_data.data
and isinstance(inline_data.data, bytes)):
image_tensor = self.img_u.bytes_to_tensor(inline_data.data)
image_tensors.append(image_tensor)
# Create a choice object in OpenAI format
finish_reason = getattr(candidate, "finish_reason", None) if hasattr(candidate, "finish_reason") else None
choice = {
"index": getattr(candidate, "index", i) if hasattr(candidate, "index") else i,
"message": {
"role": "assistant",
"content": message_content
},
"finish_reason": self.translate_finish_reason(finish_reason)
}
openai_format["choices"].append(choice)
else:
# For simple responses with just .text property
if hasattr(gemini_response, "text"):
choice = {
"index": 0,
"message": {
"role": "assistant",
"content": gemini_response.text
},
"finish_reason": "stop"
}
openai_format["choices"].append(choice)
# Add combined image tensors to the OpenAI proxy object
if image_tensors:
cat_tensor = self.img_u.pad_images_to_batch(image_tensors)
openai_format['images'] = {
"tensor": cat_tensor,
"count": len(image_tensors)
}
self.j_mngr.log_events(
f"{len(image_tensors)} image(s) generated by Gemini and converted from binary to tensor.",
is_trouble=True
)
# Extract usage information
if hasattr(gemini_response, "usage_metadata"):
usage_metadata = gemini_response.usage_metadata
if hasattr(usage_metadata, "prompt_token_count"):
openai_format["usage"]["prompt_tokens"] = usage_metadata.prompt_token_count
if hasattr(usage_metadata, "candidates_token_count"):
openai_format["usage"]["completion_tokens"] = usage_metadata.candidates_token_count
if hasattr(usage_metadata, "total_token_count"):
openai_format["usage"]["total_tokens"] = usage_metadata.total_token_count
# Handle errors - directly include the native error structure
if hasattr(gemini_response, "error"):
openai_format["gemini_error"] = gemini_response.error
# Check if there was a safety block - include native format
if hasattr(gemini_response, "prompt_feedback") and hasattr(gemini_response.prompt_feedback, "block_reason") and gemini_response.prompt_feedback.block_reason:
openai_format["gemini_safety_block"] = {
"block_reason": gemini_response.prompt_feedback.block_reason,
"block_reason_message": getattr(gemini_response.prompt_feedback, "block_reason_message", ""),
"safety_ratings": getattr(gemini_response.prompt_feedback, "safety_ratings", [])
}
return openai_format
def translate_finish_reason(self, gemini_finish_reason):
"""Extracts the finish reason from Gemini API response"""
if not gemini_finish_reason:
return "Uknown" # Default value
# Extract string value if it's an enum
if hasattr(gemini_finish_reason, 'value'):
finish_reason = gemini_finish_reason.value
if finish_reason.lower() == "stop":
finish_reason = "Normal Completion"
else:
finish_reason = f"Warning, there were problems with this inference: {finish_reason}"
return finish_reason
# If it's already a string, return it directly
return gemini_finish_reason
def request_completion(self, **kwargs):
model = kwargs.get('model', 'gemini-pro')
prompt = kwargs.get('prompt', '')
instruction = kwargs.get('instruction', '')
tokens = kwargs.get('tokens', 1200)
creative_latitude = kwargs.get('creative_latitude', 0.7)
image = kwargs.get('image', None)
example_list = kwargs.get('example_list',[])
add_params = kwargs.get('add_params', [])
completion_mode = kwargs.get('completion_mode', self.CompletionMode.TEXT.value)
#completion_action = kwargs.get('completion_action', self.CompletionAction.CLIENT)
key = self.cFig.custom_key or self.cFig.gemini_key
content = self.utils.build_gemini_content(prompt, example_list, image) #U
gen_config_params = {
"max_output_tokens": tokens,
"temperature": creative_latitude,
"response_modalities": completion_mode
}
if instruction:
gen_config_params['system_instruction'] = instruction
if add_params:
self.j_mngr.append_params(gen_config_params,add_params, ["param","value"])
# Parameter name mapping for Gemini API if needed
self.utils.model_param_adjust(gen_config_params,RequestMode.GEMINI)
try:
# Create the content config with generation_config and response_modalities
content_config = types.GenerateContentConfig(
**gen_config_params
)
# Log the configuration being used
self.j_mngr.log_events(
f"Using GenerateContentConfig with response_modalities={completion_mode}",
TroubleSgltn.Severity.INFO,
False
)
# Set up client
client = genai.Client(api_key=key)
response = client.models.generate_content(
model=model,
contents=content,
config=content_config
)
openai_format_response = self.adapt_gemini_to_openai_format(response, model)
# Log metrics using the adapted format
self._log_completion_metrics(openai_format_response, "json")
if "choices" in openai_format_response:
finish_reasons = [choice.get('finish_reason', "N/A") for choice in openai_format_response["choices"]]
# Now you have a list of all finish reasons
self.j_mngr.log_events(f"Reasons for the inference finishing: {', '.join(finish_reasons)}", is_trouble=True)
# Check if there was an error
if "gemini_error" in openai_format_response:
error_msg = str(openai_format_response["gemini_error"])
self.j_mngr.log_events(
f"Gemini response error: {error_msg}",
TroubleSgltn.Severity.ERROR,
True
)
return f"Error: {error_msg}"
# Check if there was a safety block
if "gemini_safety_block" in openai_format_response:
block_reason = openai_format_response["gemini_safety_block"]["block_reason"]
block_message = openai_format_response["gemini_safety_block"]["block_reason_message"]
self.j_mngr.log_events(
f"Gemini response blocked: {block_reason} - {block_message}",
TroubleSgltn.Severity.ERROR,
True
)
return f"Error: Content blocked - {block_message}"
# Get text content if available
text_content = ""
if openai_format_response["choices"]:
text_content = openai_format_response["choices"][0]["message"]["content"]
# Return based on completion mode
if completion_mode == self.CompletionMode.TEXT.value:
# Text only mode - return just the text content
return {"text": text_content}
if completion_mode == self.CompletionMode.TEXT_IMAGE.value:
# Text and image mode - return appropriate structure based on what's available
if openai_format_response["images"]:
return {
"text": text_content,
"images": openai_format_response["images"]
}
else:
return {
"text": text_content,
"images": {"tensor": self.blank_tensor, "count":0}
}
# Default fallback (shouldn't reach here if enum is used properly)
return {"text": text_content,
"images": {"tensor": self.blank_tensor, "count":0}}
except Exception as e:
self.j_mngr.log_events(f"An Error occurred when processing the Gemini Completion request. This process was not completed. Error: {e}",
TroubleSgltn.Severity.ERROR,
True)
return {
"text": f"Error: {e}",
"images": {"tensor": self.blank_tensor, "count":0}
}
class oai_web_request(Request):
"""Concrete class for OpenAI-compatible web requests"""
def request_completion(self, **kwargs) -> str:
GPTmodel = kwargs.get('model', "")
creative_latitude = kwargs.get('creative_latitude', 0.7)
url = kwargs.get('url', None)
tokens = kwargs.get('tokens', 500)
image = kwargs.get('image', None)
prompt = kwargs.get('prompt', None)
instruction = kwargs.get('instruction', "")
example_list = kwargs.get('example_list', [])
add_params = kwargs.get('add_params', None)