|
| 1 | +package com.xiaozhi.dialogue.llm.tool.function; |
| 2 | + |
| 3 | +import cn.hutool.core.map.MapUtil; |
| 4 | +import cn.hutool.core.util.RandomUtil; |
| 5 | +import com.xiaozhi.communication.common.ChatSession; |
| 6 | +import com.xiaozhi.dialogue.llm.ChatService; |
| 7 | +import com.xiaozhi.dialogue.llm.tool.ToolCallStringResultConverter; |
| 8 | +import com.xiaozhi.dialogue.llm.tool.ToolsGlobalRegistry; |
| 9 | +import com.xiaozhi.dialogue.service.HuiBenService; |
| 10 | +import jakarta.annotation.Resource; |
| 11 | +import org.slf4j.Logger; |
| 12 | +import org.slf4j.LoggerFactory; |
| 13 | +import org.springframework.ai.chat.model.ToolContext; |
| 14 | +import org.springframework.ai.tool.ToolCallback; |
| 15 | +import org.springframework.ai.tool.function.FunctionToolCallback; |
| 16 | +import org.springframework.ai.tool.metadata.ToolMetadata; |
| 17 | +import org.springframework.stereotype.Component; |
| 18 | + |
| 19 | +import java.util.Map; |
| 20 | + |
| 21 | +@Component |
| 22 | +public class PlayHuiBenFunction implements ToolsGlobalRegistry.GlobalFunction { |
| 23 | + private static final Logger logger = LoggerFactory.getLogger(PlayHuiBenFunction.class); |
| 24 | + |
| 25 | + @Resource |
| 26 | + private HuiBenService huiBenService; |
| 27 | + |
| 28 | + ToolCallback toolCallback = FunctionToolCallback |
| 29 | + .builder("func_playHuiBen", (Map<String, String> params, ToolContext toolContext) -> { |
| 30 | + ChatSession chatSession = (ChatSession) toolContext.getContext().get(ChatService.TOOL_CONTEXT_SESSION_KEY); |
| 31 | + Integer num = MapUtil.getInt(params, "num"); |
| 32 | + try { |
| 33 | + if (num == null || num < 5 || num > 1100) { |
| 34 | + num = RandomUtil.randomInt(5, 1100); |
| 35 | + } |
| 36 | + huiBenService.playMusic(chatSession, num); |
| 37 | + return "尝试播放绘本《" + num + "》"; |
| 38 | + |
| 39 | + } catch (Exception e) { |
| 40 | + logger.error("device 绘本播放异常,song name: {}", num, e); |
| 41 | + return "绘本播放失败"; |
| 42 | + } |
| 43 | + }) |
| 44 | + .toolMetadata(ToolMetadata.builder().returnDirect(true).build()) |
| 45 | + .description("绘本播放助手,需要用户提供绘本数字编号") |
| 46 | + .inputSchema(""" |
| 47 | + { |
| 48 | + "type": "object", |
| 49 | + "properties": { |
| 50 | + "songName": { |
| 51 | + "type": "string", |
| 52 | + "description": "要播放的绘本数字编号" |
| 53 | + } |
| 54 | + }, |
| 55 | + "required": ["num"] |
| 56 | + } |
| 57 | + """) |
| 58 | + .inputType(Map.class) |
| 59 | + .toolCallResultConverter(ToolCallStringResultConverter.INSTANCE) |
| 60 | + .build(); |
| 61 | + |
| 62 | + @Override |
| 63 | + public ToolCallback getFunctionCallTool(ChatSession chatSession) { |
| 64 | + return toolCallback; |
| 65 | + } |
| 66 | +} |
0 commit comments