aiweek-reconstruction/aichat/chat.go

62 lines
1.5 KiB
Go
Raw Normal View History

2024-05-18 01:46:35 +08:00
package aichat
import (
2024-05-20 01:00:09 +08:00
"aiweek/option"
2024-05-18 01:46:35 +08:00
"bytes"
"fmt"
"github.com/tidwall/gjson"
"io"
"log"
"net/http"
"strings"
)
type KimiResp string
type AiReq struct {
token string
body string
}
func NewAiReq(url string) *AiReq {
body := fmt.Sprintf("{\"model\":\"kimi\",\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"file\",\"file_url\":{\"url\":\"%s\"}},{\"type\":\"text\",\"text\":\"帮忙分析下工单中的错别字告诉我对应的工单id\"}]}],\"use_search\":false}", url)
return &AiReq{
2024-05-20 01:00:09 +08:00
token: option.MODEL_TOKEN,
2024-05-18 01:46:35 +08:00
body: body,
}
}
2024-05-20 01:00:09 +08:00
func (a *AiReq) StartChat(url string) KimiResp {
2024-05-18 01:46:35 +08:00
// 定义 POST 请求的 URL
// 创建一个带有 JSON 负载的 POST 请求
payload := []byte(a.body) // 根据需要修改 JSON 负载
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
if err != nil {
log.Fatal(err)
}
// 添加 Token 到请求头
req.Header.Add("Authorization", "Bearer "+a.token)
// 设置 Content-Type 为 application/json
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
2024-05-20 01:00:09 +08:00
log.Println(KimiResp(body))
2024-05-18 01:46:35 +08:00
return KimiResp(body)
}
func (k KimiResp) PrepareWechatBody() string {
wechatBody := gjson.Get(string(k), "choices.#.message.content").String()
r := strings.NewReplacer("\\n", "\n", "\\", "", "[", "", "]", "", "\"", "")
wechatBody = r.Replace(wechatBody)
return wechatBody
}