How to Change base_url in the OpenAI Python Library: 3 Ways

Blog / Developer tools

How to Change base_url in the OpenAI Python Library: 3 Ways

The most direct way to change base_url in the openai Python library is to pass it when you create the client: OpenAI(base_url="...", api_key="..."). If you would rather not touch code, set the environment variable OPENAI_BASE_URL. When both are present, the argument you pass explicitly in code wins. The library has no "config file" layer of its own. The config-file approach is really just you keeping the address in a .env or YAML file, reading it yourself, and handing it to the client.

Below are the three approaches in turn, plus a way to verify precedence and a troubleshooting order for common errors. This article assumes you are on the openai 1.x library; for fields and behavior, the official OpenAI SDK repository is the authority.

What is base_url, and when do you need to change it?

base_url is the prefix the SDK uses when it builds request paths. When you call client.chat.completions.create(...), the library appends a path such as /chat/completions to base_url and sends the request. The default points at the official OpenAI API.

You would change it in roughly three situations:

  • You are using another service that implements the OpenAI-compatible format, including cloud-hosted offerings, aggregation gateways, and the compatible endpoints of Chinese model vendors;
  • Your company has a unified egress gateway that every request must pass through;
  • You are running a compatible service locally for debugging.

If you have not yet made a first successful call, start with Calling the OpenAI API from Python: From Installing the SDK to Printing a Reply, then come back to change the address.

Method 1: constructor argument

from openai import OpenAI

client = OpenAI(
    base_url="https://your-service-address/v1",
    api_key="your API key",
)

resp = client.chat.completions.create(
    model="a model name the service supports",
    messages=[{"role": "user", "content": "Hello"}],
)
print(resp.choices[0].message.content)

This is the clearest form: the address and key are right there. The downside is that it is easy to hardcode the key and commit it to a repository, so it is better to read api_key from an environment variable anyway: api_key=os.environ["MY_API_KEY"].

If you only want one request to go to a different address, use client.with_options(base_url=...) to get a derived client; the original client is unaffected. For the exact parameters of that method, check the official docs.

Method 2: environment variables

The openai library reads two environment variables: OPENAI_API_KEY and OPENAI_BASE_URL. Once they are set, plain OpenAI() in your code is enough.

Linux / macOS:

export OPENAI_BASE_URL="https://your-service-address/v1"
export OPENAI_API_KEY="your API key"
python app.py

Windows PowerShell:

$env:OPENAI_BASE_URL = "https://your-service-address/v1"
$env:OPENAI_API_KEY = "your API key"
python app.py

The benefit is that the same code can switch between local, staging, and production addresses without changing a line of Python. Note that an environment variable only takes effect in the current terminal session. A different terminal, an IDE run configuration, or a systemd service each needs it set again, and this is the most common cause of "I definitely set it but it has no effect."

Method 3: your own config file

The SDK does not automatically read YAML, TOML, or similar files. The usual approach is a .env file with python-dotenv, or parsing a config file yourself, then passing the values to the constructor:

import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()  # Read .env in the current directory into environment variables

client = OpenAI(
    base_url=os.getenv("LLM_BASE_URL"),
    api_key=os.getenv("LLM_API_KEY"),
)

Contents of .env:

LLM_BASE_URL=https://your-service-address/v1
LLM_API_KEY=your API key

Remember to add .env to .gitignore. Using custom variable names instead of OPENAI_* here keeps other programs on the same machine from accidentally picking up the same variables.

When the three conflict, which one wins?

In openai 1.x the order is: constructor argument > environment variable > built-in library default. If you pass None as the argument, it falls back to the environment variable. You can verify the address actually in effect with one line:

print(client.base_url)

When you are trying to figure out why a request went somewhere it shouldn't, printing this value first is much faster than guessing.

Should the address include /v1, and should it end with a slash?

This is the part most likely to go wrong after you change the address.

SymptomCommon causeFix
404Missing /v1, or an extra /chat/completionsWrite base_url only up to the prefix the service docs require; do not include a specific endpoint path
404Path built as /v1/v1/...The address already contains /v1; do not repeat it
401The key and the address belong to different servicesConfirm the key belongs to the service that the current base_url points to
Connection timeoutNetwork unreachable, or the domain is wrongTest the same address with curl first, see below
Model not foundThe model name is not that service's namingUse the service's own model list

Exactly how far the address should go must follow the service provider's docs; some use /v1, others use a different prefix. Clients such as Cline and Cherry Studio have their own rules about trailing slashes, covered in Cline OpenAI Compatible Returns 401 or 404: How to Fill in the Base URL and How to Fill in the API Address in Cherry Studio.

After the change, how do you confirm it works?

First step out of Python and send a minimal request with curl to confirm that the address, key, and model name are all fine, then go back to your code. The steps are in Sending Your First LLM Request with curl: Every Parameter Explained. If curl works but Python does not, the problem is usually an environment variable that did not take effect, proxy settings, or the arguments in your code. If both fail, the address or key is the problem.

If you suspect network quality, you can use cdnping's online speed test to measure the first-connection and round-trip time from your current network to various API endpoints. For the underlying principles, see How to Read Latency When Accessing AI APIs from China.

Once it works, set the timeout and retries while you are at it. Defaults and recommendations are in How to Configure OpenAI SDK Timeouts and Retries.

Example: pointing the client at AGI Plan

AGI Plan is a multi-provider LLM aggregation gateway. It is billed by monthly subscription, accepts payment in RMB with no overseas credit card required, and is compatible with both the OpenAI and Anthropic API formats. AGI Plan is a commercial partner of cdnping. The service states clearly that it is not an officially authorized channel, and some models are available only outside China; see the AGI Plan models page for specifics.

Setup is roughly three steps: sign up with an emailed verification code, pick a plan and create a key, and change one setting. In the openai library, that means replacing base_url and api_key above with the values shown in the console. For the exact endpoint address, follow the AGI Plan console and docs; this article does not write it for them.

client = OpenAI(
    base_url=os.environ["AGIPLAN_BASE_URL"],  # Use the address shown in the console
    api_key=os.environ["AGIPLAN_API_KEY"],
)

Tools like Claude Code and Codex are the same idea: change one endpoint address. See Custom API Endpoints for Claude Code, Codex, and OpenCode. For sign-up and plans, see Getting Started with AGI Plan; to check whether the service has been healthy recently, see the AGI Plan status page.

Checklist

  1. Run print(client.base_url) to confirm the address actually in effect.
  2. Check that the address includes the prefix the service requires and that nothing is appended twice.
  3. Check that the key belongs to the service behind that address.
  4. Check that the model name comes from that service's list.
  5. Check that the environment variable is present in the current process (os.environ.get("OPENAI_BASE_URL")).
  6. Check that the key has been removed from your code and repository; if it was ever leaked, see Your OpenAI API Key Leaked: Revoke It, Check Usage, Prevent a Repeat.

Next step: confirm with curl that the new address returns a result, then move the address into an environment variable so that only OpenAI() remains in your code. That way, when you switch services later, you change configuration, not code.

Related articles

Keep reading