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模型的思考过程的确没有出现。
相关推荐
302wanger1 小时前
【阅读笔记】当AI拿走一切之后
笔记
疯狂打码的少年2 小时前
【数据结构】串(字符串):基本概念与存储
数据结构·笔记
Hotchip_MEMS4 小时前
TWS耳机微米级较量:超薄LGA封装如何助力MEMS麦克风小型化?
人工智能·笔记·物联网·电脑
Ztt6666666665 小时前
金泉方壶四面端正,月白釉却把棱角放柔了
经验分享·笔记·其他·百度·微信公众平台
学习和思考5 小时前
非自动化专业如何自学PLC?我的6个月学习路线图
笔记·学习·自动化·学习方法
疯狂打码的少年6 小时前
【数据结构】栈的应用:表达式求值(后缀表达式)
java·数据结构·笔记·算法
東隅已逝,桑榆非晚7 小时前
类和对象(中)
c++·笔记
野生yumeko8 小时前
QtScrcpy电脑无线控制手机屏幕
经验分享·笔记·智能手机
mit6.8249 小时前
archived
后端·python·flask
xian_wwq9 小时前
【学习笔记】Loop Engineering,从手动提示到目标驱动自动化-13/16
笔记·学习·自动化