-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenrouter_pipe.py
More file actions
1820 lines (1638 loc) · 78.3 KB
/
openrouter_pipe.py
File metadata and controls
1820 lines (1638 loc) · 78.3 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
"""
title: OpenRouter Pipe
author: Sena Labs
author_url: https://github.com/sena-labs
funding_url: https://github.com/sponsors/sena-labs
version: 1.6.0
license: MIT
icon_url: data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj48ZGVmcz48bGluZWFyR3JhZGllbnQgaWQ9ImJnIiB4MT0iMCUiIHkxPSIwJSIgeDI9IjEwMCUiIHkyPSIxMDAlIj48c3RvcCBvZmZzZXQ9IjAlIiBzdG9wLWNvbG9yPSIjNmQyOGQ5Ii8+PHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjYTc4YmZhIi8+PC9saW5lYXJHcmFkaWVudD48L2RlZnM+PHJlY3Qgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiIHJ4PSIyMCIgZmlsbD0idXJsKCNiZykiLz48cGF0aCBkPSJNMjAgNTAgQzIwIDMwLCA0MCAzMCwgNTAgMzAgTDUwIDIyIEw2OCA0MCBMNTAgNTggTDUwIDUwIEM0MCA1MCwgMzUgNDUsIDMwIDUwIEMyNSA1NSwgMjAgNzAsIDIwIDUwIFoiIGZpbGw9IndoaXRlIiBvcGFjaXR5PSIwLjk1Ii8+PGNpcmNsZSBjeD0iNzgiIGN5PSIzMCIgcj0iNyIgZmlsbD0id2hpdGUiIG9wYWNpdHk9IjAuOCIvPjxjaXJjbGUgY3g9IjgyIiBjeT0iNTAiIHI9IjciIGZpbGw9IndoaXRlIiBvcGFjaXR5PSIwLjk1Ii8+PGNpcmNsZSBjeD0iNzgiIGN5PSI3MCIgcj0iNyIgZmlsbD0id2hpdGUiIG9wYWNpdHk9IjAuOCIvPjxsaW5lIHgxPSI2OCIgeTE9IjQwIiB4Mj0iNzYiIHkyPSIzMiIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIyIiBvcGFjaXR5PSIwLjUiLz48bGluZSB4MT0iNjgiIHkxPSI0MCIgeDI9Ijc2IiB5Mj0iNTAiIHN0cm9rZT0id2hpdGUiIHN0cm9rZS13aWR0aD0iMiIgb3BhY2l0eT0iMC41Ii8+PGxpbmUgeDE9IjY4IiB5MT0iNDAiIHgyPSI3NiIgeTI9IjY4IiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjIiIG9wYWNpdHk9IjAuNSIvPjwvc3ZnPg==
required_open_webui_version: 0.4.0
requirements: requests>=2.20, pydantic>=2.0
description: The definitive OpenRouter integration for Open WebUI. Full catalog (chat/TTS/audio/image/embeddings), variant routing (:nitro/:exacto/:thinking/:online/:free/:extended), web search plugin with domain filters, server-side category filter, deprecation warnings, extended reasoning (minimal→xhigh + max_tokens + summary), Anthropic interleaved thinking + cache TTL, ZDR enforcement, tool/free-tier filters, provider preferences (only/quantizations/max_price/allow_fallbacks), service tier routing (auto/flex/priority/scale), generation-ID auditability, cached-input cost breakdown, model fallbacks, middle-out compression, citations, auto-discovered provider icons.
"""
import copy
import hashlib
import json
import os
import random
import re
import time
import traceback
from typing import AsyncGenerator, Callable, Generator, List, Optional, Union
import requests
from pydantic import BaseModel, Field, field_validator
# Keys injected by Open WebUI internals — must not be forwarded to OpenRouter
_OWUI_INTERNAL_KEYS = frozenset(
{"chat_id", "title", "task", "task_id", "features", "citations",
"metadata", "files", "tool_ids", "session_id", "message_id"}
)
_CITATION_RE = re.compile(r"\[(\d+)\]")
# API path constants
_API_PATH_MODELS = "/models"
_API_PATH_CHAT = "/chat/completions"
_API_PATH_ZDR_ENDPOINTS = "/endpoints/zdr"
# Beta header for Claude's interleaved-thinking + tool-use mode.
# https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
_ANTHROPIC_INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14"
# OpenRouter variant suffixes that route to specialized providers/profiles.
# https://openrouter.ai/docs/features/preset-routing
_RECOGNISED_VARIANT_TAGS = frozenset(
{"free", "thinking", "online", "nitro", "exacto", "extended"}
)
# Cache TTL for model list (seconds)
_MODELS_CACHE_TTL = 300.0 # 5 minutes
# OpenRouter's frontend provider registry — gives us icon URLs for ~70 providers
# (hosted SVG/PNG when available, gstatic favicons otherwise). Used as a
# dynamic fallback when a model's author isn't in _PROVIDER_ICONS.
_PROVIDER_REGISTRY_URL = "https://openrouter.ai/api/frontend/all-providers"
# Provider icons — synced into the Open WebUI Models database by
# _sync_model_icons() so the frontend can serve them via
# /models/model/profile/image. Disable with SYNC_PROVIDER_ICONS = False.
# Hardcoded fast path for top model authors; everything else is auto-discovered
# via _load_provider_registry().
# URLs verified against https://openrouter.ai/images/icons/ (May 2025).
_PROVIDER_ICONS = {
"openai": "https://openrouter.ai/images/icons/OpenAI.svg",
"anthropic": "https://openrouter.ai/images/icons/Anthropic.svg",
"google": "https://openrouter.ai/images/icons/GoogleGemini.svg",
"meta-llama": "https://openrouter.ai/images/icons/Meta.png",
"mistralai": "https://openrouter.ai/images/icons/Mistral.png",
"amazon": "https://openrouter.ai/images/icons/Bedrock.svg",
"deepseek": "https://openrouter.ai/images/icons/DeepSeek.png",
"cohere": "https://openrouter.ai/images/icons/Cohere.png",
"perplexity": "https://openrouter.ai/images/icons/Perplexity.svg",
"qwen": "https://openrouter.ai/images/icons/Qwen.png",
"microsoft": "https://openrouter.ai/images/icons/Microsoft.svg",
"fireworks": "https://openrouter.ai/images/icons/Fireworks.png",
"moonshotai": "https://openrouter.ai/images/icons/MoonshotAI.png",
}
def _is_safe_url(url: str) -> bool:
"""Return True only for http:// and https:// URLs."""
return isinstance(url, str) and url.lower().startswith(("http://", "https://"))
def _is_owui_managed_icon(url: str) -> bool:
"""Return True if the icon URL was set by OWUI or our sync logic.
data: URLs are the pipe's own SVG icon that OWUI assigns as default to all
manifold child models. openrouter.ai/images/models/ and
openrouter.ai/images/icons/ are the OpenRouter-hosted provider icons we
write (the former was the old path, superseded by the latter).
t0.gstatic.com/faviconV2 URLs are the gstatic favicons returned by
OpenRouter's provider registry for providers without a hosted icon — we
write those too as part of icon auto-discovery, so they must remain
overwriteable when OpenRouter updates its mapping. Any other URL is
assumed to be a user-set custom icon and must not be overwritten.
"""
return (
not url
or url.startswith("data:")
or url.startswith("https://openrouter.ai/images/models/")
or url.startswith("https://openrouter.ai/images/icons/")
or url.startswith("https://t0.gstatic.com/faviconV2")
)
def _insert_citations(text: str, citations: Optional[List[str]]) -> str:
"""Replace [n] references with markdown links (only safe HTTP URLs)."""
if not citations or not text:
return text
def _replace(match_obj):
try:
idx = int(match_obj.group(1)) - 1
if 0 <= idx < len(citations) and _is_safe_url(citations[idx]):
safe_url = citations[idx].replace(")", "%29")
return f"[[{idx + 1}]]({safe_url})"
except (ValueError, IndexError):
pass
return match_obj.group(0)
try:
return _CITATION_RE.sub(_replace, text)
except Exception as exc: # pragma: no cover
print(f"[OpenRouter Pipe] Citation injection error: {exc}")
return text
def _format_citation_list(citations: Optional[List[str]]) -> str:
if not citations:
return ""
try:
rendered = "\n".join(f"{idx + 1}. {url}" for idx, url in enumerate(citations))
return f"\n\n---\nCitations:\n{rendered}"
except Exception as exc: # pragma: no cover
print(f"[OpenRouter Pipe] Citation formatting error: {exc}")
return ""
_CURRENCY_SYMBOLS = {
"USD": "$",
"EUR": "€",
"GBP": "£",
"JPY": "¥",
"CAD": "CA$",
"AUD": "A$",
}
def _format_cost_info(usage: dict, currency: str = "USD") -> str:
"""Format token usage and cost from an OpenRouter usage dict.
When the provider reports cached prompt tokens (90%+ cheaper on most
providers), the breakdown is shown so users see the savings.
"""
if not usage:
return ""
prompt = usage.get("prompt_tokens", 0)
completion = usage.get("completion_tokens", 0)
total = usage.get("total_tokens", 0) or (prompt + completion)
cost = usage.get("cost")
# Cached prompt tokens — emitted by Anthropic prompt caching, OpenAI
# implicit caching, and Gemini context caching. Shape varies per provider.
cached_tokens = 0
details = usage.get("prompt_tokens_details") or {}
if isinstance(details, dict):
cached_tokens = details.get("cached_tokens") or 0
if not cached_tokens:
cached_tokens = usage.get("cache_read_input_tokens") or 0
if cached_tokens:
non_cached = max(prompt - int(cached_tokens), 0)
token_str = (
f"{non_cached:,} prompt + {int(cached_tokens):,} cached + "
f"{completion:,} completion = {total:,} total"
)
else:
token_str = f"{prompt:,} prompt + {completion:,} completion = {total:,} total"
parts = [f"**Tokens:** {token_str}"]
if cost is not None:
try:
cost_f = float(cost)
symbol = _CURRENCY_SYMBOLS.get(currency, f"{currency} ")
if cost_f == 0:
cost_str = f"{symbol}0.00"
elif cost_f < 0.0001:
cost_str = f"{symbol}{cost_f:.6f}"
elif cost_f < 0.01:
cost_str = f"{symbol}{cost_f:.5f}"
else:
cost_str = f"{symbol}{cost_f:.4f}"
parts.append(f"**Cost:** {cost_str}")
except (ValueError, TypeError):
pass
return f"\n\n---\n*{' · '.join(parts)}*"
def _format_generation_id(generation_id: Optional[str]) -> str:
"""Format the OpenRouter generation ID footer.
Users can pass the ID to ``GET /api/v1/generation?id={id}`` to retrieve
detailed usage and routing info for any past request.
"""
if not generation_id:
return ""
return f"\n\n---\n*Generation ID: `{generation_id}`*"
def _format_image_output(images: list) -> str:
"""Format OpenRouter image output objects as markdown image tags.
Only http(s) and data:image/* URLs are rendered; others are dropped.
Closing parentheses in URLs are percent-encoded to avoid breaking markdown.
"""
parts = []
for img in (images or []):
if not isinstance(img, dict):
continue
url = (img.get("image_url") or {}).get("url", "")
if not url:
continue
lower = url.lower()
if not (lower.startswith(("http://", "https://")) or lower.startswith("data:image/")):
continue
parts.append(f"', '%29')})")
return "\n\n".join(parts)
class Pipe:
class Valves(BaseModel):
OPENROUTER_API_KEY: str = Field(
default=os.getenv("OPENROUTER_API_KEY", ""),
description="OpenRouter API key",
json_schema_extra={"input": {"type": "password"}},
)
OPENROUTER_BASE_URL: str = Field(
default=os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1"),
description="OpenRouter base endpoint (must start with https://)",
)
REASONING_EFFORT: str = Field(
default=os.getenv("OPENROUTER_REASONING_EFFORT", ""),
description=(
"Controls reasoning depth. Works independently of Include Reasoning. "
"'minimal' favors fastest output, 'xhigh' requests maximum depth on "
"supporting models."
),
json_schema_extra={
"input": {
"type": "select",
"options": [
{"value": "", "label": "Disabled"},
{"value": "minimal", "label": "Minimal"},
{"value": "low", "label": "Low"},
{"value": "medium", "label": "Medium"},
{"value": "high", "label": "High"},
{"value": "xhigh", "label": "Extra High"},
],
}
},
)
REASONING_SUMMARY_MODE: str = Field(
default=os.getenv("OPENROUTER_REASONING_SUMMARY_MODE", "disabled"),
description=(
"Reasoning summary verbosity sent as `reasoning.summary` in the "
"request payload. 'disabled' (default) skips the field entirely; "
"supporting models emit a concise/detailed summary block alongside "
"their reasoning trace."
),
json_schema_extra={
"input": {
"type": "select",
"options": [
{"value": "disabled", "label": "Disabled"},
{"value": "auto", "label": "Auto"},
{"value": "concise", "label": "Concise"},
{"value": "detailed", "label": "Detailed"},
],
}
},
)
REASONING_MAX_TOKENS: int = Field(
default=int(os.getenv("OPENROUTER_REASONING_MAX_TOKENS", "0")),
ge=0,
description=(
"Hard cap on reasoning tokens per response (sent as "
"`reasoning.max_tokens`). 0 (default) leaves the cap to the "
"provider. Useful for budget control on deep-thinking models."
),
)
INCLUDE_REASONING: bool = Field(
default=os.getenv("OPENROUTER_INCLUDE_REASONING", "true").lower() == "true",
description="Show model reasoning in <think> blocks. Can be used with or without Reasoning Effort",
)
ENABLE_ANTHROPIC_INTERLEAVED_THINKING: bool = Field(
default=os.getenv(
"OPENROUTER_ANTHROPIC_INTERLEAVED_THINKING", "true"
).lower()
== "true",
description=(
"When True and the selected model is `anthropic/...`, send the "
"`anthropic-beta: interleaved-thinking-2025-05-14` header so Claude "
"interleaves reasoning with tool use. No effect on other providers."
),
)
MODEL_PREFIX: Optional[str] = Field(
default=None, description="Prefix shown before model names (include trailing space if needed, e.g. 'OR: ')"
)
MODEL_PROVIDERS: str = Field(
default=os.getenv("OPENROUTER_MODEL_PROVIDERS", "ALL"),
description="Provider filter (e.g. openai,google). Use ALL for all models",
)
INVERT_PROVIDER_LIST: bool = Field(
default=os.getenv("OPENROUTER_INVERT_PROVIDER_LIST", "false").lower()
== "true",
description="When true the provider list becomes an exclusion list",
)
FREE_MODEL_FILTER: str = Field(
default=os.getenv("OPENROUTER_FREE_MODEL_FILTER", "all"),
description=(
"Filter the catalog by free-tier status (':free' suffix or zero "
"prompt+completion pricing). 'all' = no filter (default), "
"'only' = keep just free models, 'exclude' = hide free models."
),
json_schema_extra={
"input": {
"type": "select",
"options": [
{"value": "all", "label": "All"},
{"value": "only", "label": "Only free"},
{"value": "exclude", "label": "Exclude free"},
],
}
},
)
TOOL_CALLING_FILTER: str = Field(
default=os.getenv("OPENROUTER_TOOL_CALLING_FILTER", "all"),
description=(
"Filter the catalog by tool-calling capability "
"(`supported_parameters` containing `tools` or `tool_choice`). "
"'all' (default) keeps everything, 'only' restricts to tool-capable "
"models, 'exclude' hides them."
),
json_schema_extra={
"input": {
"type": "select",
"options": [
{"value": "all", "label": "All"},
{"value": "only", "label": "Only tool-capable"},
{"value": "exclude", "label": "Exclude tool-capable"},
],
}
},
)
MODEL_VARIANTS: str = Field(
default=os.getenv("OPENROUTER_MODEL_VARIANTS", ""),
description=(
"Comma-separated `base_id:variant` entries to expose as virtual "
"models that inherit the base model's metadata (name, icon). "
"Example: 'openai/gpt-4o:nitro, anthropic/claude-3.5-sonnet:thinking'. "
"Recognised tags: free, thinking, online, nitro, exacto, extended. "
"OpenRouter routes the suffixed ID specially "
"(see https://openrouter.ai/docs/features/preset-routing)."
),
)
MODEL_CATEGORY: str = Field(
default=os.getenv("OPENROUTER_MODEL_CATEGORY", ""),
description=(
"Server-side category filter for `/models` (passed as "
"`?category=...`). Empty disables. Common values: "
"programming, roleplay, marketing, marketing/seo, technology, "
"science, translation, legal, finance, health, trivia, academia."
),
)
HIDE_DEPRECATED_MODELS: bool = Field(
default=os.getenv("OPENROUTER_HIDE_DEPRECATED_MODELS", "false").lower()
== "true",
description=(
"Hide models with a non-null `expiration_date`. When False "
"(default), deprecated models stay visible but are tagged with "
"a ⚠ prefix in the display name."
),
)
OUTPUT_MODALITIES: str = Field(
default=os.getenv("OPENROUTER_OUTPUT_MODALITIES", "all"),
description=(
"Output modalities to fetch from OpenRouter's /models endpoint. "
"'all' (default) lists every model — chat, TTS, audio, image, and embeddings. "
"Use 'text' for chat-only, or a comma list e.g. 'text,audio'. "
"Valid tokens: text, image, audio, embeddings, all."
),
)
PROVIDER_SORT: str = Field(
default=os.getenv("OPENROUTER_PROVIDER_SORT", ""),
description="Provider sort order: empty=default, price, throughput, latency",
json_schema_extra={
"input": {
"type": "select",
"options": [
{"value": "", "label": "Default"},
{"value": "price", "label": "Price"},
{"value": "throughput", "label": "Throughput"},
{"value": "latency", "label": "Latency"},
],
}
},
)
PROVIDER_ORDER: str = Field(
default=os.getenv("OPENROUTER_PROVIDER_ORDER", ""),
description="Preferred providers, comma-separated (e.g. anthropic,openai)",
)
PROVIDER_IGNORE: str = Field(
default=os.getenv("OPENROUTER_PROVIDER_IGNORE", ""),
description="Excluded providers, comma-separated",
)
PROVIDER_ONLY: str = Field(
default=os.getenv("OPENROUTER_PROVIDER_ONLY", ""),
description=(
"Allowlist of provider slugs to use (comma-separated). When "
"set, OpenRouter routes only to these providers. Merged with "
"your account-wide allowlist."
),
)
PROVIDER_QUANTIZATIONS: str = Field(
default=os.getenv("OPENROUTER_PROVIDER_QUANTIZATIONS", ""),
description=(
"Comma-separated quantization filters (e.g. 'bf16,fp8'). Only "
"endpoints serving the model at one of these precisions will "
"be used. Common values: bf16, fp16, fp8, int8, int4."
),
)
PROVIDER_ALLOW_FALLBACKS: bool = Field(
default=os.getenv("OPENROUTER_PROVIDER_ALLOW_FALLBACKS", "true").lower()
== "true",
description=(
"When True (default), OpenRouter falls back to alternate "
"providers if the primary one (or those in PROVIDER_ORDER) is "
"unavailable. Set False to fail fast on the primary provider."
),
)
PROVIDER_MAX_PRICE_PROMPT: str = Field(
default=os.getenv("OPENROUTER_PROVIDER_MAX_PRICE_PROMPT", ""),
description=(
"Maximum prompt price (USD per 1M tokens) you accept for this "
"request, e.g. '3.0'. Empty disables. Sent as "
"`provider.max_price.prompt`."
),
)
PROVIDER_MAX_PRICE_COMPLETION: str = Field(
default=os.getenv("OPENROUTER_PROVIDER_MAX_PRICE_COMPLETION", ""),
description=(
"Maximum completion price (USD per 1M tokens) you accept for "
"this request, e.g. '15.0'. Empty disables. Sent as "
"`provider.max_price.completion`."
),
)
SERVICE_TIER: str = Field(
default=os.getenv("OPENROUTER_SERVICE_TIER", ""),
description=(
"OpenAI-style service tier hint forwarded to compatible "
"providers. Empty (default) leaves the choice to the provider."
),
json_schema_extra={
"input": {
"type": "select",
"options": [
{"value": "", "label": "Default"},
{"value": "auto", "label": "Auto"},
{"value": "default", "label": "Default tier"},
{"value": "flex", "label": "Flex (cheaper, slower)"},
{"value": "priority", "label": "Priority (faster)"},
{"value": "scale", "label": "Scale"},
],
}
},
)
REQUIRE_PARAMETERS: bool = Field(
default=os.getenv("OPENROUTER_REQUIRE_PARAMETERS", "false").lower()
== "true",
description="Restrict to providers supporting all parameters in the request (e.g., temperature, top_p). May reduce available providers",
)
DATA_COLLECTION: str = Field(
default=os.getenv("OPENROUTER_DATA_COLLECTION", "allow"),
description="Whether AI providers can use your prompts for training. 'deny' opts out of data collection",
json_schema_extra={
"input": {
"type": "select",
"options": [
{"value": "allow", "label": "Allow"},
{"value": "deny", "label": "Deny"},
],
}
},
)
FALLBACK_MODELS: str = Field(
default=os.getenv("OPENROUTER_FALLBACK_MODELS", ""),
description="Fallback model IDs, comma-separated (e.g. openai/gpt-4o,anthropic/claude-3.5-sonnet)",
)
ENABLE_MIDDLE_OUT: bool = Field(
default=os.getenv("OPENROUTER_ENABLE_MIDDLE_OUT", "false").lower()
== "true",
description="Automatically compress long conversations that exceed the model's context window by summarizing middle messages",
)
ENABLE_WEB_SEARCH: bool = Field(
default=os.getenv("OPENROUTER_ENABLE_WEB_SEARCH", "false").lower()
== "true",
description=(
"Attach OpenRouter's `web` plugin to every request so the "
"model can ground answers in fresh web results. Stacks with "
"the `:online` variant tag (provider-side) — pick one. "
"OpenRouter charges per search call separately from tokens."
),
)
WEB_SEARCH_MAX_RESULTS: int = Field(
default=int(os.getenv("OPENROUTER_WEB_SEARCH_MAX_RESULTS", "5")),
ge=1,
le=20,
description="Maximum number of search results returned to the model when ENABLE_WEB_SEARCH is on.",
)
WEB_SEARCH_PROMPT: str = Field(
default=os.getenv("OPENROUTER_WEB_SEARCH_PROMPT", ""),
description=(
"Optional custom search prompt forwarded to the search engine "
"(`plugins[].search_prompt`). Empty uses OpenRouter's default."
),
)
WEB_SEARCH_INCLUDE_DOMAINS: str = Field(
default=os.getenv("OPENROUTER_WEB_SEARCH_INCLUDE_DOMAINS", ""),
description=(
"Comma-separated domain allowlist for web search. Wildcards "
"and path filters supported (e.g. '*.substack.com, "
"openai.com/blog')."
),
)
WEB_SEARCH_EXCLUDE_DOMAINS: str = Field(
default=os.getenv("OPENROUTER_WEB_SEARCH_EXCLUDE_DOMAINS", ""),
description="Comma-separated domain denylist for web search (same format as include list).",
)
ENABLE_CACHE_CONTROL: bool = Field(
default=os.getenv("OPENROUTER_ENABLE_CACHE_CONTROL", "false").lower()
== "true",
description="Enable prompt caching for Anthropic models (reduces cost on repeated long prompts). No effect on other providers",
)
ANTHROPIC_PROMPT_CACHE_TTL: str = Field(
default=os.getenv("OPENROUTER_ANTHROPIC_PROMPT_CACHE_TTL", "5m"),
description=(
"TTL for the Anthropic ephemeral cache breakpoint when "
"ENABLE_CACHE_CONTROL is on. '5m' (default) keeps the standard "
"short-lived cache; '1h' costs more on cache writes but persists "
"longer between turns."
),
json_schema_extra={
"input": {
"type": "select",
"options": [
{"value": "5m", "label": "5 minutes"},
{"value": "1h", "label": "1 hour"},
],
}
},
)
ZDR_ENFORCE: bool = Field(
default=os.getenv("OPENROUTER_ZDR_ENFORCE", "false").lower() == "true",
description=(
"When True, every chat request includes `provider.zdr=true` so "
"OpenRouter rejects the call unless a Zero Data Retention "
"endpoint is available for the chosen model."
),
)
ZDR_MODELS_ONLY: bool = Field(
default=os.getenv("OPENROUTER_ZDR_MODELS_ONLY", "false").lower() == "true",
description=(
"Catalog-side filter: when True, fetch OpenRouter's "
"`/endpoints/zdr` list and hide models without any ZDR-capable "
"endpoint. Pairs well with ZDR_ENFORCE for end-to-end privacy "
"guarantees."
),
)
HTTP_REFERER_OVERRIDE: str = Field(
default=os.getenv("OPENROUTER_HTTP_REFERER", ""),
description=(
"Override the `HTTP-Referer` header sent to OpenRouter for app "
"attribution (must be a full URL with scheme). Empty falls back "
"to WEBUI_URL or http://localhost:3000."
),
)
SYNC_PROVIDER_ICONS: bool = Field(
default=os.getenv("OPENROUTER_SYNC_ICONS", "true").lower() == "true",
description="Automatically sync provider icons into Open WebUI's model database so they appear in the UI",
)
REQUEST_TIMEOUT: int = Field(
default=int(os.getenv("OPENROUTER_REQUEST_TIMEOUT", "90")),
gt=0,
description="API request timeout in seconds",
)
MAX_RETRIES: int = Field(
default=2, ge=0, description="Auto-retries on transient errors (with exponential backoff)"
)
SHOW_COST_INFO: bool = Field(
default=False,
description="Append token usage and cost to each response",
)
SHOW_GENERATION_ID: bool = Field(
default=os.getenv("OPENROUTER_SHOW_GENERATION_ID", "false").lower()
== "true",
description=(
"Append the OpenRouter generation ID to each response so it "
"can be looked up later via `GET /generation?id=...` for "
"audit trails and per-request usage details."
),
)
COST_CURRENCY: str = Field(
default=os.getenv("OPENROUTER_COST_CURRENCY", "USD"),
description="Currency label shown in cost display (display only; OpenRouter bills in USD)",
json_schema_extra={
"input": {
"type": "select",
"options": [
{"value": "USD", "label": "USD ($)"},
{"value": "EUR", "label": "EUR (€)"},
{"value": "GBP", "label": "GBP (£)"},
{"value": "JPY", "label": "JPY (¥)"},
{"value": "CAD", "label": "CAD (CA$)"},
{"value": "AUD", "label": "AUD (A$)"},
],
}
},
)
@field_validator("OPENROUTER_BASE_URL")
@classmethod
def _validate_base_url(cls, v: str) -> str:
v = v.strip()
if not v.startswith(("https://", "http://")):
raise ValueError("Base URL must start with https:// or http://")
return v
def __init__(self) -> None:
self.type = "manifold"
self.valves = self.Valves()
self._session = requests.Session()
# Cache env vars that don't change at runtime
self._referer = os.getenv("WEBUI_URL", "http://localhost:3000")
self._title = os.getenv("WEBUI_NAME", "OpenWebUI")
# Model list cache
self._models_cache: Optional[List[dict]] = None
self._models_cache_ts: float = 0.0
self._models_cache_key: str = ""
# Track which model IDs already have icons synced (avoids repeated DB writes)
self._icons_synced: set = set()
# Lazy-loaded mirror of OpenRouter's provider registry (slug → icon URL).
# None = not attempted; {} = attempted but failed/empty (do not retry).
self._provider_registry: Optional[dict] = None
# Lazy-loaded set of model IDs that have at least one ZDR endpoint.
# None = not attempted; frozenset() = attempted but failed/empty.
self._zdr_model_ids: Optional[frozenset] = None
# Cache function_id once: OWUI sets __module__ to "function_{id}" at load time
_fm = type(self).__module__ or ""
self._function_id: Optional[str] = (
_fm[len("function_"):] if _fm.startswith("function_") else None
)
if not self.valves.OPENROUTER_API_KEY:
print("[OpenRouter Pipe] Warning: OPENROUTER_API_KEY not set")
@property
def _base(self) -> str:
"""Return the sanitized base URL (no trailing slash)."""
return self.valves.OPENROUTER_BASE_URL.rstrip("/")
@property
def models_url(self) -> str:
"""Return the full URL for the models endpoint."""
return f"{self._base}{_API_PATH_MODELS}"
@property
def chat_url(self) -> str:
"""Return the full URL for the chat completions endpoint."""
return f"{self._base}{_API_PATH_CHAT}"
def _build_cache_key(self) -> str:
"""Build a fingerprint of the valves that affect the model list.
The API key is hashed (not embedded raw) so it doesn't sit in plaintext
in long-lived strings that may end up in logs or memory dumps.
"""
api_key_hash = (
hashlib.sha256(self.valves.OPENROUTER_API_KEY.encode("utf-8")).hexdigest()[:16]
if self.valves.OPENROUTER_API_KEY
else ""
)
return (
f"{api_key_hash}|{self.valves.FREE_MODEL_FILTER}|"
f"{self.valves.MODEL_PROVIDERS}|{self.valves.INVERT_PROVIDER_LIST}|"
f"{self.valves.MODEL_PREFIX}|{self.valves.OUTPUT_MODALITIES}|"
f"{self.valves.TOOL_CALLING_FILTER}|{self.valves.ZDR_MODELS_ONLY}|"
f"{self.valves.MODEL_VARIANTS}|{self.valves.MODEL_CATEGORY}|"
f"{self.valves.HIDE_DEPRECATED_MODELS}"
)
def _models_cache_valid(self) -> bool:
"""Check if the cached model list is still valid."""
if not self._models_cache:
return False
if self._build_cache_key() != self._models_cache_key:
return False
return (time.monotonic() - self._models_cache_ts) < _MODELS_CACHE_TTL
def pipes(self) -> List[dict]:
"""Fetch and return the list of available OpenRouter models."""
if not self.valves.OPENROUTER_API_KEY:
return [{"id": "error", "name": "OpenRouter API key not configured. Set it in Settings."}]
# Return cached models if still valid
if self._models_cache_valid() and self._models_cache is not None:
# Continue syncing icons on cache hits until all models are confirmed.
# This resolves the race condition where OWUI registers models (and may
# overwrite icons) only after the first pipes() call returns.
if self.valves.SYNC_PROVIDER_ICONS and len(self._icons_synced) < len(self._models_cache):
self._sync_model_icons(self._models_cache)
return self._models_cache
headers = self._build_headers(include_content_type=False)
modalities = (self.valves.OUTPUT_MODALITIES or "all").strip() or "all"
params: dict = {"output_modalities": modalities}
category = (self.valves.MODEL_CATEGORY or "").strip()
if category:
params["category"] = category
response = None
try:
response = self._session.get(
self.models_url,
headers=headers,
params=params,
timeout=self.valves.REQUEST_TIMEOUT,
)
# Detect auth errors from the models endpoint itself
# 502 from Clerk usually means the key format is invalid
if response.status_code in (401, 403, 502):
detail = ""
try:
detail = response.json().get("error", {}).get("message", "")
except Exception:
pass
msg = f"Invalid API key (HTTP {response.status_code})"
if detail:
msg += f": {detail}"
msg += ". Check your OPENROUTER_API_KEY in valve settings."
return [{"id": "error", "name": msg}]
response.raise_for_status()
data = response.json().get("data", [])
except requests.exceptions.Timeout:
return [{"id": "error", "name": "Timeout fetching models. Try again or increase REQUEST_TIMEOUT."}]
except requests.exceptions.HTTPError as exc:
msg = f"HTTP {exc.response.status_code} fetching models"
try:
err = exc.response.json().get("error", {})
detail = err.get("message", str(err)) if isinstance(err, dict) else str(err)
if detail:
msg += f": {detail}"
except Exception:
pass
print(f"[OpenRouter Pipe] {msg}")
return [{"id": "error", "name": msg}]
except Exception as exc:
print(f"[OpenRouter Pipe] Model fetch error: {exc}")
traceback.print_exc()
return [{"id": "error", "name": f"Unexpected error: {exc}"}]
finally:
if response is not None:
response.close()
provider_filter = self._parse_provider_filter()
prefix = self.valves.MODEL_PREFIX or ""
free_filter = (self.valves.FREE_MODEL_FILTER or "all").strip().lower()
tool_filter = (self.valves.TOOL_CALLING_FILTER or "all").strip().lower()
zdr_only = self.valves.ZDR_MODELS_ONLY
zdr_capable_ids: Optional[frozenset] = (
self._load_zdr_model_ids() if zdr_only else None
)
models: List[dict] = []
for model in data:
model_id = model.get("id")
if not model_id:
continue
if free_filter in ("only", "exclude"):
is_free = ":free" in model_id.lower()
if not is_free:
pricing = model.get("pricing") or {}
try:
is_free = (
float(pricing.get("prompt", 1)) == 0
and float(pricing.get("completion", 1)) == 0
)
except (ValueError, TypeError):
is_free = False
if free_filter == "only" and not is_free:
continue
if free_filter == "exclude" and is_free:
continue
if tool_filter in ("only", "exclude"):
supported = model.get("supported_parameters") or []
tool_capable = any(
p in supported for p in ("tools", "tool_choice")
)
if tool_filter == "only" and not tool_capable:
continue
if tool_filter == "exclude" and tool_capable:
continue
if zdr_only and zdr_capable_ids is not None:
# OpenRouter's /endpoints/zdr returns base IDs (no '~' alias prefix
# and no ':variant' suffix). Strip both before comparing.
base_id = model_id.lstrip("~").split(":", 1)[0]
if base_id not in zdr_capable_ids:
continue
# Deprecation handling: a non-null `expiration_date` means
# OpenRouter has scheduled the model for removal. Hide the entry
# entirely when the operator opts in; otherwise keep it but tag
# the display name so users notice before relying on it.
expiration = model.get("expiration_date")
is_deprecated = expiration is not None and str(expiration).strip() != ""
if is_deprecated and self.valves.HIDE_DEPRECATED_MODELS:
continue
# Split model_id once for provider extraction.
# Strip leading '~' (OpenRouter "latest" aliases like ~anthropic/claude-haiku-latest)
# so they match the same provider filter as their base provider.
parts = model_id.split("/", 1)
provider_key = parts[0].lstrip("~").lower() if len(parts) > 1 else "openrouter"
if provider_filter:
keep = (provider_key in provider_filter) ^ self.valves.INVERT_PROVIDER_LIST
if not keep:
continue
model_name = model.get("name", model_id)
if is_deprecated:
model_name = f"⚠ {model_name} (deprecated)"
model_dict = {
"id": model_id,
"name": f"{prefix}{model_name}",
}
models.append(model_dict)
# Append virtual variant entries (e.g. openai/gpt-4o:nitro). Variants
# inherit the base model's display name; only the suffix and a tag
# label change — the icon-sync step writes the same provider icon.
models = self._expand_variant_models(models, prefix)
if not models:
if free_filter == "only":
error_text = "No free models available. Set FREE_MODEL_FILTER to 'all' to see paid models."
elif tool_filter == "only":
error_text = "No tool-capable models available. Set TOOL_CALLING_FILTER to 'all' to broaden the catalog."
elif zdr_only:
error_text = "No ZDR-capable models available. Disable ZDR_MODELS_ONLY or check your OpenRouter privacy settings."
elif provider_filter:
providers_str = ", ".join(sorted(provider_filter))
error_text = f"No models match providers: {providers_str}. Check MODEL_PROVIDERS setting."
else:
error_text = "No models found. Check your OpenRouter account and API key."
return [{"id": "error", "name": error_text}]
# Store in cache
self._models_cache = models
self._models_cache_ts = time.monotonic()
self._models_cache_key = self._build_cache_key()
# Sync provider icons into Open WebUI's Models database
if self.valves.SYNC_PROVIDER_ICONS:
self._sync_model_icons(models)
return models
@staticmethod
def _clean_model_id(model_id: str) -> str:
"""Strip the manifold prefix from a model ID.
OpenRouter model IDs use the format ``provider/model`` (e.g.
``anthropic/claude-3.5-sonnet``). The manifold prefix added by Open
WebUI is a function id without ``/`` (e.g. ``openrouter_pipe``). We
only strip when the text before the first ``.`` contains no ``/`` —
otherwise the dot is part of the model version (e.g.
``claude-3.5-sonnet``) and must be preserved.
"""
if "." not in model_id:
return model_id
prefix, rest = model_id.split(".", 1)
if "/" in prefix:
return model_id
return rest
async def pipe(
self,
body: dict,
__user__: Optional[dict] = None,
__event_emitter__: Optional[Callable] = None,
) -> Union[str, Generator[str, None, None], AsyncGenerator[str, None]]:
"""Route a chat completion request to OpenRouter (stream or non-stream).
Returns an async generator for streaming (allows proper status cleanup),
or a plain string for non-streaming responses.
"""
if not self.valves.OPENROUTER_API_KEY:
return "OpenRouter Error: OPENROUTER_API_KEY not configured. Set it in Settings → Connections."
model_id = self._clean_model_id(body.get("model", ""))
# Guard against selecting the error pseudo-model
if model_id == "error":
return "OpenRouter Error: No valid model selected. Check the model list for configuration issues."
# Validate messages exist
if not body.get("messages"):
return "OpenRouter Error: No messages provided."
if __event_emitter__:
await __event_emitter__(
{
"type": "status",
"data": {
"description": f"Querying {model_id or 'OpenRouter'}...",
"done": False,
},
}
)
payload = self._prepare_payload(body)
headers = self._build_headers(model_id=payload.get("model"))
stream = body.get("stream", False)
if stream:
gen = self._stream_response(headers, payload)
# Wrap in an async generator so we can await the done event
if __event_emitter__:
async def _wrap_stream():
try:
for chunk in gen:
yield chunk
finally:
await __event_emitter__(
{"type": "status", "data": {"description": "", "done": True}}
)
return _wrap_stream()
return gen
result = self._non_stream_response(headers, payload)
if __event_emitter__:
await __event_emitter__(
{"type": "status", "data": {"description": "", "done": True}}
)
return result
def _sync_model_icons(self, models: List[dict]) -> None:
"""Write provider icons into Open WebUI's Models DB.
Open WebUI serves model icons from its database, not from the dicts
returned by ``pipes()``. OWUI prefixes every pipe model ID with
``{function_id}.`` (e.g. ``openrouter_pipe.openai/gpt-4o``) and the
frontend requests icons using that prefixed ID.
Called both on cache miss and on subsequent cache hits (until all
models are confirmed synced). The cache-hit path is needed because
OWUI registers models *after* ``pipes()`` returns, potentially
overwriting any early insert with its own default icon; the second
call finds the models already in DB and updates them correctly.
User-set custom icons (any URL that is not a ``data:`` URL and does not
start with ``https://openrouter.ai/images/models/``) are preserved.
This is a best-effort operation — failures are silently logged.
"""
try:
from open_webui.models.models import (
ModelForm,
ModelMeta,
ModelParams,
Models,
)
except ImportError:
# Running outside Open WebUI (e.g. standalone tests) — skip silently
return
# function_id was resolved once in __init__ from type(self).__module__
if not self._function_id:
return
function_id = self._function_id