DeepSeek Practical Project Collection
10 complete and runnable DeepSeek practical projects, from AI customer service to data analysis, from code review to intelligent translation. Each project includes complete code, tech stack description, and deployment guide. Copy and run with one click.
View ProjectsAll projects are built on the DeepSeek API, compatible with V3 and R1 models, supporting Python 3.10+
10 Complete Runnable Projects
All projects are real runnable code, covering scenarios such as AI customer service, code review, document Q&A, translation, data analysis, content generation, conversation terminal, email processing, resume optimization, and news aggregation. Each project runs independently and does not depend on each other.
AI Customer Service Robot
A web-based customer service robot built with Flask, integrating DeepSeek API, supporting multi-turn dialogue, knowledge base retrieval, and context memory. Suitable for scenarios such as embedding in corporate websites and after-sales consultation.
Tech Stack
| Web Framework | Flask 3.x |
| AI Model | DeepSeek API (deepseek-chat) |
| Knowledge Base | JSON file storage + semantic retrieval |
| Frontend | HTML + CSS + JavaScript (vanilla) |
Complete Code
# app.py import os import json from flask import Flask, request, jsonify, render_template from openai import OpenAI app = Flask(__name__) client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com") # Load knowledge base with open("knowledge_base.json", "r", encoding="utf-8") as f: KNOWLEDGE_BASE = json.load(f) # Session storage (recommend Redis in production) sessions = {} SYSTEM_PROMPT = """You are a professional customer service assistant. Please answer user questions based on the following knowledge base content. Rules: 1. If the knowledge base contains relevant information, cite it accurately 2. If not, politely inform the user that they need to be transferred to a human agent 3. Keep a friendly, professional, and concise answering style Knowledge base content: {knowledge} Current conversation history: {history}""" def build_prompt(session_id, user_message): session = sessions.get(session_id, {"history": []}) history_text = "\n".join([f"{'User' if h['role']=='user' else 'Agent'}: {h['content']}" for h in session["history"][-6:]]) knowledge_text = json.dumps(KNOWLEDGE_BASE, ensure_ascii=False, indent=2) return SYSTEM_PROMPT.format(knowledge=knowledge_text, history=history_text) @app.route("/") def index(): return render_template("index.html") @app.route("/chat", methods=["POST"]) def chat(): data = request.json session_id = data.get("session_id", "default") user_message = data.get("message", "") if not user_message: return jsonify({"error": "Message cannot be empty"}), 400 if session_id not in sessions: sessions[session_id] = {"history": []} sessions[session_id]["history"].append({"role": "user", "content": user_message}) prompt = build_prompt(session_id, user_message) response = client.chat.completions.create( model="deepseek-chat", messages=[ {"role": "system", "content": prompt}, {"role": "user", "content": user_message} ], temperature=0.3, max_tokens=1024 ) reply = response.choices[0].message.content sessions[session_id]["history"].append({"role": "assistant", "content": reply}) return jsonify({"reply": reply, "session_id": session_id}) if __name__ == "__main__": app.run(debug=True, port=5000) # knowledge_base.json # { # "faq": [ # {"q": "How to return?", "a": "Click apply return on the order page..."}, # {"q": "How long is shipping time?", "a": "Ships within 48 hours after ordering..."},
How to Run
# Install dependencies pip install flask openai # Set environment variables export DEEPSEEK_API_KEY="sk-your-api-key" # Create knowledge base file echo '{"faq":[{"q":"How to return?","a":"Click apply for return on the order page..."}]}' > knowledge_base.json # Run python app.py # Visit http://localhost:5000
Expected Results
- Users ask questions through the web chat interface, and the bot answers in real-time based on the knowledge base
- Supports multi-turn dialogue, remembers context (last 6 turns)
- Content outside the knowledge base will guide users to transfer to human customer service
- Response latency < 2 seconds (depends on API network latency)
Code Review Assistant
A command-line tool that analyzes git diff output and uses DeepSeek R1 reasoning capabilities for in-depth code review. Automatically detects security vulnerabilities, code smells, best practice suggestions, and generates structured review reports.
Tech Stack
| Runtime Environment | CLI (Command Line Tool) |
| AI Model | DeepSeek R1 (deepseek-reasoner) + V3 (deepseek-chat) |
| Analysis Dimensions | Security vulnerabilities, code quality, performance, best practices |
| Output Format | Markdown / JSON / Terminal color output |
Complete Code
#!/usr/bin/env python3
# code_review.py
import os
import sys
import subprocess
import argparse
from openai import OpenAI
client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
REVIEW_PROMPT = """You are a senior code review expert. Please conduct an in-depth review of the following git diff and output a structured report.
Review dimensions:
1. Security vulnerabilities: SQL injection, XSS, sensitive information leakage, permission issues
2. Code quality: naming conventions, function length, complexity, duplicate code
3. Performance issues: N+1 queries, unnecessary loops, memory leak risks
4. Best practices: error handling, logging, type safety, test coverage
Output format (Markdown):
## Code Review Report
### Security Vulnerabilities
- [Severity] Problem description + suggested fix
### Code Quality Issues
- [Severity] Problem description + suggested refactoring
### Performance Issues
- [Severity] Problem description + optimization suggestions
### Best Practice Suggestions
- [Priority] Suggestion content
### Overall Rating
- Security: X/10
- Code Quality: X/10
- Performance: X/10
- Overall: X/10
Git Diff:
{diff}"""
def get_git_diff(staged_only=False):
cmd = ["git", "diff", "--cached"] if staged_only else ["git", "diff"]
try:
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
print(f"Error: git diff execution failed: {result.stderr}")
sys.exit(1)
return result.stdout.strip()
except FileNotFoundError:
print("Error: git command not found, please confirm you are in a git repository")
sys.exit(1)
def review_code(diff_text, use_reasoner=False):
model = "deepseek-reasoner" if use_reasoner else "deepseek-chat"
prompt = REVIEW_PROMPT.format(diff=diff_text[:30000])
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=0.1,
max_tokens=4096
)
return response.choices[0].message.content
def main():
parser = argparse.ArgumentParser(description="DeepSeek Code Review Assistant")
parser.add_argument("--staged", action="store_true", help="Only review staged changes")
parser.add_argument("--reasoner", action="store_true", help="Use R1 reasoning model (deeper but slower)")
parser.add_argument("--output", "-o", help="Output file path")
parser.add_argument("--json", action="store_true", help="Output in JSON format")
args = parser.parse_args()
diff = get_git_diff(args.staged)
if not diff:
print("No code changes to review")
return
print(f"Reviewing {len(diff)} characters of code changes...")
report = review_code(diff, args.reasoner)
if args.output:
How to Run
# Install dependencies pip install openai # Run in a git repository python code_review.py # Review staged changes python code_review.py --staged # Use R1 reasoning model for deep review python code_review.py --reasoner # Save report to file python code_review.py -o review_report.md
Expected Output
- Outputs a structured Markdown review report covering four dimensions: security, quality, performance, and best practices
- R1 reasoning mode can discover deep logical issues and potential bugs
- Supports JSON format output for easy integration into CI/CD pipelines
- Each issue includes a severity rating and specific fix suggestions
Intelligent Document Q&A (RAG System)
A document Q&A system based on the RAG architecture, supporting PDF upload, ChromaDB vector storage, and a Streamlit web interface. After uploading documents, users can perform natural language Q&A based on the document content, with cited sources.
Tech Stack
| UI Framework | Streamlit |
| Document Parsing | PyMuPDF (fitz) + LangChain Text Splitters |
| Vector Database | ChromaDB |
| AI Model | DeepSeek API (deepseek-chat) |
| Embedding | sentence-transformers (BGE Chinese model) |
Complete Code
# rag_qa.py
import os
import streamlit as st
import fitz # PyMuPDF
import chromadb
from chromadb.utils import embedding_functions
from openai import OpenAI
from langchain.text_splitter import RecursiveCharacterTextSplitter
client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
# Initialize ChromaDB
chroma_client = chromadb.PersistentClient(path="./chroma_db")
sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(
model_name="BAAI/bge-small-zh-v1.5"
)
def get_or_create_collection(name="documents"):
try:
return chroma_client.get_collection(name, embedding_function=sentence_transformer_ef)
except:
return chroma_client.create_collection(name, embedding_function=sentence_transformer_ef)
def extract_text_from_pdf(pdf_file):
doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
text = ""
for page in doc:
text += page.get_text()
return text
def split_text(text, chunk_size=500, overlap=50):
splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size, chunk_overlap=overlap,
separators=["\n\n", "\n", "。", "!", "?", ";", ".", " ", ""]
)
return splitter.split_text(text)
def index_document(text_chunks, doc_name):
collection = get_or_create_collection()
existing = collection.get()["ids"]
if existing:
collection.delete(ids=existing)
ids = [f"{doc_name}_{i}" for i in range(len(text_chunks))]
collection.add(documents=text_chunks, ids=ids)
return len(text_chunks)
def search_documents(query, top_k=3):
collection = get_or_create_collection()
results = collection.query(query_texts=[query], n_results=top_k)
return results["documents"][0] if results["documents"] else []
def generate_answer(query, context_chunks):
context = "\n\n---\n\n".join(context_chunks)
How to Run
# Install dependencies pip install streamlit PyMuPDF chromadb openai langchain sentence-transformers # Run streamlit run rag_qa.py # Visit http://localhost:8501
Expected Results
- Automatically indexes after uploading PDF, supports semantic search for Chinese documents
- Retrieves the most relevant document chunks when asking, generates accurate answers based on context
- Marks citation sources in the answer, can expand to view original document chunks
- Supports multiple document uploads, automatically re-indexes when switching documents
Multilingual Translation Tool
A high-quality translation tool based on the DeepSeek API, supporting batch translation, custom glossary, and JSON format output. Suitable for technical document translation, multilingual content localization, and other scenarios.
Tech Stack
| Runtime Environment | CLI + Python library |
| AI Model | DeepSeek API (deepseek-chat) |
| Supported Languages | 20+ languages including Chinese, English, Japanese, Korean, French, German, Spanish, Russian, etc. |
| Output Format | JSON / Markdown / Plain text |
Complete Code
#!/usr/bin/env python3
# translator.py
import os
import json
import argparse
from openai import OpenAI
client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
LANGUAGE_MAP = {
"zh": "Chinese", "en": "English", "ja": "Japanese", "ko": "Korean",
"fr": "French", "de": "German", "es": "Spanish", "ru": "Russian",
"pt": "Portuguese", "ar": "Arabic", "th": "Thai", "vi": "Vietnamese"
}
TRANSLATE_PROMPT = """You are a professional translation engine. Please translate the following text from {source} to {target}.
Translation requirements:
1. Maintain the original tone and style
2. Use industry-standard translations for technical terms
3. If a glossary is provided, strictly follow the glossary definitions
4. Do not translate code, numbers, or proper nouns
5. Return only the translated text, without any explanations
{glossary_section}
Original text:
{text}"""
def load_glossary(filepath):
if not filepath or not os.path.exists(filepath):
return {}
with open(filepath, "r", encoding="utf-8") as f:
glossary = json.load(f) if filepath.endswith(".json") else {}
if isinstance(glossary, list):
glossary = {item["source"]: item["target"] for item in glossary}
return glossary
def build_glossary_section(glossary):
if not glossary:
return ""
items = "\n".join([f"- {k} -> {v}" for k, v in glossary.items()])
return f"Glossary (must strictly follow):\n{items}"
def translate_text(text, source="zh", target="en", glossary=None):
source_name = LANGUAGE_MAP.get(source, source)
target_name = LANGUAGE_MAP.get(target, target)
glossary_section = build_glossary_section(glossary)
prompt = TRANSLATE_PROMPT.format(
source=source_name, target=target_name,
glossary_section=glossary_section, text=text
)
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}],
temperature=0.1,
max_tokens=4096
)
return response.choices[0].message.content
def batch_translate(texts, source="zh", target="en", glossary=None):
results = []
for i, text in enumerate(texts):
print(f"Translating... ({i+1}/{len(texts)})")
translated = translate_text(text, source, target, glossary)
results.append({"source": text, "target": translated})
return results
def main():
parser = argparse.ArgumentParser(description="DeepSeek Multilingual Translation Tool")
How to Run
# Install dependencies pip install openai # Single sentence translation python translator.py "人工智能正在改变世界" --target en # File translation python translator.py -f document.txt -s zh -t ja # Batch translation python translator.py -b texts.json -s zh -t en -o results.json # Translation with glossary python translator.py -f tech_doc.txt -g glossary.json -o translated.json
Expected Results
- Supports translation between 20+ languages, with quality close to professional human translation
- Glossary ensures consistency of technical terms
- Batch translation supports JSON input/output, easy to integrate into automated workflows
- Code, numbers, and proper nouns are automatically preserved without translation
Data Analysis Assistant
A natural language-driven data analysis tool. Users describe analysis needs in Chinese, and the system automatically generates Pandas code, executes analysis, generates charts, and exports Excel reports. Zero-code data analysis.
Tech Stack
| UI Framework | Streamlit |
| Data Processing | Pandas + NumPy |
| Visualization | Matplotlib + Plotly |
| AI Model | DeepSeek API (deepseek-chat) |
| Export | Excel (openpyxl) |
Complete Code
# data_analyst.py
import os
import io
import pandas as pd
import matplotlib.pyplot as plt
import streamlit as st
from openai import OpenAI
client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
CODE_GEN_PROMPT = """You are a Pandas data analysis expert. Generate executable Python code based on the user's data analysis needs.
Data information:
- Column names: {columns}
- Data types: {dtypes}
- Number of rows: {rows}
- Preview of first 5 rows:
{preview}
User requirement: {query}
Please generate a piece of Python code to implement the user's analysis needs. Code requirements:
1. Use variable df as the input DataFrame
2. Store analysis results in result_df variable (DataFrame format)
3. If a chart is needed, store the chart object in fig variable
4. Output only code, no explanatory text
5. Code must be safe, do not perform any file operations or network requests
```python"""
REPORT_PROMPT = """You are a data analyst. Based on the following analysis results, generate a concise data analysis report.
Analysis requirement: {query}
Analysis result summary: {summary}
Please generate a structured analysis report including:
1. Analysis overview
2. Key findings (3-5 items)
3. Data insights
4. Recommendations"""
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
st.set_page_config(page_title="DeepSeek Data Analysis Assistant", layout="wide")
st.title("DeepSeek Data Analysis Assistant")
uploaded_file = st.file_uploader("Upload data file", type=["csv", "xlsx", "xls"])
if uploaded_file:
if uploaded_file.name.endswith(".csv"):
df = pd.read_csv(uploaded_file)
else:
df = pd.read_excel(uploaded_file)
st.subheader("Data Preview")
st.dataframe(df.head(10), use_container_width=True)
col1, col2, col3 = st.columns(3)
col1.metric("Rows", len(df))
col2.metric("Columns", len(df.columns))
col3.metric("Missing Values", df.isnull().sum().sum())
query = st.text_area("Describe your analysis needs in Chinese", placeholder="e.g., Calculate sales by month and draw a trend chart; find the top 10 products with highest sales; analyze user age distribution, etc.")
if st.button("Start Analysis", type="primary") and query:
with st.spinner("DeepSeek is generating analysis code..."):
preview = df.head(5).to_string()
columns = ", ".join(df.columns.tolist())
dtypes = ", ".join([f"{c}: {t}" for c, t in df.dtypes.items()])
prompt = CODE_GEN_PROMPT.format(
columns=columns, dtypes=dtypes, rows=len(df),
preview=preview, query=query
)
How to Run
# Install dependencies pip install streamlit pandas openpyxl matplotlib openai # Run streamlit run data_analyst.py # Visit http://localhost:8501
Expected Outcomes
- After uploading a CSV/Excel file, describe your analysis needs in Chinese to automatically generate analysis code
- Automatically execute Pandas analysis, display result tables and visualization charts
- One-click export of analysis results to CSV or Excel format
- Automatically generate structured data analysis reports
Markdown Blog Generator
Enter a topic to automatically generate a complete Markdown blog post, including SEO-optimized front matter, structured content, and series article generation. Suitable for technical blog authors and content creators.
Tech Stack
| Runtime Environment | CLI + Python Script |
| AI Model | DeepSeek API (deepseek-chat) |
| Output Format | Markdown file (with front matter) |
| Supported Platforms | Hugo / Hexo / Jekyll / VitePress |
Complete Code
#!/usr/bin/env python3
# blog_generator.py
import os
import json
import argparse
from datetime import datetime
from openai import OpenAI
client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
OUTLINE_PROMPT = """You are a senior technical blog author. Please generate a detailed article outline for the following topic.
Topic: {topic}
Writing style: {style}
Target audience: {audience}
Please generate a detailed outline with 5-8 sections, each with 2-3 sub-points."""
ARTICLE_PROMPT = """You are a senior technical blog author. Please write a complete Markdown blog post based on the outline.
Topic: {topic}
Outline:
{outline}
Writing style: {style}
Target audience: {audience}
Requirements:
1. Use Markdown format with appropriate heading levels
2. Include code examples (if applicable)
3. Content should be detailed, each section at least 150 words
4. Start with an engaging introduction
5. End with a summary and outlook
6. Do not use HTML tags, pure Markdown format"""
SERIES_PROMPT = """You are a technical blog planner. Please generate a series article plan for the following topic.
Topic: {topic}
Number of series articles: {count}
Please generate a JSON array, each element containing:
- title: Article title
- slug: URL-friendly title
- description: Short description (within 20 characters)
- order: Sequence number
Return only the JSON array, no other content."""
def generate_outline(topic, style="Technical depth", audience="Developers"):
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": OUTLINE_PROMPT.format(
topic=topic, style=style, audience=audience
)}],
temperature=0.7,
max_tokens=2048
)
return response.choices[0].message.content
def generate_article(topic, outline, style="Technical depth", audience="Developers"):
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": ARTICLE_PROMPT.format(
topic=topic, outline=outline, style=style, audience=audience
)}],
temperature=0.7,
max_tokens=8192
)
return response.choices[0].message.content
def generate_series(topic, count=5):
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": SERIES_PROMPT.format(
topic=topic, count=count
)}],
temperature=0.7,
max_tokens=2048
)
text = response.choices[0].message.content
text = text.replace("```json", "").replace("```", "").strip()
return json.loads(text)
def create_front_matter(title, description, tags, platform="hugo"):
运行方式
# 安装依赖 pip install openai # 生成单篇文章 python blog_generator.py "Python 异步编程最佳实践" --tags Python 异步 编程 # 指定写作风格和目标读者 python blog_generator.py "Kubernetes 入门指南" --style "通俗易懂" --audience "运维新手" # 生成系列文章规划 python blog_generator.py "微服务架构设计" --series 5 # 指定博客平台 python blog_generator.py "React Hooks 深度解析" --platform hexo
预期效果
- 输入主题自动生成结构化大纲和完整 Markdown 文章
- 自动生成 SEO 友好的 front matter(Hugo/Hexo/Jekyll/VitePress)
- 支持系列文章规划,一次性生成多篇文章的选题和描述
- 文章包含代码示例、引言、总结等完整结构
AI 对话终端
基于 Rich 库的终端 AI 对话工具,支持多模型切换、对话历史保存、Markdown 渲染、代码高亮。适合开发者在终端中快速使用 DeepSeek。
技术栈
| 运行环境 | CLI (终端) |
| 终端 UI | Rich + Prompt Toolkit |
| AI 模型 | DeepSeek API (V3 + R1) |
| 历史存储 | JSON 文件 + 对话搜索 |
完整代码
#!/usr/bin/env python3
# ai_terminal.py
import os
import json
from datetime import datetime
from openai import OpenAI
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.prompt import Prompt
from rich.table import Table
console = Console()
client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
HISTORY_FILE = os.path.expanduser("~/.deepseek_terminal_history.json")
MODELS = {
"1": {"name": "deepseek-chat", "label": "DeepSeek V3 (对话)", "desc": "通用对话模型,适合日常使用"},
"2": {"name": "deepseek-reasoner", "label": "DeepSeek R1 (推理)", "desc": "推理模型,适合复杂问题分析"},
}
def load_history():
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return {"conversations": [], "settings": {"model": "deepseek-chat"}}
def save_history(history):
with open(HISTORY_FILE, "w", encoding="utf-8") as f:
json.dump(history, f, ensure_ascii=False, indent=2)
def show_banner():
banner = """
[bold cyan] ____ ____ __
/ __ \\___ ____ / __/_________ / /__
/ / / / _ \\/ __ \\/ /_/ ___/ __ \\/ //_/
/ /_/ / __/ /_/ / __(__ ) /_/ / ,<
/_____/\___/ .___/_/ /____/\____/_/|_|
/_/
[/bold cyan]
[dim]AI 对话终端 v1.0 | 输入 /help 查看命令 | /quit 退出[/dim]"""
console.print(banner)
def show_help():
help_table = Table(title="可用命令")
help_table.add_column("命令", style="cyan")
help_table.add_column("说明", style="green")
help_table.add_row("/help", "显示帮助信息")
help_table.add_row("/model", "切换模型 (V3/R1)")
help_table.add_row("/history", "查看对话历史")
help_table.add_row("/clear", "清除当前对话")
help_table.add_row("/save", "保存当前对话")
help_table.add_row("/load [id]", "加载历史对话")
help_table.add_row("/quit", "退出程序")
console.print(help_table)
def show_model_selector():
table = Table(title="选择模型")
table.add_column("编号", style="cyan")
table.add_column("模型", style="green")
table.add_column("说明")
for key, model in MODELS.items():
How to Run
# Install dependencies pip install openai rich # Run python ai_terminal.py
Expected Effects
- Chat directly with DeepSeek in the terminal, with Markdown rendering and code highlighting
- Support real-time switching between V3 and R1 models
- Conversation history automatically saved to a local JSON file, with loading and search support
- Quick operations via / commands without leaving the terminal
Email Auto-Reply System
Read emails via IMAP, use DeepSeek for intelligent classification and reply generation, support template replies and human-in-the-loop review. Suitable for customer service emails, business inquiries, etc.
Tech Stack
| Email Protocol | IMAP (read) + SMTP (send) |
| AI Model | DeepSeek API (deepseek-chat) |
| Classification Engine | DeepSeek text classification |
| Review Mechanism | Manual confirmation before sending (Human-in-the-loop) |
Complete Code
#!/usr/bin/env python3 # email_reply.py import os import imaplib import smtplib import email from email.mime.text import MIMEText from email.header import decode_header from openai import OpenAI client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com") # Email configuration IMAP_SERVER = os.getenv("IMAP_SERVER", "imap.gmail.com") IMAP_PORT = int(os.getenv("IMAP_PORT", "993")) SMTP_SERVER = os.getenv("SMTP_SERVER", "smtp.gmail.com") SMTP_PORT = int(os.getenv("SMTP_PORT", "587")) EMAIL_USER = os.getenv("EMAIL_USER") EMAIL_PASS = os.getenv("EMAIL_PASS") REPLY_TEMPLATES = { "Product Inquiry": """Thank you for your inquiry! Regarding {product}, here are the details: {details} If you have any other questions, feel free to contact us.""", "After-sales Support": """Thank you for contacting after-sales support. Regarding the issue you reported, we suggest: {solution} If you need further assistance, please provide more information.""", "Business Cooperation": """Thank you for your interest in cooperation! We are very happy to communicate further with you. {response} Looking forward to working with you!""", "Other": """Thank you for your email. {response} Best regards!""" } CLASSIFY_PROMPT = """You are an email classification assistant. Please classify the following email into one of these categories: - Product Inquiry: asking about product features, price, usage - After-sales Support: complaints, bug reports, returns/exchanges - Business Cooperation: cooperation intent, business negotiation - Spam: advertisements, scams, irrelevant content - Other: emails that cannot be categorized Return only the category name, no other content. Email subject: {subject} Email body: {body}""" REPLY_PROMPT = """You are a professional email reply assistant. Please generate a reply for the following email. Email category: {category} Email subject: {subject} Email body: {body} Reply template: {template} Please generate specific reply content, filling in the template variables. Requirements: 1. Reply professionally, politely, and concisely 2. Provide substantive answers to specific questions in the email 3. If the email information is insufficient, proactively ask for additional information needed Please return in JSON format, containing the variables needed to fill the template: {{"product": "...", "details": "...", "solution": "...", "response": "..."}}""" def decode_email_header(header): if not header: return "" decoded_parts = decode_header(header) subject = "" for part, charset in decoded_parts: if isinstance(part, bytes): subject += part.decode(charset or "utf-8", errors="ignore") else: subject += str(part) return subject def get_email_body(msg): body = "" if msg.is_multipart(): for part in msg.walk(): content_type = part.get_content_type() if content_type == "text/plain": try: body = part.get_payload(decode=True).decode("utf-8", errors="ignore") except: body = str(part.get_payload()) break else: try: body = msg.get_payload(decode=True).decode("utf-8", errors="ignore") except: body = str(msg.get_payload()) return body[:3000] def fetch_unread_emails(limit=10): mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT) mail.login(EMAIL_USER, EMAIL_PASS) mail.select("inbox") _, data = mail.search(None, "UNSEEN") email_ids = data[0].split()[-limit:] emails = [] for eid in email_ids: _, msg_data = mail.fetch(eid, "(RFC822)") msg = email.message_from_bytes(msg_data[0][1]) subject = decode_email_header(msg["Subject"]) sender = msg["From"] body = get_email_body(msg) emails.append({"id": eid.decode(), "subject": subject, "sender": sender, "body": body}) mail.logout() return emails def classify_email(subject, body): response = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": CLASSIFY_PROMPT.format( subject=subject[:200], body=body[:2000] )}], temperature=0.1, max_tokens=50 ) return response.choices[0].message.content.strip() def generate_reply(category, subject, body): template = REPLY_TEMPLATES.get(category, REPLY_TEMPLATES["Other"]) response = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": REPLY_PROMPT.format( category=category, subject=subject[:200], body=body[:2000], template=template )}], temperature=0.3, max_tokens=2048 ) import json try: text = response.choices[0].message.content text = text.replace("```json", "").replace("```", "").strip() vars_dict = json.loads(text) except: vars_dict = {"response": "We have received your email and will reply to you as soon as possible."} return template.format(**{k: v for k, v in vars_dict.items() if k in template}) def send_reply(to_address, subject, body): msg = MIMEText(body, "plain", "utf-8") msg["Subject"] = f"Re: {subject}" msg["From"] = EMAIL_USER msg["To"] = to_address server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) server.starttls() server.login(EMAIL_USER, EMAIL_PASS) server.send_message(msg) server.quit() print(f"Reply sent to: {to_address}") def main(): print("Checking unread emails...") emails = fetch_unread_emails() if not emails: print("No unread emails") return print(f"Found {len(emails)} unread emails\n") for i, mail in enumerate(emails): print(f"\n{'='*50}") print(f"[{i+1}/{len(emails)}] From: {mail['sender']}") print(f"Subject: {mail['subject']}") category = classify_email(mail["subject"], mail["body"]) if category == "Spam": print(f"Category: {category} (skipped)") continue print(f"Category: {category}") reply = generate_reply(category, mail["subject"], mail["body"]) print(f"\nGenerated reply:\n{reply}") choice = input("\nSend this reply? (y=send / n=skip / e=edit): ").strip().lower() if choice == "y": send_reply(mail["sender"], mail["subject"], reply) elif choice == "e": custom_reply = input("Enter your reply: ") if custom_reply.strip(): send_reply(mail["sender"], mail["subject"], custom_reply) print("Custom reply sent") else: print("Skipped") if __name__ == "__main__": if not EMAIL_USER or not EMAIL_PASS: print("Please set environment variables EMAIL_USER and EMAIL_PASS") print("For Gmail, you need to use an app-specific password") exit(1) main()
How to Run
# Install dependencies pip install openai
Set Environment Variables (Gmail Example)
export EMAIL_USER="your-email@gmail.com"
export EMAIL_PASS="your-app-password"
export IMAP_SERVER="imap.gmail.com"
export SMTP_SERVER="smtp.gmail.com"
# Run
python email_reply.py
Expected Results
- Automatically detect unread emails and categorize them (product inquiry/after-sales/business/spam)
- Generate professional replies using corresponding templates based on category
- Human review step: confirm before sending, support editing custom replies
- Automatically filter spam to improve processing efficiency
Resume Optimization Tool
Parse PDF resumes, match job descriptions (JD), analyze skill gaps, and provide ATS optimization suggestions. Help job seekers improve their resume pass rate.
Tech Stack
| UI Framework | Streamlit |
| Resume Parsing | PyMuPDF (fitz) |
| AI Model | DeepSeek API (deepseek-chat) |
| Output | Match score + improvement suggestions + optimized resume |
Full Code
# resume_optimizer.py import os import streamlit as st import fitz from openai import OpenAI client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com") ANALYZE_PROMPT = """You are a senior HR and resume optimization expert. Please analyze the match between the following resume and job description. Resume content: {resume} Job description: {jd} Please analyze from the following dimensions and provide results in JSON format: 1. Skill match (0-100%) 2. Experience match (0-100%) 3. Overall match (0-100%) 4. List of matched skills 5. List of missing skills 6. Resume strengths (3-5 items) 7. Resume improvement suggestions (3-5 items) 8. ATS optimization suggestions (3-5 items) Return JSON format: {{ "skill_match": number, "experience_match": number, "overall_match": number, "matched_skills": ["skill1", "skill2"], "missing_skills": ["skill1", "skill2"], "strengths": ["strength1", "strength2"], "improvements": ["suggestion1", "suggestion2"], "ats_suggestions": ["suggestion1", "suggestion2"] }}""" OPTIMIZE_PROMPT = """You are a senior resume optimization expert. Please optimize the resume content based on the following analysis and suggestions. Original resume: {resume} Job description: {jd} Match analysis: {analysis} Optimization requirements: 1. Highlight skills and experience that match the JD 2. Use industry keywords (ATS-friendly) 3. Quantify achievements (use numbers and percentages) 4. Keep the original resume's factual information, do not fabricate experience 5. Optimize wording and layout structure Please output the optimized complete resume.""" def extract_pdf_text(pdf_file): doc = fitz.open(stream=pdf_file.read(), filetype="pdf") text = "" for page in doc: text += page.get_text() return text def analyze_resume(resume_text, jd_text): response = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": ANALYZE_PROMPT.format( resume=resume_text[:5000], jd=jd_text[:3000] )}], temperature=0.1, max_tokens=2048 ) import json content = response.choices[0].message.content content = content.replace("```json", "").replace("```", "").strip() return json.loads(content) def optimize_resume(resume_text, jd_text, analysis): response = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": OPTIMIZE_PROMPT.format( resume=resume_text[:5000], jd=jd_text[:3000], analysis=json.dumps(analysis, ensure_ascii=False, indent=2) )}], temperature=0.3, max_tokens=4096 ) return response.choices[0].message.content st.set_page_config(page_title="DeepSeek Resume Optimization", layout="wide") st.title("DeepSeek Resume Optimization Tool") col1, col2 = st.columns(2) with col1: st.subheader("Upload Resume")
How to Run
# Install dependencies pip install streamlit PyMuPDF openai # Run streamlit run resume_optimizer.py # Visit http://localhost:8501
Expected Outcomes
- Upload PDF resume and paste JD, automatically analyze match
- Three-dimensional scoring (skills/experience/overall), visually display match status
- List matched and missing skills, provide specific improvement suggestions
- One-click generate ATS-friendly optimized resume, downloadable as Markdown
Daily AI Briefing
Automatically aggregate AI news, use DeepSeek for intelligent summarization and categorization, generate a beautiful daily briefing and send it via email on a schedule. Supports cron scheduling.
Tech Stack
| News Sources | RSS Feeds + Web Scraping |
| AI Model | DeepSeek API (deepseek-chat) |
| Email Sending | SMTP + HTML Email Template |
| Scheduling | cron / schedule library |
Full Code
#!/usr/bin/env python3
# daily_briefing.py
import os
import json
import smtplib
import feedparser
from datetime import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from openai import OpenAI
client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
# Email configuration
SMTP_SERVER = os.getenv("SMTP_SERVER", "smtp.gmail.com")
SMTP_PORT = int(os.getenv("SMTP_PORT", "587"))
EMAIL_USER = os.getenv("EMAIL_USER")
EMAIL_PASS = os.getenv("EMAIL_PASS")
RECIPIENTS = os.getenv("RECIPIENTS", "").split(",")
# AI news RSS feeds
RSS_FEEDS = [
"https://hnrss.org/frontpage?count=20",
"https://arxiv.org/rss/cs.AI",
"https://www.reddit.com/r/MachineLearning/.rss",
]
SUMMARIZE_PROMPT = """You are an AI industry analyst. Please generate a daily briefing summary for the following news items.
Requirements:
1. Classify news into: Large Model Updates, Open Source Tools, Industry Applications, Academic Research, Other
2. Select the 3-5 most important news for each category
3. Each news includes: title, one-sentence summary (within 30 characters), importance rating (1-5 stars)
4. Generate a "Today's Highlights" section, highlighting the 1-2 most important news
5. Add "Today's Thought" at the end (industry insight within 100 characters)
News items (title + summary):
{articles}
Please return in JSON format:
{{
"date": "date",
"highlight": [{{"title": "...", "summary": "...", "reason": "..."}}],
"categories": {{
"Large Model Updates": [{{"title": "...", "summary": "...", "rating": 5}}],
"Open Source Tools": [...],
"Industry Applications": [...],
"Academic Research": [...],
"Other": [...]
}},
"thought": "Today's thought content"
}}"""
def fetch_news():
articles = []
for feed_url in RSS_FEEDS:
try:
feed = feedparser.parse(feed_url)
for entry in feed.entries[:10]:
title = entry.get("title", "No title")
summary = entry.get("summary", entry.get("description", ""))
summary = summary[:200]
articles.append(f"- {title}: {summary}")
except Exception as e:
print(f"Failed to fetch RSS ({feed_url}): {e}")
return articles
def generate_briefing(articles):
articles_text = "\n".join(articles[:50])
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": SUMMARIZE_PROMPT.format(
articles=articles_text[:8000]
)}],
temperature=0.3,
max_tokens=4096
)
content = response.choices[0].message.content
{date_str} | Generated by DeepSeek {item["title"]} {item["summary"]} {item.get("reason", "")} {news["title"]} {news["summary"]} {briefing["thought"]} This briefing is automatically generated by DeepSeek AI | Sent daily at 8:00AI Daily Briefing
Today's Highlights
'
for item in briefing["highlight"]:
html += f'[{icon}] {category}
'
for news in news_list:
stars = str(news.get("rating", 3)) + " points"
html += f'''Today's Thought
How to Run
# Install dependencies pip install openai feedparser # Set environment variables export EMAIL_USER="your-email@gmail.com" export EMAIL_PASS="your-app-password" export RECIPIENTS="user1@example.com,user2@example.com" # Run manually python daily_briefing.py # Configure cron job (every day at 8:00 AM) # crontab -e # 0 8 * * * cd /path/to/project && python daily_briefing.py
Expected Results
- Automatically aggregate AI news from multiple RSS sources
- DeepSeek intelligently categorizes and summarizes, generating structured briefings
- Beautiful HTML email template with today's highlights and industry insights
- Supports cron scheduling for automatic daily sending
DeepSeek Practical Projects FAQ
Related Tutorials & Resources
Deep dive into DeepSeek model usage, deployment, and development techniques, from beginner to advanced.
DeepSeek Usage Tutorial
Four usage methods, from zero to mastery.
DeepSeek API Guide
API integration, pricing, rate limits, best practices.
DeepSeek + LangChain Development
Complete tutorial on Chain, Agent, Tool development.
DeepSeek RAG Knowledge Base
Retrieval-augmented generation for enterprise knowledge base Q&A.
DeepSeek Prompt Engineering
Prompt design techniques, templates, and best practices.
DeepSeek Fine-tuning Tutorial
LoRA/QLoRA fine-tuning to customize your own model.
DeepSeek Deployment Tutorial
Ollama, Docker, vLLM, K8s deployment solutions.
DeepSeek Ecosystem Tools
Ollama, Open WebUI, Dify, Continue.dev, etc.
Build AI Apps with DeepSeek + Dify
Visual orchestration, drag-and-drop workflow design.
DeepSeek Model Complete Guide
Technical architecture, benchmark performance comparison, model selection.
DeepSeek Open Source Models
Complete catalog of 6 series, 20+ models.
DeepSeek Model Download
Download guides for Ollama, Hugging Face, GitHub.