[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M792DF6KNY16DZPC5XD82KR6":3,"skill-same:01M792DF6KNY16DZPC5XD82KR6":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":42,"repositoryHtmlUrl":43,"repositoryHomepageUrl":6,"ownerHtmlUrl":44,"ownerBlogUrl":45,"ownerDescription":46,"updatedAt":47,"install":48,"resources":61},"01M792DF6KNY16DZPC5XD82KR6","langchain-multi-env-setup",null,"Build reliable dev \u002F staging \u002F prod isolation for LangChain 1.0 services —\nPydantic `Settings` + `SecretStr`, cloud Secret Manager in prod, per-env\nprompt and model version pinning, env-specific checkpointer and observability.\nUse when graduating from `.env`-in-dev to real prod infra, or debugging a\nconfig that loaded the wrong values in the wrong env.\nTrigger with \"langchain multi-env\", \"langchain pydantic settings\",\n\"langchain secret manager\", \"langchain env config\", \"langchain prod setup\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-multi-env-setup\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-multi-env-setup\ndescription: |\n  Build reliable dev \u002F staging \u002F prod isolation for LangChain 1.0 services —\n  Pydantic `Settings` + `SecretStr`, cloud Secret Manager in prod, per-env\n  prompt and model version pinning, env-specific checkpointer and observability.\n  Use when graduating from `.env`-in-dev to real prod infra, or debugging a\n  config that loaded the wrong values in the wrong env.\n  Trigger with \"langchain multi-env\", \"langchain pydantic settings\",\n  \"langchain secret manager\", \"langchain env config\", \"langchain prod setup\".\nallowed-tools: Read, Write, Edit, Bash(python:*), Bash(gcloud:*)\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, langchain, langgraph, python, langchain-1.0, config, pydantic, multi-env, secrets]\ncompatible-with: claude-code, codex\n---\n\n# LangChain Multi-Env Setup (Python)\n\n## Overview\n\nA team ships a LangChain 1.0 service to staging with `python-dotenv` loading\n`.env.staging` into `os.environ`. Security audits —\n`docker exec STAGING-POD env` prints `ANTHROPIC_API_KEY=sk-ant-api03-...` in\nplain text. Anyone with `kubectl exec`, any sidecar, any core dump, any\nerror tracker that auto-captures process env sees the key. This is pain\n**P37**: secrets loaded from `.env` in production containers leak via `env`.\n\nA second failure chains. A developer runs the staging deploy from a shell\nwhere `LANGCHAIN_ENV=production` was set hours earlier. The loader picks\nthe prod `.env`, staging answers with a prompt commit tuned only for the\nprod model tier, latency doubles. Two root causes: no type-safe env gate,\nno startup validation that would have caught the mismatched model id.\n\nBoth are one refactor:\n\n```python\n# BAD — dotenv populates os.environ; any process with container access sees it\nfrom dotenv import load_dotenv\nload_dotenv(\".env.production\")\napi_key = os.environ[\"ANTHROPIC_API_KEY\"]  # P37: leaks via `docker exec env`\n\n# GOOD — SecretStr in a validated Settings object, pulled from Secret Manager\nfrom pydantic import SecretStr\nfrom pydantic_settings import BaseSettings\n\nclass Settings(BaseSettings):\n    env: Literal[\"dev\", \"staging\", \"prod\"]\n    anthropic_api_key: SecretStr\n\nsettings = build_settings()  # pulls from GCP Secret Manager in prod\napi_key = settings.anthropic_api_key.get_secret_value()\n# repr(settings) prints `SecretStr('**********')` — safe to log\n```\n\nThis skill owns the per-env **config plumbing** — `Settings` skeleton,\nSecret Manager integration, per-env pinning, startup smoke test. It does\n**not** own the full secrets lifecycle (rotation, revocation, scope) —\nthat belongs to `langchain-security-basics`.\n\nPin: `langchain-core 1.0.x`, `langchain-anthropic 1.0.x`, `pydantic >= 2.5`,\n`pydantic-settings >= 2.1`. Pain anchors: **P37** (primary), **P20**\n(checkpointer schema — cross-ref `langchain-langgraph-checkpointing`).\n\nTwo numbers: **smoke test \u003C 10 seconds**; **env-var count ~15-30** (more\nthan 30 means `Settings` is absorbing feature flags and should split).\n\n## Prerequisites\n\n- Python 3.10+ (3.11+ recommended for `Literal` and `StrEnum` ergonomics)\n- `langchain-core >= 1.0, \u003C 2.0`\n- `pydantic >= 2.5`, `pydantic-settings >= 2.1`\n- One secret backend: GCP Secret Manager (`google-cloud-secret-manager`),\n  AWS Secrets Manager (`boto3`), or HashiCorp Vault (`hvac`)\n- Completed `langchain-sdk-patterns` — the `Settings` object is injected into\n  the chain factories from that skill\n\n## Instructions\n\nRun these six steps in order — each adds one invariant the next step depends on:\n\n1. Define a `Settings` class with `SecretStr` keys, `Literal` env, and fail-fast validation.\n2. Add a per-env loader — file in dev, env vars in staging, Secret Manager in prod.\n3. Use the cloud Secret Manager client to pull keys into memory only.\n4. Pin `model_id`, `prompt_commit_hash`, and `vector_index_name` per env.\n5. Configure the checkpointer per env — memory in dev, Postgres elsewhere.\n6. Run a startup smoke test under 10 seconds before the HTTP server binds.\n\n### Step 1 — Create a Settings class with SecretStr and fail-fast validation\n\n```python\nfrom typing import Literal\nfrom pydantic import SecretStr, HttpUrl, Field, ValidationError\nfrom pydantic_settings import BaseSettings, SettingsConfigDict\n\nclass Settings(BaseSettings):\n    model_config = SettingsConfigDict(\n        env_file=None,              # see Step 2 — loader picks the file\n        env_file_encoding=\"utf-8\",\n        case_sensitive=False,\n        extra=\"forbid\",             # reject unknown env vars — typo detection\n    )\n\n    # --- env switch (drives everything else) ---\n    env: Literal[\"dev\", \"staging\", \"prod\"] = Field(..., alias=\"LANGCHAIN_ENV\")\n\n    # --- secrets (always SecretStr — never str) ---\n    anthropic_api_key: SecretStr = Field(..., alias=\"ANTHROPIC_API_KEY\")\n    openai_api_key: SecretStr = Field(..., alias=\"OPENAI_API_KEY\")\n    langsmith_api_key: SecretStr = Field(..., alias=\"LANGSMITH_API_KEY\")\n\n    # --- per-env pinning (see Step 4) ---\n    model_id: str = Field(..., alias=\"LANGCHAIN_MODEL_ID\")\n    prompt_commit_hash: str = Field(..., alias=\"LANGCHAIN_PROMPT_COMMIT\")\n    vector_index_name: str = Field(..., alias=\"LANGCHAIN_VECTOR_INDEX\")\n\n    # --- endpoints (validated URLs — typo caught at startup) ---\n    checkpointer_url: HttpUrl | None = Field(None, alias=\"LANGCHAIN_CHECKPOINTER_URL\")\n    otel_endpoint: HttpUrl = Field(..., alias=\"OTEL_EXPORTER_OTLP_ENDPOINT\")\n\n    # --- budget guards (per-env) ---\n    max_cost_usd_per_day: float = Field(10.0, alias=\"LANGCHAIN_DAILY_BUDGET_USD\")\n    max_rpm: int = Field(60, alias=\"LANGCHAIN_MAX_RPM\")\n```\n\n`SecretStr` masks `repr(settings)` to `SecretStr('**********')` — a routine\n`logger.info(settings)` cannot leak the key. The only way to read plaintext\nis `.get_secret_value()`, which greps like a sore thumb in review.\n`extra=\"forbid\"` catches typos (`LANGCHIN_MODEL_ID`) at import time.\n`HttpUrl` rejects `http:\u002Fotel:4318` before the exporter wastes 60s on DNS.\n\nSee [Settings Skeleton](references\u002Fsettings-skeleton.md) for the full class.\n\n### Step 2 — Per-env config loading (file OR Secret Manager, never both)\n\n```python\nimport os\nfrom pathlib import Path\n\ndef build_settings() -> Settings:\n    env = os.environ.get(\"LANGCHAIN_ENV\", \"dev\")\n\n    if env == \"dev\":\n        # Local dev: .env.dev file, values checked into 1Password not git\n        return Settings(_env_file=Path(\".env.dev\"))\n\n    if env == \"staging\":\n        # CI \u002F staging: env vars injected by the orchestrator\n        # (GitHub Actions secrets, k8s envFrom: secretRef, etc.)\n        return Settings()  # reads os.environ directly\n\n    if env == \"prod\":\n        # Prod: pull from Secret Manager into memory ONLY\n        values = pull_from_secret_manager()\n        return Settings(**values)\n\n    raise ValueError(f\"unknown LANGCHAIN_ENV: {env!r}\")\n```\n\nThree loaders, one class. Dev touches a file on disk. Staging inherits env\nvars from the orchestrator — `envFrom: secretRef` is readable via\n`docker exec env`, but the blast radius is bounded and rotation is weekly.\n\nProd is the P37 fix: `pull_from_secret_manager()` builds a dict and passes\nkwargs to `Settings(...)`. Values land in the instance attribute and\n**never touch `os.environ`**. A subprocess will not inherit them.\n\n### Step 3 — Secret Manager pull (GCP example; AWS \u002F Vault in reference)\n\n```python\nfrom google.cloud import secretmanager\n\ndef pull_from_secret_manager() -> dict[str, str]:\n    client = secretmanager.SecretManagerServiceClient()\n    project = os.environ[\"GCP_PROJECT_ID\"]\n    secret_names = [\"ANTHROPIC_API_KEY\", \"OPENAI_API_KEY\", \"LANGSMITH_API_KEY\"]\n    out: dict[str, str] = {}\n    for name in secret_names:\n        resource = f\"projects\u002F{project}\u002Fsecrets\u002F{name}\u002Fversions\u002Flatest\"\n        response = client.access_secret_version(request={\"name\": resource})\n        out[name] = response.payload.data.decode(\"utf-8\")\n    # Non-secret passthrough (model id, prompt hash, endpoints)\n    for key in [\"LANGCHAIN_ENV\", \"LANGCHAIN_MODEL_ID\", \"LANGCHAIN_PROMPT_COMMIT\",\n                \"LANGCHAIN_VECTOR_INDEX\", \"LANGCHAIN_CHECKPOINTER_URL\",\n                \"OTEL_EXPORTER_OTLP_ENDPOINT\"]:\n        if key in os.environ:\n            out[key] = os.environ[key]\n    return out\n```\n\nNo `os.environ[k] = v` line. The dict goes straight into\n`Settings(**values)`. Workload-identity IAM handles auth; no static key on\ndisk. For AWS \u002F Vault see [Secret Manager Integration](references\u002Fsecret-manager-integration.md).\n\n### Step 4 — Per-env model and prompt pinning\n\nDev, staging, and prod run **different** model ids and **different** prompt\ncommit hashes. Pinning happens at env-var level so app code is env-agnostic\n(see the Env Matrix below for values). One function reads\n`settings.prompt_commit_hash` and pulls from LangSmith\n(cross-ref `langchain-prompt-engineering`):\n\n```python\nfrom langsmith import Client\nls = Client(api_key=settings.langsmith_api_key.get_secret_value())\n\ndef get_prompt(settings: Settings) -> ChatPromptTemplate:\n    return ls.pull_prompt(f\"triage-prompt:{settings.prompt_commit_hash}\")\n```\n\n**Prevents:** staging loading a prod prompt commit. Pinning per env makes\npromotion explicit — dev → staging → prod moves one hash at a time. See\n[Per-Env Pinning](references\u002Fper-env-pinning.md).\n\n### Step 5 — Per-env checkpointer selection\n\nCheckpointer choice is per-env too:\n\n```python\nfrom langgraph.checkpoint.memory import MemorySaver\nfrom langgraph.checkpoint.postgres import PostgresSaver\n\ndef build_checkpointer(settings: Settings):\n    if settings.env == \"dev\":\n        return MemorySaver()          # ephemeral, resets on restart\n    # staging + prod: Postgres with env-isolated schema\n    # cross-ref langchain-langgraph-checkpointing (P20) for schema migration\n    return PostgresSaver.from_conn_string(\n        str(settings.checkpointer_url)\n    )\n```\n\nDev uses `MemorySaver` — no infra dependency, no state between runs.\nStaging and prod use `PostgresSaver` against **separate** databases (or\nseparate schemas). Never share a checkpointer DB between envs; P20 explains\n— schema migrations on a version bump corrupt cross-env threads.\n\n### Step 6 — Startup smoke test (\u003C 10 seconds budget)\n\n```python\nimport time\nfrom anthropic import Anthropic\n\ndef validate_integrations(settings: Settings) -> None:\n    t0 = time.monotonic()\n\n    # 1. Model reachable (1-token ping ~ $0.00001)\n    anthropic = Anthropic(api_key=settings.anthropic_api_key.get_secret_value())\n    anthropic.messages.create(\n        model=settings.model_id,\n        max_tokens=1,\n        messages=[{\"role\": \"user\", \"content\": \"hi\"}],\n    )\n\n    # 2. Checkpointer reachable\n    if settings.env != \"dev\":\n        checkpointer = build_checkpointer(settings)\n        checkpointer.setup()  # runs SELECT 1 + schema check\n\n    # 3. Vector store reachable (see langchain-embeddings-search)\n    # ... describe_index call here ...\n\n    # 4. Observability endpoint reachable (OTLP HTTP health)\n    # ... requests.get(f\"{settings.otel_endpoint}\u002Fhealth\", timeout=2) ...\n\n    elapsed = time.monotonic() - t0\n    if elapsed > 10.0:\n        raise RuntimeError(\n            f\"startup smoke test took {elapsed:.1f}s (budget 10s)\"\n        )\n```\n\nCall `validate_integrations(settings)` **before** the HTTP server binds.\nFailure aborts the deploy — the readiness probe never goes green, the\nrollout halts, the bad version takes no traffic. Budget: **10 seconds**.\nPast 10s an integration is degraded — fail loudly rather than ship a 30s\ncold start. See [Startup Smoke Test](references\u002Fstartup-smoke-test.md).\n\n## Output\n\n- `Settings` class on `pydantic-settings` with `SecretStr` for keys, `Literal` env, `HttpUrl` endpoints, `extra=\"forbid\"`\n- Env-specific loader (file → dev; env vars → staging; Secret Manager → prod); values land in `Settings` only, never `os.environ`\n- Cloud Secret Manager integration (GCP \u002F AWS \u002F Vault) with IAM-bound auth; no static keys on disk\n- Per-env pinning for `model_id`, `prompt_commit_hash`, `vector_index_name`, `checkpointer_url`\n- Per-env checkpointer (`MemorySaver` dev, `PostgresSaver` on isolated DBs staging\u002Fprod)\n- Startup smoke test — model \u002F vector \u002F checkpointer \u002F observability under 10-second budget\n\n## Env Matrix\n\n| Dimension | dev | staging | prod |\n|---|---|---|---|\n| Secret backend | `.env.dev` file (git-ignored) | orchestrator env vars | cloud Secret Manager, memory only |\n| `os.environ` holds keys | yes (local) | yes (sidecar visible) | **no** (P37 fix) |\n| `model_id` | `claude-haiku-4-6` | `claude-sonnet-4-6` | `claude-sonnet-4-6` |\n| `prompt_commit_hash` | WIP | canary | stable (1 week old) |\n| `temperature` | 0.7 | 0.2 | 0.2 |\n| Checkpointer | `MemorySaver` | `PostgresSaver` (staging DB) | `PostgresSaver` (prod DB) |\n| Vector index | `dev-index` | `staging-index` | `prod-index` |\n| OTEL sample rate | 1.0 | 1.0 | 0.1 |\n| RPM limit | 10 | 60 | provider tier |\n| Daily budget | $1 | $10 | $500-$5000 |\n| Smoke probes | model | model + checkpointer + OTEL | all four |\n\n## Error Handling\n\n| Error | Cause | Fix |\n|---|---|---|\n| `docker exec POD env` shows `ANTHROPIC_API_KEY=...` in prod (P37) | `dotenv` \u002F plain env injection in prod | Pull from Secret Manager into `Settings(**values)`; never write to `os.environ` |\n| Staging answers with prod prompts \u002F wrong model | Loader defaulted or picked stale `LANGCHAIN_ENV` | `Literal[\"dev\",\"staging\",\"prod\"]` on env; raise on unknown; no default |\n| `ValidationError: extra fields forbidden` at startup | Typo (`LANGCHIN_MODEL_ID`) | Fix the typo — `extra=\"forbid\"` working as intended |\n| Startup takes 30s before first request | Serialized probes or degraded integration | Enforce 10s budget; parallelize probes; fail the deploy |\n| `repr(settings)` in a log leaks the API key | Plain `str` used, not `SecretStr` | Change field to `SecretStr`; repr masks to `'**********'` |\n| Prod silently using `MemorySaver` | `build_checkpointer` defaulted when `checkpointer_url` was None | Require `checkpointer_url` in staging\u002Fprod via a model validator |\n| Secret Manager auth fails in CI | SA not bound; `google.auth` fell back to ADC | Bind SA with `roles\u002Fsecretmanager.secretAccessor` |\n| Prompt hash rolled forward in staging without dev validation | Promotion skipped the dev gate | Enforce dev → staging → prod order in CI (see per-env pinning ref) |\n\n## Examples\n\n### Graduating a `.env`-in-dev service to prod\n\nStart: a single `.env` committed (or leaked via `docker exec env`). End:\n`Settings` class, three loaders, Secret Manager in prod, smoke test under\n10s. Three PRs — (1) introduce `Settings` without changing loader behavior,\n(2) add `SecretStr` and migrate call sites to `.get_secret_value()`,\n(3) swap prod to Secret Manager and remove the prod `.env` from the image.\nSee [Settings Skeleton](references\u002Fsettings-skeleton.md) and\n[Secret Manager Integration](references\u002Fsecret-manager-integration.md).\n\n### Wrong-env prompt loaded in staging — postmortem\n\nStaging inherited `LANGCHAIN_ENV=production` from a stale shell. The\n`Literal[\"dev\",\"staging\",\"prod\"]` field rejects `production`; CI promotion\nsets `LANGCHAIN_ENV` explicitly; `direnv` pins it per-project. See\n[Per-Env Pinning](references\u002Fper-env-pinning.md).\n\n### Smoke test blocked a bad model id\n\nA prod deploy went out with `LANGCHAIN_MODEL_ID=claude-sonnet-4-7` (not yet\nrolled out). The 1-token ping failed with `model not found`,\n`validate_integrations` raised, the container crash-looped, the rollout\nhalted, the previous version kept taking traffic. Zero user impact; failure\nbudget stayed under 3s. See [Startup Smoke Test](references\u002Fstartup-smoke-test.md).\n\n## Resources\n\n- [Pydantic Settings docs](https:\u002F\u002Fdocs.pydantic.dev\u002Flatest\u002Fconcepts\u002Fpydantic_settings\u002F)\n- [Pydantic `SecretStr`](https:\u002F\u002Fdocs.pydantic.dev\u002Flatest\u002Fapi\u002Ftypes\u002F#pydantic.types.SecretStr)\n- [GCP Secret Manager client](https:\u002F\u002Fcloud.google.com\u002Fsecret-manager\u002Fdocs\u002Freference\u002Flibraries)\n- [AWS Secrets Manager `boto3`](https:\u002F\u002Fboto3.amazonaws.com\u002Fv1\u002Fdocumentation\u002Fapi\u002Flatest\u002Freference\u002Fservices\u002Fsecretsmanager.html)\n- [HashiCorp Vault `hvac`](https:\u002F\u002Fhvac.readthedocs.io\u002F)\n- [LangChain 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Related skills in pack: `langchain-security-basics` (secrets lifecycle, owns rotation and revocation — not duplicated here); `langchain-langgraph-checkpointing` (P20 schema migration); `langchain-prompt-engineering` (prompt pin \u002F LangSmith pull workflow); `langchain-reference-architecture` (where `Settings` fits in the DI layer)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P37 primary, P20 cross-ref)\n","# LangChain Multi-Env Setup (Python)\n\n## Overview\n\nA team ships a LangChain 1.0 service to staging with `python-dotenv` loading\n`.env.staging` into `os.environ`. Security audits —\n`docker exec STAGING-POD env` prints `ANTHROPIC_API_KEY=sk-ant-api03-...` in\nplain text. Anyone with `kubectl exec`, any sidecar, any core dump, any\nerror tracker that auto-captures process env sees the key. This is pain\n**P37**: secrets loaded from `.env` in production containers leak via `env`.\n\nA second failure chains. A developer runs the staging deploy from a shell\nwhere `LANGCHAIN_ENV=production` was set hours earlier. The loader picks\nthe prod `.env`, staging answers with a prompt commit tuned only for the\nprod model tier, latency doubles. Two root causes: no type-safe env gate,\nno startup validation that would have caught the mismatched model id.\n\nBoth are one refactor:\n\n```python\n# BAD — dotenv populates os.environ; any process with container access sees it\nfrom dotenv import load_dotenv\nload_dotenv(\".env.production\")\napi_key = os.environ[\"ANTHROPIC_API_KEY\"]  # P37: leaks via `docker exec env`\n\n# GOOD — SecretStr in a validated Settings object, pulled from Secret Manager\nfrom pydantic import SecretStr\nfrom pydantic_settings import BaseSettings\n\nclass Settings(BaseSettings):\n    env: Literal[\"dev\", \"staging\", \"prod\"]\n    anthropic_api_key: SecretStr\n\nsettings = build_settings()  # pulls from GCP Secret Manager in prod\napi_key = settings.anthropic_api_key.get_secret_value()\n# repr(settings) prints `SecretStr('**********')` — safe to log\n```\n\nThis skill owns the per-env **config plumbing** — `Settings` skeleton,\nSecret Manager integration, per-env pinning, startup smoke test. It does\n**not** own the full secrets lifecycle (rotation, revocation, scope) —\nthat belongs to `langchain-security-basics`.\n\nPin: `langchain-core 1.0.x`, `langchain-anthropic 1.0.x`, `pydantic >= 2.5`,\n`pydantic-settings >= 2.1`. Pain anchors: **P37** (primary), **P20**\n(checkpointer schema — cross-ref `langchain-langgraph-checkpointing`).\n\nTwo numbers: **smoke test \u003C 10 seconds**; **env-var count ~15-30** (more\nthan 30 means `Settings` is absorbing feature flags and should split).\n\n## Prerequisites\n\n- Python 3.10+ (3.11+ recommended for `Literal` and `StrEnum` ergonomics)\n- `langchain-core >= 1.0, \u003C 2.0`\n- `pydantic >= 2.5`, `pydantic-settings >= 2.1`\n- One secret backend: GCP Secret Manager (`google-cloud-secret-manager`),\n  AWS Secrets Manager (`boto3`), or HashiCorp Vault (`hvac`)\n- Completed `langchain-sdk-patterns` — the `Settings` object is injected into\n  the chain factories from that skill\n\n## Instructions\n\nRun these six steps in order — each adds one invariant the next step depends on:\n\n1. Define a `Settings` class with `SecretStr` keys, `Literal` env, and fail-fast validation.\n2. Add a per-env loader — file in dev, env vars in staging, Secret Manager in prod.\n3. Use the cloud Secret Manager client to pull keys into memory only.\n4. Pin `model_id`, `prompt_commit_hash`, and `vector_index_name` per env.\n5. Configure the checkpointer per env — memory in dev, Postgres elsewhere.\n6. Run a startup smoke test under 10 seconds before the HTTP server binds.\n\n### Step 1 — Create a Settings class with SecretStr and fail-fast validation\n\n```python\nfrom typing import Literal\nfrom pydantic import SecretStr, HttpUrl, Field, ValidationError\nfrom pydantic_settings import BaseSettings, SettingsConfigDict\n\nclass Settings(BaseSettings):\n    model_config = SettingsConfigDict(\n        env_file=None,              # see Step 2 — loader picks the file\n        env_file_encoding=\"utf-8\",\n        case_sensitive=False,\n        extra=\"forbid\",             # reject unknown env vars — typo detection\n    )\n\n    # --- env switch (drives everything else) ---\n    env: Literal[\"dev\", \"staging\", \"prod\"] = Field(..., alias=\"LANGCHAIN_ENV\")\n\n    # --- secrets (always SecretStr — never str) ---\n    anthropic_api_key: SecretStr = Field(..., alias=\"ANTHROPIC_API_KEY\")\n    openai_api_key: SecretStr = Field(..., alias=\"OPENAI_API_KEY\")\n    langsmith_api_key: SecretStr = Field(..., alias=\"LANGSMITH_API_KEY\")\n\n    # --- per-env pinning (see Step 4) ---\n    model_id: str = Field(..., alias=\"LANGCHAIN_MODEL_ID\")\n    prompt_commit_hash: str = Field(..., alias=\"LANGCHAIN_PROMPT_COMMIT\")\n    vector_index_name: str = Field(..., alias=\"LANGCHAIN_VECTOR_INDEX\")\n\n    # --- endpoints (validated URLs — typo caught at startup) ---\n    checkpointer_url: HttpUrl | None = Field(None, alias=\"LANGCHAIN_CHECKPOINTER_URL\")\n    otel_endpoint: HttpUrl = Field(..., alias=\"OTEL_EXPORTER_OTLP_ENDPOINT\")\n\n    # --- budget guards (per-env) ---\n    max_cost_usd_per_day: float = Field(10.0, alias=\"LANGCHAIN_DAILY_BUDGET_USD\")\n    max_rpm: int = Field(60, alias=\"LANGCHAIN_MAX_RPM\")\n```\n\n`SecretStr` masks `repr(settings)` to `SecretStr('**********')` — a routine\n`logger.info(settings)` cannot leak the key. The only way to read plaintext\nis `.get_secret_value()`, which greps like a sore thumb in review.\n`extra=\"forbid\"` catches typos (`LANGCHIN_MODEL_ID`) at import time.\n`HttpUrl` rejects `http:\u002Fotel:4318` before the exporter wastes 60s on DNS.\n\nSee [Settings Skeleton](references\u002Fsettings-skeleton.md) for the full class.\n\n### Step 2 — Per-env config loading (file OR Secret Manager, never both)\n\n```python\nimport os\nfrom pathlib import Path\n\ndef build_settings() -> Settings:\n    env = os.environ.get(\"LANGCHAIN_ENV\", \"dev\")\n\n    if env == \"dev\":\n        # Local dev: .env.dev file, values checked into 1Password not git\n        return Settings(_env_file=Path(\".env.dev\"))\n\n    if env == \"staging\":\n        # CI \u002F staging: env vars injected by the orchestrator\n        # (GitHub Actions secrets, k8s envFrom: secretRef, etc.)\n        return Settings()  # reads os.environ directly\n\n    if env == \"prod\":\n        # Prod: pull from Secret Manager into memory ONLY\n        values = pull_from_secret_manager()\n        return Settings(**values)\n\n    raise ValueError(f\"unknown LANGCHAIN_ENV: {env!r}\")\n```\n\nThree loaders, one class. Dev touches a file on disk. Staging inherits env\nvars from the orchestrator — `envFrom: secretRef` is readable via\n`docker exec env`, but the blast radius is bounded and rotation is weekly.\n\nProd is the P37 fix: `pull_from_secret_manager()` builds a dict and passes\nkwargs to `Settings(...)`. Values land in the instance attribute and\n**never touch `os.environ`**. A subprocess will not inherit them.\n\n### Step 3 — Secret Manager pull (GCP example; AWS \u002F Vault in reference)\n\n```python\nfrom google.cloud import secretmanager\n\ndef pull_from_secret_manager() -> dict[str, str]:\n    client = secretmanager.SecretManagerServiceClient()\n    project = os.environ[\"GCP_PROJECT_ID\"]\n    secret_names = [\"ANTHROPIC_API_KEY\", \"OPENAI_API_KEY\", \"LANGSMITH_API_KEY\"]\n    out: dict[str, str] = {}\n    for name in secret_names:\n        resource = f\"projects\u002F{project}\u002Fsecrets\u002F{name}\u002Fversions\u002Flatest\"\n        response = client.access_secret_version(request={\"name\": resource})\n        out[name] = response.payload.data.decode(\"utf-8\")\n    # Non-secret passthrough (model id, prompt hash, endpoints)\n    for key in [\"LANGCHAIN_ENV\", \"LANGCHAIN_MODEL_ID\", \"LANGCHAIN_PROMPT_COMMIT\",\n                \"LANGCHAIN_VECTOR_INDEX\", \"LANGCHAIN_CHECKPOINTER_URL\",\n                \"OTEL_EXPORTER_OTLP_ENDPOINT\"]:\n        if key in os.environ:\n            out[key] = os.environ[key]\n    return out\n```\n\nNo `os.environ[k] = v` line. The dict goes straight into\n`Settings(**values)`. Workload-identity IAM handles auth; no static key on\ndisk. For AWS \u002F Vault see [Secret Manager Integration](references\u002Fsecret-manager-integration.md).\n\n### Step 4 — Per-env model and prompt pinning\n\nDev, staging, and prod run **different** model ids and **different** prompt\ncommit hashes. Pinning happens at env-var level so app code is env-agnostic\n(see the Env Matrix below for values). One function reads\n`settings.prompt_commit_hash` and pulls from LangSmith\n(cross-ref `langchain-prompt-engineering`):\n\n```python\nfrom langsmith import Client\nls = Client(api_key=settings.langsmith_api_key.get_secret_value())\n\ndef get_prompt(settings: Settings) -> ChatPromptTemplate:\n    return ls.pull_prompt(f\"triage-prompt:{settings.prompt_commit_hash}\")\n```\n\n**Prevents:** staging loading a prod prompt commit. Pinning per env makes\npromotion explicit — dev → staging → prod moves one hash at a time. See\n[Per-Env Pinning](references\u002Fper-env-pinning.md).\n\n### Step 5 — Per-env checkpointer selection\n\nCheckpointer choice is per-env too:\n\n```python\nfrom langgraph.checkpoint.memory import MemorySaver\nfrom langgraph.checkpoint.postgres import PostgresSaver\n\ndef build_checkpointer(settings: Settings):\n    if settings.env == \"dev\":\n        return MemorySaver()          # ephemeral, resets on restart\n    # staging + prod: Postgres with env-isolated schema\n    # cross-ref langchain-langgraph-checkpointing (P20) for schema migration\n    return PostgresSaver.from_conn_string(\n        str(settings.checkpointer_url)\n    )\n```\n\nDev uses `MemorySaver` — no infra dependency, no state between runs.\nStaging and prod use `PostgresSaver` against **separate** databases (or\nseparate schemas). Never share a checkpointer DB between envs; P20 explains\n— schema migrations on a version bump corrupt cross-env threads.\n\n### Step 6 — Startup smoke test (\u003C 10 seconds budget)\n\n```python\nimport time\nfrom anthropic import Anthropic\n\ndef validate_integrations(settings: Settings) -> None:\n    t0 = time.monotonic()\n\n    # 1. Model reachable (1-token ping ~ $0.00001)\n    anthropic = Anthropic(api_key=settings.anthropic_api_key.get_secret_value())\n    anthropic.messages.create(\n        model=settings.model_id,\n        max_tokens=1,\n        messages=[{\"role\": \"user\", \"content\": \"hi\"}],\n    )\n\n    # 2. Checkpointer reachable\n    if settings.env != \"dev\":\n        checkpointer = build_checkpointer(settings)\n        checkpointer.setup()  # runs SELECT 1 + schema check\n\n    # 3. Vector store reachable (see langchain-embeddings-search)\n    # ... describe_index call here ...\n\n    # 4. Observability endpoint reachable (OTLP HTTP health)\n    # ... requests.get(f\"{settings.otel_endpoint}\u002Fhealth\", timeout=2) ...\n\n    elapsed = time.monotonic() - t0\n    if elapsed > 10.0:\n        raise RuntimeError(\n            f\"startup smoke test took {elapsed:.1f}s (budget 10s)\"\n        )\n```\n\nCall `validate_integrations(settings)` **before** the HTTP server binds.\nFailure aborts the deploy — the readiness probe never goes green, the\nrollout halts, the bad version takes no traffic. Budget: **10 seconds**.\nPast 10s an integration is degraded — fail loudly rather than ship a 30s\ncold start. See [Startup Smoke Test](references\u002Fstartup-smoke-test.md).\n\n## Output\n\n- `Settings` class on `pydantic-settings` with `SecretStr` for keys, `Literal` env, `HttpUrl` endpoints, `extra=\"forbid\"`\n- Env-specific loader (file → dev; env vars → staging; Secret Manager → prod); values land in `Settings` only, never `os.environ`\n- Cloud Secret Manager integration (GCP \u002F AWS \u002F Vault) with IAM-bound auth; no static keys on disk\n- Per-env pinning for `model_id`, `prompt_commit_hash`, `vector_index_name`, `checkpointer_url`\n- Per-env checkpointer (`MemorySaver` dev, `PostgresSaver` on isolated DBs staging\u002Fprod)\n- Startup smoke test — model \u002F vector \u002F checkpointer \u002F observability under 10-second budget\n\n## Env Matrix\n\n| Dimension | dev | staging | prod |\n|---|---|---|---|\n| Secret backend | `.env.dev` file (git-ignored) | orchestrator env vars | cloud Secret Manager, memory only |\n| `os.environ` holds keys | yes (local) | yes (sidecar visible) | **no** (P37 fix) |\n| `model_id` | `claude-haiku-4-6` | `claude-sonnet-4-6` | `claude-sonnet-4-6` |\n| `prompt_commit_hash` | WIP | canary | stable (1 week old) |\n| `temperature` | 0.7 | 0.2 | 0.2 |\n| Checkpointer | `MemorySaver` | `PostgresSaver` (staging DB) | `PostgresSaver` (prod DB) |\n| Vector index | `dev-index` | `staging-index` | `prod-index` |\n| OTEL sample rate | 1.0 | 1.0 | 0.1 |\n| RPM limit | 10 | 60 | provider tier |\n| Daily budget | $1 | $10 | $500-$5000 |\n| Smoke probes | model | model + checkpointer + OTEL | all four |\n\n## Error Handling\n\n| Error | Cause | Fix |\n|---|---|---|\n| `docker exec POD env` shows `ANTHROPIC_API_KEY=...` in prod (P37) | `dotenv` \u002F plain env injection in prod | Pull from Secret Manager into `Settings(**values)`; never write to `os.environ` |\n| Staging answers with prod prompts \u002F wrong model | Loader defaulted or picked stale `LANGCHAIN_ENV` | `Literal[\"dev\",\"staging\",\"prod\"]` on env; raise on unknown; no default |\n| `ValidationError: extra fields forbidden` at startup | Typo (`LANGCHIN_MODEL_ID`) | Fix the typo — `extra=\"forbid\"` working as intended |\n| Startup takes 30s before first request | Serialized probes or degraded integration | Enforce 10s budget; parallelize probes; fail the deploy |\n| `repr(settings)` in a log leaks the API key | Plain `str` used, not `SecretStr` | Change field to `SecretStr`; repr masks to `'**********'` |\n| Prod silently using `MemorySaver` | `build_checkpointer` defaulted when `checkpointer_url` was None | Require `checkpointer_url` in staging\u002Fprod via a model validator |\n| Secret Manager auth fails in CI | SA not bound; `google.auth` fell back to ADC | Bind SA with `roles\u002Fsecretmanager.secretAccessor` |\n| Prompt hash rolled forward in staging without dev validation | Promotion skipped the dev gate | Enforce dev → staging → prod order in CI (see per-env pinning ref) |\n\n## Examples\n\n### Graduating a `.env`-in-dev service to prod\n\nStart: a single `.env` committed (or leaked via `docker exec env`). End:\n`Settings` class, three loaders, Secret Manager in prod, smoke test under\n10s. Three PRs — (1) introduce `Settings` without changing loader behavior,\n(2) add `SecretStr` and migrate call sites to `.get_secret_value()`,\n(3) swap prod to Secret Manager and remove the prod `.env` from the image.\nSee [Settings Skeleton](references\u002Fsettings-skeleton.md) and\n[Secret Manager Integration](references\u002Fsecret-manager-integration.md).\n\n### Wrong-env prompt loaded in staging — postmortem\n\nStaging inherited `LANGCHAIN_ENV=production` from a stale shell. The\n`Literal[\"dev\",\"staging\",\"prod\"]` field rejects `production`; CI promotion\nsets `LANGCHAIN_ENV` explicitly; `direnv` pins it per-project. See\n[Per-Env Pinning](references\u002Fper-env-pinning.md).\n\n### Smoke test blocked a bad model id\n\nA prod deploy went out with `LANGCHAIN_MODEL_ID=claude-sonnet-4-7` (not yet\nrolled out). The 1-token ping failed with `model not found`,\n`validate_integrations` raised, the container crash-looped, the rollout\nhalted, the previous version kept taking traffic. Zero user impact; failure\nbudget stayed under 3s. See [Startup Smoke Test](references\u002Fstartup-smoke-test.md).\n\n## Resources\n\n- [Pydantic Settings docs](https:\u002F\u002Fdocs.pydantic.dev\u002Flatest\u002Fconcepts\u002Fpydantic_settings\u002F)\n- [Pydantic `SecretStr`](https:\u002F\u002Fdocs.pydantic.dev\u002Flatest\u002Fapi\u002Ftypes\u002F#pydantic.types.SecretStr)\n- [GCP Secret Manager client](https:\u002F\u002Fcloud.google.com\u002Fsecret-manager\u002Fdocs\u002Freference\u002Flibraries)\n- [AWS Secrets Manager `boto3`](https:\u002F\u002Fboto3.amazonaws.com\u002Fv1\u002Fdocumentation\u002Fapi\u002Flatest\u002Freference\u002Fservices\u002Fsecretsmanager.html)\n- [HashiCorp Vault `hvac`](https:\u002F\u002Fhvac.readthedocs.io\u002F)\n- [LangChain 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Related skills in pack: `langchain-security-basics` (secrets lifecycle, owns rotation and revocation — not duplicated here); `langchain-langgraph-checkpointing` (P20 schema migration); `langchain-prompt-engineering` (prompt pin \u002F LangSmith pull workflow); `langchain-reference-architecture` (where `Settings` fits in the DI layer)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P37 primary, P20 cross-ref)\n",{"name":5,"tags":24,"author":34,"license":15,"version":35,"description":36,"allowed-tools":37,"compatible-with":38},[25,26,27,28,29,30,31,32,33],"saas","langchain","langgraph","python","langchain-1.0","config","pydantic","multi-env","secrets","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Build reliable dev \u002F staging \u002F prod isolation for LangChain 1.0 services —\nPydantic `Settings` + `SecretStr`, cloud Secret Manager in prod, per-env\nprompt and model version pinning, env-specific checkpointer and observability.\nUse when graduating from `.env`-in-dev to real prod infra, or debugging a\nconfig that loaded the wrong values in the wrong env.\nTrigger with \"langchain multi-env\", \"langchain pydantic settings\",\n\"langchain secret manager\", \"langchain env config\", \"langchain prod setup\".\n","Read, Write, Edit, Bash(python:*), Bash(gcloud:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-multi-env-setup",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill langchain-multi-env-setup",{"tool":54,"command":55},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-multi-env-setup",{"tool":57,"command":58},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-multi-env-setup","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-multi-env-setup\u002FSKILL.md",true,[],[63,70,77,84,91,99],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":95,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]