AI AgentsLangChain

How do you configure model providers and credentials?

Question 286 of 324 · Updated

On this page

Direct answer#

Configure a LangChain model provider by installing the compatible provider integration, selecting an approved model or deployment identifier, and supplying the authentication and connection settings required by that provider. Keep credentials in the application runtime, outside prompts, tool arguments, source code and user-accessible configuration.

A local development application may obtain a restricted API key from an environment variable. A production service should generally use a managed secret store or workload identity, with distinct permissions for each environment and, when required, each tenant. The LangChain integration is responsible for converting model requests into the provider's API format; the host application is responsible for choosing and authorizing the provider, resolving credentials safely, validating configuration, and managing the credential lifecycle.

The preceding lesson (#285) explains the init_chat_model factory, model-name resolution and configurable fields. This lesson concentrates on the provider authentication boundary, deployment configuration and operational security. Generic credential hygiene is covered in MLOps #23; MCP #4 covers credentials for external MCP tools rather than model inference.

1. Understand the three different configuration layers#

A common mistake is treating all configuration as one dictionary. Separate the settings according to their purpose and trust level.

LayerExamplesOwner
Application model profileApproved provider, model or deployment ID, capability requirementsApplication configuration
Provider connection and identityApproved endpoint, region, project, authentication mode, secret referenceDeployment configuration and security policy
Request dataUser messages, retrieved context, requested taskUser/application request

Provider credentials authenticate a workload to the model service. They do not authenticate the application user, authorize a database query, or prove that a model-proposed action is allowed. For example, an authenticated model API request may still contain an unauthorized attempt to retrieve a customer's invoice. The application's domain-service authorization must independently reject that attempt.

A secret reference such as a secret-manager path is different from the secret value. The profile can contain an internal reference, but the application should resolve the actual credential only through a trusted runtime identity. Secret references should also be treated as sensitive internal metadata where appropriate.

Loading diagram…

Notice that credentials go to the model client or authentication transport, not into the messages. Do not implement a tool that returns the provider API key to the model.

2. Install the appropriate provider integration#

LangChain has a common chat-model interface, while many provider adapters are distributed as independent Python packages. Install the provider package you actually use. Pin a tested compatible dependency set in a lockfile, including the integration's underlying SDK where dependency management permits.

ServiceCommon integration packageCommon authentication approach
OpenAI APIlangchain-openaiAPI key; project-specific access as supported
Anthropic APIlangchain-anthropicAPI key
Gemini Developer APIlangchain-google-genaiAPI key through the supported configuration
Vertex AIGoogle provider integration appropriate to the installed release and backendApplication Default Credentials or supported workload identity
Azure OpenAIlangchain-openaiAPI key or supported Microsoft Entra ID token mechanism
Amazon Bedrocklangchain-awsAWS SDK credential chain, IAM roles and temporary credentials
Ollamalangchain-ollamaLocal service or authenticated remote deployment, depending on the hosting architecture

These are established integration families, not a live-verified compatibility matrix. Google integration behavior has changed across versions; Gemini Developer API and Vertex AI are different authentication and deployment modes even when they can serve related models. Check the exact integration package, backend, authentication support and constructor parameters for the release you install. Do not assume that every integration works through the same generic factory arguments.

For example, a clean local OpenAI development environment may use:

BASH
python -m venv .venv # Activate the environment for your operating system. python -m pip install langchain langchain-openai python -m pip check

For production, install from a reviewed dependency lock rather than copying this unpinned setup command into a deployment script. A package installed under one Python interpreter is not necessarily available to the interpreter running the service. Check the active environment before diagnosing a missing provider adapter.

3. Environment variables and local development#

Many API-key integrations support environment variables as a convenient source of authentication. Common examples include OPENAI_API_KEY and ANTHROPIC_API_KEY. Google Gemini API-key configuration commonly supports GOOGLE_API_KEY; confirm the supported names and precedence in the selected integration and backend. Azure OpenAI key-based configuration commonly uses AZURE_OPENAI_API_KEY together with approved endpoint and deployment settings.

Use the shell, your IDE's secret injection mechanism or a local development secret loader. Do not type a real secret into a Git-tracked configuration file, notebook, Dockerfile, build argument, browser JavaScript bundle or conversation.

A repository may contain a .env.example with placeholders, for example:

DOTENV
MODEL_PROFILE=support-development OPENAI_API_KEY=

The real local file, if your development process uses one, should be excluded from version control and protected with filesystem permissions. A .env file is not automatically loaded by Python; a process manager, explicit loader or development environment must load it. Never assume a .gitignore rule erases a previously committed secret. If a key has entered Git history, revoke it and investigate exposure.

The following example illustrates a minimal OpenAI integration and a fail-fast check for missing local configuration.

PYTHON
import os from langchain_openai import ChatOpenAI if not os.environ.get("OPENAI_API_KEY", "").strip(): raise RuntimeError("OpenAI authentication is not configured") model = ChatOpenAI( model="gpt-4o-mini", temperature=0.2, ) # Optional controlled smoke test, with synthetic input only: response = model.invoke("Reply with the word ready.") print(response.content)

The example uses an illustrative model identifier; availability, sampling options and exact signatures depend on the provider account and installed version. The environment variable is read by the integration according to its supported configuration contract. Avoid printing the value or including it in an exception message.

The SDK example was not executed in this offline environment. LangChain and the checked provider integrations were not installed, and no provider credentials were accessed.

Explicit credential injection#

In a service that obtains credentials from a managed secret store, a provider-specific factory can receive a secret directly rather than modify the process environment. For instance, the conceptual pattern for a supported OpenAI integration is:

PYTHON
from langchain_openai import ChatOpenAI def build_openai_client(approved_model: str, resolved_key: str): return ChatOpenAI(model=approved_model, api_key=resolved_key)

This is a version-dependent SDK illustration, not a tested live integration. Do not expose build_openai_client as an agent tool or accept resolved_key from a user message. The secret is supplied by trusted application infrastructure.

4. Choose the correct authentication mechanism#

API keys#

An API key is commonly a bearer credential: possession of the key may allow requests according to its configured permissions. Treat it as sensitive throughout its lifetime.

Use separate project or workload credentials where supported. Apply minimum required permissions, quotas and billing constraints. Do not share one unrestricted development key among all production deployments. A secret manager should restrict which workload can read each key and record access events without logging secret values.

Workload identity and temporary credentials#

Cloud services can often authorize a workload using its assigned identity rather than a manually distributed long-lived key. AWS SDKs support a credential-provider chain, including roles and temporary credentials. Google Cloud deployments can use Application Default Credentials and supported workload-identity mechanisms. Azure deployments can use appropriate Microsoft Entra ID mechanisms when the endpoint and integration support them.

For example, an Amazon Bedrock chat integration may rely on the AWS SDK's approved identity chain rather than hard-coding AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the application. The selected integration, region, model and IAM policy must still be compatible. When using temporary AWS credentials explicitly, the session token is part of the credential set. A partial or expired set can cause authentication failures.

Workload identity does not mean "no authentication." It changes how the credential is obtained, scoped and renewed. The workload must still be authorized to invoke the selected model and access any other required resources.

Endpoints and deployment identifiers#

For hosted cloud models, selecting the correct model string alone may be insufficient. Azure OpenAI can require an Azure resource endpoint and a deployment name distinct from a public model identifier; some API modes require additional version configuration. AWS Bedrock may require region-specific access and an approved inference model or profile. Google Cloud deployments may require a project and location.

Treat endpoint configuration as privileged. A user-supplied base URL could send confidential prompts or credentials to an unintended service. Use an allowlisted provider/deployment registry and restrict outbound traffic. Never forward a credential intended for one provider to another provider or an arbitrary compatible endpoint.

Configuration questionAPI-key integrationWorkload-identity integration
How is identity established?Secret key presented to providerTrusted runtime obtains temporary token or signed credentials
What is stored?Secret or reference to secretRole or identity configuration; possibly token cache managed by SDK
How does renewal occur?Controlled key rotationRefresh mechanism supported by the credential provider
What can fail?Missing, revoked or incorrectly scoped keyIdentity chain, expired token, role trust, permissions or region
What should logs contain?Sanitized error class and key version identifier if safeSanitized error class, identity alias and correlation ID

5. Separate configuration and secrets across environments#

A production-ready application should not silently fall back from production credentials to personal development credentials. Use explicit environment profiles and validate the selected identity and approved endpoint during startup or a controlled health check.

EnvironmentRecommended boundary
Local developmentRestricted development key; synthetic or approved test data
CI unit testsFake client and synthetic credentials; no provider calls
CI integration testsDedicated test identity, bounded budget and isolated synthetic data
StagingStaging-specific secrets and provider project or deployment
ProductionManaged workload identity or managed secrets with audited access

Do not place production secrets in a client-side application or in artifacts built for public distribution. Model calls that require private credentials belong behind a trusted backend or another provider-approved delegated authentication mechanism. Do not reuse secrets across environments merely because they invoke the same model.

For containerized workloads, inject configuration at runtime instead of baking secrets into image layers. Use an approved orchestration secret facility or identity-based secret access. Remember that environment variables can be visible to processes with sufficient privileges, debugging tools or crash dumps. They are a delivery mechanism, not a secure vault.

6. Testable tenant-scoped provider configuration#

Consider a SaaS product serving two fictional tenants. Tenant A uses an approved OpenAI deployment and tenant B uses an approved Anthropic deployment. Both request the application profile named support. The profile name alone is not unique across tenants.

The trusted server authenticates the caller, determines the tenant membership, looks up the authorized profile, resolves the profile's secret and selects the provider-specific factory. Never derive tenant identity from a model-generated tool argument or blindly trust a tenant ID in the HTTP request body.

Loading diagram…

The following standard-library Python example demonstrates an application-owned profile and credential resolver. It uses only synthetic values and fake adapters. The same example was executed locally with Python 3.13.5.

PYTHON
from dataclasses import dataclass, field @dataclass(frozen=True) class Profile: provider: str model: str secret_ref: str @dataclass(frozen=True) class Credential: version: str value: str = field(repr=False) class ConfigError(Exception): pass PROFILES = { ('tenant-a', 'support'): Profile('openai', 'approved-model-a', 'a/support'), ('tenant-b', 'support'): Profile('anthropic', 'approved-model-b', 'b/support'), } def build(tenant, name, read_secret, factories): profile = PROFILES.get((tenant, name)) if profile is None: raise ConfigError('profile_not_authorized') factory = factories.get(profile.provider) if factory is None: raise ConfigError('integration_unavailable') cred = read_secret(profile.secret_ref) if cred is None or not cred.version or not cred.value.strip(): raise ConfigError('credential_missing') # Factory must be a trusted, provider-specific adapter. client = factory(model=profile.model, api_key=cred.value) return client, (tenant, name, profile.provider, cred.version) secrets = {'a/support': Credential('v1', 'synthetic-a'), 'b/support': Credential('v1', 'synthetic-b')} requests = [] def read_secret(ref): requests.append(ref) return secrets.get(ref) def fake_openai(**kwargs): assert kwargs['api_key'].startswith('synthetic-') return 'openai-client' def fake_anthropic(**kwargs): assert kwargs['api_key'].startswith('synthetic-') return 'anthropic-client' factories = {'openai': fake_openai, 'anthropic': fake_anthropic} def rejected(fn, code): try: fn() except ConfigError as exc: assert str(exc) == code else: raise AssertionError('expected rejection') client, k1 = build('tenant-a', 'support', read_secret, factories) assert client == 'openai-client' and k1 == ('tenant-a','support','openai','v1') assert build('tenant-b','support',read_secret,factories)[0] == 'anthropic-client' assert requests == ['a/support','b/support'] rejected(lambda: build('tenant-c','support',read_secret,factories), 'profile_not_authorized') assert len(requests) == 2 rejected(lambda: build('tenant-a','support',read_secret,{}), 'integration_unavailable') assert len(requests) == 2 secrets['a/support'] = Credential('v2','synthetic-rotated-a') _, k2 = build('tenant-a','support',read_secret,factories) assert k2 != k1 and k2[-1] == 'v2' secrets['a/support'] = Credential('v3',' ') rejected(lambda: build('tenant-a','support',read_secret,factories), 'credential_missing') assert 'synthetic-b' not in repr(secrets['b/support']) print('PASS: 6 scenarios; tenant routing, missing profile, missing integration, rotation, blank secret, repr redaction verified')

Actual local execution result: PASS: 6 scenarios; tenant routing, missing profile, missing integration, rotation, blank secret, repr redaction verified.

The checks establish that an unauthorized profile and an unavailable integration are rejected before a secret is read, that the two tenants resolve different secret references, that a rotated version changes the returned client identity tuple, that blank credentials are rejected and that the dataclass's ordinary repr omits its secret value.

The example has important boundaries:

  • The tenant passed to build must already be authenticated and authorized by the host. The test does not implement identity verification or real secret-manager permissions.
  • A fake adapter does not verify provider authentication, exact SDK signatures or model availability. Different providers and workload-identity modes require different factory implementations.
  • The returned tuple is an illustration of a version-aware client identity, not a complete cache key. A production key must account for deployment profile revision, endpoint, region, identity scope and any other behaviorally relevant settings.
  • repr=False is only protection against accidental dataclass repr disclosure; it does not encrypt memory or protect serialization, object inspection, exception payloads, crash dumps or arbitrary logging.
  • Do not use this example's in-memory dictionary as a production secret store. Use a managed resolver, narrow access policy, error redaction and audited secret references.

7. Credential rotation without disrupting active agents#

Long-running agents may retain a client object across multiple model calls. Updating a secret in a secret manager does not necessarily update an already-created client. Some token-provider implementations refresh automatically, while static-key clients may need reconstruction. Check the actual integration contract and avoid mutating shared global client credentials in a concurrent service.

A controlled rotation for a provider that supports overlapping active keys can proceed as follows:

  1. Issue a replacement credential with the intended permissions and restrictions.
  2. Store the replacement under a new secret version.
  3. Construct a new client with the replacement and execute a small synthetic smoke test.
  4. Atomically direct new requests to the approved new version.
  5. Drain or explicitly migrate in-flight requests according to a bounded deadline.
  6. Revoke the old key after verifying that it is no longer needed.
  7. Monitor authentication failures and remove retired client references.
Loading diagram…

If the replacement fails its verification, do not promote it. A planned rollback may temporarily use the previous credential only if that credential is still valid, authorized and not compromised. If compromise is suspected, revoke the exposed credential promptly, even when this interrupts service, and recover using a clean identity. Do not keep a compromised key active merely to achieve zero downtime.

When using expiring access tokens, rely on a supported credential-refresh mechanism or explicitly design safe renewal. Avoid simultaneous refresh requests from every worker; coordinate refresh with bounded jitter or appropriate synchronization where needed. Never cache credentials indefinitely or indefinitely retain clients using retired versions.

8. Production diagnostics: distinguish configuration, authentication and authorization errors#

A model request may fail for several reasons that look similar at the agent interface. Diagnose at the boundary where the failure occurred.

SymptomLikely causeAppropriate response
ModuleNotFoundErrorWrong interpreter or missing integrationVerify active environment, lockfile and installed package
Missing credential during constructionSecret injection or identity configuration absentCheck runtime secret availability without displaying values
HTTP 401 or provider authentication errorInvalid, expired or revoked credentialInspect secret version, identity configuration and provider error class
HTTP 403 or permission errorIdentity may be valid but lacks required action or resource accessVerify approved project, role, deployment and permission scope
HTTP 404 or deployment not foundWrong model, endpoint, region or inaccessible resourceVerify deployment identifier and authorized endpoint
HTTP 400 or invalid requestUnsupported options, schema or API versionCheck provider contract and integration version
HTTP 429 or quota errorRequest rate, token quota or billing limit reachedInspect quota category; bound retries and reduce load
Timeout or TLS failureNetwork, endpoint, deadline or certificate issueDiagnose connectivity and approved transport configuration

HTTP status codes are common diagnostic categories, not guarantees: services can use different error formats, SDKs may wrap errors and some systems intentionally conceal unauthorized resources. Use the documented provider error type and safe correlation ID rather than rely exclusively on a numeric code.

Do not retry a permanently invalid API key repeatedly. A supported temporary-token refresh may resolve an expired-token error; if renewal fails, stop and report a controlled authentication failure. Rate-limit retries should honor provider guidance and task deadlines, while configuration errors should be fixed before further requests.

Do not automatically switch to an unrelated provider when authentication fails. Different providers may have different retention, residency, cost and contractual requirements. An alternate model route must be explicitly authorized for the workload and data classification.

Safe observability#

A useful diagnostic event can include a request ID, approved profile alias, provider name, configuration revision, non-sensitive credential-version identifier, error category and latency. It must not include the API key, authorization header, secret-manager response, raw SDK exception containing credentials, or complete confidential user prompt.

Redact sensitive headers and parameters at HTTP logging, tracing and exception boundaries. Verify redaction with synthetic sentinel values. For external monitoring or trace exports, apply retention and access controls to messages and tool outputs as well as credential-related metadata.

9. Numerical production example: credential versioning and failure isolation#

Suppose ten worker processes reuse a provider client for a support workload. A planned key rotation creates version v2 while v1 is still active. Each worker has a maximum permitted request duration of 30 seconds and may finish requests that began before the routing switch.

A rollout controller can first verify v2 using a synthetic request, publish the approved version and stop assigning new requests to v1 clients. After all workers acknowledge the new version and existing v1 requests have drained or reached their deadline, the controller can revoke v1. The observed drain time, not an arbitrary sleep, should determine readiness to retire the old key. This example is hypothetical; actual providers differ in their ability to maintain simultaneous credentials.

Now suppose the service incorrectly shares one provider credential across three tenants. A single revocation might interrupt all three. Separating authorized tenant profiles and identities where requirements justify it can reduce the failure scope, but increases operational overhead. A shared service identity can be a valid design if the provider agreement, application authorization, quotas and data-isolation policy permit it. Tenant isolation is a property of the complete application and identity design, not simply the number of API keys.

10. Deployment and verification checklist#

Before deploying an agent that calls a model provider:

  • Review provider integration versions, lockfile and supported authentication mode.
  • Verify the approved model or deployment ID, endpoint, region and project.
  • Resolve the credential only through the trusted runtime and reject missing or invalid configuration.
  • Ensure authentication is separate from tool authorization and user identity.
  • Test successful inference with a bounded synthetic prompt and validate required capabilities.
  • Test missing, expired or revoked credentials in a dedicated environment; do not deliberately revoke production credentials for a routine test.
  • Confirm unauthorized tenant profiles cannot resolve other tenants' secrets.
  • Test secret-version changes, client replacement and in-flight request behavior.
  • Verify no secret values appear in logs, traces, exception reports or model messages.
  • Monitor provider errors, usage, quota and credential rotation events.
  • Document a controlled response to credential exposure, including revocation, investigation and recovery.

Interview-ready answer#

I configure LangChain provider integrations using the appropriate installed package and a versioned, approved model profile. The profile identifies the model or deployment, endpoint and authentication method; credentials come from a protected runtime source, such as restricted environment variables in development or managed secrets and workload identity in production. I keep credentials outside model messages and tools, enforce tenant and provider authorization independently, validate the actual model deployment through a bounded smoke test, and rotate credentials by replacing versioned clients safely. I distinguish missing configuration, authentication failure, missing permissions, quota limits and unsupported model settings instead of blindly retrying every error.

Official reference leads and verification status#

The following official documentation entry points are supplied for further version-specific verification:

Authorized offline research exception applied. Live documentation, current package support, provider authentication and website rendering were unavailable. These links are official reference leads rather than live-accessed sources. The standard-library example was actually executed on Python 3.13.5 and passed the six stated scenarios using fake credentials and adapters. LangChain and the checked provider packages were not installed; SDK examples are illustrative and unexecuted. Mermaid blocks use standard triple-backtick fences, but live rendering has not been tested. No real credentials were read, created, transmitted or rotated for this lesson.

References

  1. 1.
    LangChain modelsdocs.langchain.com
  2. 2.
  3. 3.
  4. 4.
    OpenAI API documentationplatform.openai.com
  5. 5.
  6. 6.
  7. 7.

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.