LLM API Guide

OpenAI Python SDK base_url: Change the API Address and Key

Change base_url and api_key in the OpenAI Python SDK via code or environment variables, and fix /v1 404s, 2.34.0 Missing credentials, and Cloudflare 403 blocks.

A phosphor-green pixel stream bends at a central junction toward a larger endpoint block on a dark CRT screen.
Illustration, AI-generated

Summary

  1. Pass base_url and api_key directly to OpenAI() or AsyncOpenAI(), or set OPENAI_BASE_URL and OPENAI_API_KEY in your environment.
  2. Include the version suffix (usually /v1) in base_url, and avoid module-level openai.base_url without a trailing slash to prevent /v1completions 404 errors.
  3. Pass a non-empty placeholder like api_key="not-needed" for local servers in openai 2.34.0+.
  4. Override the default User-Agent header when Cloudflare WAF blocks the SDK's OpenAI/Python and x-stainless-* headers with a 403 error.

To point the official OpenAI Python SDK at another provider—whether that is DeepSeek, OpenRouter, a local vLLM or Ollama server, or a third-party API relay—pass base_url and api_key directly when you initialize the OpenAI or AsyncOpenAI client.

python
from openai import OpenAI, AsyncOpenAI

# Synchronous client
client = OpenAI(
    base_url="https://api.deepseek.com/v1",
    api_key="sk-your-provider-key",
)

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(response.choices[0].message.content)

# Asynchronous client
async_client = AsyncOpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="sk-or-v1-your-key",
)

In modern releases of the openai package, configuration lives on the client instance rather than on module-level globals. You can instantiate multiple clients in the same script if you need to route different calls to different providers.

On this page

Using OPENAI_BASE_URL and OPENAI_API_KEY Environment Variables

When you are working with an existing codebase or a framework that calls OpenAI() with no arguments, you can swap the endpoint and credentials from the shell without editing Python files:

bash
export OPENAI_BASE_URL="https://api.example.com/v1"
export OPENAI_API_KEY="sk-your-key"

Once those two variables are exported, a plain client = OpenAI() call reads them automatically. If you are migrating older scripts written for openai 0.x, note that the legacy OPENAI_API_BASE environment variable was removed in v1.0 and is completely ignored by current releases. You must rename it to OPENAI_BASE_URL. If you want to route Claude Code through a gateway instead, see making Claude Code use your gateway.

There is one environment variable trap I see regularly in Docker Compose files and .env templates. Developers often leave OPENAI_BASE_URL="" with an empty value, expecting the SDK to fall back to https://api.openai.com/v1. Instead, every request fails immediately with openai.APIConnectionError: Connection error.

Inside the SDK's _client.py, the constructor only checks if base_url is None: before calling os.environ.get("OPENAI_BASE_URL"). When OPENAI_BASE_URL is exported as an empty string "", os.environ.get() returns "" rather than None. The client treats that blank string as a custom URL you intentionally configured and tries to send HTTP requests to an empty address. To switch back to OpenAI's official API, remove the line from your .env file or unset it completely:

bash
unset OPENAI_BASE_URL

If you need to clean it up inside Python before initializing the client, delete the key from os.environ if it is blank:

python
import os
from openai import OpenAI

if os.environ.get("OPENAI_BASE_URL") == "":
    del os.environ["OPENAI_BASE_URL"]

client = OpenAI()

Do You Need /v1 at the End of base_url?

Yes, for almost every OpenAI-compatible server. When you call client.chat.completions.create(), the SDK appends /chat/completions to your base_url—it does not append /v1/chat/completions. If you set base_url="https://api.example.com", the request goes to https://api.example.com/chat/completions and usually returns a 404 Not Found.

The only exception is when a provider uses a different version path in its OpenAI-compatible router. For instance, Zhipu GLM's compatible endpoint ends in /api/paas/v4. In that case, set base_url to end at /v4 so the SDK requests /api/paas/v4/chat/completions.

Provider or Server base_url Value api_key Value
OpenAI (Default) https://api.openai.com/v1 sk-proj-...
OpenRouter https://openrouter.ai/api/v1 sk-or-v1-...
DeepSeek https://api.deepseek.com/v1 sk-...
Alibaba Qwen (DashScope) https://dashscope-intl.aliyuncs.com/compatible-mode/v1 sk-...
Zhipu GLM https://open.bigmodel.cn/api/paas/v4 Your GLM key
Local Ollama http://localhost:11434/v1 "ollama" (any non-empty string)
Local vLLM / llama.cpp http://localhost:8000/v1 "not-needed" (any non-empty string)

Why Module-Level openai.base_url Throws a 404 Without a Trailing Slash

When you pass base_url="https://example.com/api/v1" into OpenAI(), the client runs an internal _enforce_trailing_slash() method so that httpx joins the sub-path cleanly as https://example.com/api/v1/chat/completions.

However, if you use the module-level client (openai.base_url = ... followed by openai.chat.completions.create() or openai.models.list()), that setter bypasses _enforce_trailing_slash(). Without a trailing slash on your string, httpx merges the last path segment directly with the endpoint name, firing requests at https://example.com/api/v1models or https://example.com/api/v1completions and failing with HTTP/1.1 404 Not Found. Always instantiate client = OpenAI(base_url=...), or put an explicit trailing slash ("https://example.com/api/v1/") on openai.base_url.

Fixing Missing credentials on Local Servers (openai 2.34.0+)

Local inference servers like llama.cpp, vLLM, LM Studio, and Ollama do not check authentication keys by default. Up through openai 2.33.0, you could pass an empty string api_key="" and the client would run without complaints.

Starting in openai 2.34.0, the SDK tightened its initialization check to evaluate not self.api_key. Passing api_key="" now crashes before making a network call:

text
openai.OpenAIError: Missing credentials. Please pass an `api_key`, `workload_identity`, `admin_api_key`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.

To satisfy the check when calling a keyless local server, pass any non-empty placeholder string:

python
from openai import AsyncOpenAI

client = AsyncOpenAI(
    base_url="http://localhost:8080/v1",
    api_key="not-needed",
)

Version 2.34.0 also introduced a breaking authentication change if you use AzureOpenAI with a custom base_url pointing to an Azure API Management gateway. In 2.33.0 and earlier, passing an Azure AD / Entra ID token into api_key worked because the SDK sent both api-key and Authorization: Bearer headers. Now api_key only sends the api-key header, causing Azure gateways to reject AD tokens with a 401 Access denied error. Pass your token to azure_ad_token (or azure_ad_token_provider) instead of api_key.

Why curl Works But the Python SDK Gets 403 Your request was blocked

One of the most frustrating issues when connecting the SDK to a custom base_url—especially self-hosted NewAPI gateways or third-party relays behind Cloudflare—is getting an immediate 403 error in Python even though the exact same URL and API key work in curl:

text
openai.PermissionDeniedError: Error code: 403 - Your request was blocked.

If you check your own Nginx or NewAPI server logs, you will not even see the failed request arrive. That happens because Cloudflare's managed "Block AI training bots" / "Manage AI bots" rules inspect the incoming request headers at the CDN edge. By default, the OpenAI Python SDK sends a User-Agent of OpenAI/Python <version> (or AsyncOpenAI/Python <version>) along with a set of x-stainless-* telemetry headers (x-stainless-lang, x-stainless-package-version, x-stainless-os, x-stainless-arch, x-stainless-runtime). Cloudflare's bot filter flags the OpenAI/Python User-Agent and drops the connection before it reaches the origin server. Some gateways also return HTTP 412 Precondition Failed when they see default Python User-Agents.

You can bypass this block from your Python script by overriding User-Agent in default_headers:

python
from openai import OpenAI

client = OpenAI(
    base_url="https://your-relay.example.com/v1",
    api_key="sk-your-key",
    default_headers={
        "User-Agent": "Mozilla/5.0",
    },
)

For most Cloudflare-fronted relays, changing User-Agent to "Mozilla/5.0" or "litellm" is enough to turn a 403 into a 200 OK. If a stricter WAF rule inspects the x-stainless-* headers as well, pass a custom httpx.Client with an event hook that strips them before the request leaves your machine:

python
import httpx
from openai import OpenAI

def strip_stainless_headers(request: httpx.Request) -> None:
    for header in list(request.headers.keys()):
        if header.lower().startswith("x-stainless-"):
            del request.headers[header]
    request.headers["User-Agent"] = "Mozilla/5.0"

http_client = httpx.Client(
    event_hooks={"request": [strip_stainless_headers]},
)

client = OpenAI(
    base_url="https://your-relay.example.com/v1",
    api_key="sk-your-key",
    http_client=http_client,
)

If you control the Cloudflare domain in front of your own NewAPI or vLLM server, the cleaner fix is in the Cloudflare dashboard: either disable the automated AI bot block under Bot Management, or create a custom Security Rule matching your /v1/* path that skips managed WAF and Super Bot Fight Mode rules.

Once your connection goes through, keep in mind that third-party proxies do not always implement newer OpenAI endpoints the same way the official OpenAI API does. For example, calling client.responses.parse() with a Pydantic schema against a relay that silently translates /v1/responses into /v1/chat/completions often returns output_parsed=None or raises a ValidationError. When working with third-party gateways, I also recommend checking that the relay actually serves the model you paid for and knowing how to handle unsupported parameter 400 errors on OpenAI-compatible gateways.

If you also switch Base URLs and API keys in terminal coding agents like Codex CLI and Claude Code, I built an open-source desktop utility called LLM API Config GUI (GitHub). Instead of editing config files and shell profiles by hand, you can swap Base URLs, keys, and model IDs from a single interface, export profiles to CC Switch, and run a built-in diagnostic test to catch 401, 403, 404, 429, and timeout errors right away. For an Android agent app, the custom endpoint setup in Mika on Android shows how to enter an endpoint, key and model.

Sources and checks

  1. OpenAI Python SDK
  2. OpenAI API
  3. GitHub