跳到正文
DEV Community· boluo·· 1 小時前AI 評分66

以 OpenAI SDK 呼叫 Gemini:可映射項目、相容性限制與成本

Calling Gemini From the OpenAI SDK: What Maps, What Breaks, and What It Costs

AI 導讀

作者梳理透過 OpenAI SDK 相容層呼叫 Gemini 時可沿用的請求格式、無法映射的功能,以及對推理成本和遷移工作的影響。一般聊天補全、串流和圖像輸入可直接映射,但 reasoning_effort 會因模型系列而異,Gemini 3 和 Gemini 4 不能關閉推理。

正文

The migration pitch is three lines: change the base_url, swap the key, rename the model. That claim is accurate for a single-turn chat completion, and it is the reason most teams start the migration on a Friday afternoon feeling confident.

Then Monday arrives. Someone asks why reasoning tokens tripled, the extraction endpoint returns a 400 it never returned before, and the caching layer that saved forty percent of input tokens turns out to have no equivalent at all. None of these are bugs. They are the parts of the request that the compatibility layer does not translate, and the documentation describes them as footnotes rather than as the boundary.

What maps cleanly

Plain chat completions, streaming, and image input are genuinely transparent. Same endpoint, same array, same response shape.

Field OpenAI Gemini via compat layer
Endpoint POST /v1/chat/completions POST /v1/chat/completions
Messages messages[] messages[]
Assistant role assistant assistant
System prompt role: "system" role: "system"
Streaming stream: true (SSE) stream: true (SSE)
Image input URL or base64 URL or base64

reasoning_effort is not a one-to-one mapping

The 2.5 family takes a token budget while 3 and 4 take discrete levels.

Field mapping between the two shapes

Rows 1 to 4 are structural: the field sits at a different depth, not just under a different name. I have a text summarisation service running on this configuration for six months without a single change to the request builder. If your workload looks like that, three lines really is the whole migration.

What does not map

The native Gemini API has a different shape, and the divergence starts at the top level of the request body rather than in some obscure corner.

Concept Native Gemini OpenAI-compatible
Message container contents[] messages[]
Message parts parts[] flat content
Model role name model assistant
System prompt separate systemInstruction field a message with role: "system"
Generation params generationConfig.{temperature, maxOutputTokens} top-level temperature, max_tokens
Reasoning depth generationConfig.thinkingConfig reasoning_effort
Cache cached_content cache_control

systemInstruction sits at the top level and is not an array element. generationConfig gathers parameters that OpenAI leaves at the root. That structural gap explains the whole pattern: the three-line swap holds while the request stays simple, and stops holding the moment you want the same control you had before.

Where the reasoning budget quietly moves

The compat layer maps reasoning_effort onto thinking_level, but the mapping differs by model family and is not reversible.

reasoning_effort Gemini 4 Gemini 3.1 Flash-Lite Gemini 3 Flash Gemini 2.5 (thinking_budget)
minimal low minimal minimal 1,024
low low low low 1,024
medium medium medium medium 8,192
high high high high 24,576

Two things cost me real time here.

Reasoning cannot be switched off. The 2.5 family accepts reasoning_effort: "none". Gemini 3 and Gemini 4 do not, and the reasoning runs regardless. A cost model built on the assumption that thinking was optional will be wrong, and the error surfaces as a line item rather than an exception. Mine showed up as a forty percent jump in the monthly bill, and it took two days to trace it back to this field.

Part of the surface is only reachable through extra_body. Content caching, safety thresholds, and Google Search grounding all travel in a nested object that has no OpenAI equivalent.

"extra_body": {
  "google": {
    "thinking_config": {
      "include_thoughts": true
    }
  }
}

Note that reasoning_effort and thinking_config overlap functionally. Send both and you get a validation error, not a merge.

Three places existing code breaks

Ordered by how much time each one cost me.

Tool calling combined with structured output. tools[] alongside response_format returns a 400 through the compat layer. Either alone works. I split one extraction call into two round trips, which roughly doubled latency on that endpoint and pushed it past my p95 target.

*Batch API file uploads. * The batch job itself runs through the OpenAI SDK, but uploading and downloading the JSONL files requires the native SDK. The layer does not cover that segment. You finish with two clients to maintain, which removes a good part of the reason for using a compatibility layer.

Prompt caching. cache_control from the Assistants API and cached_content in Gemini are separate mechanisms with different semantics. The caching that saved roughly forty percent of input tokens under OpenAI had to be rebuilt rather than ported.

One client, three providers

Most projects I touch need Gemini for long context, Claude for code generation, and DeepSeek for high volume batch work. Three SDKs, three key stores, three error formats, and one more thing to remember during an incident.

What holds up is collapsing everything onto one compatible interface and letting a gateway absorb the format differences. The gateway routes on the model field, normalizes request bodies across providers, and keeps credentials in one place.

I use CrazyRouter for this. Every model sits behind a single address.

https://api.crazyrouter.com/v1

Only the model value changes after that, so switching providers is a config edit rather than a code change.

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_CRAZYROUTER_KEY",
    base_url="https://api.crazyrouter.com/v1"
)

response = client.chat.completions.create(
    model="gemini-4-neon",
    messages=[
        {"role": "system", "content": "You are a terse technical assistant."},
        {"role": "user", "content": "List three differences between SSE and WebSocket."}
    ],
    extra_body={
        "google": {
            "thinking_config": {"thinking_level": "low"}
        }
    }
)

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

Pointing the same file at Claude is a one-word change to model, minus the extra_body block, which is Gemini specific.

Model IDs and the current catalogue are at the model list, and token counting rules plus rates are on the pricing page.

What this layer does not do is worth stating plainly. It does not extend model capability, so a field the native API rejects will not start working because it passed through a gateway. It does not erase behavioural differences, and the same reasoning_tokens get consumed either way. And it inserts a network hop, which matters when the latency budget is tight.

Reading errors by layer

Three failure layers

A 200 with an error object in the body is still a failure. Most incidents get diagnosed one layer too high. Through one gateway the error shapes are consistent, but the causes are not. Three layers, three investigations.

Layer Symptom What to check
Network no HTTP status, timeout DNS, TCP, TLS handshake
HTTP 4xx or 5xx status code and response headers
Application 200 with an error object in the body error field, finish_reason

The application layer is the one that gets skipped. A 200 does not mean success, since validation failures and quota overruns both arrive inside a response that looks healthy at the HTTP level. I once lost an afternoon to a call that reported success and returned an empty completion, because a config merge set max_tokens to 1.

When the alert fires and the first thing you check is the model name, you are debugging at the wrong layer. Start with whether a status code came back at all.

來源:DEV Community · dev.to