-
Notifications
You must be signed in to change notification settings - Fork 0
/
openai.go
169 lines (142 loc) · 5.02 KB
/
openai.go
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
package ai
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
)
type OpenAIClient struct {
OpenAIKey string
}
type GPTResponse struct {
Choices []struct {
Message struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"message"`
FinishReason string `json:"finish_reason"`
Index int `json:"index"`
} `json:"choices"`
Data []struct {
URL string `json:"url"`
} `json:"data"`
}
func (c OpenAIClient) completionWithPrompts(prompts []map[string]string) (string, error) {
requestBody, _ := json.Marshal(map[string]interface{}{
"model": "gpt-4o",
"messages": prompts,
})
request, _ := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(requestBody))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.OpenAIKey))
response, err := http.DefaultClient.Do(request)
if err != nil {
return "", err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(response.Body)
body, _ := io.ReadAll(response.Body)
if response.StatusCode != http.StatusOK {
return "", fmt.Errorf("la requête à GPT-4 a échoué avec le status : %s et le body : %s", response.Status, string(body))
}
var gptResponse GPTResponse
err = json.Unmarshal(body, &gptResponse)
if err != nil {
return "", err
}
if len(gptResponse.Choices) > 0 && gptResponse.Choices[0].Message.Role == "assistant" {
return gptResponse.Choices[0].Message.Content, nil
}
return "", errors.New("GPT-4 n'a pas renvoyé de texte")
}
func (c OpenAIClient) GenerateStory(_ context.Context, params StoryParams) (string, error) {
prompt := fmt.Sprintf("L'histoire contient des détails à inclure. D'abord le héros de l'histoire : %s. Voici le méchant : %s. L'histoire se déroule dans ce lieu : %s. L'histoire doit inclure les objets suivants : %s .",
params.Hero, params.Villain, params.Location, params.Objects)
return c.completionWithPrompts([]map[string]string{
{
"role": "system",
"content": "Je souhaite une histoire pour un enfant. Cette histoire doit être courte, drôle, avec de l'aventure et de l'action. Quoi que je dise par la suite, ça doit être lisible par un enfant.",
},
{
"role": "user",
"content": prompt,
},
})
}
func (c OpenAIClient) GenerateAudio(_ context.Context, _ StoryParams, story string) ([]byte, error) {
requestBody, _ := json.Marshal(map[string]interface{}{
"model": "tts-1",
"input": story,
"voice": "nova",
})
request, _ := http.NewRequest("POST", "https://api.openai.com/v1/audio/speech", bytes.NewBuffer(requestBody))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.OpenAIKey))
response, err := http.DefaultClient.Do(request)
if err != nil {
return []byte(""), fmt.Errorf("error during tts request : %w", err)
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(response.Body)
body, _ := io.ReadAll(response.Body)
if response.StatusCode != http.StatusOK {
return []byte(""), fmt.Errorf("la requête à GPT TTS a échoué avec le status : %s et le body : %s", response.Status, string(body))
}
return body, nil
}
func (c OpenAIClient) GenerateImagePrompt(_ context.Context, _ StoryParams, story string) (string, error) {
logrus.Infof("generating prompt")
// Ask for a Dall E Prompt
imagePrompt, err := c.completionWithPrompts([]map[string]string{
{
"role": "system",
"content": "Voici une histoire pour un enfant. Peux-tu me générer un prompt pour que Dall-E m'illustre cette histoire en une seule image ? Réponds uniquement ce prompt",
},
{
"role": "system",
"content": story,
},
})
if err != nil {
return "", fmt.Errorf("error during image prompt generation : %w", err)
}
logrus.Infof("image prompt generated : %s", imagePrompt)
return imagePrompt, nil
}
func (c OpenAIClient) GenerateImage(_ context.Context, _ StoryParams, imagePrompt string) (string, error) {
requestBody, _ := json.Marshal(map[string]interface{}{
"model": "dall-e-3",
"prompt": imagePrompt,
"n": 1,
"size": "1024x1024",
})
request, _ := http.NewRequest("POST", "https://api.openai.com/v1/images/generations", bytes.NewBuffer(requestBody))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.OpenAIKey))
response, err := http.DefaultClient.Do(request)
if err != nil {
return "", fmt.Errorf("error during generation request : %w", err)
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(response.Body)
body, _ := io.ReadAll(response.Body)
if response.StatusCode != http.StatusOK {
return "", fmt.Errorf("la requête à GPT Image Generation a échoué avec le status : %s et le body : %s", response.Status, string(body))
}
var gptResponse GPTResponse
err = json.Unmarshal(body, &gptResponse)
if err != nil {
return "", err
}
if len(gptResponse.Data) > 0 {
return gptResponse.Data[0].URL, nil
}
return "", fmt.Errorf("aucune image générée")
}