-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomfy_agent_node.py
More file actions
1673 lines (1450 loc) · 65.4 KB
/
comfy_agent_node.py
File metadata and controls
1673 lines (1450 loc) · 65.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Filename: comfy_agent_node.py
# Place this file in your ComfyUI/custom_nodes/ directory,
# or in a subdirectory like ComfyUI/custom_nodes/my_utility_nodes/
# If in a subdirectory, ensure you have an __init__.py file in that subdirectory
# that exports the NODE_CLASS_MAPPINGS and NODE_DISPLAY_NAME_MAPPINGS.
import io
import os
import sys
import shutil
import pathlib
import uuid
import threading
import time
import requests
import json
import server # ComfyUI's server instance
import nodes
import subprocess
import logging
import traceback
import base64
import datetime
import urllib.parse
from server import PromptServer
from folder_paths import (
base_path, models_dir, folder_names_and_paths,
get_filename_list, get_user_directory, get_input_directory, get_directory_by_type, recursive_search
)
from .utils import (
Paths, _log, _log_error, device_id, get_comfyui_version, headers_json, create_client, load_config, save_config, to_error_status,
is_enabled, config_str, allow_installing_models, allow_installing_nodes, allow_installing_packages, utf8str,
)
from .dtos import (
ComfyAgentConfig, Hello, RegisterComfyAgent, GetComfyAgentEvents, UpdateComfyAgent, UpdateComfyAgentStatus, UpdateWorkflowGeneration,
GpuInfo, ComfyAgentSettings,
)
from servicestack import UploadFile, WebServiceException, ResponseStatus, printdump
from PIL import Image
VERSION = 1
DEFAULT_AUTOSTART = True
DEFAULT_INSTALL_MODELS = True
DEFAULT_INSTALL_NODES = True
DEFAULT_INSTALL_PACKAGES = True
DEFAULT_ENDPOINT_URL = "https://ubixar.com"
DEFAULT_POLL_INTERVAL_SECONDS = 10
DEFAULT_REQUEST_TIMEOUT_SECONDS = 60
MIN_DOWNLOAD_BYTES=1024
# Stores the active configuration for the global poller
g_client = None
g_models = None
g_audio_model = None
g_needs_update = False
g_settings=ComfyAgentSettings(preserve_outputs=True)
g_logger_prefix = "[comfy-agent]"
g_node_dir = os.path.join(get_user_directory(), "comfy_agent")
g_running = False
g_categories = []
g_uploaded_prompts = []
g_language_models = None
# Install
g_statuses = []
g_installed_pip_packages = []
g_installed_custom_nodes = []
g_installed_models = []
g_downloading_model = None
g_downloading_model_args = None
MSG_RESTART_COMFY = "Restart ComfyUI for changes to take effect."
# --- End of Default Configuration ---
# Maintain a global dictionary of prompt_id mapping to client_id
g_pending_prompts = {}
# Store the original method
original_send_sync = PromptServer.send_sync
# Define your interceptor function
def intercepted_send_sync(self, event, data, sid=None):
# Your custom code to run before the event is sent
if event == "executed" or event == "execution_success" or event == "status" or event == "execution_error":
_log(f"{event}: " + json.dumps(data))
# Do something with the execution data
# else:
# _log(f"event={event}")
# Call the original method
result = original_send_sync(self, event, data, sid)
# Your custom code to run after the event is sent
if event == "execution_success":
_log("After execution_success event sent")
prompt_id = data['prompt_id']
if prompt_id in g_pending_prompts:
client_id = g_pending_prompts[prompt_id]
# call send_execution_success in a background thread
threading.Thread(target=send_execution_success, args=(prompt_id, client_id), daemon=True).start()
elif event == "execution_error":
prompt_id = data['prompt_id']
if prompt_id in g_pending_prompts:
client_id = g_pending_prompts[prompt_id]
_log("After execution_error event sent " + prompt_id)
_log(json.dumps(data))
exception_type = data['exception_type']
exception_message = data['exception_message']
traceback = data['traceback']
# call send_execution_error in a background thread
threading.Thread(target=send_execution_error,
args=(prompt_id, client_id, exception_type, exception_message, traceback), daemon=True).start()
return result
def remove_pending_prompt(prompt_id):
if prompt_id in g_pending_prompts:
del g_pending_prompts[prompt_id]
def send_execution_error(prompt_id, client_id, exception_type, exception_message, traceback):
_log(f"send_execution_error: prompt_id={prompt_id}, client_id={client_id}")
try:
# only join first 5 lines of traceback
stack_trace = "\n".join(traceback[:5])
# split '.' and take last part
message = f"{exception_type.split('.')[-1]}: {exception_message}"
request = UpdateWorkflowGeneration(device_id=device_id(), id=client_id, prompt_id=prompt_id,
queue_count=get_queue_count(),
error=ResponseStatus(error_code=exception_type, message=message, stack_trace=stack_trace))
g_client.post(request)
except WebServiceException as ex:
_log(f"Exception sending execution_error: {ex}")
printdump(ex.response_status)
except Exception as e:
_log(f"Error sending execution_error: {e}")
finally:
remove_pending_prompt(prompt_id)
image_extensions = ["png", "jpg", "jpeg", "webp", "gif", "bmp", "tiff"]
audio_extensions = ["mp3", "aac", "flac", "wav", "wma", "m4a", "ogg", "opus", "aiff"]
def send_execution_success(prompt_id, client_id):
_log(f"send_execution_success: prompt_id={prompt_id}, client_id={client_id}")
if prompt_id in g_uploaded_prompts:
_log(f"prompt_id={prompt_id} already sent, skipping.")
return
try:
# retry after 30 times with 100ms delay
for i in range(30):
result = PromptServer.instance.prompt_queue.get_history(prompt_id=prompt_id)
if prompt_id in result:
break
time.sleep(.1)
if prompt_id not in result:
_log(f"prompt_id={prompt_id} not found in history, skipping.")
return
# log number of iterations
_log(f"prompt_id={prompt_id} found in history ({i}):")
prompt_data = result[prompt_id]
outputs = prompt_data['outputs']
status = prompt_data['status']
_log(json.dumps(outputs))
_log(json.dumps(status))
# example image outputs:
# {"10": {"images": [{"filename": "ComfyUI_temp_pgpib_00001_.png", "subfolder": "", "type": "temp"}]}}
# example audio outputs:
# {"13":{"audio":[{"filename":"ComfyUI_00001_.flac","subfolder":"audio","type":"output"}]}}
#extract all image outputs
artifacts = []
for key, value in outputs.items():
if 'images' in value:
artifacts.extend(value['images'])
if 'audio' in value:
artifacts.extend(value['audio'])
# outputs = {"images": artifacts}
_log(json.dumps(artifacts, indent=2))
files = []
output_paths = []
for artifact in artifacts:
dir = get_directory_by_type(artifact['type'])
artifact_path = os.path.join(dir, artifact['subfolder'], artifact['filename'])
if not os.path.exists(artifact_path):
for i in range(30):
if os.path.exists(artifact_path):
break
time.sleep(.1)
if not os.path.exists(artifact_path):
_log(f"File not found: {artifact_path}")
continue
else:
_log(f"File found after {i * 1000} ms: {artifact_path}")
if artifact_path not in output_paths:
output_paths.append(artifact_path)
#lowercase extension
ext = artifact['filename'].split('.')[-1].lower()
if (ext in image_extensions):
with Image.open(artifact_path) as img:
artifact['width'] = img.width
artifact['height'] = img.height
# convert png to webp
if ext == "png":
quality = 90
buffer = io.BytesIO()
img.save(buffer, format='webp', quality=quality)
buffer.seek(0)
image_stream = buffer
artifact['filename'] = artifact['filename'].replace(".png", ".webp")
ext = "webp"
else:
image_stream=open(artifact_path, 'rb')
files.append(UploadFile(
field_name=f"output_{len(files)}",
file_name=artifact['filename'],
content_type=f"image/{ext}",
stream=image_stream
))
elif (ext in audio_extensions):
if ext != "m4a":
to_aac_path = artifact_path.replace(f".{ext}", ".m4a")
# check if ffmpeg exists
if not shutil.which("ffmpeg"):
raise FileNotFoundError("ffmpeg not found")
bitrate = "192k"
artifact['codec'] = "aac"
try:
command = [
"ffmpeg",
"-i", artifact_path,
"-c:a", artifact['codec'], # Specify AAC audio codec
"-b:a", bitrate, # Set audio bitrate
to_aac_path
]
subprocess.run(command, check=True, capture_output=True, text=True)
artifact['filename'] = os.path.basename(to_aac_path)
_log(f"Audio conversion successful: {os.path.basename(artifact_path)} -> {artifact['filename']}")
artifact_path = to_aac_path
if artifact_path not in output_paths:
output_paths.append(artifact_path)
ext = "m4a"
command = [
'ffprobe',
'-v', 'quiet', # Suppress verbose output
'-print_format', 'json', # Output in JSON format
'-show_format', # Show format information
#'-show_streams', # Show stream information
artifact_path
]
metadata_str = subprocess.check_output(command, text=True)
metadata = json.loads(metadata_str)
# _log("ffprobe metadata: ")
# print(json.dumps(metadata, indent=2))
if 'format' in metadata:
format = metadata['format']
if 'size' in format:
artifact['length'] = int(format['size'])
if 'duration' in format:
artifact['duration'] = float(format['duration'])
if 'bit_rate' in format:
artifact['bitrate'] = int(format['bit_rate'])
if 'nb_streams' in format:
artifact['streams'] = int(format['nb_streams'])
if 'nb_programs' in format:
artifact['programs'] = int(format['nb_programs'])
except subprocess.CalledProcessError as e:
_log(f"Error during conversion: {e}")
print(f"FFmpeg output: {e.stdout}")
print(f"FFmpeg error: {e.stderr}")
continue
except FileNotFoundError:
_log("Error: FFmpeg not found. Please ensure it's installed and in your PATH.")
continue
files.append(UploadFile(
field_name=f"output_{len(files)}",
file_name=artifact['filename'],
content_type="audio/mp4",
stream=open(artifact_path, 'rb')
))
else:
_log(f"Unsupported file type: {ext}")
request = UpdateWorkflowGeneration(device_id=device_id(), id=client_id, prompt_id=prompt_id,
queue_count=get_queue_count(),
outputs=json.dumps(outputs),
status=json.dumps(status))
g_client.post_files_with_request(request, files)
g_uploaded_prompts.append(prompt_id)
if not g_settings.preserve_outputs:
for path in output_paths:
try:
_log(f"Deleting output: {path}")
os.remove(path)
except Exception as e:
_log(f"Error deleting file: {e}")
except WebServiceException as ex:
_log(f"Exception sending execution_success: {ex}")
printdump(ex.response_status)
except Exception as e:
_log_error("Error sending execution_success: ", e)
stack_trace = traceback.format_exc()
logging.error(stack_trace)
exception_type = type(e).__name__ or "Exception"
send_execution_error(prompt_id, client_id, exception_type, str(e), stack_trace)
finally:
remove_pending_prompt(prompt_id)
def urljoin(*args):
trailing_slash = '/' if args[-1].endswith('/') else ''
return "/".join([str(x).strip("/") for x in args]) + trailing_slash
# copied from PromptServer
def node_info(node_class):
obj_class = nodes.NODE_CLASS_MAPPINGS[node_class]
info = {}
info['input'] = obj_class.INPUT_TYPES()
info['input_order'] = {key: list(value.keys()) for (key, value) in obj_class.INPUT_TYPES().items()}
info['output'] = obj_class.RETURN_TYPES
info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES)
info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
info['name'] = node_class
info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else ''
info['python_module'] = getattr(obj_class, "RELATIVE_PYTHON_MODULE", "nodes")
info['category'] = 'sd'
if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE is True:
info['output_node'] = True
else:
info['output_node'] = False
if hasattr(obj_class, 'CATEGORY'):
info['category'] = obj_class.CATEGORY
if hasattr(obj_class, 'OUTPUT_TOOLTIPS'):
info['output_tooltips'] = obj_class.OUTPUT_TOOLTIPS
if getattr(obj_class, "DEPRECATED", False):
info['deprecated'] = True
if getattr(obj_class, "EXPERIMENTAL", False):
info['experimental'] = True
if hasattr(obj_class, 'API_NODE'):
info['api_node'] = obj_class.API_NODE
return info
def get_object_info():
out = {}
keys = list(nodes.NODE_CLASS_MAPPINGS.keys())
for x in keys:
try:
out[x] = node_info(x)
except Exception:
logging.error(f"[ERROR] An error occurred while retrieving information for the '{x}' node.")
logging.error(traceback.format_exc())
return out
def get_object_info_json():
return json.dumps(get_object_info())
def get_object_info_json_from_url():
json = requests.get(f"{get_server_url()}/api/object_info").text
return json
def listen_to_messages_poll(sleep=3):
global g_client, g_running, g_needs_update
g_running = True
g_client = create_client()
retry_secs = 5
time.sleep(sleep)
try:
register_agent()
except Exception as ex:
_log_error("Error registering agent: ", ex)
logging.error(traceback.format_exc())
g_running = False
return
while is_enabled():
try:
g_running = True
send_update()
if g_needs_update:
g_needs_update = False
g_client = create_client()
register_agent()
_log("Polling for agent events")
request = GetComfyAgentEvents(device_id=device_id())
response = g_client.get(request)
retry_secs = 5
if response.results is not None:
event_names = [event.name for event in response.results]
_log(f"Processing {len(response.results)} agent events: {','.join(event_names)}")
for event in response.results:
if event.name == "Register":
register_agent()
elif event.name == "ExecWorkflow":
inputs = 'inputs' in event.args and event.args['inputs'].split(',') or None
exec_prompt(event.args['url'], inputs)
elif event.name == "ExecOllama":
exec_ollama(event.args['model'], event.args['endpoint'], event.args['request'], event.args['replyTo'])
elif event.name == "CaptionImage":
caption_image(event.args['url'], event.args['model'])
elif event.name == "InstallPipPackage":
install_pip_package(event.args['package'])
elif event.name == "UninstallPipPackage":
uninstall_pip_package(event.args['package'])
elif event.name == "InstallCustomNode":
install_custom_node(event.args['url'])
elif event.name == "UninstallCustomNode":
uninstall_custom_node(event.args['url'])
elif event.name == "DownloadModel":
install_model(event.args['model'])
elif event.name == "DeleteModel":
delete_model(event.args['path'])
elif event.name == "Refresh":
time_str=datetime.datetime.now().strftime("%H:%M:%S")
send_update(status=f"Updated at {time_str}")
elif event.name == "Reboot":
reboot()
except Exception as ex:
_log(f"Error connecting to {config_str('url')}: {ex}, retrying in {retry_secs}s")
time.sleep(retry_secs) # Wait before retrying
retry_secs += 5 # Exponential backoff
g_client = create_client() # Create new client to force reconnect
_log(f"Disconnected from {config_str('url')}")
g_running = False
def get_queue_count():
return PromptServer.instance.get_queue_info()['exec_info']['queue_remaining']
def resolve_url(url):
#if relative path, combine with BASE_URL
if not url.startswith("http"):
url = urljoin(config_str('url'), url)
return url
def get_server_url():
return f"http://{PromptServer.instance.address}:{PromptServer.instance.port}"
def exec_prompt(url, inputs=None):
if url is None:
_log("exec_prompt: url is None")
return
# Get the server address - typically localhost when running within ComfyUI
# server_address = PromptServer.instance.server_address
# host, port = server_address if server_address else ("127.0.0.1", 7860)
url = resolve_url(url)
_log(f"exec_prompt GET: {url}")
api_response = requests.get(url, headers=headers_json(), timeout=30)
if api_response.status_code != 200:
_log(f"Error: {api_response.status_code} - {api_response.text}")
return
input_dir = get_input_directory()
if inputs is not None:
for input in inputs:
input_url = resolve_url(input)
filename = os.path.basename(input_url)
input_file = os.path.join(input_dir, filename)
if os.path.exists(input_file):
_log(f"exec_prompt: input file already exists: {filename}")
continue
_log(f"exec_prompt GET: {input_url}")
input_response = requests.get(input_url, timeout=30)
if input_response.status_code != 200:
_log(f"Error: {input_response.status_code} - {input_response.text}")
return
# save file to input folder
with open(input_file, 'wb') as f:
f.write(input_response.content)
_log(f"exec_prompt saved input file: {filename}")
prompt_data = api_response.json()
if 'client_id' not in prompt_data:
_log("Error: No client_id in prompt data")
return
client_id = prompt_data['client_id']
# check if client_id is a value in g_pending_prompts
for key, value in g_pending_prompts.items():
if value == client_id:
prompt_id = key
_log(f"exec_prompt: client_id={client_id} already in progress prompt_id={prompt_id}")
g_client.post(UpdateWorkflowGeneration(device_id=device_id(), id=client_id, prompt_id=prompt_id,
queue_count=get_queue_count()))
return
_log(f"exec_prompt: /prompt client_id={client_id}")
# Call the /prompt endpoint
response = requests.post(
f"{get_server_url()}/prompt",
json=prompt_data,
headers=headers_json())
if response.status_code == 200:
result = response.json()
prompt_id = result['prompt_id']
_log(f"exec_prompt: /prompt OK prompt_id={prompt_id}, client_id={client_id}")
_log(json.dumps(result))
g_pending_prompts[prompt_id] = client_id
g_client.post(UpdateWorkflowGeneration(device_id=device_id(), id=client_id, prompt_id=prompt_id,
queue_count=get_queue_count()))
else:
error_message = f"Error: {response.status_code} - {response.text}"
_log(error_message)
_log(json.dumps(prompt_data))
g_client.post(UpdateWorkflowGeneration(device_id=device_id(), id=client_id, queue_count=get_queue_count(),
error={"error_code": response.status_code, "message": response.text}))
def url_to_image(url):
"""Download an image from URL and return as PIL Image object"""
try:
response = requests.get(url) # Send GET request to download the image
response.raise_for_status() # Raises an HTTPError for bad responses
image = Image.open(io.BytesIO(response.content)) # Create PIL Image from the downloaded bytes
return image
except requests.exceptions.RequestException as e:
_log(f"Error downloading image: {e}")
return None
except Exception as e:
_log_error("Error opening image: ", e)
return None
def url_to_bytes(url):
"""Download an image from URL and return as PIL Image object"""
try:
response = requests.get(url)
response.raise_for_status()
return response.content
except requests.exceptions.RequestException as e:
_log(f"Error downloading image: {e}")
return None
except Exception as e:
_log_error("Error opening image: ", e)
return None
def encode_image_to_base64(image_path):
"""
Encode an image file to base64 string.
"""
try:
with open(image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
return encoded_string
except FileNotFoundError:
_log(f"Error: Image file '{image_path}' not found.")
return None
except Exception as e:
_log_error("Error encoding image: ", e)
return None
def exec_ollama(model:str, endpoint:str, request:str, reply_to):
error = None
try:
if g_language_models is None:
error = ResponseStatus(error_code='Validation', message="Ollama is not available")
elif model is None:
error = ResponseStatus(error_code='Validation', message="model is None")
elif endpoint is None:
error = ResponseStatus(error_code='Validation', message="endpoint is None")
elif request is None:
error = ResponseStatus(error_code='Validation', message="request is None")
elif reply_to is None:
error = ResponseStatus(error_code='Validation', message="replyTo is None")
elif model not in g_language_models:
error = ResponseStatus(error_code='Validation', message=f"model {model} is not available")
reply_url = resolve_url(reply_to)
if error is not None:
if reply_to is None:
_log(f"exec_ollama: {error.error_code} {error.message}")
else:
body = {
'response_status': error
}
g_client.post_url(reply_url, body)
return
try:
ollama_request = request
if ollama_request.startswith('/') or ollama_request.startswith('http'):
url = resolve_url(request)
json = g_client.get_url(url, response_as=str)
ollama_request = json
# Send POST request to Ollama API
ollama_url = urllib.parse.urljoin(config_str('ollama_url'), endpoint)
_log(f"exec_ollama: POST {ollama_url}:")
_log(f"{ollama_request[:100]}... ({len(ollama_request)})")
response = requests.post(ollama_url, data=ollama_request, headers=headers_json(), timeout=120)
response.raise_for_status()
# Parse response
body = response.json()
_log(f"exec_ollama response: {body}")
# Send response to replyTo URL
g_client.post_url(reply_url, body)
return
except requests.exceptions.ConnectionError as e:
_log("Error: Could not connect to Ollama API. Make sure Ollama is running on localhost:11434")
error = ResponseStatus(error_code='ConnectionError', message=f"{e or 'Could not connect to Ollama API'}")
except requests.exceptions.Timeout as e:
_log("Error: Request timed out. The model might be taking too long to respond.")
error = ResponseStatus(error_code='Timeout', message=f"{e or 'Request timed out'}")
except requests.exceptions.RequestException as e:
error = ResponseStatus(error_code='RequestException', message=f"{e or 'Error making request to Ollama API'}")
except WebServiceException as e:
error = e.response_status
except Exception as e:
error = ResponseStatus(error_code='Exception', message=f"{e}")
body = {
'responseStatus': {
'errorCode': error.error_code,
'message': error.message
}
}
_log(f"exec_ollama error: {reply_url} {error.error_code} {error.message}")
g_client.post_url(reply_url, body)
except Exception as e:
_log(f"Error executing Ollama: {e}")
traceback.print_exc()
def ollama_generate(image_bytes, model, prompt):
"""
Send an image to Ollama /api/generate API
"""
# Ollama API endpoint
url = urllib.parse.urljoin(config_str('ollama_url'), '/api/generate')
# Encode image to base64
base64_image = base64.b64encode(image_bytes).decode('utf-8')
if not base64_image:
return None
# Prepare the request payload
payload = {
"model": model,
"prompt": prompt,
"images": [base64_image],
"stream": False
}
try:
# Send POST request to Ollama API
response = requests.post(url, json=payload, timeout=120)
response.raise_for_status()
# Parse response
result = response.json()
if 'response' in result:
return result['response']
else:
_log("Error: No 'response' field in API response")
_log(f"Full response: {result}")
return None
except requests.exceptions.ConnectionError:
_log("Error: Could not connect to Ollama API. Make sure Ollama is running on localhost:11434")
return None
except requests.exceptions.Timeout:
_log("Error: Request timed out. The model might be taking too long to respond.")
return None
except requests.exceptions.RequestException as e:
_log(f"Error making request: {e}")
return None
except json.JSONDecodeError as e:
_log(f"Error parsing JSON response: {e}")
return None
def caption_image(artifact_url, model):
try:
if g_language_models is None:
_log(f"caption_image: g_language_models is None {config_str('ollama_url')}")
return
if artifact_url is None:
_log("caption_image: url is None")
return
if model is None:
_log("caption_image: model is None")
return
if model not in g_language_models:
_log(f"caption_image: model {model} is not available")
return
url = resolve_url(artifact_url)
_log(f"caption_image ({model}) GET: {url}")
image_bytes = url_to_bytes(url)
if image_bytes is None:
return
request = CaptionArtifact(device_id=device_id(), artifact_url=artifact_url)
request.caption = ollama_generate(image_bytes, model, "A caption of this image: ")
request.description = ollama_generate(image_bytes, model, "A detailed description of this image: ")
_log(f"caption_image caption: {request.caption}\n{request.description}")
g_client.post(request)
except Exception as e:
_log_error("Error captioning image: ", e)
traceback.print_exc()
def on_prompt_handler(json_data):
if is_enabled():
# run send_update once in background thread
threading.Thread(target=send_update, daemon=True).start()
return json_data
def try_gpu_infos():
"""
get info of gpus from $nvidia-smi --query-gpu=index,memory.total,memory.free,memory.used --format=csv,noheader,nounits
example output: 0, 16303, 13991, 1858
"""
gpus = []
output = subprocess.check_output(['nvidia-smi', '--query-gpu=index,name,memory.total,memory.free,memory.used', '--format=csv,noheader,nounits'], text=True)
lines = output.strip().split('\n')
for line in lines:
index, name, total, free, used = line.split(',')
gpu = GpuInfo(index=int(index),name=name.strip(),total=int(total),free=int(free),used=int(used))
gpus.append(gpu)
return gpus
def gpu_infos():
try:
return try_gpu_infos()
except Exception as e:
_log_error("Error getting GPU info: ", e)
return []
def gpus_as_jsv():
gpus = gpu_infos()
# complex types on the query string need to be sent with JSV format
ret = ','.join(['{' + f"index:{gpu.index},name:\"{gpu.name}\",total:{gpu.total},free:{gpu.free},used:{gpu.used}" + '}' for gpu in gpus])
return ret
def register_agent():
# get workflows from user/default/workflows
user_dir = get_user_directory()
workflows_dir = os.path.join(user_dir, "default", "workflows")
workflows = []
# exclude .json starting with '.'
if os.path.exists(workflows_dir):
workflows = [f for f in os.listdir(workflows_dir) if f.endswith(".json") and not f.startswith(".")]
object_info_json = get_object_info_json()
object_info_file = UploadFile(
field_name="object_info",
file_name="object_info.json",
content_type="application/json",
stream=io.BytesIO(object_info_json.encode('utf-8')))
global g_language_models
g_language_models = None
ollama_base_url = config_str('ollama_url')
if ollama_base_url:
try:
g_language_models = []
# Check if Ollama is running by hitting the base endpoint with a reasonable timeout
response = requests.get(f"{ollama_base_url}/api/tags", timeout=10)
response.raise_for_status()
# Parse the response
data = response.json()
# Extract models from the response
models = data.get('models', [])
_log(f"✅ Ollama is running with {len(models)} installed models")
for i, model in enumerate(models, 1):
name = model.get('name')
if name is not None:
g_language_models.append(name)
except requests.exceptions.ConnectionError:
_log(f"❌ Cannot connect to Ollama at {ollama_base_url}")
_log("Make sure Ollama is running and accessible")
except requests.exceptions.Timeout:
_log(f"❌ Request to {ollama_base_url} timed out")
except requests.exceptions.RequestException as e:
_log(f"❌ Error connecting to Ollama: {e}")
except Exception as e:
_log(f"❌ Unexpected error: {e}")
error = None
try:
gpus = try_gpu_infos()
except Exception as e:
error = e
gpus = []
_log("Hello agent")
hello_response = g_client.get(Hello(name=device_id()))
_log(f"Hello response: {hello_response.result}")
_log(f"Registering agent with {g_client.base_url}...")
response = g_client.post_file_with_request(
request=RegisterComfyAgent(
device_id=device_id(),
version=VERSION,
comfy_version=get_comfyui_version(),
workflows=workflows,
gpus=gpus,
queue_count=get_queue_count(),
models=get_model_files(),
language_models=g_language_models,
installed_pip=g_installed_pip_packages,
installed_nodes=g_installed_custom_nodes,
installed_models=g_installed_models,
config=ComfyAgentConfig(
install_models=allow_installing_models(),
install_nodes=allow_installing_nodes(),
install_packages=allow_installing_packages(),
)
),
file=object_info_file)
if error is not None:
update_status_error(error, "Failed to get GPU info:")
_log(f"Registered device with {config_str('url')}")
printdump(response)
# check if response.categories is an array with items
if isinstance(response.categories, list):
global g_categories
g_categories = response.categories
if isinstance(response.require_pip, list):
if len(g_installed_pip_packages) == 0:
_log(f"Installing required pip packages: {len(response.require_pip)}")
for package in response.require_pip:
if package not in g_installed_pip_packages:
install_pip_package(package)
if isinstance(response.require_nodes, list):
if len(g_installed_custom_nodes) == 0:
_log(f"Installing required custom nodes: {len(response.require_nodes)}")
for node in response.require_nodes:
if node not in g_installed_custom_nodes:
install_custom_node(node)
if isinstance(response.require_models, list):
if len(g_installed_models) == 0:
_log(f"Downloading required models: {len(response.require_models)}")
for saveto_and_model in response.require_models:
if saveto_and_model not in g_installed_models:
install_model(saveto_and_model)
if isinstance(response.settings, ComfyAgentSettings):
global g_settings
g_settings = response.settings
def update_status_error(e: Exception, msg: str = None):
error = to_error_status(e, message=msg)
# if is subprocess.CalledProcessError
if isinstance(e, subprocess.CalledProcessError):
_log(msg)
stdout = utf8str(e.stdout) if e.stdout is not None else ""
update_status_async(status=msg, logs=f"{stdout}", error=error, wait=0)
return
if msg is not None:
_log(f"{msg}: {e}")
send_update(status="Error", error=error)
def update_status_async(status: str, logs: str = None, error: ResponseStatus = None, wait=1):
"""
Update the status, logs or error of the agent asynchronously (without the full update context in send_update).
"""
_log(f"status: {status}")
if not is_enabled():
return
g_statuses.append(UpdateComfyAgentStatus(
device_id=device_id(),
status=status,
logs=logs,
error=error))
if wait == 0:
update_status(wait)
else:
threading.Thread(target=update_status, args=(wait,), daemon=True).start()
def update_status(wait=1):
if not is_enabled():
return
time.sleep(wait)
if len(g_statuses) > 0:
last_status = g_statuses.pop()
g_statuses.clear()
try:
g_client.post(last_status)
except Exception as e:
_log(f"Error sending update status: {e}")
def send_update_async(status=None, error=None):
threading.Thread(target=send_update, args=(status, error), daemon=True).start()
def send_update(status=None, error=None):
if not is_enabled():
_log(status)
return
try:
current_queue = PromptServer.instance.prompt_queue.get_current_queue()
queue_running = current_queue[0]
queue_pending = current_queue[1]
request = UpdateComfyAgent(device_id=device_id(),
gpus=gpu_infos(),
models=get_model_files(),
status=status,
error=error,
language_models=g_language_models,
installed_pip=g_installed_pip_packages,
installed_nodes=g_installed_custom_nodes,
installed_models=g_installed_models
)
request.queue_count = len(queue_running) + len(queue_pending)
# get running generation ids (client_id) (max 20)
request.running_generation_ids = [entry[3]['client_id'] for entry in queue_running
if len(entry[3]['client_id']) == 32][:20]
# get queued generation ids (client_id) (max 20)
request.queued_generation_ids = [entry[3]['client_id'] for entry in queue_pending
if len(entry[3]['client_id']) == 32][:20]
_log(f"status {status or 'update'}: queue_count={request.queue_count}, running={request.running_generation_ids}, queued={request.queued_generation_ids}")
# print(request.installed_nodes)
g_statuses.clear()
g_client.post(request)
except WebServiceException as ex:
status = ex.response_status
if status.error_code == "NotFound":
_log("Device not found, reregistering")
register_agent()
return
else:
_log(f"Error sending update: {ex.message}\n{printdump(status)}")
except Exception as e:
_log_error("Error sending update: ", e)
def save_installed_items(file:str, items:list):
_log(f"Saving {file}")
items.sort()
with open(os.path.join(g_node_dir, file), "w") as f:
f.write("\n".join(items))
def load_installed_items(file:str):
install_path = os.path.join(g_node_dir, file)
if not os.path.exists(install_path):
return []
try:
with open(install_path, "r") as f:
lines = f.read().splitlines()
_log(f"Loaded {len(lines)} installed items from {file}")
printdump(lines)
return lines
except Exception as e:
_log(f"Error loading installed items from {file}: {e}")