領先一步
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 編碼愉快!