openai.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. from ..utils import verbose_debug, VERBOSE_DEBUG
  2. import os
  3. import logging
  4. import warnings
  5. from collections.abc import AsyncIterator
  6. import pipmaster as pm
  7. import tiktoken
  8. # install specific modules
  9. if not pm.is_installed("openai"):
  10. pm.install("openai")
  11. from openai import (
  12. APIConnectionError,
  13. RateLimitError,
  14. APITimeoutError,
  15. InternalServerError,
  16. BadRequestError,
  17. )
  18. from tenacity import (
  19. retry,
  20. stop_after_attempt,
  21. wait_exponential,
  22. retry_if_exception_type,
  23. )
  24. from lightrag.utils import (
  25. wrap_embedding_func_with_attrs,
  26. safe_unicode_decode,
  27. logger,
  28. )
  29. from lightrag.api import __api_version__
  30. import numpy as np
  31. import base64
  32. from typing import Any, Union
  33. from dotenv import load_dotenv
  34. # Try to import Langfuse for LLM observability (optional)
  35. # Falls back to standard OpenAI client if not available
  36. # Langfuse requires proper configuration to work correctly
  37. LANGFUSE_ENABLED = False
  38. try:
  39. # Check if required Langfuse environment variables are set
  40. langfuse_public_key = os.environ.get("LANGFUSE_PUBLIC_KEY")
  41. langfuse_secret_key = os.environ.get("LANGFUSE_SECRET_KEY")
  42. # Only enable Langfuse if both keys are configured
  43. if langfuse_public_key and langfuse_secret_key:
  44. from langfuse.openai import AsyncOpenAI # type: ignore[import-untyped]
  45. LANGFUSE_ENABLED = True
  46. logger.info("Langfuse observability enabled for OpenAI client")
  47. else:
  48. from openai import AsyncOpenAI
  49. logger.debug(
  50. "Langfuse environment variables not configured, using standard OpenAI client"
  51. )
  52. except ImportError:
  53. from openai import AsyncOpenAI
  54. logger.debug("Langfuse not available, using standard OpenAI client")
  55. # use the .env that is inside the current folder
  56. # allows to use different .env file for each lightrag instance
  57. # the OS environment variables take precedence over the .env file
  58. load_dotenv(dotenv_path=".env", override=False)
  59. class InvalidResponseError(Exception):
  60. """Custom exception class for triggering retry mechanism"""
  61. pass
  62. class TransientBadRequestError(Exception):
  63. """Wrapper to trigger retry on transient HTTP 400 errors.
  64. Some 400s are not genuine client errors: the OpenAI API (or a proxy in
  65. front of it) intermittently returns "We could not parse the JSON body of
  66. your request" when the request body is corrupted/truncated in transit.
  67. These succeed on retry, so we re-raise them as this retryable type while
  68. letting genuine 400s (bad params, content policy, etc.) fail fast.
  69. """
  70. pass
  71. def _validate_openai_response_format(response_format: Any | None) -> None:
  72. """Reject typed structured-output helpers; only wire-format dicts are supported."""
  73. if response_format is None or isinstance(response_format, dict):
  74. return
  75. raise TypeError(
  76. "openai_complete_if_cache only supports dict response_format payloads; "
  77. "typed/Pydantic response_format values are not supported."
  78. )
  79. # Module-level cache for tiktoken encodings
  80. _TIKTOKEN_ENCODING_CACHE: dict[str, Any] = {}
  81. # Whether to request base64-encoded embeddings from the API.
  82. # Base64 is more efficient over the wire; set EMBEDDING_USE_BASE64=false for
  83. # providers that don't support it (e.g. Yandex Cloud).
  84. EMBEDDING_USE_BASE64: bool = os.getenv("EMBEDDING_USE_BASE64", "true").lower() in (
  85. "true",
  86. "1",
  87. "yes",
  88. )
  89. def _get_tiktoken_encoding_for_model(model: str) -> Any:
  90. """Get tiktoken encoding for the specified model with caching.
  91. Args:
  92. model: The model name to get encoding for.
  93. Returns:
  94. The tiktoken encoding for the model.
  95. """
  96. if model not in _TIKTOKEN_ENCODING_CACHE:
  97. try:
  98. _TIKTOKEN_ENCODING_CACHE[model] = tiktoken.encoding_for_model(model)
  99. except KeyError:
  100. logger.debug(
  101. f"Encoding for model '{model}' not found, falling back to cl100k_base"
  102. )
  103. _TIKTOKEN_ENCODING_CACHE[model] = tiktoken.get_encoding("cl100k_base")
  104. return _TIKTOKEN_ENCODING_CACHE[model]
  105. def create_openai_async_client(
  106. api_key: str | None = None,
  107. base_url: str | None = None,
  108. use_azure: bool = False,
  109. azure_deployment: str | None = None,
  110. api_version: str | None = None,
  111. timeout: int | None = None,
  112. client_configs: dict[str, Any] | None = None,
  113. ) -> AsyncOpenAI:
  114. """Create an AsyncOpenAI or AsyncAzureOpenAI client with the given configuration.
  115. Args:
  116. api_key: OpenAI API key. If None, uses the OPENAI_API_KEY environment variable.
  117. base_url: Base URL for the OpenAI API. If None, uses the default OpenAI API URL.
  118. use_azure: Whether to create an Azure OpenAI client. Default is False.
  119. azure_deployment: Azure OpenAI deployment name (only used when use_azure=True).
  120. api_version: Azure OpenAI API version (only used when use_azure=True).
  121. timeout: Request timeout in seconds.
  122. client_configs: Additional configuration options for the AsyncOpenAI client.
  123. These will override any default configurations but will be overridden by
  124. explicit parameters (api_key, base_url).
  125. Returns:
  126. An AsyncOpenAI or AsyncAzureOpenAI client instance.
  127. """
  128. if use_azure:
  129. from openai import AsyncAzureOpenAI
  130. if not api_key:
  131. api_key = os.environ.get("AZURE_OPENAI_API_KEY") or os.environ.get(
  132. "LLM_BINDING_API_KEY"
  133. )
  134. if client_configs is None:
  135. client_configs = {}
  136. # Create a merged config dict with precedence: explicit params > client_configs
  137. merged_configs = {
  138. **client_configs,
  139. "api_key": api_key,
  140. }
  141. # Add explicit parameters (override client_configs)
  142. if base_url is not None:
  143. merged_configs["azure_endpoint"] = base_url
  144. if azure_deployment is not None:
  145. merged_configs["azure_deployment"] = azure_deployment
  146. if api_version is not None:
  147. merged_configs["api_version"] = api_version
  148. if timeout is not None:
  149. merged_configs["timeout"] = timeout
  150. return AsyncAzureOpenAI(**merged_configs)
  151. else:
  152. if not api_key:
  153. api_key = os.environ["OPENAI_API_KEY"]
  154. default_headers = {
  155. "User-Agent": f"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_8) LightRAG/{__api_version__}",
  156. "Content-Type": "application/json",
  157. }
  158. dashscope_workspace_id = os.getenv("DASHSCOPE_WORKSPACE_ID", "").strip()
  159. if dashscope_workspace_id:
  160. default_headers["X-DashScope-Workspace"] = dashscope_workspace_id
  161. if client_configs is None:
  162. client_configs = {}
  163. # Create a merged config dict with precedence: explicit params > client_configs > defaults
  164. merged_configs = {
  165. **client_configs,
  166. "default_headers": default_headers,
  167. "api_key": api_key,
  168. }
  169. if base_url is not None:
  170. merged_configs["base_url"] = base_url
  171. else:
  172. merged_configs["base_url"] = os.environ.get(
  173. "OPENAI_API_BASE", "https://api.openai.com/v1"
  174. )
  175. if timeout is not None:
  176. merged_configs["timeout"] = timeout
  177. return AsyncOpenAI(**merged_configs)
  178. # TODO LengthFinishReasonError should not persist into LLM cache
  179. @retry(
  180. stop=stop_after_attempt(3),
  181. wait=wait_exponential(multiplier=1, min=4, max=10),
  182. retry=(
  183. retry_if_exception_type(RateLimitError)
  184. | retry_if_exception_type(APIConnectionError)
  185. | retry_if_exception_type(APITimeoutError)
  186. | retry_if_exception_type(InvalidResponseError)
  187. # Retry transient HTTP 5xx (OpenAI "500 server_error", proxy "upstream
  188. # connect error"). InternalServerError covers all status >= 500.
  189. | retry_if_exception_type(InternalServerError)
  190. # Retry transient "could not parse JSON body" 400s (see handler below).
  191. | retry_if_exception_type(TransientBadRequestError)
  192. ),
  193. )
  194. async def openai_complete_if_cache(
  195. model: str,
  196. prompt: str,
  197. system_prompt: str | None = None,
  198. history_messages: list[dict[str, Any]] | None = None,
  199. enable_cot: bool = False,
  200. base_url: str | None = None,
  201. api_key: str | None = None,
  202. token_tracker: Any | None = None,
  203. stream: bool | None = None,
  204. timeout: int | None = None,
  205. keyword_extraction: bool = False,
  206. use_azure: bool = False,
  207. azure_deployment: str | None = None,
  208. api_version: str | None = None,
  209. image_inputs: list[Any] | None = None,
  210. **kwargs: Any,
  211. ) -> str:
  212. """Complete a prompt using OpenAI's API with caching support and Chain of Thought (COT) integration.
  213. This function supports automatic integration of reasoning content from models that provide
  214. Chain of Thought capabilities. The reasoning content is seamlessly integrated into the response
  215. using <think>...</think> tags.
  216. Structured output design note:
  217. - This adapter supports dict-based OpenAI response_format payloads,
  218. including ``{"type": "json_object"}`` and dict-form ``json_schema``.
  219. - Typed/Pydantic ``response_format`` helpers are rejected explicitly.
  220. - Structured responses are returned as raw text from ``message.content``
  221. and are not locally schema-validated here.
  222. - ``keyword_extraction`` is deprecated; prefer
  223. ``response_format={"type": "json_object"}`` instead.
  224. Note on truncated structured output: when the OpenAI SDK raises
  225. `LengthFinishReasonError`, callers may still receive partial raw JSON from
  226. `completion.choices[0].message.content`. That payload should be treated as
  227. best-effort recovery only. If the JSON was truncated or repaired after
  228. truncation, it is safer not to persist it into the LLM cache because later
  229. runs with a higher token budget could otherwise keep reusing incomplete data.
  230. Note on `reasoning_content`: This feature relies on a Deepseek Style `reasoning_content`
  231. in the API response, which may be provided by OpenAI-compatible endpoints that support
  232. Chain of Thought.
  233. COT Integration Rules:
  234. 1. COT content is accepted only when regular content is empty and `reasoning_content` has content.
  235. 2. COT processing stops when regular content becomes available.
  236. 3. If both `content` and `reasoning_content` are present simultaneously, reasoning is ignored.
  237. 4. If both fields have content from the start, COT is never activated.
  238. 5. For streaming: COT content is inserted into the content stream with <think> tags.
  239. 6. For non-streaming: COT content is prepended to regular content with <think> tags.
  240. Args:
  241. model: The OpenAI model to use. For Azure, this can be the deployment name.
  242. prompt: The prompt to complete.
  243. system_prompt: Optional system prompt to include.
  244. history_messages: Optional list of previous messages in the conversation.
  245. enable_cot: Whether to enable Chain of Thought (COT) processing. Default is False.
  246. base_url: Optional base URL for the OpenAI API. For Azure, this should be the
  247. Azure OpenAI endpoint (e.g., https://your-resource.openai.azure.com/).
  248. api_key: Optional API key. For standard OpenAI, uses OPENAI_API_KEY environment
  249. variable if None. For Azure, uses AZURE_OPENAI_API_KEY if None.
  250. token_tracker: Optional token usage tracker for monitoring API usage.
  251. stream: Whether to stream the response. Default is False.
  252. timeout: Request timeout in seconds. Default is None.
  253. keyword_extraction: Deprecated compatibility shim. When True and no
  254. explicit ``response_format`` is supplied, it is mapped to
  255. ``{"type": "json_object"}``. Prefer passing ``response_format``
  256. directly. Default is False.
  257. use_azure: Whether to use Azure OpenAI service instead of standard OpenAI.
  258. When True, creates an AsyncAzureOpenAI client. Default is False.
  259. azure_deployment: Azure OpenAI deployment name. Only used when use_azure=True.
  260. If not specified, falls back to AZURE_OPENAI_DEPLOYMENT environment variable.
  261. api_version: Azure OpenAI API version (e.g., "2024-02-15-preview"). Only used
  262. when use_azure=True. If not specified, falls back to AZURE_OPENAI_API_VERSION
  263. environment variable.
  264. **kwargs: Additional keyword arguments to pass to the OpenAI API.
  265. Special kwargs:
  266. - response_format: Structured output control forwarded to the OpenAI
  267. chat completions API. This adapter accepts dict payloads such
  268. as ``{"type": "json_object"}`` and dict-form ``json_schema``,
  269. but rejects typed/Pydantic response_format values.
  270. - openai_client_configs: Dict of configuration options for the AsyncOpenAI client.
  271. These will be passed to the client constructor but will be overridden by
  272. explicit parameters (api_key, base_url). Supports proxy configuration,
  273. custom headers, retry policies, etc.
  274. Returns:
  275. The completed text (with integrated COT content if available) or an async iterator
  276. of text chunks if streaming. COT content is wrapped in <think>...</think> tags.
  277. Raises:
  278. InvalidResponseError: If the response from OpenAI is invalid or empty.
  279. APIConnectionError: If there is a connection error with the OpenAI API.
  280. RateLimitError: If the OpenAI API rate limit is exceeded.
  281. APITimeoutError: If the OpenAI API request times out.
  282. """
  283. if history_messages is None:
  284. history_messages = []
  285. # Set openai logger level to INFO when VERBOSE_DEBUG is off
  286. if not VERBOSE_DEBUG and logger.level == logging.DEBUG:
  287. logging.getLogger("openai").setLevel(logging.INFO)
  288. # Remove special kwargs that shouldn't be passed to OpenAI
  289. kwargs.pop("hashing_kv", None)
  290. # Extract client configuration options
  291. client_configs = kwargs.pop("openai_client_configs", {})
  292. # Deprecation shims: map legacy boolean flags to response_format only when
  293. # an explicit response_format was not supplied by the caller. Prefer passing
  294. # response_format directly.
  295. entity_extraction = kwargs.pop("entity_extraction", False)
  296. if entity_extraction and kwargs.get("response_format") is None:
  297. warnings.warn(
  298. "openai_complete_if_cache(entity_extraction=True) is deprecated; "
  299. "pass response_format={'type': 'json_object'} instead.",
  300. DeprecationWarning,
  301. stacklevel=2,
  302. )
  303. kwargs["response_format"] = {"type": "json_object"}
  304. if keyword_extraction and kwargs.get("response_format") is None:
  305. warnings.warn(
  306. "openai_complete_if_cache(keyword_extraction=True) is deprecated; "
  307. "pass response_format={'type': 'json_object'} instead.",
  308. DeprecationWarning,
  309. stacklevel=2,
  310. )
  311. kwargs["response_format"] = {"type": "json_object"}
  312. _validate_openai_response_format(kwargs.get("response_format"))
  313. if kwargs.get("response_format") is not None:
  314. enable_cot = False
  315. # Create the OpenAI client (supports both OpenAI and Azure)
  316. openai_async_client = create_openai_async_client(
  317. api_key=api_key,
  318. base_url=base_url,
  319. use_azure=use_azure,
  320. azure_deployment=azure_deployment,
  321. api_version=api_version,
  322. timeout=timeout,
  323. client_configs=client_configs,
  324. )
  325. # Prepare messages
  326. messages: list[dict[str, Any]] = []
  327. if system_prompt:
  328. messages.append({"role": "system", "content": system_prompt})
  329. messages.extend(history_messages)
  330. if image_inputs:
  331. from lightrag.llm._vision_utils import normalize_image_inputs
  332. normalized_images = normalize_image_inputs(image_inputs)
  333. user_content: list[dict[str, Any]] = [{"type": "text", "text": prompt}]
  334. for img in normalized_images:
  335. user_content.append(
  336. {
  337. "type": "image_url",
  338. "image_url": {
  339. "url": f"data:{img.mime_type};base64,{img.base64_str}"
  340. },
  341. }
  342. )
  343. messages.append({"role": "user", "content": user_content})
  344. else:
  345. messages.append({"role": "user", "content": prompt})
  346. logger.debug("===== Entering func of LLM =====")
  347. logger.debug(f"Model: {model} Base URL: {base_url}")
  348. logger.debug(f"Client Configs: {client_configs}")
  349. logger.debug(f"Additional kwargs: {kwargs}")
  350. logger.debug(f"Num of history messages: {len(history_messages)}")
  351. verbose_debug(f"System prompt: {system_prompt}")
  352. verbose_debug(f"Query: {prompt}")
  353. logger.debug("===== Sending Query to LLM =====")
  354. messages = kwargs.pop("messages", messages)
  355. # Add explicit parameters back to kwargs so they're passed to OpenAI API
  356. if stream is not None:
  357. kwargs["stream"] = stream
  358. if timeout is not None:
  359. kwargs["timeout"] = timeout
  360. # Determine the correct model identifier to use
  361. # For Azure OpenAI, we must use the deployment name instead of the model name
  362. api_model = azure_deployment if use_azure and azure_deployment else model
  363. try:
  364. # Single dispatch: create() covers the dict-based response_format
  365. # payloads used by this project. Typed/Pydantic helpers are rejected
  366. # above. Length-truncation is detected via finish_reason below and the
  367. # raw content is returned unchanged so upstream tolerant JSON parsing
  368. # can still salvage it.
  369. response = await openai_async_client.chat.completions.create(
  370. model=api_model, messages=messages, **kwargs
  371. )
  372. except APITimeoutError as e:
  373. logger.error(f"OpenAI API Timeout Error: {e}")
  374. try:
  375. await openai_async_client.close()
  376. except Exception as close_error:
  377. logger.warning(f"Failed to close OpenAI client: {close_error}")
  378. raise
  379. except APIConnectionError as e:
  380. logger.error(f"OpenAI API Connection Error: {e}")
  381. try:
  382. await openai_async_client.close()
  383. except Exception as close_error:
  384. logger.warning(f"Failed to close OpenAI client: {close_error}")
  385. raise
  386. except RateLimitError as e:
  387. logger.error(f"OpenAI API Rate Limit Error: {e}")
  388. try:
  389. await openai_async_client.close()
  390. except Exception as close_error:
  391. logger.warning(f"Failed to close OpenAI client: {close_error}")
  392. raise
  393. except BadRequestError as e:
  394. # A "could not parse JSON body" 400 is transient (corrupted/truncated
  395. # request body in transit) and succeeds on retry; re-raise it as a
  396. # retryable type. Genuine 400s (bad params, content policy) fail fast.
  397. # Either way we must close the client before re-raising, matching the
  398. # other except branches above — otherwise non-transient 400s would
  399. # leak httpx connections in validation-heavy/misconfigured runs.
  400. try:
  401. await openai_async_client.close()
  402. except Exception as close_error:
  403. logger.warning(f"Failed to close OpenAI client: {close_error}")
  404. # Heuristic: match on the provider's error wording. It can drift across
  405. # providers/proxies or localization, and a genuinely malformed request
  406. # body (e.g. invalid user-supplied JSON) could also surface this text —
  407. # in that case we simply retry 3x and still fail fast. We accept that
  408. # "retry too much" trade-off to recover the common transient case.
  409. if "could not parse" in str(e).lower():
  410. logger.warning(f"Transient JSON-parse 400 from OpenAI, will retry: {e}")
  411. raise TransientBadRequestError(str(e)) from e
  412. raise
  413. except Exception as e:
  414. body = getattr(e, "body", None)
  415. request_id = getattr(e, "request_id", None)
  416. req = getattr(e, "request", None)
  417. extra_parts = []
  418. if body:
  419. extra_parts.append(f"Response body: {body}")
  420. if request_id:
  421. extra_parts.append(f"Request ID: {request_id}")
  422. if req is not None:
  423. extra_parts.append(f"Request URL: {req.url}")
  424. extra = ("\n" + "\n".join(extra_parts)) if extra_parts else ""
  425. logger.error(
  426. f"OpenAI API Call Failed,\nModel: {model},\nParams: {kwargs}, Got: {e}{extra}"
  427. )
  428. try:
  429. await openai_async_client.close()
  430. except Exception as close_error:
  431. logger.warning(f"Failed to close OpenAI client: {close_error}")
  432. raise
  433. if hasattr(response, "__aiter__"):
  434. async def inner():
  435. # Track if we've started iterating
  436. iteration_started = False
  437. final_chunk_usage = None
  438. # COT (Chain of Thought) state tracking
  439. cot_active = False
  440. cot_started = False
  441. initial_content_seen = False
  442. try:
  443. iteration_started = True
  444. async for chunk in response:
  445. # Check if this chunk has usage information (final chunk)
  446. if hasattr(chunk, "usage") and chunk.usage:
  447. final_chunk_usage = chunk.usage
  448. logger.debug(
  449. f"Received usage info in streaming chunk: {chunk.usage}"
  450. )
  451. # Check if choices exists and is not empty
  452. if not hasattr(chunk, "choices") or not chunk.choices:
  453. # Azure OpenAI sends content filter results in first chunk without choices
  454. logger.debug(
  455. f"Received chunk without choices (likely Azure content filter): {chunk}"
  456. )
  457. continue
  458. # Check if delta exists
  459. if not hasattr(chunk.choices[0], "delta"):
  460. # This might be the final chunk, continue to check for usage
  461. continue
  462. delta = chunk.choices[0].delta
  463. content = getattr(delta, "content", None)
  464. reasoning_content = getattr(delta, "reasoning_content", "")
  465. # Handle COT logic for streaming (only if enabled)
  466. if enable_cot:
  467. if content:
  468. # Regular content is present
  469. if not initial_content_seen:
  470. initial_content_seen = True
  471. # If both content and reasoning_content are present initially, don't start COT
  472. if reasoning_content:
  473. cot_active = False
  474. cot_started = False
  475. # If COT was active, end it
  476. if cot_active:
  477. yield "</think>"
  478. cot_active = False
  479. # Process regular content
  480. if r"\u" in content:
  481. content = safe_unicode_decode(content.encode("utf-8"))
  482. yield content
  483. elif reasoning_content:
  484. # Only reasoning content is present
  485. if not initial_content_seen and not cot_started:
  486. # Start COT if we haven't seen initial content yet
  487. if not cot_active:
  488. yield "<think>"
  489. cot_active = True
  490. cot_started = True
  491. # Process reasoning content if COT is active
  492. if cot_active:
  493. if r"\u" in reasoning_content:
  494. reasoning_content = safe_unicode_decode(
  495. reasoning_content.encode("utf-8")
  496. )
  497. yield reasoning_content
  498. else:
  499. # COT disabled, only process regular content
  500. if content:
  501. if r"\u" in content:
  502. content = safe_unicode_decode(content.encode("utf-8"))
  503. yield content
  504. # If neither content nor reasoning_content, continue to next chunk
  505. if content is None and reasoning_content is None:
  506. continue
  507. # Ensure COT is properly closed if still active after stream ends
  508. if enable_cot and cot_active:
  509. yield "</think>"
  510. cot_active = False
  511. # After streaming is complete, track token usage
  512. if token_tracker and final_chunk_usage:
  513. # Use actual usage from the API
  514. token_counts = {
  515. "prompt_tokens": getattr(final_chunk_usage, "prompt_tokens", 0),
  516. "completion_tokens": getattr(
  517. final_chunk_usage, "completion_tokens", 0
  518. ),
  519. "total_tokens": getattr(final_chunk_usage, "total_tokens", 0),
  520. }
  521. token_tracker.add_usage(token_counts)
  522. logger.debug(f"Streaming token usage (from API): {token_counts}")
  523. elif token_tracker:
  524. logger.debug("No usage information available in streaming response")
  525. except Exception as e:
  526. # Ensure COT is properly closed before handling exception
  527. if enable_cot and cot_active:
  528. try:
  529. yield "</think>"
  530. cot_active = False
  531. except Exception as close_error:
  532. logger.warning(
  533. f"Failed to close COT tag during exception handling: {close_error}"
  534. )
  535. logger.error(f"Error in stream response: {str(e)}")
  536. # Try to clean up resources if possible
  537. if (
  538. iteration_started
  539. and hasattr(response, "aclose")
  540. and callable(getattr(response, "aclose", None))
  541. ):
  542. try:
  543. await response.aclose()
  544. logger.debug("Successfully closed stream response after error")
  545. except Exception as close_error:
  546. logger.warning(
  547. f"Failed to close stream response: {close_error}"
  548. )
  549. # Ensure client is closed in case of exception
  550. try:
  551. await openai_async_client.close()
  552. except Exception as client_close_error:
  553. logger.warning(
  554. f"Failed to close OpenAI client after stream error: {client_close_error}"
  555. )
  556. raise
  557. finally:
  558. # Final safety check for unclosed COT tags
  559. if enable_cot and cot_active:
  560. try:
  561. yield "</think>"
  562. cot_active = False
  563. except Exception as final_close_error:
  564. logger.warning(
  565. f"Failed to close COT tag in finally block: {final_close_error}"
  566. )
  567. # Ensure resources are released even if no exception occurs
  568. # Note: Some wrapped clients (e.g., Langfuse) may not implement aclose() properly
  569. if iteration_started and hasattr(response, "aclose"):
  570. aclose_method = getattr(response, "aclose", None)
  571. if callable(aclose_method):
  572. try:
  573. await response.aclose()
  574. logger.debug("Successfully closed stream response")
  575. except (AttributeError, TypeError) as close_error:
  576. # Some wrapper objects may report hasattr(aclose) but fail when called
  577. # This is expected behavior for certain client wrappers
  578. logger.debug(
  579. f"Stream response cleanup not supported by client wrapper: {close_error}"
  580. )
  581. except Exception as close_error:
  582. logger.warning(
  583. f"Unexpected error during stream response cleanup: {close_error}"
  584. )
  585. # This prevents resource leaks since the caller doesn't handle closing
  586. try:
  587. await openai_async_client.close()
  588. logger.debug(
  589. "Successfully closed OpenAI client for streaming response"
  590. )
  591. except Exception as client_close_error:
  592. logger.warning(
  593. f"Failed to close OpenAI client in streaming finally block: {client_close_error}"
  594. )
  595. return inner()
  596. else:
  597. try:
  598. if (
  599. not response
  600. or not response.choices
  601. or not hasattr(response.choices[0], "message")
  602. ):
  603. logger.error("Invalid response from OpenAI API")
  604. try:
  605. await openai_async_client.close()
  606. except Exception as close_error:
  607. logger.warning(f"Failed to close OpenAI client: {close_error}")
  608. raise InvalidResponseError("Invalid response from OpenAI API")
  609. message = response.choices[0].message
  610. # Handle parsed responses (structured output via response_format)
  611. # When using beta.chat.completions.parse(), the response is in message.parsed
  612. if hasattr(message, "parsed") and message.parsed is not None:
  613. # Serialize the parsed structured response to JSON
  614. final_content = message.parsed.model_dump_json()
  615. logger.debug("Using parsed structured response from API")
  616. else:
  617. # Handle regular content responses
  618. content = getattr(message, "content", None)
  619. reasoning_content = getattr(message, "reasoning_content", "")
  620. # Handle COT logic for non-streaming responses (only if enabled)
  621. final_content = ""
  622. if enable_cot:
  623. # Check if we should include reasoning content
  624. should_include_reasoning = False
  625. if reasoning_content and reasoning_content.strip():
  626. if not content or content.strip() == "":
  627. # Case 1: Only reasoning content, should include COT
  628. should_include_reasoning = True
  629. final_content = (
  630. content or ""
  631. ) # Use empty string if content is None
  632. else:
  633. # Case 3: Both content and reasoning_content present, ignore reasoning
  634. should_include_reasoning = False
  635. final_content = content
  636. else:
  637. # No reasoning content, use regular content
  638. final_content = content or ""
  639. # Apply COT wrapping if needed
  640. if should_include_reasoning:
  641. if r"\u" in reasoning_content:
  642. reasoning_content = safe_unicode_decode(
  643. reasoning_content.encode("utf-8")
  644. )
  645. final_content = (
  646. f"<think>{reasoning_content}</think>{final_content}"
  647. )
  648. else:
  649. # COT disabled, only use regular content
  650. final_content = content or ""
  651. # Validate final content
  652. if not final_content or final_content.strip() == "":
  653. logger.error("Received empty content from OpenAI API")
  654. try:
  655. await openai_async_client.close()
  656. except Exception as close_error:
  657. logger.warning(f"Failed to close OpenAI client: {close_error}")
  658. raise InvalidResponseError("Received empty content from OpenAI API")
  659. # Apply Unicode decoding to final content if needed
  660. if r"\u" in final_content:
  661. final_content = safe_unicode_decode(final_content.encode("utf-8"))
  662. if token_tracker and hasattr(response, "usage"):
  663. token_counts = {
  664. "prompt_tokens": getattr(response.usage, "prompt_tokens", 0),
  665. "completion_tokens": getattr(
  666. response.usage, "completion_tokens", 0
  667. ),
  668. "total_tokens": getattr(response.usage, "total_tokens", 0),
  669. }
  670. token_tracker.add_usage(token_counts)
  671. logger.debug(f"Response content len: {len(final_content)}")
  672. verbose_debug(f"Response: {response}")
  673. return final_content
  674. finally:
  675. # Ensure client is closed in all cases for non-streaming responses
  676. try:
  677. await openai_async_client.close()
  678. except Exception as close_error:
  679. logger.warning(
  680. f"Failed to close OpenAI client in non-streaming finally block: {close_error}"
  681. )
  682. async def openai_complete(
  683. prompt,
  684. system_prompt=None,
  685. history_messages=None,
  686. keyword_extraction=False,
  687. entity_extraction=False,
  688. **kwargs,
  689. ) -> Union[str, AsyncIterator[str]]:
  690. if history_messages is None:
  691. history_messages = []
  692. # Pop entity_extraction from kwargs if also passed there (avoid duplication)
  693. entity_extraction = kwargs.pop("entity_extraction", entity_extraction)
  694. model_name = kwargs["hashing_kv"].global_config["llm_model_name"]
  695. return await openai_complete_if_cache(
  696. model_name,
  697. prompt,
  698. system_prompt=system_prompt,
  699. history_messages=history_messages,
  700. keyword_extraction=keyword_extraction,
  701. entity_extraction=entity_extraction,
  702. **kwargs,
  703. )
  704. async def gpt_4o_complete(
  705. prompt,
  706. system_prompt=None,
  707. history_messages=None,
  708. enable_cot: bool = False,
  709. keyword_extraction=False,
  710. entity_extraction=False,
  711. **kwargs,
  712. ) -> str:
  713. if history_messages is None:
  714. history_messages = []
  715. entity_extraction = kwargs.pop("entity_extraction", entity_extraction)
  716. return await openai_complete_if_cache(
  717. "gpt-4o",
  718. prompt,
  719. system_prompt=system_prompt,
  720. history_messages=history_messages,
  721. enable_cot=enable_cot,
  722. keyword_extraction=keyword_extraction,
  723. entity_extraction=entity_extraction,
  724. **kwargs,
  725. )
  726. async def gpt_4o_mini_complete(
  727. prompt,
  728. system_prompt=None,
  729. history_messages=None,
  730. enable_cot: bool = False,
  731. keyword_extraction=False,
  732. entity_extraction=False,
  733. **kwargs,
  734. ) -> str:
  735. if history_messages is None:
  736. history_messages = []
  737. entity_extraction = kwargs.pop("entity_extraction", entity_extraction)
  738. return await openai_complete_if_cache(
  739. "gpt-4o-mini",
  740. prompt,
  741. system_prompt=system_prompt,
  742. history_messages=history_messages,
  743. enable_cot=enable_cot,
  744. keyword_extraction=keyword_extraction,
  745. entity_extraction=entity_extraction,
  746. **kwargs,
  747. )
  748. async def nvidia_openai_complete(
  749. prompt,
  750. system_prompt=None,
  751. history_messages=None,
  752. enable_cot: bool = False,
  753. keyword_extraction=False,
  754. entity_extraction=False,
  755. **kwargs,
  756. ) -> str:
  757. if history_messages is None:
  758. history_messages = []
  759. entity_extraction = kwargs.pop("entity_extraction", entity_extraction)
  760. result = await openai_complete_if_cache(
  761. "nvidia/llama-3.1-nemotron-70b-instruct", # context length 128k
  762. prompt,
  763. system_prompt=system_prompt,
  764. history_messages=history_messages,
  765. enable_cot=enable_cot,
  766. keyword_extraction=keyword_extraction,
  767. entity_extraction=entity_extraction,
  768. base_url="https://integrate.api.nvidia.com/v1",
  769. **kwargs,
  770. )
  771. return result
  772. @wrap_embedding_func_with_attrs(
  773. embedding_dim=1536,
  774. max_token_size=8192,
  775. model_name="text-embedding-3-small",
  776. supports_asymmetric=True,
  777. )
  778. @retry(
  779. stop=stop_after_attempt(3),
  780. wait=wait_exponential(multiplier=1, min=4, max=60),
  781. retry=(
  782. retry_if_exception_type(RateLimitError)
  783. | retry_if_exception_type(APIConnectionError)
  784. | retry_if_exception_type(APITimeoutError)
  785. # Retry transient HTTP 5xx (OpenAI 500 / proxy upstream errors).
  786. | retry_if_exception_type(InternalServerError)
  787. ),
  788. )
  789. async def openai_embed(
  790. texts: list[str],
  791. model: str = "text-embedding-3-small",
  792. base_url: str | None = None,
  793. api_key: str | None = None,
  794. embedding_dim: int | None = None,
  795. max_token_size: int | None = None,
  796. client_configs: dict[str, Any] | None = None,
  797. token_tracker: Any | None = None,
  798. use_azure: bool = False,
  799. azure_deployment: str | None = None,
  800. api_version: str | None = None,
  801. context: str = "document",
  802. query_prefix: str | None = None,
  803. document_prefix: str | None = None,
  804. ) -> np.ndarray:
  805. """Generate embeddings for a list of texts using OpenAI's API with automatic text truncation.
  806. This function supports both standard OpenAI and Azure OpenAI services. It automatically
  807. truncates texts that exceed the model's token limit to prevent API errors.
  808. Args:
  809. texts: List of texts to embed.
  810. model: The embedding model to use. For standard OpenAI (e.g., "text-embedding-3-small").
  811. For Azure, this can be the deployment name.
  812. base_url: Optional base URL for the API. For standard OpenAI, uses default OpenAI endpoint.
  813. For Azure, this should be the Azure OpenAI endpoint (e.g., https://your-resource.openai.azure.com/).
  814. api_key: Optional API key. For standard OpenAI, uses OPENAI_API_KEY environment variable if None.
  815. For Azure, uses AZURE_EMBEDDING_API_KEY environment variable if None.
  816. embedding_dim: Optional embedding dimension for dynamic dimension reduction.
  817. **IMPORTANT**: This parameter is automatically injected by the EmbeddingFunc wrapper.
  818. Do NOT manually pass this parameter when calling the function directly.
  819. The dimension is controlled by the @wrap_embedding_func_with_attrs decorator.
  820. Manually passing a different value will trigger a warning and be ignored.
  821. When provided (by EmbeddingFunc), it will be passed to the OpenAI API for dimension reduction.
  822. max_token_size: Maximum tokens per text. Texts exceeding this limit will be truncated.
  823. **IMPORTANT**: This parameter is automatically injected by the EmbeddingFunc wrapper
  824. when the underlying function signature supports it (via inspect.signature check).
  825. The value is controlled by the @wrap_embedding_func_with_attrs decorator.
  826. Set max_token_size=0 to disable truncation.
  827. client_configs: Additional configuration options for the AsyncOpenAI/AsyncAzureOpenAI client.
  828. These will override any default configurations but will be overridden by
  829. explicit parameters (api_key, base_url). Supports proxy configuration,
  830. custom headers, retry policies, etc.
  831. token_tracker: Optional token usage tracker for monitoring API usage.
  832. use_azure: Whether to use Azure OpenAI service instead of standard OpenAI.
  833. When True, creates an AsyncAzureOpenAI client. Default is False.
  834. azure_deployment: Azure OpenAI deployment name. Only used when use_azure=True.
  835. If not specified, falls back to AZURE_EMBEDDING_DEPLOYMENT environment variable.
  836. api_version: Azure OpenAI API version (e.g., "2024-02-15-preview"). Only used
  837. when use_azure=True. If not specified, falls back to AZURE_EMBEDDING_API_VERSION
  838. environment variable.
  839. context: The embedding context - "query" for search queries, "document" for indexed content.
  840. **IMPORTANT**: This parameter is automatically injected by the EmbeddingFunc wrapper
  841. when supports_asymmetric=True. Default is "document".
  842. query_prefix: Optional prefix to prepend to texts when context="query" (e.g., "search_query: ").
  843. document_prefix: Optional prefix to prepend to texts when context="document" (e.g., "search_document: ").
  844. Returns:
  845. A numpy array of embeddings, one per input text.
  846. Raises:
  847. APIConnectionError: If there is a connection error with the OpenAI API.
  848. RateLimitError: If the OpenAI API rate limit is exceeded.
  849. APITimeoutError: If the OpenAI API request times out.
  850. """
  851. # Apply context-based prefixes if provided
  852. if context == "query" and query_prefix:
  853. texts = [query_prefix + text for text in texts]
  854. elif context == "document" and document_prefix:
  855. texts = [document_prefix + text for text in texts]
  856. # Apply text truncation if max_token_size is provided
  857. if max_token_size is not None and max_token_size > 0:
  858. encoding = _get_tiktoken_encoding_for_model(model)
  859. truncated_texts = []
  860. truncation_count = 0
  861. for text in texts:
  862. if not text:
  863. truncated_texts.append(text)
  864. continue
  865. tokens = encoding.encode(text)
  866. if len(tokens) > max_token_size:
  867. truncated_tokens = tokens[:max_token_size]
  868. truncated_texts.append(encoding.decode(truncated_tokens))
  869. truncation_count += 1
  870. logger.debug(
  871. f"Text truncated from {len(tokens)} to {max_token_size} tokens"
  872. )
  873. else:
  874. truncated_texts.append(text)
  875. if truncation_count > 0:
  876. logger.info(
  877. f"Truncated {truncation_count}/{len(texts)} texts to fit token limit ({max_token_size})"
  878. )
  879. texts = truncated_texts
  880. # Create the OpenAI client (supports both OpenAI and Azure)
  881. openai_async_client = create_openai_async_client(
  882. api_key=api_key,
  883. base_url=base_url,
  884. use_azure=use_azure,
  885. azure_deployment=azure_deployment,
  886. api_version=api_version,
  887. client_configs=client_configs,
  888. )
  889. async with openai_async_client:
  890. # Determine the correct model identifier to use
  891. # For Azure OpenAI, we must use the deployment name instead of the model name
  892. api_model = azure_deployment if use_azure and azure_deployment else model
  893. # Prepare API call parameters
  894. api_params = {
  895. "model": api_model,
  896. "input": texts,
  897. }
  898. # Add encoding_format parameter (some providers like Yandex don't support base64)
  899. # OpenAI client defaults to base64, so we must explicitly set it to "float" if disabled
  900. api_params["encoding_format"] = "base64" if EMBEDDING_USE_BASE64 else "float"
  901. # Add dimensions parameter only if embedding_dim is provided
  902. if embedding_dim is not None:
  903. api_params["dimensions"] = embedding_dim
  904. # Make API call
  905. response = await openai_async_client.embeddings.create(**api_params)
  906. if token_tracker and hasattr(response, "usage"):
  907. token_counts = {
  908. "prompt_tokens": getattr(response.usage, "prompt_tokens", 0),
  909. "total_tokens": getattr(response.usage, "total_tokens", 0),
  910. }
  911. token_tracker.add_usage(token_counts)
  912. return np.array(
  913. [
  914. np.array(dp.embedding, dtype=np.float32)
  915. if isinstance(dp.embedding, list)
  916. else np.frombuffer(base64.b64decode(dp.embedding), dtype=np.float32)
  917. for dp in response.data
  918. ]
  919. )
  920. # Azure OpenAI wrapper functions for backward compatibility
  921. async def azure_openai_complete_if_cache(
  922. model,
  923. prompt,
  924. system_prompt: str | None = None,
  925. history_messages: list[dict[str, Any]] | None = None,
  926. enable_cot: bool = False,
  927. base_url: str | None = None,
  928. api_key: str | None = None,
  929. token_tracker: Any | None = None,
  930. stream: bool | None = None,
  931. timeout: int | None = None,
  932. api_version: str | None = None,
  933. keyword_extraction: bool = False,
  934. **kwargs,
  935. ):
  936. """Azure OpenAI completion wrapper function.
  937. This function provides backward compatibility by wrapping the unified
  938. openai_complete_if_cache implementation with Azure-specific parameter handling.
  939. All parameters from the underlying openai_complete_if_cache are exposed to ensure
  940. full feature parity and API consistency.
  941. """
  942. # Handle Azure-specific environment variables and parameters
  943. deployment = os.getenv("AZURE_OPENAI_DEPLOYMENT") or model or os.getenv("LLM_MODEL")
  944. base_url = (
  945. base_url or os.getenv("AZURE_OPENAI_ENDPOINT") or os.getenv("LLM_BINDING_HOST")
  946. )
  947. api_key = (
  948. api_key or os.getenv("AZURE_OPENAI_API_KEY") or os.getenv("LLM_BINDING_API_KEY")
  949. )
  950. api_version = (
  951. api_version
  952. or os.getenv("AZURE_OPENAI_API_VERSION")
  953. or os.getenv("OPENAI_API_VERSION")
  954. or "2024-08-01-preview"
  955. )
  956. # Call the unified implementation with Azure-specific parameters
  957. return await openai_complete_if_cache(
  958. model=deployment,
  959. prompt=prompt,
  960. system_prompt=system_prompt,
  961. history_messages=history_messages,
  962. enable_cot=enable_cot,
  963. base_url=base_url,
  964. api_key=api_key,
  965. token_tracker=token_tracker,
  966. stream=stream,
  967. timeout=timeout,
  968. use_azure=True,
  969. azure_deployment=deployment,
  970. api_version=api_version,
  971. keyword_extraction=keyword_extraction,
  972. **kwargs,
  973. )
  974. async def azure_openai_complete(
  975. prompt,
  976. system_prompt=None,
  977. history_messages=None,
  978. keyword_extraction=False,
  979. entity_extraction=False,
  980. **kwargs,
  981. ) -> str:
  982. """Azure OpenAI complete wrapper function.
  983. Provides backward compatibility for azure_openai_complete calls.
  984. """
  985. if history_messages is None:
  986. history_messages = []
  987. entity_extraction = kwargs.pop("entity_extraction", entity_extraction)
  988. result = await azure_openai_complete_if_cache(
  989. os.getenv("LLM_MODEL", "gpt-4o-mini"),
  990. prompt,
  991. system_prompt=system_prompt,
  992. history_messages=history_messages,
  993. keyword_extraction=keyword_extraction,
  994. entity_extraction=entity_extraction,
  995. **kwargs,
  996. )
  997. return result
  998. @wrap_embedding_func_with_attrs(
  999. embedding_dim=1536,
  1000. max_token_size=8192,
  1001. model_name="my-text-embedding-3-large-deployment",
  1002. supports_asymmetric=True,
  1003. )
  1004. async def azure_openai_embed(
  1005. texts: list[str],
  1006. model: str | None = None,
  1007. base_url: str | None = None,
  1008. api_key: str | None = None,
  1009. embedding_dim: int | None = None,
  1010. token_tracker: Any | None = None,
  1011. client_configs: dict[str, Any] | None = None,
  1012. api_version: str | None = None,
  1013. context: str = "document",
  1014. query_prefix: str | None = None,
  1015. document_prefix: str | None = None,
  1016. ) -> np.ndarray:
  1017. """Azure OpenAI embedding wrapper function.
  1018. This function provides backward compatibility by wrapping the unified
  1019. openai_embed implementation with Azure-specific parameter handling.
  1020. All parameters from the underlying openai_embed are exposed to ensure
  1021. full feature parity and API consistency.
  1022. IMPORTANT - Decorator Usage:
  1023. 1. This function is decorated with @wrap_embedding_func_with_attrs to provide
  1024. the EmbeddingFunc interface for users who need to access embedding_dim
  1025. and other attributes.
  1026. 2. This function does NOT use @retry decorator to avoid double-wrapping,
  1027. since the underlying openai_embed.func already has retry logic.
  1028. 3. This function calls openai_embed.func (the unwrapped function) instead of
  1029. openai_embed (the EmbeddingFunc instance) to avoid double decoration issues:
  1030. ✅ Correct: await openai_embed.func(...) # Calls unwrapped function with retry
  1031. ❌ Wrong: await openai_embed(...) # Would cause double EmbeddingFunc wrapping
  1032. Double decoration causes:
  1033. - Double injection of embedding_dim parameter
  1034. - Incorrect parameter passing to the underlying implementation
  1035. - Runtime errors due to parameter conflicts
  1036. The call chain with correct implementation:
  1037. azure_openai_embed(texts)
  1038. → EmbeddingFunc.__call__(texts) # azure's decorator
  1039. → azure_openai_embed_impl(texts, embedding_dim=1536)
  1040. → openai_embed.func(texts, ...)
  1041. → @retry_wrapper(texts, ...) # openai's retry (only one layer)
  1042. → openai_embed_impl(texts, ...)
  1043. → actual embedding computation
  1044. """
  1045. # Handle Azure-specific environment variables and parameters
  1046. deployment = (
  1047. os.getenv("AZURE_EMBEDDING_DEPLOYMENT")
  1048. or model
  1049. or os.getenv("EMBEDDING_MODEL", "text-embedding-3-small")
  1050. )
  1051. base_url = (
  1052. base_url
  1053. or os.getenv("AZURE_EMBEDDING_ENDPOINT")
  1054. or os.getenv("EMBEDDING_BINDING_HOST")
  1055. )
  1056. api_key = (
  1057. api_key
  1058. or os.getenv("AZURE_EMBEDDING_API_KEY")
  1059. or os.getenv("EMBEDDING_BINDING_API_KEY")
  1060. )
  1061. api_version = (
  1062. api_version
  1063. or os.getenv("AZURE_EMBEDDING_API_VERSION")
  1064. or os.getenv("AZURE_OPENAI_API_VERSION")
  1065. or os.getenv("OPENAI_API_VERSION")
  1066. or "2024-08-01-preview"
  1067. )
  1068. # CRITICAL: Call openai_embed.func (unwrapped) to avoid double decoration
  1069. # openai_embed is an EmbeddingFunc instance, .func accesses the underlying function
  1070. return await openai_embed.func(
  1071. texts=texts,
  1072. model=deployment,
  1073. base_url=base_url,
  1074. api_key=api_key,
  1075. embedding_dim=embedding_dim,
  1076. token_tracker=token_tracker,
  1077. client_configs=client_configs,
  1078. use_azure=True,
  1079. azure_deployment=deployment,
  1080. api_version=api_version,
  1081. context=context,
  1082. query_prefix=query_prefix,
  1083. document_prefix=document_prefix,
  1084. )