83 lines
1.6 KiB
Go
83 lines
1.6 KiB
Go
package worker
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
var client *http.Client
|
|
|
|
// 初始化
|
|
func InitReq() {
|
|
client = &http.Client{}
|
|
}
|
|
|
|
// 发起post请求
|
|
func Post(url string, bodyType string, body string) (*http.Response, error) {
|
|
req, err := http.NewRequest("POST", url, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Content-Type", bodyType)
|
|
req.Body = io.NopCloser(strings.NewReader(body))
|
|
return client.Do(req)
|
|
}
|
|
|
|
// 发送到机器人
|
|
func SendToRobot(url string, body string) (map[string]interface{}, error) {
|
|
resp, err := Post(url, "application/json", body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
m := make(map[string]interface{})
|
|
err = json.NewDecoder(resp.Body).Decode(&m)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
// 生成补全的函数
|
|
func GenerateCompletion(url, prompt string, model string) (map[string]interface{}, error) {
|
|
data := map[string]interface{}{
|
|
"model": model,
|
|
"prompt": prompt,
|
|
"stream": false,
|
|
}
|
|
jsonData, err := json.Marshal(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
client_ := &http.Client{}
|
|
resp, err := client_.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var result map[string]interface{}
|
|
err = json.Unmarshal(body, &result)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return result, nil
|
|
}
|