
This Gemini 4 Carbon API guide takes you from an API key to a working request in cURL, the Python OpenAI SDK, and Google's native generateContent format, all with the model ID gemini-4-carbon. Each example follows PoYo's published request schema as of November 16, 2026. You can test prompts on the Gemini 4 Carbon model page first.
New to the model? Start with the Gemini 4 Carbon API overview for limits and positioning.
Before you start
Create a key in the PoYo dashboard and keep it on your server:
export POYO_API_KEY="your-poyo-key"
| Format | Endpoint | Use it when |
|---|---|---|
| Chat Completions | POST https://api.poyo.ai/v1/chat/completions | You already use the OpenAI SDK, text-only messages |
| Gemini Native | POST https://api.poyo.ai/v1beta/models/gemini-4-carbon:generateContent | You need image or file parts (inlineData) |
| Gemini Native streaming | POST https://api.poyo.ai/v1beta/models/gemini-4-carbon:streamGenerateContent | Native format with server-sent events |
Every request sends Authorization: Bearer $POYO_API_KEY. gemini-4-carbon does not support /v1/responses or /v1/messages on PoYo.
First Gemini 4 Carbon API request with cURL
curl https://api.poyo.ai/v1/chat/completions \
-H "Authorization: Bearer $POYO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-4-carbon",
"messages": [
{"role": "system", "content": "You are a code reviewer. Be specific and cite line numbers."},
{"role": "user", "content": "Review this function for race conditions: ..."}
],
"max_tokens": 8192,
"temperature": 1
}'
model and messages are required. Optional fields in PoYo's schema: temperature (0–2), top_p (0–1, use it or temperature, not both), max_tokens, stream, stop (up to 4 sequences), frequency_penalty and presence_penalty (−2 to 2), and n. Each message content is a string.
The response is a standard chat.completion object: text in choices[0].message.content, the stop cause in choices[0].finish_reason, and counts in usage.prompt_tokens, usage.completion_tokens, and usage.total_tokens.
Python with the OpenAI SDK
Point the SDK at PoYo and change nothing else:
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.poyo.ai/v1", api_key=os.environ["POYO_API_KEY"])
resp = client.chat.completions.create(
model="gemini-4-carbon",
messages=[
{"role": "system", "content": "You are a senior backend engineer."},
{"role": "user", "content": "Write a migration plan from Celery 4 to Celery 5."},
],
max_tokens=8192,
)
print(resp.choices[0].message.content)
print(resp.choices[0].finish_reason, resp.usage.prompt_tokens, resp.usage.completion_tokens)
Moving from gemini-4-argon, or any other model that supports Chat Completions on PoYo, is a one-line change to model.
Streaming with the OpenAI SDK
With stream=True, PoYo sends chat.completion.chunk events and ends with data: [DONE]. Text arrives in choices[0].delta.content, and the last chunk carries finish_reason and usage:
stream = client.chat.completions.create(
model="gemini-4-carbon",
messages=[{"role": "user", "content": "Explain the CAP theorem with one example per trade-off."}],
max_tokens=4096,
stream=True,
)
usage = None
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if getattr(chunk, "usage", None):
usage = chunk.usage
print("\n", usage)
The Gemini-native generateContent format
The native endpoint takes the model in the URL path. The body uses contents (each with role user or model and a parts array), plus optional generationConfig (temperature, topP, topK, maxOutputTokens, stopSequences) and safetySettings:
curl "https://api.poyo.ai/v1beta/models/gemini-4-carbon:generateContent" \
-H "Authorization: Bearer $POYO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [
{"role": "user", "parts": [{"text": "List three risks of running database migrations during peak traffic."}]}
],
"generationConfig": {"maxOutputTokens": 2048, "temperature": 0.7}
}'
The response is Google's GenerateContentResponse object, returned directly. Text is in candidates[].content.parts[].text and counts are in usageMetadata. Thinking models can add parts with thought: true or a thoughtSignature, so skip parts without text:
import os, requests
URL = "https://api.poyo.ai/v1beta/models/gemini-4-carbon:generateContent"
HEADERS = {"Authorization": f"Bearer {os.environ['POYO_API_KEY']}"}
body = {
"contents": [{"role": "user", "parts": [{"text": "Summarize the trade-offs of event sourcing."}]}],
"generationConfig": {"maxOutputTokens": 2048},
}
r = requests.post(URL, headers=HEADERS, json=body, timeout=600)
r.raise_for_status()
data = r.json()
text = "".join(
p["text"]
for c in data.get("candidates", [])
for p in c.get("content", {}).get("parts", [])
if "text" in p and not p.get("thought")
)
print(text)
print(data["usageMetadata"])
Native streaming
Swap the method for :streamGenerateContent. The response is text/event-stream: each data: line is a partial GenerateContentResponse, the last event carries finishReason, and the stream ends with data: [DONE]. The alt=sse query parameter is accepted but not required.
import json
STREAM_URL = "https://api.poyo.ai/v1beta/models/gemini-4-carbon:streamGenerateContent"
usage = {}
with requests.post(STREAM_URL, headers=HEADERS, json=body, stream=True, timeout=600) as r:
r.raise_for_status()
for line in r.iter_lines(decode_unicode=True):
if not line or not line.startswith("data: "):
continue
payload = line[len("data: "):]
if payload == "[DONE]":
break
event = json.loads(payload)
for cand in event.get("candidates", []):
for part in cand.get("content", {}).get("parts", []):
if "text" in part and not part.get("thought"):
print(part["text"], end="", flush=True)
usage = event.get("usageMetadata", usage)
print("\n", usage)
Multimodal input through the Gemini 4 Carbon API
Google lists text, image, audio, video, and PDF as input types for Gemini 4 Carbon. On PoYo, file input goes through the native format as an inlineData part with a mimeType and base64 data. PoYo's docs show an image example, and recommend putting text instructions before media parts:
{
"contents": [
{
"role": "user",
"parts": [
{"text": "Read this architecture diagram and list every service that writes to the database."},
{"inlineData": {"mimeType": "image/png", "data": "BASE64_IMAGE_DATA"}}
]
}
],
"generationConfig": {"maxOutputTokens": 4096}
}
PoYo's Chat Completions schema documents content as a string, so do not send OpenAI-style image arrays to /v1/chat/completions. For PDF, audio, and video, PoYo's docs do not show a separate example; send one small file first and check the response before you build a pipeline on it. Media counts toward the prompt: usageMetadata.promptTokensDetails breaks prompt tokens down by modality.
Setting max output
| Format | Field | Signal that output was cut off |
|---|---|---|
| Chat Completions | max_tokens | finish_reason: "length" |
| Gemini Native | generationConfig.maxOutputTokens | finishReason other than STOP |
Google lists 65,536 output tokens as the default synchronous cap and a 1,048,576-token context shared by input and output. Google's pricing page says thinking tokens are billed at the output rate, so the output count in usage can be larger than the visible text. PoYo's published schemas have no thinking-level field; the max output field is the documented length control.
Read usage and compute the cost of a request
PoYo prices gemini-4-carbon at $1.60 per 1M input tokens, $8.00 per 1M output tokens, and $0.08 per 1M cache-read tokens (1 credit = $0.005).
| Format | Input tokens | Output tokens (incl. thinking) |
|---|---|---|
| Chat Completions | usage.prompt_tokens | usage.total_tokens − usage.prompt_tokens |
| Gemini Native | usageMetadata.promptTokenCount | totalTokenCount − promptTokenCount (answer plus thoughtsTokenCount) |
INPUT_USD, OUTPUT_USD = 1.60, 8.00 # PoYo, per 1M tokens
def carbon_cost_usd(input_tokens: int, output_tokens: int) -> float:
return (input_tokens * INPUT_USD + output_tokens * OUTPUT_USD) / 1_000_000
def carbon_cost_credits(input_tokens: int, output_tokens: int) -> float:
return carbon_cost_usd(input_tokens, output_tokens) / 0.005
Measured example (PoYo production, November 16, 2026): a non-streaming /v1/chat/completions request asking gemini-4-carbon to review a 40-line Python function returned prompt_tokens: 480, completion_tokens: 1094, and total_tokens: 1574 in 6.3 seconds, with no thinking tokens reported. PoYo billed 1.904 credits for it, the same figure the formula gives.
input: 480 × $1.60 / 1,000,000 = $0.000768 (0.1536 credits)
output: 1,094 × $8.00 / 1,000,000 = $0.008752 (1.7504 credits)
total: $0.009520 (1.9040 credits)
This prices every prompt token at the full input rate. Cache-read tokens are billed at $0.08 per 1M, but PoYo's response schemas do not document a cached-token field, so treat this formula as an upper bound. Cost scenarios at scale are in Gemini 4 Carbon API pricing.
Errors worth handling
LLM endpoints on PoYo return real HTTP status codes:
| HTTP | Cause | What to do |
|---|---|---|
| 400 | Missing or invalid field; body {"code": 400, "error": {"type": "validation_error", ...}} | Fix the request; read error.details |
| 400 | Wrong format for this model; message lists the supported URIs | Use Chat Completions or Gemini Native |
| 400 | Gemini Native error, Google shape {"error": {"code": 400, "message": "...", "status": "INVALID_ARGUMENT"}} | Fix contents / generationConfig |
| 401 | Missing or invalid API key | Check the Authorization header |
| 402 | Insufficient credits | Top up before retrying |
| 404 | Unknown model ID (model_not_found) | Check the spelling: gemini-4-carbon |
| 500 / 502 / 503 | Server or upstream error | Retry with exponential backoff |
PoYo's docs say LLM endpoints are currently not rate limited, but PoYo's general error codes include 429. Handle it with a wait and retry. With the OpenAI SDK, catch openai.APIStatusError and branch on status_code. See PoYo error codes for full bodies.
Checklist before you ship
- Keep
POYO_API_KEYserver-side; never ship it in browser or mobile code. - Always set
max_tokensormaxOutputTokens, and logfinish_reason/finishReasonso truncated answers are visible. - Store the usage block of every response next to the request ID you assign, so you can reconcile spend per feature.
- Put long, stable context (repository files, documents) first and the changing question last, which gives implicit caching a chance to apply.
- Retry only 5xx and
429responses; a 400 will fail again until the body changes.
For agent loops, tool output, and long-context patterns, continue with Gemini 4 Carbon API for coding agents. To decide when Argon is enough, read Gemini 4 Carbon API vs Gemini 4 Argon.
Frequently asked questions
How do I call the Gemini 4 Carbon API in Python?
Use the OpenAI SDK with base_url="https://api.poyo.ai/v1", your PoYo key, and model="gemini-4-carbon". For native requests, POST to /v1beta/models/gemini-4-carbon:generateContent with requests.
Does the Gemini 4 Carbon API support streaming?
Yes. Set "stream": true on Chat Completions, or call :streamGenerateContent in the native format. Both return server-sent events that end with data: [DONE].
How do I send an image to the Gemini 4 Carbon API?
Use the Gemini-native endpoint with an inlineData part (mimeType plus base64 data) after your text part. Chat Completions on PoYo takes string content only.
How do I limit Gemini 4 Carbon API output tokens?
Set max_tokens (Chat Completions) or generationConfig.maxOutputTokens (native). Thinking tokens are billed as output, so compare the output count in usage with the visible text when you choose the cap.
Why does the Gemini 4 Carbon API return 400 on /v1/responses?
gemini-4-carbon supports only Chat Completions and Gemini Native on PoYo. Other formats return 400 with the list of supported URIs.