Changesets · Branches · Tags · Compare
| Changeset | 4a63e77b7e97bfd53d99a2bba0fcde0b8b22bc8e4d35bcf6d1891304b4cf92ef |
|---|---|
| Author | Lei Xu <lei@lancedb.com> · 2024-09-22 23:40 -07:00 |
| Committer | GitHub <noreply@github.com> · 2024-09-23 12:10 +05:30 |
| Parents | 97d0192aed53 |
1 file changed
modified python/python/lancedb/embeddings/openai.py +23 −22
| @@ -1,17 +1,9 @@ | ||
| 1 | -# Copyright (c) 2023. LanceDB Developers | |
| 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 | -# http://www.apache.org/licenses/LICENSE-2.0 | |
| 7 | -# | |
| 8 | -# Unless required by applicable law or agreed to in writing, software | |
| 9 | -# distributed under the License is distributed on an "AS IS" BASIS, | |
| 10 | -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 11 | -# See the License for the specific language governing permissions and | |
| 12 | -# limitations under the License. | |
| 1 | +# SPDX-License-Identifier: Apache-2.0 | |
| 2 | +# SPDX-FileCopyrightText: Copyright The LanceDB Authors | |
| 3 | + | |
| 13 | 4 | from functools import cached_property |
| 14 | 5 | from typing import TYPE_CHECKING, List, Optional, Union |
| 6 | +import logging | |
| 15 | 7 | |
| 16 | 8 | from ..util import attempt_import_or_raise |
| 17 | 9 | from .base import TextEmbeddingFunction |
| @@ -89,17 +81,26 @@ | ||
| 89 | 81 | texts: list[str] or np.ndarray (of str) |
| 90 | 82 | The texts to embed |
| 91 | 83 | """ |
| 84 | + openai = attempt_import_or_raise("openai") | |
| 85 | + | |
| 92 | 86 | # TODO retry, rate limit, token limit |
| 93 | - if self.name == "text-embedding-ada-002": | |
| 94 | - rs = self._openai_client.embeddings.create(input=texts, model=self.name) | |
| 95 | - else: | |
| 96 | - kwargs = { | |
| 97 | - "input": texts, | |
| 98 | - "model": self.name, | |
| 99 | - } | |
| 100 | - if self.dim: | |
| 101 | - kwargs["dimensions"] = self.dim | |
| 102 | - rs = self._openai_client.embeddings.create(**kwargs) | |
| 87 | + try: | |
| 88 | + if self.name == "text-embedding-ada-002": | |
| 89 | + rs = self._openai_client.embeddings.create(input=texts, model=self.name) | |
| 90 | + else: | |
| 91 | + kwargs = { | |
| 92 | + "input": texts, | |
| 93 | + "model": self.name, | |
| 94 | + } | |
| 95 | + if self.dim: | |
| 96 | + kwargs["dimensions"] = self.dim | |
| 97 | + rs = self._openai_client.embeddings.create(**kwargs) | |
| 98 | + except openai.BadRequestError: | |
| 99 | + logging.exception("Bad request: %s", texts) | |
| 100 | + return [None] * len(texts) | |
| 101 | + except Exception: | |
| 102 | + logging.exception("OpenAI embeddings error") | |
| 103 | + raise | |
| 103 | 104 | return [v.embedding for v in rs.data] |
| 104 | 105 | |
| 105 | 106 | @cached_property |