docs
0
# Containers
1
2
Create and manage isolated file storage containers for organizing and sharing files. Containers provide a way to group related files together with configurable expiration policies.
3
4
## Capabilities
5
6
### Create Container
7
8
Create a new container for file storage.
9
10
```python { .api }
11
def create(
12
self,
13
*,
14
name: str,
15
expires_after: dict | Omit = omit,
16
file_ids: list[str] | Omit = omit,
17
extra_headers: dict[str, str] | None = None,
18
extra_query: dict[str, object] | None = None,
19
extra_body: dict[str, object] | None = None,
20
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
21
) -> Container:
22
"""
23
Create a container.
24
25
Args:
26
name: Name of the container to create. Used for identification.
27
28
expires_after: Container expiration time in seconds relative to anchor time.
29
Example: {"anchor": "created_at", "days": 7} expires 7 days after creation.
30
Default: containers persist until manually deleted.
31
32
file_ids: IDs of files to copy into the container at creation.
33
Files are copied, not moved - originals remain accessible.
34
35
extra_headers: Additional HTTP headers.
36
extra_query: Additional query parameters.
37
extra_body: Additional JSON fields.
38
timeout: Request timeout in seconds.
39
40
Returns:
41
Container: Created container object with unique ID.
42
43
Notes:
44
- Containers provide isolated file storage
45
- Files are copied into containers, not moved
46
- Expired containers are automatically cleaned up
47
"""
48
```
49
50
Usage examples:
51
52
```python
53
from openai import OpenAI
54
55
client = OpenAI()
56
57
# Create empty container
58
container = client.containers.create(
59
name="project-resources"
60
)
61
print(f"Created container: {container.id}")
62
63
# Create with files
64
container = client.containers.create(
65
name="training-data",
66
file_ids=["file-abc123", "file-def456"]
67
)
68
69
# Create with expiration
70
container = client.containers.create(
71
name="temp-files",
72
expires_after={
73
"anchor": "created_at",
74
"days": 1
75
}
76
)
77
78
# Create for specific project
79
container = client.containers.create(
80
name="customer-support-logs",
81
file_ids=["file-log1", "file-log2", "file-log3"],
82
expires_after={
83
"anchor": "created_at",
84
"days": 30
85
}
86
)
87
```
88
89
### Retrieve Container
90
91
Get a container by its ID.
92
93
```python { .api }
94
def retrieve(
95
self,
96
container_id: str,
97
*,
98
extra_headers: dict[str, str] | None = None,
99
extra_query: dict[str, object] | None = None,
100
extra_body: dict[str, object] | None = None,
101
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
102
) -> Container:
103
"""
104
Retrieve a container.
105
106
Args:
107
container_id: ID of the container to retrieve.
108
109
extra_headers: Additional HTTP headers.
110
extra_query: Additional query parameters.
111
extra_body: Additional JSON fields.
112
timeout: Request timeout in seconds.
113
114
Returns:
115
Container: Container object with metadata and file information.
116
"""
117
```
118
119
### List Containers
120
121
List all containers with pagination support.
122
123
```python { .api }
124
def list(
125
self,
126
*,
127
after: str | Omit = omit,
128
limit: int | Omit = omit,
129
order: Literal["asc", "desc"] | Omit = omit,
130
extra_headers: dict[str, str] | None = None,
131
extra_query: dict[str, object] | None = None,
132
extra_body: dict[str, object] | None = None,
133
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
134
) -> SyncCursorPage[Container]:
135
"""
136
List containers.
137
138
Args:
139
after: Cursor for pagination. Object ID defining your place in the list.
140
For instance, if you receive 100 objects ending with obj_foo,
141
use after=obj_foo to fetch the next page.
142
143
limit: Maximum number of objects to return. Range: 1-100. Default: 20.
144
145
order: Sort order by created_at timestamp.
146
- "asc": Ascending (oldest first)
147
- "desc": Descending (newest first, default)
148
149
extra_headers: Additional HTTP headers.
150
extra_query: Additional query parameters.
151
extra_body: Additional JSON fields.
152
timeout: Request timeout in seconds.
153
154
Returns:
155
SyncCursorPage[Container]: Paginated list of containers.
156
Supports iteration: for container in client.containers.list(): ...
157
"""
158
```
159
160
Usage examples:
161
162
```python
163
from openai import OpenAI
164
165
client = OpenAI()
166
167
# List all containers
168
for container in client.containers.list():
169
print(f"{container.name}: {container.id}")
170
171
# List with pagination
172
page = client.containers.list(limit=10)
173
for container in page:
174
print(f"{container.name} - Created: {container.created_at}")
175
176
# Get next page
177
if page.has_more:
178
next_page = client.containers.list(
179
limit=10,
180
after=page.data[-1].id
181
)
182
183
# List in ascending order (oldest first)
184
for container in client.containers.list(order="asc"):
185
print(container.name)
186
```
187
188
### Delete Container
189
190
Delete a container.
191
192
```python { .api }
193
def delete(
194
self,
195
container_id: str,
196
*,
197
extra_headers: dict[str, str] | None = None,
198
extra_query: dict[str, object] | None = None,
199
extra_body: dict[str, object] | None = None,
200
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
201
) -> None:
202
"""
203
Delete a container.
204
205
Args:
206
container_id: ID of the container to delete.
207
208
extra_headers: Additional HTTP headers.
209
extra_query: Additional query parameters.
210
extra_body: Additional JSON fields.
211
timeout: Request timeout in seconds.
212
213
Returns:
214
None: No content returned on successful deletion.
215
216
Notes:
217
- Deletion is permanent and cannot be undone
218
- Files within the container are not deleted
219
- Original files remain accessible outside the container
220
"""
221
```
222
223
### Container Files
224
225
Manage files within a container.
226
227
```python { .api }
228
# Access via client.containers.files
229
230
def create(
231
self,
232
container_id: str,
233
*,
234
file: FileTypes | Omit = omit,
235
file_id: str | Omit = omit,
236
extra_headers: dict[str, str] | None = None,
237
extra_query: dict[str, object] | None = None,
238
extra_body: dict[str, object] | None = None,
239
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
240
) -> FileCreateResponse:
241
"""
242
Add a file to a container.
243
244
Args:
245
container_id: ID of the container.
246
247
file: File content to upload directly. Provide either this OR file_id.
248
249
file_id: ID of an existing file to add. File is copied into container.
250
Provide either this OR file.
251
252
extra_headers: Additional HTTP headers.
253
extra_query: Additional query parameters.
254
extra_body: Additional JSON fields.
255
timeout: Request timeout in seconds.
256
257
Returns:
258
FileCreateResponse: File reference within the container.
259
260
Notes:
261
- Provide either `file` (for direct upload) OR `file_id` (for reference)
262
- When using file_id, file is copied, not moved
263
- Original file remains accessible
264
- Same file can be in multiple containers
265
"""
266
267
def retrieve(
268
self,
269
container_id: str,
270
file_id: str,
271
*,
272
extra_headers: dict[str, str] | None = None,
273
extra_query: dict[str, object] | None = None,
274
extra_body: dict[str, object] | None = None,
275
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
276
) -> ContainerFile:
277
"""
278
Retrieve a file from a container.
279
280
Args:
281
container_id: ID of the container.
282
file_id: ID of the file to retrieve.
283
284
extra_headers: Additional HTTP headers.
285
extra_query: Additional query parameters.
286
extra_body: Additional JSON fields.
287
timeout: Request timeout in seconds.
288
289
Returns:
290
ContainerFile: File information and metadata.
291
"""
292
293
def list(
294
self,
295
container_id: str,
296
*,
297
after: str | Omit = omit,
298
limit: int | Omit = omit,
299
order: Literal["asc", "desc"] | Omit = omit,
300
extra_headers: dict[str, str] | None = None,
301
extra_query: dict[str, object] | None = None,
302
extra_body: dict[str, object] | None = None,
303
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
304
) -> SyncCursorPage[ContainerFile]:
305
"""
306
List files in a container.
307
308
Args:
309
container_id: ID of the container.
310
311
after: Cursor for pagination.
312
313
limit: Maximum number of files to return. Range: 1-100. Default: 20.
314
315
order: Sort order by created_at timestamp ("asc" or "desc").
316
317
extra_headers: Additional HTTP headers.
318
extra_query: Additional query parameters.
319
extra_body: Additional JSON fields.
320
timeout: Request timeout in seconds.
321
322
Returns:
323
SyncCursorPage[ContainerFile]: Paginated list of files.
324
"""
325
326
def delete(
327
self,
328
container_id: str,
329
file_id: str,
330
*,
331
extra_headers: dict[str, str] | None = None,
332
extra_query: dict[str, object] | None = None,
333
extra_body: dict[str, object] | None = None,
334
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
335
) -> None:
336
"""
337
Remove a file from a container.
338
339
Args:
340
container_id: ID of the container.
341
file_id: ID of the file to remove.
342
343
extra_headers: Additional HTTP headers.
344
extra_query: Additional query parameters.
345
extra_body: Additional JSON fields.
346
timeout: Request timeout in seconds.
347
348
Returns:
349
None: No content returned on successful removal.
350
351
Notes:
352
- Removes file from container only
353
- Original file is not deleted
354
- File remains accessible outside container
355
"""
356
```
357
358
### Container File Content
359
360
Retrieve the binary content of a file stored in a container.
361
362
```python { .api }
363
# Access via client.containers.files.content
364
365
def retrieve(
366
self,
367
file_id: str,
368
*,
369
container_id: str,
370
extra_headers: dict[str, str] | None = None,
371
extra_query: dict[str, object] | None = None,
372
extra_body: dict[str, object] | None = None,
373
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
374
) -> HttpxBinaryResponseContent:
375
"""
376
Retrieve the binary content of a container file.
377
378
Args:
379
file_id: ID of the file to retrieve content from.
380
381
container_id: ID of the container containing the file.
382
383
extra_headers: Additional HTTP headers.
384
extra_query: Additional query parameters.
385
extra_body: Additional JSON fields.
386
timeout: Request timeout in seconds.
387
388
Returns:
389
HttpxBinaryResponseContent: Binary content of the file.
390
Can be written to disk or processed in memory.
391
392
Notes:
393
- Returns raw binary data
394
- Suitable for downloading file contents
395
- Use .read() or .iter_bytes() to access content
396
"""
397
```
398
399
Usage example:
400
401
```python
402
from openai import OpenAI
403
404
client = OpenAI()
405
406
# Retrieve file content from container
407
content = client.containers.files.content.retrieve(
408
container_id="container-abc123",
409
file_id="file-def456"
410
)
411
412
# Save to disk
413
with open("downloaded_file.pdf", "wb") as f:
414
f.write(content.read())
415
416
# Or process in chunks
417
for chunk in content.iter_bytes(chunk_size=8192):
418
# Process chunk
419
pass
420
```
421
422
Complete workflow example:
423
424
```python
425
from openai import OpenAI
426
427
client = OpenAI()
428
429
# 1. Upload some files first
430
file1 = client.files.create(
431
file=open("document1.pdf", "rb"),
432
purpose="assistants"
433
)
434
435
file2 = client.files.create(
436
file=open("document2.pdf", "rb"),
437
purpose="assistants"
438
)
439
440
# 2. Create container with one file
441
container = client.containers.create(
442
name="project-docs",
443
file_ids=[file1.id],
444
expires_after={
445
"anchor": "created_at",
446
"days": 7
447
}
448
)
449
450
print(f"Created container: {container.id}")
451
452
# 3. Add another file to container
453
client.containers.files.create(
454
container_id=container.id,
455
file_id=file2.id
456
)
457
458
# 4. List all files in container
459
print("Files in container:")
460
for file in client.containers.files.list(container_id=container.id):
461
print(f" - {file.id}")
462
463
# 5. Retrieve specific file from container
464
file_info = client.containers.files.retrieve(
465
container_id=container.id,
466
file_id=file1.id
467
)
468
print(f"File info: {file_info}")
469
470
# 6. Remove a file from container
471
client.containers.files.delete(
472
container_id=container.id,
473
file_id=file1.id
474
)
475
476
# 7. Verify removal
477
remaining_files = client.containers.files.list(container_id=container.id)
478
print(f"Remaining files: {len(remaining_files.data)}")
479
480
# 8. List all containers
481
print("\nAll containers:")
482
for c in client.containers.list():
483
print(f" {c.name} ({c.id})")
484
485
# 9. Clean up - delete container
486
client.containers.delete(container_id=container.id)
487
488
# Note: Original files still exist
489
retrieved_file = client.files.retrieve(file_id=file1.id)
490
print(f"Original file still exists: {retrieved_file.id}")
491
```
492
493
Organizing files by project:
494
495
```python
496
from openai import OpenAI
497
498
client = OpenAI()
499
500
# Create containers for different projects
501
ml_container = client.containers.create(
502
name="machine-learning-project"
503
)
504
505
web_container = client.containers.create(
506
name="web-development-project"
507
)
508
509
# Upload and organize files
510
ml_file = client.files.create(
511
file=open("model_training.py", "rb"),
512
purpose="assistants"
513
)
514
515
web_file = client.files.create(
516
file=open("api_docs.md", "rb"),
517
purpose="assistants"
518
)
519
520
# Add files to appropriate containers
521
client.containers.files.create(
522
container_id=ml_container.id,
523
file_id=ml_file.id
524
)
525
526
client.containers.files.create(
527
container_id=web_container.id,
528
file_id=web_file.id
529
)
530
531
# Later: access files by project
532
print("ML Project Files:")
533
for file in client.containers.files.list(container_id=ml_container.id):
534
print(f" - {file.id}")
535
536
print("Web Project Files:")
537
for file in client.containers.files.list(container_id=web_container.id):
538
print(f" - {file.id}")
539
```
540
541
## Async Usage
542
543
```python
544
import asyncio
545
from openai import AsyncOpenAI
546
547
async def manage_containers():
548
client = AsyncOpenAI()
549
550
# Create container
551
container = await client.containers.create(
552
name="async-project",
553
expires_after={"anchor": "created_at", "days": 1}
554
)
555
556
# Add file
557
await client.containers.files.create(
558
container_id=container.id,
559
file_id="file-abc123"
560
)
561
562
# List files
563
async for file in await client.containers.files.list(
564
container_id=container.id
565
):
566
print(f"File: {file.id}")
567
568
# Delete container
569
await client.containers.delete(container_id=container.id)
570
571
asyncio.run(manage_containers())
572
```
573
574
## Types
575
576
```python { .api }
577
from typing import Literal
578
from pydantic import BaseModel
579
580
class Container(BaseModel):
581
"""Container object for file organization."""
582
id: str
583
created_at: int
584
name: str
585
object: Literal["container"]
586
expires_at: int | None # Present if expiration configured
587
file_count: int | None # Number of files in container
588
589
class ContainerFile(BaseModel):
590
"""File reference within a container."""
591
id: str
592
container_id: str
593
file_id: str
594
created_at: int
595
object: Literal["container.file"]
596
597
class SyncCursorPage[T]:
598
"""Cursor-based pagination."""
599
data: list[T]
600
has_more: bool
601
def __iter__(self) -> Iterator[T]: ...
602
603
class Omit:
604
"""Sentinel value for omitted parameters."""
605
606
class HttpxBinaryResponseContent:
607
"""Binary response content from HTTP requests."""
608
def read(self) -> bytes: ...
609
def iter_bytes(self, chunk_size: int = ...) -> Iterator[bytes]: ...
610
```
611
612
## Access Pattern
613
614
```python
615
# Synchronous
616
from openai import OpenAI
617
client = OpenAI()
618
client.containers.create(...)
619
client.containers.retrieve(...)
620
client.containers.list(...)
621
client.containers.delete(...)
622
client.containers.files.create(...)
623
client.containers.files.retrieve(...)
624
client.containers.files.list(...)
625
client.containers.files.delete(...)
626
client.containers.files.content.retrieve(...)
627
628
# Asynchronous
629
from openai import AsyncOpenAI
630
client = AsyncOpenAI()
631
await client.containers.create(...)
632
await client.containers.retrieve(...)
633
await client.containers.list(...)
634
await client.containers.delete(...)
635
await client.containers.files.create(...)
636
await client.containers.files.retrieve(...)
637
await client.containers.files.list(...)
638
await client.containers.files.delete(...)
639
await client.containers.files.content.retrieve(...)
640
```
641