Blog

Tutorial

Gemini-4 Argon and Carbon on HiAPI: curl, Python, and a Working Request

A practical integration guide for developers choosing between gemini-4-argon, gemini-4-carbon, and gemini-4-carbon@vertex

Nov 17, 2026 12 min read
Flat deep-indigo cover art of nested broad chevron arrows with apricot leading edges stepping diagonally upward, for a HiAPI tutorial article.
On this page

Choose your Gemini-4 variant before writing code

The first decision in any Gemini-4 integration is not curl versus Python — it is which model ID you send. On HiAPI, gemini-4-argon, gemini-4-carbon, and gemini-4-carbon@vertex are three distinct routable targets, and the string you pass in the model field determines which backend serves your request. Picking it up front saves you from debugging a payload that was never going to work.

The three targets in practice

  • gemini-4-argon — a separate Gemini-4 variant with its own model ID. Treat it as its own model, not an alias: behavior, latency profile, and output characteristics can differ from Carbon.
  • gemini-4-carbon — the default Carbon target on HiAPI's standard routing.
  • gemini-4-carbon@vertex — the same Carbon family served through a Vertex-backed route. The @vertex suffix is part of the model ID itself, not a separate parameter.

How to decide

Start from the workload. If you are evaluating Gemini-4 broadly, run the same prompt against both gemini-4-argon and gemini-4-carbon and compare outputs before you commit. If you specifically need the Vertex route — for example because it matches an environment your team already operates — target gemini-4-carbon@vertex directly.

The practical point: all three use the same request shape. Choosing a variant is a one-line change, so you can defer the final decision until after you have a working request. If you want the model cards first, see gemini-4-argon and gemini-4-carbon.

Throughout this guide the examples use gemini-4-carbon; swap the ID to follow along with any variant.

Get credentials and base URL in place

Before any payload matters, three things must be correct: the base URL, the API key, and the auth header format. Most first-request failures are one of these three.

What you need

  1. An API key from your HiAPI account dashboard. Treat it as a secret — load it from an environment variable rather than pasting it into source files.
  2. The HiAPI base URL. All model calls go to the same host; the model variant is selected by the model field, not by the path.
  3. Two headers on every request:
    • Authorization: Bearer $HIAPI_API_KEY
    • Content-Type: application/json

Set up your environment

export HIAPI_API_KEY="your-key-here"

Then verify it is visible to your shell before you write any code:

echo "${HIAPI_API_KEY:0:4}..."

If that prints nothing, your key is not exported in the current shell and every request will fail with an auth error. Fix it here rather than in your client.

The request shape you will reuse

Every example below sends a JSON body with a model string and a messages array. That shape does not change between curl and Python, between non-streaming and streaming, or between model variants. Keep it stable and you can port code by copying the payload.

A working request in curl

Here is a complete, copy-pasteable non-streaming call. Run this before adding anything else — a passing request here proves your key, base URL, and headers are all correct.

curl -sS "$HIAPI_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-4-carbon",
    "messages": [
      {"role": "system", "content": "You are a concise technical assistant."},
      {"role": "user", "content": "Explain what an idempotency key is in two sentences."}
    ]
  }'

What each field does

  • model — the variant selector. Change it to gemini-4-argon or gemini-4-carbon@vertex to hit a different target with zero other edits.
  • messages — an ordered array. Roles are system, user, and assistant. Keep the system message first if you use one.
  • content — the message text. For simple text turns this is a plain string.

Read the response body

The response is a JSON object containing the model's reply plus metadata such as token usage. Because this is non-streaming, the entire payload arrives at once and curl exits after printing it. If you get a parsed JSON object with a message back, your request is working — everything that follows builds on this baseline.

A quick sanity check: pipe the output through a JSON formatter (| jq .) so the response structure is legible instead of one long line.

The same request in Python

The Python port keeps the payload identical — only the transport changes. Using requests:

import os
import requests

api_key = os.environ["HIAPI_API_KEY"]
base_url = os.environ["HIAPI_BASE_URL"]

payload = {
    "model": "gemini-4-carbon",
    "messages": [
        {"role": "system", "content": "You are a concise technical assistant."},
        {"role": "user", "content": "Explain what an idempotency key is in two sentences."},
    ],
}

response = requests.post(
    f"{base_url}/chat/completions",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    json=payload,
    timeout=60,
)
response.raise_for_status()
data = response.json()
print(data["choices"][0]["message"]["content"])

Why this mirrors the curl call

Notice that payload is byte-for-byte the JSON body from the previous section. The json= argument serializes it and sets Content-Type for you; the header dict supplies auth. Nothing about the model, messages, or roles changed.

Two habits worth keeping

  • Set a timeout. Without one, a stalled connection hangs your process indefinitely. timeout=60 is a reasonable starting point for non-streaming calls.
  • Call raise_for_status() before reading the body. A failed request returns a structured error object, not a completion — inspecting json() on a 4xx will mislead you. Let the exception fire first, then log the response text.

Keep the payload in a function or a small config object so the streaming and tool-call sections can extend it rather than duplicate it.

Adding streaming to the call

Get the non-streaming request passing first. Then enable streaming — the failure mode is different, and layering both changes at once makes errors ambiguous.

Turn streaming on

Add a single field to the existing payload:

{
  "model": "gemini-4-carbon",
  "stream": true,
  "messages": [
    {"role": "user", "content": "List three uses for a message queue."}
  ]
}

That is the entire protocol change. The server now responds with a sequence of events instead of one JSON document.

Consuming the stream correctly

The critical rule: do not call .json() on a streamed response. You will get a parse error because the body is not a single JSON object. With requests, iterate the lines and parse each chunk individually:

import json, os, requests

response = requests.post(
    f"{os.environ['HIAPI_BASE_URL']}/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['HIAPI_API_KEY']}"},
    json={
        "model": "gemini-4-carbon",
        "stream": True,
        "messages": [{"role": "user", "content": "List three uses for a message queue."}],
    },
    stream=True,
    timeout=60,
)
response.raise_for_status()

for line in response.iter_lines():
    if not line:
        continue
    decoded = line.decode("utf-8")
    if decoded.startswith("data: "):
        decoded = decoded[len("data: "):]
    if decoded.strip() == "[DONE]":
        break
    try:
        chunk = json.loads(decoded)
    except json.JSONDecodeError:
        continue
    print(chunk)

What to watch for

  • Pass stream=True to requests. Without it the client buffers the entire body before you see a line, which defeats the purpose.
  • Skip blank lines and non-JSON keepalives. The try/except above is deliberate — streams can contain lines that are not parseable chunks.
  • Accumulate text across chunks. Each chunk carries a fragment, not the full reply. Append text deltas as they arrive.

Once streaming works, return stream to false for your non-streaming tests so tool calls stay easy to read. For an overview of the Carbon target, the gemini-4-carbon model page is a good reference point.

Adding tool calls to the payload

Tool calls change the request in two places: you declare tools, and you handle a response turn that may contain a tool-call request instead of text. Add this only after non-streaming text calls pass.

Declaring tools

Add a tools array alongside model and messages. Each tool has a name, a description, and a JSON Schema for its parameters. The description matters — it is what the model uses to decide whether to invoke the tool.

{
  "model": "gemini-4-carbon",
  "messages": [
    {"role": "user", "content": "What is the weather in Lisbon?"}
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Return current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "City name"}
          },
          "required": ["city"]
        }
      }
    }
  ]
}

The tool-call loop

A tool-using request is a conversation, not a single call:

  1. Send the user message with the tool declarations.
  2. Inspect the assistant turn. If it contains tool-call arguments, the model wants you to run something.
  3. Execute the function locally — HiAPI does not run your code.
  4. Append two messages: the assistant's tool-call turn, and a tool role message carrying the function result, keyed to the matching call ID.
  5. Resend the full message history. The model now produces the final answer.

Failure points specific to tools

  • Schema mismatch. If your parameters schema marks a field required but the result omits it, the follow-up turn can be rejected. Keep the schema exact.
  • Dropping history. Every resend must include the original user message and the tool-call turn — not just the tool result.
  • Streaming plus tools. Tool-call arguments can arrive split across stream chunks. While you are learning the flow, run tools with stream: false so each turn arrives as one readable object.

Switching models and providers without rewriting your client

Because the model variant is just a string in the payload, switching targets is configuration, not refactoring. Structure your client so the model ID is read from a variable — an environment variable, a config file, a CLI flag — and never hardcoded in multiple places.

The switch itself

export HIAPI_MODEL="gemini-4-carbon"      # default
export HIAPI_MODEL="gemini-4-argon"       # different variant
export HIAPI_MODEL="gemini-4-carbon@vertex"  # Vertex-backed Carbon

In code, reference the variable in the payload:

payload = {
    "model": os.environ["HIAPI_MODEL"],
    "messages": messages,
}

The @vertex suffix travels inside the model string. Do not split it into a separate field or strip it — it is part of the routable ID, and stripping it silently routes you to the non-Vertex target.

What to re-test after a switch

  1. Plain text turn — confirms the ID is recognized and auth still works.
  2. Your longest real prompt — variants can differ in how they handle long or structured input; verify truncation and formatting.
  3. Streaming — re-run the streaming path, since chunk pacing and boundaries can differ per target.
  4. Tool calls — re-verify the full tool-call loop; argument formatting is where variant differences surface most often.

Keep a small smoke-test script that runs these four checks against whatever HIAPI_MODEL is set to. That way a provider switch is a config change plus one command, not a debugging session.

Troubleshooting common request failures

Nearly every integration failure falls into a small set of buckets. Match the symptom, apply the fix, and re-run the non-streaming baseline before touching anything else.

Authentication and routing

  • 401 or 403. The key is missing, expired, or not prefixed correctly. Check that the header is exactly Authorization: Bearer <key> with a single space, and that the variable is actually exported in the shell or process running the code. Echo the first few characters to confirm.
  • 404 on the endpoint. Your base URL is wrong or has a duplicated path segment. The model goes in the body, not the URL.
  • Model not found. You have a typo in the model ID. Compare character by character against gemini-4-argon, gemini-4-carbon, and gemini-4-carbon@vertex — the @vertex suffix is the most common thing people drop.

Payload problems

  • 400 with a schema message. Usually messages is malformed: missing role, content that is not a string where one is expected, or an empty array. Start from the minimal two-line payload in this guide and add fields back one at a time.
  • 400 after adding tools. Your parameters schema is invalid JSON Schema, or the tool result turn does not match the call ID from the assistant message. Log the full response body — the error text names the offending field.

Streaming failures

  • JSON parse error on the response. You are calling .json() on a stream. Iterate lines and parse each chunk instead, and skip blank lines and [DONE] markers.
  • Response arrives all at once. You forgot stream=True on the client call, so requests buffered the body.
  • Truncated output. Your loop breaks early — often on a blank line or keepalive. Only stop on the explicit end-of-stream marker.

Debugging discipline

Bisect in the same order you built: auth and headers, then non-streaming text, then streaming, then tools. Each layer has a distinct failure signature, so the last thing you changed is almost always the cause. Log the HTTP status and full response body on every failure — the message usually names the exact field.

Get the baseline passing against gemini-4-argon or gemini-4-carbon, then grow the payload from there. The gemini-4-argon model page is the place to start if you are still deciding which variant fits your workload.

Related articles

View all articles →

Start building with persistent AI artifacts

Get your API key and call image, video and audio models through one task-based API.

Read the API docs