llm-catalog-core 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of llm-catalog-core might be problematic. Click here for more details.
- llm_catalog_core-0.1.0/LICENSE +201 -0
- llm_catalog_core-0.1.0/PKG-INFO +47 -0
- llm_catalog_core-0.1.0/README.md +20 -0
- llm_catalog_core-0.1.0/pyproject.toml +46 -0
- llm_catalog_core-0.1.0/src/llm_catalog/core/__init__.py +56 -0
- llm_catalog_core-0.1.0/src/llm_catalog/core/catalog.py +95 -0
- llm_catalog_core-0.1.0/src/llm_catalog/core/codegen.py +109 -0
- llm_catalog_core-0.1.0/src/llm_catalog/core/config.py +271 -0
- llm_catalog_core-0.1.0/src/llm_catalog/core/errors.py +35 -0
- llm_catalog_core-0.1.0/src/llm_catalog/core/py.typed +0 -0
- llm_catalog_core-0.1.0/src/llm_catalog/core/resolve.py +51 -0
- llm_catalog_core-0.1.0/src/llm_catalog/core/transport.py +187 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Shinsuke Mori
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llm-catalog-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Gateway-agnostic core for llm-catalog: config schema, resolver, GatewayTransport, and LiteLLM codegen. Knows nothing about any runtime adapter.
|
|
5
|
+
Keywords: llm,catalog,gateway,httpx,config
|
|
6
|
+
Author: Shinsuke Mori
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Dist: pydantic>=2.7
|
|
19
|
+
Requires-Dist: pyyaml>=6.0
|
|
20
|
+
Requires-Dist: httpx>=0.27
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Project-URL: Homepage, https://github.com/sincekmori/llm-catalog
|
|
23
|
+
Project-URL: Repository, https://github.com/sincekmori/llm-catalog
|
|
24
|
+
Project-URL: Issues, https://github.com/sincekmori/llm-catalog/issues
|
|
25
|
+
Project-URL: Changelog, https://github.com/sincekmori/llm-catalog/blob/main/packages/llm-catalog-core/CHANGELOG.md
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# llm-catalog-core
|
|
29
|
+
|
|
30
|
+
Gateway-agnostic core for [llm-catalog](https://github.com/sincekmori/llm-catalog).
|
|
31
|
+
It holds the config schema, loader/validation, role resolution, the path-rewriting `GatewayTransport`, and native LiteLLM codegen.
|
|
32
|
+
|
|
33
|
+
This package knows nothing about any runtime adapter, so installing it pulls in neither Pydantic AI nor LiteLLM.
|
|
34
|
+
Use it directly when you only need resolution or codegen.
|
|
35
|
+
Otherwise install one of the adapter distributions (`llm-catalog-pydantic-ai`, `llm-catalog-litellm`), which depend on this.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from llm_catalog.core import Catalog
|
|
39
|
+
|
|
40
|
+
cat = Catalog.from_file("catalog.yaml")
|
|
41
|
+
rm = cat.resolve_role("fast") # -> ResolvedModel (no adapter types)
|
|
42
|
+
print(rm.backend, rm.slug, rm.base_url)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
See the [repository README](https://github.com/sincekmori/llm-catalog) for the full picture, the public/private boundary, and the verification notes.
|
|
46
|
+
|
|
47
|
+
import namespace: `llm_catalog.core`
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# llm-catalog-core
|
|
2
|
+
|
|
3
|
+
Gateway-agnostic core for [llm-catalog](https://github.com/sincekmori/llm-catalog).
|
|
4
|
+
It holds the config schema, loader/validation, role resolution, the path-rewriting `GatewayTransport`, and native LiteLLM codegen.
|
|
5
|
+
|
|
6
|
+
This package knows nothing about any runtime adapter, so installing it pulls in neither Pydantic AI nor LiteLLM.
|
|
7
|
+
Use it directly when you only need resolution or codegen.
|
|
8
|
+
Otherwise install one of the adapter distributions (`llm-catalog-pydantic-ai`, `llm-catalog-litellm`), which depend on this.
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from llm_catalog.core import Catalog
|
|
12
|
+
|
|
13
|
+
cat = Catalog.from_file("catalog.yaml")
|
|
14
|
+
rm = cat.resolve_role("fast") # -> ResolvedModel (no adapter types)
|
|
15
|
+
print(rm.backend, rm.slug, rm.base_url)
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
See the [repository README](https://github.com/sincekmori/llm-catalog) for the full picture, the public/private boundary, and the verification notes.
|
|
19
|
+
|
|
20
|
+
import namespace: `llm_catalog.core`
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "llm-catalog-core"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Gateway-agnostic core for llm-catalog: config schema, resolver, GatewayTransport, and LiteLLM codegen. Knows nothing about any runtime adapter."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "Shinsuke Mori" }]
|
|
10
|
+
keywords = ["llm", "catalog", "gateway", "httpx", "config"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3.10",
|
|
16
|
+
"Programming Language :: Python :: 3.11",
|
|
17
|
+
"Programming Language :: Python :: 3.12",
|
|
18
|
+
"Programming Language :: Python :: 3.13",
|
|
19
|
+
"Programming Language :: Python :: 3.14",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"pydantic>=2.7",
|
|
24
|
+
"pyyaml>=6.0",
|
|
25
|
+
"httpx>=0.27",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/sincekmori/llm-catalog"
|
|
30
|
+
Repository = "https://github.com/sincekmori/llm-catalog"
|
|
31
|
+
Issues = "https://github.com/sincekmori/llm-catalog/issues"
|
|
32
|
+
Changelog = "https://github.com/sincekmori/llm-catalog/blob/main/packages/llm-catalog-core/CHANGELOG.md"
|
|
33
|
+
|
|
34
|
+
[project.scripts]
|
|
35
|
+
llm-catalog-codegen = "llm_catalog.core.codegen:main"
|
|
36
|
+
|
|
37
|
+
[build-system]
|
|
38
|
+
requires = ["uv_build>=0.11,<0.12"]
|
|
39
|
+
build-backend = "uv_build"
|
|
40
|
+
|
|
41
|
+
# PEP 420 namespace: ship only the `llm_catalog/core` subpackage. No
|
|
42
|
+
# llm_catalog/__init__.py is created, so this distribution merges into the shared
|
|
43
|
+
# `llm_catalog` namespace alongside the adapter distributions.
|
|
44
|
+
[tool.uv.build-backend]
|
|
45
|
+
module-name = "llm_catalog.core"
|
|
46
|
+
namespace = true
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Copyright 2026 Shinsuke Mori
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""llm-catalog-core: gateway-agnostic config, resolution, transport, and codegen.
|
|
4
|
+
|
|
5
|
+
This distribution knows nothing about any runtime adapter (Pydantic AI, LiteLLM).
|
|
6
|
+
It loads and validates ``catalog.yaml``, resolves roles/keys to
|
|
7
|
+
:class:`ResolvedModel`, provides the path-rewriting :class:`GatewayTransport`,
|
|
8
|
+
and generates a native LiteLLM config (:func:`to_litellm_config`).
|
|
9
|
+
|
|
10
|
+
``llm_catalog`` is a PEP 420 namespace shared with the adapter distributions;
|
|
11
|
+
this package ships only ``llm_catalog.core``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from .catalog import Catalog
|
|
15
|
+
from .codegen import to_litellm_config
|
|
16
|
+
from .config import (
|
|
17
|
+
Backend,
|
|
18
|
+
CatalogConfig,
|
|
19
|
+
Gateway,
|
|
20
|
+
ModelCapabilities,
|
|
21
|
+
ModelEntry,
|
|
22
|
+
Provider,
|
|
23
|
+
RoleRef,
|
|
24
|
+
load_config,
|
|
25
|
+
parse_config,
|
|
26
|
+
)
|
|
27
|
+
from .errors import (
|
|
28
|
+
ConfigError,
|
|
29
|
+
LLMCatalogError,
|
|
30
|
+
ProviderIdCollisionWarning,
|
|
31
|
+
ResolutionError,
|
|
32
|
+
)
|
|
33
|
+
from .resolve import ResolvedModel
|
|
34
|
+
from .transport import GatewayTransport, GatewayTransportSync, HeaderRewrite
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"Backend",
|
|
38
|
+
"Catalog",
|
|
39
|
+
"CatalogConfig",
|
|
40
|
+
"ConfigError",
|
|
41
|
+
"Gateway",
|
|
42
|
+
"GatewayTransport",
|
|
43
|
+
"GatewayTransportSync",
|
|
44
|
+
"HeaderRewrite",
|
|
45
|
+
"LLMCatalogError",
|
|
46
|
+
"ModelCapabilities",
|
|
47
|
+
"ModelEntry",
|
|
48
|
+
"Provider",
|
|
49
|
+
"ProviderIdCollisionWarning",
|
|
50
|
+
"ResolutionError",
|
|
51
|
+
"ResolvedModel",
|
|
52
|
+
"RoleRef",
|
|
53
|
+
"load_config",
|
|
54
|
+
"parse_config",
|
|
55
|
+
"to_litellm_config",
|
|
56
|
+
]
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Copyright 2026 Shinsuke Mori
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The gateway-agnostic resolution entry point.
|
|
4
|
+
|
|
5
|
+
:class:`Catalog` is the centre of ``llm-catalog-core``. It does **resolution
|
|
6
|
+
only**: role/key -> :class:`ResolvedModel`. It returns no Pydantic AI / LiteLLM
|
|
7
|
+
objects (those live in the adapter distributions), so importing it pulls in
|
|
8
|
+
neither runtime.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .config import CatalogConfig, ModelEntry, Provider, load_config
|
|
14
|
+
from .errors import ResolutionError
|
|
15
|
+
from .resolve import ResolvedModel
|
|
16
|
+
|
|
17
|
+
__all__ = ["Catalog"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Catalog:
|
|
21
|
+
"""Resolves roles and ``provider:model`` keys to :class:`ResolvedModel`."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, config: CatalogConfig) -> None:
|
|
24
|
+
self._config = config
|
|
25
|
+
self._providers: dict[str, Provider] = {p.id: p for p in config.providers}
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def from_file(cls, path: str | Path) -> "Catalog":
|
|
29
|
+
"""Load and validate ``catalog.yaml`` (or .json) and build a catalog."""
|
|
30
|
+
return cls(load_config(path))
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def config(self) -> CatalogConfig:
|
|
34
|
+
"""The validated underlying config."""
|
|
35
|
+
return self._config
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def roles(self) -> list[str]:
|
|
39
|
+
"""The names of every defined role."""
|
|
40
|
+
return list(self._config.roles)
|
|
41
|
+
|
|
42
|
+
def resolve_role(self, role: str) -> ResolvedModel:
|
|
43
|
+
"""Resolve a role name to a :class:`ResolvedModel`."""
|
|
44
|
+
ref = self._config.roles.get(role)
|
|
45
|
+
if ref is None:
|
|
46
|
+
raise ResolutionError(
|
|
47
|
+
f'Unknown role "{role}". Defined roles: {sorted(self._config.roles)}.'
|
|
48
|
+
)
|
|
49
|
+
return self._resolve(ref.provider, ref.model)
|
|
50
|
+
|
|
51
|
+
def resolve_key(self, key: str) -> ResolvedModel:
|
|
52
|
+
"""Resolve a ``"provider:model_id"`` key to a :class:`ResolvedModel`."""
|
|
53
|
+
provider_id, sep, model_id = key.partition(":")
|
|
54
|
+
if not sep:
|
|
55
|
+
raise ResolutionError(
|
|
56
|
+
f'Invalid model key "{key}"; expected "provider:model_id".'
|
|
57
|
+
)
|
|
58
|
+
return self._resolve(provider_id, model_id)
|
|
59
|
+
|
|
60
|
+
def meta_for_role(self, role: str) -> ResolvedModel:
|
|
61
|
+
"""Alias of :meth:`resolve_role`, named for capability/metadata lookups."""
|
|
62
|
+
return self.resolve_role(role)
|
|
63
|
+
|
|
64
|
+
def _resolve(self, provider_id: str, model_id: str) -> ResolvedModel:
|
|
65
|
+
provider = self._providers.get(provider_id)
|
|
66
|
+
if provider is None:
|
|
67
|
+
raise ResolutionError(f'Unknown provider "{provider_id}".')
|
|
68
|
+
|
|
69
|
+
model = _find_model(provider, model_id)
|
|
70
|
+
if model is None:
|
|
71
|
+
raise ResolutionError(
|
|
72
|
+
f'Unknown model "{model_id}" in provider "{provider_id}".'
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
backend = provider.gateway.backends[model.backend]
|
|
76
|
+
# provider defaults first, then model settings win on conflict.
|
|
77
|
+
settings = {**provider.settings, **model.settings}
|
|
78
|
+
|
|
79
|
+
return ResolvedModel(
|
|
80
|
+
provider_id=provider.id,
|
|
81
|
+
model_id=model.id,
|
|
82
|
+
backend=model.backend,
|
|
83
|
+
slug=model.slug or model.id,
|
|
84
|
+
api=model.api,
|
|
85
|
+
base_url=provider.gateway.base_url,
|
|
86
|
+
api_key_env=provider.gateway.api_key_env,
|
|
87
|
+
path_template=backend.path_template,
|
|
88
|
+
action_map=dict(backend.action_map),
|
|
89
|
+
settings=settings,
|
|
90
|
+
capabilities=model.capabilities,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _find_model(provider: Provider, model_id: str) -> ModelEntry | None:
|
|
95
|
+
return next((m for m in provider.models if m.id == model_id), None)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Copyright 2026 Shinsuke Mori
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Generate a native LiteLLM ``config.yaml`` from a ``catalog.yaml`` (route 2a).
|
|
4
|
+
|
|
5
|
+
This is the *lean alternative* to the LiteLLM plugin: it emits a plain LiteLLM
|
|
6
|
+
config that uses LiteLLM's **built-in** providers (``anthropic/...``,
|
|
7
|
+
``openai/...``, ``gemini/...``) plus ``api_base``, with a ``model_group_alias``
|
|
8
|
+
for the roles.
|
|
9
|
+
|
|
10
|
+
It imports neither ``litellm`` nor any adapter — it is pure dict/YAML text — so
|
|
11
|
+
it ships in *core* and runs with only ``llm-catalog-core`` installed.
|
|
12
|
+
|
|
13
|
+
Limitations (documented in the README): because it relies on LiteLLM's built-in
|
|
14
|
+
path construction, it does **not** honour a custom ``pathTemplate`` or native
|
|
15
|
+
grounding. Use the ``llm-catalog-litellm`` plugin when those matter.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import yaml
|
|
24
|
+
|
|
25
|
+
from .config import CatalogConfig, ModelEntry, Provider, load_config
|
|
26
|
+
|
|
27
|
+
__all__ = ["main", "to_litellm_config"]
|
|
28
|
+
|
|
29
|
+
# catalog backend -> LiteLLM built-in provider prefix.
|
|
30
|
+
_BACKEND_TO_LITELLM: dict[str, str] = {
|
|
31
|
+
"anthropic": "anthropic",
|
|
32
|
+
"openai": "openai",
|
|
33
|
+
"google": "gemini",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _litellm_params(provider: Provider, model: ModelEntry) -> dict[str, Any]:
|
|
38
|
+
prefix = _BACKEND_TO_LITELLM[model.backend]
|
|
39
|
+
slug = model.slug or model.id
|
|
40
|
+
|
|
41
|
+
params: dict[str, Any] = {
|
|
42
|
+
"model": f"{prefix}/{slug}",
|
|
43
|
+
"api_base": provider.gateway.base_url,
|
|
44
|
+
# LiteLLM reads "os.environ/NAME" as an env reference — the key value is
|
|
45
|
+
# never written into the generated file.
|
|
46
|
+
"api_key": f"os.environ/{provider.gateway.api_key_env}",
|
|
47
|
+
}
|
|
48
|
+
# Merge provider then model defaults (model wins).
|
|
49
|
+
merged = {**provider.settings, **model.settings}
|
|
50
|
+
params.update(merged)
|
|
51
|
+
return params
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def to_litellm_config(config: CatalogConfig) -> dict[str, Any]:
|
|
55
|
+
"""Build a LiteLLM ``config.yaml`` structure (model_list + role aliases)."""
|
|
56
|
+
model_list: list[dict[str, Any]] = [
|
|
57
|
+
{
|
|
58
|
+
"model_name": f"{provider.id}/{model.id}",
|
|
59
|
+
"litellm_params": _litellm_params(provider, model),
|
|
60
|
+
}
|
|
61
|
+
for provider in config.providers
|
|
62
|
+
for model in provider.models
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
result: dict[str, Any] = {"model_list": model_list}
|
|
66
|
+
|
|
67
|
+
if config.roles:
|
|
68
|
+
result["router_settings"] = {
|
|
69
|
+
"model_group_alias": {
|
|
70
|
+
role: f"{ref.provider}/{ref.model}"
|
|
71
|
+
for role, ref in config.roles.items()
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return result
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def main(argv: list[str] | None = None) -> int:
|
|
78
|
+
"""Generate a LiteLLM config.yaml from a catalog (CLI entry point).
|
|
79
|
+
|
|
80
|
+
Usage: ``python -m llm_catalog.core.codegen catalog.yaml -o out.yaml``.
|
|
81
|
+
"""
|
|
82
|
+
parser = argparse.ArgumentParser(
|
|
83
|
+
prog="llm-catalog-codegen",
|
|
84
|
+
description="Generate a native LiteLLM config.yaml from a catalog.yaml.",
|
|
85
|
+
)
|
|
86
|
+
parser.add_argument("catalog", type=Path, help="path to catalog.yaml / .json")
|
|
87
|
+
parser.add_argument(
|
|
88
|
+
"-o",
|
|
89
|
+
"--output",
|
|
90
|
+
type=Path,
|
|
91
|
+
default=None,
|
|
92
|
+
help="output path (default: stdout)",
|
|
93
|
+
)
|
|
94
|
+
args = parser.parse_args(argv)
|
|
95
|
+
|
|
96
|
+
config = load_config(args.catalog)
|
|
97
|
+
rendered = yaml.safe_dump(
|
|
98
|
+
to_litellm_config(config), sort_keys=False, allow_unicode=True
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
if args.output is None:
|
|
102
|
+
sys.stdout.write(rendered)
|
|
103
|
+
else:
|
|
104
|
+
args.output.write_text(rendered, encoding="utf-8")
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
if __name__ == "__main__": # pragma: no cover
|
|
109
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
# Copyright 2026 Shinsuke Mori
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Declarative ``catalog.yaml`` schema, loader, and validation.
|
|
4
|
+
|
|
5
|
+
This is the single source of truth for providers, the models they serve, and the
|
|
6
|
+
roles an application references. It mirrors the structure of the TypeScript
|
|
7
|
+
``ai-sdk-catalog`` config so the *same* file can drive both ecosystems: the
|
|
8
|
+
camelCase keys (``baseURL``, ``apiKeyEnvVarName``, ``pathTemplate``,
|
|
9
|
+
``actionMap``) are accepted via Pydantic aliases, while ``populate_by_name``
|
|
10
|
+
also lets Python code build models with snake_case names.
|
|
11
|
+
|
|
12
|
+
Unlike the TypeScript schema, this Python schema models **gateway providers
|
|
13
|
+
only** — every provider routes through a gateway and every model names a
|
|
14
|
+
``backend``. Direct/resolver providers are out of scope here.
|
|
15
|
+
|
|
16
|
+
Secrets never live in config: a model carries only ``api_key_env`` (the *name*
|
|
17
|
+
of an environment variable), never the key value itself.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import warnings
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Literal
|
|
24
|
+
|
|
25
|
+
import yaml
|
|
26
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
27
|
+
|
|
28
|
+
from .errors import ConfigError, ProviderIdCollisionWarning
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"Backend",
|
|
32
|
+
"CatalogConfig",
|
|
33
|
+
"Gateway",
|
|
34
|
+
"ModelCapabilities",
|
|
35
|
+
"ModelEntry",
|
|
36
|
+
"Provider",
|
|
37
|
+
"RoleRef",
|
|
38
|
+
"load_config",
|
|
39
|
+
"parse_config",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
# Built-in LiteLLM provider names. A custom provider id that collides with one of
|
|
43
|
+
# these is silently bypassed by LiteLLM's custom_provider_map (upstream issue
|
|
44
|
+
# #23352), so we warn at load time. This list is intentionally conservative — it
|
|
45
|
+
# covers the common built-ins; it does not need to be exhaustive to be useful.
|
|
46
|
+
_LITELLM_BUILTIN_PROVIDERS: frozenset[str] = frozenset(
|
|
47
|
+
{
|
|
48
|
+
"openai",
|
|
49
|
+
"azure",
|
|
50
|
+
"azure_ai",
|
|
51
|
+
"anthropic",
|
|
52
|
+
"bedrock",
|
|
53
|
+
"vertex_ai",
|
|
54
|
+
"vertex_ai_beta",
|
|
55
|
+
"gemini",
|
|
56
|
+
"google",
|
|
57
|
+
"palm",
|
|
58
|
+
"cohere",
|
|
59
|
+
"cohere_chat",
|
|
60
|
+
"mistral",
|
|
61
|
+
"groq",
|
|
62
|
+
"xai",
|
|
63
|
+
"deepseek",
|
|
64
|
+
"perplexity",
|
|
65
|
+
"ollama",
|
|
66
|
+
"ollama_chat",
|
|
67
|
+
"openrouter",
|
|
68
|
+
"fireworks_ai",
|
|
69
|
+
"together_ai",
|
|
70
|
+
"deepinfra",
|
|
71
|
+
"cerebras",
|
|
72
|
+
"replicate",
|
|
73
|
+
"huggingface",
|
|
74
|
+
"nlp_cloud",
|
|
75
|
+
"ai21",
|
|
76
|
+
"voyage",
|
|
77
|
+
"databricks",
|
|
78
|
+
"watsonx",
|
|
79
|
+
"sagemaker",
|
|
80
|
+
"cloudflare",
|
|
81
|
+
"nvidia_nim",
|
|
82
|
+
"sambanova",
|
|
83
|
+
}
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# camelCase aliases must round-trip both ways (read camelCase from YAML, or build
|
|
87
|
+
# from snake_case in code), so every model uses this config.
|
|
88
|
+
_MODEL_CONFIG = ConfigDict(populate_by_name=True, extra="forbid")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class Backend(BaseModel):
|
|
92
|
+
"""How one upstream backend is laid out on the gateway.
|
|
93
|
+
|
|
94
|
+
``path_template`` is the path (relative to the gateway ``base_url``) the
|
|
95
|
+
gateway expects, with ``{slug}`` (the model) and optionally ``{action}`` (the
|
|
96
|
+
operation, google only) placeholders. ``action_map`` renames an operation to
|
|
97
|
+
the gateway's name (e.g. ``streamGenerateContent`` ->
|
|
98
|
+
``customStreamGenerateContent``); operations not listed pass through unchanged.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
model_config = _MODEL_CONFIG
|
|
102
|
+
|
|
103
|
+
path_template: str = Field(alias="pathTemplate")
|
|
104
|
+
action_map: dict[str, str] = Field(default_factory=dict, alias="actionMap")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class ModelCapabilities(BaseModel):
|
|
108
|
+
"""Python-side capability hints, namespaced under ``capabilities:``.
|
|
109
|
+
|
|
110
|
+
These are optional and ignored by the TypeScript side. They tell the adapters
|
|
111
|
+
how to drive a model without hardcoding anything gateway-specific.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
model_config = _MODEL_CONFIG
|
|
115
|
+
|
|
116
|
+
structured_output: Literal["native", "tool", "prompted"] = "native"
|
|
117
|
+
multi_step_tools: bool = True
|
|
118
|
+
grounding: list[str] = Field(default_factory=list)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class ModelEntry(BaseModel):
|
|
122
|
+
"""One model a provider serves, tagged with the backend that handles it."""
|
|
123
|
+
|
|
124
|
+
model_config = _MODEL_CONFIG
|
|
125
|
+
|
|
126
|
+
id: str
|
|
127
|
+
backend: Literal["anthropic", "openai", "google"]
|
|
128
|
+
slug: str | None = None # path segment; defaults to ``id`` when omitted
|
|
129
|
+
api: Literal["chat", "responses"] | None = None # openai backend only
|
|
130
|
+
settings: dict[str, Any] = Field(default_factory=dict)
|
|
131
|
+
capabilities: ModelCapabilities = Field(default_factory=ModelCapabilities)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class Gateway(BaseModel):
|
|
135
|
+
"""Where the gateway lives, which env var holds its key, and its topology."""
|
|
136
|
+
|
|
137
|
+
model_config = _MODEL_CONFIG
|
|
138
|
+
|
|
139
|
+
base_url: str = Field(alias="baseURL")
|
|
140
|
+
api_key_env: str = Field(alias="apiKeyEnvVarName")
|
|
141
|
+
backends: dict[str, Backend]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class Provider(BaseModel):
|
|
145
|
+
"""A gateway provider and the models it serves.
|
|
146
|
+
|
|
147
|
+
``settings`` are provider-level call defaults; each model's own ``settings``
|
|
148
|
+
are merged on top (model wins).
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
model_config = _MODEL_CONFIG
|
|
152
|
+
|
|
153
|
+
id: str
|
|
154
|
+
gateway: Gateway
|
|
155
|
+
settings: dict[str, Any] = Field(default_factory=dict)
|
|
156
|
+
models: list[ModelEntry]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class RoleRef(BaseModel):
|
|
160
|
+
"""A role points at exactly one ``(provider, model)`` pair."""
|
|
161
|
+
|
|
162
|
+
model_config = _MODEL_CONFIG
|
|
163
|
+
|
|
164
|
+
provider: str
|
|
165
|
+
model: str
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class CatalogConfig(BaseModel):
|
|
169
|
+
"""The whole catalog: providers plus the roles an app references."""
|
|
170
|
+
|
|
171
|
+
model_config = _MODEL_CONFIG
|
|
172
|
+
|
|
173
|
+
providers: list[Provider]
|
|
174
|
+
roles: dict[str, RoleRef] = Field(default_factory=dict)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _check_invariants(config: CatalogConfig) -> None:
|
|
178
|
+
"""Cross-field checks that need the whole object.
|
|
179
|
+
|
|
180
|
+
Raises :class:`ConfigError` for hard inconsistencies and emits
|
|
181
|
+
:class:`ProviderIdCollisionWarning` for the soft LiteLLM-collision case.
|
|
182
|
+
"""
|
|
183
|
+
provider_ids: set[str] = set()
|
|
184
|
+
# provider id -> {model id -> ModelEntry}
|
|
185
|
+
index: dict[str, dict[str, ModelEntry]] = {}
|
|
186
|
+
|
|
187
|
+
for provider in config.providers:
|
|
188
|
+
if provider.id in provider_ids:
|
|
189
|
+
raise ConfigError(f'Duplicate provider id "{provider.id}".')
|
|
190
|
+
provider_ids.add(provider.id)
|
|
191
|
+
|
|
192
|
+
if provider.id in _LITELLM_BUILTIN_PROVIDERS:
|
|
193
|
+
warnings.warn(
|
|
194
|
+
f'Provider id "{provider.id}" collides with a built-in LiteLLM '
|
|
195
|
+
"provider name; LiteLLM may silently bypass the custom handler "
|
|
196
|
+
"(issue #23352). Choose a distinct provider id.",
|
|
197
|
+
ProviderIdCollisionWarning,
|
|
198
|
+
stacklevel=3,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
models: dict[str, ModelEntry] = {}
|
|
202
|
+
for model in provider.models:
|
|
203
|
+
if model.id in models:
|
|
204
|
+
raise ConfigError(
|
|
205
|
+
f'Duplicate model id "{model.id}" in provider "{provider.id}".'
|
|
206
|
+
)
|
|
207
|
+
models[model.id] = model
|
|
208
|
+
|
|
209
|
+
if model.backend not in provider.gateway.backends:
|
|
210
|
+
raise ConfigError(
|
|
211
|
+
f'Model "{model.id}" uses backend "{model.backend}", but '
|
|
212
|
+
f'"{provider.id}.gateway.backends.{model.backend}" is not '
|
|
213
|
+
"configured."
|
|
214
|
+
)
|
|
215
|
+
if model.api is not None and model.backend != "openai":
|
|
216
|
+
raise ConfigError(
|
|
217
|
+
f'Model "{model.id}" sets api="{model.api}", which is only '
|
|
218
|
+
f'allowed when backend == "openai" (got "{model.backend}").'
|
|
219
|
+
)
|
|
220
|
+
index[provider.id] = models
|
|
221
|
+
|
|
222
|
+
for role, ref in config.roles.items():
|
|
223
|
+
models = index.get(ref.provider, {})
|
|
224
|
+
if ref.provider not in index:
|
|
225
|
+
raise ConfigError(
|
|
226
|
+
f'Role "{role}" references unknown provider "{ref.provider}".'
|
|
227
|
+
)
|
|
228
|
+
if ref.model not in models:
|
|
229
|
+
raise ConfigError(
|
|
230
|
+
f'Role "{role}" references unknown model "{ref.provider}:{ref.model}".'
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def parse_config(data: dict[str, Any]) -> CatalogConfig:
|
|
235
|
+
"""Validate an already-parsed mapping and return a typed :class:`CatalogConfig`.
|
|
236
|
+
|
|
237
|
+
This is the portable core (no filesystem access): hand it a dict from any
|
|
238
|
+
source — parsed YAML/JSON, a fixture, an API response. Raises
|
|
239
|
+
:class:`ConfigError` on any schema or invariant violation.
|
|
240
|
+
"""
|
|
241
|
+
try:
|
|
242
|
+
config = CatalogConfig.model_validate(data)
|
|
243
|
+
except ValidationError as exc:
|
|
244
|
+
raise ConfigError(str(exc)) from exc
|
|
245
|
+
_check_invariants(config)
|
|
246
|
+
return config
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def load_config(path: str | Path) -> CatalogConfig:
|
|
250
|
+
"""Read ``path`` (.yaml/.yml/.json), validate it, and return the config.
|
|
251
|
+
|
|
252
|
+
The extension selects the parser; YAML is a superset of JSON so ``.json``
|
|
253
|
+
also parses as YAML, but we honour the extension for clarity. Raises
|
|
254
|
+
:class:`ConfigError` (with the file path) on any problem.
|
|
255
|
+
"""
|
|
256
|
+
p = Path(path)
|
|
257
|
+
text = p.read_text(encoding="utf-8")
|
|
258
|
+
try:
|
|
259
|
+
data = json.loads(text) if p.suffix.lower() == ".json" else yaml.safe_load(text)
|
|
260
|
+
except (yaml.YAMLError, json.JSONDecodeError) as exc:
|
|
261
|
+
raise ConfigError(f"{p}: failed to parse: {exc}") from exc
|
|
262
|
+
|
|
263
|
+
if not isinstance(data, dict):
|
|
264
|
+
raise ConfigError(
|
|
265
|
+
f"{p}: expected a mapping at the top level, got {type(data).__name__}."
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
try:
|
|
269
|
+
return parse_config(data)
|
|
270
|
+
except ConfigError as exc:
|
|
271
|
+
raise ConfigError(f"{p}:\n{exc}") from exc
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Copyright 2026 Shinsuke Mori
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Error and warning types raised by llm-catalog-core.
|
|
4
|
+
|
|
5
|
+
Everything user-facing inherits from :class:`LLMCatalogError` so callers can
|
|
6
|
+
catch the whole family with one ``except``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LLMCatalogError(Exception):
|
|
11
|
+
"""Base class for every error raised by llm-catalog."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ConfigError(LLMCatalogError):
|
|
15
|
+
"""The ``catalog.yaml`` is structurally invalid or internally inconsistent.
|
|
16
|
+
|
|
17
|
+
Raised by :func:`llm_catalog.core.load_config` / ``parse_config`` for schema
|
|
18
|
+
violations (wrapping Pydantic's ``ValidationError``) and for the cross-field
|
|
19
|
+
checks (unknown role target, backend not configured, ``api`` on a non-openai
|
|
20
|
+
backend, ...).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ResolutionError(LLMCatalogError):
|
|
25
|
+
"""A role or ``provider:model`` key could not be resolved against the config."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ProviderIdCollisionWarning(UserWarning):
|
|
29
|
+
"""A provider ``id`` collides with a built-in LiteLLM provider name.
|
|
30
|
+
|
|
31
|
+
LiteLLM silently bypasses a ``custom_provider_map`` entry whose name clashes
|
|
32
|
+
with a built-in provider (upstream issue #23352). We surface this as a
|
|
33
|
+
warning at load time so the collision is caught before it manifests as a
|
|
34
|
+
confusing routing bug.
|
|
35
|
+
"""
|
|
File without changes
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Copyright 2026 Shinsuke Mori
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The resolved view of a single model, produced by :class:`Catalog`.
|
|
4
|
+
|
|
5
|
+
A :class:`ResolvedModel` is a flat, adapter-agnostic snapshot of everything
|
|
6
|
+
needed to call one model through its gateway: the addressing (backend, slug,
|
|
7
|
+
api), the gateway endpoint (``base_url`` + path template), the *name* of the env
|
|
8
|
+
var holding the key, the merged call settings, and the capability hints.
|
|
9
|
+
|
|
10
|
+
It deliberately holds no Pydantic AI / LiteLLM types and no secret values — the
|
|
11
|
+
key is read from the environment at call time by whichever adapter uses it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from .config import ModelCapabilities
|
|
19
|
+
|
|
20
|
+
__all__ = ["ResolvedModel"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class ResolvedModel:
|
|
25
|
+
"""Flat, gateway-aware description of one model. Adapter-agnostic."""
|
|
26
|
+
|
|
27
|
+
provider_id: str
|
|
28
|
+
model_id: str
|
|
29
|
+
backend: str
|
|
30
|
+
slug: str
|
|
31
|
+
api: str | None
|
|
32
|
+
base_url: str
|
|
33
|
+
api_key_env: str
|
|
34
|
+
path_template: str
|
|
35
|
+
action_map: dict[str, str] = field(default_factory=dict)
|
|
36
|
+
settings: dict[str, Any] = field(default_factory=dict)
|
|
37
|
+
capabilities: ModelCapabilities = field(default_factory=ModelCapabilities)
|
|
38
|
+
|
|
39
|
+
def api_key(self) -> str:
|
|
40
|
+
"""Read the key value from the environment, lazily and per call.
|
|
41
|
+
|
|
42
|
+
Raises :class:`KeyError` (via ``os.environ``) when the variable is unset,
|
|
43
|
+
which surfaces a clear, actionable message naming the missing var.
|
|
44
|
+
"""
|
|
45
|
+
try:
|
|
46
|
+
return os.environ[self.api_key_env]
|
|
47
|
+
except KeyError as exc:
|
|
48
|
+
raise KeyError(
|
|
49
|
+
f'environment variable "{self.api_key_env}" is not set '
|
|
50
|
+
f'(needed for provider "{self.provider_id}")'
|
|
51
|
+
) from exc
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# Copyright 2026 Shinsuke Mori
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Path-rewriting httpx transport that adapts vendor SDKs to a gateway layout.
|
|
4
|
+
|
|
5
|
+
Each vendor SDK (anthropic / openai / google-genai) builds its own fixed request
|
|
6
|
+
path (``/v1/messages``, ``/chat/completions``, ``/v1beta/models/{m}:{action}``).
|
|
7
|
+
A gateway instead expects a ``path_template`` such as ``anthropic/{slug}``.
|
|
8
|
+
|
|
9
|
+
:class:`GatewayTransport` sits in the vendor SDK's ``httpx`` client and rewrites
|
|
10
|
+
each outgoing request's path to the gateway's, leaving everything else (method,
|
|
11
|
+
headers, body, query string) intact. It lives in *core* so both adapters reuse
|
|
12
|
+
the exact same rewriting.
|
|
13
|
+
|
|
14
|
+
Slug source
|
|
15
|
+
-----------
|
|
16
|
+
The ``{slug}`` placeholder is filled from, in order:
|
|
17
|
+
|
|
18
|
+
* an explicit ``slug`` passed to the transport (what the adapters do — they know
|
|
19
|
+
the resolved model's slug, which may differ from the model id carried in the
|
|
20
|
+
request), or
|
|
21
|
+
* the model identifier extracted from the request itself (body ``model`` for
|
|
22
|
+
fixed-path backends, the URL for google) when no explicit slug is given.
|
|
23
|
+
|
|
24
|
+
Extraction is what keeps the transport generic and is exercised directly by the
|
|
25
|
+
tests; the explicit-slug path is what lets a configured ``slug`` differ from the
|
|
26
|
+
model id sent upstream in the body.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
import re
|
|
31
|
+
from collections.abc import Callable
|
|
32
|
+
|
|
33
|
+
import httpx
|
|
34
|
+
|
|
35
|
+
__all__ = ["GatewayTransport", "GatewayTransportSync", "HeaderRewrite"]
|
|
36
|
+
|
|
37
|
+
HeaderRewrite = Callable[[httpx.Headers], None]
|
|
38
|
+
|
|
39
|
+
# Matches the model id and operation in a google-genai URL path, e.g.
|
|
40
|
+
# "/v1beta/models/gemini-2.5-pro:streamGenerateContent".
|
|
41
|
+
_GOOGLE_PATH = re.compile(r"/models/(?P<model>[^:/]+):(?P<action>[A-Za-z]+)")
|
|
42
|
+
|
|
43
|
+
# Backends whose model lives in the JSON request body (not the URL).
|
|
44
|
+
_BODY_BACKENDS = frozenset({"anthropic", "openai"})
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _extract_slug_action(
|
|
48
|
+
request: httpx.Request, backend: str
|
|
49
|
+
) -> tuple[str | None, str | None]:
|
|
50
|
+
"""Pull ``(slug, action)`` out of a request for the given backend.
|
|
51
|
+
|
|
52
|
+
Returns ``(None, None)`` when nothing can be extracted (the caller then falls
|
|
53
|
+
back to the configured slug, or leaves the request unrewritten).
|
|
54
|
+
"""
|
|
55
|
+
if backend == "google":
|
|
56
|
+
match = _GOOGLE_PATH.search(request.url.path)
|
|
57
|
+
if match is None:
|
|
58
|
+
return None, None
|
|
59
|
+
return match.group("model"), match.group("action")
|
|
60
|
+
|
|
61
|
+
if backend in _BODY_BACKENDS:
|
|
62
|
+
try:
|
|
63
|
+
raw = request.content
|
|
64
|
+
except httpx.RequestNotRead: # streaming body not materialised — uncommon here
|
|
65
|
+
return None, None
|
|
66
|
+
if not raw:
|
|
67
|
+
return None, None
|
|
68
|
+
try:
|
|
69
|
+
body = json.loads(raw)
|
|
70
|
+
except ValueError: # JSONDecodeError and UnicodeDecodeError both subclass it
|
|
71
|
+
return None, None
|
|
72
|
+
model = body.get("model") if isinstance(body, dict) else None
|
|
73
|
+
return (model if isinstance(model, str) and model else None), None
|
|
74
|
+
|
|
75
|
+
return None, None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _build_url(
|
|
79
|
+
request: httpx.Request,
|
|
80
|
+
*,
|
|
81
|
+
base_url: str,
|
|
82
|
+
path_template: str,
|
|
83
|
+
action_map: dict[str, str],
|
|
84
|
+
backend: str,
|
|
85
|
+
slug: str | None,
|
|
86
|
+
) -> httpx.URL | None:
|
|
87
|
+
"""Compute the rewritten gateway URL, or ``None`` to leave the request as-is."""
|
|
88
|
+
extracted_slug, action = _extract_slug_action(request, backend)
|
|
89
|
+
final_slug = slug if slug is not None else extracted_slug
|
|
90
|
+
if final_slug is None:
|
|
91
|
+
# Nothing to substitute — don't touch the request.
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
mapped_action = action_map.get(action, action) if action is not None else ""
|
|
95
|
+
new_path = path_template.format(slug=final_slug, action=mapped_action)
|
|
96
|
+
|
|
97
|
+
base = base_url.rstrip("/")
|
|
98
|
+
path = new_path.lstrip("/")
|
|
99
|
+
# Plain concatenation (not httpx.URL.join) so a gateway base path like
|
|
100
|
+
# ".../base" is preserved rather than treated as a sibling to replace.
|
|
101
|
+
url = httpx.URL(f"{base}/{path}")
|
|
102
|
+
# Re-attach the original query string (e.g. google's ?alt=sse).
|
|
103
|
+
return url.copy_merge_params(request.url.params)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class GatewayTransport(httpx.AsyncBaseTransport):
|
|
107
|
+
"""Async transport that rewrites vendor paths to the gateway's layout."""
|
|
108
|
+
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
inner: httpx.AsyncBaseTransport,
|
|
112
|
+
base_url: str,
|
|
113
|
+
path_template: str,
|
|
114
|
+
backend: str,
|
|
115
|
+
action_map: dict[str, str] | None = None,
|
|
116
|
+
slug: str | None = None,
|
|
117
|
+
header_rewrite: HeaderRewrite | None = None,
|
|
118
|
+
) -> None:
|
|
119
|
+
self.inner = inner
|
|
120
|
+
self.base_url = base_url
|
|
121
|
+
self.path_template = path_template
|
|
122
|
+
self.backend = backend
|
|
123
|
+
self.action_map = action_map or {}
|
|
124
|
+
self.slug = slug
|
|
125
|
+
self.header_rewrite = header_rewrite
|
|
126
|
+
|
|
127
|
+
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
|
128
|
+
"""Rewrite the request path to the gateway layout, then delegate."""
|
|
129
|
+
new_url = _build_url(
|
|
130
|
+
request,
|
|
131
|
+
base_url=self.base_url,
|
|
132
|
+
path_template=self.path_template,
|
|
133
|
+
action_map=self.action_map,
|
|
134
|
+
backend=self.backend,
|
|
135
|
+
slug=self.slug,
|
|
136
|
+
)
|
|
137
|
+
if new_url is not None:
|
|
138
|
+
request.url = new_url
|
|
139
|
+
if self.header_rewrite is not None:
|
|
140
|
+
self.header_rewrite(request.headers)
|
|
141
|
+
return await self.inner.handle_async_request(request)
|
|
142
|
+
|
|
143
|
+
async def aclose(self) -> None:
|
|
144
|
+
"""Close the wrapped inner transport."""
|
|
145
|
+
await self.inner.aclose()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class GatewayTransportSync(httpx.BaseTransport):
|
|
149
|
+
"""Synchronous counterpart of :class:`GatewayTransport`."""
|
|
150
|
+
|
|
151
|
+
def __init__(
|
|
152
|
+
self,
|
|
153
|
+
inner: httpx.BaseTransport,
|
|
154
|
+
base_url: str,
|
|
155
|
+
path_template: str,
|
|
156
|
+
backend: str,
|
|
157
|
+
action_map: dict[str, str] | None = None,
|
|
158
|
+
slug: str | None = None,
|
|
159
|
+
header_rewrite: HeaderRewrite | None = None,
|
|
160
|
+
) -> None:
|
|
161
|
+
self.inner = inner
|
|
162
|
+
self.base_url = base_url
|
|
163
|
+
self.path_template = path_template
|
|
164
|
+
self.backend = backend
|
|
165
|
+
self.action_map = action_map or {}
|
|
166
|
+
self.slug = slug
|
|
167
|
+
self.header_rewrite = header_rewrite
|
|
168
|
+
|
|
169
|
+
def handle_request(self, request: httpx.Request) -> httpx.Response:
|
|
170
|
+
"""Rewrite the request path to the gateway layout, then delegate."""
|
|
171
|
+
new_url = _build_url(
|
|
172
|
+
request,
|
|
173
|
+
base_url=self.base_url,
|
|
174
|
+
path_template=self.path_template,
|
|
175
|
+
action_map=self.action_map,
|
|
176
|
+
backend=self.backend,
|
|
177
|
+
slug=self.slug,
|
|
178
|
+
)
|
|
179
|
+
if new_url is not None:
|
|
180
|
+
request.url = new_url
|
|
181
|
+
if self.header_rewrite is not None:
|
|
182
|
+
self.header_rewrite(request.headers)
|
|
183
|
+
return self.inner.handle_request(request)
|
|
184
|
+
|
|
185
|
+
def close(self) -> None:
|
|
186
|
+
"""Close the wrapped inner transport."""
|
|
187
|
+
self.inner.close()
|