Last reviewed: October 30, 2026 (Asia/Shanghai).

Direct answer

Choose the egress policy when constructing the HTTPX client used for CometAPI. For an application-managed policy, set trust_env=False, select either approved direct egress or an explicitly configured required proxy, and supply the intended CA context. Reject missing required-proxy configuration before admitting traffic. Keep that policy attached to every client used by the route.

HTTPX’s environment-variable reference says environment settings are used by default. HTTP_PROXY, HTTPS_PROXY, and ALL_PROXY can select a proxy; NO_PROXY can exempt destinations. Consequently, two workers with identical API URLs can use different paths when their launch environments differ. Disabling inheritance is a client configuration choice; it does not disable a transparent network proxy or service mesh.

There is a coupled trust change to handle: HTTPX also recognizes SSL_CERT_FILE and SSL_CERT_DIR. Turning off environment inheritance can remove an intentionally supplied CA override. Preserve the approved CA source explicitly, using the SSLContext pattern in the HTTPX SSL guide . Never compensate for a resulting certificate error with verify=False.

Who this is for

This guide is for Python gateway maintainers and SREs diagnosing CometAPI requests that behave differently across workers, containers, development shells, or fallback routes. It covers client-side proxy selection in HTTPX. The endpoint remains the documented API endpoint; the proxy controls how the client reaches it.

The examples are configuration patterns and proposed verification steps. They do not report a CometAPI incident, an authenticated API test, or a measured deployment outcome.

Key takeaways

  • Give the route a named egress mode and configuration revision.
  • Configure a required proxy explicitly and stop when its configuration is missing.
  • Handle CA selection alongside trust_env; retain HTTPS verification.
  • Verify the actual connection path, since an unchanged request URL does not prove direct egress.
  • Keep proxy credentials and provider credentials separate in configuration and diagnostics.
  • Classify local egress failures before allowing retries or fallback.

Contract details to verify

Record the route’s API origin, endpoint path, egress mode, approved proxy reference, CA-bundle revision, client-library version, configuration revision, and client-construction owner. Mark direct egress as permitted or forbidden. A policy called “proxy preferred” leaves the failure behavior unresolved; decide whether inability to reach the proxy must hold the route.

The CometAPI Chat Completions reference documents the HTTPS API host api.cometapi.com with the /v1 SDK base path, POST /v1/chat/completions, and bearer authentication. Keep this API identity separate from the proxy address. Do not replace the API base URL with an ordinary forward proxy’s address. An application gateway that exposes its own API endpoint requires a different endpoint and credential contract.

Use this small decision table before changing a worker:

Intended modeHTTPX configurationRequired acceptance evidence
Approved direct egresstrust_env=False, no explicit proxy, explicit CA contextControlled request uses the permitted direct path
Required HTTP proxytrust_env=False, explicit proxy, explicit CA contextControlled request reaches the approved proxy; proxy failure produces no direct retry
Deliberately environment-managedEnvironment inheritance retained under a documented launch policyEffective proxy, bypass, and CA settings match the approved deployment revision

The first two modes are the application-managed pattern below. An intentionally environment-managed deployment can also be valid, but it needs controlled variable injection and equivalent path evidence. Do not change it to direct egress merely to make a failing request succeed.

Construct the client from trusted configuration

The HTTPX proxy guide documents the proxy constructor argument. This example combines it with an explicit CA bundle and rejects contradictory mode settings. Pass values from trusted server configuration, after validating the proxy destination against your deployment policy:

import ssl
import httpx


def make_chat_client(*, mode, ca_bundle, approved_proxy_url=None):
    if mode not in {"direct", "proxy_required"}:
        raise ValueError("invalid_egress_mode")
    if mode == "proxy_required" and not approved_proxy_url:
        raise ValueError("missing_required_proxy")
    if mode == "direct" and approved_proxy_url is not None:
        raise ValueError("unexpected_proxy_configuration")
    if not ca_bundle:
        raise ValueError("missing_ca_bundle")

    context = ssl.create_default_context(cafile=ca_bundle)
    return httpx.Client(
        base_url=httpx.URL(
            scheme="https", host="api.cometapi.com", path="/v1/"
        ),
        trust_env=False,
        proxy=approved_proxy_url,
        verify=context,
        follow_redirects=False,
        timeout=httpx.Timeout(20.0, connect=5.0),
    )

Use the returned client for this route and close it during the owning application’s shutdown. The trailing slash permits a relative request path such as chat/completions. Supply the CometAPI bearer token on the API request from your server-side secret mechanism. The factory does not send a request or validate a completion envelope; retain those checks in the outbound adapter. Its network timeouts also do not replace the user’s total deadline.

For a typical HTTP CONNECT proxy, the proxy URL may use the http scheme even when the API URL uses https. HTTPX explains that HTTPS can run through a tunnel established via an HTTP proxy. This does not call for downgrading the API URL. If your proxy itself uses HTTPS, review its separate TLS configuration as well. Record whether a proxy tunnels TLS or intentionally terminates and re-establishes it; that changes the trust boundary.

HTTPX supports proxy authentication in the proxy URL’s user-information component. Keep that value in a protected configuration source and never print the complete URL. Proxy credentials and the CometAPI bearer token authenticate different hops. Redacting the provider header alone does not make proxy configuration safe to log.

Audit custom transports, mounts, wrappers, and separately created clients. A setting on one factory does not govern a client constructed elsewhere. If mounts install their own transports, verify their proxy and TLS settings explicitly. For response lifetime ownership after dispatch, use the site’s HTTPX stream cleanup guide .

Happy-path operator workflow

Start with the actual worker launch path. Inventory whether proxy, bypass, and CA variables are present without dumping the process environment. Include the lowercase spellings accepted by the deployed stack in that inventory. Record presence and approved configuration references; keep values in the protected configuration system.

Construct a new client from the candidate policy in one staging worker. Check configuration validation first: an unsupported mode, absent required proxy, contradictory direct-mode setting, or unreadable CA bundle must prevent readiness. Then make a synthetic request through a controlled endpoint and proxy recorder with no production credentials or customer content.

Verify where the connection went using the controlled proxy’s records or authorized network telemetry. An HTTPX request hook showing the API hostname describes the logical request destination, not necessarily the socket’s first hop. For direct mode, require the approved direct path. For required-proxy mode, require proxy-path evidence and confirm that direct access is denied by deployment egress controls where policy requires it.

Repeat with a fresh process and the same launcher used by production. Once path and trust checks pass, perform your separately authorized, bounded CometAPI readiness check using a model approved for your account. Require the API response contract as well as transport success. Retain the site’s zero-hop redirect policy so a successful proxy connection cannot silently introduce another destination.

Error-path operator workflow

When workers disagree, compare egress mode, policy revision, CA revision, library version, and client-construction path before changing provider routing. Inspect the service launcher and container configuration, rather than assuming an interactive shell has the same environment.

If the required proxy is unavailable, hold that route. Do not catch the error and construct a direct client as an undocumented recovery step. A separately approved fallback remains subject to its own egress policy, remaining deadline, attempt budget, and replay checks. Failure before a proxy connection and failure after request transmission have different implications; retain what is known about dispatch instead of assuming no provider work occurred.

If certificate verification fails after disabling inheritance, compare the explicit CA bundle with the former approved environment override. Restore the intended trust source through configuration review and a new client. The site’s TLS trust guide covers verification and rotation evidence in depth.

Emit a bounded event with route label, egress mode, policy revision, proxy reference, CA revision, client version, failure stage, sanitized error class, and terminal action. Mark the observed path as unknown when evidence is unavailable. Keep full proxy URLs, exception strings, environment dumps, prompts, and authorization material out of ordinary logs.

Verify the policy under conflicting settings

Run these cases in disposable staging processes. Use the exact deployed HTTPX version and a controlled proxy; changing process-wide variables inside a busy worker can affect unrelated code. These are acceptance criteria, not reported results:

Controlled caseExpected application-managed behavior
An unrelated HTTPS_PROXY or ALL_PROXY is injectedDirect mode stays on its approved direct path; required-proxy mode still uses its explicit proxy
NO_PROXY names the test destinationRequired-proxy mode still uses its explicit proxy
Required proxy configuration is absentClient construction fails before any request
The configured proxy refuses connectionsAttempt fails without an application retry through direct egress
SSL_CERT_FILE points to an unrelated test fileThe explicitly supplied CA context remains authoritative
The configured CA bundle is invalid or the test peer has the wrong certificateConstruction or verification fails; no insecure retry occurs
A replacement worker starts under the production launcherIt reports the intended policy revision and reproduces the verified path

Observe both the proxy recorder and the direct-path recorder or egress telemetry. A final application error alone cannot show whether an earlier direct attempt occurred. An in-memory mock transport also cannot prove that environment proxy routing works: use real controlled sockets for this boundary. After the configuration change, replace or drain old clients deliberately; editing a launch variable does not establish that an existing client’s route changed.

Failure modes

Only HTTPS_PROXY is removed. Other inherited proxy or bypass settings can still affect a default client. Choose the complete inheritance policy rather than deleting one variable during an incident.

trust_env=False becomes accidental bypass. The deployment required a proxy but never passed one explicitly. Require the mode and proxy binding together, with network enforcement for mandatory egress.

A CA override disappears. Disabling inheritance changes both routing inputs and CA inputs. Supply the reviewed CA context before rollout.

The request URL is treated as path evidence. The logical API origin can remain unchanged through a proxy. Verify the connection path independently.

A wrapper rebuilds the client. Another constructor restores default inheritance. Centralize route construction and exercise that exact path in staging.

FAQ

Does trust_env=False disable an explicitly configured proxy?

No. It disables HTTPX’s environment inheritance. The proxy argument supplies an explicit proxy configuration. Verify custom mounts and transports separately.

Should every deployment disable environment inheritance?

No. Some platforms intentionally manage egress and CA settings through the launch environment. Keep that choice explicit, control the injected settings, and test bypass behavior. The application-managed pattern provides a reproducible alternative.

Does an HTTP proxy mean the API request uses plaintext?

An HTTP proxy can establish a tunnel through which the client performs HTTPS with the API server. Keep the API URL on HTTPS and verification enabled. Determine separately whether your approved proxy intercepts TLS.

Does explicit client configuration prevent every proxy bypass?

No. Other clients, custom transports, application retry logic, and network intermediaries need their own controls. Enforce a mandatory proxy path at the network boundary and test the complete deployed route.

Reader next step

Choose one CometAPI route and record its intended egress mode, approved proxy reference, CA revision, and client owner. Run the conflicting-variable and unavailable-proxy cases with synthetic data, and retain evidence of the actual path. Promote one replacement worker only after its path and trust behavior match the policy.

When that boundary is ready, Start with CometAPI and apply the verified client configuration to a small, authorized readiness request.

Sources checked

  • HTTPX: Environment Variables — checked October 30, 2026. Supports default inheritance, trust_env=False, proxy selection, bypass settings, and CA environment variables.
  • HTTPX: Proxies — checked October 30, 2026. Supports explicit proxy configuration, mounts, proxy authentication, and HTTPS tunneling through an HTTP proxy.
  • HTTPX: SSL — checked October 30, 2026. Supports default verification, explicit CA contexts, and CA environment overrides.
  • CometAPI: Create a chat completion — checked October 30, 2026. Supports the API base URL, Chat Completions endpoint, required request fields, bearer authentication, and response contract.

These are maintained primary technical references for an evergreen configuration problem. They support the documented client and API behavior; the egress modes, hold decisions, and acceptance matrix are engineering recommendations to verify in your own deployment.