抢占先机
VMware 提供培训和认证,助力您的快速发展。
了解更多本周早些时候,Ollama 推出了一个令人兴奋的新功能:对大型语言模型(LLMs)的工具支持。
今天,我们激动地宣布 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
要开始使用 Spring AI 的 Ollama 函数调用功能,请将以下依赖项添加到您的项目中
<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=http://localhost: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 愉快地编码!