85 lines
2.2 KiB
Go
85 lines
2.2 KiB
Go
package system
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"strings"
|
||
|
||
"github.com/go-kratos/kratos/v2/log"
|
||
"kra/internal/conf"
|
||
)
|
||
|
||
// AutoCodeLLMUsecase LLM用例
|
||
type AutoCodeLLMUsecase struct {
|
||
config *conf.AutoCodeLLMConfig
|
||
log *log.Helper
|
||
}
|
||
|
||
// NewAutoCodeLLMUsecase 创建LLM用例
|
||
func NewAutoCodeLLMUsecase(config *conf.AutoCodeLLMConfig, logger log.Logger) *AutoCodeLLMUsecase {
|
||
return &AutoCodeLLMUsecase{
|
||
config: config,
|
||
log: log.NewHelper(logger),
|
||
}
|
||
}
|
||
|
||
// LLMResponse LLM响应结构
|
||
type LLMResponse struct {
|
||
Code int `json:"code"`
|
||
Msg string `json:"msg"`
|
||
Data interface{} `json:"data"`
|
||
}
|
||
|
||
// LLMAuto 调用大模型服务,返回生成结果数据
|
||
// 入参为通用 JSONMap,需包含 mode(例如 ai/butler/eye/painter 等)以及业务 prompt/payload
|
||
func (uc *AutoCodeLLMUsecase) LLMAuto(ctx context.Context, llm map[string]interface{}) (interface{}, error) {
|
||
if uc.config.AiPath == "" {
|
||
return nil, errors.New("请先前往插件市场个人中心获取AiPath并填入配置文件中")
|
||
}
|
||
|
||
// 构建调用路径:{AiPath} 中的 {FUNC} 由 mode 替换
|
||
mode := fmt.Sprintf("%v", llm["mode"])
|
||
path := strings.ReplaceAll(uc.config.AiPath, "{FUNC}", fmt.Sprintf("api/chat/%s", mode))
|
||
|
||
// 构建请求体
|
||
body, err := json.Marshal(llm)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("序列化请求失败: %w", err)
|
||
}
|
||
|
||
// 发送HTTP请求
|
||
req, err := http.NewRequestWithContext(ctx, "POST", path, strings.NewReader(string(body)))
|
||
if err != nil {
|
||
return nil, fmt.Errorf("创建请求失败: %w", err)
|
||
}
|
||
req.Header.Set("Content-Type", "application/json")
|
||
|
||
client := &http.Client{}
|
||
res, err := client.Do(req)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("大模型生成失败: %w", err)
|
||
}
|
||
defer res.Body.Close()
|
||
|
||
// 读取响应
|
||
b, err := io.ReadAll(res.Body)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("读取大模型响应失败: %w", err)
|
||
}
|
||
|
||
var resStruct LLMResponse
|
||
if err = json.Unmarshal(b, &resStruct); err != nil {
|
||
return nil, fmt.Errorf("解析大模型响应失败: %w", err)
|
||
}
|
||
|
||
if resStruct.Code == 7 { // 业务约定:7 表示模型生成失败
|
||
return nil, fmt.Errorf("大模型生成失败: %s", resStruct.Msg)
|
||
}
|
||
|
||
return resStruct.Data, nil
|
||
}
|