Tutorials Logic, IN info@tutorialslogic.com

LangChain Setup: Environment, Keys, Project Structure and Configuration

Recommended Project Layout

A strong LangChain project starts with predictable setup. Keep secrets out of source control, isolate dependencies, place prompts and chains in testable modules, and build configuration that can switch models or vector stores without rewriting business logic.

This lesson uses Python because most LangChain examples and integrations are strongest there. The same architectural ideas apply if your application is a web API, worker, CLI, or notebook prototype.

Separate the parts that change often from the parts that should stay stable. Prompts change often. Model provider choices may change. Your input and output schemas should be stable because the rest of the app depends on them.

  • <code>app/config.py</code> loads environment settings.
  • <code>app/chains/</code> stores deterministic runnable pipelines.
  • <code>app/retrieval/</code> stores loaders, chunkers, embeddings, and retrievers.
  • <code>app/tools/</code> stores tool functions used by agents.
  • <code>tests/evals/</code> stores representative questions and expected behavior.

Dependency Choices

LangChain is split into core packages and integration packages. Install only what you use. A typical OpenAI-based project may need <code>langchain</code>, <code>langchain-core</code>, <code>langchain-openai</code>, <code>python-dotenv</code>, and a vector store package.

  • Pin dependencies for production projects.
  • Keep provider-specific code behind factory functions.
  • Load secrets from environment variables, not from prompt files or source code.

Package Boundaries and Reproducible Installs

Modern LangChain separates the core orchestration package from provider integrations. Install only the provider packages the project uses, inside an isolated environment. A successful installation is not enough: record the resolved versions so another machine and CI can reproduce the same imports and behavior.

Start from a supported Python version, upgrade the installer inside the environment, install LangChain plus one provider integration, and run an import smoke test. Pin or lock dependencies for an application; use deliberate upgrade pull requests instead of allowing production builds to resolve new transitive versions unexpectedly.

  • Use python -m pip so pip belongs to the active interpreter.
  • Keep provider integrations explicit, such as langchain-openai or the provider required by the project.
  • Do not install every integration into one environment; it increases conflicts and review work.
  • Capture versions with the project lock tool or a reviewed requirements file.

Create and verify a minimal environment

Create and verify a minimal environment
python -m venv .venv
# Windows PowerShell: .\.venv\Scripts\Activate.ps1
# macOS/Linux: source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install langchain langchain-openai
python -c "import langchain; import langchain_openai; print('imports ok')"

The final command verifies the interpreter can import both orchestration and provider packages before application code is added.

Secrets, Provider Configuration, and a Smoke Test

Provider credentials belong in environment variables or a managed secret store, never in source code, screenshots, notebooks committed to Git, or tutorial output. Use a restricted development key, keep .env out of version control, and configure separate credentials for local, test, and production environments.

The first runtime check should make one small model call with a timeout and controlled output. This separates installation and credential failures from later prompt, retrieval, tool, or graph logic. Record the model identifier in configuration because model aliases and capabilities can change independently of LangChain.

  • Fail at startup with a clear message when a required environment variable is missing.
  • Use the provider integration documented for the selected model rather than relying on an old import path.
  • Set request limits and timeouts before running batch, agent, or evaluation workloads.
  • Never print the complete environment or exception objects that may include request headers.

Install and Configure

This setup keeps secrets in <code>.env</code> and centralizes the model constructor. Later lessons can reuse the same model factory.

Install and Configure
# pip install langchain langchain-core langchain-openai python-dotenv pydantic

# .env
# OPENAI_API_KEY=your_key_here
# LLM_MODEL=gpt-4o-mini

# app/config.py
from functools import lru_cache
from pydantic import Field
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    openai_api_key: str = Field(alias="OPENAI_API_KEY")
    llm_model: str = Field(default="gpt-4o-mini", alias="LLM_MODEL")

    class Config:
        env_file = ".env"

@lru_cache
def get_settings() -> Settings:
    return Settings()

# app/models.py
from langchain_openai import ChatOpenAI
from app.config import get_settings

def build_chat_model(temperature: float = 0.2) -> ChatOpenAI:
    settings = get_settings()
    return ChatOpenAI(
        model=settings.llm_model,
        temperature=temperature,
        api_key=settings.openai_api_key,
        timeout=30,
        max_retries=2,
    )
  • A factory function makes tests and provider swaps easier.
  • Timeouts and retries should be explicit for production services.
Before you move on

LangChain Setup: Environment, Keys, Project Structure and Configuration Mastery Check

3 checks
  • This setup keeps secrets in <code>.env</code> and centralizes the model constructor.
  • Later lessons can reuse the same model factory.
  • Separate the parts that change often from the parts that should stay stable.

LangChain Setup Questions Learners Ask

No. Start with prompt and model chains. Add vector storage only when you need retrieval over private or large content.

Both are valid. Small prompts can live near the chain. Larger prompts that change often are easier to review in separate template files.

Run one direct model invocation and confirm the API key, model name, timeout, and tracing configuration.

Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.