DeepSeek笔记(三):结合Flask实现以WEB方式访问本地部署的DeepSeek-R1模型

经过硬件升级改造,将显卡升级GeForce RTX 5090,按照前两篇关于DeepSeek笔记,重新搭建了DeepSeek-R1:32b模型。为了后续能通过多终端通过URL访问使用本地的DeepSeek模型,结合Python+Flask+Ollama+DeepSeek-R1:32b模型构建一个Web服务。其过程如下所示:

一、安装必要的库

1.关于Ollama库

在DeepSeek笔记一中安装成功后,可以不需要安装Ollama库。如果不放心,也可以执行下列指令:

bash 复制代码
pip install ollama

2.安装Flask库

运行cmd,启动控制台中,在控制台执行下列命令:

bash 复制代码
pip install flask

二、使用Ollama库访问本地部署的DeepSeek-R1模型

新建一个Python文件,代码如下:

python 复制代码
"""
    利用Ollama封装来调用
"""
from ollama import chat
from ollama import ChatResponse

def getFrmOllama(content:str):
    """
    通过Ollama封装调用

    Args:
        content (str): _消息_
    """
    print("client")
    response:ChatResponse = chat(model="deepseek-r1:32b",messages=[{"role":"user","content":f"{content}"}],)
    print(response['message']['content'])
    print(response.message.content)
    
    
if __name__ =="__main__":
    getFrmOllama("请用英语介绍DeepSeek-R1模型,谢谢!")

测试上述程序,运行结果是:

三、利用Flask生成简单访问DeepSeek-R1模型的Web服务

1.搭建简单的WEB服务

Flask框架可以快速搭建简单的WEB服务。在这里,将搭建一个访问DeepSeek-R1模型的Web简单应用,响应的结果为json数据。代码如下:

python 复制代码
"""
    结合Ollama和flask生成访问DeepSeek模型的api接口
"""

from flask import Flask,request,jsonify
from ollama import chat,ChatResponse

app = Flask("__main__")

def getFrmOllama(content:str):
    """
    表示从

    Args:
        content (str): 表示发送给DeepSeek模型的文本'
    """
    response:ChatResponse = chat(model = "deepseek-r1:32b",
                                 messages=[{"role":"user","content":f"{content}"}])
    result ={"content":f"{content}",
             "response":f"{response.message.content}"}
    return result


@app.route("/result/<string:content>",methods=["GET","POST"])
def getResult(content):
    """
    表示相应的结果

    Args:
        content (_type_): _发出咨询的消息_
        
    """
    response = getFrmOllama(content)
    return jsonify(response)

if __name__ == "__main__":
    app.run()

运行上述代码,Flask顺利启动,但是在浏览器却显示500错误,表示服务器出现内部问题。注意到访问本地部署的DeepSeek-R1模型,响应时间比较久,估计是因为这个原因导致服务出现500错误。因此考虑使用简单的协程方式来处理。将上述的代码修改为如下形式:

python 复制代码
"""
    结合Ollama和flask生成访问DeepSeek模型的api接口
"""

from flask import Flask,request,jsonify
from ollama import chat,ChatResponse

app = Flask("__main__")

async def getFrmOllama(content:str):
    """
    表示从

    Args:
        content (str): 表示发送给DeepSeek模型的文本'
    """
    response:ChatResponse = chat(model = "deepseek-r1:32b",
                                 messages=[{"role":"user","content":f"{content}"}])
    result ={"content":f"{content}",
             "response":f"{response.message.content}"}
    return result


@app.route("/result/<string:content>",methods=["GET","POST"])
def getResult(content):
    """
    表示相应的结果

    Args:
        content (_type_): _发出咨询的消息_
        
    """
    response = asyncio.run(getFrmOllama(content))
    return jsonify(response)

if __name__ == "__main__":
    app.run()

然后启动Flask服务,这时运行结果类似下图所示:

2.在服务中关闭DeepSeek的思考的代码处理

从上述运行结果可以发现,response的信息包括了DeepSeek-R1模型思考的过程,有时并不希望出现思考信息,需要关闭DeepSeek的思考。

python 复制代码
# -*- coding:utf-8 -*-

"""
    结合Ollama和flask生成访问DeepSeek模型的api接口
"""

from flask import Flask,request,jsonify
from ollama import chat,ChatResponse

import asyncio

app = Flask("__main__")

async def getFrmOllama(content:str,think:bool):
    """
    表示从

    Args:
        content (str): 表示发送给DeepSeek模型的文本'
    """
    response:ChatResponse = chat(model = "deepseek-r1:32b",
                                 messages=[{"role":"user","content":f"{content}"}],
                                 think = think)
    result ={"content":f"{content}",
             "response":f"{response.message.content}"}
    return result


@app.route("/result/<string:content>",methods=["GET","POST"])
def getResult(content):
    """
    表示相应的结果

    Args:
        content (_type_): _发出咨询的消息_
        
    """
    response = asyncio.run(getFrmOllama(content,True))
    return jsonify(response)


@app.route("/resultnothink/<string:content>",methods=["GET","POST"])
def getResultWithoutThink(content):
    """
    表示相应的结果

    Args:
        content (_type_): _发出咨询的消息_
        
    """
    response = asyncio.run(getFrmOllama(content,False))
    return jsonify(response)

if __name__ == "__main__":
    app.run()

针对上述代码修改如下几处:

  • 修改getFrmOllama函数,增加一个think参数,参数类型为bool,当think取值为True,表示可以思考,当取值为False,表示关闭思考;
  • 真实启动或关闭DeepSeek-R1模型的思考过程,是通过设置ollama.chat()函数的think参数来实现的;
  • 分别定义getResult函数和getResultWithoutThink函数处理两种不同情况:启动思考和关闭思考;
    运行上述修改后代码,测试关闭思考过程,运行结果如下所示:

    从运行结果可以发现,DeepSeek-R1模型的思考过程的确没有出现。
相关推荐
长路归期无望3 小时前
C语言小白实现多功能计算器的艰难历程
c语言·开发语言·数据结构·笔记·学习·算法
yuxb735 小时前
Ceph 分布式存储学习笔记(二):池管理、认证和授权管理与集群配置(下)
笔记·ceph·学习
悠哉悠哉愿意5 小时前
【ROS2学习笔记】话题通信篇:python话题订阅与发布
笔记·学习·ros2
东方芷兰6 小时前
JavaWeb 课堂笔记 —— 20 SpringBootWeb案例 配置文件
java·开发语言·笔记·算法·log4j·intellij-idea·lua
我命由我123457 小时前
Photoshop - Photoshop 工具库
笔记·学习·ui·职场和发展·职场·photoshop·ps
常州晟凯电子科技8 小时前
君正T32开发笔记之固件烧写
人工智能·笔记·嵌入式硬件·物联网
干饭小白10 小时前
程序员基础数学1-概率论和数理统计-第六章 样本及抽样分布
笔记
hhzz11 小时前
Pythoner 的Flask项目实践-在web页面实现矢量数据转换工具集功能(附源码)
前端·python·flask
哈里谢顿12 小时前
flask中的 Blueprint总结
flask
丰锋ff12 小时前
2021 年真题配套词汇单词笔记(考研真相)
笔记