ai-courseware/eino-project/internal/service/agent.go

75 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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})
}