-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathendpoints.go
76 lines (64 loc) · 2.24 KB
/
endpoints.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 copilot
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
func ChatCompletions(ctx context.Context, integrationID, apiKey string, req *ChatCompletionsRequest) (io.ReadCloser, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.githubcopilot.com/chat/completions", bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+apiKey)
if integrationID != "" {
httpReq.Header.Set("Copilot-Integration-Id", integrationID)
}
resp, err := (&http.Client{}).Do(httpReq)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
fmt.Println(string(b))
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return resp.Body, nil
}
func Embeddings(ctx context.Context, integrationID string, token string, req *EmbeddingsRequest) (*EmbeddingsResponse, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.githubcopilot.com/embeddings", bytes.NewReader(body))
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+token)
if integrationID != "" {
httpReq.Header.Set("Copilot-Integration-Id", integrationID)
}
resp, err := (&http.Client{}).Do(httpReq)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
fmt.Println(string(b))
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
var embeddingsResponse *EmbeddingsResponse
err = json.NewDecoder(resp.Body).Decode(&embeddingsResponse)
if err != nil {
return nil, fmt.Errorf("failed to decode request body")
}
return embeddingsResponse, nil
}