TL;DR
Gemini 4 Hydrogen API is available through Googleโs Gemini API and supported third-party gateways such as CometAPI. Choose the route first: use Google for provider-specific features and account controls, or use CometAPI when you want a unified model gateway or an OpenAI-compatible client. Start with a small text request, then add streaming, conversation history, files, and tools.
You need Python 3.10 or later, a key for the selected route, and access to gemini-4-hydrogen. The optional JavaScript example uses Node.js 22 or later. Keep credentials in the server environment throughout the tutorial.
Key Takeaways
- Use
gemini-4-hydrogenas the model ID for the Gemini 4 Hydrogen API. - Google and CometAPI have separate credentials and billing. Match the key to the endpoint you select.
- Start with native GenerateContent; use CometAPIโs OpenAI-compatible interface when it fits an existing chat client.
- Keep the complete model response in multi-turn history, including signatures, before returning a follow-up or tool result.
- Compare actual token usage and completed tasks when choosing a route; the standard token-price example appears in the pricing section.
What Is the Gemini 4 Hydrogen API?
Google introduced Hydrogen on November 12, 2026. The API accepts prompts and supported files, then returns generated text or structured function calls for your application to handle. You do not need to host the model yourself.
Start with a text-only request and verify the returned text, finish reason, and token usage before adding tools or files. Once this works, add conversation state or a read-only business tool instead of building the entire workflow at once.
Gemini 4 Hydrogen API specifications
| Specification | Google-documented model capability |
|---|---|
| Model ID | gemini-4-hydrogen |
| Input | Text, images, audio, video, and supported documents |
| Output | Text, with structured function-call parts when tools are used |
| Unified context budget | 1,048,576 tokens across input and output |
| Single foreground output segment | Up to 65,536 tokens, including reasoning and function calls |
| Application features | Thinking-level control, structured output, and function calling |
These are model capabilities, not a guarantee that every gateway exposes every provider feature. The examples below use standard request fields and short foreground generations.
Google Official API vs CometAPI
Both routes support Gemini requests, but they use different endpoints, credentials, and billing systems. Use Google for provider-specific features; use CometAPI for a unified gateway or an existing compatible client.
| Decision | Google Gemini Developer API | CometAPI Gemini integration |
|---|---|---|
| Native API host | generativelanguage.googleapis.com | api.cometapi.com |
| API key in this guide | GEMINI_API_KEY | COMETAPI_KEY |
| Account and billing | Managed through Google | Managed through CometAPI |
| Best starting point | Google-specific features and account controls | Unified model access or an existing OpenAI-compatible client |
Keep the same prompt and output budget when checking the two routes so the results are useful to compare. The JavaScript and OpenAI-compatible alternatives remain explicitly configured for CometAPI.
How to Use Gemini 4 Hydrogen API Step by Step?
Step 1: Create an API key
For CometAPI, create an account and generate a key in the API token console. For direct Google access, create a Gemini API key in Google AI Studio. Confirm model access and the selected accountโs billing or available quota.
Store the key securely. A CometAPI key cannot authenticate a request to Googleโs endpoint, and a Google key cannot authenticate a CometAPI request.
Set the key for your chosen route in Bash; you only need one of these assignments.
export COMETAPI_KEY="YOUR_COMETAPI_KEY"
# Or, for direct Google access:
export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"
Set the corresponding key in PowerShell on Windows.
$env:COMETAPI_KEY = "YOUR_COMETAPI_KEY"
# Or, for direct Google access:
$env:GEMINI_API_KEY = "YOUR_GEMINI_API_KEY"
Step 2: Send a first request with cURL
Send a native text request through CometAPI from a Bash terminal.
curl "https://api.cometapi.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $COMETAPI_KEY" \
-H "Content-Type: application/json" \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "Explain how an AI coding agent works in five steps."
}
]
}
],
"generationConfig": {
"maxOutputTokens": 4096,
"thinkingConfig": {
"thinkingLevel": "MEDIUM"
}
}
}'
Alternatively, send the same native request directly to Google with a Google API key.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "Explain how an AI coding agent works in five steps."
}
]
}
],
"generationConfig": {
"maxOutputTokens": 4096,
"thinkingConfig": {
"thinkingLevel": "MEDIUM"
}
}
}'
After the request succeeds, verify three fields: candidates[0].content.parts for visible text, finishReason for completion status, and usageMetadata for token usage. Fix authentication or request errors before adding more application code.
Step 3: Configure the Python Client and Send a Request
Install the packages used by the Python examples.
python -m pip install requests openai
Save this helper as hydrogen_client.py. Leave PROVIDER set to cometapi for CometAPI, or set it to google for direct Gemini Developer API access. Later native examples import this file, so they keep the selected route.
Configure the selected endpoint and define reusable request and text helpers.
import os
import requests
MODEL = "gemini-4-hydrogen"
PROVIDER = "cometapi" # Change to "google" for direct access.
ROUTES = {
"cometapi": ("https://api.cometapi.com", "COMETAPI_KEY"),
"google": ("https://generativelanguage.googleapis.com", "GEMINI_API_KEY"),
}
BASE_URL, KEY_NAME = ROUTES[PROVIDER]
API_KEY = os.environ[KEY_NAME]
URL = f"{BASE_URL}/v1beta/models/{MODEL}:generateContent"
def generate(payload):
response = requests.post(
URL,
headers={"x-goog-api-key": API_KEY},
json=payload,
timeout=120,
)
response.raise_for_status()
return response.json()
def visible_text(data):
candidates = data.get("candidates") or []
if not candidates:
raise ValueError("No candidate returned; inspect promptFeedback.")
candidate = candidates[0]
parts = candidate.get("content", {}).get("parts", [])
text = "".join(
part.get("text", "") for part in parts
if not part.get("thought", False)
)
if not text:
raise ValueError(
f"No visible text; inspect parts and finishReason: "
f"{candidate.get('finishReason')}"
)
return text
Save the following as hydrogen.py beside the helper. It prints the answer, completion reason, and usage so you can distinguish a completed answer from an output that stopped at a token limit.
Send a text request using the configured provider.
from hydrogen_client import generate, visible_text
data = generate({
"contents": [{"role": "user", "parts": [{
"text": "Explain API rate limiting in three sentences."
}]}],
"generationConfig": {
"maxOutputTokens": 4096,
"thinkingConfig": {"thinkingLevel": "MEDIUM"},
},
})
print(visible_text(data))
candidate = data["candidates"][0]
print("Finish reason:", candidate.get("finishReason"))
print("Usage:", data.get("usageMetadata", {}))
Run the script in the terminal where you set the selected API key.
python hydrogen.py
Read the answer, then check finishReason to see why generation stopped. In usageMetadata, check how many tokens the request used. MAX_TOKENS means the response may be incomplete, even when the HTTP request succeeds.
Use JavaScript or an OpenAI-Compatible Client
Choose the example that fits your application. The Node.js example sends a native Gemini request. If you already use the OpenAI SDK, skip to the Python example below.
JavaScript with Node.js
Save the following as hydrogen.js and run node hydrogen.js. It sends the same native request shape and extracts all visible text parts.
Send a native GenerateContent request from Node.js.
const apiKey = process.env.COMETAPI_KEY;
if (!apiKey) throw new Error("Set COMETAPI_KEY before running this script.");
const baseUrl = "https://api.cometapi.com";
const model = "gemini-4-hydrogen";
async function main() {
const response = await fetch(
`${baseUrl}/v1beta/models/${model}:generateContent`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"x-goog-api-key": apiKey
},
body: JSON.stringify({
contents: [
{
role: "user",
parts: [
{
text: "Explain how an AI coding agent works."
}
]
}
],
generationConfig: {
maxOutputTokens: 4096,
thinkingConfig: {
thinkingLevel: "MEDIUM"
}
}
})
}
);
if (!response.ok) {
throw new Error(
`API error: ${response.status} ${await response.text()}`
);
}
const data = await response.json();
const candidate = data.candidates?.[0];
const text = (candidate?.content?.parts || [])
.filter(part => !part.thought)
.map(part => part.text || "")
.join("");
if (!text) {
throw new Error(`No visible text; finishReason=${candidate?.finishReason}`);
}
console.log(text);
}
main().catch(console.error);
Python with the OpenAI SDK
If your application already uses the OpenAI SDK, CometAPI also exposes POST /v1/chat/completions. The simplest migration is to change the API key, base URL, and model ID. Use this route for common chat workflows; use the Gemini-native endpoint when you need provider-specific Gemini fields.
Create a Chat Completions request through CometAPI.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["COMETAPI_KEY"],
base_url="https://api.cometapi.com/v1"
)
response = client.chat.completions.create(
model="gemini-4-hydrogen",
messages=[
{
"role": "user",
"content": "Explain how an AI coding agent works."
}
]
)
print(response.choices[0].message.content)
The native examples use contents and generationConfig; Chat Completions uses messages and its own request fields. Keep each request in one format instead of copying native fields into an SDK call that does not accept them.
Advanced Gemini 4 Hydrogen API Features
The following examples reuse hydrogen_client.py from the setup section, so they work with the provider selected in PROVIDER. The streaming example below uses the separate CometAPI Chat Completions client, which fits an existing OpenAI-compatible application.
Configure reasoning and structured output
Use generationConfig to set thinkingConfig.thinkingLevel to LOW, MEDIUM, HIGH, or XHIGH. Choose an output budget that leaves room for both reasoning and the visible answer. When the application expects JSON, use responseMimeType and responseSchema rather than relying on a natural-language formatting request alone.
Set the output budget and reasoning level for a native request.
{
"generationConfig": {
"maxOutputTokens": 4096,
"thinkingConfig": {"thinkingLevel": "MEDIUM"}
}
}
Stream responses through CometAPI
Streaming returns generated content incrementally instead of waiting for the complete answer. It is useful for chat interfaces, coding assistants, and applications where perceived latency matters.
CometAPI documents streaming Chat Completions with stream=true. The Python example handles chunks without choices, which can occur in streaming responses.
Print text as it arrives through the OpenAI-compatible endpoint.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["COMETAPI_KEY"],
base_url="https://api.cometapi.com/v1"
)
stream = client.chat.completions.create(
model="gemini-4-hydrogen",
messages=[
{
"role": "user",
"content": (
"Write a Python function that validates an email "
"address and explain the main checks."
)
}
],
stream=True
)
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
if delta and delta.content:
print(delta.content, end="", flush=True)
print()
For a native client, CometAPI documents streamGenerateContent with Server-Sent Events. That route returns GenerateContent response objects rather than Chat Completions deltas. Keep the parser matched to the route; streaming behavior can vary between the native Gemini endpoint and an OpenAI-compatible gateway. Test the exact Hydrogen route used by your application before migrating an existing streaming client.
Preserve multi-turn conversation history
Send the previous user and model turns with the next request. Keep the modelโs complete content object instead of rebuilding it from visible text; this preserves returned metadata for the next turn. Save the example as hydrogen_history.py beside the shared helper.
Make two related requests while preserving the full first model response.
from hydrogen_client import generate, visible_text
history = [{"role": "user", "parts": [{
"text": "Suggest a simple queue-based background job architecture."
}]}]
config = {
"maxOutputTokens": 4096,
"thinkingConfig": {"thinkingLevel": "MEDIUM"},
}
first = generate({"contents": history, "generationConfig": config})
print(visible_text(first))
candidate = first["candidates"][0]
if candidate.get("finishReason") != "STOP":
raise RuntimeError("The first turn did not finish normally.")
history.append(candidate["content"])
history.append({"role": "user", "parts": [{
"text": "Now identify three failure scenarios in that design."
}]})
second = generate({"contents": history, "generationConfig": config})
print(visible_text(second))
print("Finish reason:", second["candidates"][0].get("finishReason"))
Run python hydrogen_history.py. The second answer should address the design from the first turn. Keep the earlier conversation prefix unchanged in this example; long-running applications need a separate policy for compaction and context limits.
Send images and PDFs
Hydrogen supports image and document understanding. In the Gemini-native request format, add an inlineData part alongside the text instruction. This is useful for screenshot analysis, architecture diagrams, scanned forms, and report extraction.
Save this example as analyze_file.py beside hydrogen_client.py. It sends one local image or PDF, so you can reuse the same code for both inputs. Use a small file for the first request; Base64 increases the request size.
Analyze a local PNG, JPEG, or PDF using the shared native client.
import base64
import sys
from pathlib import Path
from hydrogen_client import generate, visible_text
path = Path(sys.argv[1])
mime_types = {
".png": "image/png", ".jpg": "image/jpeg",
".jpeg": "image/jpeg", ".pdf": "application/pdf",
}
mime_type = mime_types.get(path.suffix.lower())
if mime_type is None:
raise ValueError("Choose a PNG, JPEG, or PDF file.")
data = generate({
"contents": [{"role": "user", "parts": [
{"text": "Summarize this file and identify the key findings."},
{"inlineData": {
"mimeType": mime_type,
"data": base64.b64encode(path.read_bytes()).decode("ascii"),
}},
]}],
"generationConfig": {"maxOutputTokens": 4096},
})
print(visible_text(data))
Run the file example with your own document or image.
python analyze_file.py report.pdf
python analyze_file.py diagram.png
The file bytes must match the declared MIME type. A renamed file extension does not convert the file. If an upload is rejected, inspect the error for a size or format limit before trying again; do not assume that a Google-hosted file URI is accessible through a third-party gateway.
Connect application-controlled tools
Function calling lets the model request an operation that your application performs. The model returns a structured function call; your application validates the arguments, executes the function, and sends the result back.
This example uses a small, fictional order database. Save it as order_agent.py beside the shared client. It implements the round trip, caps the loop at four requests, and preserves the full model contentโincluding any returned signaturesโbetween turns.
Run a bounded function-calling loop against a local demonstration database.
from hydrogen_client import generate, visible_text
orders = {"DEMO-1001": {"status": "shipped", "carrier": "Example Carrier"}}
tools = [{"functionDeclarations": [{
"name": "lookup_order",
"description": "Retrieve a demonstration order by its order ID.",
"parameters": {
"type": "OBJECT",
"properties": {"order_id": {"type": "STRING"}},
"required": ["order_id"],
},
}]}]
history = [{"role": "user", "parts": [{
"text": "Use lookup_order to check the status of DEMO-1001."
}]}]
for _ in range(4):
data = generate({
"contents": history,
"tools": tools,
"generationConfig": {"maxOutputTokens": 4096},
})
candidates = data.get("candidates") or []
if not candidates or not candidates[0].get("content"):
raise RuntimeError("No model content returned.")
model_content = candidates[0]["content"]
calls = [
part["functionCall"] for part in model_content.get("parts", [])
if "functionCall" in part
]
if not calls:
print(visible_text(data))
break
history.append(model_content) # Preserve all parts and signatures.
results = []
for call in calls:
args = call.get("args", {})
order_id = args.get("order_id") if isinstance(args, dict) else None
if call.get("name") != "lookup_order":
raise ValueError("Unexpected function name.")
if not isinstance(order_id, str) or not order_id:
raise ValueError("order_id must be a non-empty string.")
result = orders.get(order_id, {"error": "Order not found"})
reply = {"name": call["name"], "response": result}
if "id" in call:
reply["id"] = call["id"]
results.append({"functionResponse": reply})
history.append({"role": "user", "parts": results})
else:
raise RuntimeError("Tool-call limit reached before a final answer.")
Run python order_agent.py. The final answer should reflect the local record for DEMO-1001. In a real service, authorize the user before accessing an order; the modelโs choice of an order ID is not proof of permission.
How Much Does Gemini 4 Hydrogen API Cost?
The rates below are USD per million tokens, checked on November 17, 2026. They compare standard uncached input and output, not batch, priority, cached-input, or separately billed tool usage.
| Token type | Google Global Standard | Gemini 4 Hydrogen API in CometAPI |
|---|---|---|
| Input tokens / 1M | $1.50 | $1.20 |
| Output tokens / 1M | $7.50 | $6.00 |
For 100,000 input tokens and 10,000 billable output tokens, the CometAPI estimate is 0.1 ร $1.20 + 0.01 ร $6.00 = $0.18. The same volumes at Googleโs listed standard rates cost $0.225, a 20% difference. Include reasoning tokens in output usage and check your accountโs billed usage when estimating a real workflow.
How Do You Migrate to Gemini 4 Hydrogen API?
What Changes When Migrating from Gemini 3.8 Flash?
Before you change the model ID, check the reasoning setting, the context budget, and the conversation history your client sends with each request.
| Integration detail | Gemini 3.8 Flash | Gemini 4 Hydrogen |
|---|---|---|
| Default thinking level | MEDIUM | HIGH |
| Context accounting | Separate input and output limits | One shared input/output budget |
| Multi-turn state | Review the existing clientโs history handling | Preserve complete model parts and signatures; prefix edits require special handling |
The documented migration changes matter most when your application relies on defaults, compacts history, or runs several tool turns. Set reasoning explicitly and test a short existing workflow before changing the production model.
Update an existing integration
Create a test configuration with the new model ID while keeping its key and endpoint together. Run the same representative workflow with both configurations so you can compare their behavior.
- Send a fresh text request and verify its completion reason and token usage.
- Replay a multi-turn task and a tool round trip using complete model response objects.
- Remove incompatible controls listed in the limitations section before comparing request outcomes.
- Exercise your rollback path in a fresh conversation; do not assume another model accepts Hydrogenโs saved reasoning metadata.
Decide whether the migration helps your workload
Adopt the new configuration when it meets the taskโs quality and latency targets at an acceptable cost per completed task. If the current client already meets those targets, use a limited pilot to establish a benefit before moving every request. Keep the prompts, inputs, and scoring criteria consistent during the evaluation.
Gemini 4 Hydrogen API Limitations
The Hydrogen developer guide describes restrictions that affect existing clients. Address them in request construction rather than retrying the same rejected payload.
- Unsupported fields: remove thinkingBudget, thinkingLevel set to MINIMAL, frequencyPenalty, presencePenalty, and candidateCount greater than one.
- Ignored sampling settings: custom temperature, topP, and topK do not control Hydrogen output.
- Caching: explicit cachedContent is unsupported. Stable prompt prefixes can use implicit caching, but that does not establish a gateway-specific cache discount.
- Long output: the sample client in this guide only implements a synchronous request. It does not cover background long decode or provider-specific continuation workflows.
- Conversation changes: modifying earlier prompts or tool definitions can invalidate the reasoning state. Preserve the prefix, or implement the documented prefix-mismatch behavior for the selected route.
Common setup checks
| Symptom | First check |
|---|---|
| 401 or 403 | Confirm that the credential belongs to the endpoint and has access to the selected model. |
| 400 | Read the error body; inspect unsupported fields, malformed JSON, and conversation metadata. |
| No visible text | Inspect promptFeedback, candidate parts, and finishReason; the response may be blocked, incomplete, or requesting a tool. |
| MAX_TOKENS | Treat the text as potentially incomplete and review the output budget before accepting it. |
| File request rejected | Verify the actual MIME type and the selected routeโs payload limit. |
For unexpected failures, record the model, route, status, timestamp, and request ID when available. Keep API keys and sensitive file contents out of routine logs.
FAQ
How should I retry Gemini 4 Hydrogen API rate-limit errors?
For HTTP 429, reduce concurrency and retry with exponential backoff and jitter, with a fixed maximum number of attempts. Keep the request ID when the gateway provides one. Do not retry invalid requests or authentication failures unchanged; CometAPIโs error and retry guide distinguishes those from transient failures. A timeout can occur after processing has started, so protect any application-side action from duplicate execution.
Can I call Gemini 4 Hydrogen API directly from a web app?
Route requests through your own backend. A key embedded in frontend JavaScript can be extracted by visitors, even if the code is bundled or minified. Let the backend authenticate users, apply usage limits, and send the model request. For streaming, forward the incremental response to the browser without exposing the upstream API key.
How should I handle an interrupted Gemini 4 Hydrogen stream?
Treat the received text as a partial result until the response completes. A new request starts a new generation; it does not automatically resume the broken stream at the same token. Keep partial output separate from a retried answer, and do not execute actions from incomplete JSON or unfinished tool arguments. Offer a visible retry action rather than silently concatenating two generations.
Conclusion
Use a representative task as your first acceptance check: the request should succeed, the application should extract the intended result, and the recorded token usage should fit your budget. Add one feature at a time and keep that check in your integration suite. A small, observable client is easier to extend than a large workflow whose failures are difficult to trace.

