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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
|
from builtins import list as _list
from pathlib import Path
from typing import Any, Optional
from uuid import UUID
import aiofiles
from shared.api.models import (
WrappedBooleanResponse,
WrappedConversationMessagesResponse,
WrappedConversationResponse,
WrappedConversationsResponse,
WrappedMessageResponse,
)
class ConversationsSDK:
def __init__(self, client):
self.client = client
async def create(
self,
name: Optional[str] = None,
) -> WrappedConversationResponse:
"""Create a new conversation.
Returns:
WrappedConversationResponse
"""
data: dict[str, Any] = {}
if name:
data["name"] = name
response_dict = await self.client._make_request(
"POST",
"conversations",
data=data,
version="v3",
)
return WrappedConversationResponse(**response_dict)
async def list(
self,
ids: Optional[list[str | UUID]] = None,
offset: Optional[int] = 0,
limit: Optional[int] = 100,
) -> WrappedConversationsResponse:
"""List conversations with pagination and sorting options.
Args:
ids (Optional[list[str | UUID]]): List of conversation IDs to retrieve
offset (int, optional): Specifies the number of objects to skip. Defaults to 0.
limit (int, optional): Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.
Returns:
WrappedConversationsResponse
"""
params: dict = {
"offset": offset,
"limit": limit,
}
if ids:
params["ids"] = ids
response_dict = await self.client._make_request(
"GET",
"conversations",
params=params,
version="v3",
)
return WrappedConversationsResponse(**response_dict)
async def retrieve(
self,
id: str | UUID,
) -> WrappedConversationMessagesResponse:
"""Get detailed information about a specific conversation.
Args:
id (str | UUID): The ID of the conversation to retrieve
Returns:
WrappedConversationMessagesResponse
"""
response_dict = await self.client._make_request(
"GET",
f"conversations/{str(id)}",
version="v3",
)
return WrappedConversationMessagesResponse(**response_dict)
async def update(
self,
id: str | UUID,
name: str,
) -> WrappedConversationResponse:
"""Update an existing conversation.
Args:
id (str | UUID): The ID of the conversation to update
name (str): The new name of the conversation
Returns:
WrappedConversationResponse
"""
data: dict[str, Any] = {
"name": name,
}
response_dict = await self.client._make_request(
"POST",
f"conversations/{str(id)}",
json=data,
version="v3",
)
return WrappedConversationResponse(**response_dict)
async def delete(
self,
id: str | UUID,
) -> WrappedBooleanResponse:
"""Delete a conversation.
Args:
id (str | UUID): The ID of the conversation to delete
Returns:
WrappedBooleanResponse
"""
response_dict = await self.client._make_request(
"DELETE",
f"conversations/{str(id)}",
version="v3",
)
return WrappedBooleanResponse(**response_dict)
async def add_message(
self,
id: str | UUID,
content: str,
role: str,
metadata: Optional[dict] = None,
parent_id: Optional[str] = None,
) -> WrappedMessageResponse:
"""Add a new message to a conversation.
Args:
id (str | UUID): The ID of the conversation to add the message to
content (str): The content of the message
role (str): The role of the message (e.g., "user" or "assistant")
parent_id (Optional[str]): The ID of the parent message
metadata (Optional[dict]): Additional metadata to attach to the message
Returns:
WrappedMessageResponse
"""
data: dict[str, Any] = {
"content": content,
"role": role,
}
if parent_id:
data["parent_id"] = parent_id
if metadata:
data["metadata"] = metadata
response_dict = await self.client._make_request(
"POST",
f"conversations/{str(id)}/messages",
json=data,
version="v3",
)
return WrappedMessageResponse(**response_dict)
async def update_message(
self,
id: str | UUID,
message_id: str,
content: Optional[str] = None,
metadata: Optional[dict] = None,
) -> WrappedMessageResponse:
"""Update an existing message in a conversation.
Args:
id (str | UUID): The ID of the conversation containing the message
message_id (str): The ID of the message to update
content (str): The new content of the message
metadata (dict): Additional metadata to attach to the message
Returns:
WrappedMessageResponse
"""
data: dict[str, Any] = {"content": content}
if metadata:
data["metadata"] = metadata
response_dict = await self.client._make_request(
"POST",
f"conversations/{str(id)}/messages/{message_id}",
json=data,
version="v3",
)
return WrappedMessageResponse(**response_dict)
async def export(
self,
output_path: str | Path,
columns: Optional[_list[str]] = None,
filters: Optional[dict] = None,
include_header: bool = True,
) -> None:
"""Export conversations to a CSV file, streaming the results directly
to disk.
Args:
output_path (str | Path): Local path where the CSV file should be saved
columns (Optional[list[str]]): Specific columns to export. If None, exports default columns
filters (Optional[dict]): Optional filters to apply when selecting conversations
include_header (bool): Whether to include column headers in the CSV (default: True)
Returns:
None
"""
# Convert path to string if it's a Path object
output_path = (
str(output_path) if isinstance(output_path, Path) else output_path
)
# Prepare request data
data: dict[str, Any] = {"include_header": include_header}
if columns:
data["columns"] = columns
if filters:
data["filters"] = filters
# Stream response directly to file
async with aiofiles.open(output_path, "wb") as f:
async with self.client.session.post(
f"{self.client.base_url}/v3/conversations/export",
json=data,
headers={
"Accept": "text/csv",
**self.client._get_auth_header(),
},
) as response:
if response.status != 200:
raise ValueError(
f"Export failed with status {response.status}",
response,
)
async for chunk in response.content.iter_chunks():
if chunk:
await f.write(chunk[0])
async def export_messages(
self,
output_path: str | Path,
columns: Optional[_list[str]] = None,
filters: Optional[dict] = None,
include_header: bool = True,
) -> None:
"""Export messages to a CSV file, streaming the results directly to
disk.
Args:
output_path (str | Path): Local path where the CSV file should be saved
columns (Optional[list[str]]): Specific columns to export. If None, exports default columns
filters (Optional[dict]): Optional filters to apply when selecting messages
include_header (bool): Whether to include column headers in the CSV (default: True)
Returns:
None
"""
# Convert path to string if it's a Path object
output_path = (
str(output_path) if isinstance(output_path, Path) else output_path
)
# Prepare request data
data: dict[str, Any] = {"include_header": include_header}
if columns:
data["columns"] = columns
if filters:
data["filters"] = filters
# Stream response directly to file
async with aiofiles.open(output_path, "wb") as f:
async with self.client.session.post(
f"{self.client.base_url}/v3/conversations/export_messages",
json=data,
headers={
"Accept": "text/csv",
**self.client._get_auth_header(),
},
) as response:
if response.status != 200:
raise ValueError(
f"Export failed with status {response.status}",
response,
)
async for chunk in response.content.iter_chunks():
if chunk:
await f.write(chunk[0])
|