Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions sentry_sdk/integrations/openai.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from functools import wraps
from collections.abc import Iterable

import sentry_sdk
from sentry_sdk import consts
Expand All @@ -17,14 +18,19 @@
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from typing import Any, Iterable, List, Optional, Callable, AsyncIterator, Iterator
from typing import Any, List, Optional, Callable, AsyncIterator, Iterator
from sentry_sdk.tracing import Span

try:
try:
from openai import NOT_GIVEN
from openai import NotGiven
except ImportError:
NOT_GIVEN = None
NotGiven = None

try:
from openai import Omit
except ImportError:
Omit = None

from openai.resources.chat.completions import Completions, AsyncCompletions
from openai.resources import Embeddings, AsyncEmbeddings
Expand Down Expand Up @@ -204,12 +210,12 @@ def _set_input_data(span, kwargs, operation, integration):
for key, attribute in kwargs_keys_to_attributes.items():
value = kwargs.get(key)

if value is not NOT_GIVEN and value is not None:
if value is not None and _is_given(value):
set_data_normalized(span, attribute, value)

# Input attributes: Tools
tools = kwargs.get("tools")
if tools is not NOT_GIVEN and tools is not None and len(tools) > 0:
if tools is not None and _is_given(tools) and len(tools) > 0:
set_data_normalized(
span, SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, safe_serialize(tools)
)
Expand Down Expand Up @@ -689,3 +695,15 @@ async def _sentry_patched_responses_async(*args, **kwargs):
return await _execute_async(f, *args, **kwargs)

return _sentry_patched_responses_async


def _is_given(obj):
# type: (Any) -> bool
"""
Check for givenness safely across different openai versions.
"""
if NotGiven is not None and isinstance(obj, NotGiven):
return False
if Omit is not None and isinstance(obj, Omit):
return False
return True
7 changes: 6 additions & 1 deletion tests/integrations/openai/test_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
except ImportError:
NOT_GIVEN = None

try:
from openai import omit
except ImportError:
omit = None

from openai import AsyncOpenAI, OpenAI, AsyncStream, Stream, OpenAIError
from openai.types import CompletionUsage, CreateEmbeddingResponse, Embedding
from openai.types.chat import ChatCompletion, ChatCompletionMessage, ChatCompletionChunk
Expand Down Expand Up @@ -1424,7 +1429,7 @@ async def test_streaming_responses_api_async(
)
@pytest.mark.parametrize(
"tools",
[[], None, NOT_GIVEN],
[[], None, NOT_GIVEN, omit],
)
def test_empty_tools_in_chat_completion(sentry_init, capture_events, tools):
sentry_init(
Expand Down