跳到主要内容

Ollama

Ollamaとは?​

Ollamaは、大規模言語モデルをローカル(CPUおよびGPUモード)で簡単にセットアップして実行できる高度なAIツールです。Ollamaを使用すると、ユーザーはLlama 2などの強力な言語モデルを活用し、独自のモデルをカスタマイズして作成することもできます。Ollamaは、モデルの重み、設定、データをModelfileで定義された単一のパッケージにバンドルします。GPUの使用を含むセットアップと設定の詳細を最適化します。

Ollamaの詳細については、以下をご覧ください:

講演​

Docker Con 23でのプレゼンテーションをご覧ください:

Code to the Moonによる紹介をご覧ください:

はじめに​

始めるには、プロジェクトのpom.xmlに以下の依存関係を追加してください:


<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-ollama</artifactId>
<version>1.23.0</version>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>ollama</artifactId>
<version>1.19.1</version>
</dependency>

Ollamaがtestcontainersで実行されている場合の簡単なチャット例コードを試してみてください:

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Image;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.ollama.OllamaChatModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.Container;
import org.testcontainers.ollama.OllamaContainer;
import org.testcontainers.utility.DockerImageName;

import java.io.IOException;
import java.util.List;

public class OllamaChatExample {

private static final Logger log = LoggerFactory.getLogger(OllamaChatExample.class);

static final String OLLAMA_IMAGE = "ollama/ollama:latest";
static final String TINY_DOLPHIN_MODEL = "tinydolphin";
static final String DOCKER_IMAGE_NAME = "tc-ollama/ollama:latest-tinydolphin";

public static void main(String[] args) {
// Create and start the Ollama container
DockerImageName dockerImageName = DockerImageName.parse(OLLAMA_IMAGE);
DockerClient dockerClient = DockerClientFactory.instance().client();
List<Image> images = dockerClient.listImagesCmd().withReferenceFilter(DOCKER_IMAGE_NAME).exec();
OllamaContainer ollama;
if (images.isEmpty()) {
ollama = new OllamaContainer(dockerImageName);
} else {
ollama = new OllamaContainer(DockerImageName.parse(DOCKER_IMAGE_NAME).asCompatibleSubstituteFor(OLLAMA_IMAGE));
}
ollama.start();

// Pull the model and create an image based on the selected model.
try {
log.info("Start pulling the '{}' model ... would take several minutes ...", TINY_DOLPHIN_MODEL);
Container.ExecResult r = ollama.execInContainer("ollama", "pull", TINY_DOLPHIN_MODEL);
log.info("Model pulling competed! {}", r);
} catch (IOException | InterruptedException e) {
throw new RuntimeException("Error pulling model", e);
}
ollama.commitToImage(DOCKER_IMAGE_NAME);

// Build the ChatModel
ChatModel model = OllamaChatModel.builder()
.baseUrl(ollama.getEndpoint())
.temperature(0.0)
.logRequests(true)
.logResponses(true)
.modelName(TINY_DOLPHIN_MODEL)
.build();

// Example usage
String answer = model.chat("Provide 3 short bullet points explaining why Java is awesome");
System.out.println(answer);

// Stop the Ollama container
ollama.stop();
}
}

Ollamaがローカルで実行されている場合は、以下のチャット例コードも試すことができます:

class OllamaChatLocalModelTest {
static String MODEL_NAME = "llama3.2"; // try other local ollama model names
static String BASE_URL = "http://localhost:11434"; // local ollama base url

public static void main(String[] args) {
ChatModel model = OllamaChatModel.builder()
.baseUrl(BASE_URL)
.modelName(MODEL_NAME)
.build();
String answer = model.chat("List top 10 cites in China");
System.out.println(answer);

model = OllamaChatModel.builder()
.baseUrl(BASE_URL)
.modelName(MODEL_NAME)
.responseFormat(JSON)
.build();

String json = model.chat("List top 10 cites in US");
System.out.println(json);
}
}

Ollamaがtestcontainersで実行されている場合の簡単なストリーミングチャット例コードを試してみてください:

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Image;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.ollama.OllamaStreamingChatModel;
import dev.langchain4j.model.output.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.Container;
import org.testcontainers.ollama.OllamaContainer;
import org.testcontainers.utility.DockerImageName;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class OllamaStreamingChatExample {

private static final Logger log = LoggerFactory.getLogger(OllamaStreamingChatExample.class);

static final String OLLAMA_IMAGE = "ollama/ollama:latest";
static final String TINY_DOLPHIN_MODEL = "tinydolphin";
static final String DOCKER_IMAGE_NAME = "tc-ollama/ollama:latest-tinydolphin";

public static void main(String[] args) {
DockerImageName dockerImageName = DockerImageName.parse(OLLAMA_IMAGE);
DockerClient dockerClient = DockerClientFactory.instance().client();
List<Image> images = dockerClient.listImagesCmd().withReferenceFilter(DOCKER_IMAGE_NAME).exec();
OllamaContainer ollama;
if (images.isEmpty()) {
ollama = new OllamaContainer(dockerImageName);
} else {
ollama = new OllamaContainer(DockerImageName.parse(DOCKER_IMAGE_NAME).asCompatibleSubstituteFor(OLLAMA_IMAGE));
}
ollama.start();
try {
log.info("Start pulling the '{}' model ... would take several minutes ...", TINY_DOLPHIN_MODEL);
Container.ExecResult r = ollama.execInContainer("ollama", "pull", TINY_DOLPHIN_MODEL);
log.info("Model pulling competed! {}", r);
} catch (IOException | InterruptedException e) {
throw new RuntimeException("Error pulling model", e);
}
ollama.commitToImage(DOCKER_IMAGE_NAME);

StreamingChatModel model = OllamaStreamingChatModel.builder()
.baseUrl(ollama.getEndpoint())
.temperature(0.0)
.logRequests(true)
.logResponses(true)
.modelName(TINY_DOLPHIN_MODEL)
.build();

String userMessage = "Write a 100-word poem about Java and AI";

CompletableFuture<ChatResponse> futureResponse = new CompletableFuture<>();
model.chat(userMessage, new StreamingChatResponseHandler() {

@Override
public void onPartialResponse(String partialResponse) {
System.out.print(partialResponse);
}

@Override
public void onCompleteResponse(ChatResponse completeResponse) {
futureResponse.complete(completeResponse);
}

@Override
public void onError(Throwable error) {
futureResponse.completeExceptionally(error);
}
});

futureResponse.join();
ollama.stop();
}
}

ローカルで Ollama を実行している場合は、以下のストリーミングチャットのサンプルコードも試せます:

class OllamaStreamingChatLocalModelTest {
static String MODEL_NAME = "llama3.2"; // try other local ollama model names
static String BASE_URL = "http://localhost:11434"; // local ollama base url

public static void main(String[] args) {
StreamingChatModel model = OllamaStreamingChatModel.builder()
.baseUrl(BASE_URL)
.modelName(MODEL_NAME)
.temperature(0.0)
.build();
String userMessage = "Write a 100-word poem about Java and AI";

CompletableFuture<ChatResponse> futureResponse = new CompletableFuture<>();
model.chat(userMessage, new StreamingChatResponseHandler() {

@Override
public void onPartialResponse(String partialResponse) {
System.out.print(partialResponse);
}

@Override
public void onCompleteResponse(ChatResponse completeResponse) {
futureResponse.complete(completeResponse);
}

@Override
public void onError(Throwable error) {
futureResponse.completeExceptionally(error);
}
});

futureResponse.join();
}
}

パラメータ​

OllamaChatModelとOllamaStreamingChatModelクラスは、ビルダーパターンを使用して以下のパラメータでインスタンス化できます:

パラメータ説明型例
httpClientBuilderカスタマイズ可能な HTTP クライアントを参照HttpClientBuilder
baseUrlOllama サーバーのベース URL。Stringhttp://localhost:11434
defaultRequestParametersChatRequestParameters
modelNameOllama サーバーで使用するモデルの名前。String
temperature生成されるレスポンスのランダム性を制御します。値が高い(例:1.0)ほど多様な出力になり、低い(例:0.2)ほど決定的なレスポンスになります。Double
topK生成中の各ステップで考慮する、確率の高いトークンの数を指定します。Integer
topP上位トークンの累積確率のしきい値を設定することで、生成されるレスポンスの多様性を制御します。Double
mirostatInteger
mirostatEtaDouble
mirostatTauDouble
repeatLastNInteger
repeatPenalty生成された出力で類似のトークンを繰り返すモデルにペナルティを課します。Double
seed生成されるレスポンスの再現性のために、乱数シードを設定します。Integer
numPredict各入力プロンプトに対して生成する予測の数。Integer
numCtxInteger
stop生成された場合にレスポンスの終了を示す文字列のリスト。List<String>
minPDouble
responseFormat生成される出力の望ましい形式。TEXT、または JSON(オプションで JSON Schema 定義付き)ResponseFormat
thinkthinking を制御します。Boolean
truncateプロンプトがコンテキストウィンドウに収まらない場合のサーバーの動作を制御します。下記を参照。Booleantrue (server default)
returnThinkingBoolean
timeoutAPI 呼び出しが完了するまでに許容される最大時間。DurationPT60S
customHeadersカスタム HTTP ヘッダー。Map<String, String>
logRequestsBoolean
logResponsesBoolean
listenersチャットモデルのオブザーバビリティを参照List<ChatModelListener>
supportedCapabilitiesAiServices API が使用するモデル機能のセット(OllamaChatModel のみサポート)Set<Capability>RESPONSE_FORMAT_JSON_SCHEMA
maxRetriesAPI 呼び出しが失敗した場合の最大リトライ回数。Integer

使用例​

OllamaChatModel ollamaChatModel = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("llama3.1")
.temperature(0.8)
.timeout(Duration.ofSeconds(60))
.build();

Spring Bootでの使用例​

Ollama の Spring Boot starter をインポートします:

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-ollama-spring-boot4-starter</artifactId>
<version>1.23.0-beta33</version>
</dependency>
备注

この starter には Spring Boot 4 が必要です。Spring Boot 3 では、代わりに langchain4j-ollama-spring-boot-starter を使用してください。 詳細は Spring Boot 統合を参照してください。

その後、OllamaChatModel Bean を設定します:

langchain4j.ollama.chat-model.base-url=http://localhost:11434
langchain4j.ollama.chat-model.model-name=llama3.1
langchain4j.ollama.chat-model.temperature=0.8
langchain4j.ollama.chat-model.timeout=PT60S

JSONモード​

OllamaChatModel ollamaChatModel = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("llama3.1")
.responseFormat(ResponseFormat.JSON)
.temperature(0.8)
.timeout(Duration.ofSeconds(60))
.build();

構造化出力​

ビルダーを使用したJSONスキーマ定義​

OllamaChatModel ollamaChatModel = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("llama3.1")
.responseFormat(ResponseFormat.builder()
.type(ResponseFormatType.JSON)
.jsonSchema(JsonSchema.builder().rootElement(JsonObjectSchema.builder()
.addProperty("name", JsonStringSchema.builder().build())
.addProperty("capital", JsonStringSchema.builder().build())
.addProperty(
"languages",
JsonArraySchema.builder()
.items(JsonStringSchema.builder().build())
.build())
.required("name", "capital", "languages")
.build())
.build())
.build())
.temperature(0.8)
.timeout(Duration.ofSeconds(60))
.build();

ChatRequest APIを使用したJSONスキーマ​

OllamaChatModel ollamaChatModel = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("llama3.1")
.build();

ChatResponse chatResponse = ollamaChatModel.chat(ChatRequest.builder()
.messages(userMessage("Tell me about Canada."))
.responseFormat(ResponseFormat.builder()
.type(ResponseFormatType.JSON)
.jsonSchema(JsonSchema.builder().rootElement(JsonObjectSchema.builder()
.addProperty("name", JsonStringSchema.builder().build())
.addProperty("capital", JsonStringSchema.builder().build())
.addProperty(
"languages",
JsonArraySchema.builder()
.items(JsonStringSchema.builder().build())
.build())
.required("name", "capital", "languages")
.build())
.build())
.build())
.build());

String jsonFormattedResponse = chatResponse.aiMessage().text();

/* jsonFormattedResponse value:

{
"capital" : "Ottawa",
"languages" : [ "English", "French" ],
"name" : "Canada"
}

*/


AiServicesでのJsonスキーマ​

OllamaChatModelがRESPONSE_FORMAT_JSON_SCHEMAのサポート機能で作成されると、AIServiceはインターフェースの戻り値から自動的にスキーマを生成します。詳細は構造化出力をご覧ください。

OllamaChatModel ollamaChatModel = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("llama3.1")
.supportedCapabilities(RESPONSE_FORMAT_JSON_SCHEMA)
.build();

コンテキストウィンドウを超えるプロンプト(Prompts that exceed the context window)​

デフォルトでは、Ollama はプロンプトのうちコンテキストウィンドウに収まらない部分を切り捨て、残りの部分から回答します。レスポンスは通常の 200 であり、promptEvalCount は切り捨て後のプロンプトを数えるため、レスポンスにもトークン使用量にも、入力が失われたことは表れません。

代わりにエラーを受け取るには、truncate を false に設定します。サーバーは HTTP 400 でリクエストを拒否し、プロンプトのサイズとコンテキストのサイズの両方を報告します:

ChatModel model = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("llama3.1:8b")
.numCtx(4096)
.truncate(false)
.build();

これは、会話がツール結果ごとに増えていくマルチターンのエージェントループで役立ちます。そうした場面では、プロンプトが黙って短縮されるほうが、リクエストが失敗するよりも悪い結果になります。truncate を未設定のままにすると、サーバーのデフォルトが維持されます。

Thinking / 推論(Reasoning)​

Thinking 機能がサポートされており、次のパラメータで制御されます:

  • think:LLM が思考するかどうか、またどのように思考するかを制御します:
    • true:LLM が思考し、思考内容を別の thinking フィールドで返します
    • false:LLM は思考しません
    • null(未設定):推論型 LLM(たとえば DeepSeek R1)は、<think> と </think> で区切られた思考内容を実際のレスポンスの前に付加します
  • returnThinking:API レスポンスの thinking フィールドを解析して AiMessage.thinking() で返すかどうかを制御し、OllamaStreamingChatModel を使用する場合に StreamingChatResponseHandler.onPartialThinking() と TokenStream.onPartialThinking() のコールバックを呼び出すかどうかも制御します。デフォルトでは無効です。

thinking を設定する例を次に示します:

ChatModel model = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("qwen3:0.6b")
.think(true)
.returnThinking(true)
.build();

カスタムメッセージ​

OllamaChatModelとOllamaStreamingChatModelは、標準のチャットメッセージタイプに加えてカスタムチャットメッセージをサポートしています。 カスタムメッセージを使用して、任意の属性を持つメッセージを指定できます。これは、 Granite Guardianのような一部のモデルで役立ちます。 非標準のメッセージを使用します。

CustomMessageを使用して任意の属性を持つメッセージを指定する方法を見てみましょう:

OllamaChatModel ollamaChatModel = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("granite3-guardian")
.build();

String retrievedContext = "One significant part of treaty making is that signing a treaty implies recognition that the other side is a sovereign state and that the agreement being considered is enforceable under international law. Hence, nations can be very careful about terming an agreement to be a treaty. For example, within the United States, agreements between states are compacts and agreements between states and the federal government or between agencies of the government are memoranda of understanding.";

List<ChatMessage> messages = List.of(
SystemMessage.from("context_relevance"),
UserMessage.from("What is the history of treaty making?"),
CustomMessage.from(Map.of(
"role", "context",
"content", retrievedContext
))
);

ChatResponse chatResponse = ollamaChatModel.chat(ChatRequest.builder().messages(messages).build());

System.out.println(chatResponse.aiMessage().text()); // "Yes" (meaning risk detected by Granite Guardian)

決定モデル(Decision models)​

Ollama は決定モデルも実行できます。決定モデルは、はい/いいえ、選択、尺度の質問に確率で回答します。 詳細は Ollama 決定モデルを参照してください。