aiweek-reconstruction/aichat/chat.go

71 lines
2.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package aichat
import (
"bytes"
"fmt"
"github.com/tidwall/gjson"
"io"
"log"
"net/http"
"strings"
)
type KimiResp string
type AiReq struct {
token string
body string
url string
}
const token = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyLWNlbnRlciIsImV4cCI6MTcyMzYyMTk1NywiaWF0IjoxNzE1ODQ1OTU3LCJqdGkiOiJjcDJybWg5a3FxNGxraGNqbTVtZyIsInR5cCI6InJlZnJlc2giLCJzdWIiOiJjbzU4anJxbG5sOTZlanF1czVnMCIsInNwYWNlX2lkIjoiY281OGpycWxubDk2ZWpxdXM1ZmciLCJhYnN0cmFjdF91c2VyX2lkIjoiY281OGpycWxubDk2ZWpxdXM1ZjAifQ.WNq2OH5egQKlnnuM4ygY2MjjmgsjhEOwHJdV7oQA66_mrHgGKluilcBuMZ5dMpClpAOnVY6wJ021dYHajzuInQ"
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{
token: token,
body: body,
url: url,
}
}
func (a *AiReq) StartChat(kimiUrl string) KimiResp {
// 定义 POST 请求的 URL
url := kimiUrl
// 创建一个带有 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)
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)
fmt.Println("body", wechatBody)
//wechatBody = strings.Replace(wechatBody, "\\n", "\n", -1)
//wechatBody = strings.Replace(wechatBody, "\\", "", -1)
//wechatBody = strings.Replace(wechatBody, "[", "", -1)
//wechatBody = strings.Replace(wechatBody, "]", "", -1)
//wechatBody = strings.Replace(wechatBody, "\"", "", 1)
return wechatBody
}