Ollama 임베딩 설정
Ollama 임베딩 설정
Ollama를 쓰면 다양한 AI 모델을 로컬에서 실행하고 그 모델들로 임베딩을 생성할 수 있어요. 임베딩은 부동소수점 숫자의 벡터(목록)예요. 두 벡터 사이의 거리가 작을수록 연관성이 크고, 클수록 연관성이 작아요. OllamaEmbeddingModel 구현은 Ollama의 Embeddings API 엔드포인트를 활용해요.
출처: 공식문서
사전 준비 (Prerequisites)
먼저 Ollama 인스턴스에 접근할 수 있어야 해요. 몇 가지 방법이 있는데, 그중 대표적인 건 다음과 같아요.
- Ollama 다운로드·설치 후 로컬 머신에서 실행
- Testcontainers로 Ollama 구성·실행
애플리케이션에서 쓸 모델은 Ollama 모델 라이브러리에서 pull할 수 있어요.
ollama pull <model-name>
수천 개의 무료 GGUF Hugging Face 모델도 pull할 수 있어요.
자동 설정 (Auto-Configuration)
Spring AI는 Ollama 임베딩 모델에 대한 Spring Boot 자동 설정을 제공해요. 활성화하려면 Maven pom.xml 또는 Gradle build.gradle에 spring-ai-starter-model-ollama 의존성을 추가하면 돼요.
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-ollama'
}
기본 프로퍼티 (Base Properties)
Ollama에 연결하는 설정은 spring.ai.ollama 프리픽스를 사용해요.
| Property | Description | Default |
| spring.ai.ollama.base-url | Base URL where Ollama API server is running. | http://localhost:11434 |
Ollama 통합 초기화와 모델 자동 pull 관련 프로퍼티예요.
| Property | Description | Default |
| spring.ai.ollama.init.pull-model-strategy | Whether to pull models at startup-time and how. | never |
| spring.ai.ollama.init.max-retries | Maximum number of retries for the model pull operation. | 0 |
| spring.ai.ollama.init.embedding.include | Include this type of models in the initialization task. | true |
| spring.ai.ollama.init.embedding.additional-models | Additional models to initialize besides the ones configured via default properties. | [] |
임베딩 프로퍼티 (Embedding Properties)
임베딩 자동 설정의 켜고 끔은 spring.ai.model.embedding 프리픽스로 제어해요. 켜려면 spring.ai.model.embedding=ollama(기본값), 끄려면 spring.ai.model.embedding=none으로 설정하면 돼요.
Ollama 임베딩 모델을 설정하는 프리픽스는 spring.ai.ollama.embedding 이에요. model, keep-alive, truncate 같은 Ollama 요청(고급) 파라미터와 Ollama 모델 프로퍼티를 포함해요.
| Property | Description | Default | | spring.ai.ollama.embedding.enabled (Removed and no longer valid) | Enables the Ollama embedding model auto-configuration. | true | | spring.ai.ollama.embedding.model | The name of the supported model to use. You can use dedicated Embedding Model types. | mxbai-embed-large | | spring.ai.ollama.embedding.keep_alive | Controls how long the model will stay loaded into memory following the request | 5m | | spring.ai.ollama.embedding.truncate | Truncates the end of each input to fit within context length. Returns error if false and context length is exceeded. | true |
나머지 options 프로퍼티는 Ollama Valid Parameters and Values와 Ollama Types에 기반해요.
| Property | Description | Default | | spring.ai.ollama.embedding.numa | Whether to use NUMA. | false | | spring.ai.ollama.embedding.num-ctx | Sets the size of the context window used to generate the next token. | 2048 | | spring.ai.ollama.embedding.num-batch | Prompt processing maximum batch size. | 512 | | spring.ai.ollama.embedding.num-gpu | The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. 1 here indicates that NumGPU should be set dynamically. | -1 | | spring.ai.ollama.embedding.main-gpu | When using multiple GPUs this option controls which GPU is used for small tensors. | 0 | | spring.ai.ollama.embedding.low-vram | - | false | | spring.ai.ollama.embedding.f16-kv | - | true | | spring.ai.ollama.embedding.logits-all | Return logits for all the tokens, not just the last one. | - | | spring.ai.ollama.embedding.vocab-only | Load only the vocabulary, not the weights. | - | | spring.ai.ollama.embedding.use-mmap | By default, models are mapped into memory so only necessary parts load as needed. If the model is larger than total RAM, turning off mmap would prevent loading at all. | null | | spring.ai.ollama.embedding.use-mlock | Lock the model in memory, preventing it from being swapped out when memory-mapped. Improves performance but requires more RAM. | false | | spring.ai.ollama.embedding.num-thread | Sets the number of threads to use during computation. Recommended to set to the number of physical CPU cores. 0 = let the runtime decide. | 0 | | spring.ai.ollama.embedding.num-keep | - | 4 | | spring.ai.ollama.embedding.seed | Sets the random number seed to use for generation. Setting this makes the model generate the same text for the same prompt. | -1 | | spring.ai.ollama.embedding.num-predict | Maximum number of tokens to predict when generating text. (-1 = infinite generation, -2 = fill context) | -1 | | spring.ai.ollama.embedding.top-k | Reduces the probability of generating nonsense. A higher value (e.g., 100) gives more diverse answers, a lower value (e.g., 10) is more conservative. | 40 | | spring.ai.ollama.embedding.top-p | Works together with top-k. A higher value (e.g., 0.95) leads to more diverse text. | 0.9 | | spring.ai.ollama.embedding.min-p | Alternative to top_p. Minimum probability for a token to be considered, relative to the most likely token. | 0.0 | | spring.ai.ollama.embedding.tfs-z | Tail-free sampling reduces the impact of less probable tokens. A value of 1.0 disables this setting. | 1.0 | | spring.ai.ollama.embedding.typical-p | - | 1.0 | | spring.ai.ollama.embedding.repeat-last-n | Sets how far back the model looks to prevent repetition. (Default: 64, 0 = disabled, -1 = num_ctx) | 64 | | spring.ai.ollama.embedding.temperature | The temperature of the model. Increasing it makes the model answer more creatively. | 0.8 | | spring.ai.ollama.embedding.repeat-penalty | Sets how strongly to penalize repetitions. | 1.1 | | spring.ai.ollama.embedding.presence-penalty | - | 0.0 | | spring.ai.ollama.embedding.frequency-penalty | - | 0.0 | | spring.ai.ollama.embedding.mirostat | Enable Mirostat sampling for controlling perplexity. (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0) | 0 | | spring.ai.ollama.embedding.mirostat-tau | Controls the balance between coherence and diversity of the output. | 5.0 | | spring.ai.ollama.embedding.mirostat-eta | Influences how quickly the algorithm responds to feedback from the generated text. | 0.1 | | spring.ai.ollama.embedding.penalize-newline | - | true | | spring.ai.ollama.embedding.stop | Sets the stop sequences to use. | - | | spring.ai.ollama.embedding.functions | List of functions, identified by their names, to enable for function calling in a single prompt request. Functions must exist in the toolCallbacks registry. | - |
spring.ai.ollama.embedding으로 시작하는 모든 프로퍼티는 런타임 옵션을 EmbeddingRequest 호출에 추가해 실행 시점에 덮어쓸 수 있어요.
런타임 옵션 (Runtime Options)
OllamaEmbeddingOptions.java는 사용할 모델, 저수준 GPU·CPU 튜닝 등 Ollama 구성을 제공해요.
참고:
OllamaOptions클래스는 deprecated 됐어요. 채팅 모델에는OllamaChatOptions, 임베딩 모델에는OllamaEmbeddingOptions를 사용하세요. 두 새 클래스는 타입 안전한 모델별 설정 옵션을 제공해요.
기본 옵션은 spring.ai.ollama.embedding 프로퍼티로 설정할 수 있어요. 시작 시점에는 OllamaEmbeddingModel(OllamaApi ollamaApi, OllamaEmbeddingOptions options)으로 모든 임베딩 요청의 기본 옵션을 설정하고, 런타임에는 OllamaEmbeddingOptions 인스턴스를 EmbeddingRequest의 일부로 사용해 덮어쓸 수 있어요.
EmbeddingResponse embeddingResponse = embeddingModel.call(
new EmbeddingRequest(List.of("Hello World", "World is big and salvation is near"),
OllamaEmbeddingOptions.builder()
.model("Different-Embedding-Model-Deployment-Name"))
.truncates(false)
.build());
모델 자동 풀 (Auto-pulling Models)
시작 시 모델을 자동으로 pull하도록 설정할 수 있어요.
spring:
ai:
ollama:
init:
pull-model-strategy: always
embedding:
additional-models:
- mxbai-embed-large
- nomic-embed-text
pull 전략을 특정 타입의 모델에만 적용하고 싶으면 임베딩 모델을 초기화 작업에서 제외할 수도 있어요.
spring:
ai:
ollama:
init:
pull-model-strategy: always
embedding:
include: false
이렇게 하면 임베딩 모델을 제외한 모든 모델에 pull 전략이 적용돼요.
HuggingFace 모델
Ollama는 기본적으로 모든 GGUF Hugging Face 임베딩 모델에 접근할 수 있어요. 이름으로 아무 모델이나 pull할 수 있고(ollama pull hf.co/<username>/<model-repository>), 자동 pull 전략으로도 설정할 수 있어요.
spring.ai.ollama.embedding.model=hf.co/mixedbread-ai/mxbai-embed-large-v1
spring.ai.ollama.init.pull-model-strategy=always
spring.ai.ollama.embedding.model: 사용할 Hugging Face GGUF 모델을 지정spring.ai.ollama.init.pull-model-strategy=always: (선택) 시작 시 모델 자동 pull 활성화
프로덕션에서는 지연을 피하기 위해 모델을 미리 다운로드해 두는 게 좋아요: ollama pull hf.co/mixedbread-ai/mxbai-embed-large-v1
수동 설정 (Manual Configuration)
Spring Boot를 쓰지 않는다면 OllamaEmbeddingModel을 직접 구성할 수 있어요. spring-ai-ollama 의존성을 Maven pom.xml 또는 Gradle build.gradle에 추가하면 돼요.
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama</artifactId>
</dependency>
dependencies {
implementation 'org.springframework.ai:spring-ai-ollama'
}
spring-ai-ollama 의존성은 OllamaChatModel에도 접근할 수 있게 해줘요. 그런 다음 OllamaEmbeddingModel 인스턴스를 만들고 두 입력 텍스트의 임베딩을 계산해요.
var ollamaApi = OllamaApi.builder().build();
var embeddingModel = new OllamaEmbeddingModel(this.ollamaApi,
OllamaEmbeddingOptions.builder()
.model(OllamaModel.MISTRAL.id())
.build());
EmbeddingResponse embeddingResponse = this.embeddingModel.call(
new EmbeddingRequest(List.of("Hello World", "World is big and salvation is near"),
OllamaEmbeddingOptions.builder()
.model("chroma/all-minilm-l6-v2-f32"))
.truncate(false)
.build());
OllamaEmbeddingOptions는 모든 임베딩 요청에 대한 설정 정보를 제공해요.