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
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ typing = [
"aiohttp>=3.14.3",
"openai-agents>=0.22.0",
"mistralai>=2.10.1",
"typesafe-sdk>=0.7.2",
"typesafe-sdk>=0.7.5",
]
test = [
"dataclasses ; python_full_version < '3.7'",
Expand Down
65 changes: 51 additions & 14 deletions sentry_sdk/integrations/typesafe.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,26 @@
Union,
)

from typesafe_sdk import JSONContent
from typesafe_sdk import Content
from typesafe_sdk._core.question_types import Questions

class NoulModel(TypedDict):
type: Literal["noul"]
instructions: NotRequired[JSONContent | None]
instructions: NotRequired[Content | None]

class ChoiceModel(TypedDict):
type: Literal["choice"]
criteria: NotRequired[Mapping[str, JSONContent | None]]
instructions: NotRequired[JSONContent | None]
criteria: NotRequired[Mapping[str, Content | None]]
instructions: NotRequired[Content | None]

class ScoreModel(TypedDict):
type: Literal["score"]
criteria: NotRequired[Sequence[JSONContent]]
instructions: NotRequired[JSONContent | None]
criteria: NotRequired[Sequence[Content]]
instructions: NotRequired[Content | None]

class InputMessageModel(TypedDict):
type: Literal["evaluation"]
state: NotRequired[JSONContent]
state: NotRequired[Content]
questions: NotRequired[dict[str, Union[NoulModel, ChoiceModel, ScoreModel]]]

class NoulEvaluationModel(TypedDict):
Expand All @@ -66,14 +66,27 @@ class ScoreEvaluationModel(TypedDict):


try:
from typesafe_sdk import Choice, ChoiceAnswer, Noul, NoulAnswer, Score, ScoreAnswer
from typesafe_sdk import (
Choice,
ChoiceAnswer,
Noul,
NoulAnswer,
Score,
ScoreAnswer,
)
from typesafe_sdk._core.client.aio.client import AsyncTypeSafeClient
from typesafe_sdk._core.client.sync.client import TypeSafeClient
from typesafe_sdk._core.response_types import Answer, SystemOneResponse
except ImportError:
raise DidNotEnable("typesafe-sdk not installed")


try:
from typesafe_sdk import Image
except ImportError:
Image = None # type: ignore[misc, assignment]


class TypeSafeIntegration(Integration):
identifier = "typesafe"
origin = f"auto.ai.{identifier}"
Expand All @@ -86,6 +99,16 @@ def setup_once() -> None:
)


def _json_default(value: object) -> str:
"""
Render an inline typesafe `Image` as its reference, mirroring the SDK's handling.
"""
if Image is not None and isinstance(value, Image):
return str(value)

return "<unserializable>"


def _transform_questions(
questions: "Questions",
) -> "dict[str, Union[NoulModel, ChoiceModel, ScoreModel]]":
Expand Down Expand Up @@ -146,7 +169,7 @@ def _transform_questions(
}
if "criteria" in question:
choice["criteria"] = cast(
"Mapping[str, JSONContent | None]", question["criteria"]
"Mapping[str, Content | None]", question["criteria"]
)
if "instructions" in question:
choice["instructions"] = question["instructions"]
Expand All @@ -159,7 +182,7 @@ def _transform_questions(
"type": question_type,
}
if "criteria" in question:
score["criteria"] = cast("Sequence[JSONContent]", question["criteria"])
score["criteria"] = cast("Sequence[Content]", question["criteria"])
if "instructions" in question:
score["instructions"] = question["instructions"]

Expand Down Expand Up @@ -265,7 +288,13 @@ def wrap_system_one(self: "TypeSafeClient", *args: "Any", **kwargs: "Any") -> "A
if isinstance(questions, Mapping):
input_message["questions"] = _transform_questions(questions)

set_on_span(SPANDATA.GEN_AI_INPUT_MESSAGES, json.dumps([input_message]))
set_on_span(
SPANDATA.GEN_AI_INPUT_MESSAGES,
json.dumps(
[input_message],
default=_json_default,
),
)

response = f(self, *args, **kwargs)

Expand Down Expand Up @@ -301,7 +330,8 @@ def wrap_system_one(self: "TypeSafeClient", *args: "Any", **kwargs: "Any") -> "A
response.answers
),
}
]
],
default=_json_default,
),
)

Expand Down Expand Up @@ -372,7 +402,13 @@ async def wrap_system_one_async(
if isinstance(questions, Mapping):
input_message["questions"] = _transform_questions(questions)

set_on_span(SPANDATA.GEN_AI_INPUT_MESSAGES, json.dumps([input_message]))
set_on_span(
SPANDATA.GEN_AI_INPUT_MESSAGES,
json.dumps(
[input_message],
default=_json_default,
),
)

response = await f(self, *args, **kwargs)

Expand Down Expand Up @@ -408,7 +444,8 @@ async def wrap_system_one_async(
response.answers
),
}
]
],
default=_json_default,
),
)

Expand Down
139 changes: 139 additions & 0 deletions tests/integrations/typesafe/test_typesafe.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
Usage,
)

try:
from typesafe_sdk import Image
except ImportError:
Image = None
Comment thread
alexander-alderman-webb marked this conversation as resolved.
Resolved

import sentry_sdk
from sentry_sdk.consts import OP, SPANDATA
from sentry_sdk.integrations.typesafe import TypeSafeIntegration
Expand Down Expand Up @@ -623,3 +628,137 @@ async def test_system_one_async(
},
}
]


@pytest.mark.skipif(
Image is None, reason="Image was added in version v0.7.5 of typesafe-sdk"
)
def test_system_one_with_inline_image(
sentry_init,
capture_items,
typesafe_response,
):
sentry_init(
integrations=[TypeSafeIntegration()],
traces_sample_rate=1.0,
send_default_pii=True,
trace_lifecycle="stream",
)

photo = Image(b"\x89PNG\r\n\x1a\nimage data")
listing = Image(b"\xff\xd8\xffimage data")

client = TypeSafeClient(api_key="z")
items = capture_items("span")

with mock.patch.object(
TypeSafeClient, "_request", return_value=typesafe_response
), sentry_sdk.start_transaction(name="typesafe"):
client.system_one(
state=[
{"role": "user", "msg": ["Here is what came back:", photo]},
("listing", listing),
],
questions={
"same": Noul(instructions=["Is it the item in this photo?", listing]),
"condition": Choice(criteria={"new": photo, "used": None}),
"damage": Score(criteria=["none", {"example": [photo]}]),
},
)

sentry_sdk.flush()
spans = [item.payload for item in items]
(span,) = spans

assert json.loads(span["attributes"][SPANDATA.GEN_AI_INPUT_MESSAGES]) == [
{
"type": "evaluation",
"state": [
{"role": "user", "msg": ["Here is what came back:", str(photo)]},
["listing", str(listing)],
],
"questions": {
"same": {
"type": "noul",
"instructions": ["Is it the item in this photo?", str(listing)],
},
"condition": {
"type": "choice",
"criteria": {"new": str(photo), "used": None},
},
"damage": {
"type": "score",
"criteria": ["none", {"example": [str(photo)]}],
},
},
}
]


@pytest.mark.asyncio
@pytest.mark.skipif(
Image is None, reason="Image was added in version v0.7.5 of typesafe-sdk"
)
async def test_system_one_async_with_inline_image(
sentry_init,
capture_items,
typesafe_response,
):
sentry_init(
integrations=[TypeSafeIntegration()],
traces_sample_rate=1.0,
send_default_pii=True,
trace_lifecycle="stream",
)

photo = Image(b"\x89PNG\r\n\x1a\nimage data")
listing = Image(b"\xff\xd8\xffimage data")

client = AsyncTypeSafeClient(api_key="z")
items = capture_items("span")

with mock.patch.object(
AsyncTypeSafeClient,
"_request",
new_callable=mock.AsyncMock,
return_value=typesafe_response,
), sentry_sdk.start_transaction(name="typesafe"):
await client.system_one(
state=[
{"role": "user", "msg": ["Here is what came back:", photo]},
("listing", listing),
],
questions={
"same": Noul(instructions=["Is it the item in this photo?", listing]),
"condition": Choice(criteria={"new": photo, "used": None}),
"damage": Score(criteria=["none", {"example": [photo]}]),
},
)

sentry_sdk.flush()
spans = [item.payload for item in items]
(span,) = spans

assert json.loads(span["attributes"][SPANDATA.GEN_AI_INPUT_MESSAGES]) == [
{
"type": "evaluation",
"state": [
{"role": "user", "msg": ["Here is what came back:", str(photo)]},
["listing", str(listing)],
],
"questions": {
"same": {
"type": "noul",
"instructions": ["Is it the item in this photo?", str(listing)],
},
"condition": {
"type": "choice",
"criteria": {"new": str(photo), "used": None},
},
"damage": {
"type": "score",
"criteria": ["none", {"example": [str(photo)]}],
},
},
}
]
Loading
Loading