|
1 | 1 | from collections.abc import Iterable |
2 | | -from typing import TYPE_CHECKING |
| 2 | +from typing import TYPE_CHECKING, cast |
3 | 3 |
|
4 | 4 | if TYPE_CHECKING: |
5 | | - from typing import Union |
| 5 | + from typing import TypeGuard, Union |
6 | 6 |
|
7 | 7 | from openai.types.chat import ( |
8 | 8 | ChatCompletionContentPartParam, |
| 9 | + ChatCompletionContentPartRefusalParam, |
| 10 | + ChatCompletionContentPartTextParam, |
9 | 11 | ChatCompletionMessageParam, |
10 | 12 | ChatCompletionSystemMessageParam, |
11 | 13 | ChatCompletionToolUnionParam, |
|
14 | 16 | from sentry_sdk._types import TextPart, ToolDefinition |
15 | 17 |
|
16 | 18 |
|
17 | | -def _is_system_instruction(message: "ChatCompletionMessageParam") -> bool: |
| 19 | +def _is_system_instruction( |
| 20 | + message: "ChatCompletionMessageParam", |
| 21 | +) -> "TypeGuard[ChatCompletionSystemMessageParam]": |
18 | 22 | return isinstance(message, dict) and message.get("role") == "system" |
19 | 23 |
|
20 | 24 |
|
21 | 25 | def _get_system_instructions( |
22 | 26 | messages: "Iterable[ChatCompletionMessageParam]", |
23 | | -) -> "list[ChatCompletionMessageParam]": |
| 27 | +) -> "list[ChatCompletionSystemMessageParam]": |
24 | 28 | if not isinstance(messages, Iterable): |
25 | 29 | return [] |
26 | 30 |
|
27 | 31 | return [message for message in messages if _is_system_instruction(message)] |
28 | 32 |
|
29 | 33 |
|
30 | 34 | def _get_text_items( |
31 | | - content: "Union[str, Iterable[ChatCompletionContentPartParam]]", |
| 35 | + content: "Union[str, Iterable[Union[ChatCompletionContentPartParam, ChatCompletionContentPartTextParam, ChatCompletionContentPartRefusalParam]]]", |
32 | 36 | ) -> "list[str]": |
33 | 37 | if isinstance(content, str): |
34 | 38 | return [content] |
35 | 39 |
|
36 | 40 | if not isinstance(content, Iterable): |
37 | 41 | return [] |
38 | 42 |
|
39 | | - text_items = [] |
| 43 | + text_items: "list[str]" = [] |
40 | 44 | for part in content: |
41 | 45 | if isinstance(part, dict) and part.get("type") == "text": |
42 | | - text = part.get("text", None) |
| 46 | + text = cast("ChatCompletionContentPartTextParam", part).get("text", None) |
43 | 47 | if text is not None: |
44 | 48 | text_items.append(text) |
45 | 49 |
|
|
0 commit comments