1.介绍
1.1 什么是华为云Flexus X实例
最近华为云828 B2B企业节正在举办,Flexus X实例的促销也非常给力,大家可以去看看。特别是对算力性能有要求,同时对自建MySQL、Redis、Nginx性能有要求的小伙伴,千万不要错过。
Flexus云服务器X实例是新一代面向中小企业和开发者打的柔性算力云服务器,可智能感知业务负载,适用于电商直播、企业建站、开发测试环境、游戏服务器、音视频服务等中低负载场景。

1.2什么是Ollama
Ollama是一个开源的 LLM(大型语言模型)服务工具,用于简化在本地运行大语言模型,降低使用大语言模型的门槛,使得大模型的开发者、研究人员和爱好者能够在本地环境快速实验、管理和部署最新大语言模型,包括如Llama 3、Phi 3、Mistral、Gemma,Qwen等开源的大型语言模型。

2 准备华为云Flexus应用服务器L实例
注册并登录华为云找到华为云Flexus云服务

选择合适的服务器进行购买
选择相应的配置并购买
购买之后找到控制台进行密码修改和远程登陆
使用远程连接工具连接云服务器

3 部署Ollama服务

这里官网提供了三种系统的安装包这里下载安装即可使用。
这里我采用docker部署的方式
docker pull ollama/ollama

查看镜像
docker image ls

运行容器
bash
docker run -itd -p11434:11434 --name ollama ollama/ollama

进入容器中

拉取对应的大模型 (mistral,llama3,qwen2,...)这里以mistral为例

运行对应的大模型 ollama run mistral

4 实现问答对话
这里我们使用Spring AI 快速搭建一个问答服务其中集成了ollama 可以快速链接到ollama服务,记得开放11434的端口
XML
<properties>
<java.version>17</java.version>
<spring-ai.version>1.0.0-M1</spring-ai.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>
</dependencies>
java
@RestController
@RequestMapping("/chat")
public class ChatController {
@Resource
private OllamaChatModel ollamaChatModel;
@Resource
private InMemoryChatMemory inMemoryChatMemory;
@Operation(summary = "同步输出")
@GetMapping("/question")
public String question(@RequestParam String question) {
return ollamaChatModel.call(question);
}
@Operation(summary = "流式输出")
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> stream(@RequestParam String question) {
return ollamaChatModel.stream(question);
}
@Operation(summary = "连续对话")
@GetMapping(value = "/history", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> history(@RequestParam String conversationId, @RequestParam String question) {
List<Message> messages = new ArrayList<>();
List<Message> conversation = inMemoryChatMemory.get(conversationId, 10);
if (conversation != null) {
messages.addAll(conversation);
}
messages.add(new UserMessage(question));
Prompt prompt = new Prompt(messages);
UserMessage message = new UserMessage(question);
List<Message> userMessages = new ArrayList<>();
userMessages.add(message);
inMemoryChatMemory.add(conversationId, userMessages);
return ollamaChatModel.stream(prompt).map((result) -> result.getResult().getOutput().getContent());
}
}
