-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathIFLLMNode.py
1714 lines (1500 loc) · 75.6 KB
/
IFLLMNode.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
# IFLLMNode.py
import os
import sys
import json
import torch
import asyncio
import requests
from PIL import Image
from io import BytesIO
import tempfile
import time
from typing import List, Dict, Any, Optional, Union, Tuple
from pathlib import Path
from .send_request import send_request
from .utils import (
get_api_key,
get_models,
process_images_for_comfy,
clean_text,
load_placeholder_image,
validate_models,
save_combo_settings,
load_combo_settings,
create_settings_from_ui,
prepare_batch_images,
process_auto_mode_images,
tensor_to_pil,
gemini2_process_images,
gemini2_prepare_response,
gemini2_create_client,
validate_gemini_key
)
import base64
import numpy as np
import codecs
import random
import math
# Add Google Gemini SDK imports
try:
from google import genai
from google.genai import types
GEMINI_SDK_AVAILABLE = True
except ImportError:
GEMINI_SDK_AVAILABLE = False
print("Google Generative AI SDK not found. Install with: pip install google-generativeai")
# Add ComfyUI directory to path
comfy_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
if comfy_path not in sys.path:
sys.path.insert(0, comfy_path)
try:
import folder_paths
except ImportError:
print("Error: Could not import folder_paths. Make sure ComfyUI core is in your Python path.")
folder_paths = None
# Set up logging
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
try:
from server import PromptServer
from aiohttp import web
@PromptServer.instance.routes.post("/IF_LLM/get_llm_models")
async def get_llm_models_endpoint(request):
try:
data = await request.json()
llm_provider = data.get("llm_provider")
engine = llm_provider
base_ip = data.get("base_ip")
port = data.get("port")
external_api_key = data.get("external_api_key")
if external_api_key:
api_key = external_api_key
else:
api_key_name = f"{llm_provider.upper()}_API_KEY"
try:
api_key = get_api_key(api_key_name, engine)
except ValueError:
api_key = None
node = IFLLM()
models = node.get_models(engine, base_ip, port, api_key)
return web.json_response(models)
except Exception as e:
print(f"Error in get_llm_models_endpoint: {str(e)}")
return web.json_response([], status=500)
@PromptServer.instance.routes.post("/IF_LLM/add_routes")
async def add_routes_endpoint(request):
return web.json_response({"status": "success"})
@PromptServer.instance.routes.post("/IF_LLM/save_combo_settings")
async def save_combo_settings_endpoint(request):
try:
data = await request.json()
# Convert UI settings to proper format
settings = create_settings_from_ui(data)
# Get node instance
node = IFLLM()
# Save settings
saved_settings = save_combo_settings(settings, node.combo_presets_dir)
return web.json_response({
"status": "success",
"message": "Combo settings saved successfully",
"settings": saved_settings
})
except Exception as e:
logger.error(f"Error saving combo settings: {str(e)}")
return web.json_response({
"status": "error",
"message": str(e)
}, status=500)
except AttributeError:
print("PromptServer.instance not available. Skipping route decoration for IF_LLM.")
class IFLLM:
def __init__(self):
self.strategies = "normal"
# Initialize paths and load presets
# Get the directory where the current script is located
current_dir = os.path.dirname(os.path.abspath(__file__))
# Build paths relative to the script location
self.presets_dir = os.path.join(current_dir, "IF_AI", "presets")
self.combo_presets_dir = os.path.join(self.presets_dir, "AutoCombo")
# Load preset configurations
self.profiles = self.load_presets(os.path.join(self.presets_dir, "profiles.json"))
self.neg_prompts = self.load_presets(os.path.join(self.presets_dir, "neg_prompts.json"))
self.embellish_prompts = self.load_presets(os.path.join(self.presets_dir, "embellishments.json"))
self.style_prompts = self.load_presets(os.path.join(self.presets_dir, "style_prompts.json"))
self.stop_strings = self.load_presets(os.path.join(self.presets_dir, "stop_strings.json"))
# Initialize placeholder image path
self.placeholder_image_path = os.path.join(self.presets_dir, "placeholder.png")
# Default values
self.base_ip = "localhost"
self.port = "11434"
self.engine = "transformers"
self.selected_model = "Qwen2.5-VL-3B-Instruct-AWQ"
self.profile = "IF_PromptMKR_IMG"
self.messages = []
self.keep_alive = False
self.seed = 94687328150
self.history_steps = 10
self.external_api_key = ""
self.preset = "Default"
self.precision = "fp16"
self.attention = "sdpa"
self.Omni = None
self.mask = None
self.aspect_ratio = "1:1"
self.keep_alive = False
self.clear_history = False
self.random = False
self.max_tokens = 2048
self.temperature = 0.8
self.top_k = 40
self.top_p = 0.9
self.repeat_penalty = 1.1
self.batch_count = 4
@classmethod
def INPUT_TYPES(cls):
node = cls()
return {
"required": {
"llm_provider": (["transformers","llamacpp", "ollama", "kobold", "lmstudio", "textgen", "groq", "gemini", "openai", "anthropic", "mistral","deepseek","xai"], {"default": "transformers"}),
"llm_model": ((), {}),
"base_ip": ("STRING", {"default": "localhost"}),
"port": ("STRING", {"default": "11434"}),
"user_prompt": ("STRING", {"multiline": True}),
},
"optional": {
"images": ("IMAGE", {"list": True}),
"strategy": (["normal", "omost", "create", "edit", "variations", "gemini2_create"], {"default": "normal"}),
"mask": ("MASK", {}),
"prime_directives": ("STRING", {"forceInput": True, "tooltip": "The system prompt for the LLM."}),
"profiles": (["None"] + list(cls().profiles.keys()), {"default": "None", "tooltip": "The pre-defined system_prompt from the json profile file on the presets folder you can edit or make your own will be listed here."}),
"embellish_prompt": (list(cls().embellish_prompts.keys()), {"tooltip": "The pre-defined embellishment from the json embellishments file on the presets folder you can edit or make your own will be listed here."}),
"style_prompt": (list(cls().style_prompts.keys()), {"tooltip": "The pre-defined style from the json style_prompts file on the presets folder you can edit or make your own will be listed here."}),
"neg_prompt": (list(cls().neg_prompts.keys()), {"tooltip": "The pre-defined negative prompt from the json neg_prompts file on the presets folder you can edit or make your own will be listed here."}),
"stop_string": (list(cls().stop_strings.keys()), {"tooltip": "Specifies a string at which text generation should stop."}),
"max_tokens": ("INT", {"default": 2048, "min": 1, "max": 8192, "tooltip": "Maximum number of tokens to generate in the response."}),
"random": ("BOOLEAN", {"default": False, "label_on": "Seed", "label_off": "Temperature", "tooltip": "Toggles between using a fixed seed or temperature-based randomness."}),
"seed": ("INT", {"default": 0, "tooltip": "Random seed for reproducible outputs."}),
"keep_alive": ("BOOLEAN", {"default": True, "label_on": "Keeps Model on Memory", "label_off": "Unloads Model from Memory", "tooltip": "Determines whether to keep the model loaded in memory between calls."}),
"clear_history": ("BOOLEAN", {"default": True, "label_on": "Clear History", "label_off": "Keep History", "tooltip": "Determines whether to clear the history between calls."}),
"history_steps": ("INT", {"default": 10, "tooltip": "Number of steps to keep in history."}),
"aspect_ratio": (["1:1", "16:9", "4:5", "3:4", "5:4", "9:16"], {"default": "1:1", "tooltip": "Aspect ratio for the generated images."}),
"auto": ("BOOLEAN", {"default": False, "label_on": "Auto Is Enabled", "label_off": "Auto is Disabled", "tooltip": "If true, it generates auto promts based on the listed images click the save Auto settings to set the auto prompt generation file"}),
"batch_count": ("INT", {"default": 1, "tooltip": "Number of images to generate. only for create, edit and variations strategies."}),
"external_api_key": ("STRING", {"default": "", "tooltip": "If this is not empty, it will be used instead of the API key from the .env file. Make sure it is empty to use the .env file."}),
"Omni": ("OMNI", {"default": None, "tooltip": "Additional input for the selected tool."}),
"attention": (["sdpa", "flash_attention_2", "xformers"], {"default": "sdpa", "tooltip": "Select attention mechanism on Transformer models."}),
},
"hidden": {
"temperature": ("FLOAT", {"default": 0.8, "min": 0.0, "max": 1.0, "tooltip": "Controls randomness in output generation. Higher values increase creativity but may reduce coherence."}),
"top_k": ("INT", {"default": 40, "tooltip": "Limits the next token selection to the K most likely tokens."}),
"top_p": ("FLOAT", {"default": 0.9, "tooltip": "Cumulative probability cutoff for token selection."}),
"repeat_penalty": ("FLOAT", {"default": 1.1, "tooltip": "Penalizes repetition in generated text."}),
"precision": (["fp16", "fp32", "bf16"], {"tooltip": "Select preccision on Transformer models."}),
},
}
RETURN_TYPES = ("STRING", "STRING", "STRING", "OMNI", "IMAGE", "MASK")
RETURN_NAMES = ("question", "response", "negative", "omni", "generated_images", "mask")
FUNCTION = "process_image_wrapper"
OUTPUT_NODE = True
CATEGORY = "ImpactFrames💥🎞️/IF_LLM"
@classmethod
def IS_CHANGED(cls, llm_provider, llm_model, **kwargs):
# Only report a change when the model or provider has actually changed
# This prevents ComfyUI from resetting the model selection
# Using a unique identifier instead of random to maintain consistency
import hashlib
# Create a unique hash based on the provider and model
unique_id = f"{llm_provider}:{llm_model}"
hash_obj = hashlib.md5(unique_id.encode())
# Return a deterministic value based on the hash
# This ensures the same provider/model combo always returns the same value
# but different combos return different values
return int(hash_obj.hexdigest(), 16) / (2**128)
async def process_image(
self,
llm_provider: str,
llm_model: str,
base_ip: str,
port: str,
user_prompt: str,
strategy: str = "normal",
images=None,
messages=None,
prime_directives: Optional[str] = None,
profiles: Optional[str] = None,
embellish_prompt: Optional[str] = None,
style_prompt: Optional[str] = None,
neg_prompt: Optional[str] = None,
stop_string: Optional[str] = None,
max_tokens: int = 2048,
seed: int = 0,
random: bool = False,
temperature: float = 0.8,
top_k: int = 40,
top_p: float = 0.9,
repeat_penalty: float = 1.1,
keep_alive: bool = False,
clear_history: bool = False,
history_steps: int = 10,
external_api_key: str = "",
precision: str = "fp16",
attention: str = "sdpa",
Omni: Optional[str] = None,
aspect_ratio: str = "1:1",
mask: Optional[torch.Tensor] = None,
batch_count: int = 4,
auto: bool = False,
auto_mode: bool = False,
**kwargs
) -> Union[str, Dict[str, Any]]:
try:
# Initialize variables at the start
formatted_response = None
generated_images = None
generated_masks = None
tool_output = None
current_images = None
current_mask = None
if external_api_key != "":
llm_api_key = external_api_key
else:
llm_api_key = get_api_key(f"{llm_provider.upper()}_API_KEY", llm_provider)
print(f"LLM API key: {llm_api_key[:5]}...")
# Validate LLM model
validate_models(llm_model, llm_provider, "LLM", base_ip, port, llm_api_key)
# Handle history
messages = messages or []
if clear_history:
messages = []
elif history_steps > 0:
messages = messages[-history_steps:]
# Handle stop
if stop_string is None or stop_string == "None":
stop_content = None
else:
stop_content = self.stop_strings.get(stop_string, None)
stop = stop_content
if llm_provider not in ["ollama", "llamacpp", "vllm", "lmstudio", "gemeni"]:
if llm_provider == "kobold":
stop = stop_content + \
["\n\n\n\n\n"] if stop_content else ["\n\n\n\n\n"]
elif llm_provider == "mistral":
stop = stop_content + \
["\n\n"] if stop_content else ["\n\n"]
else:
stop = stop_content if stop_content else None
# Prepare embellishments and styles
embellish_content = self.embellish_prompts.get(embellish_prompt, "").strip() if embellish_prompt else ""
style_content = self.style_prompts.get(style_prompt, "").strip() if style_prompt else ""
neg_content = self.neg_prompts.get(neg_prompt, "").strip() if neg_prompt else ""
profile_content = self.profiles.get(profiles, "")
# Prepare system prompt
if prime_directives is not None:
system_message = prime_directives
else:
system_message= json.dumps(profile_content)
tool_type = Omni
strategy_name = strategy
kwargs = {
'batch_count': batch_count,
'llm_provider': llm_provider,
'base_ip': base_ip,
'port': port,
'llm_model': llm_model,
'system_message': system_message,
'seed': seed,
'temperature': temperature,
'max_tokens': max_tokens,
'random': random,
'top_k': top_k,
'top_p': top_p,
'repeat_penalty': repeat_penalty,
'stop': stop,
'keep_alive': keep_alive,
'llm_api_key': llm_api_key,
'precision': precision,
'attention': attention,
'aspect_ratio': aspect_ratio,
'neg_prompt': neg_prompt,
'neg_content': neg_content,
'formatted_response': formatted_response,
'generated_images': generated_images,
'generated_masks': generated_masks,
'tool_output': tool_output,
'omni': tool_type,
}
# If images is None or empty, skip "image-based" logic but still allow LLM tasks to proceed
if images is not None and len(images) > 0:
current_images = images
else:
print("No images connected; continuing with text-based tasks only.")
# If no mask is connected, load a placeholder or just skip
if mask is not None:
current_mask = mask
else:
current_mask = load_placeholder_image(self.placeholder_image_path)[1]
if auto:
try:
# Use the main auto mode processing function
result = await self.process_auto_mode(
images=current_images,
mask=current_mask,
messages=messages,
strategy=strategy,
auto_mode=auto_mode,
**kwargs
)
if result:
return result
else:
#self, images, masks, error_message, prompt=""
return self.create_error_response(
current_images,
current_mask,
"No results generated from auto mode processing.",
user_prompt
)
except Exception as e:
logger.error(f"Error in auto mode processing: {str(e)}")
return self.create_error_response(
current_images,
current_mask,
"No results generated from auto mode processing.",
user_prompt
)
else:
# Execute strategy-specific logic
if strategy_name == "normal":
return await self.execute_normal_strategy(
user_prompt, current_images, current_mask, messages, embellish_content, style_content, **kwargs)
elif strategy_name == "create":
return await self.execute_create_strategy(
user_prompt, current_mask, **kwargs)
elif strategy_name == "omost":
return await self.execute_omost_strategy(
user_prompt, current_images, current_mask, embellish_content, style_content, **kwargs)
elif strategy_name == "variations":
return await self.execute_variations_strategy(
user_prompt, current_images, **kwargs)
elif strategy_name == "edit":
return await self.execute_edit_strategy(
user_prompt, current_images, current_mask, **kwargs)
elif strategy_name == "gemini2_create":
return await self.execute_gemini2_create_strategy(
user_prompt, current_images, current_mask, **kwargs)
else:
raise ValueError(f"Unsupported strategy: {strategy_name}")
except Exception as e:
logger.error(f"Error in process_image: {str(e)}")
return self.create_error_response(
current_images,
current_mask,
"No results generated from auto mode processing.",
user_prompt
)
async def process_auto_mode(self, images, mask, messages, strategy, auto_mode=True, embellish_content="", style_content="", **kwargs):
"""
Main auto mode processing function that preserves batch handling.
"""
try:
# Determine batch size based on mode
batch_size = 4 if auto_mode else 1
# Process images into appropriate batches
image_batches, mask_batches = process_auto_mode_images(
images=images,
mask=mask,
batch_size=batch_size
)
all_results = []
user_prompt = kwargs.get('user_prompt', '')
batch_count = kwargs.get('batch_count', 1)
# Process each image/mask batch
for img_batch, mask_batch in zip(image_batches, mask_batches):
for i in range(img_batch.size(0)):
single_img = img_batch[i:i+1]
single_mask = mask_batch[i:i+1]
# Generate combo prompt once for this image
combo_prompt = await self.generate_combo_prompts(
images=single_img,
settings_dict=None
)
# Process batch_count iterations for this image
for iteration in range(batch_count):
batch_results = await self.process_auto_batch(
batch_images=single_img,
batch_mask=single_mask,
strategy=strategy,
prompt=combo_prompt,
messages=messages,
embellish_content=embellish_content,
style_content=style_content,
**{**kwargs,
'batch_count': 1, # Process single iteration here
'seed': kwargs.get('seed', 0) + iteration if kwargs.get('seed') is not None else None
}
)
if batch_results:
if isinstance(batch_results, list):
all_results.extend(batch_results)
else:
all_results.append(batch_results)
if not all_results:
return [{
"Question": user_prompt,
"Response": "No results generated",
"Negative": "",
"Tool_Output": None,
"Retrieved_Image": images,
"Mask": mask
}]
return all_results
except Exception as e:
logger.error(f"Error in process_auto_mode: {str(e)}")
return [{
"Question": kwargs.get('user_prompt', ''),
"Response": f"Error: {str(e)}",
"Negative": "",
"Tool_Output": None,
"Retrieved_Image": images,
"Mask": mask
}]
async def process_auto_batch(self, batch_images, batch_mask, strategy, prompt, messages,
embellish_content="", style_content="", **kwargs):
"""
Process single iteration of auto mode batch.
Batch count iterations are handled by process_auto_mode.
"""
try:
# Create clean kwargs without user_prompt
batch_kwargs = {
k: v for k, v in kwargs.items()
if k not in ['user_prompt']
}
# Execute strategy (should process just one iteration)
if strategy == "normal":
results = await self.execute_normal_strategy(
user_prompt=prompt,
current_images=batch_images,
current_mask=batch_mask,
messages=messages,
embellish_content=embellish_content,
style_content=style_content,
**batch_kwargs
)
elif strategy == "omost":
results = await self.execute_omost_strategy(
user_prompt=prompt,
current_images=batch_images,
current_mask=batch_mask,
embellish_content=embellish_content,
style_content=style_content,
**batch_kwargs
)
else:
raise ValueError(f"Unsupported strategy for auto mode: {strategy}")
return results
except Exception as e:
logger.error(f"Error processing auto batch: {str(e)}")
return None
async def execute_normal_strategy(self, user_prompt, current_images, current_mask, messages, embellish_content, style_content, **kwargs):
"""
Execute normal strategy with robust error handling and response validation.
"""
try:
results = []
batch_count = kwargs.get('batch_count', 1)
# Process and validate images
images_to_send = current_images if (current_images is not None and current_images.nelement() > 0) else None
# Process batch_count times
for i in range(batch_count):
try:
# Update seed for each iteration if using random seeding
current_seed = kwargs['seed'] + i if kwargs.get('random', False) and kwargs.get('seed') is not None else kwargs.get('seed')
# Make the API request
response = await send_request(
llm_provider=kwargs.get('llm_provider'),
base_ip=kwargs.get('base_ip'),
port=kwargs.get('port'),
images=images_to_send,
llm_model=kwargs.get('llm_model'),
system_message=kwargs.get('system_message'),
user_message=user_prompt,
messages=messages or [], # Ensure messages is never None
seed=current_seed,
temperature=kwargs.get('temperature', 0.7),
max_tokens=kwargs.get('max_tokens', 2048),
random=kwargs.get('random', False),
top_k=kwargs.get('top_k', 40),
top_p=kwargs.get('top_p', 0.9),
repeat_penalty=kwargs.get('repeat_penalty', 1.1),
stop=kwargs.get('stop'),
keep_alive=kwargs.get('keep_alive', False),
llm_api_key=kwargs.get('llm_api_key'),
precision=kwargs.get('precision', 'fp16'),
attention=kwargs.get('attention', 'sdpa'),
aspect_ratio=kwargs.get('aspect_ratio', '1:1'),
strategy="normal",
mask=current_mask
)
# Validate and extract response content
response_content = ""
if response is None:
logger.error("Received a None response from the LLM API.")
continue # Skip to the next iteration
elif isinstance(response, dict):
if "choices" in response and response["choices"]:
message = response["choices"][0].get("message", {})
response_content = message.get("content", "")
# Additional validation for empty content
if not response_content:
logger.warning("Empty response content in choices")
continue
elif "response" in response:
response_content = response["response"]
else:
logger.warning(f"Unexpected response format: {response}")
continue
elif isinstance(response, str):
response_content = response
if not response_content:
logger.warning("Empty response content received")
continue
# Proceed with cleaning and formatting the response
cleaned_response = clean_text(response_content)
final_prompt = "\n".join(filter(None, [
embellish_content.strip() if embellish_content else "",
cleaned_response.strip(),
style_content.strip() if style_content else ""
]))
# Generate negative prompt if needed
if kwargs.get('neg_prompt') == "AI_Fill":
neg_prompt = await self.generate_negative_prompt(
cleaned_response,
images=current_images,
**kwargs
)
else:
neg_prompt = kwargs.get('neg_content', '')
# Add result to results list
results.append({
"Question": user_prompt,
"Response": final_prompt,
"Negative": neg_prompt,
"Tool_Output": None,
"Retrieved_Image": current_images,
"Mask": current_mask
})
except Exception as batch_error:
logger.error(f"Error in batch {i}: {str(batch_error)}")
continue
# Keep message history if enabled
if kwargs.get('keep_alive') and results:
messages.extend([
{"role": "user", "content": user_prompt},
{"role": "assistant", "content": results[-1]["Response"]}
])
# Return results or error response
if not results:
return [self.create_error_response(
current_images,
current_mask,
"No valid results generated from normal strategy.",
user_prompt
)]
return results
except Exception as e:
logger.error(f"Error in normal strategy: {str(e)}")
return [self.create_error_response(
current_images,
current_mask,
f"Error in normal strategy: {str(e)}",
user_prompt
)]
async def execute_omost_strategy(
self, user_prompt, current_images, current_mask,
embellish_content="", style_content="", **kwargs
):
"""Execute OMOST strategy with batch processing and proper negative prompt generation"""
omni = kwargs.get("omni", None)
# Make sure user_prompt is a string, in case it's a list
if isinstance(user_prompt, list):
user_prompt = " ".join(user_prompt)
try:
batch_count = kwargs.get('batch_count', 1)
messages = []
system_prompt = self.profiles.get("IF_Omost")
results = []
logger.debug(f"Processing {batch_count} batches in OMOST strategy")
# Process batch_count times
for batch_idx in range(batch_count):
try:
# Get LLM response (dict or str).
llm_response = await send_request(
llm_provider=kwargs.get('llm_provider'),
base_ip=kwargs.get('base_ip'),
port=kwargs.get('port'),
images=current_images,
llm_model=kwargs.get('llm_model'),
system_message=system_prompt,
user_message=user_prompt,
messages=messages,
seed=kwargs.get('seed', 0) + batch_idx if kwargs.get('seed', 0) != 0 else kwargs.get('seed', 0),
temperature=kwargs.get('temperature', 0.7),
max_tokens=kwargs.get('max_tokens', 2048),
random=kwargs.get('random', False),
top_k=kwargs.get('top_k', 40),
top_p=kwargs.get('top_p', 0.9),
repeat_penalty=kwargs.get('repeat_penalty', 1.1),
stop=kwargs.get('stop', None),
keep_alive=kwargs.get('keep_alive', False),
llm_api_key=kwargs.get('llm_api_key'),
precision=kwargs.get('precision', 'fp16'),
attention=kwargs.get('attention', 'sdpa'),
aspect_ratio=kwargs.get('aspect_ratio', '1:1'),
strategy="omost",
mask=current_mask
)
if not llm_response:
logger.warning(f"No response from LLM in batch {batch_idx}")
continue
# If llm_response is dict, extract text from "choices"
# or fallback to stringifying.
if isinstance(llm_response, dict):
if "choices" in llm_response and llm_response["choices"]:
choice = llm_response["choices"][0]
if "message" in choice and "content" in choice["message"]:
llm_response = choice["message"]["content"]
else:
llm_response = json.dumps(llm_response)
elif "response" in llm_response:
llm_response = llm_response["response"]
else:
llm_response = json.dumps(llm_response)
elif not isinstance(llm_response, str):
llm_response = str(llm_response)
# IMPORTANT: Avoid calling clean_text() so Canvas code remains intact.
final_prompt = "\n".join(
filter(None,
[
embellish_content.strip(),
llm_response.strip(),
style_content.strip()
]
)
)
# Lazy load omost_function
omost_function = get_omost_function()
tool_result = await omost_function({
"name": "omost_tool",
"description": "Analyzes images composition and generates a Canvas representation.",
"system_prompt": system_prompt,
"input": user_prompt,
"llm_response": llm_response,
"function_call": None,
"omni_input": omni
})
# Handle negative prompt if requested
if kwargs.get('neg_prompt') == "AI_Fill":
neg_prompt = await self.generate_negative_prompt(
llm_response, # pass raw text if you want the LLM to see code
images=current_images,
**kwargs
)
else:
neg_prompt = kwargs.get('neg_content', '')
if isinstance(tool_result, dict):
if "error" in tool_result:
logger.warning(
f"OMOST tool warning in batch {batch_idx}: {tool_result['error']}"
)
continue
canvas_cond = tool_result.get("canvas_conditioning")
if canvas_cond is not None:
# Ensure canvas_conditioning is a flat list of dicts
if (
isinstance(canvas_cond, list)
and len(canvas_cond) == 1
and isinstance(canvas_cond[0], list)
):
# Flatten once
canvas_cond = canvas_cond[0]
tool_result["canvas_conditioning"] = canvas_cond
results.append({
"Question": user_prompt,
"Response": final_prompt,
"Negative": neg_prompt,
"Tool_Output": canvas_cond,
"Retrieved_Image": current_images,
"Mask": current_mask
})
except Exception as batch_error:
logger.error(f"Error in OMOST batch {batch_idx}: {str(batch_error)}")
continue
# Keep message history if enabled
if kwargs.get('keep_alive') and results:
messages.append({"role": "user", "content": user_prompt})
messages.append({"role": "assistant", "content": results[-1]["Response"]})
logger.debug(f"Generated {len(results)} results in OMOST strategy")
if not results:
return [self.create_error_response(
current_images,
current_mask,
"No valid results generated",
user_prompt
)]
return results
except Exception as e:
logger.error(f"Error in OMOST strategy: {str(e)}")
return [self.create_error_response(
current_images,
current_mask,
"No valid results generated",
user_prompt
)]
async def execute_create_strategy(self, user_prompt, current_mask, **kwargs):
try:
# Create strategy - no input images needed
messages = []
api_response = await send_request(
llm_provider=kwargs.get('llm_provider'),
base_ip=kwargs.get('base_ip'),
port=kwargs.get('port'),
images=None, # No input images needed for create
llm_model=kwargs.get('llm_model'),
system_message=kwargs.get('system_message'),
user_message=user_prompt,
messages=messages,
seed=kwargs.get('seed', 0),
temperature=kwargs.get('temperature'),
max_tokens=kwargs.get('max_tokens'),
random=kwargs.get('random'),
top_k=kwargs.get('top_k'),
top_p=kwargs.get('top_p'),
repeat_penalty=kwargs.get('repeat_penalty'),
stop=kwargs.get('stop'),
keep_alive=kwargs.get('keep_alive'),
llm_api_key=kwargs.get('llm_api_key'),
precision=kwargs.get('precision'),
attention=kwargs.get('attention'),
aspect_ratio=kwargs.get('aspect_ratio'),
strategy="create",
batch_count= 1,
mask=current_mask
)
# Extract base64 images from response
all_base64_images = []
if isinstance(api_response, dict) and "images" in api_response:
base64_images = api_response.get("images", [])
all_base64_images.extend(base64_images if isinstance(base64_images, list) else [base64_images])
# Process the images if we have any
if all_base64_images:
# Prepare data for processing
image_data = {
"data": [{"b64_json": img} for img in all_base64_images]
}
# Process images
images_tensor, mask_tensor = process_images_for_comfy(
image_data,
placeholder_image_path=self.placeholder_image_path,
response_key="data",
field_name="b64_json"
)
logger.debug(f"Retrieved_Image tensor shape: {images_tensor.shape}")
return {
"Question": user_prompt,
"Response": f"Create image{'s' if len(all_base64_images) > 1 else ''} successfully generated.",
"Negative": kwargs.get('neg_content', ''),
"Tool_Output": all_base64_images,
"Retrieved_Image": images_tensor,
"Mask": mask_tensor
}
else:
# No images were generated
image_tensor, mask_tensor = load_placeholder_image(self.placeholder_image_path)
return self.create_error_response(
image_tensor,
mask_tensor,
"No images were generated in create strategy",
user_prompt
)
except Exception as e:
logger.error(f"Error in create strategy: {str(e)}")
image_tensor, mask_tensor = load_placeholder_image(self.placeholder_image_path)
return self.create_error_response(
image_tensor,
mask_tensor,
f"Error in create strategy: {str(e)}",
user_prompt
)
async def execute_variations_strategy(self, user_prompt, images, **kwargs):
"""Core implementation of variations strategy"""
try:
batch_count = kwargs.get('batch_count', 1)
messages = []
api_responses = []
# Prepare input images
input_images = prepare_batch_images(images)
# Process each input image
for img in input_images:
try:
# Send request for variations
api_response = await send_request(
images=img,
user_message=user_prompt,
messages=messages,
strategy="variations",
batch_count=batch_count,
mask=None, # Variations don't use masks
**kwargs
)
if api_response:
api_responses.append(api_response)
except Exception as e:
logger.error(f"Error processing image variation: {str(e)}")
continue
# Extract and process base64 images from responses
all_base64_images = []
for response in api_responses:
if isinstance(response, dict) and "images" in response:
base64_images = response.get("images", [])
if isinstance(base64_images, list):
all_base64_images.extend(base64_images)
else:
all_base64_images.append(base64_images)
# Process the generated images
if all_base64_images:
# Prepare data for processing
image_data = {
"data": [{"b64_json": img} for img in all_base64_images]
}
# Convert to tensors
images_tensor, mask_tensor = process_images_for_comfy(
image_data,
placeholder_image_path=self.placeholder_image_path,
response_key="data",
field_name="b64_json"
)
logger.debug(f"Variations image tensor shape: {images_tensor.shape}")
return {
"Question": user_prompt,
"Response": f"Generated {len(all_base64_images)} variations successfully.",
"Negative": kwargs.get('neg_content', ''),
"Tool_Output": all_base64_images,
"Retrieved_Image": images_tensor,
"Mask": mask_tensor
}
else: