基于上一个项目Spring Boot 接入Ollama实现与Deepseek简单对话修改,增加嵌入库配置,修改模型拉取策略为always
application.yml配置参考:
spring:
application:
name: demo-boot-ollama
ai:
ollama:
init:
pull-model-strategy: always # 下载策略
embedding:
additional-models:
- mxbai-embed-large
- nomic-embed-text
base-url: http://192.168.31.162:11434
chat:
options:
model: deepseek-r1:8b
启动项目可以看到在拉取项目日志:
提示:虽然打开模型拉取为自动,但是底部不过国内下载慢,容易挂。所以建议还是先拉取好了再来用。。。
spring 官网文章也有提到会影响程序启动
![]()
所以实际使用推荐配置为never并提前下载好模型。
spring: application: name: demo-boot-ollama ai: ollama: init: pull-model-strategy: never # 下载策略
@RestController
public class EmbeddingController {
@Resource
EmbeddingModel embeddingModel;
@GetMapping("/ai/embedding")
public Map embed(@RequestParam(value = "message",defaultValue = "告诉我一个笑话")String message) {
EmbeddingResponse embeddingResponse = this.embeddingModel.embedForResponse(List.of(message));
return Map.of("embedding", embeddingResponse);
}
}
重启项目后访问:
手动嵌入测试
public class EmbedTests {
public static void main(String[] args) {
var ollamaApi = new OllamaApi("http://192.168.31.162:11434");
OllamaEmbeddingModel embeddingModel = new OllamaEmbeddingModel(
ollamaApi,
OllamaOptions.builder()
.model(OllamaModel.MISTRAL.id())
.build(),
ObservationRegistry.NOOP,
ModelManagementOptions.defaults()
);
EmbeddingResponse helloWorld = embeddingModel.call(
new EmbeddingRequest(
List.of("Hello World", "World is big and salvation is near"),
OllamaOptions.builder().model("chroma/all-minilm-l6-v2-f32")
.truncate(false)//truncate | 截断,删节;把……截成平面
.build()
)
);
Map<String, EmbeddingResponse> embedding = Map.of("embedding", helloWorld);
System.out.println(helloWorld);
}
}
提示:请先下载好模型
chroma/all-minilm-l6-v2-f32
命令:ollama pull chroma/all-minilm-l6-v2-f32
特别提醒:文中的向量与矢量都是代指 Vector 仅各个平台翻译不同,无任何区别。故向量数据库也是矢量数据库 或者 Vector Database
http://blog.xqlee.com/article/2502181258385692.html