-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathchat.go
71 lines (59 loc) · 1.74 KB
/
chat.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
package gigachat
import (
"bytes"
"context"
"encoding/json"
"net/http"
)
type ChatRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Temperature *float64 `json:"temperature"`
TopP *float64 `json:"top_p"`
N *int64 `json:"n"`
Stream *bool `json:"stream"`
MaxTokens *int64 `json:"max_tokens"`
RepetitionPenalty *float64 `json:"repetition_penalty"`
UpdateInterval *int64 `json:"update_interval"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ChatResponse struct {
Model string `json:"model"`
Created int64 `json:"created"`
Method string `json:"object"`
Choices []Choice `json:"choices"`
Usage Usage `json:"usage"`
}
type Choice struct {
Index int64 `json:"index"`
FinishReason string `json:"finish_reason"`
Message Message
}
type Usage struct {
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
TotalTokens int64 `json:"total_tokens"`
}
func (c *Client) Chat(in *ChatRequest) (*ChatResponse, error) {
return c.ChatWithContext(context.Background(), in)
}
func (c *Client) ChatWithContext(ctx context.Context, in *ChatRequest) (*ChatResponse, error) {
reqBytes, _ := json.Marshal(in)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.config.BaseUrl+ChatPath, bytes.NewReader(reqBytes))
if err != nil {
return nil, err
}
res, err := c.sendRequest(ctx, req)
if err != nil {
return nil, err
}
defer res.Body.Close()
var chatResponse ChatResponse
if err := json.NewDecoder(res.Body).Decode(&chatResponse); err != nil {
return nil, err
}
return &chatResponse, nil
}