TL;DR
從一個簡短的文字請求開始,透過 CometAPI 向 Gemini 4 Neon API 發送請求。在終端機檢查回應與 token 使用情況,然後在 Python 或 Node.js 中使用同一把金鑰。若已使用 OpenAI 客戶端,選擇 Chat Completions;若需要更明確的思考控制、檔案輸入或回應結構,使用原生的 GenerateContent。
Key Takeaways
- 在 Chat Completions 的 request body 或原生 GenerateContent 的 URL 中使用 gemini-4-neon。
- 將 CometAPI 金鑰保存在伺服器端。對 Chat Completions 以 bearer token 傳遞,對原生端點則使用 x-goog-api-key 標頭。
- 從 chat 回應讀取 choices,從原生回應讀取 candidates。每條路徑需要各自的解析器。
- 使用回應中的 token 計數來估算成本。思考用的 tokens 會計入付費輸出。
What Is the Gemini 4 Neon API?
Google 於 2026 年 11 月 18 日推出 Gemini 4 Neon。對於客服應用,一次請求可以結合客戶的描述與螢幕截圖或 PDF,並回傳文字摘要。若結果要進入工單系統,你可以在每次請求中要求相同欄位。使用模型 ID gemini-4-neon 可傳送文字、影像、音訊、影片或文件。模型可回傳文字或結構化輸出,包括函數呼叫。你的輸入與生成的回應共用 1,048,576 個 tokens 的預算。每個前景回應區段最多可使用 65,536 個 tokens,包含推理所消耗的 tokens。
How Do You Use the Gemini 4 Neon API Step by Step?
Step 1: Create a CometAPI account and API key
登入 CometAPI,在儀表板建立 API 金鑰,並在將要執行範例的終端機中設定。
在 Bash 中,為當前 shell 設定金鑰與模型。
export COMETAPI_KEY="YOUR_COMETAPI_KEY"
export COMETAPI_MODEL="gemini-4-neon"
在 PowerShell 中,為當前工作階段設定相同變數。
$env:COMETAPI_KEY = "YOUR_COMETAPI_KEY"
$env:COMETAPI_MODEL = "gemini-4-neon"
Step 2: Make your first Gemini 4 Neon API call with cURL
在 Bash 中執行此命令。原生 GenerateContent 端點在 URL 中使用模型 ID,並在 contents 中放入提示。此範例請求三個可靠性風險,方便你辨識成功回應。
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"}}
}'
在 candidates[0].content.parts 中尋找答案。candidate 的 finishReason 告訴你為何停止生成。頂層的 usageMetadata 記錄 token 使用情況。
若要直接透過 Google 執行相同的原生請求,在你的 shell 中設定 GEMINI_API_KEY。於上述 cURL 指令中,將主機改為 generativelanguage.googleapis.com,並將標頭值改為 $GEMINI_API_KEY。保持模型路徑與 JSON 主體相同。使用來自具備 Gemini API 付費層存取權的 Google Cloud 專案的金鑰。Google 會向該專案計費並套用其配額。請參見 Gemini API pricing page 以了解可用層級。
Step 3: Send a chat request from Python
在你將用來執行範例的 Python 環境安裝 OpenAI 客戶端。
pip install --upgrade openai
將以下內容存為 neon_chat.py。此客戶端在 JSON 主體中傳送模型 ID,並從第一個 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)
執行程式。
python neon_chat.py
JavaScript alternative with Node.js
對於具有內建 fetch 的 Node.js,將以下內容存為 neon_chat.mjs。在設定好金鑰與模型的終端機中執行 node neon_chat.mjs。成功的請求會列印助理的答案。
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
四種支援的思考層級為 LOW、MEDIUM、HIGH 與 XHIGH。預設為 HIGH。對延遲敏感的任務,可在具代表性的輸入上嘗試 MEDIUM,並檢查是否仍滿足你的驗收標準。
若要讓模型在快取設計上有更多推理空間,將 cURL 範例中的 JSON 主體替換為下列內容。輸出預算同時涵蓋推理與可見答案。
{
"contents": [{"parts": [{"text": "Identify consistency risks in a distributed cache."}]}],
"generationConfig": {"thinkingConfig": {"thinkingLevel": "HIGH"}, "maxOutputTokens": 8192}
}
對於事故報告,要求你的追蹤器所需的欄位。使用 python -m pip install requests 安裝 requests,然後將以下輔助程式存為 neon_native.py。事故報告與 PDF 範例都使用它來發送原生請求並讀取可見文字。
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"))
將下列內容存為 incident.py,放在輔助程式旁,並執行 python incident.py。此結構要求四個必要字串,因此你可以在每次事故中讀取相同欄位。
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)
一個示例性的輸出結構如下:
{
"category": "Database",
"severity": "High",
"root_cause": "Database connection pool exhaustion",
"recommended_action": "Review connection lifecycle, pool sizing, and concurrency limits."
}
使用 json.loads(output) 解析回傳的文字,然後依你的應用程式結構驗證欄位。例如,若你的事故追蹤器只接受三個嚴重性標籤,請在建立工單前檢查其值。
Stream text to the client
串流允許應用程式逐步顯示生成文字,而非等待完整回應。
在 neon_chat.py 中,保留客戶端設定,並以以下程式碼取代請求與列印語句。再次執行腳本,即可看到答案隨每段文字片段到達而逐步顯示。
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()
對於背景分類、結構化擷取或短小的自動化決策,使用一般非串流請求可能更簡單。
Carry context into the next turn
假設使用者先詢問報告中出現哪些風險,接著再問應先處理哪一項。在原生請求中,將下一個 contents 陣列以原始使用者輪次開頭,附加第一次回應的完整 candidates[0].content,並附加新的使用者問題。這會保留模型的 parts 以及任何思考簽章。若基於 UI 中顯示的文字重建模型輪次,可能會丟失下一次請求所需的欄位。
Send an image or PDF
將 report.pdf 與一個名為 read_pdf.py 的新腳本放在 neon_native.py 同一目錄下。把以下程式碼貼到 read_pdf.py,並在該目錄執行 python read_pdf.py。提示與 PDF 在同一訊息中傳送,因此你可以要求模型引用其發現背後的章節。
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"},
}))
若要分析本機影像,將文件的 MIME 類型改為 image/png 或 image/jpeg,並以相同方法編碼影像位元組。
Connect a read-only application tool
對於查詢訂單狀態的助理,在 tools[].functionDeclarations 中宣告一個函數,如 get_order_status,且包含一個必要的 order_id 字串。當回傳的 part 包含 functionCall 時,檢查名稱、驗證 ID,並確認呼叫者可檢視該訂單,再查詢你的服務。模型提供參數,你的應用程式執行查詢。請參閱 Google 的 function calling guide。
將完整的模型輪次附加到會話中,然後回傳帶有函數名稱、當提供時匹配的呼叫 ID,以及你服務狀態的 functionResponse part。傳送更新後的 contents,以便 Neon 能使用實際的訂單狀態作答。
How Much Does Gemini 4 Neon API Cost?
對於標準請求,分別計算未快取輸入、快取讀取與輸出。以下價格為 2026 年 11 月 22 日的每百萬 tokens 美元價格。
| 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
一個包含 100,000 個未快取輸入 tokens 與 10,000 個付費輸出 tokens 的請求,在 CometAPI 的成本為 $0.36。輸入佔 $0.24,輸出佔 $0.12。相同的 token 使用量在 Google 標準費率下為 $0.45。此範例不包含付費工具呼叫。
How Do You Migrate an Existing Workflow to Gemini 4 Neon?
對於 Chat Completions,保留你現有的 CometAPI base URL 與金鑰,然後將 model 欄位改為 gemini-4-neon。對於 GenerateContent,將 URL 中的模型改為新值,並在重放已儲存的請求前檢視原生請求設定。
Native request settings
當你從 Gemini 3 或更早版本遷移原生 Google 請求時,以 thinkingLevel 取代舊版思考預算,並移除 MINIMAL。移除 temperature、topP 與 topK:Neon 對於範圍內的自訂值會忽略,對於超出範圍的值會回傳 HTTP 400。移除 cachedContent 參照。對至少 4,096 tokens 的共享提示前綴,可能套用隱式快取。
A first production check
可靠的遷移測試應使用相同的具代表性提示,對比舊整合與新整合。
記錄任務成功率、總延遲、輸入 tokens、輸出 tokens 與最終成本。
What Limits Should You Check Before Deploying Gemini 4 Neon?
為提示、模型推理與可見答案預留預算。較長的文件會減少可用的生成空間。若原生回應以 MAX_TOKENS 結束,請先檢視 usageMetadata,再決定是增加輸出配額或減少輸入。
Common setup errors
- HTTP 400 在更改模型後發生。閱讀錯誤訊息以了解被拒絕的欄位。檢查你的請求主體是否符合端點,並移除任何過時的思考設定。
- HTTP 401 或 403。檢查 API 金鑰是否屬於你呼叫的提供者,且其專案或帳戶具有模型存取權。
- HTTP 429。檢查你帳戶的速率限制與剩餘配額。若遇到臨時限制,當提供 Retry-After 標頭時請遵循其間隔,並為重試次數設定上限。
| 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?
若 candidates 為空,請檢查 promptFeedback。若存在 candidate,請檢視其 finishReason 與回傳的 parts 類型。functionCall 需要工具處理,而 text part 可直接顯示。在決定是否重試前,請記錄這些欄位。
Can I use the JavaScript example in a public web page?
請在伺服器端的 Node.js 中使用該範例。瀏覽器使用者可以檢視請求的 Authorization 標頭並取得金鑰。讓前端頁面將提示送到你的後端,然後由後端回傳或串流回應。
Can a Gemini 4 Neon stream continue past the output limit?
串流控制文字到達的時機。要生成超過 65,536-token 的區段需要續傳協定。Google 在其 Agent Platform v1beta1 端點上提供了續傳文件。若你的應用程式需要透過 CometAPI 進行多區段輸出,請在排程任務前確認特定路徑的支援情況。
Conclusion
對於既有應用,先遷移一個具代表性的工作流程。擴大整合前,量測完成品質、推理 token 消耗、延遲與成本。
對於新的整合,保存一組成功的請求與回應作為固定測試檔。當你加入串流、結構化輸出或檔案輸入時,使用該組測試來檢查你的解析器。
SEO Metadata
Meta title: 如何透過 CometAPI 使用 Gemini 4 Neon API:2026 完整指南
Meta description: 透過 CometAPI 使用 cURL、Python 或 JavaScript 呼叫 Gemini 4 Neon API。支援文字串流、請求 JSON、分析 PDF,並估算 token 成本。
Keywords: Gemini 4 Neon API, CometAPI, Gemini GenerateContent, Python, JavaScript, 串流, 結構化 JSON, API 定價
URL slug: how-to-use-gemini-4-neon-api

