genkit-vertexai 0.9.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.
@@ -0,0 +1,36 @@
1
+ *$py.class
2
+ *.egg
3
+ *.egg-info/
4
+ *.py[cod]
5
+ *.so
6
+ .DS_Store
7
+ .Python
8
+ .cache/
9
+ .coverage
10
+ .eggs/
11
+ .genkit
12
+ .idea/
13
+ .installed.cfg
14
+ .mypy_cache/
15
+ .pytest_cache/
16
+ .ruff_cache/
17
+ .venv
18
+ ENV/
19
+ __pycache__/
20
+ build/
21
+ develop-eggs/
22
+ dist/
23
+ downloads/
24
+ eggs/
25
+ lib/
26
+ lib64/
27
+ parts/
28
+ sdist/
29
+ site/
30
+ var/
31
+ venv/
32
+ wheels/
33
+ .gemini/artifacts/
34
+
35
+ *.bak
36
+ release-manifest.json
@@ -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 2025 Google LLC
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,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: genkit-vertexai
3
+ Version: 0.9.0
4
+ Summary: Genkit Google Cloud Vertex AI Plugin
5
+ Project-URL: Bug Tracker, https://github.com/genkit-ai/genkit/issues
6
+ Project-URL: Documentation, https://firebase.google.com/docs/genkit
7
+ Project-URL: Homepage, https://github.com/genkit-ai/genkit
8
+ Project-URL: Repository, https://github.com/genkit-ai/genkit/tree/main/py
9
+ Author: Google
10
+ Author-email: Yesudeep Mangalapilly <yesudeep@google.com>, Elisa Shen <mengqin@google.com>, Niraj Nepal <nnepal@google.com>
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: ai,artificial-intelligence,generative-ai,genkit,google,llm,machine-learning,model-garden,vertex-ai
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Environment :: Console
16
+ Classifier: Environment :: Web Environment
17
+ Classifier: Framework :: AsyncIO
18
+ Classifier: Framework :: Pydantic
19
+ Classifier: Framework :: Pydantic :: 2
20
+ Classifier: Intended Audience :: Developers
21
+ Classifier: License :: OSI Approved :: Apache Software License
22
+ Classifier: Operating System :: OS Independent
23
+ Classifier: Programming Language :: Python
24
+ Classifier: Programming Language :: Python :: 3 :: Only
25
+ Classifier: Programming Language :: Python :: 3.10
26
+ Classifier: Programming Language :: Python :: 3.11
27
+ Classifier: Programming Language :: Python :: 3.12
28
+ Classifier: Programming Language :: Python :: 3.13
29
+ Classifier: Programming Language :: Python :: 3.14
30
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
31
+ Classifier: Topic :: Software Development :: Libraries
32
+ Classifier: Typing :: Typed
33
+ Requires-Python: >=3.10
34
+ Requires-Dist: anthropic>=0.40.0
35
+ Requires-Dist: genkit
36
+ Requires-Dist: genkit-anthropic
37
+ Requires-Dist: genkit-openai
38
+ Requires-Dist: google-cloud-aiplatform>=1.77.0
39
+ Requires-Dist: google-cloud-bigquery>=3.11.0
40
+ Requires-Dist: google-cloud-firestore>=2.14.0
41
+ Requires-Dist: google-genai>=1.7.0
42
+ Requires-Dist: strenum>=0.4.15; python_version < '3.11'
43
+ Requires-Dist: structlog>=25.2.0
44
+ Description-Content-Type: text/markdown
45
+
46
+ # Genkit Vertex AI Plugin
47
+
48
+ Integrate Genkit with Google Cloud Vertex AI Model Garden.
49
+
50
+ ## Installation
51
+
52
+ ```bash
53
+ uv add genkit-vertexai
54
+ ```
55
+
56
+ ## Usage
57
+
58
+ ```python
59
+ from genkit import Genkit
60
+ from genkit_vertexai.model_garden import ModelGarden
61
+
62
+ ai = Genkit(
63
+ plugins=[ModelGarden(project_id='my-project', location='us-central1')],
64
+ )
65
+
66
+ res = await ai.generate(
67
+ model='modelgarden/anthropic/claude-3-5-sonnet-v2@20241022',
68
+ prompt='Explain recursion in 10 words.',
69
+ )
70
+ print(res.text)
71
+ ```
72
+
73
+ Requires Google Cloud Application Default Credentials (ADC) or explicit credentials.
@@ -0,0 +1,28 @@
1
+ # Genkit Vertex AI Plugin
2
+
3
+ Integrate Genkit with Google Cloud Vertex AI Model Garden.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ uv add genkit-vertexai
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ from genkit import Genkit
15
+ from genkit_vertexai.model_garden import ModelGarden
16
+
17
+ ai = Genkit(
18
+ plugins=[ModelGarden(project_id='my-project', location='us-central1')],
19
+ )
20
+
21
+ res = await ai.generate(
22
+ model='modelgarden/anthropic/claude-3-5-sonnet-v2@20241022',
23
+ prompt='Explain recursion in 10 words.',
24
+ )
25
+ print(res.text)
26
+ ```
27
+
28
+ Requires Google Cloud Application Default Credentials (ADC) or explicit credentials.
@@ -0,0 +1,87 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ [project]
18
+ authors = [
19
+ { name = "Google" },
20
+ { name = "Yesudeep Mangalapilly", email = "yesudeep@google.com" },
21
+ { name = "Elisa Shen", email = "mengqin@google.com" },
22
+ { name = "Niraj Nepal", email = "nnepal@google.com" },
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 3 - Alpha",
26
+ "Environment :: Console",
27
+ "Environment :: Web Environment",
28
+ "Framework :: AsyncIO",
29
+ "Framework :: Pydantic",
30
+ "Framework :: Pydantic :: 2",
31
+ "Intended Audience :: Developers",
32
+ "Operating System :: OS Independent",
33
+ "Programming Language :: Python",
34
+ "Programming Language :: Python :: 3 :: Only",
35
+ "Programming Language :: Python :: 3.10",
36
+ "Programming Language :: Python :: 3.11",
37
+ "Programming Language :: Python :: 3.12",
38
+ "Programming Language :: Python :: 3.13",
39
+ "Programming Language :: Python :: 3.14",
40
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
41
+ "Topic :: Software Development :: Libraries",
42
+ "Typing :: Typed",
43
+ "License :: OSI Approved :: Apache Software License",
44
+ ]
45
+ dependencies = [
46
+ "genkit",
47
+ "google-genai>=1.7.0",
48
+ "google-cloud-aiplatform>=1.77.0",
49
+ "google-cloud-bigquery>=3.11.0",
50
+ "google-cloud-firestore>=2.14.0",
51
+ "structlog>=25.2.0",
52
+ "strenum>=0.4.15; python_version < '3.11'",
53
+ "anthropic>=0.40.0",
54
+ "genkit-anthropic",
55
+ "genkit-openai",
56
+ ]
57
+ description = "Genkit Google Cloud Vertex AI Plugin"
58
+ keywords = [
59
+ "genkit",
60
+ "ai",
61
+ "llm",
62
+ "machine-learning",
63
+ "artificial-intelligence",
64
+ "generative-ai",
65
+ "google",
66
+ "vertex-ai",
67
+ "model-garden",
68
+ ]
69
+ license = "Apache-2.0"
70
+ name = "genkit-vertexai"
71
+ readme = "README.md"
72
+ requires-python = ">=3.10"
73
+ version = "0.9.0"
74
+
75
+ [project.urls]
76
+ "Bug Tracker" = "https://github.com/genkit-ai/genkit/issues"
77
+ "Documentation" = "https://firebase.google.com/docs/genkit"
78
+ "Homepage" = "https://github.com/genkit-ai/genkit"
79
+ "Repository" = "https://github.com/genkit-ai/genkit/tree/main/py"
80
+
81
+ [build-system]
82
+ build-backend = "hatchling.build"
83
+ requires = ["hatchling"]
84
+
85
+ [tool.hatch.build.targets.wheel]
86
+ only-include = ["src/genkit_vertexai"]
87
+ sources = ["src"]
@@ -0,0 +1,17 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Vertex AI plugin."""
@@ -0,0 +1,68 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Vertex AI Plugin for Genkit.
18
+
19
+ This plugin provides integration with Google Cloud's Vertex AI platform,
20
+ including Model Garden for accessing third-party models and Vector Search
21
+ for RAG applications.
22
+
23
+ Example:
24
+ ```python
25
+ from genkit import Genkit
26
+ from genkit_vertexai.model_garden import ModelGarden
27
+
28
+ # 1. Initialize Genkit with the Model Garden plugin
29
+ ai = Genkit(
30
+ plugins=[ModelGarden(project_id='my-project', location='us-central1')],
31
+ )
32
+
33
+ # 2. Call models under the modelgarden/ namespace (not vertexai/)
34
+ res = await ai.generate(
35
+ model='modelgarden/anthropic/claude-3-5-sonnet-v2@20241022',
36
+ prompt='Explain recursion in 10 words.',
37
+ )
38
+
39
+ # 3. Inspect output shapes directly
40
+ print(res.text)
41
+ # => A function calling itself until reaching a base stopping condition.
42
+ ```
43
+
44
+ Requirements:
45
+ - Requires Google Cloud Application Default Credentials (ADC) or explicit credentials.
46
+
47
+ See Also:
48
+ - Vertex AI Model Garden: https://cloud.google.com/vertex-ai/docs/model-garden
49
+ - Vertex AI Vector Search: https://cloud.google.com/vertex-ai/docs/vector-search
50
+ """
51
+
52
+ from genkit_vertexai.model_garden import ModelGarden, ModelGardenPlugin
53
+
54
+
55
+ def package_name() -> str:
56
+ """Get the package name for the Vertex AI plugin.
57
+
58
+ Returns:
59
+ The fully qualified package name as a string.
60
+ """
61
+ return 'genkit_vertexai'
62
+
63
+
64
+ __all__ = [
65
+ 'ModelGarden',
66
+ 'ModelGardenPlugin',
67
+ 'package_name',
68
+ ]
@@ -0,0 +1,24 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Constants used by the Vertex AI plugin.
18
+
19
+ This module defines constants used throughout the Vertex AI plugin,
20
+ including environment variable names and configuration values.
21
+ """
22
+
23
+ GCLOUD_PROJECT = 'GCLOUD_PROJECT'
24
+ DEFAULT_REGION = 'us-central1'
@@ -0,0 +1,23 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+
18
+ """Model Garden integration for Vertex AI."""
19
+
20
+ from .model_garden import model_garden_name
21
+ from .modelgarden_plugin import ModelGarden, ModelGardenPlugin
22
+
23
+ __all__ = ['ModelGarden', 'ModelGardenPlugin', 'model_garden_name']
@@ -0,0 +1,117 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+
18
+ """Anthropic models."""
19
+
20
+ from collections.abc import Awaitable, Callable
21
+ from typing import cast
22
+
23
+ from anthropic import AsyncAnthropic, AsyncAnthropicVertex
24
+ from genkit_anthropic.config import AnthropicConfig
25
+ from genkit_anthropic.models import AnthropicModel
26
+ from pydantic import ConfigDict
27
+ from pydantic.config import JsonDict
28
+
29
+ from genkit import ModelConfig, ModelInfo, ModelRequest, ModelResponse, Supports
30
+ from genkit.plugin_api import ActionRunContext, loop_local_client
31
+
32
+
33
+ def _vertex_anthropic_config_schema_extra(schema: JsonDict) -> None:
34
+ """Drop options Vertex Model Garden cannot honor from the advertised schema."""
35
+ base_extra = AnthropicConfig.model_config.get('json_schema_extra')
36
+ if callable(base_extra):
37
+ cast(Callable[[JsonDict], None], base_extra)(schema)
38
+ properties = schema.get('properties')
39
+ if isinstance(properties, dict):
40
+ properties.pop('apiKey', None)
41
+
42
+
43
+ class VertexAnthropicConfig(AnthropicConfig):
44
+ """Anthropic config for Vertex Model Garden.
45
+
46
+ ``apiKey`` is omitted because :class:`AsyncAnthropicVertex` authenticates
47
+ with ambient Google credentials and ignores a per-request Anthropic key.
48
+ """
49
+
50
+ model_config = ConfigDict(**{
51
+ **AnthropicConfig.model_config,
52
+ 'json_schema_extra': _vertex_anthropic_config_schema_extra,
53
+ })
54
+
55
+
56
+ class AnthropicModelGarden:
57
+ """Manages integration with Anthropic models on Vertex AI Model Garden."""
58
+
59
+ def __init__(
60
+ self,
61
+ model: str,
62
+ location: str,
63
+ project_id: str,
64
+ ) -> None:
65
+ """Initializes the AnthropicModelGarden instance.
66
+
67
+ Args:
68
+ model: The name of the specific model to be used from Model Garden
69
+ in the way <publisher>/<model> (e.g., 'anthropic/claude-3-5-sonnet-v2@20241022').
70
+ location: The Google Cloud region where the Model Garden service
71
+ is hosted (e.g., 'us-central1').
72
+ project_id: The Google Cloud project ID where the Model Garden
73
+ model is deployed.
74
+ """
75
+ self.name = model
76
+ self._runtime_client = loop_local_client(lambda: AsyncAnthropicVertex(region=location, project_id=project_id))
77
+ # Strip 'anthropic/' prefix for the model passed to Anthropic SDK
78
+ clean_model_name = model.removeprefix('anthropic/')
79
+ self._model_name = clean_model_name
80
+
81
+ def get_handler(self) -> Callable[[ModelRequest, ActionRunContext], Awaitable[ModelResponse]]:
82
+ """Returns the generate handler function for this model.
83
+
84
+ Returns:
85
+ The handler function that can be used as an Action's fn parameter.
86
+ """
87
+
88
+ async def _generate(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse:
89
+ model = AnthropicModel(
90
+ model_name=self._model_name,
91
+ client=cast(AsyncAnthropic, self._runtime_client()),
92
+ )
93
+ return await model.generate(request, ctx)
94
+
95
+ return _generate
96
+
97
+ def get_model_info(self) -> ModelInfo:
98
+ """Returns the model information/metadata for this model.
99
+
100
+ Returns:
101
+ ModelInfo with the model's capabilities.
102
+ """
103
+ return ModelInfo(
104
+ label=f'ModelGarden - {self.name}',
105
+ supports=Supports(
106
+ multiturn=True,
107
+ media=True,
108
+ tools=True,
109
+ system_role=True,
110
+ output=['text', 'json'],
111
+ ),
112
+ )
113
+
114
+ @staticmethod
115
+ def get_config_schema() -> type[ModelConfig]:
116
+ """Returns the config schema for this model type."""
117
+ return VertexAnthropicConfig
@@ -0,0 +1,93 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+
18
+ """Vertex AI client.
19
+
20
+ Provides an async factory for creating AsyncOpenAI clients authenticated
21
+ with Google Cloud credentials. Credential refresh is performed off the
22
+ event loop using ``asyncio.to_thread`` to avoid blocking.
23
+ """
24
+
25
+ import asyncio
26
+
27
+ import google.auth.credentials
28
+ import google.auth.transport.requests
29
+ from google import auth
30
+ from openai import AsyncOpenAI as _AsyncOpenAI
31
+
32
+
33
+ def _refresh_credentials(
34
+ project_id: str | None,
35
+ ) -> tuple[google.auth.credentials.Credentials, str]:
36
+ """Resolve and refresh Google Cloud credentials (blocking I/O).
37
+
38
+ This is intentionally synchronous — it is called via
39
+ ``asyncio.to_thread`` so the event loop is never blocked.
40
+
41
+ Args:
42
+ project_id: Explicit project ID, or None to auto-detect.
43
+
44
+ Returns:
45
+ A (credentials, project_id) tuple with a refreshed token.
46
+ """
47
+ credentials: google.auth.credentials.Credentials
48
+ resolved_project_id: str | None = project_id
49
+ if project_id:
50
+ credentials, _ = auth.default()
51
+ else:
52
+ credentials, resolved_project_id = auth.default()
53
+
54
+ credentials.refresh(google.auth.transport.requests.Request())
55
+
56
+ if not resolved_project_id:
57
+ raise ValueError('Could not determine project_id from credentials or arguments.')
58
+
59
+ return credentials, resolved_project_id
60
+
61
+
62
+ class OpenAIClient:
63
+ """Factory for AsyncOpenAI clients authenticated via Google Cloud.
64
+
65
+ Use the async ``create()`` classmethod instead of direct instantiation
66
+ to avoid blocking the event loop during credential refresh.
67
+ """
68
+
69
+ @classmethod
70
+ async def create(cls, **openai_params: object) -> _AsyncOpenAI:
71
+ """Create an AsyncOpenAI client with refreshed Google credentials.
72
+
73
+ Runs the blocking ``credentials.refresh()`` call in a thread so
74
+ the event loop is never blocked.
75
+
76
+ Args:
77
+ **openai_params: Must include ``location`` and optionally
78
+ ``project_id``.
79
+
80
+ Returns:
81
+ A configured AsyncOpenAI client.
82
+ """
83
+ location = openai_params.get('location')
84
+ project_id_str = str(val) if (val := openai_params.get('project_id')) is not None else None
85
+
86
+ # Offload blocking credential refresh to a thread.
87
+ credentials, resolved_project_id = await asyncio.to_thread(_refresh_credentials, project_id_str)
88
+
89
+ base_url = (
90
+ f'https://{location}-aiplatform.googleapis.com/v1beta1'
91
+ f'/projects/{resolved_project_id}/locations/{location}/endpoints/openapi'
92
+ )
93
+ return _AsyncOpenAI(api_key=credentials.token, base_url=base_url)
@@ -0,0 +1,132 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+
18
+ """Model Garden implementation."""
19
+
20
+ from __future__ import annotations
21
+
22
+ import typing
23
+ from collections.abc import Callable
24
+
25
+ if typing.TYPE_CHECKING:
26
+ from openai import AsyncOpenAI
27
+
28
+ from genkit import ModelRequest, ModelResponse
29
+ from genkit.plugin_api import ActionRunContext
30
+
31
+ from genkit_openai.models import (
32
+ SUPPORTED_OPENAI_COMPAT_MODELS,
33
+ get_default_model_info,
34
+ )
35
+ from genkit_openai.models.model import OpenAIModel
36
+ from genkit_vertexai.model_garden.client import OpenAIClient
37
+
38
+ MODELGARDEN_PLUGIN_NAME = 'modelgarden'
39
+
40
+
41
+ def model_garden_name(name: str) -> str:
42
+ """Create a Model Garden action name.
43
+
44
+ Args:
45
+ name: Base name for the action.
46
+
47
+ Returns:
48
+ The fully qualified Model Garden action name.
49
+ """
50
+ return f'{MODELGARDEN_PLUGIN_NAME}/{name}'
51
+
52
+
53
+ class ModelGardenModel:
54
+ """Manages integration with Google's Model Garden service for Genkit.
55
+
56
+ This class provides a convenient way to interact with models hosted on
57
+ Google's Model Garden, allowing them to be exposed as Genkit models
58
+ with OpenAI compatibility. It handles client initialization, model
59
+ information retrieval, and dynamic model definition within the Genkit
60
+ registry.
61
+ """
62
+
63
+ def __init__(
64
+ self,
65
+ model: str,
66
+ location: str,
67
+ project_id: str,
68
+ ) -> None:
69
+ """Initialize the ModelGardenModel instance.
70
+
71
+ Client creation is deferred to ``create_client()`` (async) so the
72
+ blocking credential refresh never runs on the event loop.
73
+
74
+ Args:
75
+ model: The name of the specific model to be used from Model Garden
76
+ in the way <publisher>/<model> (e.g., 'meta/llama3.2-pro-max').
77
+ location: The Google Cloud region where the Model Garden service
78
+ is hosted (e.g., 'us-central1').
79
+ project_id: The Google Cloud project ID where the Model Garden
80
+ model is deployed.
81
+ """
82
+ self.name = model
83
+ self._openai_params = {'location': location, 'project_id': project_id}
84
+
85
+ async def create_client(self) -> AsyncOpenAI:
86
+ """Create the AsyncOpenAI client with refreshed credentials.
87
+
88
+ This offloads the blocking ``credentials.refresh()`` call to a
89
+ thread via ``OpenAIClient.create()``.
90
+
91
+ Returns:
92
+ The authenticated AsyncOpenAI client.
93
+ """
94
+ return await OpenAIClient.create(**self._openai_params)
95
+
96
+ def get_model_info(self) -> dict[str, object] | None:
97
+ """Retrieve metadata and supported features for the specified model.
98
+
99
+ This method looks up the model's information from a predefined list
100
+ of supported OpenAI-compatible models or provides default information.
101
+
102
+ Returns:
103
+ A dictionary containing the model's 'name' and 'supports' features,
104
+ or None if no information can be found (though typically, a default
105
+ is provided). The 'supports' key contains a dictionary representing
106
+ the model's capabilities (e.g., tools, streaming).
107
+ """
108
+ model_info = SUPPORTED_OPENAI_COMPAT_MODELS.get(self.name, get_default_model_info(self.name))
109
+ supports = model_info.supports
110
+ return {
111
+ 'name': model_info.label,
112
+ 'supports': (
113
+ supports.model_dump(by_alias=False, exclude_none=False)
114
+ if supports and hasattr(supports, 'model_dump')
115
+ else {}
116
+ ),
117
+ }
118
+
119
+ def to_openai_compatible_model(self) -> Callable:
120
+ """Convert the Model Garden model into an OpenAI-compatible Genkit model function.
121
+
122
+ Returns:
123
+ A callable function (specifically, the ``generate`` method of an
124
+ ``OpenAIModel`` instance) that can be used by Genkit.
125
+ """
126
+
127
+ async def _generate(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse:
128
+ client = await self.create_client()
129
+ openai_model = OpenAIModel(self.name, client)
130
+ return await openai_model.generate(request, ctx)
131
+
132
+ return _generate
@@ -0,0 +1,214 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """ModelGarden API Compatible Plugin for Genkit."""
18
+
19
+ import os
20
+ import warnings
21
+ from typing import cast
22
+
23
+ from genkit_openai.models import SUPPORTED_OPENAI_COMPAT_MODELS
24
+ from genkit_openai.typing import OpenAIConfig
25
+ from genkit_vertexai import constants as const
26
+
27
+ from genkit.model import model_action_metadata
28
+ from genkit.plugin_api import Action, ActionKind, ActionMetadata, Plugin, to_json_schema
29
+
30
+ from .model_garden import MODELGARDEN_PLUGIN_NAME, ModelGardenModel, model_garden_name
31
+
32
+
33
+ class ModelGarden(Plugin):
34
+ """Model Garden plugin for Genkit.
35
+
36
+ This plugin provides integration with Google Cloud's Vertex AI platform,
37
+ enabling the use of Vertex AI models and services within the Genkit
38
+ framework. It handles initialization of the Model Garden client and
39
+ registration of model actions.
40
+ """
41
+
42
+ name = MODELGARDEN_PLUGIN_NAME
43
+
44
+ def __init__(
45
+ self,
46
+ project_id: str | None = None,
47
+ location: str | None = None,
48
+ models: list[str] | None = None,
49
+ model_locations: dict[str, str] | None = None,
50
+ ) -> None:
51
+ """Initializes the plugin and sets up its configuration.
52
+
53
+ This constructor prepares the plugin by assigning the Google Cloud project ID,
54
+ location, and a list of models to be used.
55
+
56
+ Args:
57
+ project_id: The Google Cloud project ID to use. If not provided, it attempts
58
+ to load from the `GCLOUD_PROJECT` environment variable.
59
+ location: The Google Cloud region to use for services. If not provided,
60
+ it defaults to `DEFAULT_REGION`.
61
+ models: An optional list of model names to register with the plugin.
62
+ model_locations: An optional dictionary mapping model names to their specific
63
+ Google Cloud regions. This overrides the default `location` for the
64
+ specified models.
65
+ """
66
+ self.project_id = (
67
+ project_id
68
+ if project_id is not None
69
+ else os.getenv(const.GCLOUD_PROJECT) or os.getenv('GOOGLE_CLOUD_PROJECT')
70
+ )
71
+
72
+ self.location = (
73
+ location or os.getenv('GOOGLE_CLOUD_LOCATION') or os.getenv('GOOGLE_CLOUD_REGION') or const.DEFAULT_REGION
74
+ )
75
+
76
+ self.models = models
77
+ self.model_locations = model_locations or {}
78
+
79
+ async def init(self) -> list[Action]:
80
+ """Initialize plugin.
81
+
82
+ Returns:
83
+ Empty list (using lazy loading via resolve).
84
+ """
85
+ return []
86
+
87
+ async def resolve(self, action_type: ActionKind, name: str) -> Action | None:
88
+ """Resolve an action by creating and returning an Action object.
89
+
90
+ Args:
91
+ action_type: The kind of action to resolve.
92
+ name: The namespaced name of the action to resolve.
93
+
94
+ Returns:
95
+ Action object if found, None otherwise.
96
+ """
97
+ if action_type != ActionKind.MODEL:
98
+ return None
99
+
100
+ return await self._create_model_action(name)
101
+
102
+ async def _create_model_action(self, name: str) -> Action:
103
+ """Create an Action object for a Model Garden Vertex AI model.
104
+
105
+ Args:
106
+ name: The namespaced name of the model.
107
+
108
+ Returns:
109
+ Action object for the model.
110
+ """
111
+ # Extract local name (remove plugin prefix)
112
+ clean_name = (
113
+ name.replace(MODELGARDEN_PLUGIN_NAME + '/', '') if name.startswith(MODELGARDEN_PLUGIN_NAME) else name
114
+ )
115
+
116
+ if clean_name.startswith('anthropic/'):
117
+ from .anthropic import AnthropicModelGarden as AnthropicWorker
118
+
119
+ location = self.model_locations.get(clean_name, self.location)
120
+ if not self.project_id:
121
+ raise ValueError('project_id must be provided')
122
+ model_proxy = AnthropicWorker(
123
+ model=clean_name,
124
+ location=location,
125
+ project_id=self.project_id,
126
+ )
127
+
128
+ handler = model_proxy.get_handler()
129
+ model_info = model_proxy.get_model_info()
130
+
131
+ return Action(
132
+ kind=ActionKind.MODEL,
133
+ name=name,
134
+ fn=handler,
135
+ metadata={
136
+ 'model': {
137
+ **model_info.model_dump(),
138
+ 'customOptions': to_json_schema(model_proxy.get_config_schema()),
139
+ },
140
+ },
141
+ )
142
+
143
+ location = self.model_locations.get(clean_name, self.location)
144
+ if not self.project_id:
145
+ raise ValueError('project_id must be provided')
146
+ model_proxy = ModelGardenModel(
147
+ model=clean_name,
148
+ location=location,
149
+ project_id=self.project_id,
150
+ )
151
+
152
+ # Get model info and handler
153
+ model_info = SUPPORTED_OPENAI_COMPAT_MODELS.get(clean_name, {})
154
+ handler = model_proxy.to_openai_compatible_model()
155
+
156
+ return Action(
157
+ kind=ActionKind.MODEL,
158
+ name=name,
159
+ fn=handler,
160
+ metadata={
161
+ 'model': {
162
+ **(
163
+ model_info.model_dump() # type: ignore[union-attr]
164
+ if hasattr(model_info, 'model_dump')
165
+ else cast(dict[str, object], model_info)
166
+ ),
167
+ 'customOptions': to_json_schema(OpenAIConfig),
168
+ },
169
+ },
170
+ )
171
+
172
+ async def list_actions(self) -> list[ActionMetadata]:
173
+ """Generate a list of available actions or models.
174
+
175
+ Returns:
176
+ list[ActionMetadata]: A list of ActionMetadata objects, each with the following attributes:
177
+ - name (str): The name of the action or model.
178
+ - kind (ActionKind): The type or category of the action.
179
+ - info (dict): The metadata dictionary describing the model configuration and properties.
180
+ - config_schema (type): The schema class used for validating the model's configuration.
181
+ """
182
+ actions_list = []
183
+ for model, model_info in SUPPORTED_OPENAI_COMPAT_MODELS.items():
184
+ actions_list.append(
185
+ model_action_metadata(
186
+ name=model_garden_name(model), info=model_info.model_dump(), config_schema=OpenAIConfig
187
+ )
188
+ )
189
+
190
+ return actions_list
191
+
192
+
193
+ class ModelGardenPlugin(ModelGarden):
194
+ """Deprecated alias for :class:`ModelGarden`."""
195
+
196
+ def __init__(
197
+ self,
198
+ project_id: str | None = None,
199
+ location: str | None = None,
200
+ models: list[str] | None = None,
201
+ model_locations: dict[str, str] | None = None,
202
+ ) -> None:
203
+ """Initialize the plugin and emit a deprecation warning."""
204
+ warnings.warn(
205
+ 'ModelGardenPlugin is deprecated; use ModelGarden from genkit_vertexai.model_garden instead.',
206
+ DeprecationWarning,
207
+ stacklevel=2,
208
+ )
209
+ super().__init__(
210
+ project_id=project_id,
211
+ location=location,
212
+ models=models,
213
+ model_locations=model_locations,
214
+ )
File without changes
@@ -0,0 +1,75 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Unittests for VertexAI Model Garden OpenAI Client."""
18
+
19
+ from unittest.mock import MagicMock, patch
20
+
21
+ import pytest
22
+ from genkit_vertexai.model_garden.client import OpenAIClient
23
+
24
+
25
+ @pytest.mark.asyncio
26
+ @patch('google.auth.default')
27
+ @patch('google.auth.transport.requests.Request')
28
+ @patch('genkit_vertexai.model_garden.client._AsyncOpenAI')
29
+ async def test_client_initialization_with_explicit_project_id(
30
+ mock_openai_cls: MagicMock, mock_request_cls: MagicMock, mock_default_auth: MagicMock
31
+ ) -> None:
32
+ """Unittests for init client."""
33
+ mock_location = 'location'
34
+ mock_project_id = 'project_id'
35
+ mock_token = 'token'
36
+
37
+ mock_credentials = MagicMock()
38
+ mock_credentials.token = mock_token
39
+
40
+ mock_default_auth.return_value = (mock_credentials, 'project_id')
41
+
42
+ client_instance = await OpenAIClient.create(location=mock_location, project_id=mock_project_id)
43
+
44
+ mock_default_auth.assert_called_once()
45
+ mock_credentials.refresh.assert_called_once()
46
+ mock_request_cls.assert_called_once()
47
+
48
+ assert client_instance is not None
49
+
50
+
51
+ @pytest.mark.asyncio
52
+ @patch('google.auth.default')
53
+ @patch('google.auth.transport.requests.Request')
54
+ @patch('genkit_vertexai.model_garden.client._AsyncOpenAI')
55
+ async def test_client_initialization_without_explicit_project_id(
56
+ mock_openai_cls: MagicMock, mock_request_cls: MagicMock, mock_default_auth: MagicMock
57
+ ) -> None:
58
+ """Unittests for init client."""
59
+ mock_location = 'location'
60
+ mock_token = 'token'
61
+
62
+ mock_credentials = MagicMock()
63
+ mock_credentials.token = mock_token
64
+
65
+ mock_default_auth.return_value = (mock_credentials, 'project_id')
66
+
67
+ client_instance = await OpenAIClient.create(
68
+ location=mock_location,
69
+ )
70
+
71
+ mock_default_auth.assert_called_once()
72
+ mock_credentials.refresh.assert_called_once()
73
+ mock_request_cls.assert_called_once()
74
+
75
+ assert client_instance is not None
@@ -0,0 +1,114 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Unittests for VertexAI Model Garden Models."""
18
+
19
+ import warnings
20
+ from typing import Any
21
+ from unittest.mock import MagicMock, patch
22
+
23
+ import pytest
24
+ from genkit_anthropic.config import AnthropicConfig
25
+ from genkit_vertexai.model_garden import ModelGarden, ModelGardenPlugin
26
+ from genkit_vertexai.model_garden.anthropic import AnthropicModelGarden
27
+ from genkit_vertexai.model_garden.model_garden import ModelGardenModel
28
+
29
+
30
+ @pytest.fixture
31
+ @patch('genkit_vertexai.model_garden.model_garden.OpenAIClient')
32
+ def model_garden_instance(client: MagicMock) -> ModelGardenModel:
33
+ """Model Garden fixture."""
34
+ return ModelGardenModel(model='test', location='us-central1', project_id='project')
35
+
36
+
37
+ @pytest.mark.parametrize(
38
+ 'model_name, expected',
39
+ [
40
+ (
41
+ 'meta/llama-3.1-405b-instruct-maas',
42
+ {
43
+ 'name': 'ModelGarden - Meta - llama-3.1',
44
+ 'supports': {
45
+ 'constrained': None,
46
+ 'content_type': None,
47
+ 'context': None,
48
+ 'long_running': False,
49
+ 'multiturn': True,
50
+ 'media': False,
51
+ 'tools': True,
52
+ 'system_role': True,
53
+ 'output': [
54
+ 'json_mode',
55
+ 'text',
56
+ ],
57
+ 'tool_choice': None,
58
+ },
59
+ },
60
+ ),
61
+ (
62
+ 'meta/lazaro-model-pro-max',
63
+ {
64
+ 'name': 'ModelGarden - meta/lazaro-model-pro-max',
65
+ 'supports': {
66
+ 'constrained': None,
67
+ 'content_type': None,
68
+ 'context': None,
69
+ 'long_running': None,
70
+ 'multiturn': True,
71
+ 'media': True,
72
+ 'tools': True,
73
+ 'system_role': True,
74
+ 'output': [
75
+ 'json_mode',
76
+ 'text',
77
+ ],
78
+ 'tool_choice': None,
79
+ },
80
+ },
81
+ ),
82
+ ],
83
+ )
84
+ def test_get_model_info(model_name: str, expected: dict[str, Any], model_garden_instance: ModelGardenModel) -> None:
85
+ """Unittest for get_model_info."""
86
+ model_garden_instance.name = model_name
87
+
88
+ result = model_garden_instance.get_model_info()
89
+
90
+ assert result == expected
91
+
92
+
93
+ def test_model_garden_plugin_deprecated_alias() -> None:
94
+ """ModelGardenPlugin warns and delegates to ModelGarden."""
95
+ with warnings.catch_warnings(record=True) as caught:
96
+ warnings.simplefilter('always', DeprecationWarning)
97
+ plugin = ModelGardenPlugin(project_id='my-project', location='us-central1')
98
+
99
+ assert len(caught) == 1
100
+ assert 'ModelGardenPlugin is deprecated' in str(caught[0].message)
101
+ assert isinstance(plugin, ModelGarden)
102
+
103
+
104
+ def test_anthropic_model_garden_uses_anthropic_config_schema() -> None:
105
+ """Anthropic Model Garden advertises the schema enforced by its handler."""
106
+ schema = AnthropicModelGarden.get_config_schema()
107
+ assert issubclass(schema, AnthropicConfig)
108
+
109
+
110
+ def test_anthropic_model_garden_does_not_advertise_api_key() -> None:
111
+ """Vertex authenticates with Google credentials, so apiKey is not offered."""
112
+ properties = AnthropicModelGarden.get_config_schema().model_json_schema()['properties']
113
+ assert 'apiKey' not in properties
114
+ assert 'apiVersion' in properties