genkit-openai 0.9.0__py3-none-any.whl
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.
- genkit_openai/__init__.py +60 -0
- genkit_openai/models/__init__.py +54 -0
- genkit_openai/models/audio.py +383 -0
- genkit_openai/models/handler.py +130 -0
- genkit_openai/models/image.py +179 -0
- genkit_openai/models/model.py +418 -0
- genkit_openai/models/model_info.py +220 -0
- genkit_openai/models/utils.py +520 -0
- genkit_openai/openai_plugin.py +515 -0
- genkit_openai/py.typed +0 -0
- genkit_openai/typing.py +342 -0
- genkit_openai-0.9.0.dist-info/METADATA +67 -0
- genkit_openai-0.9.0.dist-info/RECORD +15 -0
- genkit_openai-0.9.0.dist-info/WHEEL +4 -0
- genkit_openai-0.9.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,60 @@
|
|
|
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
|
+
"""OpenAI-compatible model provider for Genkit.
|
|
19
|
+
|
|
20
|
+
This plugin provides integration with OpenAI and any OpenAI-compatible API
|
|
21
|
+
endpoints (such as Azure OpenAI, Together AI, or Anyscale) using the official
|
|
22
|
+
OpenAI Python SDK.
|
|
23
|
+
|
|
24
|
+
Example:
|
|
25
|
+
```python
|
|
26
|
+
from genkit import Genkit
|
|
27
|
+
from genkit_openai import OpenAI
|
|
28
|
+
|
|
29
|
+
# 1. Initialize Genkit with OpenAI plugin
|
|
30
|
+
ai = Genkit(plugins=[OpenAI()])
|
|
31
|
+
|
|
32
|
+
# 2. Generate content using GPT-4o
|
|
33
|
+
res = await ai.generate(
|
|
34
|
+
model='openai/gpt-4o',
|
|
35
|
+
prompt='Suggest 2 catchy names for an AI newsletter.',
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
# 3. Inspect output shapes directly
|
|
39
|
+
print(res.text)
|
|
40
|
+
# => 1. Prompt Daily
|
|
41
|
+
# 2. Neural Notes
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Requirements:
|
|
45
|
+
- Requires the ``OPENAI_API_KEY`` environment variable or explicit ``api_key``.
|
|
46
|
+
|
|
47
|
+
See Also:
|
|
48
|
+
- OpenAI documentation: https://platform.openai.com/docs/
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from .openai_plugin import OpenAI, openai_model
|
|
52
|
+
from .typing import OpenAIConfig
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def package_name() -> str:
|
|
56
|
+
"""The package name for the OpenAI-compatible model provider."""
|
|
57
|
+
return 'genkit_openai'
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
__all__ = ['OpenAI', 'OpenAIConfig', 'openai_model', 'package_name']
|
|
@@ -0,0 +1,54 @@
|
|
|
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
|
+
"""OpenAI Compatible Models for Genkit."""
|
|
19
|
+
|
|
20
|
+
from .audio import (
|
|
21
|
+
SUPPORTED_STT_MODELS,
|
|
22
|
+
SUPPORTED_TTS_MODELS,
|
|
23
|
+
OpenAISTTModel,
|
|
24
|
+
OpenAITTSModel,
|
|
25
|
+
)
|
|
26
|
+
from .handler import OpenAIModelHandler
|
|
27
|
+
from .image import (
|
|
28
|
+
SUPPORTED_IMAGE_MODELS,
|
|
29
|
+
OpenAIImageModel,
|
|
30
|
+
)
|
|
31
|
+
from .model import OpenAIModel
|
|
32
|
+
from .model_info import (
|
|
33
|
+
SUPPORTED_EMBEDDING_MODELS,
|
|
34
|
+
SUPPORTED_OPENAI_COMPAT_MODELS,
|
|
35
|
+
SUPPORTED_OPENAI_MODELS,
|
|
36
|
+
PluginSource,
|
|
37
|
+
get_default_model_info,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
'OpenAIImageModel',
|
|
42
|
+
'OpenAIModel',
|
|
43
|
+
'OpenAIModelHandler',
|
|
44
|
+
'OpenAISTTModel',
|
|
45
|
+
'OpenAITTSModel',
|
|
46
|
+
'PluginSource',
|
|
47
|
+
'SUPPORTED_EMBEDDING_MODELS',
|
|
48
|
+
'SUPPORTED_IMAGE_MODELS',
|
|
49
|
+
'SUPPORTED_OPENAI_COMPAT_MODELS',
|
|
50
|
+
'SUPPORTED_OPENAI_MODELS',
|
|
51
|
+
'SUPPORTED_STT_MODELS',
|
|
52
|
+
'SUPPORTED_TTS_MODELS',
|
|
53
|
+
'get_default_model_info',
|
|
54
|
+
]
|
|
@@ -0,0 +1,383 @@
|
|
|
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
|
+
"""OpenAI-compatible audio models for Genkit (TTS and STT).
|
|
18
|
+
|
|
19
|
+
Provides text-to-speech (TTS) and speech-to-text (STT / transcription)
|
|
20
|
+
capabilities via the OpenAI Audio API.
|
|
21
|
+
|
|
22
|
+
Supported TTS models: tts-1, tts-1-hd, gpt-4o-mini-tts
|
|
23
|
+
Supported STT models: gpt-4o-transcribe, gpt-4o-mini-transcribe, whisper-1
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import base64
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from openai import AsyncOpenAI
|
|
32
|
+
from openai._legacy_response import HttpxBinaryResponseContent
|
|
33
|
+
from openai.types.audio import Transcription
|
|
34
|
+
|
|
35
|
+
from genkit import (
|
|
36
|
+
Media,
|
|
37
|
+
MediaPart,
|
|
38
|
+
Message,
|
|
39
|
+
ModelInfo,
|
|
40
|
+
ModelRequest,
|
|
41
|
+
ModelResponse,
|
|
42
|
+
Part,
|
|
43
|
+
Role,
|
|
44
|
+
Supports,
|
|
45
|
+
TextPart,
|
|
46
|
+
)
|
|
47
|
+
from genkit.model import FinishReason
|
|
48
|
+
from genkit.plugin_api import ActionRunContext
|
|
49
|
+
from genkit_openai.models.utils import (
|
|
50
|
+
_extract_media,
|
|
51
|
+
_extract_text,
|
|
52
|
+
_find_text,
|
|
53
|
+
decode_data_uri_bytes,
|
|
54
|
+
extract_config_dict,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Maps audio response formats to their MIME types.
|
|
58
|
+
RESPONSE_FORMAT_MEDIA_TYPES: dict[str, str] = {
|
|
59
|
+
'mp3': 'audio/mpeg',
|
|
60
|
+
'opus': 'audio/opus',
|
|
61
|
+
'aac': 'audio/aac',
|
|
62
|
+
'flac': 'audio/flac',
|
|
63
|
+
'wav': 'audio/wav',
|
|
64
|
+
'pcm': 'audio/L16',
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
# Maps content types to file extensions for STT input filenames.
|
|
68
|
+
_CONTENT_TYPE_TO_EXTENSION: dict[str, str] = {
|
|
69
|
+
'audio/mpeg': 'mp3',
|
|
70
|
+
'audio/mp3': 'mp3',
|
|
71
|
+
'audio/wav': 'wav',
|
|
72
|
+
'audio/ogg': 'ogg',
|
|
73
|
+
'audio/flac': 'flac',
|
|
74
|
+
'audio/webm': 'webm',
|
|
75
|
+
'audio/mp4': 'mp4',
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
# Supported TTS models with their metadata.
|
|
79
|
+
SUPPORTED_TTS_MODELS: dict[str, ModelInfo] = {
|
|
80
|
+
'tts-1': ModelInfo(
|
|
81
|
+
label='OpenAI - TTS 1',
|
|
82
|
+
supports=Supports(
|
|
83
|
+
media=False,
|
|
84
|
+
output=['media'],
|
|
85
|
+
multiturn=False,
|
|
86
|
+
system_role=False,
|
|
87
|
+
tools=False,
|
|
88
|
+
),
|
|
89
|
+
),
|
|
90
|
+
'tts-1-hd': ModelInfo(
|
|
91
|
+
label='OpenAI - TTS 1 HD',
|
|
92
|
+
supports=Supports(
|
|
93
|
+
media=False,
|
|
94
|
+
output=['media'],
|
|
95
|
+
multiturn=False,
|
|
96
|
+
system_role=False,
|
|
97
|
+
tools=False,
|
|
98
|
+
),
|
|
99
|
+
),
|
|
100
|
+
'gpt-4o-mini-tts': ModelInfo(
|
|
101
|
+
label='OpenAI - GPT-4o Mini TTS',
|
|
102
|
+
supports=Supports(
|
|
103
|
+
media=False,
|
|
104
|
+
output=['media'],
|
|
105
|
+
multiturn=False,
|
|
106
|
+
system_role=False,
|
|
107
|
+
tools=False,
|
|
108
|
+
),
|
|
109
|
+
),
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
# Supported STT / transcription models with their metadata.
|
|
113
|
+
SUPPORTED_STT_MODELS: dict[str, ModelInfo] = {
|
|
114
|
+
'gpt-4o-transcribe': ModelInfo(
|
|
115
|
+
label='OpenAI - GPT-4o Transcribe',
|
|
116
|
+
supports=Supports(
|
|
117
|
+
media=True,
|
|
118
|
+
output=['text', 'json'],
|
|
119
|
+
multiturn=False,
|
|
120
|
+
system_role=False,
|
|
121
|
+
tools=False,
|
|
122
|
+
),
|
|
123
|
+
),
|
|
124
|
+
'gpt-4o-mini-transcribe': ModelInfo(
|
|
125
|
+
label='OpenAI - GPT-4o Mini Transcribe',
|
|
126
|
+
supports=Supports(
|
|
127
|
+
media=True,
|
|
128
|
+
output=['text', 'json'],
|
|
129
|
+
multiturn=False,
|
|
130
|
+
system_role=False,
|
|
131
|
+
tools=False,
|
|
132
|
+
),
|
|
133
|
+
),
|
|
134
|
+
'whisper-1': ModelInfo(
|
|
135
|
+
label='OpenAI - Whisper 1',
|
|
136
|
+
supports=Supports(
|
|
137
|
+
media=True,
|
|
138
|
+
output=['text', 'json'],
|
|
139
|
+
multiturn=False,
|
|
140
|
+
system_role=False,
|
|
141
|
+
tools=False,
|
|
142
|
+
),
|
|
143
|
+
),
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _to_tts_params(
|
|
148
|
+
model_name: str,
|
|
149
|
+
request: ModelRequest,
|
|
150
|
+
) -> dict[str, Any]:
|
|
151
|
+
"""Convert a ModelRequest into OpenAI TTS parameters.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
model_name: The TTS model name (e.g., 'tts-1').
|
|
155
|
+
request: The Genkit generate request.
|
|
156
|
+
|
|
157
|
+
Returns:
|
|
158
|
+
A dictionary of parameters for client.audio.speech.create().
|
|
159
|
+
"""
|
|
160
|
+
text = _extract_text(request)
|
|
161
|
+
config = extract_config_dict(request)
|
|
162
|
+
|
|
163
|
+
params: dict[str, Any] = {
|
|
164
|
+
'model': config.pop('version', None) or model_name,
|
|
165
|
+
'input': text,
|
|
166
|
+
'voice': config.pop('voice', 'alloy'),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
# Optional TTS-specific params.
|
|
170
|
+
for key in ('speed', 'response_format', 'instructions'):
|
|
171
|
+
if key in config:
|
|
172
|
+
params[key] = config.pop(key)
|
|
173
|
+
|
|
174
|
+
# Strip standard GenAI config keys.
|
|
175
|
+
for key in ('temperature', 'max_output_tokens', 'stop_sequences', 'top_k', 'top_p'):
|
|
176
|
+
config.pop(key, None)
|
|
177
|
+
|
|
178
|
+
return {k: v for k, v in params.items() if v is not None}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _to_tts_response(
|
|
182
|
+
response: HttpxBinaryResponseContent,
|
|
183
|
+
response_format: str = 'mp3',
|
|
184
|
+
) -> ModelResponse:
|
|
185
|
+
"""Convert an OpenAI speech response to a Genkit ModelResponse.
|
|
186
|
+
|
|
187
|
+
The response body is read as bytes and encoded as a base64 data URI.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
response: The raw HTTP response from client.audio.speech.create().
|
|
191
|
+
response_format: The audio format used (determines MIME type).
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
A ModelResponse with a media part containing the audio data.
|
|
195
|
+
"""
|
|
196
|
+
# The response from speech.create() is an HttpxBinaryResponseContent
|
|
197
|
+
# which supports .read() to get raw bytes.
|
|
198
|
+
audio_bytes = response.read()
|
|
199
|
+
media_type = RESPONSE_FORMAT_MEDIA_TYPES.get(response_format, 'audio/mpeg')
|
|
200
|
+
b64_data = base64.b64encode(audio_bytes).decode('ascii')
|
|
201
|
+
|
|
202
|
+
return ModelResponse(
|
|
203
|
+
message=Message(
|
|
204
|
+
role=Role.MODEL,
|
|
205
|
+
content=[
|
|
206
|
+
Part(
|
|
207
|
+
root=MediaPart(
|
|
208
|
+
media=Media(
|
|
209
|
+
content_type=media_type,
|
|
210
|
+
url=f'data:{media_type};base64,{b64_data}',
|
|
211
|
+
)
|
|
212
|
+
)
|
|
213
|
+
)
|
|
214
|
+
],
|
|
215
|
+
),
|
|
216
|
+
finish_reason=FinishReason.STOP,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _to_stt_params(
|
|
221
|
+
model_name: str,
|
|
222
|
+
request: ModelRequest,
|
|
223
|
+
) -> dict[str, Any]:
|
|
224
|
+
"""Convert a ModelRequest into OpenAI transcription parameters.
|
|
225
|
+
|
|
226
|
+
Extracts the audio media from the first message and converts it into
|
|
227
|
+
a file-like object suitable for the transcriptions API.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
model_name: The STT model name (e.g., 'whisper-1').
|
|
231
|
+
request: The Genkit generate request.
|
|
232
|
+
|
|
233
|
+
Returns:
|
|
234
|
+
A dictionary of parameters for client.audio.transcriptions.create().
|
|
235
|
+
"""
|
|
236
|
+
media_url, content_type = _extract_media(request)
|
|
237
|
+
config = extract_config_dict(request)
|
|
238
|
+
|
|
239
|
+
audio_bytes = decode_data_uri_bytes(media_url)
|
|
240
|
+
|
|
241
|
+
ext = _CONTENT_TYPE_TO_EXTENSION.get(content_type, 'mp3')
|
|
242
|
+
|
|
243
|
+
params: dict[str, Any] = {
|
|
244
|
+
'model': config.pop('version', None) or model_name,
|
|
245
|
+
'file': (f'input.{ext}', audio_bytes, content_type or 'audio/mpeg'),
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
prompt_text = _find_text(request)
|
|
249
|
+
if prompt_text:
|
|
250
|
+
params['prompt'] = prompt_text
|
|
251
|
+
|
|
252
|
+
# Temperature if provided.
|
|
253
|
+
if temp := config.pop('temperature', None):
|
|
254
|
+
params['temperature'] = temp
|
|
255
|
+
|
|
256
|
+
# Optional STT-specific params.
|
|
257
|
+
for key in ('language', 'timestamp_granularities'):
|
|
258
|
+
if key in config:
|
|
259
|
+
params[key] = config.pop(key)
|
|
260
|
+
|
|
261
|
+
# Determine response format: config override > output format > default.
|
|
262
|
+
response_format = config.pop('response_format', None)
|
|
263
|
+
if not response_format and request.output_format and request.output_format in ('json', 'text'):
|
|
264
|
+
response_format = request.output_format
|
|
265
|
+
params['response_format'] = response_format or 'text'
|
|
266
|
+
|
|
267
|
+
# Strip standard GenAI config keys.
|
|
268
|
+
for key in ('max_output_tokens', 'stop_sequences', 'top_k', 'top_p'):
|
|
269
|
+
config.pop(key, None)
|
|
270
|
+
|
|
271
|
+
return {k: v for k, v in params.items() if v is not None}
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _to_stt_response(result: Transcription | str) -> ModelResponse:
|
|
275
|
+
"""Convert an OpenAI transcription result to a Genkit ModelResponse.
|
|
276
|
+
|
|
277
|
+
Handles the full union of types returned by transcriptions.create().
|
|
278
|
+
All non-str result types (Transcription, TranscriptionVerbose,
|
|
279
|
+
TranscriptionDiarized) have a .text attribute.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
result: The transcription result (either a Transcription-like
|
|
283
|
+
object with a .text attribute, or a plain string).
|
|
284
|
+
|
|
285
|
+
Returns:
|
|
286
|
+
A ModelResponse with a text part containing the transcription.
|
|
287
|
+
"""
|
|
288
|
+
if isinstance(result, str):
|
|
289
|
+
text = result
|
|
290
|
+
elif hasattr(result, 'text'):
|
|
291
|
+
text = result.text
|
|
292
|
+
else:
|
|
293
|
+
text = str(result)
|
|
294
|
+
return ModelResponse(
|
|
295
|
+
message=Message(
|
|
296
|
+
role=Role.MODEL,
|
|
297
|
+
content=[Part(root=TextPart(text=text))],
|
|
298
|
+
),
|
|
299
|
+
finish_reason=FinishReason.STOP,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
class OpenAITTSModel:
|
|
304
|
+
"""Handles text-to-speech via the OpenAI Audio API.
|
|
305
|
+
|
|
306
|
+
Args:
|
|
307
|
+
model_name: The TTS model to use (e.g., 'tts-1').
|
|
308
|
+
client: An async OpenAI client instance.
|
|
309
|
+
"""
|
|
310
|
+
|
|
311
|
+
def __init__(self, model_name: str, client: AsyncOpenAI) -> None:
|
|
312
|
+
"""Initialize the TTS model.
|
|
313
|
+
|
|
314
|
+
Args:
|
|
315
|
+
model_name: The TTS model to use (e.g., 'tts-1').
|
|
316
|
+
client: An async OpenAI client instance.
|
|
317
|
+
"""
|
|
318
|
+
self._model_name = model_name
|
|
319
|
+
self._client = client
|
|
320
|
+
|
|
321
|
+
@property
|
|
322
|
+
def name(self) -> str:
|
|
323
|
+
"""The name of the TTS model."""
|
|
324
|
+
return self._model_name
|
|
325
|
+
|
|
326
|
+
async def generate(self, request: ModelRequest, ctx: ActionRunContext) -> ModelResponse:
|
|
327
|
+
"""Generate speech audio from the request.
|
|
328
|
+
|
|
329
|
+
Args:
|
|
330
|
+
request: The generate request containing the text input.
|
|
331
|
+
ctx: The action run context.
|
|
332
|
+
|
|
333
|
+
Returns:
|
|
334
|
+
A ModelResponse containing audio media parts.
|
|
335
|
+
"""
|
|
336
|
+
params = _to_tts_params(self._model_name, request)
|
|
337
|
+
response_format = params.get('response_format', 'mp3')
|
|
338
|
+
result = await self._client.audio.speech.create(**params)
|
|
339
|
+
return _to_tts_response(result, response_format)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
class OpenAISTTModel:
|
|
343
|
+
"""Handles speech-to-text (transcription) via the OpenAI Audio API.
|
|
344
|
+
|
|
345
|
+
Args:
|
|
346
|
+
model_name: The STT model to use (e.g., 'whisper-1').
|
|
347
|
+
client: An async OpenAI client instance.
|
|
348
|
+
"""
|
|
349
|
+
|
|
350
|
+
def __init__(self, model_name: str, client: AsyncOpenAI) -> None:
|
|
351
|
+
"""Initialize the STT model.
|
|
352
|
+
|
|
353
|
+
Args:
|
|
354
|
+
model_name: The STT model to use (e.g., 'whisper-1').
|
|
355
|
+
client: An async OpenAI client instance.
|
|
356
|
+
"""
|
|
357
|
+
self._model_name = model_name
|
|
358
|
+
self._client = client
|
|
359
|
+
|
|
360
|
+
@property
|
|
361
|
+
def name(self) -> str:
|
|
362
|
+
"""The name of the STT model."""
|
|
363
|
+
return self._model_name
|
|
364
|
+
|
|
365
|
+
async def generate(self, request: ModelRequest, ctx: ActionRunContext) -> ModelResponse:
|
|
366
|
+
"""Transcribe audio from the request.
|
|
367
|
+
|
|
368
|
+
Args:
|
|
369
|
+
request: The generate request containing audio media input.
|
|
370
|
+
ctx: The action run context.
|
|
371
|
+
|
|
372
|
+
Returns:
|
|
373
|
+
A ModelResponse containing the transcribed text.
|
|
374
|
+
"""
|
|
375
|
+
params = _to_stt_params(self._model_name, request)
|
|
376
|
+
result = await self._client.audio.transcriptions.create(
|
|
377
|
+
**params,
|
|
378
|
+
stream=False,
|
|
379
|
+
)
|
|
380
|
+
# transcriptions.create(stream=False) returns a union of
|
|
381
|
+
# Transcription | TranscriptionVerbose | TranscriptionDiarized | str.
|
|
382
|
+
# _to_stt_response handles all of these via isinstance/hasattr checks.
|
|
383
|
+
return _to_stt_response(result) # pyright: ignore[reportArgumentType]
|
|
@@ -0,0 +1,130 @@
|
|
|
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
|
+
"""OpenAI Compatible Model handlers for Genkit."""
|
|
18
|
+
|
|
19
|
+
from collections.abc import Awaitable, Callable
|
|
20
|
+
|
|
21
|
+
from openai import AsyncOpenAI
|
|
22
|
+
|
|
23
|
+
from genkit import (
|
|
24
|
+
ModelInfo,
|
|
25
|
+
ModelRequest,
|
|
26
|
+
ModelResponse,
|
|
27
|
+
)
|
|
28
|
+
from genkit.plugin_api import ActionRunContext
|
|
29
|
+
from genkit_openai.models.model import OpenAIModel
|
|
30
|
+
from genkit_openai.models.model_info import (
|
|
31
|
+
SUPPORTED_OPENAI_COMPAT_MODELS,
|
|
32
|
+
SUPPORTED_OPENAI_MODELS,
|
|
33
|
+
PluginSource,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class OpenAIModelHandler:
|
|
38
|
+
"""Handles OpenAI API interactions for the Genkit plugin."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, model: OpenAIModel, source: PluginSource = PluginSource.OPENAI) -> None:
|
|
41
|
+
"""Initializes the OpenAIModelHandler with a specified model.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
model: An instance of a Model subclass representing the OpenAI model.
|
|
45
|
+
source: Helps distinguish if model handler is called from model-garden plugin.
|
|
46
|
+
Default source is openai.
|
|
47
|
+
"""
|
|
48
|
+
self._model = model
|
|
49
|
+
self._source = source
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def _get_supported_models(source: PluginSource) -> dict[str, ModelInfo]:
|
|
53
|
+
"""Returns the supported models based on the plugin source.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
source: Helps distinguish if model handler is called from model-garden plugin.
|
|
57
|
+
Default source is openai.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
Openai models if source is openai. Merges supported openai models
|
|
61
|
+
with openai-compat models if source is model-garden.
|
|
62
|
+
|
|
63
|
+
"""
|
|
64
|
+
return SUPPORTED_OPENAI_COMPAT_MODELS if source == PluginSource.MODEL_GARDEN else SUPPORTED_OPENAI_MODELS
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def get_model_handler(
|
|
68
|
+
cls, model: str, client: AsyncOpenAI, source: PluginSource = PluginSource.OPENAI
|
|
69
|
+
) -> Callable[[ModelRequest, ActionRunContext], Awaitable[ModelResponse]]:
|
|
70
|
+
"""Factory method to initialize the model handler for the specified OpenAI model.
|
|
71
|
+
|
|
72
|
+
OpenAI models in this context are not instantiated as traditional
|
|
73
|
+
classes but rather as Actions. This method returns a callable that
|
|
74
|
+
serves as an action handler, conforming to the structure of:
|
|
75
|
+
|
|
76
|
+
Action[ModelRequest, ModelResponse, ModelResponseChunk]
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
model: The OpenAI model name.
|
|
80
|
+
client: OpenAI client instance.
|
|
81
|
+
source: Helps distinguish if model handler is called from model-garden plugin.
|
|
82
|
+
Default source is openai.
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
A callable function that acts as an action handler.
|
|
86
|
+
|
|
87
|
+
Raises:
|
|
88
|
+
ValueError: If the specified model is not supported.
|
|
89
|
+
"""
|
|
90
|
+
supported_models = cls._get_supported_models(source)
|
|
91
|
+
|
|
92
|
+
if model not in supported_models:
|
|
93
|
+
raise ValueError(f"Model '{model}' is not supported.")
|
|
94
|
+
|
|
95
|
+
openai_model = OpenAIModel(model, client)
|
|
96
|
+
return cls(openai_model, source).generate
|
|
97
|
+
|
|
98
|
+
def _validate_version(self, version: str) -> None:
|
|
99
|
+
"""Validates whether the specified model version is supported.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
version: The version of the model to be validated.
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
ValueError: If the specified model version is not supported.
|
|
106
|
+
"""
|
|
107
|
+
supported_models = self._get_supported_models(self._source)
|
|
108
|
+
model_info = supported_models[self._model.name]
|
|
109
|
+
if model_info.versions is not None and version not in model_info.versions:
|
|
110
|
+
raise ValueError(f"Model version '{version}' is not supported.")
|
|
111
|
+
|
|
112
|
+
async def generate(self, request: ModelRequest, ctx: ActionRunContext) -> ModelResponse:
|
|
113
|
+
"""Processes the request using OpenAI's chat completion API.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
request: The request containing messages and configurations.
|
|
117
|
+
ctx: The context of the action run.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
A ModelResponse containing the model's response.
|
|
121
|
+
|
|
122
|
+
Raises:
|
|
123
|
+
ValueError: If the specified model version is not supported.
|
|
124
|
+
"""
|
|
125
|
+
request.config = self._model.normalize_config(request.config)
|
|
126
|
+
|
|
127
|
+
if request.config and hasattr(request.config, 'model') and request.config.model:
|
|
128
|
+
self._validate_version(request.config.model)
|
|
129
|
+
|
|
130
|
+
return await self._model.generate(request, ctx)
|