Streamlit的DeepSeek对话应用,提供简单、直观的AI交互体验
1. 项目概述
一个基于Streamlit的DeepSeek对话应用,提供简单、直观的AI交互体验。
2. 环境准备
2.1 安装依赖
pip install streamlit requests
3. 完整代码实现
import streamlit as st
import requests
import json
from typing import List, Dict
# 配置DeepSeek API
DEEPSEEK_API_URL = "https://api.siliconflow.cn/v1/chat/completions"
class DeepSeekChatApp:
def __init__(self):
# 初始化会话状态
if 'messages' not in st.session_state:
st.session_state.messages = []
# API密钥配置
self.api_key = st.secrets.get("DEEPSEEK_API_KEY", "your_api_key")
def get_deepseek_response(self, messages: List[Dict], temperature: float = 0.7) -> str:
"""调用DeepSeek API获取响应"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
payload = {
"model": "deepseek-ai/DeepSeek-V3",
"messages": messages,
"temperature": temperature,
"max_tokens": 2048,
"stream": True
}
try:
response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload, stream=True)
response.raise_for_status()
full_response = ""
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
if line == 'data: [DONE]':
break
try:
chunk = json.loads(line[6:])
if chunk['choices'][0]['delta'].get('content'):
content = chunk['choices'][0]['delta']['content']
full_response += content
yield content
except json.JSONDecodeError:
continue
except requests.RequestException as e:
st.error(f"API调用错误: {str(e)}")
yield f"API调用错误: {str(e)}"
def render_chat_interface(self):
"""渲染聊天界面"""
st.title("🤖 DeepSeek AI 对话助手")
# 侧边栏配置
with st.sidebar:
st.header("对话设置")
temperature = st.slider("创造力", 0.0, 1.0, 0.7, step=0.1)
system_prompt = st.text_area("系统角色设定", "你是一个友好、专业的AI助手")
# 显示历史消息
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# 用户输入
if prompt := st.chat_input("输入您的问题"):
# 添加用户消息
st.session_state.messages.append({"role": "user", "content": prompt})
# 显示用户消息
with st.chat_message("user"):
st.markdown(prompt)
# 准备API消息列表
messages = [
{"role": "system", "content": system_prompt},
*[{"role": m["role"], "content": m["content"]} for m in st.session_state.messages]
]
# 显示AI响应
with st.chat_message("assistant"):
response_placeholder = st.empty()
full_response = ""
# 流式显示响应
for chunk in self.get_deepseek_response(messages, temperature):
full_response += chunk
response_placeholder.markdown(full_response + "▌")
response_placeholder.markdown(full_response)
# 保存AI消息
st.session_state.messages.append({"role": "assistant", "content": full_response})
def main():
chat_app = DeepSeekChatApp()
chat_app.render_chat_interface()
if __name__ == "__main__":
main()
4. 应用特性
4.1 核心功能
- 流式对话交互
- 动态系统角色设定
- 对话历史记录
- 可调节AI创造力
4.2 技术亮点
- 使用Streamlit构建界面
- 流式API调用
- 上下文管理
- 错误处理机制
5. 运行方法
streamlit run deepseek_chat_app.py
6. 注意事项
- 需要有效的DeepSeek API密钥
- 建议在
st.secrets
中配置密钥 - 遵守API使用条款
7. API Key 和 Secrets 管理
1. Streamlit Secrets 配置
1.1 创建 secrets.toml 文件
在项目根目录创建 .streamlit/secrets.toml
文件:
# DeepSeek API配置
DEEPSEEK_API_KEY = "your_api_key_here"
DEEPSEEK_API_URL = "https://api.siliconflow.cn/v1/chat/completions"
1.2 安全存储 API Key
- 使用
.streamlit/secrets.toml
管理敏感信息 - 将
.streamlit/secrets.toml
添加到.gitignore
- 避免将 API Key 硬编码到代码中
2. 环境变量替代方案
2.1 设置环境变量
# Linux/Mac
export DEEPSEEK_API_KEY='your_api_key'
# Windows
set DEEPSEEK_API_KEY=your_api_key
3. 最佳实践
3.1 API Key 安全建议
- 不要在公开仓库中存储 API Key
- 使用环境变量或 secrets 管理
- 定期更换 API Key
- 限制 API Key 的权限和使用范围
3.2 权限控制
- 仅授予必要的 API 权限
- 监控 API 使用情况
- 设置使用配额和限制
8. 体验DeepSeek
快来体验 DeepSeek: