搶佔先機
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=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 愉快地編碼!