-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodes_api.py
More file actions
1067 lines (941 loc) · 33 KB
/
Copy pathnodes_api.py
File metadata and controls
1067 lines (941 loc) · 33 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
"""
OpenRouter API nodes for ComfyUI-Wudd.
The nodes intentionally use the classic ComfyUI custom node API used by the
rest of this repository. HTTP work is pushed through asyncio.to_thread so
multiple API nodes can run concurrently when ComfyUI schedules them together.
"""
import asyncio
import base64
import hashlib
import http.client
import json
import os
import ssl
from io import BytesIO
from urllib.parse import urljoin, urlparse
import numpy as np
from PIL import Image
from .nodes_common import WUDD_CATEGORY, tensor_to_base64_png
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
OPENROUTER_CHAT_PATH = "chat/completions"
TEXT_CATEGORY = f"{WUDD_CATEGORY}/OpenRouter/Text"
IMAGE_CATEGORY = f"{WUDD_CATEGORY}/OpenRouter/Image"
MAX_TEXT_IMAGE_INPUTS = 16
MAX_IMAGE_NODE_INPUTS = 16
REASONING_EFFORTS = ["none", "minimal", "low", "medium", "high"]
TEXT_RESPONSE_FORMATS = ["text", "json_object"]
IMAGE_RESPONSE_MODALITIES = ["IMAGE+TEXT", "IMAGE"]
STANDARD_ASPECT_RATIOS = [
"auto",
"1:1",
"2:3",
"3:2",
"3:4",
"4:3",
"4:5",
"5:4",
"9:16",
"16:9",
"21:9",
]
EXTENDED_ASPECT_RATIOS = [
*STANDARD_ASPECT_RATIOS,
"1:4",
"4:1",
"1:8",
"8:1",
]
GPT_IMAGE_SIZES = ["auto", "1K", "2K", "4K"]
GEMINI_IMAGE_SIZES = ["auto", "0.5K", "1K", "2K", "4K"]
OPENAI_GPT_TEXT_MODELS = ["openai/gpt-5.5", "openai/gpt-5.5-pro"]
OPENAI_GPT_IMAGE_MODELS = ["openai/gpt-5.4-image-2"]
CLAUDE_TEXT_MODELS = ["anthropic/claude-opus-4.7", "anthropic/claude-sonnet-4.6"]
GEMINI_TEXT_MODELS = ["google/gemini-3.1-pro-preview", "google/gemini-3-flash-preview"]
GEMINI_IMAGE_MODELS = ["google/gemini-3-pro-image-preview", "google/gemini-3.1-flash-image-preview"]
def _image_port_inputs(max_images):
return {f"image_{i}": ("IMAGE",) for i in range(1, max_images + 1)}
def _api_runtime_inputs():
return {
"base_url": (
"STRING",
{
"default": OPENROUTER_BASE_URL,
"advanced": True,
},
),
"timeout_seconds": (
"INT",
{
"default": 300,
"min": 5,
"max": 3600,
"step": 1,
"advanced": True,
},
),
"verify_ssl": (
"BOOLEAN",
{
"default": True,
"advanced": True,
},
),
}
def _system_and_extra_inputs():
return {
"system_prompt": (
"STRING",
{
"default": "",
"multiline": True,
},
),
"extra_body_json": (
"STRING",
{
"default": "",
"multiline": True,
"advanced": True,
},
),
}
def _normalize_base_url(base_url):
base_url = (base_url or "").strip() or OPENROUTER_BASE_URL
if not base_url.startswith(("http://", "https://")):
base_url = "https://" + base_url
return base_url.rstrip("/")
def _build_chat_url(base_url):
base_url = _normalize_base_url(base_url)
if base_url.endswith("/chat/completions"):
return base_url
return urljoin(base_url + "/", OPENROUTER_CHAT_PATH)
def _resolve_api_key(api_key):
api_key = (api_key or "").strip() or os.environ.get("OPENROUTER_API_KEY", "").strip()
if not api_key:
raise ValueError("OpenRouter API key is required. Set api_key or OPENROUTER_API_KEY.")
return api_key
def _validate_model(model):
model = (model or "").strip()
if not model:
raise ValueError("OpenRouter model id cannot be empty.")
return model
def _validate_prompt(prompt):
prompt = str(prompt or "")
if not prompt.strip():
raise ValueError("Prompt cannot be empty.")
return prompt
def _parse_json_object(text, field_name):
text = (text or "").strip()
if not text:
return {}
try:
value = json.loads(text)
except json.JSONDecodeError as exc:
raise ValueError(f"{field_name} must be a valid JSON object: {exc}") from exc
if not isinstance(value, dict):
raise ValueError(f"{field_name} must be a JSON object.")
return value
def _split_stop_sequences(stop_sequences):
values = []
for line in str(stop_sequences or "").splitlines():
line = line.strip()
if line:
values.append(line)
return values
def _add_reasoning(payload, reasoning_effort):
if reasoning_effort and reasoning_effort != "none":
payload["reasoning"] = {"effort": reasoning_effort}
def _add_response_format(payload, response_format):
if response_format == "json_object":
payload["response_format"] = {"type": "json_object"}
def _add_stop_sequences(payload, stop_sequences):
stop = _split_stop_sequences(stop_sequences)
if stop:
payload["stop"] = stop
def _add_image_config(payload, model, aspect_ratio, image_size):
if image_size == "0.5K" and model != "google/gemini-3.1-flash-image-preview":
raise ValueError("0.5K image_size is only supported by google/gemini-3.1-flash-image-preview.")
image_config = {}
if aspect_ratio and aspect_ratio != "auto":
image_config["aspect_ratio"] = aspect_ratio
if image_size and image_size != "auto":
image_config["image_size"] = image_size
if image_config:
payload["image_config"] = image_config
def _hash_value(hasher, value):
if hasattr(value, "detach") and hasattr(value, "cpu"):
arr = value.detach().cpu().numpy()
hasher.update(str(arr.shape).encode("utf-8"))
hasher.update(arr.tobytes())
return
if isinstance(value, np.ndarray):
hasher.update(str(value.shape).encode("utf-8"))
hasher.update(value.tobytes())
return
if isinstance(value, dict):
for key in sorted(value):
_hash_value(hasher, key)
_hash_value(hasher, value[key])
return
if isinstance(value, (list, tuple)):
for item in value:
_hash_value(hasher, item)
return
hasher.update(str(value).encode("utf-8"))
hasher.update(b"\x00")
def _stable_hash(*args, **kwargs):
hasher = hashlib.sha256()
_hash_value(hasher, args)
_hash_value(hasher, kwargs)
return hasher.hexdigest()
def _flatten_image_inputs(values, max_images):
frames = []
for image in values:
if image is None:
continue
shape = getattr(image, "shape", None)
if shape is None:
raise ValueError("Image input is not a tensor-like object.")
if len(shape) == 4:
for index in range(shape[0]):
frames.append(image[index])
if len(frames) >= max_images:
return frames
elif len(shape) == 3:
frames.append(image)
if len(frames) >= max_images:
return frames
else:
raise ValueError(f"Unsupported IMAGE tensor shape: {tuple(shape)}")
return frames
def _collect_numbered_images(kwargs, max_images):
values = [kwargs.get(f"image_{i}") for i in range(1, max_images + 1)]
return _flatten_image_inputs(values, max_images)
def _image_frame_to_data_url(image):
return f"data:image/png;base64,{tensor_to_base64_png(image)}"
def _build_user_content(prompt, images):
content = [{"type": "text", "text": prompt}]
for image in images:
content.append(
{
"type": "image_url",
"image_url": {
"url": _image_frame_to_data_url(image),
},
}
)
return content
def _build_messages(prompt, system_prompt="", images=None):
messages = []
system_prompt = str(system_prompt or "").strip()
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
if images:
messages.append({"role": "user", "content": _build_user_content(prompt, images)})
else:
messages.append({"role": "user", "content": prompt})
return messages
def _json_dumps(value):
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
def _http_json(url, api_key, payload, timeout_seconds=300, verify_ssl=True):
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"X-Title": "ComfyUI-Wudd",
}
body = _json_dumps(payload).encode("utf-8")
status, raw_body = _http_request(
url,
method="POST",
headers=headers,
body=body,
timeout_seconds=timeout_seconds,
verify_ssl=verify_ssl,
)
if status >= 400:
raise ValueError(f"OpenRouter API error {status}: {raw_body}")
try:
return json.loads(raw_body)
except json.JSONDecodeError as exc:
raise ValueError(f"OpenRouter returned invalid JSON: {raw_body}") from exc
def _http_bytes(url, timeout_seconds=300, verify_ssl=True):
status, raw_body = _http_request(
url,
method="GET",
headers={},
body=None,
timeout_seconds=timeout_seconds,
verify_ssl=verify_ssl,
decode_body=False,
)
if status >= 400:
raise ValueError(f"Image download failed with HTTP {status}.")
return raw_body
def _http_request(url, method, headers, body, timeout_seconds, verify_ssl, decode_body=True):
parsed = urlparse(url)
if parsed.scheme not in ("http", "https"):
raise ValueError(f"Unsupported URL scheme: {url}")
ssl_context = None
if parsed.scheme == "https" and not verify_ssl:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
connection_cls = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
port = parsed.port or (443 if parsed.scheme == "https" else 80)
path = parsed.path or "/"
if parsed.query:
path = f"{path}?{parsed.query}"
conn = None
try:
if parsed.scheme == "https":
conn = connection_cls(parsed.hostname, port, timeout=timeout_seconds, context=ssl_context)
else:
conn = connection_cls(parsed.hostname, port, timeout=timeout_seconds)
conn.request(method, path, body=body, headers=headers)
resp = conn.getresponse()
raw = resp.read()
if decode_body:
raw = raw.decode("utf-8", errors="replace")
return resp.status, raw
except ssl.SSLError as exc:
raise ValueError(f"SSL error while reaching OpenRouter: {exc}") from exc
except OSError as exc:
raise ValueError(f"Failed to reach OpenRouter: {exc}") from exc
finally:
if conn is not None:
try:
conn.close()
except OSError:
pass
def _first_message(response_json):
choices = response_json.get("choices") or []
if not choices:
return {}
return choices[0].get("message") or {}
def _extract_text_from_content(content):
if isinstance(content, str):
return content
if not isinstance(content, list):
return ""
parts = []
for item in content:
if isinstance(item, str):
parts.append(item)
continue
if not isinstance(item, dict):
continue
item_type = item.get("type")
if item_type in ("text", "output_text") and isinstance(item.get("text"), str):
parts.append(item["text"])
elif isinstance(item.get("text"), str):
parts.append(item["text"])
return "".join(parts)
def _extract_text(response_json):
texts = []
for choice in response_json.get("choices") or []:
message = choice.get("message") or {}
text = _extract_text_from_content(message.get("content"))
if text:
texts.append(text)
return "\n\n".join(texts)
def _extract_reasoning(response_json):
message = _first_message(response_json)
reasoning = message.get("reasoning") or response_json.get("reasoning")
if isinstance(reasoning, str):
return reasoning
if reasoning:
return _json_dumps(reasoning)
details = message.get("reasoning_details") or response_json.get("reasoning_details")
if not details:
return ""
if isinstance(details, str):
return details
if isinstance(details, list):
parts = []
for item in details:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
text = item.get("text") or item.get("summary")
parts.append(text if isinstance(text, str) else _json_dumps(item))
return "\n".join(part for part in parts if part)
return _json_dumps(details)
def _extract_image_url_from_value(value):
if isinstance(value, str):
return value
if not isinstance(value, dict):
return None
if isinstance(value.get("url"), str):
return value["url"]
if isinstance(value.get("b64_json"), str):
return f"data:image/png;base64,{value['b64_json']}"
return None
def _extract_generated_image_urls(response_json):
urls = []
for choice in response_json.get("choices") or []:
message = choice.get("message") or {}
for image in message.get("images") or []:
if not isinstance(image, dict):
continue
url = _extract_image_url_from_value(image.get("image_url")) or _extract_image_url_from_value(image)
if url:
urls.append(url)
content = message.get("content")
if isinstance(content, list):
for item in content:
if not isinstance(item, dict):
continue
if item.get("type") in ("image_url", "output_image", "image"):
url = (
_extract_image_url_from_value(item.get("image_url"))
or _extract_image_url_from_value(item.get("image"))
or _extract_image_url_from_value(item)
)
if url:
urls.append(url)
return urls
def _decode_data_url(data_url):
try:
header, data = data_url.split(",", 1)
except ValueError as exc:
raise ValueError("Invalid data URL returned by OpenRouter.") from exc
if ";base64" not in header:
raise ValueError("Only base64 data URLs are supported for returned images.")
return base64.b64decode(data)
def _load_pil_from_url(image_url, timeout_seconds=300, verify_ssl=True):
if image_url.startswith("data:"):
raw = _decode_data_url(image_url)
else:
raw = _http_bytes(image_url, timeout_seconds=timeout_seconds, verify_ssl=verify_ssl)
try:
image = Image.open(BytesIO(raw))
image.load()
return image.convert("RGB")
except Exception as exc:
raise ValueError("OpenRouter returned an image that Pillow could not decode.") from exc
def _pil_images_to_tensor_batch(images):
import torch
if not images:
raise ValueError("No images to convert.")
max_width = max(image.width for image in images)
max_height = max(image.height for image in images)
tensors = []
for image in images:
canvas = Image.new("RGB", (max_width, max_height), (0, 0, 0))
canvas.paste(image.convert("RGB"), (0, 0))
arr = np.asarray(canvas).astype(np.float32) / 255.0
tensors.append(torch.from_numpy(arr).unsqueeze(0))
return torch.cat(tensors, dim=0)
class _OpenRouterBase:
FUNCTION = "generate"
@classmethod
def IS_CHANGED(cls, *args, **kwargs):
return _stable_hash(cls.__name__, args, kwargs)
async def _send_chat(self, api_key, base_url, payload, timeout_seconds, verify_ssl):
api_key = _resolve_api_key(api_key)
url = _build_chat_url(base_url)
return await asyncio.to_thread(
_http_json,
url,
api_key,
payload,
int(timeout_seconds),
bool(verify_ssl),
)
async def _text_request(
self,
prompt,
api_key,
model,
payload_options,
system_prompt="",
extra_body_json="",
images=None,
base_url=OPENROUTER_BASE_URL,
timeout_seconds=300,
verify_ssl=True,
):
prompt = _validate_prompt(prompt)
model = _validate_model(model)
payload = {
"model": model,
"messages": _build_messages(prompt, system_prompt=system_prompt, images=images),
"stream": False,
}
payload.update(payload_options)
payload.update(_parse_json_object(extra_body_json, "extra_body_json"))
response_json = await self._send_chat(api_key, base_url, payload, timeout_seconds, verify_ssl)
text = _extract_text(response_json)
if not text:
raise ValueError(f"No text output found in OpenRouter response: {_json_dumps(response_json)}")
return text, _extract_reasoning(response_json), response_json.get("id", "")
async def _image_request(
self,
prompt,
api_key,
model,
payload_options,
system_prompt="",
extra_body_json="",
images=None,
base_url=OPENROUTER_BASE_URL,
timeout_seconds=300,
verify_ssl=True,
):
prompt = _validate_prompt(prompt)
model = _validate_model(model)
payload = {
"model": model,
"messages": _build_messages(prompt, system_prompt=system_prompt, images=images),
"stream": False,
}
payload.update(payload_options)
payload.update(_parse_json_object(extra_body_json, "extra_body_json"))
response_json = await self._send_chat(api_key, base_url, payload, timeout_seconds, verify_ssl)
image_urls = _extract_generated_image_urls(response_json)
if not image_urls:
text = _extract_text(response_json).strip()
if text:
raise ValueError(f"OpenRouter returned no image. Text response: {text}")
raise ValueError(f"No image output found in OpenRouter response: {_json_dumps(response_json)}")
pil_images = await asyncio.gather(
*[
asyncio.to_thread(
_load_pil_from_url,
image_url,
int(timeout_seconds),
bool(verify_ssl),
)
for image_url in image_urls
]
)
return _pil_images_to_tensor_batch(pil_images), _extract_text(response_json), response_json.get("id", "")
class WuddOpenRouterGPTText(_OpenRouterBase):
@classmethod
def INPUT_TYPES(cls):
optional = _system_and_extra_inputs()
optional.update(_image_port_inputs(MAX_TEXT_IMAGE_INPUTS))
return {
"required": {
"prompt": ("STRING", {"default": "", "multiline": True}),
"api_key": ("STRING", {"default": ""}),
"model": (OPENAI_GPT_TEXT_MODELS, {"default": "openai/gpt-5.5"}),
"max_tokens": (
"INT",
{"default": 4096, "min": 16, "max": 128000, "step": 1},
),
"reasoning_effort": (REASONING_EFFORTS, {"default": "none"}),
"include_reasoning": ("BOOLEAN", {"default": False}),
"response_format": (TEXT_RESPONSE_FORMATS, {"default": "text"}),
"seed": (
"INT",
{
"default": 0,
"min": 0,
"max": 2147483647,
"step": 1,
"control_after_generate": True,
},
),
**_api_runtime_inputs(),
},
"optional": optional,
}
RETURN_TYPES = ("STRING", "STRING", "STRING")
RETURN_NAMES = ("text", "reasoning", "response_id")
CATEGORY = TEXT_CATEGORY
async def generate(
self,
prompt,
api_key,
model,
max_tokens,
reasoning_effort,
include_reasoning,
response_format,
seed,
base_url,
timeout_seconds,
verify_ssl,
system_prompt="",
extra_body_json="",
**kwargs,
):
options = {
"max_tokens": int(max_tokens),
}
_add_reasoning(options, reasoning_effort)
_add_response_format(options, response_format)
if include_reasoning:
options["include_reasoning"] = True
if int(seed) > 0:
options["seed"] = int(seed)
images = _collect_numbered_images(kwargs, MAX_TEXT_IMAGE_INPUTS)
return await self._text_request(
prompt,
api_key,
model,
options,
system_prompt=system_prompt,
extra_body_json=extra_body_json,
images=images,
base_url=base_url,
timeout_seconds=timeout_seconds,
verify_ssl=verify_ssl,
)
class WuddOpenRouterClaudeText(_OpenRouterBase):
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"prompt": ("STRING", {"default": "", "multiline": True}),
"api_key": ("STRING", {"default": ""}),
"model": (CLAUDE_TEXT_MODELS, {"default": "anthropic/claude-sonnet-4.6"}),
"max_tokens": (
"INT",
{"default": 4096, "min": 16, "max": 128000, "step": 1},
),
"temperature": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01},
),
"top_p": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01},
),
"top_k": (
"INT",
{"default": 0, "min": 0, "max": 1000, "step": 1},
),
"verbosity": (["none", "low", "medium", "high", "xhigh", "max"], {"default": "none"}),
"reasoning_effort": (REASONING_EFFORTS, {"default": "none"}),
"include_reasoning": ("BOOLEAN", {"default": False}),
**_api_runtime_inputs(),
},
"optional": {
**_system_and_extra_inputs(),
"stop_sequences": (
"STRING",
{
"default": "",
"multiline": True,
"advanced": True,
},
),
},
}
RETURN_TYPES = ("STRING", "STRING", "STRING")
RETURN_NAMES = ("text", "reasoning", "response_id")
CATEGORY = TEXT_CATEGORY
async def generate(
self,
prompt,
api_key,
model,
max_tokens,
temperature,
top_p,
top_k,
verbosity,
reasoning_effort,
include_reasoning,
base_url,
timeout_seconds,
verify_ssl,
system_prompt="",
extra_body_json="",
stop_sequences="",
):
options = {
"max_tokens": int(max_tokens),
}
supports_sampling = "sonnet" in str(model).lower()
if supports_sampling and float(temperature) != 1.0:
options["temperature"] = float(temperature)
if supports_sampling and float(top_p) != 1.0:
options["top_p"] = float(top_p)
if supports_sampling and int(top_k) > 0:
options["top_k"] = int(top_k)
if verbosity != "none":
options["verbosity"] = verbosity
_add_reasoning(options, reasoning_effort)
_add_stop_sequences(options, stop_sequences)
if include_reasoning:
options["include_reasoning"] = True
return await self._text_request(
prompt,
api_key,
model,
options,
system_prompt=system_prompt,
extra_body_json=extra_body_json,
base_url=base_url,
timeout_seconds=timeout_seconds,
verify_ssl=verify_ssl,
)
class WuddOpenRouterGeminiText(_OpenRouterBase):
@classmethod
def INPUT_TYPES(cls):
optional = _system_and_extra_inputs()
optional.update(_image_port_inputs(MAX_TEXT_IMAGE_INPUTS))
optional["stop_sequences"] = (
"STRING",
{
"default": "",
"multiline": True,
"advanced": True,
},
)
return {
"required": {
"prompt": ("STRING", {"default": "", "multiline": True}),
"api_key": ("STRING", {"default": ""}),
"model": (GEMINI_TEXT_MODELS, {"default": "google/gemini-3.1-pro-preview"}),
"max_tokens": (
"INT",
{"default": 4096, "min": 16, "max": 128000, "step": 1},
),
"temperature": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.01},
),
"top_p": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01},
),
"reasoning_effort": (REASONING_EFFORTS, {"default": "none"}),
"include_reasoning": ("BOOLEAN", {"default": False}),
"response_format": (TEXT_RESPONSE_FORMATS, {"default": "text"}),
"seed": (
"INT",
{
"default": 0,
"min": 0,
"max": 2147483647,
"step": 1,
"control_after_generate": True,
},
),
**_api_runtime_inputs(),
},
"optional": optional,
}
RETURN_TYPES = ("STRING", "STRING", "STRING")
RETURN_NAMES = ("text", "reasoning", "response_id")
CATEGORY = TEXT_CATEGORY
async def generate(
self,
prompt,
api_key,
model,
max_tokens,
temperature,
top_p,
reasoning_effort,
include_reasoning,
response_format,
seed,
base_url,
timeout_seconds,
verify_ssl,
system_prompt="",
extra_body_json="",
stop_sequences="",
**kwargs,
):
options = {
"max_tokens": int(max_tokens),
}
if float(temperature) != 1.0:
options["temperature"] = float(temperature)
if float(top_p) != 1.0:
options["top_p"] = float(top_p)
if int(seed) > 0:
options["seed"] = int(seed)
_add_reasoning(options, reasoning_effort)
_add_response_format(options, response_format)
_add_stop_sequences(options, stop_sequences)
if include_reasoning:
options["include_reasoning"] = True
images = _collect_numbered_images(kwargs, MAX_TEXT_IMAGE_INPUTS)
return await self._text_request(
prompt,
api_key,
model,
options,
system_prompt=system_prompt,
extra_body_json=extra_body_json,
images=images,
base_url=base_url,
timeout_seconds=timeout_seconds,
verify_ssl=verify_ssl,
)
class WuddOpenRouterGPTImage(_OpenRouterBase):
@classmethod
def INPUT_TYPES(cls):
optional = _system_and_extra_inputs()
optional.update(_image_port_inputs(MAX_IMAGE_NODE_INPUTS))
return {
"required": {
"prompt": ("STRING", {"default": "", "multiline": True}),
"api_key": ("STRING", {"default": ""}),
"model": (OPENAI_GPT_IMAGE_MODELS, {"default": "openai/gpt-5.4-image-2"}),
"response_modalities": (IMAGE_RESPONSE_MODALITIES, {"default": "IMAGE+TEXT"}),
"aspect_ratio": (STANDARD_ASPECT_RATIOS, {"default": "auto"}),
"image_size": (GPT_IMAGE_SIZES, {"default": "auto"}),
"max_tokens": (
"INT",
{"default": 4096, "min": 16, "max": 128000, "step": 1},
),
"reasoning_effort": (REASONING_EFFORTS, {"default": "none"}),
"seed": (
"INT",
{
"default": 0,
"min": 0,
"max": 2147483647,
"step": 1,
"control_after_generate": True,
},
),
**_api_runtime_inputs(),
},
"optional": optional,
}
RETURN_TYPES = ("IMAGE", "STRING", "STRING")
RETURN_NAMES = ("image", "text", "response_id")
CATEGORY = IMAGE_CATEGORY
async def generate(
self,
prompt,
api_key,
model,
response_modalities,
aspect_ratio,
image_size,
max_tokens,
reasoning_effort,
seed,
base_url,
timeout_seconds,
verify_ssl,
system_prompt="",
extra_body_json="",
**kwargs,
):
options = {
"modalities": ["image"] if response_modalities == "IMAGE" else ["image", "text"],
"max_tokens": int(max_tokens),
}
_add_image_config(options, model, aspect_ratio, image_size)
if int(seed) > 0:
options["seed"] = int(seed)
_add_reasoning(options, reasoning_effort)
images = _collect_numbered_images(kwargs, MAX_IMAGE_NODE_INPUTS)
return await self._image_request(
prompt,
api_key,
model,
options,
system_prompt=system_prompt,
extra_body_json=extra_body_json,
images=images,
base_url=base_url,
timeout_seconds=timeout_seconds,
verify_ssl=verify_ssl,
)
class WuddOpenRouterGeminiImage(_OpenRouterBase):
@classmethod
def INPUT_TYPES(cls):
optional = _system_and_extra_inputs()
optional.update(_image_port_inputs(MAX_IMAGE_NODE_INPUTS))
return {
"required": {
"prompt": ("STRING", {"default": "", "multiline": True}),
"api_key": ("STRING", {"default": ""}),
"model": (GEMINI_IMAGE_MODELS, {"default": "google/gemini-3.1-flash-image-preview"}),
"response_modalities": (IMAGE_RESPONSE_MODALITIES, {"default": "IMAGE+TEXT"}),
"aspect_ratio": (EXTENDED_ASPECT_RATIOS, {"default": "auto"}),
"image_size": (GEMINI_IMAGE_SIZES, {"default": "auto"}),
"max_tokens": (
"INT",
{"default": 4096, "min": 16, "max": 128000, "step": 1},
),
"temperature": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.01},
),
"top_p": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01},
),
"reasoning_effort": (REASONING_EFFORTS, {"default": "none"}),
"seed": (
"INT",
{
"default": 0,
"min": 0,
"max": 2147483647,
"step": 1,