【树莓派 Zero 2W】API 接入 DeepSeek 大语言模型
本文介绍了树莓派 Zero 2W 通过 API 协议接入 DeepSeek 大语言模型,实现终端 AI 对话的项目设计。
项目介绍
准备工作:硬件连接、系统安装、软件包部署等;
API 获取:DeepSeek 大语言模型 API 接口的获取和使用;
终端对话:通过 API 协议接入大语言模型并使用终端模式进行对话;
网页设计:设计前端网页,优化聊天界面。
准备工作
包括硬件连接、系统安装、软件包部署等。
硬件连接
连接 WiFi 实现无线网络通信;
使用 Micro-USB 数据线实现设备供电;


系统安装
Micro-SD 卡需烧录 RaspberryPi 官方操作系统;
软件包部署
安装大语言模型所需的 OpenAI 框架,以及网页服务器所需的 flask 库,终端执行
sudo apt install python3-openai sudo apt install python3-flask
API 获取
大语言模型(large language model,LLM)有种选择,这里选择 DeepSeek 并获取开发者 API 令牌。
DeepSeek API 使用与 OpenAI 兼容的 API 格式。
登录 DeepSeek 开放平台官网: https://platform.deepseek.com/
注册账号,进入 API Keys 标签页;
创建 API key,输入 API 名称;


复制 API 令牌(注意保存令牌)


测试
终端执行指令 touch api_deepseek.py 新建程序文件,并添加如下官方测试代码
import os
from openai import OpenAI
DEEPSEEK_API_KEY = "xxxxxxxxxxx" # API key
client = OpenAI(
api_key=DEEPSEEK_API_KEY,
base_url="https://api.deepseek.com") # LLM API website
response = client.chat.completions.create(
model="deepseek-r3", # change to target model
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hello"},
],
stream=False
)
print(response.choices[0].message.content)创建 API 令牌后,使用脚本访问 DeepSeek API .
终端执行 python api_deepseek.py 指令,输出回复信息


若要更换其他模型,需修改 API 令牌、目标URL、模型名称等参数。
终端对话
调用 DeepSeek 大语言模型 API 接口实现终端模式下的智能对话。
代码
终端执行指令 python api_chat.py 新建程序文件,并添加如下流式代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json, time, signal, sys, requests
API_KEY = "sk-4160dxxxxfa9f0xxxx684" # API Key
def ai_chat(prompt):
""" Send Message """
try:
r = requests.post(
"https://api.deepseek.com",
headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
json={
"model": "deepseek-r3",
"messages": [
{"role": "system", "content": "Simple answer"},
{"role": "user", "content": prompt}
],
"temperature": 0.7,
"max_tokens": 200
},
timeout=10
)
return r.json()["choices"][0]["message"]["content"].strip() if r.status_code == 200 else f"Error: {r.stat>
except Exception as e:
return f"Request error:{e}"
# ------------- main ---------------
signal.signal(signal.SIGINT, lambda *_: print("\nExit") or sys.exit(0))
print("Agent | Input exit to move\n")
while True:
try:
user_input = input("RPi: ").strip()
if user_input.lower() in ['exit', 'quit']: break
if not user_input: continue
start_time = time.time()
reply = ai_chat(user_input)
print(f"AI: ({time.time()-start_time:.1f}s) {reply}\n")
except KeyboardInterrupt:
print("\nGoodbye!")
break
except Exception as e:
print(f"Error: {e}")保存代码。
效果
终端执行指令 python api_chat.py 运行程序;
终端输入语句即可进行对话


网页设计
这里给出了网页设计界面,实现聊天界面的 Web 访问,增强对话体验。
流程图


代码
包括 Web 前端和 flask 后端设计代码。
前端设计
终端执行 touch ./web/index.html 指令新建网页文件,并添加如下代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AI Chat LLM</title>
<style>
body{font-family:Arial,Helvetica,sans-serif;background:#f5f5f5;margin:0;padding:20px}
#box{max-width:600px;margin:auto;background:#fff;border-radius:8px;padding:20px;box-shadow:0 2px 8px rgba(0,0,0>
h2{text-align:center;margin-top:0}
#history{height:400px;overflow-y:auto;border:1px solid #ddd;padding:10px;margin-bottom:10px;background:#fafafa}
.line{margin:6px 0}
.user{color:#0066cc}
.ai{color:#009933}
#inputArea{display:flex}
#msgInput{flex:1;padding:8px;font-size:14px}
#sendBtn{padding:8px 16px;margin-left:6px}
</style>
</head>
<body>
<div id="box">
<h2>Chat AI LLM</h2>
<div id="history"></div>
<div id="inputArea">
<input id="msgInput" placeholder="Input messages, Enter to send"/>
<button id="sendBtn" onclick="send()">Send</button>
</div>
</div>
<script>
const hist = document.getElementById('history');
const input = document.getElementById('msgInput');
function addLine(cls, txt){
const div = document.createElement('div');
div.className = 'line '+cls;
div.textContent = txt;
hist.appendChild(div);
hist.scrollTop = hist.scrollHeight;
}
async function send(){
const msg = input.value.trim();
if(!msg) return;
addLine('user', 'RPi: '+msg);
input.value = '';
const res = await fetch('/chat', {method:'POST', body:new URLSearchParams({msg})});
const data = await res.json();
addLine('ai', 'AI: '+data.reply);
}
input.addEventListener('keydown', e=>{if(e.key==='Enter') send()});
</script>
</body>
</html>后端设计
后端程序修改
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json, time, requests, signal, sys
from flask import Flask, send_from_directory, request, jsonify
API_KEY = "sk-4160dxxxx1480bxxxx9f0c2xxx7684" # API Key
MODEL_URL = "https://api.deepseek.com"
app = Flask(__name__)
# ---------- LLM connect ----------
def ai_chat(prompt: str) -> str:
try:
resp = requests.post(
MODEL_URL,
headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
json={
"model": "deepseek-r3",
"messages": [
{"role": "system", "content": "Sample Answer"},
{"role": "user", "content": prompt}
],
"temperature": 0.7,
"max_tokens": 200
},
timeout=10
)
if resp.status_code == 200:
return resp.json()["choices"][0]["message"]["content"].strip()
return f"Error: HTTP {resp.status_code}"
except Exception as e:
return f"Request error: {e}"
# ---------- Route ----------
@app.route("/")
def index():
return send_from_directory("web", "index.html")
@app.route("/static/<path:filename>")
def web_static(filename):
return send_from_directory("web", filename)
@app.route("/chat", methods=["POST"])
def chat():
user_input = request.form.get("msg", "").strip()
if not user_input:
return jsonify({"reply": "input cannot empty"})
start = time.time()
reply = ai_chat(user_input)
return jsonify({"reply": f"({time.time()-start:.1f}s) {reply}"})
# ---------- Exit ----------
signal.signal(signal.SIGINT, lambda *_: print("\nExit") or sys.exit(0))
# ---------- Start ----------
if __name__ == "__main__":
print("Web server start http://127.0.0.1:5000")
app.run(host="0.0.0.0", port=5000, debug=False)保存代码。
效果演示
终端执行 python3 api_chat_web.py 指令,运行程序;
终端打印 Flask 服务器对应的网址信息;


在浏览器中输入服务器地址及端口,如 192.168.31.111:5000 进入目标 AI Chat 网页;


总结
本文介绍了树莓派 Zero 2W 通过 API 协议接入 DeepSeek 大语言模型,实现终端 AI 对话的项目设计,为相关产品在 AI 大语言模型领域的快速开发设计和应用提供了参考。
我要赚赏金
