-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
72 lines (62 loc) · 1.78 KB
/
Copy pathclient.go
File metadata and controls
72 lines (62 loc) · 1.78 KB
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func NewOpenAIClient(apiKey string) *OpenAIClient {
return &OpenAIClient{APIKey: apiKey}
}
func (c *OpenAIClient) CreateResponse(req ResponseRequest) (ResponseBody, error) {
var resp ResponseBody
reqBody, err := json.Marshal(req)
if err != nil {
return resp, err
}
httpReq, err := http.NewRequest("POST", "https://api.openai.com/v1/responses", bytes.NewBuffer(reqBody))
if err != nil {
return resp, err
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.APIKey))
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return resp, err
}
defer httpResp.Body.Close()
var respBody []byte
respBody, err = io.ReadAll(httpResp.Body)
if err != nil {
return resp, err
}
// for debugging
// fmt.Printf("%s", respBody)
// fmt.Printf("Status Code: %d\n", httpResp.StatusCode)
switch httpResp.StatusCode {
case http.StatusBadRequest:
var errorResponse map[string]string
err = json.Unmarshal(respBody, &errorResponse)
if err != nil {
return resp, fmt.Errorf("failed to unmarshal 400 error response: %v", err)
}
return resp, fmt.Errorf("400 Bad Request: %v", errorResponse["error"])
case http.StatusOK:
var incompleteResponse map[string]interface{}
err = json.Unmarshal(respBody, &incompleteResponse)
if err != nil {
return resp, err
}
if status, ok := incompleteResponse["status"].(string); ok && status == "incomplete" {
return resp, fmt.Errorf("incomplete response: %v", incompleteResponse["incomplete_details"])
}
err = json.Unmarshal(respBody, &resp)
if err != nil {
return resp, err
}
return resp, nil
default:
return resp, fmt.Errorf("non-OK response code: %d", httpResp.StatusCode)
}
}