← Back to research
Guides11 min readPublished 2026-07-20

Claude API in Python: OpenAI-Compatible Example with LumeAPI

Call Claude Sonnet from Python through LumeAPI. Stream responses, estimate token cost, handle errors, and understand OpenAI-compatibility limits in production.

By LumeAPI Engineering Team

Claude API hub → Explore Lower-Cost Claude Access →

Last verified: July 20, 2026

A Python application can call Claude Sonnet through LumeAPI with the same OpenAI client used for other compatible text models. Configure https://api.lumeapi.site/v1, provide one LumeAPI key, and select claude-sonnet-4-6. This is useful when an application wants Claude without maintaining a separate provider client, billing account, and request-log pipeline.

The gateway exposes an OpenAI-compatible Chat Completions shape. Claude's native Anthropic API remains a different interface, so compatibility should be treated as a tested integration surface rather than a claim that both native APIs are identical.

Choose Sonnet or Opus

The LumeAPI catalog listed the following Claude text models on July 20, 2026. Prices are per 1 million input/output tokens.

Model IDLumeAPI input / outputPage reference input / outputDifference shownUse when
claude-sonnet-4-6$1.80 / $9.00$3.00 / $15.0040% lowerDay-to-day chat, writing, coding, and agents
claude-opus-4-8$3.00 / $15.00$5.00 / $25.0040% lowerHarder analysis and instructions where quality outweighs cost
claude-opus-4-7$3.00 / $15.00$5.00 / $25.0040% lowerExisting evaluations or prompts tied to that version

Start with Sonnet unless an evaluation proves that Opus materially improves the completed task. The phrase 'up to 70% lower' applies to supported models elsewhere in the LumeAPI catalog; the Claude models in this table show 40% lower than their displayed reference rates.

Install the client and store the key

Install the OpenAI Python library because this tutorial uses LumeAPI's compatible endpoint:

bash
python -m pip install --upgrade openai

Set the key outside code:

bash
export LUMEAPI_KEY='your-lumeapi-key'

PowerShell:

powershell
$env:LUMEAPI_KEY = 'your-lumeapi-key'

Do not use ANTHROPIC_API_KEY for this route. A key works only with the provider or gateway that issued it.

Send a Claude request from Python

Create claude_example.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': 'Answer as a careful senior Python reviewer.',
        },
        {
            'role': 'user',
            'content': 'List three risks in retrying a payment tool call.',
        },
    ],
)

print(response.choices[0].message.content)
print({
    'model': response.model,
    'input_tokens': response.usage.prompt_tokens if response.usage else None,
    'output_tokens': response.usage.completion_tokens if response.usage else None,
})

The generated text uses the familiar choices[0].message.content path. The exact model ID matters: use claude-sonnet-4-6, not a display label guessed from a provider announcement.

Native Claude versus the LumeAPI compatible route

The native Anthropic Python SDK uses Anthropic() and client.messages.create(). The LumeAPI path in this guide uses OpenAI() and client.chat.completions.create().

ConcernNative Anthropic APILumeAPI route in this guide
ClientAnthropic SDKOpenAI SDK
Base URL and keyAnthropic account configurationLumeAPI base URL and LumeAPI key
MethodMessages APIChat Completions
Model IDNative provider identifierExact ID in the LumeAPI catalog
BillingProvider accountShared LumeAPI USD wallet
Operational reviewProvider controlsLumeAPI per-call model, token, cost, and latency logs
Advanced featuresNative provider contractOnly features documented and tested on the compatible route

Use the native provider SDK if an application depends on a provider-native feature that the gateway does not document. Use the compatible route when one client, one key, consolidated billing, and easier model switching are more valuable.

Stream Claude output

python
import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model=os.getenv('LUMEAPI_MODEL', 'claude-sonnet-4-6'),
    messages=[
        {'role': 'user', 'content': 'Write a six-step deployment checklist.'}
    ],
    stream=True,
)

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

print()

Test streaming in the actual web framework. A successful command-line iterator does not prove that proxies, serverless timeouts, browser disconnects, or your SSE parser behave correctly.

Estimate a Sonnet request

Suppose a request uses 2,000 input tokens and 600 output tokens. With the Sonnet rates above:

text
2,000 / 1,000,000 × $1.80 = $0.0036
  600 / 1,000,000 × $9.00 = $0.0054
total                            $0.0090

At the reference rates displayed on the same LumeAPI page, the same token counts total $0.0150. The calculated difference is 40%. The actual cost depends on measured usage, retries, caching behavior if supported, and the model selected for each call.

python
def claude_cost(input_tokens: int, output_tokens: int) -> float:
    return (
        input_tokens / 1_000_000 * 1.80
        + output_tokens / 1_000_000 * 9.00
    )

print(f'${claude_cost(2000, 600):.4f}')

After running real traffic, use the LumeAPI wallet and call logs to review billed cost and latency instead of treating this estimate as an invoice.

Switch from Claude to another model without a second client

Centralize model IDs so application code does not recreate clients:

python
import os
from openai import OpenAI

MODELS = {
    'claude': 'claude-sonnet-4-6',
    'gpt': 'gpt-5.4-mini',
    'gemini': 'gemini-3.5-flash',
}

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

def ask(question: str, family: str = 'claude') -> str:
    response = client.chat.completions.create(
        model=MODELS[family],
        messages=[{'role': 'user', 'content': question}],
    )
    return response.choices[0].message.content or ''

This demonstrates application-controlled model switching. It does not claim that every model interprets prompts, tools, schemas, or sampling parameters identically. Run regression tests whenever the selected model changes.

Add bounded error handling

python
import os
import openai
from openai import OpenAI

client = OpenAI(
    api_key=os.environ['LUMEAPI_KEY'],
    base_url='https://api.lumeapi.site/v1',
    timeout=45.0,
    max_retries=2,
)

def ask_claude(question: str) -> str:
    try:
        response = client.chat.completions.create(
            model='claude-sonnet-4-6',
            messages=[{'role': 'user', 'content': question}],
        )
        return response.choices[0].message.content or ''
    except openai.AuthenticationError as exc:
        raise RuntimeError('Check LUMEAPI_KEY and the LumeAPI base URL.') from exc
    except openai.RateLimitError as exc:
        raise RuntimeError('Rate limited; use bounded backoff or queueing.') from exc
    except openai.APITimeoutError as exc:
        raise RuntimeError('Claude did not complete before the timeout.') from exc
    except openai.APIStatusError as exc:
        raise RuntimeError(
            f'HTTP {exc.status_code}; request_id={exc.request_id}'
        ) from exc

Never retry a failed tool action blindly. If Claude can trigger emails, writes, orders, or payments, make the application action idempotent before enabling retries.

Common Claude Python problems

401 authentication failure

Confirm that the request uses a LumeAPI key with the LumeAPI hostname. A native Anthropic key is not interchangeable. Check the process environment without printing the credential.

Model not found

Copy the exact ID from the Claude Sonnet 4.6 docs. Also confirm that the base URL ends in /v1.

Tool calls behave differently after a model switch

Revalidate tool selection, argument schemas, parallel calls, loop termination, and side-effect protection. OpenAI compatibility describes the request surface, not identical model behavior.

The response style changed

Model changes require prompt and output regression tests. Validate structured application data with a schema instead of assuming prose will retain the same format.

Why this Claude setup fits a multi-model product

LumeAPI lets a backend use one compatible client, API key, and USD wallet for available Claude, GPT, and Gemini text models. The same account also includes listed image and video models, with modality-specific request parameters and asynchronous flows where documented. Per-call logs make it possible to review which model ran, how many tokens were used, what it cost, and how long it took.

That consolidation is valuable only if the application remains explicit about model choice and compatibility. Keep a model allowlist, test fallback behavior before production, and document which provider-native features are outside the shared interface.

Production checklist

  • Keep the LumeAPI key server-side.
  • Copy current Claude model IDs from the catalog.
  • Test prompts, streaming, tools, schemas, errors, latency, and cost.
  • Log selected model and request outcome.
  • Compare cost per successful task, not only token rate.
  • Keep model selection in configuration for quick rollback.
  • Use the Claude API hub, lower-cost Claude page, and OpenAI-compatible API as current product references.

Sources and verification

The code blocks were parsed with Python on July 20, 2026. No customer inference key was used for a billable output, so quality and latency are not claimed.