Skip to content

Commit eda36c0

Browse files
feat(tracer): improve conditional imports and type hinting for OpenAI integration
- Implemented conditional import handling for the `openai` library, allowing for graceful degradation when the library is not installed. - Enhanced type hints using forward references for `openai` types to improve code clarity and maintainability. - Introduced informative error messages when the `openai` library is missing, guiding users on how to install it. - This update ensures better compatibility and user experience when working with optional dependencies in the OpenAI integration.
1 parent 3229f41 commit eda36c0

1 file changed

Lines changed: 23 additions & 6 deletions

File tree

src/openlayer/lib/integrations/openai_tracer.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,25 @@
44
import logging
55
import time
66
from functools import wraps
7-
from typing import Any, Dict, Iterator, List, Optional, Union
7+
from typing import Any, Dict, Iterator, List, Optional, Union, TYPE_CHECKING
88

9-
import openai
9+
try:
10+
import openai
11+
HAVE_OPENAI = True
12+
except ImportError:
13+
HAVE_OPENAI = False
14+
15+
if TYPE_CHECKING:
16+
import openai
1017

1118
from ..tracing import tracer
1219

1320
logger = logging.getLogger(__name__)
1421

1522

1623
def trace_openai(
17-
client: Union[openai.OpenAI, openai.AzureOpenAI],
18-
) -> Union[openai.OpenAI, openai.AzureOpenAI]:
24+
client: Union["openai.OpenAI", "openai.AzureOpenAI"],
25+
) -> Union["openai.OpenAI", "openai.AzureOpenAI"]:
1926
"""Patch the OpenAI or AzureOpenAI client to trace chat completions.
2027
2128
The following information is collected for each chat completion:
@@ -42,6 +49,11 @@ def trace_openai(
4249
Union[openai.OpenAI, openai.AzureOpenAI]
4350
The patched OpenAI client.
4451
"""
52+
if not HAVE_OPENAI:
53+
raise ImportError(
54+
"OpenAI library is not installed. Please install it with: pip install openai"
55+
)
56+
4557
is_azure_openai = isinstance(client, openai.AzureOpenAI)
4658
create_func = client.chat.completions.create
4759

@@ -358,12 +370,17 @@ def parse_non_streaming_output_data(
358370

359371
# --------------------------- OpenAI Assistants API -------------------------- #
360372
def trace_openai_assistant_thread_run(
361-
client: openai.OpenAI, run: "openai.types.beta.threads.run.Run"
373+
client: "openai.OpenAI", run: "openai.types.beta.threads.run.Run"
362374
) -> None:
363375
"""Trace a run from an OpenAI assistant.
364376
365377
Once the run is completed, the thread data is published to Openlayer,
366378
along with the latency, and number of tokens used."""
379+
if not HAVE_OPENAI:
380+
raise ImportError(
381+
"OpenAI library is not installed. Please install it with: pip install openai"
382+
)
383+
367384
_type_check_run(run)
368385

369386
# Do nothing if the run is not completed
@@ -398,7 +415,7 @@ def trace_openai_assistant_thread_run(
398415

399416
def _type_check_run(run: "openai.types.beta.threads.run.Run") -> None:
400417
"""Validate the run object."""
401-
if not isinstance(run, openai.types.beta.threads.run.Run):
418+
if HAVE_OPENAI and not isinstance(run, openai.types.beta.threads.run.Run):
402419
raise ValueError(f"Expected a Run object, but got {type(run)}.")
403420

404421

0 commit comments

Comments
 (0)