Skip to content

Commit

Permalink
Added an example of image generation using DALL-E (sashabaranov#168)
Browse files Browse the repository at this point in the history
* add "name" property for ChatCompletionMessage

* added a comment to the "Name" property

* Added an example of image generation using DALL-E

---------

Co-authored-by: Contantine A <avdeev@embria.com>
  • Loading branch information
fussraider and Contantine A authored Mar 16, 2023
1 parent abffece commit 3c8be76
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,86 @@ func main() {
```
</details>

<details>
<summary>DALL-E 2 image generation</summary>

```go
package main

import (
"bytes"
"context"
"encoding/base64"
"fmt"
openai "github.com/sashabaranov/go-openai"
"image/png"
"os"
)

func main() {
c := openai.NewClient("your token")
ctx := context.Background()

// Sample image by link
reqUrl := openai.ImageRequest{
Prompt: "Parrot on a skateboard performs a trick, cartoon style, natural light, high detail",
Size: openai.CreateImageSize256x256,
ResponseFormat: openai.CreateImageResponseFormatURL,
N: 1,
}

respUrl, err := c.CreateImage(ctx, reqUrl)
if err != nil {
fmt.Printf("Image creation error: %v\n", err)
return
}
fmt.Println(respUrl.Data[0].URL)

// Example image as base64
reqBase64 := openai.ImageRequest{
Prompt: "Portrait of a humanoid parrot in a classic costume, high detail, realistic light, unreal engine",
Size: openai.CreateImageSize256x256,
ResponseFormat: openai.CreateImageResponseFormatB64JSON,
N: 1,
}

respBase64, err := c.CreateImage(ctx, reqBase64)
if err != nil {
fmt.Printf("Image creation error: %v\n", err)
return
}

imgBytes, err := base64.StdEncoding.DecodeString(respBase64.Data[0].B64JSON)
if err != nil {
fmt.Printf("Base64 decode error: %v\n", err)
return
}

r := bytes.NewReader(imgBytes)
imgData, err := png.Decode(r)
if err != nil {
fmt.Printf("PNG decode error: %v\n", err)
return
}

file, err := os.Create("image.png")
if err != nil {
fmt.Printf("File creation error: %v\n", err)
return
}
defer file.Close()

if err := png.Encode(file, imgData); err != nil {
fmt.Printf("PNG encode error: %v\n", err)
return
}

fmt.Println("The image was saved as example.png")
}

```
</details>

<details>
<summary>Configuring proxy</summary>

Expand Down

0 comments on commit 3c8be76

Please sign in to comment.