75 lines
2.0 KiB
Go
75 lines
2.0 KiB
Go
package service
|
||
|
||
import (
|
||
"context"
|
||
"eino-project/internal/domain/agent"
|
||
"eino-project/internal/domain/llm"
|
||
"eino-project/internal/pkg/adkutil"
|
||
"encoding/json"
|
||
"net/http"
|
||
|
||
"github.com/cloudwego/eino/adk"
|
||
"github.com/go-kratos/kratos/v2/log"
|
||
kratoshttp "github.com/go-kratos/kratos/v2/transport/http"
|
||
)
|
||
|
||
type AgentService struct {
|
||
productAgent adk.Agent
|
||
log *log.Helper
|
||
}
|
||
|
||
func NewAgentService(
|
||
logger log.Logger,
|
||
models llm.LLM,
|
||
) *AgentService {
|
||
return &AgentService{
|
||
log: log.NewHelper(logger),
|
||
// 构建商品查询 ChatModelAgent,绑定工具并让模型自动选择调用
|
||
productAgent: agent.NewProductChatAgent(context.Background(), models),
|
||
}
|
||
}
|
||
|
||
type ProductQueryRes struct {
|
||
Items []*ProductItem `json:"items"`
|
||
Source string `json:"source"`
|
||
Count int `json:"count"`
|
||
}
|
||
type ProductItem struct {
|
||
ID string `json:"id"`
|
||
Name string `json:"name"`
|
||
Price int `json:"price"`
|
||
Description string `json:"description"`
|
||
}
|
||
|
||
type CommonResp struct {
|
||
Code int `json:"code"`
|
||
Msg string `json:"msg"`
|
||
Data interface{} `json:"data"`
|
||
}
|
||
|
||
// HandleProductQuery 商品查询处理
|
||
func (a *AgentService) HandleProductQuery(ctx kratoshttp.Context) error {
|
||
type reqType struct {
|
||
Message string `json:"message"`
|
||
Session string `json:"session_id"`
|
||
}
|
||
|
||
var req reqType
|
||
if err := json.NewDecoder(ctx.Request().Body).Decode(&req); err != nil {
|
||
return ctx.JSON(http.StatusBadRequest, &CommonResp{
|
||
Code: http.StatusBadRequest,
|
||
Msg: "Invalid request body",
|
||
})
|
||
}
|
||
if a.productAgent == nil {
|
||
return ctx.JSON(http.StatusInternalServerError, &CommonResp{Code: http.StatusInternalServerError, Msg: "product agent not configured"})
|
||
}
|
||
|
||
out, err := adkutil.QueryJSONWithLogger[ProductQueryRes](ctx, a.productAgent, req.Message, a.log)
|
||
if err != nil {
|
||
return ctx.JSON(http.StatusInternalServerError, &CommonResp{Code: http.StatusInternalServerError, Msg: err.Error()})
|
||
}
|
||
|
||
return ctx.JSON(http.StatusOK, &CommonResp{Code: http.StatusOK, Msg: "success", Data: out})
|
||
}
|