Skills MCP Model 博客 提交 Skills

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 Projects
10
Complete Projects
100%
Runnable Code
5 Major
Application Scenarios

All 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..."},

# {"q": "What payment methods are supported?", "a": "WeChat, Alipay, bank cards..."} # ], # "policies": { # "return": "7-day no-reason return, items must be in original packaging...", # "warranty": "All products enjoy 1-year warranty service..." # } # }

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

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: with open(args.output, "w", encoding="utf-8") as f: f.write(report) print(f"Review report saved to: {args.output}") else: print("\n" + "=" * 60) print(report) print("=" * 60) if __name__ == "__main__": main()

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) prompt = f"""You are a professional document Q&A assistant. Please answer the user's question based on the following document content. Rules: 1. If the document contains relevant information, cite it accurately and answer 2. If the document does not contain relevant information, clearly inform the user 3. Mark the citation source at the end of the answer (e.g., "According to paragraph X of the document") Document content: {context} User question: {query} Please answer: """ response = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": prompt}], temperature=0.1, max_tokens=2048 ) return response.choices[0].message.content # Streamlit UI st.set_page_config(page_title="DeepSeek Document Q&A", layout="wide") st.title("DeepSeek Intelligent Document Q&A") tab1, tab2 = st.tabs(["Upload Document", "Ask"]) with tab1: uploaded_file = st.file_uploader("Upload PDF document", type=["pdf"]) if uploaded_file: with st.spinner("Parsing document..."): text = extract_text_from_pdf(uploaded_file) st.info(f"Extracted {len(text)} characters") chunks = split_text(text) count = index_document(chunks, uploaded_file.name) st.success(f"Indexed {count} text chunks. You can now ask questions!") with tab2: query = st.text_input("Enter your question") if query: with st.spinner("Retrieving and generating answer..."): chunks = search_documents(query) if chunks: answer = generate_answer(query, chunks) st.markdown(answer) with st.expander("View retrieved document chunks"): for i, chunk in enumerate(chunks): st.markdown(f"**Chunk {i+1}:**") st.text(chunk[:300] + "...") else: st.warning("No relevant document content found. Please upload a document first.")

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") parser.add_argument("text", nargs="?", help="Text to translate") parser.add_argument("--file", "-f", help="Read text from file") parser.add_argument("--source", "-s", default="zh", help="Source language code (default: zh)") parser.add_argument("--target", "-t", default="en", help="Target language code (default: en)") parser.add_argument("--glossary", "-g", help="Glossary JSON file path") parser.add_argument("--output", "-o", help="Output JSON file path") parser.add_argument("--batch", "-b", help="Batch translation: JSON file path (one entry per line)") args = parser.parse_args() glossary = load_glossary(args.glossary) if args.batch: with open(args.batch, "r", encoding="utf-8") as f: texts = json.load(f) results = batch_translate(texts, args.source, args.target, glossary) output = json.dumps(results, ensure_ascii=False, indent=2) elif args.file: with open(args.file, "r", encoding="utf-8") as f: text = f.read() result = translate_text(text, args.source, args.target, glossary) output = json.dumps({"source": text, "target": result}, ensure_ascii=False, indent=2) elif args.text: result = translate_text(args.text, args.source, args.target, glossary) output = json.dumps({"source": args.text, "target": result}, ensure_ascii=False, indent=2) else: parser.print_help() return if args.output: with open(args.output, "w", encoding="utf-8") as f: f.write(output) print(f"Translation result saved to: {args.output}") else: print(output) if __name__ == "__main__": main()

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 ) response = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": prompt}], temperature=0.1, max_tokens=2048 ) code = response.choices[0].message.content.strip() code = code.replace("```python", "").replace("```", "").strip() st.code(code, language="python") with st.spinner("Executing analysis..."): try: local_vars = {"df": df.copy(), "pd": pd, "plt": plt, "result_df": None, "fig": None} exec(code, {"__builtins__": __builtins__}, local_vars) result_df = local_vars.get("result_df") fig = local_vars.get("fig") if result_df is not None: st.subheader("Analysis Results") st.dataframe(result_df, use_container_width=True) csv = result_df.to_csv(index=False).encode("utf-8-sig") st.download_button("Download CSV", csv, "analysis_result.csv", "text/csv") buffer = io.BytesIO() with pd.ExcelWriter(buffer, engine="openpyxl") as writer: result_df.to_excel(writer, index=False, sheet_name="Analysis Results") st.download_button("Download Excel", buffer.getvalue(), "analysis_result.xlsx") if fig is not None: st.subheader("Visualization Charts") st.pyplot(fig) if result_df is not None: with st.spinner("Generating analysis report..."): summary = result_df.describe().to_string() report_prompt = REPORT_PROMPT.format(query=query, summary=summary[:3000]) report = client.chat.completions.create( model="deepseek-chat", messages=[{"role": "user", "content": report_prompt}], temperature=0.3, max_tokens=2048 ) st.subheader("Analysis Report") st.markdown(report.choices[0].message.content) except Exception as e: st.error(f"Code execution error: {str(e)}") st.info("Please try to rephrase your analysis requirements")

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"): date = datetime.now().strftime("%Y-%m-%d") if platform == "hugo": return f"""--- title: "{title}" date: {date} draft: false tags: [{', '.join([f'\"{t}\"' for t in tags])}] description: "{description}" categories: ["技术"] ---""" elif platform == "hexo": return f"""--- title: {title} date: {date} tags: [{', '.join(tags)}] description: {description} ---""" else: return f"""--- title: {title} date: {date} tags: [{', '.join(tags)}] description: {description} ---""" def save_article(content, filename, front_matter=""): full_content = f"{front_matter}\n\n{content}" if front_matter else content os.makedirs("output", exist_ok=True) filepath = os.path.join("output", filename) with open(filepath, "w", encoding="utf-8") as f: f.write(full_content) return filepath def main(): parser = argparse.ArgumentParser(description="DeepSeek Markdown 博客生成器") parser.add_argument("topic", help="文章主题") parser.add_argument("--style", "-s", default="技术深度", help="写作风格") parser.add_argument("--audience", "-a", default="开发者", help="目标读者") parser.add_argument("--tags", "-t", nargs="+", default=[], help="文章标签") parser.add_argument("--platform", "-p", default="hugo", choices=["hugo", "hexo", "jekyll", "vitepress"]) parser.add_argument("--series", type=int, help="生成系列文章规划(指定数量)") parser.add_argument("--desc", "-d", default="", help="文章描述") args = parser.parse_args() if args.series: print(f"正在生成「{args.topic}」系列文章规划 ({args.series} 篇)...") series = generate_series(args.topic, args.series) filepath = save_article(json.dumps(series, ensure_ascii=False, indent=2), "series_plan.json") print(f"系列规划已保存至: {filepath}") for item in series: print(f" [{item['order']}] {item['title']} - {item['description']}") return print(f"正在生成「{args.topic}」大纲...") outline = generate_outline(args.topic, args.style, args.audience) print("大纲:\n" + outline) print(f"\n正在生成完整文章...") article = generate_article(args.topic, outline, args.style, args.audience) slug = args.topic.lower().replace(" ", "-").replace("/", "-") filename = f"{slug}.md" description = args.desc or f"关于{args.topic}的深度技术文章" tags = args.tags or ["技术", "教程"] front_matter = create_front_matter(args.topic, description, tags, args.platform) filepath = save_article(article, filename, front_matter) word_count = len(article) print(f"\n文章已保存至: {filepath}") print(f"字数: {word_count}") if __name__ == "__main__": main()

运行方式

# 安装依赖 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(): table.add_row(key, model["label"], model["desc"]) console.print(table) def chat(messages, model="deepseek-chat"): try: response = client.chat.completions.create( model=model, messages=messages, temperature=0.7, max_tokens=4096 ) return response.choices[0].message.content except Exception as e: return f"[Error] API call failed: {str(e)}" def main(): history = load_history() show_banner() messages = [{"role": "system", "content": "You are a helpful AI assistant powered by DeepSeek. Please answer in Chinese."}] current_model = history["settings"]["model"] conv_id = datetime.now().strftime("%Y%m%d_%H%M%S") while True: try: user_input = Prompt.ask("\n[bold green]You[/bold green]") if user_input.startswith("/"): cmd = user_input.strip().lower() if cmd == "/quit": console.print("[yellow]Goodbye![/yellow]") break elif cmd == "/help": show_help() elif cmd == "/model": show_model_selector() choice = Prompt.ask("Select model number", default="1") if choice in MODELS: current_model = MODELS[choice]["name"] history["settings"]["model"] = current_model save_history(history) console.print(f"[green]Switched to: {MODELS[choice]['label']}[/green]") elif cmd == "/clear": messages = [messages[0]] conv_id = datetime.now().strftime("%Y%m%d_%H%M%S") console.print("[green]Conversation cleared[/green]") elif cmd == "/save": history["conversations"].append({ "id": conv_id, "date": datetime.now().isoformat(), "model": current_model, "messages": messages[1:] }) save_history(history) console.print(f"[green]Conversation saved (ID: {conv_id})[/green]") elif cmd == "/history": if not history["conversations"]: console.print("[dim]No previous conversations[/dim]") else: for conv in history["conversations"][-10:]: console.print(f" [cyan]{conv['id']}[/cyan] {conv['date'][:10]} ({conv['model']}) - {len(conv['messages'])} turns") elif cmd.startswith("/load"): parts = user_input.split() if len(parts) > 1: target_id = parts[1] for conv in history["conversations"]: if conv["id"] == target_id: messages = [messages[0]] + conv["messages"] conv_id = target_id current_model = conv["model"] console.print(f"[green]Loaded conversation: {target_id}[/green]") break else: console.print("[red]Conversation not found[/red]") continue messages.append({"role": "user", "content": user_input}) with console.status("[cyan]Thinking...[/cyan]"): reply = chat(messages, current_model) messages.append({"role": "assistant", "content": reply}) console.print(f"\n[bold blue]DeepSeek[/bold blue]:") console.print(Markdown(reply)) except KeyboardInterrupt: console.print("\n[yellow]Goodbye![/yellow]") break except EOFError: break if __name__ == "__main__": main()

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")

resume_file = st.file_uploader("Upload PDF Resume", type=["pdf"], key="resume") if resume_file: resume_text = extract_pdf_text(resume_file) st.text_area("Resume Content Preview", resume_text, height=300) with col2: st.subheader("Job Description") jd_text = st.text_area("Paste Job Description (JD)", height=300, placeholder="Paste the full description of the target position...") if resume_file and jd_text and st.button("Start Analysis", type="primary"): with st.spinner("Analyzing resume-job match..."): analysis = analyze_resume(resume_text, jd_text) st.subheader("Match Analysis") col_a, col_b, col_c = st.columns(3) col_a.metric("Skill Match", f"{analysis.get('skill_match', 0)}%") col_b.metric("Experience Match", f"{analysis.get('experience_match', 0)}%") col_c.metric("Overall Match", f"{analysis.get('overall_match', 0)}%") col_m, col_n = st.columns(2) with col_m: st.markdown("**Matched Skills**") for skill in analysis.get("matched_skills", []): st.markdown(f"- {skill}") with col_n: st.markdown("**Missing Skills**") for skill in analysis.get("missing_skills", []): st.markdown(f"- {skill}") st.markdown("**Resume Strengths**") for s in analysis.get("strengths", []): st.markdown(f"- {s}") st.markdown("**Improvement Suggestions**") for s in analysis.get("improvements", []): st.markdown(f"- {s}") st.markdown("**ATS Optimization Suggestions**") for s in analysis.get("ats_suggestions", []): st.markdown(f"- {s}") if st.button("Generate Optimized Resume"): with st.spinner("Optimizing resume..."): optimized = optimize_resume(resume_text, jd_text, analysis) st.subheader("Optimized Resume") st.markdown(optimized) st.download_button("Download Optimized Resume", optimized, "optimized_resume.md")

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 content = content.replace("```json", "").replace("```", "").strip() return json.loads(content) def build_html_email(briefing): date_str = briefing.get("date", datetime.now().strftime("%Y年%m月%d日")) html = f"""

AI Daily Briefing

{date_str} | Generated by DeepSeek

""" if briefing.get("highlight"): html += '
' html += '

Today's Highlights

' for item in briefing["highlight"]: html += f'

{item["title"]}

' html += f'

{item["summary"]}

' html += f'

{item.get("reason", "")}

' html += '
' category_icons = { "大模型动态": "LLM", "开源工具": "Open", "行业应用": "App", "学术研究": "Edu", "其他": "More" } for category, news_list in briefing.get("categories", {}).items(): if not news_list: continue icon = category_icons.get(category, category[:2]) html += f'

[{icon}] {category}

' for news in news_list: stars = str(news.get("rating", 3)) + " points" html += f'''

{news["title"]}

{news["summary"]}

{stars}
''' if briefing.get("thought"): html += f'''

Today's Thought

{briefing["thought"]}

''' html += '

This briefing is automatically generated by DeepSeek AI | Sent daily at 8:00

' html += '
' return html def send_email(html_content): msg = MIMEMultipart("alternative") msg["Subject"] = f"AI Daily Briefing - {datetime.now().strftime('%Y-%m-%d')}" msg["From"] = EMAIL_USER msg["To"] = ", ".join(RECIPIENTS) msg.attach(MIMEText(html_content, "html", "utf-8")) server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) server.starttls() server.login(EMAIL_USER, EMAIL_PASS) server.send_message(msg) server.quit() print(f"Briefing sent to: {', '.join(RECIPIENTS)}") def main(): print(f"[{datetime.now()}] Starting daily AI briefing generation...") print("Fetching news...") articles = fetch_news() print(f"Fetched {len(articles)} articles") print("Generating briefing...") briefing = generate_briefing(articles) html = build_html_email(briefing) if EMAIL_USER and RECIPIENTS and RECIPIENTS[0]: print("Sending email...") send_email(html) else: output_path = f"briefing_{datetime.now().strftime('%Y%m%d')}.html" with open(output_path, "w", encoding="utf-8") as f: f.write(html) print(f"Briefing saved to: {output_path}") if __name__ == "__main__": if not EMAIL_USER or not EMAIL_PASS: print("Email sending not configured, saving as local HTML file") print("To send email, set EMAIL_USER, EMAIL_PASS, RECIPIENTS environment variables") main()

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

Do these projects require a paid DeepSeek API? +
DeepSeek API offers a free tier; new users receive a certain number of tokens upon registration. All projects use the DeepSeek API, which is billed per usage and extremely cost-effective. For example, the deepseek-chat model costs only a few RMB per million tokens. If you deploy DeepSeek locally using Ollama, it is completely free. In the project code, you only need to change the base_url to point to your local Ollama instance to switch.
Can these projects run on Windows? +
All projects are developed in Python and are cross-platform compatible with Windows, macOS, and Linux. When running on Windows, ensure Python 3.10+ is installed and dependencies are installed via pip. Streamlit projects run perfectly on Windows. The email project requires configuring the correct IMAP/SMTP server addresses (e.g., for QQ Mail: imap.qq.com / smtp.qq.com).
How do I replace the DeepSeek API with a local Ollama model in the projects? +
Simply modify two parts of the code: change the base_url from "https://api.deepseek.com" to "http://localhost:11434/v1", and change the model name from "deepseek-chat" to your Ollama model name (e.g., "deepseek-r1:8b"). The API Key can be any string (Ollama local does not require verification). All project code is fully compatible with the OpenAI API format, so switching is seamless.
Can these projects be used directly in production? +
The project code provides complete core functionality, but for direct production use, we recommend the following enhancements: 1) Add user authentication and permission management; 2) Use persistent storage like Redis instead of in-memory storage; 3) Add request rate limiting and error retry mechanisms; 4) Configure logging and monitoring alerts; 5) Manage sensitive information using environment variables and configuration files. The code is suitable as a learning reference and for rapid prototyping; production deployment requires customization based on actual needs.
How can I contribute code or suggest improvements to the projects? +
These projects are part of the DeepSeek practical tutorial, and you are free to modify and distribute the code. If you have suggestions or find bugs, you can provide feedback through the following channels: 1) Submit an Issue on the project's GitHub repository; 2) Fork the repository and submit a Pull Request; 3) Share your improved version through the DeepSeek official community. We encourage community contributions to jointly improve these practical projects.

Related Tutorials & Resources

Deep dive into DeepSeek model usage, deployment, and development techniques, from beginner to advanced.

每日精选 Skill 推荐,免费送到你邮箱

输入邮箱,每天接收一个精选 AI Agent 技能推荐。完全免费,持续更新。

完全免费,取消任意时间。我们不会发送垃圾邮件。