Skills MCP Model 博客 提交 Skills

DeepSeek + LangChain Development Tutorial

LangChain is the most popular framework for building LLM applications. This tutorial starts from scratch and teaches you how to build complete AI applications using DeepSeek models + LangChain.

Start Learning

Why Choose DeepSeek + LangChain?

DeepSeek offers extremely high performance and low-cost API services, while LangChain provides a mature LLM application development framework. Combining the two makes AI application development simple and efficient.

Environment Preparation

Before coding, you need to prepare the Python development environment and necessary dependencies.

1.1 Install Python

Ensure your system has Python 3.9 or higher installed. Python 3.11+ is recommended for better performance.

# Check Python version python --version # Example output: Python 3.11.8 # If not installed, please visit https://www.python.org/downloads/ to download and install

1.2 Create a Virtual Environment (Recommended)

Using a virtual environment isolates project dependencies and avoids conflicts with other projects.

# Create project directory mkdir deepseek-langchain-app cd deepseek-langchain-app # Create virtual environment python -m venv venv # Activate virtual environment # Windows: venv\Scripts\activate # macOS/Linux: source venv/bin/activate

1.3 Install LangChain and Dependencies

# Core dependencies pip install langchain langchain-openai # Optional dependencies for later chapters pip install langchain-community faiss-cpu tiktoken

1.4 Get DeepSeek API Key

Visit platform.deepseek.com, register and log in, then create a key on the "API Keys" page. It is recommended to set the API Key as an environment variable:

# Windows PowerShell $env:DEEPSEEK_API_KEY = "sk-your-api-key-here" # macOS/Linux export DEEPSEEK_API_KEY="sk-your-api-key-here" # Or read in Python code import os api_key = os.getenv("DEEPSEEK_API_KEY")

Security Note

Never hardcode API keys in your code. Use environment variables or a .env file to manage sensitive information. Add the .env file to .gitignore.

Basic Call — Using LangChain to Call DeepSeek

LangChain uses the ChatOpenAI class to be compatible with OpenAI-format APIs. Simply modify the base_url and model parameters to connect to DeepSeek.

2.1 Simplest Call

from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage, SystemMessage # Create DeepSeek model instance llm = ChatOpenAI( model="deepseek-chat", # V3 model; for R1 reasoning use "deepseek-reasoner" api_key="sk-your-api-key-here", # Recommended to use environment variable base_url="https://api.deepseek.com/v1", temperature=0.7, max_tokens=512, ) # Send messages messages = [ SystemMessage(content="You are a professional Chinese AI assistant, concise and accurate."), HumanMessage(content="Please introduce the LangChain framework in three sentences."), ] response = llm.invoke(messages) print(response.content)

2.2 Streaming Output

Streaming output allows the AI to return content word by word like typing, improving user experience.

from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage llm = ChatOpenAI( model="deepseek-chat", api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", streaming=True, # Enable streaming output ) messages = [HumanMessage(content="Write a quicksort algorithm in Python")] for chunk in llm.stream(messages): print(chunk.content, end="", flush=True)

2.3 Using DeepSeek R1 Reasoning Model

DeepSeek R1 is a reasoning-enhanced model that performs better on complex tasks such as mathematics, logic, and programming. The calling method is exactly the same as V3, just change the model name.

from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage # Use DeepSeek R1 reasoning model llm = ChatOpenAI( model="deepseek-reasoner", # R1 reasoning model api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", ) messages = [HumanMessage(content="Prove that the square root of 2 is irrational")] response = llm.invoke(messages) print(response.content)

Model Selection Recommendations

  • deepseek-chat (V3): Daily conversation, content writing, translation, general code generation, best cost-performance
  • deepseek-reasoner (R1): Mathematical reasoning, complex logical analysis, algorithm design, scientific research

Chain Chaining

Chain is the core abstraction of LangChain. It connects multiple components together to form reusable processing flows. From simple LLMChain to complex SequentialChain, build your AI workflow step by step.

3.1 LLMChain — The Simplest Chain

LLMChain combines PromptTemplate and LLM, and is the most basic chaining pattern.

from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser # Initialize model llm = ChatOpenAI( model="deepseek-chat", api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", temperature=0.7, ) # Define prompt template prompt = ChatPromptTemplate.from_messages([ ("system", "You are a {role}, skilled in {skill}. Answer concisely and professionally."), ("user", "{input}"), ]) # Build chain: Prompt -> LLM -> Output parser chain = prompt | llm | StrOutputParser() # Run chain result = chain.invoke({ "role": "Python backend engineer", "skill": Django REST Framework", "input": "How to design a high-performance REST API? Please list 5 key principles.", }) print(result)

3.2 SequentialChain — Execute Multiple Chains Sequentially

SequentialChain connects multiple steps, where the output of the previous step serves as the input to the next.

from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser llm = ChatOpenAI( model="deepseek-chat", api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", temperature=0.7, ) # Step 1: Generate outline outline_prompt = ChatPromptTemplate.from_template( "Please generate an article outline with 3 key points for the following topic:\n\nTopic: {topic}" ) # Step 2: Generate content based on outline write_prompt = ChatPromptTemplate.from_template( "Based on the following outline, write an article of about 500 words:\n\nOutline: {outline}\n\nPlease write in fluent Chinese." ) # Build sequential chain outline_chain = outline_prompt | llm | StrOutputParser() write_chain = write_prompt | llm | StrOutputParser() # Connect with RunnableLambda from langchain_core.runnables import RunnableLambda full_chain = ( RunnableLambda(lambda x: {"outline": outline_chain.invoke({"topic": x["topic"]})}) | RunnableLambda(lambda x: write_chain.invoke({"outline": x["outline"]})) ) result = full_chain.invoke({"topic": "人工智能在医疗领域的应用"}) print(result)

3.3 Using LCEL (LangChain Expression Language)

LCEL is the recommended way to build chains in LangChain, using the pipe operator | to combine components, making the code more concise and readable.

from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser llm = ChatOpenAI( model="deepseek-chat", api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", ) # LCEL style: translation chain translate_prompt = ChatPromptTemplate.from_template( "Translate the following text into {target_lang}, output only the translation:\n\n{text}" ) translate_chain = translate_prompt | llm | StrOutputParser() response = translate_chain.invoke({ "target_lang": "English", "text": "人工智能正在深刻改变我们的生活方式和工作方式。", }) print(response)

ConversationChain Dialogue Memory

Memory is the core of a dialogue system. LangChain provides various memory components that allow DeepSeek to remember context and enable natural multi-turn conversations.

4.1 ConversationBufferMemory — Complete Memory

Retains all conversation history. Suitable for short conversations; token consumption increases as the conversation grows long.

from langchain_openai import ChatOpenAI from langchain.memory import ConversationBufferMemory from langchain.chains import ConversationChain llm = ChatOpenAI( model="deepseek-chat", api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", temperature=0.7, ) # Create memory component memory = ConversationBufferMemory() # Create conversation chain conversation = ConversationChain( llm=llm, memory=memory, verbose=True, # Print debug info ) # Multi-turn conversation print(conversation.predict(input="Hello, my name is Xiao Ming.")) print(conversation.predict(input="I like hot pot. Can you recommend a few hot pot restaurants in Beijing?")) print(conversation.predict(input="Do you remember my name?"))

4.2 ConversationBufferWindowMemory — Sliding Window Memory

Retains only the most recent K turns to avoid excessive token consumption. Suitable for long conversations.

from langchain.memory import ConversationBufferWindowMemory from langchain.chains import ConversationChain memory = ConversationBufferWindowMemory(k=3) # Keep only the last 3 turns conversation = ConversationChain( llm=llm, memory=memory, verbose=True, ) print(conversation.predict(input="Turn 1: My name is Xiao Ming.")) print(conversation.predict(input="Turn 2: I am 25 years old.")) print(conversation.predict(input="Turn 3: I live in Beijing.")) print(conversation.predict(input="Turn 4: My favorite color is blue.")) print(conversation.predict(input="What is my name?")) # Outside window, may forget

4.3 ConversationSummaryMemory — Summary Memory

Uses LLM to automatically summarize historical conversations, retaining key information while controlling token consumption.

from langchain.memory import ConversationSummaryMemory from langchain.chains import ConversationChain # Summary memory: use LLM to automatically summarize historical conversations memory = ConversationSummaryMemory(llm=llm) conversation = ConversationChain( llm=llm, memory=memory, verbose=True, ) # Conduct multi-turn complex conversation print(conversation.predict( input="Please explain in detail what machine learning is, including supervised learning, unsupervised learning, and reinforcement learning." )) print(conversation.predict( input="Based on what you just said, which category does deep learning belong to? Why?" )) # View current summary print("\n=== Conversation Summary ===") print(memory.load_memory_variables({}))

4.4 Using RunnableWithMessageHistory (Recommended)

The new version of LangChain recommends using RunnableWithMessageHistory, which is more flexible and controllable.

from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.runnables.history import RunnableWithMessageHistory from langchain_community.chat_message_histories import ChatMessageHistory llm = ChatOpenAI( model="deepseek-chat", api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", ) # Create prompt with memory slot prompt = ChatPromptTemplate.from_messages([ ("system", "You are a friendly AI assistant."), MessagesPlaceholder(variable_name="history"), ("human", "{input}"), ]) chain = prompt | llm # Store history records store = {} def get_session_history(session_id: str): if session_id not in store: store[session_id] = ChatMessageHistory() return store[session_id] # Wrap into a chain with history with_history = RunnableWithMessageHistory( chain, get_session_history=get_session_history, input_messages_key="input", history_messages_key="history", ) # Multi-turn conversation response1 = with_history.invoke( {"input": "Hello, my name is Xiao Ming, I am a Python developer."}, config={"configurable": {"session_id": "user_001"}}, ) print(response1.content) response2 = with_history.invoke( {"input": "Do you remember my name and profession?"}, config={"configurable": {"session_id": "user_001"}}, ) print(response2.content)

Memory Component Selection Recommendations

  • Short conversations (<10 turns): ConversationBufferMemory, retain full context
  • Long conversations (>10 turns): ConversationBufferWindowMemory or ConversationSummaryMemory
  • Production environment: Recommend RunnableWithMessageHistory, combined with external storage like Redis

Agent Tool Calling

Agent is one of LangChain's most powerful features. It allows the LLM to make autonomous decisions, select and call external tools to accomplish complex tasks.

5.1 Custom Tool — Calculator

Use the @tool decorator to define custom tools, allowing the Agent to call them when needed.

from langchain_openai import ChatOpenAI from langchain_core.tools import tool from langgraph.prebuilt import create_react_agent # Initialize model llm = ChatOpenAI( model="deepseek-chat", api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", temperature=0.0, # Low temperature recommended for Agent scenarios ) # Define custom tool @tool def calculator(expression: str) -> str: """Calculate mathematical expressions. Input should be a valid Python math expression, e.g., '2 + 3 * 4'.""" try: result = eval(expression, {"__builtins__": {}}, {}) return f"Calculation result: {expression} = {result}" except Exception as e: return f"Calculation error: {str(e)}" @tool def get_word_count(text: str) -> str: """Count the number of characters in the text. Input is the text string to count.""" # Chinese character count chinese_chars = sum(1 for c in text if '\u4e00' <= c <= '\u9fff') return f"Character count: {chinese_chars} Chinese characters in total" # Create Agent tools = [calculator, get_word_count] agent = create_react_agent(llm, tools) # Test Agent response = agent.invoke({ "messages": [ ("user", "Please calculate the result of (15 + 27) * 3 - 8, then tell me how many characters are in the phrase '人工智能改变世界'.") ] }) for msg in response["messages"]: if msg.type == "ai": print(msg.content)

5.2 Web Search Tool

Integrate the Tavily Search API to enable the Agent to search the internet in real time for the latest information.

# Install dependencies # pip install langchain-community tavily-python from langchain_openai import ChatOpenAI from langchain_community.tools.tavily_search import TavilySearchResults from langgraph.prebuilt import create_react_agent llm = ChatOpenAI( model="deepseek-chat", api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", temperature=0.0, ) # Create search tool (requires Tavily API Key) search = TavilySearchResults( max_results=3, tavily_api_key="tvly-your-tavily-key", # Register at https://tavily.com to get one ) tools = [search] agent = create_react_agent(llm, tools) response = agent.invoke({ "messages": [ ("user", "Search for the latest developments on DeepSeek models in 2026, and summarize in Chinese.") ] }) for msg in response["messages"]: if msg.type == "ai": print(msg.content)

Agent Development Notes

  • Set temperature to 0: Agents require deterministic output to avoid random failures in tool calls.
  • Write clear tool descriptions: The docstring directly affects whether the Agent correctly invokes the tool.
  • Security first: eval() is for demonstration only; use a safe expression parser in production.
  • Use langgraph: LangGraph is the recommended Agent framework by LangChain, more stable than the legacy AgentExecutor.

RAG Retrieval-Augmented Generation

RAG (Retrieval-Augmented Generation) enables DeepSeek to answer questions based on your private documents. This is the core technology for building enterprise knowledge base Q&A systems.

6.1 Complete RAG Flow

From document loading to vector storage to retrieval-based Q&A, the complete RAG implementation process.

# Install dependencies # pip install langchain-community faiss-cpu pypdf from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain_community.document_loaders import TextLoader, PyPDFLoader from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_community.vectorstores import FAISS from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough # 1. Initialize model llm = ChatOpenAI( model="deepseek-chat", api_key="sk-your-api-key-here", base_url="https://api.deepseek.com/v1", temperature=0.3, # Lower temperature recommended for RAG scenarios ) # 2. Load documents # Load text file loader = TextLoader("data/knowledge.txt", encoding="utf-8") documents = loader.load() # If loading PDF # loader = PyPDFLoader("data/report.pdf") # documents = loader.load() # 3. Text splitting text_splitter = RecursiveCharacterTextSplitter( chunk_size=500, # 500 characters per chunk chunk_overlap=50, # 50-character overlap to maintain context separators=["\n\n", "\n", "。", "!", "?", " "], ) chunks = text_splitter.split_documents(documents) print(f"Document split into {len(chunks)} chunks") # 4. Create vector store # Note: DeepSeek does not yet provide an official Embedding API, # so we use OpenAI's Embedding or a local model here. embeddings = OpenAIEmbeddings( model="text-embedding-3-small", # If using a local model, you can choose HuggingFace or other solutions. ) vectorstore = FAISS.from_documents(chunks, embeddings) # 5. Create retriever retriever = vectorstore.as_retriever( search_type="similarity", # similarity search search_kwargs={"k": 4}, # return top 4 relevant document chunks ) # 6. Build RAG prompt rag_prompt = ChatPromptTemplate.from_messages([ ("system", """You are a document-based Q&A assistant. Please answer the user's question based on the following context. If the context does not contain relevant information, say "Based on the provided documents, this question cannot be answered." Do not make up any information. Context: {context}"""), ("human", "{question}"), ]) # 7. Build RAG chain def format_docs(docs): return "\n\n".join(doc.page_content for doc in docs) rag_chain = ( {"context": retriever | format_docs, "question": RunnablePassthrough()} | rag_prompt | llm | StrOutputParser() ) # 8. Ask a question question = "What are the key milestones in the project timeline in this document?" answer = rag_chain.invoke(question) print(answer)

6.2 Using a Local Embedding Model

If you don't want to rely on the OpenAI Embedding API, you can use a local model.

# Install dependencies # pip install sentence-transformers from langchain_community.embeddings import HuggingFaceEmbeddings # Use local BGE Chinese Embedding model embeddings = HuggingFaceEmbeddings( model_name="BAAI/bge-small-zh-v1.5", model_kwargs={"device": "cpu"}, encode_kwargs={"normalize_embeddings": True}, ) # Rest of the code is the same as above vectorstore = FAISS.from_documents(chunks, embeddings)

RAG Optimization Tips

  • chunk_size tuning: Too small loses context, too large reduces retrieval accuracy. For Chinese documents, 300-800 characters is recommended.
  • Hybrid retrieval: Combine keyword retrieval (BM25) and vector retrieval to improve recall.
  • Re-ranking: Use a Cross-Encoder to re-rank results after retrieval.
  • Citation tracing: Require the model to cite specific document fragments in the prompt to enhance credibility.

Integration with Ollama Local Model

If you run DeepSeek models locally with Ollama, LangChain provides seamless integration. Data is processed entirely locally, ensuring privacy and security.

7.1 Using ChatOllama to Connect to Local Model

# Install dependencies # pip install langchain-ollama from langchain_ollama import ChatOllama from langchain_core.messages import HumanMessage, SystemMessage # Connect to DeepSeek model in local Ollama llm = ChatOllama( model="deepseek-r1:8b", # Your Ollama model name base_url="http://localhost:11434", # Ollama default address temperature=0.7, ) messages = [ SystemMessage(content="You are a professional Python programming assistant."), HumanMessage(content="Please write a decorator in Python to calculate function execution time."), ] response = llm.invoke(messages) print(response.content)

7.2 Local Ollama + RAG

Combine local Ollama models with RAG workflows to build a fully localized knowledge base Q&A system.

from langchain_ollama import ChatOllama, OllamaEmbeddings from langchain_community.document_loaders import TextLoader from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_community.vectorstores import FAISS from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough # Use local Ollama model and embeddings llm = ChatOllama(model="deepseek-r1:8b", temperature=0.3) embeddings = OllamaEmbeddings(model="nomic-embed-text") # Need to run ollama pull nomic-embed-text first # Load documents loader = TextLoader("data/knowledge.txt", encoding="utf-8") documents = loader.load() # Split documents text_splitter = RecursiveCharacterTextSplitter( chunk_size=500, chunk_overlap=50, ) chunks = text_splitter.split_documents(documents) # Create vector store vectorstore = FAISS.from_documents(chunks, embeddings) retriever = vectorstore.as_retriever(search_kwargs={"k": 4}) # Build RAG chain rag_prompt = ChatPromptTemplate.from_messages([ ("system", "Answer the question based on the following context:\n\n{context}"), ("human", "{question}"), ]) def format_docs(docs): return "\n\n".join(doc.page_content for doc in docs) rag_chain = ( {"context": retriever | format_docs, "question": RunnablePassthrough()} | rag_prompt | llm | StrOutputParser() ) question = "What key technologies are mentioned in the document?" answer = rag_chain.invoke(question) print(answer)

Local Deployment Notes

  • Ollama service running: Ensure Ollama is running in the background, listening on localhost:11434 by default
  • Model downloaded: Use ollama list to confirm the model exists
  • Embedding model: Local RAG requires a separate embedding model, such as nomic-embed-text or bge-m3
  • Performance depends on hardware: 8B models run well on consumer GPUs, CPU inference is slower

Complete Project Example — Intelligent Customer Service Bot

Integrate all the knowledge learned earlier to build a complete intelligent customer service bot. It has conversational memory, knowledge base retrieval, tool invocation, and streaming output capabilities.

8.1 Project Structure

chatbot/ ├── main.py # Main entry point ├── chatbot.py # Core chat logic ├── knowledge.py # Knowledge base management ├── tools.py # Custom tools ├── config.py # Configuration file ├── data/ │ └── faq.txt # Knowledge base documents └── requirements.txt # Dependency list

8.2 config.py — Configuration File

import os # DeepSeek API configuration DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY", "sk-your-api-key") DEEPSEEK_BASE_URL = "https://api.deepseek.com/v1" DEEPSEEK_MODEL = "deepseek-chat" # Model parameters TEMPERATURE = 0.7 MAX_TOKENS = 2048 # Knowledge base configuration KNOWLEDGE_BASE_DIR = "data" CHUNK_SIZE = 500 CHUNK_OVERLAP = 50 RETRIEVAL_K = 4 # System prompt SYSTEM_PROMPT = """You are a professional intelligent customer service assistant, named "Xiao Shen Assistant". You need to: 1. Answer user questions in a friendly and professional manner 2. Prioritize using information from the knowledge base to answer product-related questions 3. If the knowledge base does not contain relevant information, use general knowledge to answer 4. For calculation problems, use the calculator tool 5. Always reply in Chinese"""

8.3 tools.py — Custom Tools

from langchain_core.tools import tool from datetime import datetime @tool def calculator(expression: str) -> str: """Calculate a mathematical expression. Input is a valid Python mathematical expression.""" try: safe_dict = { "abs": abs, "round": round, "min": min, "max": max, "sum": sum, "pow": pow, "int": int, "float": float, } result = eval(expression, {"__builtins__": safe_dict}, {}) return f"计算结果:{expression} = {result}" except Exception as e: return f"计算错误:{str(e)}" @tool def get_current_time() -> str: """获取当前日期和时间。""" now = datetime.now() return f"当前时间:{now.strftime('%Y年%m月%d日 %H:%M:%S')}(星期{['一','二','三','四','五','六','日'][now.weekday()]})"

8.4 knowledge.py — 知识库管理

import os from langchain_community.document_loaders import TextLoader, DirectoryLoader from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_community.vectorstores import FAISS from langchain_openai import OpenAIEmbeddings from config import ( KNOWLEDGE_BASE_DIR, CHUNK_SIZE, CHUNK_OVERLAP, RETRIEVAL_K, DEEPSEEK_API_KEY, ) class KnowledgeBase: """知识库管理器""" def __init__(self): self.embeddings = OpenAIEmbeddings( model="text-embedding-3-small", api_key=DEEPSEEK_API_KEY, ) self.vectorstore = None self.text_splitter = RecursiveCharacterTextSplitter( chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, separators=["\n\n", "\n", "。", "!", "?"], ) def load_documents(self) -> bool: """加载知识库文档""" if not os.path.exists(KNOWLEDGE_BASE_DIR): print(f"知识库目录不存在:{KNOWLEDGE_BASE_DIR}") return False loader = DirectoryLoader( KNOWLEDGE_BASE_DIR, glob="*.txt", loader_cls=TextLoader, loader_kwargs={"encoding": "utf-8"}, ) documents = loader.load() if not documents: print("知识库中没有找到文档") return False chunks = self.text_splitter.split_documents(documents) self.vectorstore = FAISS.from_documents(chunks, self.embeddings) print(f"知识库加载完成:{len(documents)} 个文档,{len(chunks)} 个片段") return True def search(self, query: str) -> str: """搜索相关知识""" if not self.vectorstore: return "" docs = self.vectorstore.similarity_search(query, k=RETRIEVAL_K) return "\n\n".join(doc.page_content for doc in docs)

8.5 chatbot.py — 核心聊天逻辑

from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.runnables.history import RunnableWithMessageHistory from langchain_community.chat_message_histories import ChatMessageHistory from config import ( DEEPSEEK_API_KEY, DEEPSEEK_BASE_URL, DEEPSEEK_MODEL, TEMPERATURE, MAX_TOKENS, SYSTEM_PROMPT, ) from knowledge import KnowledgeBase class DeepSeekChatbot: """DeepSeek 智能客服机器人""" def __init__(self): # 初始化 LLM self.llm = ChatOpenAI( model=DEEPSEEK_MODEL, api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL, temperature=TEMPERATURE, max_tokens=MAX_TOKENS, streaming=True, ) # Initialize knowledge base self.kb = KnowledgeBase() kb_loaded = self.kb.load_documents() # Build prompt if kb_loaded: system_template = SYSTEM_PROMPT + "\n\nKnowledge base reference information:\n{knowledge}" else: system_template = SYSTEM_PROMPT self.prompt = ChatPromptTemplate.from_messages([ ("system", system_template), MessagesPlaceholder(variable_name="history"), ("human", "{input}"), ]) # Create chain chain = self.prompt | self.llm # Conversation history storage self.store = {} self.chain_with_history = RunnableWithMessageHistory( chain, get_session_history=self._get_session_history, input_messages_key="input", history_messages_key="history", ) def _get_session_history(self, session_id: str): if session_id not in self.store: self.store[session_id] = ChatMessageHistory() return self.store[session_id] def chat(self, user_input: str, session_id: str = "default"): """Send a message and get a reply""" # Search knowledge base knowledge = self.kb.search(user_input) if self.kb.vectorstore else "Knowledge base not loaded" # Invoke chain response = self.chain_with_history.invoke( { "input": user_input, "knowledge": knowledge, }, config={"configurable": {"session_id": session_id}}, ) return response.content def chat_stream(self, user_input: str, session_id: str = "default"): """Streaming chat""" knowledge = self.kb.search(user_input) if self.kb.vectorstore else "Knowledge base not loaded" for chunk in self.chain_with_history.stream( { "input": user_input, "knowledge": knowledge, }, config={"configurable": {"session_id": session_id}}, ): if chunk.content: yield chunk.content

8.6 main.py — Main Entry

from chatbot import DeepSeekChatbot def main(): """Intelligent customer service robot main program""" print("=" * 50) print(" XiaoShen Assistant - DeepSeek Intelligent Customer Service Robot") print(" Enter 'quit' to exit, 'clear' to clear conversation history") print("=" * 50) # Initialize robot print("\nInitializing...") bot = DeepSeekChatbot() print("Initialization complete!\n") session_id = "user_default" while True: try: user_input = input("\nYou: ").strip() if not user_input: continue if user_input.lower() == 'quit': print("\nThank you for using, goodbye!") break if user_input.lower() == 'clear': bot.store.pop(session_id, None) print("Conversation history cleared.") continue # Stream output reply print("\nXiaoShen Assistant: ", end="", flush=True) for chunk in bot.chat_stream(user_input, session_id): print(chunk, end="", flush=True) print() except KeyboardInterrupt: print("\n\nThank you for using, goodbye!") break except Exception as e: print(f"\nError occurred: {e}") if __name__ == "__main__": main()

8.7 Running the Project

# Install dependencies pip install langchain langchain-openai langchain-community langchain-text-splitters faiss-cpu # Set API Key # Windows: $env:DEEPSEEK_API_KEY = "sk-your-api-key" # macOS/Linux: export DEEPSEEK_API_KEY="sk-your-api-key" # Create knowledge base documents mkdir data echo "Product A costs 999 yuan, supports 7-day no-reason return. Product B costs 1999 yuan, provides 2-year warranty." > data/faq.txt # Run python main.py

More DeepSeek Tutorials

Continue exploring DeepSeek usage, deployment, and model knowledge.

DeepSeek + LangChain Development FAQ

Is DeepSeek API compatible with LangChain? +
Fully compatible. DeepSeek API follows the OpenAI interface format, and LangChain's ChatOpenAI class can be used directly. Simply set base_url to https://api.deepseek.com/v1 and model to deepseek-chat or deepseek-reasoner. All LangChain features (Chain, Agent, Memory, RAG) work normally.
What prerequisites are needed for DeepSeek + LangChain development? +
You need Python basics (functions, classes, module imports) and basic API call concepts. If you are familiar with pip installing dependencies and environment variable configuration, you can follow this tutorial without obstacles. No machine learning or deep learning background is required; LangChain encapsulates the underlying complexity.
Is DeepSeek R1 and V3 used the same way in LangChain? +
The usage is exactly the same; you only need to change the model parameter. V3 (deepseek-chat) is suitable for general conversation and content generation, while R1 (deepseek-reasoner) is suitable for mathematical reasoning and complex logical analysis. For Agent and tool calling scenarios, V3 is recommended because R1's reasoning process may affect the determinism of tool calls.
How can DeepSeek's Embedding API be used for LangChain RAG? +
DeepSeek currently does not provide an official Embedding API. In LangChain RAG, you can use OpenAI's Embedding API (text-embedding-3-small) or use local embedding models (such as BGE series, nomic-embed-text via Ollama). The local solution is completely free and data stays within your domain.
What is the difference between LangChain and LangGraph? Which should I use? +
LangChain is an LLM application development framework providing high-level abstractions like Chain, Agent, and Memory. LangGraph is a low-level framework introduced by the LangChain team, focusing on building stateful, multi-step Agent workflows. For simple scenarios, LangChain's Chain is sufficient; for complex Agents and multi-step processes, LangGraph's create_react_agent is recommended. This tutorial covers both approaches.

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

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

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