> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apimart.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Using APIMart with Gemini CLI

> Detailed guide on configuring APIMart API service in Gemini CLI command-line tool. Learn how to use APIMart’s AI models—including Gemini, GPT, and Claude series—from the terminal.

## Introduction

Gemini CLI is Google’s official command-line tool that lets developers interact with Gemini AI models from the terminal. After configuring APIMart API, you can use APIMart’s advanced models—GPT, Claude, and Gemini—in Gemini CLI.

## Prerequisites

Before you start:

1. **Node.js and npm installed**\
   Download and install from the [Node.js website](https://nodejs.org/) (v16 or higher recommended)

2. **APIMart API key**\
   Sign in to the [APIMart Console](https://apimart.ai/keys) and copy your API key (starts with `sk-`)

<Note>
  **Tip:** If you don’t have an APIMart account yet, register at [APIMart](https://apimart.ai) first and create an API key.
</Note>

## Step 1: Install Gemini CLI

### 1.1 Global install

Install Gemini CLI globally with npm:

```bash theme={null}
npm install -g @google/gemini-cli
```

### 1.2 Verify installation

Check that the CLI is available:

```bash theme={null}
gemini --version
```

If a version number is printed, installation succeeded.

<Note>**Tip:** If the command is not found, restart your terminal or check your npm global `PATH` configuration.</Note>

## Step 2: Configure APIMart API

### 2.1 Temporary environment variables

For testing or one-off use; values are cleared when you close the terminal.

**Windows (PowerShell):**

```powershell theme={null}
$env:GEMINI_API_KEY = "sk-xxxxxxxxxxxx"
$env:GEMINI_BASE_URL = "https://api.apimart.ai/v1"
```

**macOS/Linux (Bash):**

```bash theme={null}
export GEMINI_API_KEY="sk-xxxxxxxxxxxx"
export GEMINI_BASE_URL="https://api.apimart.ai/v1"
```

### 2.2 Permanent environment variables (recommended)

Persist configuration so new shells pick it up automatically.

**Windows (PowerShell):**

1. Run PowerShell as Administrator
2. Set user-level environment variables:

```powershell theme={null}
[System.Environment]::SetEnvironmentVariable('GEMINI_API_KEY', 'sk-xxxxxxxxxxxx', 'User')
[System.Environment]::SetEnvironmentVariable('GEMINI_BASE_URL', 'https://api.apimart.ai/v1', 'User')
```

3. Restart PowerShell, or reload variables:

```powershell theme={null}
$env:GEMINI_API_KEY = [System.Environment]::GetEnvironmentVariable('GEMINI_API_KEY', 'User')
$env:GEMINI_BASE_URL = [System.Environment]::GetEnvironmentVariable('GEMINI_BASE_URL', 'User')
```

**macOS/Linux (Bash):**

1. Edit your shell rc file:

```bash theme={null}
# Bash
nano ~/.bashrc

# Zsh (default on macOS)
nano ~/.zshrc
```

2. Append:

```bash theme={null}
# APIMart Gemini CLI
export GEMINI_API_KEY="sk-xxxxxxxxxxxx"
export GEMINI_BASE_URL="https://api.apimart.ai/v1"
```

3. Reload:

```bash theme={null}
source ~/.bashrc   # Bash
source ~/.zshrc    # Zsh
```

### 2.3 Using a `.env` file

Create `.env` in your project:

```bash theme={null}
# .env
GEMINI_API_KEY=sk-xxxxxxxxxxxx
GEMINI_BASE_URL=https://api.apimart.ai/v1
```

Load variables before running Gemini:

**macOS/Linux:**

```bash theme={null}
export $(cat .env | xargs) && gemini chat
```

**Windows (PowerShell):**

```powershell theme={null}
Get-Content .env | ForEach-Object {
    $name, $value = $_.split('=')
    Set-Content env:\$name $value
}
gemini chat
```

<Note>
  **Important:** - Replace `sk-xxxxxxxxxxxx` with your real key from the [APIMart Console](https://apimart.ai/keys) - Set `GEMINI_BASE_URL` to `https://api.apimart.ai/v1` so Gemini CLI talks to APIMart - Add `.env` to `.gitignore` so keys are not committed
</Note>

### 2.4 Verify configuration

**macOS/Linux:**

```bash theme={null}
echo $GEMINI_API_KEY
echo $GEMINI_BASE_URL
```

**Windows (PowerShell):**

```powershell theme={null}
echo $env:GEMINI_API_KEY
echo $env:GEMINI_BASE_URL
```

If the values look correct, configuration succeeded.

## Step 3: Use Gemini CLI

### 3.1 Basic chat

Interactive session:

```bash theme={null}
gemini chat
```

One-off prompt:

```bash theme={null}
gemini "Give a short overview of the history of artificial intelligence"
```

### 3.2 Choose a model

```bash theme={null}
gemini chat --model gpt-4o
```

Or:

```bash theme={null}
gemini "Write a Python quicksort implementation" --model claude-sonnet-4-5-20250929
```

### 3.3 Read prompts from a file

```bash theme={null}
gemini --input prompt.txt
```

Or pipe:

```bash theme={null}
cat prompt.txt | gemini
```

### 3.4 Save output to a file

```bash theme={null}
gemini "Generate a React component" --output component.jsx
```

## Step 4: Call APIMart from your code

### 4.1 Python SDK

```python theme={null}
import openai

# APIMart
openai.api_key = "sk-xxxxxxxxxxxx"  # Your APIMart API key
openai.api_base = "https://api.apimart.ai/v1"

response = openai.ChatCompletion.create(
    model="gemini-2.0-flash-exp",
    messages=[
        {"role": "user", "content": "Hi—please introduce yourself"}
    ]
)

print(response.choices[0].message.content)
```

### 4.2 JavaScript / TypeScript

```javascript theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: "sk-xxxxxxxxxxxx",
  baseURL: "https://api.apimart.ai/v1",
});

async function main() {
  const completion = await client.chat.completions.create({
    model: "gemini-2.0-flash-exp",
    messages: [{ role: "user", content: "Hi—please introduce yourself" }],
  });

  console.log(completion.choices[0].message.content);
}

main();
```

### 4.3 cURL

```bash theme={null}
curl https://api.apimart.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxxxxxx" \
  -d '{
    "model": "gemini-2.0-flash-exp",
    "messages": [
      {"role": "user", "content": "Hi—please introduce yourself"}
    ]
  }'
```

## Step 5: Pick a model

### Recommended models

APIMart supports many models; choose by task and budget.

**Gemini**

| Model name       | Model ID               | Characteristics   | Good for                     |
| ---------------- | ---------------------- | ----------------- | ---------------------------- |
| Gemini 2.0 Flash | `gemini-2.0-flash-exp` | Fast, multimodal  | Quick answers, vision + text |
| Gemini 2.5 Pro   | `gemini-2.5-pro`       | Strong capability | Hard problems, analysis      |
| Gemini 2.5 Flash | `gemini-2.5-flash`     | Very responsive   | Real-time chat, batch jobs   |

**GPT**

| Model name  | Model ID      | Characteristics | Good for                    |
| ----------- | ------------- | --------------- | --------------------------- |
| GPT-5       | `gpt-5`       | Top-tier        | Reasoning, creative writing |
| GPT-4o      | `gpt-4o`      | High quality    | General chat, content       |
| GPT-4o Mini | `gpt-4o-mini` | Cost-efficient  | Simple tasks, high volume   |

**Claude**

| Model name        | Model ID                     | Characteristics  | Good for               |
| ----------------- | ---------------------------- | ---------------- | ---------------------- |
| Claude Sonnet 4.5 | `claude-sonnet-4-5-20250929` | Strong reasoning | Code, logic            |
| Claude Haiku 4.5  | `claude-haiku-4-5-20251001`  | Very fast        | Q\&A, low-latency chat |

<Tip>
  **Quick picks:** - 🚀 **Google-style stack:** `gemini-2.0-flash-exp`, `gemini-2.5-pro` - 💡 **Coding:** `claude-sonnet-4-5-20250929`, `gpt-5` - 💰 **Cost:** `gpt-4o-mini`, `claude-haiku-4-5-20251001` - ⚡ **Speed:** `gemini-2.0-flash-exp`, `gpt-4o-mini`
</Tip>

## Advanced features

### Multimodal (images)

With a multimodal model such as Gemini 2.0 Flash:

```python theme={null}
response = openai.ChatCompletion.create(
    model="gemini-2.0-flash-exp",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What’s in this image?"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://example.com/image.jpg"
                    }
                }
            ]
        }
    ]
)
```

### Streaming

Stream tokens as they arrive:

```python theme={null}
stream = openai.ChatCompletion.create(
    model="gemini-2.0-flash-exp",
    messages=[{"role": "user", "content": "Write a short poem about spring"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end='')
```

### Tuning parameters

Shape randomness and length:

```python theme={null}
response = openai.ChatCompletion.create(
    model="gemini-2.0-flash-exp",
    messages=[{"role": "user", "content": "Your question"}],
    temperature=0.7,        # randomness (0–2)
    max_tokens=2000,        # max output length
    top_p=0.9,              # nucleus sampling
    presence_penalty=0,     # topic diversity
    frequency_penalty=0     # repetition penalty
)
```

## FAQ

### Q1: “Invalid API key” or auth errors

1. **Key format**
   * Must start with `sk-`
   * No extra spaces when pasting

2. **Environment variables**

   ```bash theme={null}
   # macOS / Linux
   echo $GEMINI_API_KEY
   echo $GEMINI_BASE_URL

   # Windows PowerShell
   echo $env:GEMINI_API_KEY
   echo $env:GEMINI_BASE_URL
   ```

3. **Key status**
   * Check the key in the [APIMart Console](https://apimart.ai/keys)
   * Ensure your account has balance

### Q2: How do I verify the API setup?

```python theme={null}
import openai

openai.api_key = "sk-xxxxxxxxxxxx"
openai.api_base = "https://api.apimart.ai/v1"

try:
    response = openai.ChatCompletion.create(
        model="gemini-2.0-flash-exp",
        messages=[{"role": "user", "content": "test"}],
        max_tokens=10
    )
    print("✅ API configuration OK")
    print(f"Reply: {response.choices[0].message.content}")
except Exception as e:
    print(f"❌ API configuration failed: {e}")
```

### Q3: Which languages are supported?

Any language that can send HTTP requests works with APIMart:

* ✅ **Python** — OpenAI SDK recommended
* ✅ **JavaScript / TypeScript** — Node or browser
* ✅ **Java** — HTTP client
* ✅ **Go** — stdlib or libraries
* ✅ **PHP** — cURL or Guzzle
* ✅ **Ruby** — HTTP gems
* ✅ **C# / .NET** — `HttpClient`
* ✅ **Swift** — `URLSession`
* ✅ **Others** — anything with HTTP

### Q4: Where can I see usage and billing?

In the [APIMart Console](https://apimart.ai/overview):

* 📊 Live call stats
* 💰 Cost and invoices
* 📈 Usage trends
* 🔍 Request logs
* ⚙️ API key management

### Q5: Common API errors

| Error                       | Likely cause           | What to do                                  |
| --------------------------- | ---------------------- | ------------------------------------------- |
| `401 Unauthorized`          | Bad or revoked key     | Fix key in env / console                    |
| `429 Too Many Requests`     | Rate limit             | Slow down or upgrade plan                   |
| `500 Internal Server Error` | Transient server issue | Retry later; contact support if it persists |
| `insufficient_quota`        | Low balance            | Top up in console                           |

## Best practices

### 1. Retries and backoff

```python theme={null}
import openai
import time

def call_with_retry(max_retries=3):
    for i in range(max_retries):
        try:
            response = openai.ChatCompletion.create(
                model="gemini-2.0-flash-exp",
                messages=[{"role": "user", "content": "Your question"}]
            )
            return response
        except openai.error.RateLimitError:
            if i < max_retries - 1:
                time.sleep(2 ** i)
                continue
            raise
        except Exception as e:
            print(f"Error: {e}")
            raise

response = call_with_retry()
```

### 2. Cost control

```python theme={null}
def choose_model(complexity):
    if complexity == "simple":
        return "gpt-4o-mini"
    elif complexity == "medium":
        return "gemini-2.0-flash-exp"
    return "gpt-5"

model = choose_model("simple")
response = openai.ChatCompletion.create(
    model=model,
    messages=[{"role": "user", "content": "Your question"}],
    max_tokens=500
)
```

### 3. System prompts

```python theme={null}
response = openai.ChatCompletion.create(
    model="gemini-2.0-flash-exp",
    messages=[
        {
            "role": "system",
            "content": "You are an expert Python assistant who writes clear, efficient code."
        },
        {
            "role": "user",
            "content": "Implement quicksort for me"
        }
    ]
)
```

## Features

With **Google AI Studio** and **APIMart** you get:

* 🤖 **Many models** — GPT, Claude, Gemini, and more
* 🌍 **OpenAI-compatible** — familiar request / response shape
* ⚡ **Performance** — low latency, high concurrency
* 💰 **Clear pricing** — pay as you go
* 📊 **Observability** — monitor calls in real time
* 🔒 **Security** — enterprise-oriented safeguards
* 🚀 **Fast integration** — simple HTTP / SDK calls
* 📚 **Docs** — guides and examples

## Support

* 📚 [APIMart documentation](https://docs.apimart.ai)
* 📚 [Google AI Studio documentation](https://ai.google.dev/docs)
* 💬 [Discord](https://discord.gg/V8zqssyZ5c)
* 🐦 [Twitter @APIMart\_](https://x.com/APIMart_)
* 📧 [zhihong@apimart.ai](mailto:zhihong@apimart.ai)

***

<Card title="Get started with APIMart" icon="rocket" href="https://apimart.ai">
  Create an account, grab an API key, and use multiple AI models from Google AI Studio workflows and beyond.
</Card>
