76 lines
2.1 KiB
Go
76 lines
2.1 KiB
Go
package tools
|
||
|
||
import (
|
||
"context"
|
||
"strings"
|
||
|
||
"github.com/cloudwego/eino/components/tool"
|
||
"github.com/cloudwego/eino/components/tool/utils"
|
||
)
|
||
|
||
var productsMock = []*Product{
|
||
{ID: "P001", Name: "手机 A1", Price: 1999, Description: "入门级智能手机"},
|
||
{ID: "P002", Name: "手机 Pro X", Price: 5999, Description: "旗舰级拍照手机"},
|
||
{ID: "P003", Name: "笔记本 M3", Price: 8999, Description: "轻薄高性能笔记本"},
|
||
{ID: "P004", Name: "耳机 Air", Price: 1299, Description: "降噪真无线耳机"},
|
||
{ID: "271", Name: "商品 271", Price: 2710, Description: "样例商品用于测试按ID查询"},
|
||
}
|
||
|
||
// 工具返回
|
||
type Product struct {
|
||
ID string `json:"id"`
|
||
Name string `json:"name"`
|
||
Price float64 `json:"price"`
|
||
Description string `json:"description"`
|
||
}
|
||
|
||
// --- Eino ADK Tool 实现:按ID查询 ---
|
||
type ProductByIDInput struct {
|
||
ID string `json:"id" jsonschema:"description=商品ID"`
|
||
}
|
||
|
||
func NewProductByIDTool() tool.InvokableTool {
|
||
toolImpl, err := utils.InferTool("get_product_by_id", "根据商品ID查询商品详情,返回商品对象。", productByID)
|
||
if err != nil {
|
||
panic(err)
|
||
}
|
||
return toolImpl
|
||
}
|
||
|
||
func productByID(ctx context.Context, in *ProductByIDInput) (*Product, error) {
|
||
for _, it := range productsMock {
|
||
if it.ID == in.ID {
|
||
return it, nil
|
||
}
|
||
}
|
||
return &Product{}, nil
|
||
}
|
||
|
||
// --- Eino ADK Tool 实现:按名称搜索 ---
|
||
|
||
type ProductSearchInput struct {
|
||
Name string `json:"name" jsonschema:"description=商品名称关键词"`
|
||
}
|
||
|
||
func NewProductSearchByNameTool() tool.InvokableTool {
|
||
toolImpl, err := utils.InferTool("search_product_by_name", "根据商品名称关键词搜索商品列表,返回数组。", productSearchByName)
|
||
if err != nil {
|
||
panic(err)
|
||
}
|
||
return toolImpl
|
||
}
|
||
|
||
func productSearchByName(ctx context.Context, in *ProductSearchInput) ([]*Product, error) {
|
||
if in.Name == "" {
|
||
return []*Product{}, nil
|
||
}
|
||
q := strings.ToLower(in.Name)
|
||
var out []*Product
|
||
for _, it := range productsMock {
|
||
if strings.Contains(strings.ToLower(it.Name), q) {
|
||
out = append(out, it)
|
||
}
|
||
}
|
||
return out, nil
|
||
}
|