openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.103.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/image_stream.py

53lines · modeblame

a85ad051stainless-app[bot]11 months ago1#!/usr/bin/env python
2
3import base64
4from pathlib import Path
5
6from openai import OpenAI
7
8client = OpenAI()
9
10
11def main() -> None:
12"""Example of OpenAI image streaming with partial images."""
13stream = client.images.generate(
14model="gpt-image-1",
15prompt="A cute baby sea otter",
16n=1,
17size="1024x1024",
18stream=True,
19partial_images=3,
20)
21
22for event in stream:
23if event.type == "image_generation.partial_image":
24print(f" Partial image {event.partial_image_index + 1}/3 received")
25print(f" Size: {len(event.b64_json)} characters (base64)")
26
27# Save partial image to file
28filename = f"partial_{event.partial_image_index + 1}.png"
29image_data = base64.b64decode(event.b64_json)
30with open(filename, "wb") as f:
31f.write(image_data)
32print(f" 💾 Saved to: {Path(filename).resolve()}")
33
34elif event.type == "image_generation.completed":
35print(f"\n✅ Final image completed!")
36print(f" Size: {len(event.b64_json)} characters (base64)")
37
38# Save final image to file
39filename = "final_image.png"
40image_data = base64.b64decode(event.b64_json)
41with open(filename, "wb") as f:
42f.write(image_data)
43print(f" 💾 Saved to: {Path(filename).resolve()}")
44
45else:
46print(f"❓ Unknown event: {event}") # type: ignore[unreachable]
47
48
49if __name__ == "__main__":
50try:
51main()
52except Exception as error:
fd2c3f12David Meadows10 months ago53print(f"Error generating image: {error}")