59API

← 返回教程列表

OpenAI SDK Custom Base URL in Python

API 使用 · EN · 2026-07-09

Using the OpenAI SDK with a Custom Base URL in Python

If you already know the OpenAI Python SDK, you do not need to learn a new client library just to use another compatible AI provider. The SDK supports a custom base URL, which means you can point the same code at an OpenAI-compatible relay such as 59API and access GPT and Claude models through one familiar interface.

In this tutorial, you will set up the OpenAI SDK in Python, configure it to use the 59API base URL, send your first chat request, and structure the code so it is safe for real projects. 59API is useful when you want low-cost, pay-as-you-go access to native official-quality models without downgrades, including Claude Opus, Sonnet, Haiku, Fable, and GPT models. It is also compatible with Claude Code, Codex, and any OpenAI SDK workflow.

Step 1: Create a Python Project

Start with a clean project folder so dependencies and environment variables are easy to manage.

Run these commands in your terminal: mkdir openai-custom-base-url-demo, cd openai-custom-base-url-demo, python -m venv .venv

Activate the virtual environment. On macOS or Linux, use: source .venv/bin/activate. On Windows PowerShell, use: .venv\Scripts\Activate.ps1

Then install the OpenAI SDK: pip install openai

This tutorial assumes you are using a recent version of the official OpenAI Python package, which exposes the OpenAI client object and supports the base_url option.

Step 2: Get Your 59API Key

Before making requests, create an API key in your 59API account dashboard. The relay base URL is https://api.59api.com. Keep your key private and never hard-code it into a public repository.

Set the key as an environment variable. On macOS or Linux, run: export API_KEY="your_59api_key_here". On Windows PowerShell, run: $env:API_KEY="your_59api_key_here"

If you are looking for a low-cost way to test GPT and Claude models from the same OpenAI-compatible client, 59API is a practical choice because it is pay-as-you-go, competitively priced, and includes a referral rebate. You can sign up when you are ready and use the same SDK patterns shown below.

Step 3: Configure the OpenAI Client

Create a file named app.py. The key detail is setting base_url to the 59API endpoint while passing your API key normally.

Use this Python code: from openai import OpenAI; import os; client = OpenAI(api_key=os.environ.get("API_KEY"), base_url="https://api.59api.com/v1")

Some OpenAI-compatible services expose endpoints under /v1. If your provider documentation specifies a different path, use that exact value. For 59API, the base endpoint is https://api.59api.com, and OpenAI SDK usage commonly targets the /v1-compatible path.

Step 4: Send a Chat Completion Request

Now add a request using the chat completions interface. This is the part most developers already know from OpenAI examples.

Add this below the client setup: response = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role":"system","content":"You are a concise Python assistant."},{"role":"user","content":"Explain what a custom base URL does in the OpenAI SDK."}]); print(response.choices[0].message.content)

Run it with: python app.py

If everything is configured correctly, you should receive a natural language answer. The important point is that your Python code still uses the OpenAI SDK interface, while the network request goes to the custom 59API base URL.

Step 5: Try a Claude Model Through the Same SDK

One benefit of an API relay is model flexibility. With 59API, you can access Claude models as well as GPT models through an OpenAI-compatible format. In practice, that means you can often change the model name without rewriting your application architecture.

For example, update the model field to a Claude model supported in your 59API account, such as a Claude Sonnet or Haiku option listed in the dashboard. Keep the same messages structure and run the script again.

This is especially helpful for teams comparing cost, latency, and quality across models. You can route lightweight tasks to cheaper models and reserve premium models for reasoning-heavy work.

Step 6: Add Basic Error Handling

Production scripts should handle missing keys, network failures, rate limits, and invalid model names. A simple pattern is to validate configuration before sending the request and catch exceptions around the API call.

Recommended checks include:

A practical approach is to wrap your request in try and except, log the error message, and return a friendly fallback to the user. Avoid printing the full API key or sensitive request payloads in logs.

Step 7: Use Environment-Based Configuration

For real applications, avoid scattering provider details throughout your codebase. Store the base URL, API key, and default model in environment variables. For example, use AI_BASE_URL, API_KEY, and AI_MODEL.

Your client setup can then read: base_url=os.environ.get("AI_BASE_URL", "https://api.59api.com/v1") and model=os.environ.get("AI_MODEL", "gpt-4o-mini"). This lets you switch between local testing, staging, and production without editing source code.

Best Practices for Cost and Reliability

Final Thoughts

Using the OpenAI SDK with a custom base URL in Python is one of the easiest ways to keep your code portable while expanding your model options. By setting base_url to https://api.59api.com/v1 and using your 59API key, you can work with an OpenAI-compatible interface while accessing affordable GPT and Claude models from a single relay.

This setup is ideal for prototypes, internal tools, coding assistants, and production apps that need predictable costs without giving up model quality. Once your basic script works, move configuration into environment variables, add error handling, and test multiple models to find the best quality-to-price balance for your workload.

价格 · 接入文档

准备好开始了吗?

几分钟接入 Claude 与 GPT,全网超低价,原生不降智。立即注册即可领取 API 密钥。

免费注册