-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgigachat.go
More file actions
191 lines (179 loc) · 5.37 KB
/
gigachat.go
File metadata and controls
191 lines (179 loc) · 5.37 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Package gigachat Предоставляет доступ Gigachat
//
// Этот пакет сделан для того чтоб спрашивать у нейросети gigachat от сбера.
// Так и делать embedding
package gigachat
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"io"
"log"
"log/slog"
"net/http"
)
type Gigachat struct {
ApiHost string
RepetitionPenalty int
TopP float32
Model string
MaxTokens int
Temperature float32
AuthData string
Functions []Function
}
func NewGigachat() *Gigachat {
return &Gigachat{
ApiHost: GigaChatApiHost,
RepetitionPenalty: 1,
TopP: 1.0,
Model: GigaChatModel,
MaxTokens: GigaChatMaxTokens,
Temperature: 1,
AuthData: "",
Functions: []Function{},
}
}
func (g *Gigachat) getRequestUrl(path string) string {
return "https://" + g.ApiHost + GigaChatApiPath + path
}
func (g *Gigachat) getRequest(url string) (*http.Request, error) {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
request.Header.Set("Accept", "application/json")
request.Header.Set("Authorization", "Bearer "+g.getCurrentToken())
return request, nil
}
// Создаем POST запрос к API
func (g *Gigachat) postRequest(url string, body io.Reader) (*http.Request, error) {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
request, err := http.NewRequest("POST", url, body)
request.Header.Add("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
request.Header.Set("Authorization", "Bearer "+g.getCurrentToken())
if err != nil {
return nil, err
}
return request, nil
}
// GetModels Получить список моделей.
func (g *Gigachat) GetModels() ([]ModelItem, error) {
url := g.getRequestUrl(GigaChatModelsPath)
request, err := g.getRequest(url)
if err != nil {
return nil, err
}
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusOK {
return nil, errors.New("Response status: " + string(response.Status))
}
body, err := io.ReadAll(response.Body)
defer response.Body.Close()
var result ModelsResponse
err2 := json.Unmarshal(body, &result)
if err2 != nil {
log.Fatal(err2)
}
return result.Data, nil
}
// Embeddings получить вектора текста. Ограничение по количеству что-то типа 512.
func (g *Gigachat) Embeddings(input string) ([]float32, error) {
url := g.getRequestUrl(GigaChatEmbeddingsPath)
var inputs []string
inputs = append(inputs, input)
jData, errJsonRequestEncode := json.Marshal(&EmbeddingsRequest{
Model: "Embeddings",
Input: inputs,
})
if errJsonRequestEncode != nil {
return nil, errJsonRequestEncode
}
request, err := g.postRequest(url, bytes.NewReader(jData))
if err != nil {
return nil, err
}
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusOK {
body, _ := io.ReadAll(response.Body)
defer response.Body.Close()
return nil, errors.New("Response status: " + string(response.Status) + " " + string(body))
}
body, err := io.ReadAll(response.Body)
defer response.Body.Close()
var result EmbeddingsResponse
err = json.Unmarshal(body, &result)
return result.Data[0].Embedding, nil
}
// Получить функции
func (g *Gigachat) getFunctions() []Function {
return g.Functions
}
// ChatCompletions Сдалать запрос к модели.
func (g *Gigachat) ChatCompletions(messages []MessageRequest) (ChatCompletionResponse, error) {
url := g.getRequestUrl(GigaChatChatCompletionPath)
chatRequest := ChatCompletionRequest{
Model: g.Model,
MaxTokens: g.MaxTokens,
Temperature: g.Temperature,
Messages: messages,
Stream: false,
RepetitionPenalty: g.RepetitionPenalty,
TopP: g.TopP,
UpdateInterval: 0,
}
if len(g.getFunctions()) > 0 {
chatRequest.FunctionCall = GigaChatFunctionCallModeAuto
chatRequest.Functions = g.getFunctions()
}
jData, errJsonRequestEncode := json.Marshal(&chatRequest)
slog.Info("jData:", jData)
if errJsonRequestEncode != nil {
return ChatCompletionResponse{}, errJsonRequestEncode
}
request, err := g.postRequest(url, bytes.NewReader(jData))
if err != nil {
return ChatCompletionResponse{}, err
}
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return ChatCompletionResponse{}, err
}
if response.StatusCode != http.StatusOK {
return ChatCompletionResponse{}, errors.New("Response status: " + string(response.Status))
}
body, err := io.ReadAll(response.Body)
slog.Info("body:", body)
defer response.Body.Close()
var result ChatCompletionResponse
err = json.Unmarshal(body, &result)
if err != nil {
slog.Error("Json Unmarshal error:", err)
}
return result, nil
}
// Ask Просто спросить у модели
func (g *Gigachat) Ask(input string) (string, error) {
result, err := g.ChatCompletions([]MessageRequest{
{
Role: GigaChatRoleUser,
Content: input,
},
})
if err != nil {
return "", err
}
return result.Choices[0].Message.Content, nil
}