Spring AI を使用したコンソールアプリケーションを作ってみようとしてちょっとハマったのでメモ。
Spring Initializr で以下のような設定で新規プロジェクトを作る(ほぼほぼ初期値のまま作る)。

プロジェクトの依存関係は以下の通り。Spring Boot バージョンは 3.4.7 を使用(3.5以降にすると SpringShell が使えなくなるので)。
- Ollama
- Spring Boot DevTools
- Lombok
- SpringShell (調べた感じだと、コンソールアプリを作る場合はこれを組み込むっぽい)
application.properties に Ollama で使用する model をセットする。
spring.ai.ollama.chat.options.model=gemma3:4b
とりあえず、問い合わせを行うソースを記述してみる。
package com.example.demo;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringAiConsoleTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAiConsoleTestApplication.class, args);
}
@Bean
public CommandLineRunner run() {
return args -> {
String response = chat("美味しいシュークリームの使い方は。");
System.out.println(response);
};
}
@Autowired
private ChatClient.Builder chatClientBuilder;
public String chat(String message) {
ChatClient client = chatClientBuilder.build();
String result = client
.prompt()
.user(message)
.call()
.content();
return result;
}
}
実行してみる。
***************************
APPLICATION FAILED TO START
***************************
Description:
Web application could not be started as there was no org.springframework.boot.web.reactive.server.ReactiveWebServerFactory bean defined in the context.
Action:
Check your application's dependencies for a supported reactive web server.
Check the configured web application type.
build.gradle をアレコレといじってみると、
implementation 'org.springframework.ai:spring-ai-starter-model-ollama'
および
mavenBom "org.springframework.ai:spring-ai-bom:${springAiVersion}"
があると、 Web Server を要求してしまうっぽい。
main の部分を以下のように記述すれば実行できた。
public static void main(String[] args) {
SpringApplication application = new SpringApplication(SpringAiConsoleTestApplication.class);
application.setWebApplicationType(WebApplicationType.NONE); // コンソールアプリケーションとして実行するため、WebApplicationTypeをNONEに設定
application.run(args);
}
(結果の例(先頭数行を抜粋))
美味しいシュークリームの使い方はたくさんありますね!いくつかアイデアをまとめました。
**1. そのまま食べる**
* **シンプルに:** 表面の粉砂糖をはたいて、そのままでも美味しい!
* **アレンジ:**
* ブラックコーヒーや紅茶との相性は抜群。
* 季節のフルーツ(いちご、ぶどう、柑橘など)を添えても。
* ブランデーやラム酒を少量たらしても大人な味わいに。
**2. デザートとして**
Spring Framework 関連の使い方はまだまだ知識不足だなぁ・・・。
もっといろいろと勉強しないと。
Recent Comments