How to Use OpenAI-Compatible APIs? A Guide to Python Integration and Multi-Model Switching

OpenAI-compatible APIs provide developers with a standardized way to access large models. Using Python code examples, this article explains how to use the OpenAI SDK to connect to different model services and implement model switching, streaming output, and unified configuration management.

openai-compatible-api-guide

Key takeaways

  • Unified interface access: OpenAI-compatible APIs support reusing the OpenAI SDK. By configuring the API Key, Base URL, and Model ID, you can reduce repeated integration work for different large models.
  • Python calls and multi-model switching: Through code examples, learn basic API calls, streaming output, token usage statistics, and multi-model switching for more flexible model access and management.
Audience
Developers · Beginner

How to Use OpenAI-Compatible APIs? A Guide to Python Integration and Multi-Model Switching

As large models such as DeepSeek and Tongyi Qianwen begin to offer OpenAI-compatible interfaces, developers no longer need to rewrite complete calling programs for every text model that supports this interface.

In many cases, you only need to adjust the API Base URL, API Key, and model name to reuse existing OpenAI SDK calling logic.

However, OpenAI compatibility does not mean that all models have identical features, parameters, and response results.

This article starts with environment configuration, introduces how to call OpenAI-compatible APIs through Python code examples, and further explains multi-model switching, streaming output, and interface management in production environments.

01 What Is an OpenAI-Compatible API?

An OpenAI-compatible API means that a model provider adopts the same or similar request format, interface paths, and response structure as the OpenAI API, allowing developers to use existing OpenAI SDKs or related development tools to call other model services.

Among them, the Chat Completions interface is a relatively common form of compatibility.

A typical request structure is as follows:

{
  "model": "your-model-id",
  "messages": [
    {
      "role": "user",
      "content": "你好,请介绍一下大模型 API。"
    }
  ],
  "stream": false
}

With a standardized interface structure, developers can reduce repeated integration work across different models.

However, interface compatibility mainly solves the problem of how to make calls; it does not mean that different models have the same reasoning ability, context length, tool-calling ability, or output quality.

02 What Configuration Is Needed to Access an OpenAI-Compatible API?

Usually, you need to prepare the following three core configurations.

Configuration item

Purpose

API Base URL

Specifies the base interface address of the model service

API Key

Used for identity authentication and call permission verification

Model ID

Specifies the model to be called

SDK

Provides development capabilities such as sending requests and parsing responses

The API Base URL and API Key must match the actual service platform being used.

The Model ID should also follow the corresponding platform's model catalog or interface documentation, rather than directly using the model's marketing name.

03 Install the Python SDK

It is recommended to use a Python virtual environment to manage project dependencies.

Create a virtual environment:

python -m venv .venv

Activate the environment in Windows PowerShell:

.venv\Scripts\Activate.ps1

Activate the environment on Linux or macOS:

source .venv/bin/activate

Install the OpenAI Python SDK:

pip install --upgrade openai

If the project needs to use .env file to manage environment variables, you can also install:

pip install python-dotenv

In formal projects, it is recommended to record and lock tested dependency versions to avoid compatibility issues caused by SDK updates.

04 Configure the API Key, Base URL, and Model Name

Create a .env file:

LLM_API_KEY=your_api_key
LLM_BASE_URL=https://your-provider.example/v1
LLM_MODEL=your_model_id

The above content is a configuration example and must be replaced with the information provided by the actual service platform.

Also, in the .gitignore file, add:

.env
.venv/
__pycache__/

Avoid uploading the API Key to public code repositories.

For production environments, use environment variables, key management services, or other secure configuration mechanisms instead of writing keys directly into code.

05 Make Your First API Request with Python

Create a main.py file:

import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI(
    api_key=os.environ["LLM_API_KEY"],
    base_url=os.environ["LLM_BASE_URL"],
    timeout=60.0
)

response = client.chat.completions.create(
    model=os.environ["LLM_MODEL"],
    messages=[
        {
            "role": "system",
            "content": "你是一名专业的技术助手。"
        },
        {
            "role": "user",
            "content": "请用三句话解释什么是 MaaS。"
        }
    ]
)

print(response.choices[0].message.content)

Run the program:

python main.py

If the interface address, key, and model identifier are correct and the service supports the Chat Completions interface, the program can return content generated by the model.

The API endpoint is not hardcoded to a specific model vendor; instead, the configuration is managed through environment variables to make it easier to switch model services later.

06 How to implement streaming output?

A standard API request usually waits for the model to generate a complete response before returning the result.

Streaming output (Streaming) allows the client to receive content progressively as the model generates.

For interactive applications such as AI chatbots, intelligent customer service, and code assistants, streaming output can reduce the time users wait for the first piece of content.

Example code:

stream = client.chat.completions.create(
    model=os.environ["LLM_MODEL"],
    messages=[
        {
            "role": "user",
            "content": "介绍大模型 API 的三个应用场景。"
        }
    ],
    stream=True
)

for chunk in stream:
    if chunk.choices:
        content = chunk.choices[0].delta.content
        if content:
            print(content, end="", flush=True)

print()

Note that streaming output mainly improves the content display experience and does not necessarily mean that the model's overall generation time is shorter.

Different model services may also differ in streaming fields such as reasoning content, tool call events, and usage statistics.

07 How to switch between multiple large models through a unified interface?

If multiple models are provided by the same compatible API service, developers can manage the model name as an independent parameter.

For example:

def ask_model(model_id, prompt):
    response = client.chat.completions.create(
        model=model_id,
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ]
    )

    return response.choices[0].message.content

Calling different models:

result_a = ask_model(
    "your-model-a",
    "请总结大模型 API 的主要优势。"
)

result_b = ask_model(
    "your-model-b",
    "请总结大模型 API 的主要优势。"
)

print("模型 A:", result_a)
print("模型 B:", result_b)

The model names above are placeholders and need to be replaced with the Model IDs actually supported by the platform.

If the two models come from different service platforms, you usually also need to configure the Base URL and API Key separately.

Select models based on task type

Enterprises can further bind model configurations to business tasks.

MODEL_CONFIG = {
    "classification": "your-lightweight-model",
    "reasoning": "your-reasoning-model",
    "generation": "your-general-model"
}

def run_task(task_type, prompt):
    model_id = MODEL_CONFIG[task_type]
    return ask_model(model_id, prompt)

For example:

result = run_task(
    "classification",
    "判断这条客户反馈属于哪种问题类型。"
)

print(result)

This approach is a basic rule-based model routing method.

Compared with hardcoding fixed model names directly in business code, independent configuration reduces the modification work required for future model upgrades and replacements.

However, before formal use, you still need to verify the task quality and parameter compatibility of each model.

08 How to record token usage and API call costs?

For interfaces that support usage statistics, you can obtain token consumption from the usage field in the response.

response = client.chat.completions.create(
    model=os.environ["LLM_MODEL"],
    messages=[
        {
            "role": "user",
            "content": "解释什么是模型路由。"
        }
    ]
)

if response.usage:
    print("输入 Token:", response.usage.prompt_tokens)
    print("输出 Token:", response.usage.completion_tokens)
    print("总 Token:", response.usage.total_tokens)

Enterprises can further write the following data to logs or monitoring systems:

  • The actual model name called.

  • Request time and response duration.

  • Input and output token counts.

  • Cache hit usage (if provided by the interface).

  • Request success or failure status.

  • The corresponding business task and project identifier.

This data can help teams compare the actual usage costs of different models and identify abnormal calls and unnecessary duplicate requests.

Total token count is not equal to actual cost. Cost calculation still needs to combine different billing rules for input, output, cache, etc.

09 How to handle API call exceptions?

In production environments, you cannot assume that every API request will succeed.

The OpenAI Python SDK provides corresponding exception types, and developers can handle them based on the cause of the error.

from openai import (
    AuthenticationError,
    RateLimitError,
    APITimeoutError,
    APIConnectionError,
    APIStatusError
)

try:
    result = ask_model(
        os.environ["LLM_MODEL"],
        "介绍 AI Agent 的基本原理。"
    )

    print(result)

except AuthenticationError:
    print("身份验证失败,请检查 API Key。")

except RateLimitError:
    print("请求受限,请检查额度与限流规则。")

except APITimeoutError:
    print("请求超时。")

except APIConnectionError:
    print("网络连接异常,请检查服务地址。")

except APIStatusError as e:
    print("API 请求失败,状态码:", e.status_code)

Common errors and handling methods are as follows:

Error type

Common cause

Recommended handling

400

Invalid request parameters or format

Check model parameters and API documentation

401

Invalid API Key

Check the API key and service address

403

Missing access permissions

Check account and model permissions

404

API or model does not exist

Verify the Base URL and Model ID

429

Request rate limiting or quota limit

Check rate limiting rules and account quota

5xx

Server-side exception

Perform limited retries based on the error type

Timeout

Network or generation takes too long

Check timeout configuration and service status

The SDK itself may perform automatic retries for some errors. If the application layer implements another retry mechanism, avoid stacking duplicates that cause too many requests.

For AI Agents that may trigger external operations, you also need to prevent retries from causing duplicate execution.

10 What are the limitations of OpenAI-compatible interfaces?

OpenAI-compatible interfaces can reduce basic integration costs, but developers still need to be aware of the following differences.

Model parameters are not fully consistent

Some models may not support temperature, top_p or specific generation control parameters.

Reasoning models may also use different reasoning modes and output limits.

Tool calling capabilities vary

Even if a model supports the Chat Completions interface, it does not necessarily mean that it supports Function Calling, structured output, or parallel tool calls.

Multimodal interfaces require separate adaptation

Image, video, speech, and 3D generation models may use different API paths, request parameters, and task query mechanisms.

Especially for time-consuming tasks such as video generation, you may need to submit an asynchronous task first and then query the generation result.

You cannot assume that all models can be called through the same Chat Completions method.

Model output quality needs to be revalidated

After switching models, the same prompt may produce different output content, format, and length.

Enterprises should validate the actual effect after model switching through business test sets, rather than only checking whether the interface returns successfully.

11 How to access multiple AI models through AGTCloud?

AGTCloud provides multi-model API services for developers and enterprises, covering model capabilities such as text, image, video, speech, and 3D.

For text models that support OpenAI-compatible interfaces, developers can refer to the SDK calling method in this article and configure the corresponding API Key, Base URL, and Model ID according to AGTCloud's current developer documentation.

For other models such as image and video models, you need to integrate them according to the API specifications of the corresponding models.

Developers are advised to first complete basic calls for a single model, and then gradually implement streaming output, usage monitoring, multi-model configuration, and exception handling.

Access AGTCloud:https://agtcloud.cn/

Frequently Asked Questions (FAQ)

Does an OpenAI-compatible API have to use an OpenAI API key?

No. Developers should use the API key provided by the actual model service platform and configure the corresponding base URL.

Can the OpenAI SDK be used to call DeepSeek and Tongyi Qianwen?

For model services that provide a corresponding OpenAI-compatible interface, the OpenAI SDK can be used to call them; specific support depends on the provider's documentation.

Does switching models only require changing the model name?

If the models are on the same service platform and use the same compatible interface, basic calls may only require changing the Model ID. However, the parameters, capabilities, and output quality of different models still need to be validated.

Do OpenAI-compatible APIs support streaming output?

Many compatible interfaces support streaming output, but specific event formats, reasoning content, and usage statistics capabilities may vary.

Do all AI models support OpenAI-compatible interfaces?

No. Some text models provide compatible interfaces, while image, video, audio, and other models may require separate API specifications.

Summary

OpenAI-compatible APIs provide developers with a relatively standardized way to access large models, reducing duplicate development work and providing a foundation for multi-model switching.

In real projects, it is recommended to manage the endpoint URL, API key, and model name separately, while establishing unified exception handling, token usage tracking, and model testing mechanisms.

Truly reliable multi-model integration is not only about different models returning results successfully, but also about ensuring that business quality, call costs, and service stability after model switching meet expectations.


Docs ↗

Frequently asked questions

No. Developers should use the API Key provided by the actual model service platform and configure the corresponding Base URL.

Z

Zhou Jingxing

AI Industry Research

AGTCloud AI industry observation columnist, focusing on the global large model ecosystem, MaaS platform development, model commercialization, and enterprise AI infrastructure. Provides structured analysis and market observation around the model service market, API pricing, platform selection, and industry application trends.