-
Notifications
You must be signed in to change notification settings - Fork 0
/
openai.go
76 lines (66 loc) · 1.58 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
package ai
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
"github.com/pkg/errors"
)
type OpenAIProvider struct {
BaseProvider
}
func NewOpenAIProvider() (*OpenAIProvider, error) {
apiKey := os.Getenv("OPENAI_API_KEY")
if apiKey == "" {
return nil, fmt.Errorf("OPENAI_API_KEY environment variable is not set")
}
provider := &OpenAIProvider{
BaseProvider: BaseProvider{
APIKey: apiKey,
URL: "https://api.openai.com/v1/chat/completions",
},
}
provider.Model = provider.GetEnvOrDefault("OPENAI_MODEL", "gpt-4")
return provider, nil
}
func (p *OpenAIProvider) GenerateResponse(ctx context.Context, prompt string) (string, error) {
requestBody := map[string]interface{}{
"model": p.Model,
"messages": []map[string]string{
{"role": "user", "content": prompt},
},
}
details := RequestDetails{
URL: p.URL,
APIKey: p.APIKey,
RequestBody: requestBody,
}
options := ClientOptions{
Timeout: 30 * time.Second,
RetryAttempts: 3,
RetryDelay: time.Second,
}
responseBody, err := sendRequest(ctx, details, options)
if err != nil {
return "", err
}
var openAIResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
err = json.Unmarshal(responseBody, &openAIResp)
if err != nil {
return "", errors.Wrap(err, "error unmarshaling OpenAI response")
}
if len(openAIResp.Choices) == 0 {
return "", fmt.Errorf("no response from OpenAI")
}
return openAIResp.Choices[0].Message.Content, nil
}
func (p *OpenAIProvider) Name() string {
return "openai"
}