kefu/lib/coze.go

75 lines
1.7 KiB
Go
Raw Permalink Normal View History

2024-12-10 02:50:12 +00:00
package lib
import (
"bytes"
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
"io/ioutil"
"log"
"net/http"
)
type Coze struct {
BOT_ID, API_KEY string
}
type CozeCompletionMessage struct {
Role string `json:"role"`
Content string `json:"content"`
ContentType string `json:"content_type"`
Type string `json:"type"`
}
func (this *Coze) ChatCoze(conversation_id, user, query string, messages []CozeCompletionMessage) (string, error) {
url := "https://api.coze.cn/open_api/v2/chat"
// 构建请求参数
params := map[string]interface{}{
"conversation_id": conversation_id,
"bot_id": this.BOT_ID,
"user": user,
"query": query,
"chat_history": messages,
}
// 创建HTTP请求的body
jsonParams, err := json.Marshal(params)
requestBody := bytes.NewBuffer(jsonParams)
log.Println("coze扣子智能体:", string(jsonParams))
// 创建POST请求
req, err := http.NewRequest("POST", url, requestBody)
if err != nil {
fmt.Println("创建请求失败:", err)
return "", err
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+this.API_KEY)
// 发送请求
client := http.Client{}
response, err := client.Do(req)
if err != nil {
fmt.Println("发送请求失败:", err)
return "", err
}
defer response.Body.Close()
// 读取响应
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
respStr := string(responseBody)
log.Println("coze扣子智能体:", respStr)
content := ""
respArr := gjson.Get(respStr, "messages").Array()
for _, item := range respArr {
if item.Get("type").String() == "answer" {
content = item.Get("content").String()
}
}
return content, nil
}