Skip to content

InvalidURL error when NO_PROXY environment variable contains newline characters #3303

@yie1d

Description

@yie1d

Confirm this is an issue with the Python library and not an underlying OpenAI API

  • This is an issue with the Python library

Describe the bug

When the NO_PROXY environment variable contains newline characters (common in Docker environments, .env files, or shell scripts), creating an OpenAI client raises InvalidURL.

The error occurs because httpx's get_environment_proxies() only splits NO_PROXY by comma ,, not by newline \n. When a newline is present in the value, it becomes part of the hostname and triggers
URL validation failure.

The fix in httpx would be trivial, but the encode/httpx project is currently not actively accepting external PRs or issues.

Suggesting that openai-python sanitize proxy-related environment variables when initializing the internal httpx client.

To Reproduce

import os
os.environ['NO_PROXY'] = 'localhost\n192.168.1.1'

from openai import OpenAI
client = OpenAI(api_key='sk-test')

Error:
httpx.InvalidURL: Invalid non-printable ASCII character in URL, '\n' at position 16

Code snippets

Root cause trace:

  # 1. stdlib returns raw value with newline
  from urllib.request import getproxies
  import os
  os.environ['NO_PROXY'] = 'localhost\n192.168.1.1'
  print(getproxies())
  # {'no': 'localhost\n192.168.1.1', ...}

  # 2. httpx splits only by comma, newline stays in hostname
  from httpx._utils import get_environment_proxies
  print(get_environment_proxies())
  # {'all://*localhost\n192.168.1.1': None, ...}

  # 3. httpx URL parser rejects non-printable character
  import httpx
  httpx.Client()
  # InvalidURL: Invalid non-printable ASCII character in URL, '\n' at position 16

  Workaround:

  import os
  for key in ("NO_PROXY", "no_proxy"):
      val = os.environ.get(key)
      if val and "\n" in val:
          os.environ[key] = ",".join(
              part.strip() for part in val.replace("\n", ",").split(",") if part.strip()
          )

  from openai import OpenAI  # now works

OS

Windows / Linux (any)

Python version

3.11+

Library version

openai: latest

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions