搶先一步
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 +
... 支援的模型清單可以在模型頁面的工具類別下找到。
ollama run mistral
若要開始將 Ollama 函數呼叫與 Spring AI 搭配使用,請將下列相依性新增至您的專案
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>
請參考相依性管理章節以將 Spring AI BOM 新增至您的建置檔案。
以下是如何將 Ollama 函數呼叫與 Spring AI 搭配使用的簡單範例
@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,然後可以提取即時天氣資料。
預期的回應看起來像這樣:"阿姆斯特丹目前的天氣是攝氏 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://127.0.0.1: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 開心編碼!