1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.tool.annotation.Tool; import org.springframework.ai.tool.annotation.ToolParam; import org.springframework.ai.tool.function.FunctionToolCallback; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux;
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.function.Function;
@Slf4j @RestController @RequestMapping("/tool") public class ToolController {
@Resource private ChatClient ollamaChatChatClient;
@RequestMapping(value = "/chat1", produces = "text/stream;charset=utf8") public Flux<String> chat1() { Flux<String> flux = ollamaChatChatClient.prompt().user("设置一个10分钟后的闹钟").tools(new DateTimeTool()).stream().content(); return flux; }
class DateTimeTool {
@Tool(description = "获取系统当前时间") public String test() { log.info("获取系统时间"); return LocalDateTime.now().toString(); }
@Tool public String test2() { return "123"; }
@Tool public void set(@ToolParam(description = "Time in ISO-8601 format") String time) { LocalDateTime alarmTime = LocalDateTime.parse(time, DateTimeFormatter.ISO_DATE_TIME); log.info("设置闹钟时间:{}", alarmTime); } }
@RequestMapping(value = "/chat2", produces = "text/stream;charset=utf8") public Flux<String> chat2() {
FunctionToolCallback<WeatherService.WeatherRequest, WeatherService.WeatherResponse> weatherCallback = FunctionToolCallback.builder("getCurrentWeather", new WeatherService()).description("获取当前的地区天气").inputType(WeatherService.WeatherRequest.class).build();
Flux<String> flux = ollamaChatChatClient.prompt().user("武汉今天的天气如何?").toolCallbacks(weatherCallback).stream().content(); return flux; }
class WeatherService implements Function<WeatherService.WeatherRequest, WeatherService.WeatherResponse> {
public record WeatherRequest(String location) { }
public record WeatherResponse(String location, double temperature, String unit) { }
@Override public WeatherResponse apply(WeatherRequest request) { log.info("参数location:{}", request.location); return new WeatherResponse(request.location, 22.0, "°C"); } } }
|