领先一步
VMware 提供培训和认证,助您加速进步。
了解更多本周早些时候,Ollama 发布了一项令人兴奋的新功能:大型语言模型(LLM)的工具支持。
今天,我们很高兴地宣布,Spring AI (1.0.0-SNAPSHOT) 已全面支持此强大功能,将 Ollama 的函数调用能力引入 Spring 生态系统。
Ollama 的工具支持允许模型决定何时调用外部函数以及如何使用返回的数据。这开启了无限的可能性,从访问实时信息到执行复杂计算。Spring AI 将这一概念无缝集成到 Spring 生态系统中,使 Java 开发人员能够极其轻松地在他们的应用程序中利用此功能。Spring AI 对 Ollama 函数调用的支持包含以下关键功能:

您首先需要在本地机器上运行 Ollama (0.2.8+)。请参阅官方 Ollama 项目 README,开始在本地运行模型。然后拉取支持工具的模型,例如 Llama 3.1、Mistral、Firefunction v2、Command-R +... 可以在模型页面上的 Tools 类别下找到支持的模型列表。
ollama run mistral
要开始使用 Ollama 函数调用与 Spring AI,请将以下依赖项添加到您的项目中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>
请参阅 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。
以下是使用 Spring AI 的 Ollama 函数调用的简单示例
@SpringBootApplication
public class OllamaApplication {
public static void main(String[] args) {
SpringApplication.run(OllamaApplication.class, args);
}
@Bean
CommandLineRunner runner(ChatClient.Builder chatClientBuilder) {
return args -> {
var chatClient = chatClientBuilder.build();
var response = chatClient.prompt()
.user("What is the weather in Amsterdam and Paris?")
.functions("weatherFunction") // reference by bean name.
.call()
.content();
System.out.println(response);
};
}
@Bean
@Description("Get the weather in location")
public Function<WeatherRequest, WeatherResponse> weatherFunction() {
return new MockWeatherService();
}
public static class MockWeatherService implements Function<WeatherRequest, WeatherResponse> {
public record WeatherRequest(String location, String unit) {}
public record WeatherResponse(double temp, String unit) {}
@Override
public WeatherResponse apply(WeatherRequest request) {
double temperature = request.location().contains("Amsterdam") ? 20 : 25;
return new WeatherResponse(temperature, request.unit);
}
}
}
在此示例中,当模型需要天气信息时,它将自动调用 weatherFunction bean,该 bean 随后可以获取实时天气数据。
预期的响应如下:“阿姆斯特丹当前天气为 20 摄氏度,巴黎当前天气为 25 摄氏度。”
完整的示例代码可在以下位置找到: https://github.com/tzolov/ollama-tools
Ollama 与 OpenAI API 兼容,您可以使用 Spring AI OpenAI 客户端与 Ollama 通信并使用工具。为此,您需要使用 OpenAI 客户端但设置 base-url:spring.ai.openai.chat.base-url=https://:11434 并选择一个提供的 Ollama Tools 模型:spring.ai.openai.chat.options.model=mistral。
请查看 OllamaWithOpenAiChatModelIT.java 测试,了解通过 Spring AI OpenAI 使用 Ollama 的示例。
正如 Ollama 博文中所述,目前他们的 API 不支持 Streaming Tool Calls 或 Tool choice。
一旦这些限制得到解决,Spring AI 也将准备好提供支持。
通过构建在 Ollama 创新的工具支持之上,并将其集成到 Spring 生态系统中,Spring AI 为 Java 开发人员创建了一种强大的新方式来构建 AI 增强型应用程序。此功能为创建更动态、响应更快的 AI 驱动型系统开辟了令人兴奋的可能性,这些系统可以与现实世界的数据和服务进行交互。
使用 Spring AI 的 Ollama 函数调用的一些好处包括:
我们鼓励您尝试此新功能,并告诉我们您在项目中是如何使用它的。有关更详细的信息和高级用法,请查阅我们的官方文档。
祝您使用 Spring AI 和 Ollama 编码愉快!