Start with a short text request to the Gemini 4 Neon API in CometAPI. Check the response and token usage in your terminal, then use the same key in Python or Node.js. Choose Chat Completions for an existing OpenAI client or native GenerateContent when you need explicit thinking controls, file input, or a response schema.
Key Takeaways
Use gemini-4-neon in the Chat Completions request body or in the native GenerateContent URL.
Keep your CometAPI key on the server. Pass it as a bearer token for Chat Completions or in the x-goog-api-key header for the native endpoint.
Read choices from a chat response and candidates from a native response. Each route needs its own parser.
Use the response’s token counts to estimate cost. Thinking tokens count toward billed output.
Reviewed for clarity, source attribution and current API terminology.
What Is the Gemini 4 Neon API?
Google introduced Gemini 4 Neon on November 18, 2026. For a support application, one request can combine a customer’s description with a screenshot or PDF and return a text summary. If the result goes into a ticketing system, you can ask for the same fields on every request.Use the model ID gemini-4-neon to send text, images, audio, video, or documents. The model can return text or structured output, including function calls. Your input and the generated response share a budget of 1,048,576 tokens. Each foreground response segment can use up to 65,536 tokens, including tokens spent on reasoning.
How Do You Use the Gemini 4 Neon API Step by Step?
Step 1: Create a CometAPI account and API key
Sign in to CometAPI, create an API key in the dashboard, and set it in the terminal that will run the examples.
In Bash, set the key and model for the current shell.
Step 2: Make your first Gemini 4 Neon API call with cURL
Run this command in Bash. The native GenerateContent endpoint takes the model ID in the URL and the prompt in contents. The example asks for three reliability risks so you can recognize a successful response.
curl "https://api.cometapi.com/v1beta/models/${COMETAPI_MODEL}:generateContent" \
-H "x-goog-api-key: $COMETAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{"parts": [{"text": "List three reliability risks for a Python API service."}]}],
"generationConfig": {"maxOutputTokens": 4096, "thinkingConfig": {"thinkingLevel": "MEDIUM"}}
}'
Look for the answer in candidates[0].content.parts. A candidate’s finishReason tells you why generation stopped. The top-level usageMetadata records token usage.
To run the same native request directly through Google, set GEMINI_API_KEY in your shell. In the cURL command above, change the host to generativelanguage.googleapis.com and the header value to $GEMINI_API_KEY. Keep the model path and JSON body the same.Use a key from a Google Cloud project with paid-tier access to the Gemini API. Google bills that project and applies its quota when you send the request. See the Gemini API pricing page for tier availability.
Step 3: Send a chat request from Python
Install the OpenAI client in the Python environment you will use to run the example.
pip install --upgrade openai
Save this as neon_chat.py. The client sends the model ID in the JSON body and reads the assistant’s text from the first choice.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1")
reply = client.chat.completions.create(
model=os.environ["COMETAPI_MODEL"],
messages=[{"role": "user", "content": "Suggest three ways to make a REST API more reliable."}],
)
print(reply.choices[0].message.content)
Run the program.
python neon_chat.py
JavaScript alternative with Node.js
For Node.js with built-in fetch, save this as neon_chat.mjs. Run node neon_chat.mjs in the terminal where you set your key and model. A successful request prints the assistant’s answer.
const { COMETAPI_KEY, COMETAPI_MODEL } = process.env;
if (!COMETAPI_KEY || !COMETAPI_MODEL) throw new Error("Set COMETAPI_KEY and COMETAPI_MODEL first.");
const response = await fetch("https://api.cometapi.com/v1/chat/completions", {
method: "POST",
headers: { Authorization: `Bearer ${COMETAPI_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
model: COMETAPI_MODEL,
messages: [{ role: "user", content: "Show me how to validate an API input in JavaScript." }],
}),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const { choices } = await response.json();
console.log(choices[0].message.content);
How Do You Use Gemini 4 Neon’s Advanced API Features?
Configure thinking and structured output
The four supported thinking levels are LOW, MEDIUM, HIGH, and XHIGH. HIGH is the default. For a latency-sensitive task, try MEDIUM on a representative input and check whether it still meets your acceptance criteria.
To give the model more room to reason about a cache design, replace the JSON body in the cURL example with the one below. The output budget covers both reasoning and the visible answer.
{
"contents": [{"parts": [{"text": "Identify consistency risks in a distributed cache."}]}],
"generationConfig": {"thinkingConfig": {"thinkingLevel": "HIGH"}, "maxOutputTokens": 8192}
}
For an incident report, ask for the fields your tracker needs. Install requests with python -m pip install requests, then save this helper as neon_native.py. Both the incident report and the PDF example use it to send a native request and read the visible text.
import os
import requests
def generate(parts, config):
model = os.environ["COMETAPI_MODEL"]
url = f"https://api.cometapi.com/v1beta/models/{model}:generateContent"
response = requests.post(
url, headers={"x-goog-api-key": os.environ["COMETAPI_KEY"]},
json={"contents": [{"role": "user", "parts": parts}], "generationConfig": config},
timeout=180,
)
response.raise_for_status()
parts_out = response.json()["candidates"][0]["content"]["parts"]
return "".join(p.get("text", "") for p in parts_out if not p.get("thought"))
Save the following as incident.py beside the helper and run python incident.py. The schema asks for four required strings, so you can read the same fields for each incident.
from neon_native import generate
fields = ["category", "severity", "root_cause", "recommended_action"]
schema = {
"type": "OBJECT",
"properties": {name: {"type": "STRING"} for name in fields},
"required": fields,
}
prompt = "Analyze this incident: the API returned 503s after its database connection pool filled up."
output = generate([{"text": prompt}], {
"responseMimeType": "application/json", "responseSchema": schema,
"maxOutputTokens": 4096, "thinkingConfig": {"thinkingLevel": "MEDIUM"},
})
print(output)
An illustrative output structure would be:
{
"category": "Database",
"severity": "High",
"root_cause": "Database connection pool exhaustion",
"recommended_action": "Review connection lifecycle, pool sizing, and concurrency limits."
}
Parse the returned text with json.loads(output), then validate the fields against your application schema. For example, if your incident tracker accepts only three severity labels, check the value before creating a ticket.
Stream text to the client
Streaming allows applications to display generated text incrementally rather than waiting for the complete response.
In neon_chat.py, keep the client setup and replace the request and print statement with the lines below. Run the script again to see the answer appear as each text fragment arrives.
stream = client.chat.completions.create(
model=os.environ["COMETAPI_MODEL"],
messages=[{"role": "user", "content": "Explain how to build a fault-tolerant task queue."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
For background classification, structured extraction, or short automated decisions, a normal non-streaming request may be simpler.
Carry context into the next turn
Suppose a user asks which risks appear in a report and then asks which one to address first. In a native request, start the next contents array with the original user turn, append the complete candidates[0].content from the first response, and append the new user question. This preserves the model’s parts and any thought signatures. Rebuilding the model turn from the text displayed in your UI can discard fields the next request needs.
Send an image or PDF
Put report.pdf and a new script named read_pdf.py beside neon_native.py. Paste the code below into read_pdf.py and run python read_pdf.py from that directory. The prompt and PDF travel in the same message, so you can ask the model to cite the sections behind its findings.
import base64
from pathlib import Path
from neon_native import generate
encoded = base64.b64encode(Path("report.pdf").read_bytes()).decode("ascii")
parts = [
{"text": "Summarize the findings, identify three risks, and cite the relevant sections."},
{"inlineData": {"mimeType": "application/pdf", "data": encoded}},
]
print(generate(parts, {
"maxOutputTokens": 8192, "thinkingConfig": {"thinkingLevel": "HIGH"},
}))
To analyze a local image, replace the document’s MIME type with image/png or image/jpeg and encode the image bytes using the same method.
Connect a read-only application tool
For an order-status assistant, declare a function such as get_order_status with one required order_id string in tools[].functionDeclarations. When a returned part contains a functionCall, check the name, validate the ID, and verify the caller can view that order before querying your service. The model supplies the arguments and your application performs the lookup. See Google’s function calling guide.
Append the complete model turn to the conversation, then return a functionResponse part with the function name, the matching call ID when supplied, and the status from your service. Send the updated contents so Neon can answer using the actual order status.
How Much Does Gemini 4 Neon API Cost?
For a standard request, count uncached input, cache reads, and output separately. The prices below are in USD per million tokens as of November 22, 2026.
Token category
Google standard
CometAPI
Uncached input
$3.00
$2.40
Cached input
$0.15
$0.12
Output, including thinking
$15.00
$12.00
Cost of a single request
A request with 100,000 uncached input tokens and 10,000 billed output tokens costs $0.36 on CometAPI. The input accounts for $0.24 and the output for $0.12. The same token usage costs $0.45 at Google’s standard rates. This example includes no paid tool calls.
How Do You Migrate an Existing Workflow to Gemini 4 Neon?
For Chat Completions, keep your existing CometAPI base URL and key, then change the model field to gemini-4-neon. For GenerateContent, change the model in the URL and review the native request settings before replaying a saved request.
Native request settings
When migrating a native Google request from Gemini 3 or earlier, replace legacy thinking budgets with thinkingLevel and remove MINIMAL. Remove temperature, topP, and topK: Neon ignores in-range custom values and returns HTTP 400 for out-of-range values. Remove cachedContent references. Implicit caching can apply to shared prompt prefixes of at least 4,096 tokens.
A first production check
A reliable migration test should compare the old and new integrations using the same representative prompts.
Record task success, total latency, input tokens, output tokens, and resulting cost.
What Limits Should You Check Before Deploying Gemini 4 Neon?
Budget for the prompt, the model’s reasoning, and the visible answer. A long document leaves less room for generation. If a native response ends with MAX_TOKENS, inspect usageMetadata before increasing the output allowance or reducing the input.
Common setup errors
HTTP 400 after a model change. Read the error message for the rejected field. Check that your request body matches the endpoint and remove any obsolete thinking settings.
HTTP 401 or 403. Check that the API key belongs to the provider you’re calling and that its project or account has access to the model.
HTTP 429. Check your account’s rate limit and remaining quota. If you hit a temporary limit, wait for the interval in the Retry-After header when one is supplied, and cap the number of retries.
Symptom
What to check first
HTTP 400 after changing models
Inspect the response error message. Check the request shape for the selected endpoint and remove obsolete thinking settings.
HTTP 401 or 403
Check that the key belongs to the endpoint’s provider and the account has model access.
HTTP 429
Inspect the account’s rate limit and quota. For a temporary rate limit, honor Retry-After when supplied and bound your retries.
FAQ
Why did my native request return HTTP 200 with no visible answer?
Inspect promptFeedback if candidates is empty. If a candidate exists, examine its finishReason and the types of parts it returned. A functionCall needs tool handling, while a text part can be displayed. Log these fields before deciding whether to retry.
Can I use the JavaScript example in a public web page?
Keep the example in Node.js on your server. A browser user can inspect a request’s Authorization header and recover the key. Have the page send its prompt to your backend, then return the response text or stream from there.
Can a Gemini 4 Neon stream continue past the output limit?
Streaming controls when text arrives. Generating beyond a 65,536-token segment requires a continuation protocol. Google documents continuation on its Agent Platform v1beta1 endpoints. If your application needs multi-segment output through CometAPI, verify support on the exact route before scheduling the job.
Conclusion
For an existing application, migrate one representative workflow first. Measure completion quality, reasoning token consumption, latency, and cost before expanding the integration.
For a new integration, save one successful request and its response as a fixture. Use that pair to check your parser when you add streaming, structured output, or file input.
SEO Metadata
Meta title: How to Use Gemini 4 Neon API with CometAPI: Complete Guide 2026
Meta description: Call the Gemini 4 Neon API through CometAPI with cURL, Python, or JavaScript. Stream text, request JSON, analyze PDFs, and estimate token costs.