暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

DeepSeek Step by Step(3)——构建web化访问页面

追梦IT人 2025-02-13
198
如前文所述,构建web化访问页面有多种方式,flask、streamlit、gradio都可以,也看过很多基于streamlit、gradio开发简单机器学习和人工智能的页面,毕竟内置了很多组件,这些组件自带CSS,比flask从头到尾构建还是快速很多,虽然笔者对后两者没怎么研究过,但不妨碍就学习deepseek而言只是做个尝试性的demo。
Streamlit 和 Gradio 都是用于构建和部署机器学习应用的工具,deepseek给出的建议是如果你需要构建复杂的数据科学应用或高度定制化的界面,Streamlit 是更好的选择;如果你只需要快速部署和分享机器学习模型,Gradio 更加轻便和高效。就简单实现deepseek对话框而言,个人认为streamlit更加美观和易懂一些。
在streamlit代码中实现流式和批量输出两种模式,就感知而言,当然是流式数据获取和前端流式数据输出更加流畅一些。
  1. import streamlit as st
  2. import requests
  3. import json

  4. # 设置本地DeepSeek APIURL


  5. DEEPSEEK_API_URL = "http://localhost:12345/api/generate"
  6. headers = {"Content-Type": "application/json"}
  7. streamflag=False

  8. # 设置Streamlit页面标题
  9. st.title("DeepSeek 本地对话界面")

  10. # 初始化会话状态
  11. if "messages" not in st.session_state:
  12.     st.session_state.messages = []

  13. # 显示历史消息
  14. for message in st.session_state.messages:
  15.     with st.chat_message(message["role"]):
  16.         st.markdown(message["content"])

  17. # 用户输入
  18. if prompt := st.chat_input("请输入你的问题:"):
  19.     # 添加用户消息到会话状态
  20.     st.session_state.messages.append({"role": "user", "content": prompt})
  21.     with st.chat_message("user"):
  22.         st.markdown(prompt)
  23.     # 定义请求的数据
  24.     data = {
  25.         "model": "deepseek-r1:14b",  # 替换为你的本地模型名称
  26.         "prompt": prompt,
  27.         "stream": True  # 启用流式响应为True,不启用为False
  28.     }
  29.     contentjson = json.dumps(data)

  30.     # ---------------------------------------非流式响应的代码----------------------------------------------
  31.     # try:
  32.     #     response = requests.post(DEEPSEEK_API_URL, headers=headers, data=contentjson)
  33.     #     response.raise_for_status()  # 检查响应状态码
  34.     #     result = response.json()
  35.     #     returntxt=result['response']
  36.     #     returntxt=returntxt.replace('<think>\n\n</think>\n\n','').replace('<think>','').replace('</think>','')
  37.     #     st.markdown(returntxt)
  38.     # except Exception as e:
  39.     #     st.error(f"调用API时出错:{str(e)}")

  40.     # ---------------------------------------流式响应的代码----------------------------------------------
  41.     # 发送请求并处理流式响应
  42.     with st.chat_message("assistant"):
  43.         response_placeholder = st.empty()  # 创建一个占位符用于流式更新
  44.         full_response = ""
  45.         try:
  46.             # 发送POST请求
  47.             with requests.post(DEEPSEEK_API_URL, headers=headers, data=contentjson, stream=True) as response:
  48.                 if response.status_code == 200:
  49.                     # 逐行读取流式响应
  50.                     for line in response.iter_lines():
  51.                         if line:
  52.                             # 解析JSON数据
  53.                             decoded_line = line.decode("utf-8") # 转码
  54.                             chunk = json.loads(decoded_line)    # 将字符串类型的字典转为真正的字典类型
  55.                             # 解析返回内容
  56.                             # 判断是否有返回内容
  57.                             if 'response' in chunk:
  58.                                 piece = chunk['response']       # 获取返回内容
  59.                                 piece=piece.replace('<think>\n\n</think>\n\n','').replace('<think>','').replace('</think>','')  # 对一些符号进行额外处理
  60.                                 if piece !='':
  61.                                     full_response += piece
  62.                                     response_placeholder.markdown(full_response)  # 更新占位符内容
  63.                 else:
  64.                     st.error(f"API调用失败,状态码:{response.status_code}")
  65.         except Exception as e:
  66.             st.error(f"调用API时出错:{str(e)}")

  67.     # 将助手回复添加到会话状态
  68.     st.session_state.messages.append({"role": "assistant", "content": full_response})

这里只需要执行一下相关命令即可 

streamlit run deepseekV3.0.py

运行的效果如下:



在gradio代码中只实现了批量输出模式,关于流式的实在不想找了。

  1. import gradio as gr
  2. import json,requests

  3. DEEPSEEK_API_URL = "http://localhost:12345/api/generate"
  4. headers = {"Content-Type": "application/json"}
  5. streamflag=False


  6. def generate_response(prompt):
  7.     """通过Ollama API生成响应"""
  8.     content = {
  9.         "model": "deepseek-r1:14b",  # 模型名称
  10.         "prompt": prompt,  # 输入的提示信息
  11.         "stream": True  # 是否使用流式响应
  12.     }
  13.     contentjson = json.dumps(content)
  14.     response = requests.post(DEEPSEEK_API_URL, headers=headers, data=contentjson, stream=True)
  15.     response.raise_for_status()
  16.     generated_text = ""
  17.     for line in response.iter_lines():
  18.         if line:
  19.             decoded_line = line.decode('utf-8')
  20.             chunk = json.loads(decoded_line)
  21.             if 'response' in chunk:
  22.                 piece = chunk['response']  # 获取返回内容
  23.                 piece = piece.replace('<think>\n\n</think>\n\n', '').replace('<think>', '').replace('</think>','')  # 对一些符号进行额外处理
  24.                 if piece != '':
  25.                     generated_text += piece
  26.     return generated_text.strip()  # 返回最终的文本,去除最后的换行符

  27. # 创建Gradio界面
  28. iface = gr.Interface(fn=generate_response, inputs=gr.components.Textbox(lines=3, label="输入你的提示"), outputs="text",
  29.                      live=True)
  30. iface.launch()

执行相关命令

python .\deepseekV3.0.py

运行的效果如下:


毕竟无论大模型还是网上的代码都不太靠谱,所有代码必须在实践中不断完善和迭代,上述代码已通过努力在本机上完全跑通,仅供参考,

关于代码实现这部分就翻过去了,后续更多的会关注个人知识库构建和模型微调方面的事情,如有未有相关成效的情况下,也可能会把春节期间关于机器学习的系列先发上来。

最后欢迎关注公众号:python与大数据分析


文章转载自追梦IT人,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论