-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathmessage.py
More file actions
142 lines (111 loc) · 4.87 KB
/
message.py
File metadata and controls
142 lines (111 loc) · 4.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
from __future__ import annotations
from collections.abc import Iterable
from typing import TypedDict, Union, cast
from typing_extensions import NotRequired, Required
from yandex_cloud_ml_sdk._models.completions.message import (
FunctionResultMessageDict, MessageInputType, MessageType, TextMessageWithToolCallsProtocol
)
from yandex_cloud_ml_sdk._tools.tool_result import ToolResultDictType
from yandex_cloud_ml_sdk._types.json import JsonObject
from yandex_cloud_ml_sdk._types.message import TextMessageDict, TextMessageProtocol
from yandex_cloud_ml_sdk._utils.coerce import coerce_tuple
class ChatFunctionResultMessageDict(TypedDict):
role: NotRequired[str]
tool_call_id: Required[str]
content: Required[str]
ChatCompletionsMessageType = Union[MessageType, ChatFunctionResultMessageDict, MessageInputType]
ChatMessageInputType = Union[ChatCompletionsMessageType, Iterable[ChatCompletionsMessageType]]
# pylint: disable-next=too-many-return-statements
def message_to_json(message: ChatCompletionsMessageType, tool_name_ids: dict[str, str]) -> JsonObject | list[JsonObject]:
if isinstance(message, str):
return {'role': 'user', 'content': message}
if isinstance(message, TextMessageProtocol):
if isinstance(message, TextMessageWithToolCallsProtocol) and message.tool_calls:
return {
'role': message.role,
'tool_calls': [
# pylint: disable-next=protected-access
tool_call._json_origin for tool_call in message.tool_calls
]
}
return {
"content": message.text,
"role": message.role,
}
if isinstance(message, dict):
text = message.get('text') or message.get('content', '')
assert isinstance(text, str)
if tool_call_id := message.get('tool_call_id'):
assert isinstance(tool_call_id, str)
message = cast(ChatFunctionResultMessageDict, message)
role = message.get('role', 'tool')
return {
'role': role,
'content': text,
'tool_call_id': tool_call_id,
}
if tool_calls := message.get('tool_calls'):
tool_calls = cast(JsonObject, tool_calls)
role = message.get('role', 'assistant')
return {
'tool_calls': tool_calls,
'role': role,
}
if text:
message = cast(TextMessageDict, message)
role = message.get('role', 'user')
return {
'content': text,
'role': role
}
if tool_results := message.get('tool_results'):
assert isinstance(tool_results, list)
message = cast(FunctionResultMessageDict, message)
role = message.get('role', 'tool')
result: list[JsonObject] = []
for tool_result in tool_results:
tool_result = cast(ToolResultDictType, tool_result)
name = tool_result['name']
content = tool_result['content']
id_ = tool_name_ids.get(name)
if not id_:
raise ValueError(
f'failed to find tool call with name "{name}" in previous messages for message {message}'
)
result.append({
'role': role,
'content': content,
'tool_call_id': id_,
})
return result
raise TypeError(f'{message=!r} should have a "text", "content" or "tool_call_id" key')
raise TypeError(f'{message=!r} should be str, dict with "text" or "tool_call_id" key or TextMessage instance')
def messages_to_json(messages: ChatMessageInputType) -> list[JsonObject]:
""":meta private:"""
msgs: tuple[ChatCompletionsMessageType, ...] = coerce_tuple(
messages,
(dict, str, TextMessageProtocol), # type: ignore[arg-type]
)
result: list[JsonObject] = []
last_tool_call_ids: dict[str, str] = {}
for message in msgs:
converted = message_to_json(message, last_tool_call_ids)
if isinstance(converted, list):
result.extend(converted)
continue
assert isinstance(converted, dict)
if tool_calls := converted.get('tool_calls'):
assert isinstance(tool_calls, list)
for tool_call in tool_calls:
assert isinstance(tool_call, dict)
id_ = tool_call.get('id')
assert isinstance(id_, str)
function = tool_call.get('function', {})
assert isinstance(function, dict)
name = function.get('name')
assert isinstance(name, str)
last_tool_call_ids[name] = id_
else:
last_tool_call_ids = {}
result.append(converted)
return result