forked from mark3labs/mcphost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
76 lines (66 loc) · 1.75 KB
/
client.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 openai
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
)
type Client struct {
apiKey string
baseURL string
client *http.Client
}
func NewClient(apiKey string, baseURL string) *Client {
if baseURL == "" {
baseURL = "https://api.openai.com/v1"
} else if !strings.HasSuffix(baseURL, "/v1") {
baseURL = strings.TrimSuffix(baseURL, "/") + "/v1"
}
return &Client{
apiKey: apiKey,
baseURL: baseURL,
client: &http.Client{},
}
}
func (c *Client) CreateChatCompletion(ctx context.Context, req CreateRequest) (*APIResponse, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("error marshaling request: %w", err)
}
httpReq, err := http.NewRequestWithContext(
ctx,
"POST",
fmt.Sprintf("%s/chat/completions", c.baseURL),
bytes.NewReader(body),
)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
resp, err := c.client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var errResp struct {
Error struct {
Message string `json:"message"`
Type string `json:"type"`
Code string `json:"code"`
} `json:"error"`
}
if err := json.NewDecoder(resp.Body).Decode(&errResp); err != nil {
return nil, fmt.Errorf("error response with status %d", resp.StatusCode)
}
return nil, fmt.Errorf("%s: %s", errResp.Error.Type, errResp.Error.Message)
}
var response APIResponse
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil, fmt.Errorf("error decoding response: %w", err)
}
return &response, nil
}