2024-09-27 12:47:04 -04:00
|
|
|
"""
|
|
|
|
Copyright 2024, Zep Software, Inc.
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
"""
|
|
|
|
|
2024-12-02 11:17:37 -05:00
|
|
|
from collections.abc import Iterable
|
2025-03-15 14:15:45 -07:00
|
|
|
from typing import Union
|
2024-09-27 12:47:04 -04:00
|
|
|
|
2025-03-15 14:15:45 -07:00
|
|
|
from openai import AsyncAzureOpenAI, AsyncOpenAI
|
2024-09-27 12:47:04 -04:00
|
|
|
from openai.types import EmbeddingModel
|
|
|
|
|
|
|
|
from .client import EmbedderClient, EmbedderConfig
|
|
|
|
|
|
|
|
DEFAULT_EMBEDDING_MODEL = 'text-embedding-3-small'
|
|
|
|
|
|
|
|
|
|
|
|
class OpenAIEmbedderConfig(EmbedderConfig):
|
|
|
|
embedding_model: EmbeddingModel | str = DEFAULT_EMBEDDING_MODEL
|
|
|
|
api_key: str | None = None
|
|
|
|
base_url: str | None = None
|
|
|
|
|
|
|
|
|
|
|
|
class OpenAIEmbedder(EmbedderClient):
|
|
|
|
"""
|
|
|
|
OpenAI Embedder Client
|
2025-03-15 14:15:45 -07:00
|
|
|
|
|
|
|
This client supports both AsyncOpenAI and AsyncAzureOpenAI clients.
|
2024-09-27 12:47:04 -04:00
|
|
|
"""
|
|
|
|
|
2025-03-15 14:15:45 -07:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
config: OpenAIEmbedderConfig | None = None,
|
|
|
|
client: Union[AsyncOpenAI, AsyncAzureOpenAI, None] = None,
|
|
|
|
):
|
2024-09-27 12:47:04 -04:00
|
|
|
if config is None:
|
|
|
|
config = OpenAIEmbedderConfig()
|
|
|
|
self.config = config
|
2025-03-15 14:15:45 -07:00
|
|
|
|
|
|
|
if client is not None:
|
|
|
|
self.client = client
|
|
|
|
else:
|
|
|
|
self.client = AsyncOpenAI(api_key=config.api_key, base_url=config.base_url)
|
2024-09-27 12:47:04 -04:00
|
|
|
|
|
|
|
async def create(
|
2024-12-02 11:17:37 -05:00
|
|
|
self, input_data: str | list[str] | Iterable[int] | Iterable[Iterable[int]]
|
2024-09-27 12:47:04 -04:00
|
|
|
) -> list[float]:
|
2024-10-28 14:50:16 -04:00
|
|
|
result = await self.client.embeddings.create(
|
|
|
|
input=input_data, model=self.config.embedding_model
|
|
|
|
)
|
2024-09-27 12:47:04 -04:00
|
|
|
return result.data[0].embedding[: self.config.embedding_dim]
|