EN ▾
Get API key

Gemini API Example Code Ported to an OpenAI-Style API

This gemini api example is converted line by line to an OpenAI-style API: prompts, chat history, streaming, JSON and tool calls, with Python and Node code you can paste.

Updated

Two glass bridges carrying code blocks with an adapter plate between them, picturing code ported between APIs
A brass key above connected sockets, illustrating one API key plugged into several tools

Key points

  1. Roles change from model to assistant, and parts become content.
  2. Keys and endpoint move into the client constructor; the model ID is uncensored.
  3. JSON mode and tools map to response_format and tools.
  4. Images, audio and embeddings do not port; this API is text only.

The mapping at a glance

A typical gemini api example in Python uses a model object, a generate_content call and a .text property. Porting it to an OpenAI-style API means swapping those for a client, a chat.completions.create call and choices[0].message.content. The ideas stay the same; only the names change.

ConceptGemini SDK styleOpenAI style (this API)
Auth and endpointAPI key configured in the SDKbase_url plus bearer key
ModelA Gemini model nameuncensored
System promptsystem_instructionmessage with role system
Assistant role in historymodelassistant
Message textpartscontent
Max lengthmax_output_tokensmax_tokens (optional)
JSON outputresponse_mime_typeresponse_format json_object
Streamstream=True on generate_contentstream=True on create

Method names vary between versions of Google's libraries, so check their current docs for the exact call you are porting. The OpenAI side is stable and works with any OpenAI client. This site is not affiliated with Google: it serves an independent open-weight model under the ID uncensored, so outputs will differ in style from Gemini's.

Example 1: a single prompt

Before, in a typical Gemini call:

import google.generativeai as genai

genai.configure(api_key="GEMINI_KEY")
model = genai.GenerativeModel("gemini-model-name")
resp = model.generate_content(
    "Write a two-sentence product blurb for a hiking backpack.",
    generation_config={"temperature": 0.7, "max_output_tokens": 200},
)
print(resp.text)

After, against this API:

from openai import OpenAI

client = OpenAI(base_url="https://api.geminiuncensored.top/v1", api_key="YOUR_KEY")
resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a two-sentence product blurb for a hiking backpack."}],
    temperature=0.7,
    max_tokens=200,
)
print(resp.choices[0].message.content)

Notice what moved. The key and the endpoint now live in the client constructor. The generation settings are top-level arguments instead of a config dictionary. And the prompt is a list of messages rather than a string. The key integration guide shows where to store the key safely.

Example 2: system prompt and chat history

Gemini history uses the role model for earlier answers and wraps text in parts. In the OpenAI format the role is assistant and the text sits in content. A small helper converts stored history:

def to_openai(history):
    # history: list of dicts with role user or model, and parts as a list of text
    out = []
    for turn in history:
        role = "assistant" if turn["role"] == "model" else turn["role"]
        out.append({"role": role, "content": "".join(turn["parts"])})
    return out

history = [
    {"role": "user", "parts": ["My name is Dana."]},
    {"role": "model", "parts": ["Nice to meet you, Dana."]},
]

messages = [{"role": "system", "content": "You are a friendly assistant."}]
messages += to_openai(history)
messages.append({"role": "user", "content": "What is my name?"})

resp = client.chat.completions.create(model="uncensored", messages=messages)
print(resp.choices[0].message.content)

The system prompt moves from a constructor argument to the first message. Both APIs are stateless in practice: you resend the history on each call, so input tokens grow with the conversation. The context window is 100,000 tokens, prompt and completion together.

Example 3: streaming

In Gemini you iterate chunks and read chunk.text. Here you read the delta from each chunk:

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Tell a very short story about a lighthouse."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

Streaming uses server-sent events. A streamed request occupies its concurrency slot until the stream finishes: full keys allow 8 concurrent requests, trial keys allow 2. If you break out of the loop early, close the stream.

Node.js

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.geminiuncensored.top/v1",
  apiKey: process.env.API_KEY,
});

const stream = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Name three birds." }],
  stream: true,
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

Example 4: JSON output and function calls

For JSON, Gemini uses a response MIME type. Here you use response_format. Describe the fields in the prompt, because JSON mode guarantees valid syntax and not your schema.

import json

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Return JSON with keys city and country for: Lisbon"}],
    response_format={"type": "json_object"},
    temperature=0,
)
print(json.loads(resp.choices[0].message.content))

Function calling maps to tools. Instead of function declarations you pass a list of objects with type: "function", set tool_choice if needed, and return results as messages with role: "tool" and the matching tool_call_id. Streamed tool calls arrive in pieces in delta.tool_calls.

tools = [{
    "type": "function",
    "function": {
        "name": "get_time",
        "description": "Get the current time in a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]
resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "What time is it in Tokyo?"}],
    tools=tools,
)
print(resp.choices[0].message.tool_calls)

What does not port

Some Gemini features have no equivalent here. This API is text only: there is no image or audio input, no image, audio or video generation, no embeddings and no fine-tuning. If your code sends images or files to Gemini, keep those calls where they are and port only the text paths. Grounding or built-in search tools are Gemini-side features that you would replace with your own tool functions.

Safety settings also do not carry over. The model here is tuned to answer without content refusals for lawful adult use, so there are no per-category thresholds to set. One hard limit remains: sexual content involving minors is never allowed. Read how to use a Gemini API alternative for deciding which traffic to move.

Errors, limits and the balance header

The OpenAI client raises typed exceptions. The two you will meet first are authentication errors from a wrong key, and HTTP 429. The 429 error code tells you the cause: rate_limited for requests per minute (300 on a full key, 60 on a trial key) and concurrency for too many requests at once. On temporary overload the API also returns 429 with Retry-After: 5.

import time
from openai import RateLimitError

def call(messages):
    for attempt in range(4):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError as e:
            time.sleep(float(e.response.headers.get("Retry-After", 2)))
    raise RuntimeError("still rate limited")

Every response includes X-Request-Id, X-Balance-USD and the rate limit headers. Read the balance header to know when to top up. The docs list all endpoints: POST /v1/chat/completions, POST /v1/responses and GET /v1/models.

Cost and payment

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit. The earlier backpack example, with about 20 input and 60 output tokens, costs 20 x $0.15 / 1M plus 60 x $0.50 / 1M, which is $0.000003 plus $0.00003, or $0.000033. Top up any whole amount from $20 to $500 with crypto (USDT on TRC20 or USDC on Base); bonuses are +5% from $50, +10% from $100 and +15% from $200. To test the port first, claim $0.50 of trial credit with one click on the API key page. Details are on the pricing page.

Questions and answers

Can I keep using Google's library with this API?

No. The endpoint speaks the OpenAI protocol, so use an OpenAI client with the base URL and your key.

Is the output the same as Gemini's?

No. It is a different open-weight model, so wording and style differ. Retest your prompts and adjust the system message.

Does streaming work the same way?

Streaming uses server-sent events with stream set to true. Read delta content from each chunk.

Can I send images?

No. The API is text only, so keep image calls on the service that supports them.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.