|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/base64" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + |
| 10 | + "github.com/openai/openai-go" |
| 11 | +) |
| 12 | + |
| 13 | +func main() { |
| 14 | + client := openai.NewClient() |
| 15 | + ctx := context.Background() |
| 16 | + |
| 17 | + fmt.Println("Starting image streaming example...") |
| 18 | + |
| 19 | + stream := client.Images.GenerateStreaming(ctx, openai.ImageGenerateParams{ |
| 20 | + Model: openai.ImageModelGPTImage1, |
| 21 | + Prompt: "A cute baby sea otter", |
| 22 | + N: openai.Int(1), |
| 23 | + Size: openai.ImageGenerateParamsSize1024x1024, |
| 24 | + PartialImages: openai.Int(3), |
| 25 | + }) |
| 26 | + |
| 27 | + for stream.Next() { |
| 28 | + event := stream.Current() |
| 29 | + |
| 30 | + switch variant := event.AsAny().(type) { |
| 31 | + case openai.ImageGenPartialImageEvent: |
| 32 | + fmt.Printf(" Partial image %d/3 received\n", variant.PartialImageIndex+1) |
| 33 | + fmt.Printf(" Size: %d characters (base64)\n", len(variant.B64JSON)) |
| 34 | + |
| 35 | + // Save partial image to file |
| 36 | + filename := fmt.Sprintf("partial_%d.png", variant.PartialImageIndex+1) |
| 37 | + if err := saveBase64Image(variant.B64JSON, filename); err != nil { |
| 38 | + panic(fmt.Errorf("failed to save partial image: %w", err)) |
| 39 | + } |
| 40 | + absPath, _ := filepath.Abs(filename) |
| 41 | + fmt.Printf(" 💾 Saved to: %s\n", absPath) |
| 42 | + case openai.ImageGenCompletedEvent: |
| 43 | + fmt.Printf("\n✅ Final image completed!\n") |
| 44 | + fmt.Printf(" Size: %d characters (base64)\n", len(variant.B64JSON)) |
| 45 | + |
| 46 | + // Save final image to file |
| 47 | + filename := "final_image.png" |
| 48 | + if err := saveBase64Image(variant.B64JSON, filename); err != nil { |
| 49 | + panic(fmt.Errorf("failed to save final image: %w", err)) |
| 50 | + } |
| 51 | + absPath, _ := filepath.Abs(filename) |
| 52 | + fmt.Printf(" 💾 Saved to: %s\n", absPath) |
| 53 | + |
| 54 | + default: |
| 55 | + fmt.Printf("Received unknown event type: %+v\n", event) |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if err := stream.Err(); err != nil { |
| 60 | + panic(fmt.Errorf("error during streaming: %w", err)) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +func saveBase64Image(b64Data, filename string) error { |
| 65 | + imageData, err := base64.StdEncoding.DecodeString(b64Data) |
| 66 | + if err != nil { |
| 67 | + return fmt.Errorf("failed to decode base64: %w", err) |
| 68 | + } |
| 69 | + |
| 70 | + if err := os.WriteFile(filename, imageData, 0644); err != nil { |
| 71 | + return fmt.Errorf("failed to write file: %w", err) |
| 72 | + } |
| 73 | + |
| 74 | + return nil |
| 75 | +} |
0 commit comments