spring-ai-alibaba第三章ollama集成Tool

1、当我们使用大模型问

请告诉我现在北京时间几点了

回答如下

此时就需要大模型的 function call 的功能,也就是 给大模型加上工具

2、代码如下

获取时间的工具类

package com.alibaba.cloud.ai.example.chat.ollama.tools.time;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author yingzi
 * @date 2025/3/27:10:56
 */
public class TimeUtils {

    public static String getTimeByZoneId(String zoneId) {

        // Get the time zone using ZoneId
        ZoneId zid = ZoneId.of(zoneId);

        // Get the current time in this time zone
        ZonedDateTime zonedDateTime = ZonedDateTime.now(zid);

        // Defining a formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");

        // Format ZonedDateTime as a string
        String formattedDateTime = zonedDateTime.format(formatter);

        return formattedDateTime;
    }
}

获取时间的工具

package com.alibaba.cloud.ai.example.chat.ollama.tools.time.method;

import com.alibaba.cloud.ai.example.chat.ollama.tools.time.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

public class TimeTools {
    private static final Logger logger = LoggerFactory.getLogger(TimeTools.class);

    @Tool(description = "Get the time of a specified city.")
    public String  getCityTimeMethod(@ToolParam(description = "Time zone id, such as Asia/Shanghai") String timeZoneId) {
        logger.info("The current time zone is {}", timeZoneId);
        return String.format("The current time zone is %s and the current time is " + "%s", timeZoneId,
                TimeUtils.getTimeByZoneId(timeZoneId));
    }
}

controller代码如下

package com.alibaba.cloud.ai.example.chat.ollama.controller;

import com.alibaba.cloud.ai.example.chat.ollama.tools.time.method.TimeTools;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/time")
public class TimeController {

    private final ChatClient ollamaiChatClient;

    public TimeController(ChatClient.Builder chatClientBuilder) {
        this.ollamaiChatClient = chatClientBuilder.build();
    }

    /**
     * 无工具版
     */
    @GetMapping("/chat")
    public String simpleChat(@RequestParam(value = "query", defaultValue = "请告诉我现在北京时间几点了") String query) {
        return ollamaiChatClient.prompt(query).call().content();
    }

    /**
     * 调用工具版 - function
     */
    @GetMapping("/chat-tool-function")
    public String chatTranslateFunction(@RequestParam(value = "query", defaultValue = "请告诉我现在北京时间几点了") String query) {
        return ollamaiChatClient.prompt(query).tools("getCityTimeFunction").call().content();
    }

    /**
     * 调用工具版 - method
     */
    @GetMapping("/chat-tool-method")
    public String chatTranslateMethod(@RequestParam(value = "query", defaultValue = "请告诉我现在北京时间几点了") String query) {
        return ollamaiChatClient.prompt(query).tools(new TimeTools()).call().content();
    }

}

调用接口  http://127.0.0.1:10005/time/chat-tool-method  如下

### Spring AI Ollama Spring Boot Starter 使用指南 #### 了解 Spring AIOllama集成背景 Spring AI 是一个用于构建人工智能应用程序的框架,而 Ollama 提供了强大的自然语言处理能力。两者结合能够帮助开发者更轻松地创建生成式AI应用[^3]。 #### 添加 Maven 依赖项 为了在项目中使用 `spring-ai-ollama-spring-boot-starter` ,需要向项目的 pom.xml 文件添加如下两个依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-ollama-spring-boot-starter</artifactId> </dependency> ``` 上述代码片段展示了如何引入必要的库来支持 Web 功能以及与 Ollama 的交互功能[^4]。 #### 配置 application.properties 或者 application.yml 通常情况下,默认设置即可满足大多数需求;但是也可以通过自定义属性进一步调整行为。例如,在application.properties文件里指定Ollama API key: ```properties spring.ai.ollama.api-key=your_api_key_here ``` 对于YAML格式,则应这样写入配置信息: ```yaml spring: ai: ollama: api-key: your_api_key_here ``` 这些配置允许应用程序连接到特定的服务实例并验证身份认证凭证。 #### 编写控制器类实现业务逻辑 接下来就是编写具体的业务逻辑部分了。这里给出一个简单的例子展示怎样调用API完成对话任务: ```java @RestController @RequestMapping("/chat") public class ChatController { @Autowired private OllamaService ollamaService; @PostMapping public String chat(@RequestBody Map<String, String> body){ return this.ollamaService.generateResponse(body.get("message")); } } ``` 此段代码定义了一个RESTful接口 `/chat` 接收POST请求并将消息转发给Ollama服务获取回复内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值