-
Notifications
You must be signed in to change notification settings - Fork 27
/
LLM.py
801 lines (710 loc) · 30.7 KB
/
LLM.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
from openai import AzureOpenAI, OpenAI,AsyncAzureOpenAI,AsyncOpenAI
from anthropic import Anthropic,AsyncAnthropic
from zhipuai import ZhipuAI
from dashscope import Generation
from dashscope.aigc.generation import AioGeneration
from abc import abstractmethod
from http import HTTPStatus
import platform
import dashscope
import yaml
import os
with open('config.yaml', 'r') as file:
config = yaml.safe_load(file)
for key, value in config.items():
os.environ[key] = str(value)
import httpx
import logging
import json
import time
from tenacity import (
retry,
stop_after_attempt,
wait_fixed,
)
import asyncio
import requests
from PIL import Image
from io import BytesIO
from utils import fetch_image,get_openai_url,encode_image
def before_retry_fn(retry_state):
if retry_state.attempt_number > 1:
logging.info(f"Retrying API call. Attempt #{retry_state.attempt_number}, f{retry_state}")
token_log_file = os.environ.get("TOKEN_LOG_FILE", "logs/token.json")
class base_llm:
def __init__(self) -> None:
pass
@abstractmethod
def response(self,messages,**kwargs):
pass
def get_imgs(self,prompt, save_path="saves/dalle3.jpg"):
pass
class base_img_llm(base_llm):
def __init__(self) -> None:
pass
@abstractmethod
def get_img(self,prompt, save_path="saves/dalle3.jpg"):
pass
class openai_llm(base_llm):
def __init__(self) -> None:
super().__init__()
is_azure = config.get("is_azure", True)
if is_azure:
if "AZURE_OPENAI_ENDPOINT" not in os.environ or os.environ["AZURE_OPENAI_ENDPOINT"] == "":
raise ValueError("AZURE_OPENAI_ENDPOINT is not set")
if "AZURE_OPENAI_KEY" not in os.environ or os.environ["AZURE_OPENAI_KEY"] == "":
raise ValueError("AZURE_OPENAI_KEY is not set")
api_version = os.environ.get("AZURE_OPENAI_API_VERSION",None)
if api_version == "":
api_version = None
self.client = AzureOpenAI(
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
api_key=os.environ["AZURE_OPENAI_KEY"],
api_version= api_version
)
self.async_client = AsyncAzureOpenAI(
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
api_key=os.environ["AZURE_OPENAI_KEY"],
api_version= api_version
)
else:
if "OPENAI_API_KEY" not in os.environ or os.environ["OPENAI_API_KEY"] == "":
raise ValueError("OPENAI_API_KEY is not set")
api_key = os.environ.get("OPENAI_API_KEY",None)
proxy_url = os.environ.get("OPENAI_PROXY_URL", None)
if proxy_url == "":
proxy_url = None
base_url = os.environ.get("OPENAI_BASE_URL", None)
if base_url == "":
base_url = None
http_client = httpx.Client(proxy=proxy_url) if proxy_url else None
async_http_client = httpx.AsyncClient(proxy=proxy_url) if proxy_url else None
self.client = OpenAI(api_key=api_key,base_url=base_url,http_client=http_client)
self.async_client = AsyncOpenAI(api_key=api_key,base_url=base_url,http_client=async_http_client)
def process_messages(self, messages):
new_messages = []
for message in messages:
if message["role"] == "user":
content = message["content"]
if isinstance(content, list):
new_content= []
for c in content:
if c["type"] == "image":
new_content.append({"type":"image_url","image_url":{"url":get_openai_url(c["url"]),"detail":"high"}})
else:
new_content.append(c)
new_messages.append({"role":"user","content":new_content})
else:
new_messages.append(message)
else:
new_messages.append(message)
return new_messages
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
def response(self,messages,**kwargs):
messages = self.process_messages(messages)
try:
response = self.client.chat.completions.create(
# gpt-35-turbo-16k gpt4-turbo-2024-04-29 gpt-4o-2
model=kwargs.get("model", "gpt-35-turbo-16k"),
messages=messages,
n = kwargs.get("n", 1),
temperature= kwargs.get("temperature", 0.7),
max_tokens=kwargs.get("max_tokens", 4000),
timeout=kwargs.get("timeout", 180)
)
except Exception as e:
model = kwargs.get("model", "gpt-35-turbo-16k")
print(f"get {model} response failed: {e}")
logging.info(e)
return
if not os.path.exists(token_log_file):
with open(token_log_file, "w") as f:
json.dump({},f)
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = kwargs.get("model", "gpt-35-turbo-16k")
if current_model not in tokens:
tokens[current_model] = [0,0]
tokens[current_model][0] += response.usage.prompt_tokens
tokens[current_model][1] += response.usage.completion_tokens
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return response.choices[0].message.content
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
async def response_async(self,messages,**kwargs):
messages = self.process_messages(messages)
try:
response = await self.async_client.chat.completions.create(
# gpt-35-turbo-16k gpt4-turbo-2024-04-29 gpt-4o-2
model=kwargs.get("model", "gpt-35-turbo-16k"),
messages=messages,
n = kwargs.get("n", 1),
temperature= kwargs.get("temperature", 0.7),
max_tokens=kwargs.get("max_tokens", 4000),
timeout=kwargs.get("timeout", 180)
)
except Exception as e:
model = kwargs.get("model", "gpt-35-turbo-16k")
print(f"get {model} response failed: {e}")
logging.info(e)
return
if not os.path.exists(token_log_file):
with open(token_log_file, "w") as f:
json.dump({},f)
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = kwargs.get("model", "gpt-35-turbo-16k")
if current_model not in tokens:
tokens[current_model] = [0,0]
tokens[current_model][0] += response.usage.prompt_tokens
tokens[current_model][1] += response.usage.completion_tokens
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return response.choices[0].message.content
class claude_llm(base_llm):
def __init__(self) -> None:
super().__init__()
if "CLAUDE_API_KEY" not in os.environ or os.environ["CLAUDE_API_KEY"] == "":
raise ValueError("CLAUDE_API_KEY is not set")
self.client = Anthropic(api_key=os.environ["CLAUDE_API_KEY"])
self.async_client = AsyncAnthropic(api_key=os.environ["CLAUDE_API_KEY"])
def process_messages(self, messages):
new_messages = []
for message in messages:
if message["role"] == "user":
content = message["content"]
if isinstance(content, list):
new_content = []
for c in content:
if c["type"] == "image":
image_type = c["url"].split(".")[-1]
if image_type == "jpg":
image_type = "jpeg"
new_content.append({"type":"image","source":{"type":"base64","media_type":f"image/{image_type}","data":encode_image(c["url"])}})
else:
new_content.append(c)
new_messages.append({"role":"user","content":new_content})
else:
new_messages.append(message)
else:
new_messages.append(message)
return new_messages
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
def response(self, messages, **kwargs):
messages = self.process_messages(messages)
try:
response = self.client.messages.create(
model = kwargs.get("model", "claude-3-5-sonnet-20240620"),
temperature= kwargs.get("temperature", 0.7),
max_tokens=kwargs.get("max_tokens", 4000),
messages=messages,
timeout=kwargs.get("timeout", 180)
)
except Exception as e:
model = kwargs.get("model", "gpt-35-turbo-16k")
print(f"get {model} response failed: {e}")
print(e)
logging.info(e)
return
if not os.path.exists(token_log_file):
with open(token_log_file, "w") as f:
json.dump({},f)
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = kwargs.get("model", "gpt-35-turbo-16k")
if current_model not in tokens:
tokens[current_model] = [0,0]
tokens[current_model][0] += response.usage.input_tokens
tokens[current_model][1] += response.usage.output_tokens
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return response.content[0].text
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
async def response_async(self, messages, **kwargs):
messages = self.process_messages(messages)
try:
response = await self.async_client.messages.create(
model = kwargs.get("model", "claude-3-5-sonnet-20240620"),
temperature= kwargs.get("temperature", 0.7),
max_tokens=kwargs.get("max_tokens", 4000),
messages=messages,
timeout=kwargs.get("timeout", 180)
)
except Exception as e:
model = kwargs.get("model", "gpt-35-turbo-16k")
print(f"get {model} response failed: {e}")
logging.info(e)
return
if not os.path.exists(token_log_file):
with open(token_log_file, "w") as f:
json.dump({},f)
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = kwargs.get("model", "gpt-35-turbo-16k")
if current_model not in tokens:
tokens[current_model] = [0,0]
tokens[current_model][0] += response.usage.input_tokens
tokens[current_model][1] += response.usage.output_tokens
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return response.content[0].text
class glm_llm(base_llm):
def __init__(self) -> None:
super().__init__()
if "GLM_API_KEY" not in os.environ or os.environ["GLM_API_KEY"] == "":
raise ValueError("GLM_API_KEY is not set")
self.client = ZhipuAI(api_key=os.environ["GLM_API_KEY"])
def process_messages(self, messages):
new_messages = []
for message in messages:
if message["role"] == "user":
content = message["content"]
if isinstance(content, list):
new_content= []
for c in content:
if c["type"] == "image":
new_content.append({"type":"image_url","image_url":{"url":get_openai_url(c["url"]),"detail":"high"}})
else:
new_content.append(c)
new_messages.append({"role":"user","content":new_content})
else:
new_messages.append(message)
else:
new_messages.append(message)
return new_messages
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
def response(self, messages, **kwargs):
messages = self.process_messages(messages)
try:
response = self.client.chat.completions.create(
model = kwargs.get("model", "glm-4v"),
messages = messages,
timeout = kwargs.get("timeout", 180),
max_tokens=kwargs.get("max_tokens", 4000)
)
except Exception as e:
model = kwargs.get("model", "glm-4v")
print(f"get {model} response failed: {e}")
print(e)
logging.info(e)
return
if not os.path.exists(token_log_file):
with open(token_log_file, "w") as f:
json.dump({},f)
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = kwargs.get("model", "glm-4")
if current_model not in tokens:
tokens[current_model] = [0,0]
tokens[current_model][0] += response.usage.prompt_tokens
tokens[current_model][1] += response.usage.completion_tokens
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return response.choices[0].message.content
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
async def response_async(self, messages, **kwargs):
messages = self.process_messages(messages)
try:
response_total = self.client.chat.asyncCompletions.create(
model = kwargs.get("model", "glm-4"),
messages = messages,
timeout = kwargs.get("timeout", 180),
max_tokens=kwargs.get("max_tokens", 4000),
)
task_id = response_total.id
task_status = response_total.task_status
async def time_sleep():
await asyncio.sleep(1)
get_cnt = 0
while task_status != 'SUCCESS' and task_status != 'FAILED' and get_cnt <= 40:
await time_sleep()
result_response = self.client.chat.asyncCompletions.retrieve_completion_result(id=task_id)
task_status = result_response.task_status
time.sleep(2)
get_cnt += 1
response = result_response
except Exception as e:
model = kwargs.get("model", "glm-4v")
print(f"get {model} response failed: {e}")
print(e)
logging.info(e)
return
if not os.path.exists(token_log_file):
with open(token_log_file, "w") as f:
json.dump({},f)
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = kwargs.get("model", "glm-4v")
if current_model not in tokens:
tokens[current_model] = [0,0]
tokens[current_model][0] += response.usage.prompt_tokens
tokens[current_model][1] += response.usage.completion_tokens
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return response.choices[0].message.content
class qwen_llm(base_llm):
def __init__(self) -> None:
super().__init__()
if "DASHSCOPE_API_KEY" not in os.environ or os.environ["DASHSCOPE_API_KEY"] == "":
raise ValueError("DASHSCOPE_API_KEY is not set")
dashscope.api_key = os.environ["DASHSCOPE_API_KEY"]
def process_messages(self, messages):
new_messages = []
for message in messages:
if message["role"] == "user":
content = message["content"]
if isinstance(content, list):
new_content= []
for c in content:
if c["type"] == "image":
new_content.append({"type":"image_url","image_url":{"url":get_openai_url(c["url"]),"detail":"high"}})
else:
new_content.append(c)
new_messages.append({"role":"user","content":new_content})
else:
new_messages.append(message)
else:
new_messages.append(message)
return new_messages
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
def response(self, messages, **kwargs):
messages = self.process_messages(messages)
try:
response = Generation.call(
model = kwargs.get("model", "qwen-max-longcontext"),
messages = messages,
timeout = kwargs.get("timeout", 180),
max_tokens=kwargs.get("max_tokens", 4000),
result_format = "message"
)
except Exception as e:
model = kwargs.get("model", "qwen-max-longcontext")
print(f"get {model} response failed: {e}")
print(e)
logging.info(e)
return
if not os.path.exists(token_log_file):
with open(token_log_file, "w") as f:
json.dump({},f)
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = kwargs.get("model", "qwen-max-longcontext")
if current_model not in tokens:
tokens[current_model] = [0,0]
tokens[current_model][0] += response.usage.input_tokens
tokens[current_model][1] += response.usage.output_tokens
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return response.output.choices[0].message.content
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
async def response_async(self, messages, **kwargs):
messages = self.process_messages(messages)
try:
response = await AioGeneration.call(
model = kwargs.get("model", "qwen-max-longcontext"),
messages = messages,
timeout = kwargs.get("timeout", 180),
max_tokens=kwargs.get("max_tokens", 4000),
result_format = "message"
)
except Exception as e:
print("response:",response)
model = kwargs.get("model", "qwen-max-longcontext")
print(f"get {model} response failed: {e}")
logging.info(e)
return
if not os.path.exists(token_log_file):
with open(token_log_file, "w") as f:
json.dump({},f)
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = kwargs.get("model", "qwen-max-longcontext")
if current_model not in tokens:
tokens[current_model] = [0,0]
tokens[current_model][0] += response.usage.input_tokens
tokens[current_model][1] += response.usage.output_tokens
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return response.output.choices[0].message.content
class Dalle3_llm(base_img_llm):
def __init__(self) -> None:
super().__init__()
is_azure = config.get("is_azure", True)
if is_azure:
api_version = os.environ.get("AZURE_OPENAI_API_VERSION",None)
if api_version == "":
api_version = None
self.client = AzureOpenAI(
azure_endpoint=os.environ["AZURE_OPENAI_DALLE_ENDPOINT"],
api_key=os.environ["AZURE_OPENAI_DALLE_KEY"],
api_version= api_version
)
self.async_client = AsyncAzureOpenAI(
azure_endpoint=os.environ["AZURE_OPENAI_DALLE_ENDPOINT"],
api_key=os.environ["AZURE_OPENAI_DALLE_KEY"],
api_version= api_version
)
else:
api_key = os.environ.get("OPENAI_API_KEY",None)
proxy_url = os.environ.get("OPENAI_PROXY_URL", None)
if proxy_url == "":
proxy_url = None
base_url = os.environ.get("OPENAI_BASE_URL", None)
if base_url == "":
base_url = None
http_client = httpx.Client(proxy=proxy_url) if proxy_url else None
async_http_client = httpx.AsyncClient(proxy=proxy_url) if proxy_url else None
self.client = OpenAI(api_key=api_key,base_url=base_url,http_client=http_client)
self.async_client = AsyncOpenAI(api_key=api_key,base_url=base_url,http_client=async_http_client)
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
def get_img(self,prompt, save_path="saves/dalle3.jpg"):
try:
return self._get_img(prompt, save_path)
except Exception as e:
# Catch the specific safety warning and modify the prompt
if "Your prompt may contain text that is not allowed by our safety system." in str(e):
logging.info(f"Safety system error with prompt: {prompt}. Modifying prompt and retrying.")
new_prompt = "a colorful abstract painting of a cat"
return self._get_img(new_prompt, save_path)
print("Error: generate img failed",e)
def _get_img(self,prompt, save_path):
img_client = self.client
result = img_client.images.generate(
model="dalle3",
prompt=prompt,
n=1,
timeout=180
)
image_url = json.loads(result.model_dump_json())['data'][0]['url']
img = requests.get(image_url).content
img = Image.open(BytesIO(img))
img.save(save_path)
# Log token usage
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = "dalle3"
if current_model not in tokens:
tokens[current_model] = 0
tokens[current_model] += 1
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return img
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
async def get_img_async(self,prompt, save_path="saves/dalle3.jpg"):
try:
return await self._get_img_async(prompt, save_path)
except Exception as e:
# Catch the specific safety warning and modify the prompt
if "Your prompt may contain text that is not allowed by our safety system." in str(e):
logging.info(f"Safety system error with prompt: {prompt}. Modifying prompt and retrying.")
new_prompt = "a colorful abstract painting of a cat"
return await self._get_img_async(new_prompt, save_path)
print("Error: generate img failed",e)
async def _get_img_async(self,prompt, save_path):
img_client = self.async_client
result = await img_client.images.generate(
model="dalle3",
prompt=prompt,
n=1,
timeout=180
)
image_url = json.loads(result.model_dump_json())['data'][0]['url']
img = await fetch_image(image_url)
img = Image.open(BytesIO(img))
img.save(save_path)
# Log token usage
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = "dalle3"
if current_model not in tokens:
tokens[current_model] = 0
tokens[current_model] += 1
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return img
class cogview3_llm(base_img_llm):
def __init__(self) -> None:
super().__init__()
self.client = ZhipuAI(api_key=os.environ["GLM_API_KEY"])
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
def get_img(self,prompt, save_path="saves/cogview-3.jpg"):
try:
return self._get_img(prompt, save_path)
except Exception as e:
# Catch the specific safety warning and modify the prompt
try:
new_prompt = "一只可爱的小猫在草地奔跑"
return self._get_img(new_prompt, save_path)
except Exception as e:
print("Error: generate img failed",e)
def _get_img(self,prompt, save_path):
result = self.client.images.generations(
model="cogview-3",
prompt=prompt,
n=1,
timeout=180
)
image_url = json.loads(result.model_dump_json())['data'][0]['url']
img = requests.get(image_url).content
img = Image.open(BytesIO(img))
img.save(save_path)
# Log token usage
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = "cogview-3"
if current_model not in tokens:
tokens[current_model] = 0
tokens[current_model] += 1
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return img
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
async def get_img_async(self,prompt, save_path="saves/cogview-3.jpg"):
try:
return await self._get_img_async(prompt, save_path)
except Exception as e:
# Catch the specific safety warning and modify the prompt
try:
new_prompt = "一只可爱的小猫在草地奔跑"
return await self._get_img_async(new_prompt, save_path)
except Exception as e:
print("Error: generate img failed",e)
async def _get_img_async(self,prompt, save_path):
result = self.client.images.generations(
model="cogview-3",
prompt=prompt,
n=1,
timeout=180
)
image_url = json.loads(result.model_dump_json())['data'][0]['url']
img = await fetch_image(image_url)
img = Image.open(BytesIO(img))
img.save(save_path)
# Log token usage
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = "cogview-3"
if current_model not in tokens:
tokens[current_model] = 0
tokens[current_model] += 1
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return img
class sd3_img_llm(base_img_llm):
def __init__(self) -> None:
super().__init__()
self.api_key = os.environ.get("SD3_API_KEY", None)
def get_keys(self):
keys = []
with open(token_log_file, "r") as f:
tokens = json.load(f)
for key in tokens.keys():
keys.append(key)
return keys
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
def get_img(self,prompt, save_path="saves/sd3.jpg"):
try:
return self._get_img(prompt, save_path)
except Exception as e:
# Catch the specific safety warning and modify the prompt
try:
new_prompt = "a colorful abstract painting of a cat"
return self._get_img(new_prompt, save_path)
except Exception as e:
print("Error: generate img failed",e)
def _get_img(self,prompt, save_path):
url = "https://api.siliconflow.cn/v1/stabilityai/stable-diffusion-3-medium/text-to-image"
payload = {
"prompt": prompt,
"image_size": "1024x1024",
"batch_size": 1,
"num_inference_steps": 20,
"guidance_scale": 7
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": "Bearer " + self.api_key
}
response = requests.post(url, json=payload, headers=headers)
image_url = response.json()["images"][0]["url"]
img = requests.get(image_url).content
img = Image.open(BytesIO(img))
img.save(save_path)
# Log token usage
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = "sd3"
if current_model not in tokens:
tokens[current_model] = 0
tokens[current_model] += 1
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return img
@retry(wait=wait_fixed(10), stop=stop_after_attempt(10), before=before_retry_fn)
async def get_img_async(self,prompt, save_path="saves/sd3.jpg"):
try:
return await self._get_img_async(prompt, save_path)
except Exception as e:
# Catch the specific safety warning and modify the prompt
try:
new_prompt = "a colorful abstract painting of a cat"
return await self._get_img_async(new_prompt, save_path)
except Exception as e:
print("Error: generate img failed",e)
async def _get_img_async(self,prompt, save_path):
url = "https://api.siliconflow.cn/v1/stabilityai/stable-diffusion-3-medium/text-to-image"
payload = {
"prompt": prompt,
"image_size": "1024x1024",
"batch_size": 1,
"num_inference_steps": 20,
"guidance_scale": 7
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": "Bearer " + self.api_key
}
response = requests.post(url, json=payload, headers=headers)
image_url = response.json()["images"][0]["url"]
img = await fetch_image(image_url)
img = Image.open(BytesIO(img))
img.save(save_path)
# Log token usage
with open(token_log_file, "r") as f:
tokens = json.load(f)
current_model = "sd3"
if current_model not in tokens:
tokens[current_model] = 0
tokens[current_model] += 1
with open(token_log_file, "w") as f:
json.dump(tokens, f)
return img
def get_llm():
llm_type = config.get("LLM_TYPE", "openai")
img_gen_type = config.get("IMG_GEN_TYPE", "dalle3")
llm , img_generator = None,None
if llm_type in ["openai"]:
llm = openai_llm()
elif llm_type == "claude":
llm = claude_llm()
elif llm_type == "glm":
llm = glm_llm()
elif llm_type == "qwen":
llm = qwen_llm()
else:
raise ValueError(f"Unknown LLM type: {llm_type}")
if img_gen_type == "dalle3":
img_generator = Dalle3_llm()
elif img_gen_type == "cogview-3":
img_generator = cogview3_llm()
elif img_gen_type == "sd3":
img_generator = sd3_img_llm()
else:
raise ValueError(f"Unknown image generator type: {img_gen_type}")
return llm, img_generator
if __name__ == "__main__":
img_llm = sd3_img_llm()
prompt = "孙悟空大战猪八戒"
img_llm.get_img(prompt,"1.jpg")