← Back to research
Guides12 min readPublished 2026-07-24

OpenAI Compatible API Python Claude Example: Switch Clients, Not SDKs (2026)

Use this openai compatible api python claude example to change one base URL, keep your Python client, and run Claude Sonnet 4.6 for half the reference rate.

By LumeAPI Engineering Team

OpenAI-Compatible API hub →

Last verified: July 24, 2026

Short path: Start with the OpenAI-compatible API guide, then see the LumeAPI-compatible endpoint and AI API pricing.

If your Python app already uses the OpenAI SDK, the simplest route to Claude is not a rewrite to a second client library. Change the base_url, replace the model ID, and keep calling Chat Completions. This openai compatible api python claude example uses claude-sonnet-4-6 through LumeAPI’s compatible endpoint.

Quick Answer

QuestionDirect answer
Can I call Claude from the Python OpenAI SDK?Yes. Point OpenAI() at https://api.lumeapi.site/v1, use a LumeAPI key, and request claude-sonnet-4-6.
What is the smallest working change?Replace your client construction with OpenAI(base_url="https://api.lumeapi.site/v1", api_key=os.environ["LUMEAPI_KEY"]), then change the model value.
What does Claude Sonnet cost through LumeAPI?claude-sonnet-4-6 is $1.50 per 1M input tokens and $7.50 per 1M output tokens, versus $3.00 and $15.00 reference pricing.
What is the main catch?OpenAI-compatible Chat Completions does not guarantee parity with every provider-native feature, API endpoint, cache control, or batch workflow. Verify those before migrating production-specific behavior.

In short

For a normal Chat Completions workload, keep your Python OpenAI client and swap the endpoint plus model ID. That is usually safer than maintaining parallel OpenAI and Anthropic SDK call paths for the same application flow.

The part that catches teams is not the first successful request. It is assuming that a compatible endpoint makes every provider-native option portable. Migrate the core chat path first, then test streaming, tools, structured output, and any provider-specific features against your own integration tests.

What most guides get wrong

The common advice is: “Claude needs the Anthropic SDK, so add a second client.” That is only true when you need Anthropic-native API surfaces or behavior that your current compatible endpoint does not expose.

For a Python service already built around OpenAI Chat Completions, a second SDK often creates more migration work than value. You now have two request builders, two exception hierarchies, two message formats to reason about, and two places where an engineer can accidentally send production traffic with the wrong credentials.

The better first move is narrower: retain the request shape your service already knows, change the OpenAI client’s base URL, use the exact Claude model ID, and validate the response on a real task. This does not turn Claude into “OpenAI under the hood.” It gives you one compatible call surface for the overlap: chat-completion requests. Treat anything outside that overlap as a separate compatibility test, not an assumption.

A realistic production scenario

Nina maintains a FastAPI service that turns support tickets into escalation summaries. The service already uses the Python OpenAI client, passes a system prompt plus ticket text, and returns a short response to an internal dashboard.

Her team’s first migration attempt added the Anthropic SDK beside the OpenAI SDK. By Friday, they had duplicate prompt-building code: one function emitted OpenAI-style messages; another rebuilt the same ticket context in a different request shape. A small prompt edit landed in one path but not the other. Their evaluation failures looked like model quality regressions, but the two models were not receiving identical input.

The simpler fix was to preserve the existing Chat Completions request, point the client to the compatible gateway, and change only the model ID. For a workload of 20 million input tokens and 4 million output tokens each month, claude-sonnet-4-6 costs $120 at the listed reference rate and $60 through LumeAPI. The savings mattered, but eliminating the duplicate request path saved more engineering time.

Expert take

An OpenAI-compatible gateway is most useful when your application has already standardized on the OpenAI SDK’s request and response shape. You get a controlled migration: one client constructor, one message representation, one place to set timeouts and observability, and a model string that can move between supported catalog models.

That makes model comparison less destructive. You can run the same prompt fixture against gpt-5.6-terra and claude-sonnet-4-6 without immediately rewriting your application architecture. For teams with a mature regression suite, that is the real advantage: model selection becomes an evaluation decision rather than a client-library project.

There is an important boundary. Do not use compatibility as a reason to abandon a provider-native integration you depend on. If your system requires a native batch API, provider-specific prompt caching controls, an endpoint outside Chat Completions, or a feature with semantics your tests rely on, consult the official provider documentation and test that path directly. A lower token rate does not compensate for a broken background job or changed tool-call behavior.

LumeAPI is an independent third-party gateway, not OpenAI, Anthropic, or Google. It provides an OpenAI-compatible Chat Completions endpoint; it should not be treated as a promise of identical behavior to every native provider API feature.

For SDK behavior and supported client configuration, check the official OpenAI Python library documentation. For Anthropic’s own guidance on OpenAI SDK compatibility, see the Anthropic OpenAI SDK compatibility documentation.

The working Python OpenAI SDK Claude example

Install the OpenAI Python library if it is not already in your environment:

bash
pip install openai

Set your LumeAPI key in the shell. Do not hard-code it in a source file or commit it to a repository.

bash
export LUMEAPI_KEY="your_lumeapi_key"

Create claude_via_openai_sdk.py:

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["LUMEAPI_KEY"],
    base_url="https://api.lumeapi.site/v1",
)

response = client.chat.completions.create(
    model="claude-sonnet-4-6",
    messages=[
        {
            "role": "system",
            "content": "You are a concise backend engineering assistant.",
        },
        {
            "role": "user",
            "content": "Explain why idempotency matters for webhook handlers in three bullets.",
        },
    ],
)

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

Run it:

bash
python claude_via_openai_sdk.py

The important lines are these:

python
base_url="https://api.lumeapi.site/v1"
model="claude-sonnet-4-6"

Your code still imports OpenAI because the SDK is the client library. The selected model is Claude because the request goes to the LumeAPI endpoint and names a Claude model in the LumeAPI catalog.

Why the base URL change matters

A Python OpenAI client has two separate decisions embedded in it:

  1. Which endpoint receives the request
  2. Which model ID the endpoint should run

Changing only the model ID while leaving the default endpoint in place is a common migration mistake. If your base_url still points at OpenAI’s default API, claude-sonnet-4-6 is not a valid request there.

Likewise, changing the base URL but retaining an OpenAI model ID does not test Claude. The endpoint and model must match:

What you want to testbase_urlmodel
Claude through LumeAPIhttps://api.lumeapi.site/v1claude-sonnet-4-6
GPT through LumeAPIhttps://api.lumeapi.site/v1gpt-5.6-terra
Your existing direct OpenAI pathYour existing OpenAI configurationYour existing OpenAI model ID

Keep that distinction visible in configuration. A good pattern is to set the endpoint and model through environment variables rather than scattering them across route handlers.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["LUMEAPI_KEY"],
    base_url=os.getenv("LLM_BASE_URL", "https://api.lumeapi.site/v1"),
)

model = os.getenv("LLM_MODEL", "claude-sonnet-4-6")

response = client.chat.completions.create(
    model=model,
    messages=[
        {"role": "user", "content": "Return one short status update for a deployment."},
    ],
)

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

That setup also makes evaluation runs straightforward: change LLM_MODEL between runs, preserve the prompt fixture, and compare outputs without editing application code.

OpenAI SDK Claude base URL migration checklist

Before you switch production traffic, use this checklist:

  • [ ] Confirm your client is created with base_url="https://api.lumeapi.site/v1".
  • [ ] Use LUMEAPI_KEY, not a provider key intended for another endpoint.
  • [ ] Use an exact catalog model ID such as claude-sonnet-4-6.
  • [ ] Run one known prompt locally and log the returned response.model.
  • [ ] Test your application’s longest ordinary prompt, not only “hello world.”
  • [ ] Test tool calls, streaming, JSON expectations, and retry handling if your app uses them.
  • [ ] Keep a small evaluation set so model changes are measured rather than decided from one impressive answer.
  • [ ] Check whether any job depends on a provider-native Batch, caching, or non-Chat-Completions endpoint before moving it.

Most failed migrations are configuration drift, not Python problems. A deployment environment still has OPENAI_API_KEY; a worker has an old base URL; a test uses one model while the queue worker uses another. Put endpoint, key name, and model selection in the same configuration module and print only non-secret configuration at startup.

A curl request for isolating SDK problems

When a Python request fails, first separate “gateway configuration” from “SDK integration.” This curl command uses the same endpoint, authorization scheme, model ID, and Chat Completions route.

bash
curl https://api.lumeapi.site/v1/chat/completions \
  -H "Authorization: Bearer $LUMEAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "messages": [
      {
        "role": "user",
        "content": "Reply with exactly: connection verified"
      }
    ]
  }'

If curl succeeds but the Python request fails, inspect your Python environment first:

  • Is LUMEAPI_KEY available to the process running Python?
  • Is a framework wrapper overwriting base_url?
  • Are you constructing a new default OpenAI() client elsewhere?
  • Is the worker process using a different environment file than your shell?

If both fail, verify the URL, key, and model ID before changing prompts or adding retries. Retrying a malformed request five times only creates five bad requests.

Cost math: Claude Sonnet versus GPT for a compatible client

The OpenAI SDK client does not dictate which model you must use. With the same compatible endpoint, you can compare Claude and GPT model IDs at the request level.

The following rates come from the LumeAPI catalog updated July 22, 2026. Reference pricing is shown as supplied in the catalog; use official provider pricing pages for current provider billing details and feature-specific pricing.

ModelReference input / 1M tokensReference output / 1M tokensLumeAPI input / 1M tokensLumeAPI output / 1M tokens
claude-sonnet-4-6$3.00$15.00$1.50$7.50
claude-opus-4-8$5.00$25.00$2.50$12.50
gpt-5.6-terra$2.50$15.00$0.75$4.50
gpt-5.6-sol$5.00$30.00$1.50$9.00

Here is a concrete monthly scenario: 20 million input tokens and 4 million output tokens.

Model and rate sourceInput calculationOutput calculationEstimated monthly total
claude-sonnet-4-6 reference rate20 × $3.00 = $604 × $15.00 = $60$120
claude-sonnet-4-6 via LumeAPI20 × $1.50 = $304 × $7.50 = $30$60
gpt-5.6-terra reference rate20 × $2.50 = $504 × $15.00 = $60$110
gpt-5.6-terra via LumeAPI20 × $0.75 = $154 × $4.50 = $18$33

The useful lesson is not “always choose the lowest row.” Output tokens dominate many assistant and agent workloads. A model that produces longer responses, retries more often, or receives full conversation history on every turn can erase a rate advantage quickly.

Track input and output tokens separately. If your bill rose after a model migration, inspect output growth and repeated context before blaming the price per million tokens.

For current model-specific rates, see the Claude Sonnet 4.6 model page and LumeAPI pricing.

Which model should a Python OpenAI client use?

Use the same request harness to decide, but do not choose based on a single prompt.

ScenarioRecommended starting pointWhy
Existing GPT-oriented application needs a low-friction cost checkgpt-5.6-terraIt preserves your existing model family while changing the gateway configuration.
You want to evaluate Claude without adopting another Python SDKclaude-sonnet-4-6It is available through the same compatible Chat Completions client pattern.
A task has repeatedly failed your quality checks with the selected modelEscalate to claude-opus-4-8 for that task onlyKeep the expensive model behind an evaluation failure or routing rule rather than making it the default.
A workflow relies on a provider-native featureUse the provider-native path after confirming requirementsCompatibility is not a substitute for an API feature you actually need.

A practical decision rule: start with claude-sonnet-4-6 for the workload you are evaluating. If it fails the same predefined evaluation twice for a task class, test claude-opus-4-8 only on that class. Do not route every classification, summary, and tool-repair hop to an expensive model because one complex task needed it.

How to migrate an existing direct OpenAI client

Suppose your current code looks like this:

python
from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-5.6-terra",
    messages=[
        {"role": "user", "content": "Summarize this incident report."}
    ],
)

For Claude through LumeAPI, the minimum code change is:

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["LUMEAPI_KEY"],
    base_url="https://api.lumeapi.site/v1",
)

response = client.chat.completions.create(
    model="claude-sonnet-4-6",
    messages=[
        {"role": "user", "content": "Summarize this incident report."}
    ],
)

Do not casually change the prompt, temperature controls, tool schema, response parser, and model in the same pull request. If output quality changes, you need to know whether the cause was model behavior, a modified prompt, or a parser assumption.

A safer sequence is:

  1. Preserve your existing messages exactly.
  2. Change endpoint and credentials.
  3. Change the model ID.
  4. Run saved production-like fixtures.
  5. Compare output validity, tool-call parsing, token use, and task success.
  6. Only then tune the prompt for the new model.

You can find a basic compatible-client walkthrough in Python OpenAI-compatible API examples and a focused migration discussion in using Claude with the OpenAI SDK.

Common failure modes

The request still goes to the old provider endpoint

This usually happens because an application has more than one client constructor. A local test uses the new base_url, but a background worker imports a shared module that still calls OpenAI() with defaults.

Fix it by creating one client factory. Pass that client into services rather than constructing SDK clients inside route handlers, queue jobs, or tools.

The model ID is close, but not exact

Model IDs are identifiers, not friendly names. Use claude-sonnet-4-6, not a guessed string such as claude-sonnet, sonnet-4.6, or claude-4-6-sonnet.

Exact IDs prevent an avoidable class of deployment-only failures.

The app assumes every response has identical semantics

Your code may be more coupled to one provider than it appears. Typical examples include strict assumptions about tool-call fields, JSON formatting, finish reasons, or streamed chunk handling.

The fix is not a blanket parser rewrite. Add fixtures for the response details your application actually consumes, then test those fixtures with the target model and endpoint.

Retry logic turns a temporary error into duplicate work

A retry policy should distinguish between a request that was rejected before processing and a request where your application cannot determine whether work completed. For side-effecting agent tasks, attach your own idempotency key to the job record and persist the result before retrying downstream actions.

Do not let a seventh retry repeat the same expensive tool-planning prompt because a worker lost its local state.

FAQ

Can I use this openai compatible api python claude example with my existing OpenAI client?

Yes. Create the OpenAI Python client with the LumeAPI base URL and LumeAPI key, then set model="claude-sonnet-4-6" in your Chat Completions request.

Your existing message-building code can remain if it already uses a standard Chat Completions shape. Test any application-specific parsing and tool workflows before moving production traffic.

What is the correct OpenAI SDK Claude base URL?

The base URL is https://api.lumeapi.site/v1.

Use it when constructing the Python OpenAI client. The Chat Completions path is then handled by the SDK from that base URL.

Can I call Claude with the OpenAI Python SDK without the Anthropic SDK?

Yes, for supported OpenAI-compatible Chat Completions requests through LumeAPI.

You may still need a provider-native integration if your workflow depends on Anthropic-specific API features that are outside the compatible Chat Completions surface.

Which Claude model ID should I use in the Python OpenAI client?

Use claude-sonnet-4-6 for the standard Claude Sonnet option listed in the LumeAPI catalog.

For a more expensive Claude option, the catalog also lists claude-opus-4-8 and claude-opus-4-7. Evaluate them on your workload rather than defaulting to a higher-cost model.

Does changing the model ID alone send my request to Claude?

No. The model ID alone is not enough if your client still points to its default provider endpoint.

Set both the LumeAPI base_url and the Claude model ID. Treat them as one configuration change.

Is LumeAPI cheaper than the reference Claude Sonnet rate?

For the catalog rates verified July 22, 2026, claude-sonnet-4-6 is listed at $1.50 per 1M input tokens and $7.50 per 1M output tokens through LumeAPI, versus $3.00 and $15.00 reference pricing.

Your total bill still depends on prompt size, output length, retries, and how often your application resends conversation context.

Next steps

  1. Copy the Python example, set LUMEAPI_KEY, and send one known test prompt to claude-sonnet-4-6.
  2. Run your saved prompts against both claude-sonnet-4-6 and gpt-5.6-terra; compare task success and input/output token use separately.
  3. Move the endpoint and model into shared configuration, then review the OpenAI-compatible API setup before routing production traffic.