guides

Gemini 4 Neon API for Coding Agents: Streaming, 1M Context & Cost Budgets

Poyo.ai Team
9 min read
Share:

Gemini 4 Neon API powering a coding agent loop

The Gemini 4 Neon API is Google's fast option for agentic coding: Google built it for multi-file refactoring, secure code generation, and agents that need to respond quickly to corrections. This guide wires gemini-4-neon (model page) into a coding agent through PoYo's OpenAI-compatible endpoint. The agent streams each turn, reads a large slice of the repository, stops at a hard turn and dollar budget, and hands long-horizon work to Gemini 4 Carbon.

If you haven't sent a first request yet, start with the Gemini 4 Neon API guide.

Why the Gemini 4 Neon API for agents

Google's numbers for Neon's coding and agent work (all from Google DeepMind):

SignalGoogle's figureWhat it means for an agent
Terminal-Bench 4.165.2%Shell-driven tasks, same score as Carbon
CursorBench 4.165.4%IDE-style edits
AutoBaxBench76.0% (Carbon 74.0%)Generated patches are more often secure
Agent Arena Index#2 for mid-task steerabilityHandles user corrections mid-run
SpeedAbout 2× Carbon end-to-endShorter wait per turn
Cost per task32% lower than Carbon at high (Google's prices)Fewer tokens per finished task

On PoYo, Neon is $2.40 input / $12.00 output / $0.12 cache read per 1M tokens (480 / 2,400 / 24 credits), which is 1.5× Carbon's per-token price. The budget code below uses Neon's rates.

What the API gives a coding agent

ItemGemini 4 Neon on PoYo
Model IDgemini-4-neon
Endpoint used herePOST https://api.poyo.ai/v1/chat/completions (OpenAI SDK, base_url="https://api.poyo.ai/v1")
Native alternativePOST /v1beta/models/gemini-4-neon:generateContent and :streamGenerateContent
Context window1,048,576 tokens shared by input, thinking, and output
Max output per response64K tokens by default
Streaming"stream": true; the last chunk carries finish_reason and usage
Rate limitsPoYo's docs say LLM endpoints are currently not rate limited
Errors400, 401, 402 (insufficient credits), 404; retry 429 / 500 / 502 / 503 with backoff

The Chat Completions docs document model, messages (string content), max_tokens, stream, temperature, top_p, stop, n, and the penalty fields. The agent below uses only those.

Tool calling: what is documented today

PoYo documents tools for Anthropic Messages and Responses, but not for Gemini models in either Chat Completions or Gemini Native. So this agent uses a JSON action protocol: the system prompt lists allowed actions, the model replies with one JSON object per turn, and your code runs it and returns the result as the next user message. The model can only request the four actions you wrote, so it can't run arbitrary shell commands.

Thinking level in an agent loop

Google gives Neon four thinking levels: low, medium, high (default), and xhigh. A sensible split is lower levels for interactive coding and xhigh for hard architecture or reasoning steps. PoYo's model page says thinking control goes through the native format, but PoYo's published schemas don't list a thinking field yet. This loop sends none, so every turn runs at high. Thinking tokens are billed as output, which is why the budget check reads completion_tokens from every turn instead of estimating from visible text.

Long-context repo input: 1M in, 64K out

  • Every turn resends the history. A 300K-token snapshot over 12 turns is at least 3.6M input tokens: $8.64 at $2.40 per 1M before output. If implicit caching serves that prefix, the same tokens cost $0.432 at the $0.12 cache-read rate, but Google offers implicit caching only, so budget for the full rate.
  • Output is capped at 64K per response. Ask for one file per write_file action.
  • Measure token counts. Read usage.prompt_tokens from the first call and tune MAX_SNAPSHOT_CHARS.

The bounded agent loop in Python

import json, os, subprocess, time
from pathlib import Path
from openai import OpenAI, APIStatusError

client = OpenAI(api_key=os.environ["POYO_API_KEY"], base_url="https://api.poyo.ai/v1")

NEON, CARBON = "gemini-4-neon", "gemini-4-carbon"
PRICES = {NEON: (2.40, 12.00), CARBON: (1.60, 8.00)}   # PoYo USD per 1M tokens (2026-11-23)

MAX_TURNS, BUDGET_USD = 12, 3.00
MAX_TOKENS_PER_TURN = 16_000          # default cap is 64K
MAX_SNAPSHOT_CHARS = 400_000
MAX_RESULT_CHARS = 20_000
REPO = Path("./my-repo").resolve()

SYSTEM = """You are a coding agent working in a Python repository.
Reply with exactly one JSON object and nothing else. Allowed actions:
{"action": "read_file", "path": "<relative path>"}
{"action": "write_file", "path": "<relative path>", "content": "<full file content>"}
{"action": "run_tests"}
{"action": "done", "summary": "<what changed and why>"}"""


def snapshot() -> str:
    parts, total = [], 0
    for p in sorted(REPO.rglob("*.py")):
        block = f"### {p.relative_to(REPO)}\n{p.read_text(encoding='utf-8', errors='replace')}\n"
        if total + len(block) > MAX_SNAPSHOT_CHARS:
            break
        parts.append(block)
        total += len(block)
    return "".join(parts)


def safe_path(rel: str) -> Path:
    p = (REPO / rel).resolve()
    if not p.is_relative_to(REPO):
        raise ValueError("path outside repository")
    return p


def execute(action: dict) -> str:
    kind = action.get("action")
    if kind == "read_file":
        return safe_path(action["path"]).read_text(encoding="utf-8", errors="replace")
    if kind == "write_file":
        safe_path(action["path"]).write_text(action["content"], encoding="utf-8")
        return "written"
    if kind == "run_tests":
        r = subprocess.run(["pytest", "-q"], cwd=REPO, capture_output=True, text=True, timeout=600)
        return f"exit={r.returncode}\n{r.stdout}\n{r.stderr}"
    raise ValueError(f"unknown action {kind!r}")


def call(model: str, messages: list):
    """One streamed turn with retries. Returns (text, usage, finish_reason)."""
    for attempt in range(4):
        try:
            stream = client.chat.completions.create(
                model=model, messages=messages, max_tokens=MAX_TOKENS_PER_TURN, stream=True
            )
            text, usage, finish = [], None, None
            for chunk in stream:
                if chunk.choices:
                    c = chunk.choices[0]
                    if c.delta and c.delta.content:
                        text.append(c.delta.content)
                    finish = c.finish_reason or finish
                if getattr(chunk, "usage", None):
                    usage = chunk.usage
            return "".join(text), usage, finish
        except APIStatusError as e:
            if e.status_code in (429, 500, 502, 503) and attempt < 3:
                time.sleep(2 ** attempt)
                continue
            raise


def run(task: str, model: str = NEON) -> str:
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": f"Repository:\n{snapshot()}\n\nTask: {task}"},
    ]
    spent = 0.0
    for turn in range(MAX_TURNS):
        text, usage, finish = call(model, messages)
        if usage:
            p_in, p_out = PRICES[model]
            spent += (usage.prompt_tokens * p_in + usage.completion_tokens * p_out) / 1_000_000
        if spent > BUDGET_USD:
            return f"stopped: budget reached (${spent:.2f})"
        if finish == "length":
            messages.append({"role": "user", "content": "Reply was cut off. Send a shorter single action."})
            continue
        messages.append({"role": "assistant", "content": text})
        try:
            action = json.loads(text)
            if action.get("action") == "done":
                return f"done in {turn + 1} turns, ${spent:.2f}: {action.get('summary')}"
            result = execute(action)
        except Exception as e:
            result = f"error: {e}"
        messages.append({"role": "user", "content": result[:MAX_RESULT_CHARS]})
    return f"stopped: turn limit (${spent:.2f})"

The loop prices every prompt token at the full input rate, so the budget is an upper bound. It retries only 429 and 5xx; a 400, 401, 402, or 404 stops the run, because retrying won't change the result.

Steering the agent mid-run

Google ranks Neon #2 on the Agent Arena Index for mid-task steerability, which matters when a person watches the agent work. With the JSON action protocol, steering is just another user message. Between turns, check a queue for user input and, if there is any, append it before the next call:

  • Correction: "Don't touch settings.py; the bug is in the serializer." Append it as a user message and let the next action respond to it.
  • Scope change: "Also add a regression test." The model can pick it up without restarting, because the full history is still in messages.
  • Stop: check the queue before each call and return early. Nothing is billed for a turn you don't send.

Each steering message adds only a few dozen input tokens, but the next call still resends the whole history, so a late correction in a 300K-token run costs about $0.72 in input at $2.40 per 1M. Correct early when you can.

Production checklist

  • Log usage.prompt_tokens, usage.completion_tokens, finish_reason, model ID, and wall time for every turn.
  • Keep the system prompt and repository snapshot byte-identical across turns, so implicit caching has a stable prefix.
  • Trim tool results to MAX_RESULT_CHARS and summarize old test logs instead of resending them.
  • Run the agent in a disposable checkout or container, never against your main working tree.
  • Review the diff before merging. Google's secure-coding scores are a reason to trust the patches more, not a reason to skip review.
  • Set the budget per run, not per day, so one runaway task can't use the whole allowance.

When to hand off to Gemini 4 Carbon

Google's table shows Carbon slightly ahead on Agents' Last Exam v1.1 (77.4% vs 75.8%) and GraphWalks 256K–1M (96.2% vs 95.2%), and Carbon is cheaper per token on PoYo. A practical split:

SituationModel
Interactive fixes, PR review, short refactorsgemini-4-neon
Overnight multi-hour runs where latency doesn't mattergemini-4-carbon
Neon hits the turn limit without doneRetry the task once with run(task, model=CARBON)

Both models accept the same request body, so the hand-off is just the model argument. Read more in Gemini 4 Neon API vs Gemini 4 Carbon and the earlier Gemini 4 Carbon API for coding agents.

Frequently asked questions

Does the Gemini 4 Neon API support function calling on PoYo?

PoYo's docs don't currently document tools for Gemini models. Use a JSON action protocol in message content, as shown above, until native function calling is documented.

Can the Gemini 4 Neon API stream agent turns?

Yes. Set stream=True; text arrives in choices[0].delta.content and the final chunk carries finish_reason and usage.

How much context can a Gemini 4 Neon API agent use?

1,048,576 tokens shared by input, thinking, and output, with a 64K default output cap per response.

How do I cap the cost of a Gemini 4 Neon API agent run?

Read usage after every turn, price it at $2.40 input and $12.00 output per 1M, and stop when the running total passes your budget.

Is the Gemini 4 Neon API rate limited on PoYo?

PoYo's docs say LLM endpoints are currently not rate limited. Still retry 429 and 5xx responses with backoff.

Share: