基于deepseek-r1+ollama+milvus 搭建本地RAG知识库

1,275 阅读4分钟

思路:用户输入-->文本向量化-->搜索向量数据-->搜索结果作为提示词-->DeepSeek-R1-->结果输出。

环境准备:Ollama、JDK17、虚拟机(云服务器也可以)

(1)📢 Ollama安装deepseek-r1:7b

deepseek模型大小根据个人电脑的配置选择,最好是大于1.5b。

Windows系统进入命令提示,通过ollama下载deepseek-r1:7b

ollama run deepseek-r1:7b

(2)🎨 Ollama安装bge-m3:latest

bge-m3是一个向量模型,会将输入的汉字转换成向量。

Windows系统进入命令提示,通过ollama下载bge-m3:latest

ollama run bge-m3:latest

以下是安装好的模型:

image.png

(3)🧊 安装向量数据库milvus

通过Docker安装向量数据库milvus,为了可视化操作数据库,还可以安装zilliz/attu

  • 下载milvus安装脚本(单机模式)
curl -sfL https://raw.githubusercontent.com/milvus-io/milvus/master/scripts/standalone_embed.sh -o standalone_embed.sh
  • 在此之前我们需要创建一个docker网络,zilliz/attu和milvus通信
# 自定义docker网络
docker network create icontainer

# 查看我们创建的docker网络
docker network ls
  • 修改standalone_embed.sh,将docker run时的network指定为自定义的网络,下边是修改后的shell脚本
#!/usr/bin/env bash

# Licensed to the LF AI & Data foundation under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

run_embed() {
    cat << EOF > embedEtcd.yaml
listen-client-urls: http://0.0.0.0:2379
advertise-client-urls: http://0.0.0.0:2379
quota-backend-bytes: 4294967296
auto-compaction-mode: revision
auto-compaction-retention: '1000'
EOF

    cat << EOF > user.yaml
# Extra config to override default milvus.yaml
EOF

    sudo docker run -d \
        --name milvus-standalone \
        --security-opt seccomp:unconfined \
        --net=icontainer \
        -e ETCD_USE_EMBED=true \
        -e ETCD_DATA_DIR=/var/lib/milvus/etcd \
        -e ETCD_CONFIG_PATH=/milvus/configs/embedEtcd.yaml \
        -e COMMON_STORAGETYPE=local \
        -v $(pwd)/volumes/milvus:/var/lib/milvus \
        -v $(pwd)/embedEtcd.yaml:/milvus/configs/embedEtcd.yaml \
        -v $(pwd)/user.yaml:/milvus/configs/user.yaml \
        -p 19530:19530 \
        -p 9091:9091 \
        -p 2379:2379 \
        --health-cmd="curl -f http://localhost:9091/healthz" \
        --health-interval=30s \
        --health-start-period=90s \
        --health-timeout=20s \
        --health-retries=3 \
        milvusdb/milvus:v2.5.4 \
        milvus run standalone  1> /dev/null
}

wait_for_milvus_running() {
    echo "Wait for Milvus Starting..."
    while true
    do
        res=`sudo docker ps|grep milvus-standalone|grep healthy|wc -l`
        if [ $res -eq 1 ]
        then
            echo "Start successfully."
            echo "To change the default Milvus configuration, add your settings to the user.yaml file and then restart the service."
            break
        fi
        sleep 1
    done
}

start() {
    res=`sudo docker ps|grep milvus-standalone|grep healthy|wc -l`
    if [ $res -eq 1 ]
    then
        echo "Milvus is running."
        exit 0
    fi

    res=`sudo docker ps -a|grep milvus-standalone|wc -l`
    if [ $res -eq 1 ]
    then
        sudo docker start milvus-standalone 1> /dev/null
    else
        run_embed
    fi

    if [ $? -ne 0 ]
    then
        echo "Start failed."
        exit 1
    fi

    wait_for_milvus_running
}

stop() {
    sudo docker stop milvus-standalone 1> /dev/null

    if [ $? -ne 0 ]
    then
        echo "Stop failed."
        exit 1
    fi
    echo "Stop successfully."

}

delete_container() {
    res=`sudo docker ps|grep milvus-standalone|wc -l`
    if [ $res -eq 1 ]
    then
        echo "Please stop Milvus service before delete."
        exit 1
    fi
    sudo docker rm milvus-standalone 1> /dev/null
    if [ $? -ne 0 ]
    then
        echo "Delete milvus container failed."
        exit 1
    fi
    echo "Delete milvus container successfully."
}

delete() {
    delete_container
    sudo rm -rf $(pwd)/volumes
    sudo rm -rf $(pwd)/embedEtcd.yaml
    sudo rm -rf $(pwd)/user.yaml
    echo "Delete successfully."
}

upgrade() {
    read -p "Please confirm if you'd like to proceed with the upgrade. The default will be to the latest version. Confirm with 'y' for yes or 'n' for no. > " check
    if [ "$check" == "y" ] ||[ "$check" == "Y" ];then
        res=`sudo docker ps -a|grep milvus-standalone|wc -l`
        if [ $res -eq 1 ]
        then
            stop
            delete_container
        fi

        curl -sfL https://raw.githubusercontent.com/milvus-io/milvus/master/scripts/standalone_embed.sh -o standalone_embed_latest.sh && \
        bash standalone_embed_latest.sh start 1> /dev/null && \
        echo "Upgrade successfully."
    else
        echo "Exit upgrade"
        exit 0
    fi
}

case $1 in
    restart)
        stop
        start
        ;;
    start)
        start
        ;;
    stop)
        stop
        ;;
    upgrade)
        upgrade
        ;;
    delete)
        delete
        ;;
    *)
        echo "please use bash standalone_embed.sh restart|start|stop|upgrade|delete"
        ;;
esac
  • 执行standalone_embed.sh脚本
./standalone_embed.sh start
  • 下载zilliz/attu镜像
docker pull zilliz/attu:v2.5
  • 启动zilliz/attu:v2.5,需要填写宿主机的ip
docker run -d -p 8000:3000 --net=icontainer -e MILVUS_URL=192.168.10.33:19530 zilliz/attu:v2.5

image.png

  • 创建向量数据库,命名deepseek4j_test

image.png

(4)🚀 通过代码测试本地RAG的效果

通过SpringBoot3+JDK17搭建RAG项目

  • 引入相关的maven依赖
<!-- pig提供的deepseek开源工具包 -->
<dependency>
    <groupId>io.github.pig-mesh.ai</groupId>
    <artifactId>deepseek-spring-boot-starter</artifactId>
    <version>1.4.3</version>
</dependency>

<!-- 链接 milvus SDK-->
<dependency>
    <groupId>io.milvus</groupId>
    <artifactId>milvus-sdk-java</artifactId>
    <version>2.5.3</version>
</dependency>
  • 配置yml文件,填写LLM大模型配置
deepseek:
  api-key: deepseek  # 必填项:你的 API 密钥
  model: deepseek-r1:7b
  base-url: http://127.0.0.1:11434/v1  # 可选,默认为官方 API 地址
embedding:
  api-key: embedding
  model: bge-m3:latest
  base-url: http://127.0.0.1:11434/v1
  • 插入测试数据

我们需要向milvus数据库中插入数据

@Autowired
EmbeddingClient embeddingClient;

@GetMapping(value = "/addMilvusData")
public void insert() {
    // Connect to Milvus server
    ConnectConfig connectConfig = ConnectConfig.builder()
            .uri("http://192.168.10.33:19530") // 获取的 Milvus 链接端点
            .serverName("deepseek4j_test")
            .build();
    MilvusClientV2 milvusClientV2 = new MilvusClientV2(connectConfig);
    // 这里可以换成你自己的测试文件
    String law = FileUtil.readString("C:\Users\14997\Desktop\code\Rag测试.txt", StandardCharsets.UTF_8);
    String[] lawSplits = StrUtil.split(law, 400);


    List<JsonObject> data = new ArrayList<>();
    for (String lawSplit : lawSplits) {
        List<Float> floatList = embeddingClient.embed(lawSplit);

        JsonObject jsonObject = new JsonObject();

        // 将 List<Float> 转换为 JsonArray
        JsonArray jsonArray = new JsonArray();
        for (Float value : floatList) {
            jsonArray.add(value);
        }
        jsonObject.add("vector", jsonArray);
        jsonObject.addProperty("text", lawSplit);

        data.add(jsonObject);
    }

    InsertReq insertReq = InsertReq.builder()
            .collectionName("deepseek4j_test")
            .data(data)
            .build();

    milvusClientV2.insert(insertReq);
}

插入结果:

image.png

  • 编写测试代码
@Autowired
private DeepSeekClient deepSeekClient;
@Autowired
EmbeddingClient embeddingClient;

@GetMapping(value = "/chat2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ChatCompletionResponse> chat2(HttpServletResponse response) {

    // Connect to Milvus server
    ConnectConfig connectConfig = ConnectConfig.builder()
            .uri("http://192.168.10.33:19530") // 获取的 Milvus 链接端点
            .serverName("deepseek4j_test")
            .build();

    String prompt = "小明的小狗叫什么?";
    MilvusClientV2 milvusClientV2 = new MilvusClientV2(connectConfig);

    List<Float> floatList = embeddingClient.embed(prompt);

    SearchReq searchReq = SearchReq.builder()
            .collectionName("deepseek4j_test")
            .data(Collections.singletonList(new FloatVec(floatList)))
            .outputFields(Collections.singletonList("text"))
            .searchParams(Map.of("anns_field", "vector"))
            .topK(3)
            .build();

    SearchResp searchResp = milvusClientV2.search(searchReq);

    List<String> resultList = new ArrayList<>();
    List<List<SearchResp.SearchResult>> searchResults = searchResp.getSearchResults();
    for (List<SearchResp.SearchResult> results : searchResults) {
        System.out.println("TopK results:");
        for (SearchResp.SearchResult result : results) {
            resultList.add(result.getEntity().get("text").toString());
        }
    }


    ChatCompletionRequest request = ChatCompletionRequest.builder()
            // 根据渠道模型名称动态修改这个参数
            .model("deepseek-r1:7b")
            .addUserMessage(String.format("你要根据用户输入的问题:%s \n \n 参考如下内容: %s  \n\n 整理处理最终结果", prompt, resultList)).build();
    response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8");
    return deepSeekClient.chatFluxCompletion(request);
}

测试结果:小明的小狗叫米粒

以上就是文章的全部内容。 山高路远,我们江湖再见!