Getting Started with LangChain: Unified Interfaces and Agent Development Explained

A LangChain beginner's guide covering unified interfaces, DeepSeek pitfalls, and Agent development essentials.
This guide introduces the LangChain framework, detailing the recommended init_chat_model unified interface over vendor-specific model classes, the key pitfall of disabling DeepSeek's thinking mode for Agent stability, environment setup with .env files, and how AI Agents excel at semantic understanding tasks traditional rule-based code cannot handle.
What is LangChain: A Unified Foundation for AI Application Development
LangChain is an open-source framework for developing large model applications. It was founded in October 2022 by Harrison Chase, at a pivotal turning point in large language model technology—OpenAI released ChatGPT in November of the same year, sparking a global wave of AI application development. Before this, developers who wanted to integrate models like GPT-3 into their applications had to manually handle numerous tedious engineering details such as API authentication, prompt concatenation, context window management, and multi-turn conversation state maintenance. The emergence of LangChain was essentially a systematic summary and abstraction of the engineering practices of that era—it standardized the "glue code" scattered across various developer projects into a reusable component system. As large models like GPT-4 exploded in growth, LangChain quickly became one of the most active open-source projects in the field of AI application development, with its GitHub Star count surpassing tens of thousands within just a few months.
Its core value lies in providing a unified interface for the complex and diverse model ecosystem—whether you use DeepSeek, OpenAI, Anthropic, Qwen, Zhipu, or Tencent Hunyuan, you can call them using the same code paradigm. At the underlying level, you only need to swap out the model, rather than writing separate adaptation code for each vendor. This design philosophy draws on the "Adapter Pattern" from software engineering—decoupling upper-layer business code from concrete implementations by using a unified abstraction layer to hide underlying differences.
The Adapter Pattern and LangChain's Abstraction System
The Adapter Pattern is a classic structural pattern among the GoF (Gang of Four) design patterns. Its core idea is to introduce an "adapter" intermediate layer that converts incompatible interfaces into the unified interface expected by the caller—much like a universal charging plug that standardizes different countries' power standards into an input acceptable to a device. LangChain extends this further, not only unifying the underlying API call formats, but also standardizing the complete pipeline of prompt templates (PromptTemplate), output parsing (OutputParser), conversation memory (Memory), and tool calling (Tool), building a full-stack abstraction system oriented toward LLM application development. This means that every skill a developer masters within the LangChain framework can be reused across models, greatly reducing the cost of vendor migration.
It's worth mentioning that LCEL (LangChain Expression Language), which LangChain heavily promoted after version 0.1, further deepened this abstraction philosophy. LCEL draws on the concept of pipelines from functional programming, using the | operator to chain components like PromptTemplate, LLM, and OutputParser into a declarative processing chain—for example, chain = prompt | llm | parser. This design not only makes code more readable but also makes the entire chain naturally support streaming output (Streaming), batch processing (Batch), and asynchronous calls (Async).
The Engineering Value of Functional Programming and the Pipeline Paradigm
The concept of pipelines in Functional Programming (FP) originates from the philosophy of the Unix shell's
|operator: each program does only one thing, and programs are connected via standard input and output. In modern programming languages, Elixir's|>operator, Haskell's function composition operator., and JavaScript's proposed Pipeline Operator all embody this idea. LCEL introduces this paradigm into LLM application development, bringing multiple engineering benefits: First, the responsibility boundaries of each component (PromptTemplate, LLM, OutputParser) are clear and individually testable; second, the composability of pipelines allows complex processing chains to be built incrementally from simple components rather than written into a single large function; most importantly, LCEL uniformly implements capabilities likestream(),batch(), andainvoke()at the pipeline level, so developers don't need to rewrite logic for each call mode—this "define once, call in many ways" feature is exactly LCEL's core competitive advantage over hand-written chain code. The object returned byinit_chat_modelrecommended later fully conforms to LCEL's Runnable interface specification, which is precisely the deeper reason it outperforms each vendor's proprietary model classes.
This has significant implications for actual development. In the past, when integrating different models, developers often had to study each vendor's authentication methods, request structures, and response formats; but under LangChain's abstraction, these differences are hidden, and developers can focus solely on the business logic itself. For teams that need to balance cost and performance across multiple models, this switchability is especially critical.

Environment Setup: The .env File and Dependency Installation
Before writing code, you need to prepare a .env file in the project root directory to store the API Key and Base URL provided by each model vendor. Platforms like DeepSeek, OpenAI, Anthropic, Hunyuan, Alibaba Qwen, and Zhipu all require their own keys and connection addresses, which can usually be obtained from the "API Keys" page in the respective platform's console.
The API Key is the credential for accessing large model services, essentially equivalent to an account password. Once leaked, it can lead to fraudulent charges or data breaches. The combination of the .env file and python-dotenv is a direct embodiment of the "separation of config from code" principle in The Twelve-Factor App methodology—this cloud-native application best practice, summarized by Heroku engineers in 2011, explicitly requires storing environment-related configurations such as API keys and database connection strings in environment variables, rather than hardcoding them in the code.
The Twelve-Factor App Methodology and the Evolution of Secret Management
The Twelve-Factor App is a cloud-native application-building methodology summarized by Heroku co-founder Adam Wiggins in 2011. Its third factor, "Config," clearly states that an application's config (everything that varies between deployment environments) should be completely separated from the code and stored in environment variables. This principle gave rise to the standard development practice of
.env+.gitignore. However, as the cloud-native ecosystem matured, secret management has developed a more comprehensive hierarchical system: development environments use.envfiles for convenience, CI/CD environments use platform-built-in Secret variables (such as GitHub Actions Secrets, GitLab CI Variables) for security isolation, and production environments are recommended to use professional secret management services such as HashiCorp Vault (supporting dynamic secret generation and automatic rotation), AWS Secrets Manager (deeply integrated with IAM roles), or Azure Key Vault. These tools not only encrypt and store secrets but also provide audit logs, access control, and automatic rotation capabilities, greatly shortening response time when a secret is leaked. They are essential infrastructure for modern AI applications moving toward production.
In team collaboration scenarios, it's common to also maintain a .env.example file (containing the key names of all required variables but without actual values) as a configuration reference template for new members, while adding .env to .gitignore to prevent sensitive information from entering the version control system.
Dependency installation is very simple. Taking DeepSeek as an example:
pip install langchain langchain-openai langchain-deepseek
After installation, load the environment variables via python-dotenv:
from dotenv import load_dotenv
import os
load_dotenv(override=True) # 优先从本项目 .env 加载
deepseek_api_key = os.getenv("DEEPSEEK_API_KEY")
deepseek_base_url = os.getenv("DEEPSEEK_BASE_URL")
override=True means prioritizing the current project's .env config to avoid conflicts with system-level environment variables. This is especially important in multi-project development scenarios—it ensures that the current project's configuration takes precedence over system-level or shell-level environment variables of the same name, preventing cross-project contamination.
Two Ways to Create Models: Model Classes vs. Unified Interface
LangChain provides two ways to create large model objects, and understanding the trade-offs between them is key to getting started.
Method 1: Model Classes (Not Recommended)
Each vendor has a corresponding model class, such as DeepSeek's ChatDeepSeek, OpenAI's ChatOpenAI, and Anthropic's ChatAnthropic:
from langchain_deepseek import ChatDeepSeek
llm = ChatDeepSeek(
api_key=deepseek_api_key,
api_base=deepseek_base_url,
model="deepseek-chat" # 更推荐最新的 deepseek-v3-pro
)
resp = llm.invoke("你好,请给我推荐几本书")
print(resp)
Why not recommended? There are two reasons: First, the naming of each model class is inconsistent and hard to remember; second, and more critically—objects created with model classes may return nested structures that deviate from the standard format (missing or extra fields) when building Agents or DeepAgents, causing frequent parsing errors. From the LCEL architecture perspective, the completeness of each vendor's model class implementation of the Runnable interface varies, potentially causing unexpected behavior during streaming output or batch calls, whereas init_chat_model provides unified guarantees for these capabilities.

Method 2: The Unified Interface init_chat_model (Recommended)
init_chat_model is LangChain's unified creation method compatible with various vendors, and it is currently the best practice. Behind it lies the fact that OpenAI's Chat Completions API has effectively become the industry standard for large model interfaces.
The Historical Background of the OpenAI Chat Completions API Becoming the Industry Standard
The Chat Completions API launched by OpenAI in 2023 designed a concise yet complete message protocol: using
role(system/user/assistant/tool) to distinguish conversation participants,contentto carry text and multimodal content, andtool_callsto structurally describe tool call intentions. The brilliance of this protocol lies in unifying conversation context, instruction injection, and function calling into the same data model, greatly reducing the parsing complexity at the application layer. Precisely because of this forward-looking design, numerous domestic and international model vendors (including DeepSeek, Zhipu GLM, Alibaba Qwen, 01.AI, Mistral, Together AI, etc.) have chosen to proactively be compatible with the OpenAI protocol rather than designing their own private API formats. This "protocol standardization" created a virtuous cycle: developers only need to learn one API, ecosystem tools (like LangChain, LlamaIndex) only need to maintain one core parsing logic, and the R&D efficiency of the entire industry has significantly improved. It's worth noting that this phenomenon is not uncommon in tech history—SQL for relational databases and HTTP for web services both went through similar evolutionary paths from "single-vendor design" to "industry de facto standard." The triumph of the OpenAI protocol is essentially the result of the resonance of three factors: first-mover advantage, design rationality, and ecosystem network effects.
Numerous domestic and international model vendors (including DeepSeek, Zhipu GLM, Alibaba Qwen, 01.AI, etc.) have chosen to be compatible with the OpenAI protocol, which means you only need to modify base_url and api_key to call different vendors' models with exactly the same code.
from langchain.chat_models import init_chat_model
llm = init_chat_model(
model="deepseek-v3-pro",
model_provider="deepseek", # 也可写 openai、anthropic、google、ollama 等
api_key=deepseek_api_key,
base_url=deepseek_base_url
)
model_provider supports many platforms such as OpenAI, Anthropic, AWS, Google, Ollama, Groq, and HuggingFace. If you can't find a certain domestic vendor (such as Zhipu), as long as it's compatible with the OpenAI protocol, simply filling in openai will also work fine. If no provider is specified, the framework will also attempt to infer it automatically. This "OpenAI protocol compatibility" strategy reduces the migration cost for developers and accelerates the ecosystem integration of the entire industry.
A Key Pitfall: It's Recommended to Disable DeepSeek's Thinking Mode
This is a very valuable piece of practical experience. DeepSeek-v3-pro has thinking mode enabled by default, which causes two obvious problems in LangChain:
- Noticeably slower response speed: Thinking mode makes each response sluggish, which is completely unnecessary for simple tasks.
- Potential compatibility issues: During Agent or tool loop execution, LangChain's compatibility with thinking mode is still imperfect, and it's prone to throwing various errors due to "missing thinking parameters."
The Technical Principles of Chain-of-Thought Reasoning
Chain-of-Thought Reasoning (CoT) was formally proposed and systematically validated by the Google Brain team in the 2022 paper "Chain-of-Thought Prompting Elicits Reasoning in Large Language Models." Its core finding is that when a model outputs intermediate reasoning steps before generating the final answer, accuracy on complex mathematical operations, multi-step logical reasoning, and other tasks can be greatly improved—because the text output at each step itself becomes the context for subsequent reasoning, guiding the model to "think step by step" rather than jumping directly to conclusions. The DeepSeek-R1 series further internalized CoT as a training objective: through large-scale reinforcement learning (the GRPO algorithm), the model spontaneously learns to produce structured reasoning chains within
<think>tags, and then refines the final answer from them.However, this additional token output stream (
thinking_tokens) interrupts the standard JSON tool call parsing flow in LangChain's Agent framework. The Agent framework operates on the ReAct (Reasoning + Acting) paradigm—this paradigm was jointly proposed by Princeton University and Google Brain in 2022, with the core idea of having the model alternately execute two phases: "Reasoning" and "Acting." The reasoning phase produces an analysis of the current situation, while the acting phase outputs JSON strictly conforming to thetool_callsformat to drive tool calls. When DeepSeek's CoT content is inserted into this loop, the reasoning text within<think>tags gets mixed withtool_callsJSON in the same response, making it impossible for the parser to correctly extract tool call instructions, which then triggers exceptions and interrupts the entire Agent loop. Therefore, for tasks that don't rely on deep reasoning (such as information extraction, document classification, and Q&A routing), explicitly disabling thinking mode is the optimal practice that balances stability and response speed.
Therefore, it's recommended to explicitly disable thinking mode when creating the model:
llm = init_chat_model(
model="deepseek-v3-pro",
model_provider="deepseek",
api_key=deepseek_api_key,
base_url=deepseek_base_url,
extra_body={"thinking": {"type": "disabled"}}
)

The impact of thinking mode is small in single-turn conversations, but once you enter an Agent multi-turn loop, disabling it makes the entire process more stable and efficient.
How AI Applications Integrate with Existing Business
Many developers have a doubt: does learning large models mean abandoning your existing skill stack? The answer is exactly the opposite. AI capabilities should be viewed as an extension of existing technology, not an independent and isolated new direction.
Whether you work in Java backend, frontend, testing, or data analysis, AI applications don't exist in isolation—they always serve specific business needs: the frontend can embed intelligent customer service conversations, the backend can host AI feature development, and testing and data analysis can likewise be combined with AI to improve efficiency.

A real case: the intelligent document formatting feature in a certain mobile app. On the surface, it's Python handling formatting, but behind the scenes it heavily relies on AI Agents. For example, identifying author information in documents, distinguishing titles from subtitles, and differentiating between highly similar content like "figure captions/figure notes/table titles/table notes/figure legends"—these tasks are nearly impossible to complete accurately using traditional rule-based code and must be understood and processed by an AI Agent in combination with context, ultimately outputting messy and disorganized academic documents into a standardized format.
This reveals the core advantage of AI Agents over traditional code: traditional rule-based code relies on explicit if-else logic and regular expressions, which naturally fail when faced with the semantic ambiguity of natural language. This phenomenon is known in engineering circles as "Rule Explosion"—when the semantic variation of the input space is rich enough, the number of rules needed to cover all edge cases grows exponentially, ultimately making the system difficult to maintain and yielding extremely low recall. Taking "figure caption" recognition as an example, it may appear below a figure, to its right, or embedded within a body paragraph, and may be presented in various forms such as "Note:", "Source:", or "Figure X:". It's nearly impossible to enumerate all variants using regular expressions alone.
The "Rule Explosion" Problem and the Structured Output Capabilities of AI Agents
The solution offered by AI Agents is to use the semantic representations learned during the large model's pretraining phase to map natural language fragments of diverse surface forms into a unified semantic category space, then combine structured output techniques (such as JSON Schema constraints and Pydantic model validation) to convert the semantic understanding results into a standard format that downstream systems can directly consume. "Figure captions" and "figure titles" are extremely similar literally, but their semantics and formatting rules are completely different—only an AI that understands context can reliably distinguish them. This combination of "semantic understanding + structured output" is precisely the core competitive advantage of AI Agents over traditional rule-based systems in scenarios like document processing, information extraction, and content classification.
It's worth understanding in depth that Pydantic plays a crucial role in this combination. Pydantic is the most mainstream data validation library in the Python ecosystem. It defines the Schema of data structures through Python Type Hints and performs strict type validation and automatic conversion at runtime. In LangChain, the
with_structured_output()method accepts a Pydantic model class as input, and the framework automatically converts it into a JSON Schema and injects it into the model's prompt or Function Calling parameters, guiding the model to output content strictly according to the predefined structure, ultimately returning a validated Pydantic object. This mechanism seamlessly bridges "natural language understanding" and "strong-typed data constraints," effectively constraining the uncertainty of AI output before it enters downstream business logic. It's a key engineering practice for building production-grade AI applications.
This example illustrates that the true value of AI application development often lies hidden in those business scenarios that "seem simple but are actually full of semantic understanding challenges."
Summary
Starting from LangChain's positioning, this tutorial has systematically covered environment configuration, the trade-offs between the two model creation methods, and the practical pitfall of DeepSeek's thinking mode. For beginners, prioritizing the init_chat_model unified interface and disabling DeepSeek's thinking mode are two golden practices that can be implemented immediately.
Building on this foundation, the progressive learning path is roughly as follows: after mastering LCEL's pipeline composition capabilities, you can build AI Agents with tool-calling capabilities (based on the reasoning-action loop of the ReAct paradigm); combining vector databases with document retrieval allows you to build a RAG knowledge base (Retrieval-Augmented Generation, enabling the model to access private knowledge).
The Working Principles and Engineering Value of RAG Technology
RAG (Retrieval-Augmented Generation) was formally proposed by Meta AI Research in the 2020 paper "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks." Its core insight is to decouple "knowledge storage" from "language generation"—knowledge doesn't have to be entirely encoded into model weights, but is instead stored in external vector databases (such as Chroma, Faiss, Pinecone, Weaviate) and dynamically retrieved during inference to splice relevant fragments into the context. The specific process is: first, chunk the documents and convert them into high-dimensional vectors via an embedding model to store in the vector database; when a user asks a question, the question is likewise converted into a vector and an approximate nearest neighbor search (ANN Search) is performed to retrieve the most semantically relevant document fragments; finally, the retrieval results are injected into the LLM's prompt along with the original question, and the model generates an answer based on this "on-the-spot evidence." RAG's engineering value manifests in three dimensions: knowledge can be updated in real time (no need to retrain the model), answers can be traced and verified (reference documents can be annotated), and hallucination rates can be significantly reduced (the probability of the model fabricating content drops greatly when there's evidence to check). These three points precisely address the core pain points enterprises face when deploying large models in internal knowledge base scenarios, making RAG one of the most mainstream enterprise-grade AI application architectures today.
RAG is currently the mainstream technical path for deploying large models in enterprise internal data scenarios. Its core idea is to strip "memory" from model weights into an independently updatable vector database, so that knowledge updates don't require retraining the model. Combining the two enables you to build AI applications that truly serve the business.
Key Takeaways
- Use
init_chat_modelrather than vendor-proprietary model classes to ensure full compatibility with LCEL pipelines - Disable DeepSeek's thinking mode (
extra_body={"thinking": {"type": "disabled"}}) to avoid Agent tool call parsing failures .envfile +.gitignoreis the foundational practice for secret management; production environments should upgrade to professional secret management services- OpenAI protocol compatibility is an important reference indicator when choosing a domestic model vendor; protocol compatibility means zero migration cost
- AI capabilities are an extension of your existing skill stack, not a replacement—the value of AI Agents lies in tackling semantic understanding challenges that traditional rule-based code cannot handle
Related articles

The Open-Weight Model Alliance: The Dual Game of AI Safety and American Competitiveness
Analysis of how the open-weight model alliance serves both digital safety and U.S. competitiveness, exploring transparency, ecosystem building, and geopolitical AI competition.

Local Merge Queues: Solving Code Conflicts for Parallel AI Programming Agents
Deep dive into how local merge queues solve code conflict challenges when multiple AI programming agents work in parallel, covering merge queue principles and multi-agent development trends.

Local Merge Queues: Solving Code Conflicts from Parallel AI Coding Agents
Deep dive into how local merge queues solve code conflict challenges when multiple AI coding agents work in parallel, covering merge queue principles and multi-agent development trends.