Elffuss BraidHub

kikocis/lancedb public

chore: add error handling for openai embedding generation (#1680)

Changeset4a63e77b7e97bfd53d99a2bba0fcde0b8b22bc8e4d35bcf6d1891304b4cf92ef
AuthorLei Xu <lei@lancedb.com> · 2024-09-22 23:40 -07:00
CommitterGitHub <noreply@github.com> · 2024-09-23 12:10 +05:30
Parents97d0192aed53

Browse the files at this changeset

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+
134 from functools import cached_property
145 from typing import TYPE_CHECKING, List, Optional, Union
6+import logging
157
168 from ..util import attempt_import_or_raise
179 from .base import TextEmbeddingFunction
@@ -89,17 +81,26 @@
8981 texts: list[str] or np.ndarray (of str)
9082 The texts to embed
9183 """
84+ openai = attempt_import_or_raise("openai")
85+
9286 # 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
103104 return [v.embedding for v in rs.data]
104105
105106 @cached_property