2025-02-17 12:20:47 +08:00
|
|
|
from ..utils import verbose_debug, VERBOSE_DEBUG
|
2025-01-25 00:11:00 +01:00
|
|
|
import sys
|
|
|
|
import os
|
2025-02-17 12:20:47 +08:00
|
|
|
import logging
|
2025-01-25 00:11:00 +01:00
|
|
|
|
|
|
|
if sys.version_info < (3, 9):
|
|
|
|
from typing import AsyncIterator
|
|
|
|
else:
|
|
|
|
from collections.abc import AsyncIterator
|
2025-01-25 00:55:07 +01:00
|
|
|
import pipmaster as pm # Pipmaster for dynamic library install
|
2025-01-25 00:11:00 +01:00
|
|
|
|
|
|
|
# install specific modules
|
|
|
|
if not pm.is_installed("openai"):
|
|
|
|
pm.install("openai")
|
|
|
|
|
|
|
|
from openai import (
|
|
|
|
AsyncOpenAI,
|
|
|
|
APIConnectionError,
|
|
|
|
RateLimitError,
|
|
|
|
APITimeoutError,
|
|
|
|
)
|
|
|
|
from tenacity import (
|
|
|
|
retry,
|
|
|
|
stop_after_attempt,
|
|
|
|
wait_exponential,
|
|
|
|
retry_if_exception_type,
|
|
|
|
)
|
|
|
|
from lightrag.utils import (
|
|
|
|
wrap_embedding_func_with_attrs,
|
|
|
|
locate_json_string_body_from_string,
|
|
|
|
safe_unicode_decode,
|
|
|
|
logger,
|
|
|
|
)
|
|
|
|
from lightrag.types import GPTKeywordExtractionFormat
|
2025-02-06 22:55:22 +08:00
|
|
|
from lightrag.api import __api_version__
|
2025-01-25 00:11:00 +01:00
|
|
|
|
|
|
|
import numpy as np
|
2025-02-18 16:55:48 +01:00
|
|
|
from typing import Any, Union
|
2025-01-25 00:11:00 +01:00
|
|
|
|
2025-04-17 05:20:22 +08:00
|
|
|
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
# use the .env that is inside the current folder
|
|
|
|
# allows to use different .env file for each lightrag instance
|
|
|
|
# the OS environment variables take precedence over the .env file
|
|
|
|
load_dotenv(dotenv_path=".env", override=False)
|
|
|
|
|
2025-02-06 23:12:35 +08:00
|
|
|
|
2025-02-06 19:42:57 +08:00
|
|
|
class InvalidResponseError(Exception):
|
|
|
|
"""Custom exception class for triggering retry mechanism"""
|
2025-02-06 23:12:35 +08:00
|
|
|
|
2025-02-06 19:42:57 +08:00
|
|
|
pass
|
2025-01-25 00:55:07 +01:00
|
|
|
|
2025-02-06 23:12:35 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
def create_openai_async_client(
|
|
|
|
api_key: str | None = None,
|
|
|
|
base_url: str | None = None,
|
|
|
|
client_configs: dict[str, Any] = None,
|
|
|
|
) -> AsyncOpenAI:
|
|
|
|
"""Create an AsyncOpenAI client with the given configuration.
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
Args:
|
|
|
|
api_key: OpenAI API key. If None, uses the OPENAI_API_KEY environment variable.
|
|
|
|
base_url: Base URL for the OpenAI API. If None, uses the default OpenAI API URL.
|
|
|
|
client_configs: Additional configuration options for the AsyncOpenAI client.
|
|
|
|
These will override any default configurations but will be overridden by
|
|
|
|
explicit parameters (api_key, base_url).
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
Returns:
|
|
|
|
An AsyncOpenAI client instance.
|
|
|
|
"""
|
|
|
|
if not api_key:
|
|
|
|
api_key = os.environ["OPENAI_API_KEY"]
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
default_headers = {
|
|
|
|
"User-Agent": f"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_8) LightRAG/{__api_version__}",
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
}
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
if client_configs is None:
|
|
|
|
client_configs = {}
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
# Create a merged config dict with precedence: explicit params > client_configs > defaults
|
2025-04-03 14:44:56 +08:00
|
|
|
merged_configs = {
|
|
|
|
**client_configs,
|
|
|
|
"default_headers": default_headers,
|
|
|
|
"api_key": api_key,
|
|
|
|
}
|
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
if base_url is not None:
|
|
|
|
merged_configs["base_url"] = base_url
|
2025-04-10 12:10:35 +08:00
|
|
|
else:
|
2025-04-20 14:33:33 +08:00
|
|
|
merged_configs["base_url"] = os.environ.get(
|
|
|
|
"OPENAI_API_BASE", "https://api.openai.com/v1"
|
|
|
|
)
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
return AsyncOpenAI(**merged_configs)
|
|
|
|
|
|
|
|
|
2025-01-25 00:11:00 +01:00
|
|
|
@retry(
|
|
|
|
stop=stop_after_attempt(3),
|
|
|
|
wait=wait_exponential(multiplier=1, min=4, max=10),
|
2025-04-29 17:43:27 +08:00
|
|
|
retry=(
|
2025-04-29 17:52:07 +08:00
|
|
|
retry_if_exception_type(RateLimitError)
|
|
|
|
| retry_if_exception_type(APIConnectionError)
|
|
|
|
| retry_if_exception_type(APITimeoutError)
|
|
|
|
| retry_if_exception_type(InvalidResponseError)
|
2025-01-25 00:11:00 +01:00
|
|
|
),
|
|
|
|
)
|
|
|
|
async def openai_complete_if_cache(
|
2025-02-18 16:55:48 +01:00
|
|
|
model: str,
|
|
|
|
prompt: str,
|
|
|
|
system_prompt: str | None = None,
|
|
|
|
history_messages: list[dict[str, Any]] | None = None,
|
|
|
|
base_url: str | None = None,
|
|
|
|
api_key: str | None = None,
|
2025-03-28 01:25:15 +08:00
|
|
|
token_tracker: Any | None = None,
|
2025-02-18 16:55:48 +01:00
|
|
|
**kwargs: Any,
|
2025-01-25 00:11:00 +01:00
|
|
|
) -> str:
|
2025-03-27 15:39:39 -07:00
|
|
|
"""Complete a prompt using OpenAI's API with caching support.
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
Args:
|
|
|
|
model: The OpenAI model to use.
|
|
|
|
prompt: The prompt to complete.
|
|
|
|
system_prompt: Optional system prompt to include.
|
|
|
|
history_messages: Optional list of previous messages in the conversation.
|
|
|
|
base_url: Optional base URL for the OpenAI API.
|
|
|
|
api_key: Optional OpenAI API key. If None, uses the OPENAI_API_KEY environment variable.
|
|
|
|
**kwargs: Additional keyword arguments to pass to the OpenAI API.
|
|
|
|
Special kwargs:
|
|
|
|
- openai_client_configs: Dict of configuration options for the AsyncOpenAI client.
|
|
|
|
These will be passed to the client constructor but will be overridden by
|
|
|
|
explicit parameters (api_key, base_url).
|
|
|
|
- hashing_kv: Will be removed from kwargs before passing to OpenAI.
|
|
|
|
- keyword_extraction: Will be removed from kwargs before passing to OpenAI.
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
Returns:
|
|
|
|
The completed text or an async iterator of text chunks if streaming.
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
Raises:
|
|
|
|
InvalidResponseError: If the response from OpenAI is invalid or empty.
|
|
|
|
APIConnectionError: If there is a connection error with the OpenAI API.
|
|
|
|
RateLimitError: If the OpenAI API rate limit is exceeded.
|
|
|
|
APITimeoutError: If the OpenAI API request times out.
|
|
|
|
"""
|
2025-02-06 14:46:07 +08:00
|
|
|
if history_messages is None:
|
|
|
|
history_messages = []
|
2025-02-17 12:20:47 +08:00
|
|
|
|
|
|
|
# Set openai logger level to INFO when VERBOSE_DEBUG is off
|
|
|
|
if not VERBOSE_DEBUG and logger.level == logging.DEBUG:
|
|
|
|
logging.getLogger("openai").setLevel(logging.INFO)
|
2025-02-17 12:34:54 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
# Extract client configuration options
|
|
|
|
client_configs = kwargs.pop("openai_client_configs", {})
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
# Create the OpenAI client
|
|
|
|
openai_async_client = create_openai_async_client(
|
2025-04-03 14:44:56 +08:00
|
|
|
api_key=api_key, base_url=base_url, client_configs=client_configs
|
2025-01-25 00:11:00 +01:00
|
|
|
)
|
2025-03-27 15:39:39 -07:00
|
|
|
|
|
|
|
# Remove special kwargs that shouldn't be passed to OpenAI
|
2025-01-25 00:11:00 +01:00
|
|
|
kwargs.pop("hashing_kv", None)
|
|
|
|
kwargs.pop("keyword_extraction", None)
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
# Prepare messages
|
2025-02-18 16:55:48 +01:00
|
|
|
messages: list[dict[str, Any]] = []
|
2025-01-25 00:11:00 +01:00
|
|
|
if system_prompt:
|
|
|
|
messages.append({"role": "system", "content": system_prompt})
|
|
|
|
messages.extend(history_messages)
|
|
|
|
messages.append({"role": "user", "content": prompt})
|
|
|
|
|
2025-03-28 21:33:59 +08:00
|
|
|
logger.debug("===== Entering func of LLM =====")
|
2025-02-06 19:42:57 +08:00
|
|
|
logger.debug(f"Model: {model} Base URL: {base_url}")
|
|
|
|
logger.debug(f"Additional kwargs: {kwargs}")
|
2025-03-28 21:33:59 +08:00
|
|
|
logger.debug(f"Num of history messages: {len(history_messages)}")
|
2025-02-17 01:38:18 +08:00
|
|
|
verbose_debug(f"System prompt: {system_prompt}")
|
2025-03-28 21:33:59 +08:00
|
|
|
verbose_debug(f"Query: {prompt}")
|
|
|
|
logger.debug("===== Sending Query to LLM =====")
|
2025-02-06 19:42:57 +08:00
|
|
|
|
2025-02-17 12:34:54 +08:00
|
|
|
try:
|
2025-05-09 15:54:54 +08:00
|
|
|
# Don't use async with context manager, use client directly
|
|
|
|
if "response_format" in kwargs:
|
|
|
|
response = await openai_async_client.beta.chat.completions.parse(
|
|
|
|
model=model, messages=messages, **kwargs
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
response = await openai_async_client.chat.completions.create(
|
|
|
|
model=model, messages=messages, **kwargs
|
|
|
|
)
|
2025-02-06 19:42:57 +08:00
|
|
|
except APIConnectionError as e:
|
2025-02-18 16:55:48 +01:00
|
|
|
logger.error(f"OpenAI API Connection Error: {e}")
|
2025-05-09 15:54:54 +08:00
|
|
|
await openai_async_client.close() # Ensure client is closed
|
2025-02-06 19:42:57 +08:00
|
|
|
raise
|
|
|
|
except RateLimitError as e:
|
2025-02-18 16:55:48 +01:00
|
|
|
logger.error(f"OpenAI API Rate Limit Error: {e}")
|
2025-05-09 15:54:54 +08:00
|
|
|
await openai_async_client.close() # Ensure client is closed
|
2025-02-06 19:42:57 +08:00
|
|
|
raise
|
|
|
|
except APITimeoutError as e:
|
2025-02-18 16:55:48 +01:00
|
|
|
logger.error(f"OpenAI API Timeout Error: {e}")
|
2025-05-09 15:54:54 +08:00
|
|
|
await openai_async_client.close() # Ensure client is closed
|
2025-02-06 19:42:57 +08:00
|
|
|
raise
|
|
|
|
except Exception as e:
|
2025-02-18 16:55:48 +01:00
|
|
|
logger.error(
|
|
|
|
f"OpenAI API Call Failed,\nModel: {model},\nParams: {kwargs}, Got: {e}"
|
|
|
|
)
|
2025-05-09 15:54:54 +08:00
|
|
|
await openai_async_client.close() # Ensure client is closed
|
2025-02-06 19:42:57 +08:00
|
|
|
raise
|
2025-01-25 00:11:00 +01:00
|
|
|
|
|
|
|
if hasattr(response, "__aiter__"):
|
|
|
|
|
|
|
|
async def inner():
|
2025-04-29 17:43:27 +08:00
|
|
|
# Track if we've started iterating
|
|
|
|
iteration_started = False
|
2025-02-05 10:44:48 +08:00
|
|
|
try:
|
2025-04-29 17:43:27 +08:00
|
|
|
iteration_started = True
|
2025-02-05 10:44:48 +08:00
|
|
|
async for chunk in response:
|
2025-04-19 12:57:08 +08:00
|
|
|
# Check if choices exists and is not empty
|
2025-04-20 11:17:51 +08:00
|
|
|
if not hasattr(chunk, "choices") or not chunk.choices:
|
2025-04-19 12:57:08 +08:00
|
|
|
logger.warning(f"Received chunk without choices: {chunk}")
|
|
|
|
continue
|
2025-04-20 11:17:51 +08:00
|
|
|
|
2025-04-19 12:57:08 +08:00
|
|
|
# Check if delta exists and has content
|
2025-04-20 11:17:51 +08:00
|
|
|
if not hasattr(chunk.choices[0], "delta") or not hasattr(
|
|
|
|
chunk.choices[0].delta, "content"
|
|
|
|
):
|
|
|
|
logger.warning(
|
|
|
|
f"Received chunk without delta content: {chunk.choices[0]}"
|
|
|
|
)
|
|
|
|
continue
|
2025-02-05 10:44:48 +08:00
|
|
|
content = chunk.choices[0].delta.content
|
|
|
|
if content is None:
|
|
|
|
continue
|
|
|
|
if r"\u" in content:
|
|
|
|
content = safe_unicode_decode(content.encode("utf-8"))
|
2025-03-17 11:41:55 +08:00
|
|
|
yield content
|
2025-02-05 10:44:48 +08:00
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Error in stream response: {str(e)}")
|
2025-04-29 17:43:27 +08:00
|
|
|
# Try to clean up resources if possible
|
2025-04-29 17:52:07 +08:00
|
|
|
if (
|
|
|
|
iteration_started
|
|
|
|
and hasattr(response, "aclose")
|
|
|
|
and callable(getattr(response, "aclose", None))
|
|
|
|
):
|
2025-04-29 17:43:27 +08:00
|
|
|
try:
|
|
|
|
await response.aclose()
|
|
|
|
logger.debug("Successfully closed stream response after error")
|
|
|
|
except Exception as close_error:
|
2025-04-29 17:52:07 +08:00
|
|
|
logger.warning(
|
|
|
|
f"Failed to close stream response: {close_error}"
|
|
|
|
)
|
2025-05-09 15:54:54 +08:00
|
|
|
# Ensure client is closed in case of exception
|
|
|
|
await openai_async_client.close()
|
2025-02-05 10:44:48 +08:00
|
|
|
raise
|
2025-04-29 17:43:27 +08:00
|
|
|
finally:
|
|
|
|
# Ensure resources are released even if no exception occurs
|
2025-04-29 17:52:07 +08:00
|
|
|
if (
|
|
|
|
iteration_started
|
|
|
|
and hasattr(response, "aclose")
|
|
|
|
and callable(getattr(response, "aclose", None))
|
|
|
|
):
|
2025-04-29 17:43:27 +08:00
|
|
|
try:
|
|
|
|
await response.aclose()
|
|
|
|
logger.debug("Successfully closed stream response")
|
|
|
|
except Exception as close_error:
|
2025-04-29 17:52:07 +08:00
|
|
|
logger.warning(
|
|
|
|
f"Failed to close stream response in finally block: {close_error}"
|
|
|
|
)
|
2025-05-12 17:37:28 +08:00
|
|
|
|
|
|
|
# This prevents resource leaks since the caller doesn't handle closing
|
|
|
|
try:
|
|
|
|
await openai_async_client.close()
|
|
|
|
logger.debug(
|
|
|
|
"Successfully closed OpenAI client for streaming response"
|
|
|
|
)
|
|
|
|
except Exception as client_close_error:
|
|
|
|
logger.warning(
|
|
|
|
f"Failed to close OpenAI client in streaming finally block: {client_close_error}"
|
|
|
|
)
|
2025-01-25 00:11:00 +01:00
|
|
|
|
2025-03-17 11:41:55 +08:00
|
|
|
return inner()
|
2025-02-06 19:42:57 +08:00
|
|
|
|
2025-01-25 00:11:00 +01:00
|
|
|
else:
|
2025-05-09 15:54:54 +08:00
|
|
|
try:
|
|
|
|
if (
|
|
|
|
not response
|
|
|
|
or not response.choices
|
|
|
|
or not hasattr(response.choices[0], "message")
|
|
|
|
or not hasattr(response.choices[0].message, "content")
|
|
|
|
):
|
|
|
|
logger.error("Invalid response from OpenAI API")
|
|
|
|
await openai_async_client.close() # Ensure client is closed
|
|
|
|
raise InvalidResponseError("Invalid response from OpenAI API")
|
|
|
|
|
|
|
|
content = response.choices[0].message.content
|
|
|
|
|
|
|
|
if not content or content.strip() == "":
|
|
|
|
logger.error("Received empty content from OpenAI API")
|
|
|
|
await openai_async_client.close() # Ensure client is closed
|
|
|
|
raise InvalidResponseError("Received empty content from OpenAI API")
|
|
|
|
|
|
|
|
if r"\u" in content:
|
|
|
|
content = safe_unicode_decode(content.encode("utf-8"))
|
|
|
|
|
|
|
|
if token_tracker and hasattr(response, "usage"):
|
|
|
|
token_counts = {
|
|
|
|
"prompt_tokens": getattr(response.usage, "prompt_tokens", 0),
|
|
|
|
"completion_tokens": getattr(
|
|
|
|
response.usage, "completion_tokens", 0
|
|
|
|
),
|
|
|
|
"total_tokens": getattr(response.usage, "total_tokens", 0),
|
|
|
|
}
|
|
|
|
token_tracker.add_usage(token_counts)
|
|
|
|
|
|
|
|
logger.debug(f"Response content len: {len(content)}")
|
|
|
|
verbose_debug(f"Response: {response}")
|
|
|
|
|
|
|
|
return content
|
|
|
|
finally:
|
|
|
|
# Ensure client is closed in all cases for non-streaming responses
|
|
|
|
await openai_async_client.close()
|
2025-01-25 00:11:00 +01:00
|
|
|
|
|
|
|
|
|
|
|
async def openai_complete(
|
2025-02-06 16:24:02 +08:00
|
|
|
prompt,
|
|
|
|
system_prompt=None,
|
|
|
|
history_messages=None,
|
|
|
|
keyword_extraction=False,
|
|
|
|
**kwargs,
|
2025-01-25 00:11:00 +01:00
|
|
|
) -> Union[str, AsyncIterator[str]]:
|
2025-02-06 14:46:07 +08:00
|
|
|
if history_messages is None:
|
|
|
|
history_messages = []
|
2025-01-25 00:11:00 +01:00
|
|
|
keyword_extraction = kwargs.pop("keyword_extraction", None)
|
|
|
|
if keyword_extraction:
|
|
|
|
kwargs["response_format"] = "json"
|
|
|
|
model_name = kwargs["hashing_kv"].global_config["llm_model_name"]
|
|
|
|
return await openai_complete_if_cache(
|
|
|
|
model_name,
|
|
|
|
prompt,
|
|
|
|
system_prompt=system_prompt,
|
|
|
|
history_messages=history_messages,
|
|
|
|
**kwargs,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
async def gpt_4o_complete(
|
2025-02-06 16:24:02 +08:00
|
|
|
prompt,
|
|
|
|
system_prompt=None,
|
|
|
|
history_messages=None,
|
|
|
|
keyword_extraction=False,
|
|
|
|
**kwargs,
|
2025-01-25 00:11:00 +01:00
|
|
|
) -> str:
|
2025-02-06 14:46:07 +08:00
|
|
|
if history_messages is None:
|
|
|
|
history_messages = []
|
2025-01-25 00:11:00 +01:00
|
|
|
keyword_extraction = kwargs.pop("keyword_extraction", None)
|
|
|
|
if keyword_extraction:
|
|
|
|
kwargs["response_format"] = GPTKeywordExtractionFormat
|
|
|
|
return await openai_complete_if_cache(
|
|
|
|
"gpt-4o",
|
|
|
|
prompt,
|
|
|
|
system_prompt=system_prompt,
|
|
|
|
history_messages=history_messages,
|
|
|
|
**kwargs,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
async def gpt_4o_mini_complete(
|
2025-02-06 16:24:02 +08:00
|
|
|
prompt,
|
|
|
|
system_prompt=None,
|
|
|
|
history_messages=None,
|
|
|
|
keyword_extraction=False,
|
|
|
|
**kwargs,
|
2025-01-25 00:11:00 +01:00
|
|
|
) -> str:
|
2025-02-06 14:46:07 +08:00
|
|
|
if history_messages is None:
|
|
|
|
history_messages = []
|
2025-01-25 00:11:00 +01:00
|
|
|
keyword_extraction = kwargs.pop("keyword_extraction", None)
|
|
|
|
if keyword_extraction:
|
|
|
|
kwargs["response_format"] = GPTKeywordExtractionFormat
|
|
|
|
return await openai_complete_if_cache(
|
|
|
|
"gpt-4o-mini",
|
|
|
|
prompt,
|
|
|
|
system_prompt=system_prompt,
|
|
|
|
history_messages=history_messages,
|
|
|
|
**kwargs,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
async def nvidia_openai_complete(
|
2025-02-06 16:24:02 +08:00
|
|
|
prompt,
|
|
|
|
system_prompt=None,
|
|
|
|
history_messages=None,
|
|
|
|
keyword_extraction=False,
|
|
|
|
**kwargs,
|
2025-01-25 00:11:00 +01:00
|
|
|
) -> str:
|
2025-02-06 14:46:07 +08:00
|
|
|
if history_messages is None:
|
|
|
|
history_messages = []
|
2025-01-25 00:11:00 +01:00
|
|
|
keyword_extraction = kwargs.pop("keyword_extraction", None)
|
|
|
|
result = await openai_complete_if_cache(
|
|
|
|
"nvidia/llama-3.1-nemotron-70b-instruct", # context length 128k
|
|
|
|
prompt,
|
|
|
|
system_prompt=system_prompt,
|
|
|
|
history_messages=history_messages,
|
|
|
|
base_url="https://integrate.api.nvidia.com/v1",
|
|
|
|
**kwargs,
|
|
|
|
)
|
|
|
|
if keyword_extraction: # TODO: use JSON API
|
|
|
|
return locate_json_string_body_from_string(result)
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
@wrap_embedding_func_with_attrs(embedding_dim=1536, max_token_size=8192)
|
|
|
|
@retry(
|
|
|
|
stop=stop_after_attempt(3),
|
|
|
|
wait=wait_exponential(multiplier=1, min=4, max=60),
|
2025-04-29 17:43:27 +08:00
|
|
|
retry=(
|
2025-04-29 17:52:07 +08:00
|
|
|
retry_if_exception_type(RateLimitError)
|
|
|
|
| retry_if_exception_type(APIConnectionError)
|
|
|
|
| retry_if_exception_type(APITimeoutError)
|
2025-01-25 00:11:00 +01:00
|
|
|
),
|
|
|
|
)
|
|
|
|
async def openai_embed(
|
|
|
|
texts: list[str],
|
|
|
|
model: str = "text-embedding-3-small",
|
|
|
|
base_url: str = None,
|
|
|
|
api_key: str = None,
|
2025-03-27 15:39:39 -07:00
|
|
|
client_configs: dict[str, Any] = None,
|
2025-01-25 00:11:00 +01:00
|
|
|
) -> np.ndarray:
|
2025-03-27 15:39:39 -07:00
|
|
|
"""Generate embeddings for a list of texts using OpenAI's API.
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
Args:
|
|
|
|
texts: List of texts to embed.
|
|
|
|
model: The OpenAI embedding model to use.
|
|
|
|
base_url: Optional base URL for the OpenAI API.
|
|
|
|
api_key: Optional OpenAI API key. If None, uses the OPENAI_API_KEY environment variable.
|
|
|
|
client_configs: Additional configuration options for the AsyncOpenAI client.
|
|
|
|
These will override any default configurations but will be overridden by
|
|
|
|
explicit parameters (api_key, base_url).
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
Returns:
|
|
|
|
A numpy array of embeddings, one per input text.
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-03-27 15:39:39 -07:00
|
|
|
Raises:
|
|
|
|
APIConnectionError: If there is a connection error with the OpenAI API.
|
|
|
|
RateLimitError: If the OpenAI API rate limit is exceeded.
|
|
|
|
APITimeoutError: If the OpenAI API request times out.
|
|
|
|
"""
|
|
|
|
# Create the OpenAI client
|
|
|
|
openai_async_client = create_openai_async_client(
|
2025-04-03 14:44:56 +08:00
|
|
|
api_key=api_key, base_url=base_url, client_configs=client_configs
|
2025-01-25 00:11:00 +01:00
|
|
|
)
|
2025-04-03 14:44:56 +08:00
|
|
|
|
2025-05-08 11:42:53 +10:00
|
|
|
async with openai_async_client:
|
|
|
|
response = await openai_async_client.embeddings.create(
|
|
|
|
model=model, input=texts, encoding_format="float"
|
|
|
|
)
|
|
|
|
return np.array([dp.embedding for dp in response.data])
|