> ## 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.

# Usando o APIMart com o Gemini CLI

> Guia detalhado sobre como configurar o serviço de API do APIMart na ferramenta de linha de comando Gemini CLI. Aprenda como usar os modelos de IA do APIMart — incluindo as séries Gemini, GPT e Claude — a partir do terminal.

## Introdução

Gemini CLI é a ferramenta oficial de linha de comando do Google que permite aos desenvolvedores interagir com os modelos de IA Gemini a partir do terminal. Após configurar a API do APIMart, você pode usar os modelos avançados do APIMart — GPT, Claude e Gemini — no Gemini CLI.

## Pré-requisitos

Antes de começar:

1. **Node.js e npm instalados**\
   Baixe e instale do [site do Node.js](https://nodejs.org/) (v16 ou superior recomendado)

2. **Chave de API do APIMart**\
   Faça login no [Console do APIMart](https://apimart.ai/keys) e copie sua chave de API (começa com `sk-`)

<Note>
  **Dica:** Se você ainda não tem uma conta no APIMart, registre-se primeiro em [APIMart](https://apimart.ai) e crie uma chave de API.
</Note>

## Etapa 1: Instalar o Gemini CLI

### 1.1 Instalação global

Instale o Gemini CLI globalmente com o npm:

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

### 1.2 Verificar a instalação

Verifique se o CLI está disponível:

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

Se um número de versão for impresso, a instalação foi bem-sucedida.

<Note>**Dica:** Se o comando não for encontrado, reinicie o terminal ou verifique a configuração global do `PATH` do npm.</Note>

## Etapa 2: Configurar a API do APIMart

### 2.1 Variáveis de ambiente temporárias

Para testes ou uso único; os valores são limpos quando você fecha o 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 Variáveis de ambiente permanentes (recomendado)

Persista a configuração para que novos shells a captem automaticamente.

**Windows (PowerShell):**

1. Execute o PowerShell como Administrador
2. Defina variáveis de ambiente no nível do usuário:

```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. Reinicie o PowerShell ou recarregue as variáveis:

```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. Edite o arquivo rc do seu shell:

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

# Zsh (padrão no macOS)
nano ~/.zshrc
```

2. Anexe:

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

3. Recarregue:

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

### 2.3 Usando um arquivo `.env`

Crie um arquivo `.env` no seu projeto:

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

Carregue as variáveis antes de executar o 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>
  **Importante:** - Substitua `sk-xxxxxxxxxxxx` pela sua chave real do [Console do APIMart](https://apimart.ai/keys) - Defina `GEMINI_BASE_URL` como `https://api.apimart.ai/v1` para que o Gemini CLI se comunique com o APIMart - Adicione `.env` ao `.gitignore` para que as chaves não sejam commitadas
</Note>

### 2.4 Verificar a configuração

**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
```

Se os valores parecerem corretos, a configuração foi bem-sucedida.

## Etapa 3: Usar o Gemini CLI

### 3.1 Chat básico

Sessão interativa:

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

Prompt único:

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

### 3.2 Escolher um modelo

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

Ou:

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

### 3.3 Ler prompts de um arquivo

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

Ou via pipe:

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

### 3.4 Salvar saída em um arquivo

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

## Etapa 4: Chamar o APIMart a partir do seu código

### 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"}
    ]
  }'
```

## Etapa 5: Escolher um modelo

### Modelos recomendados

O APIMart suporta muitos modelos; escolha por tarefa e orçamento.

**Gemini**

| Nome do modelo   | ID do modelo           | Características    | Bom para                            |
| ---------------- | ---------------------- | ------------------ | ----------------------------------- |
| Gemini 2.0 Flash | `gemini-2.0-flash-exp` | Rápido, multimodal | Respostas rápidas, visão + texto    |
| Gemini 2.5 Pro   | `gemini-2.5-pro`       | Capacidade forte   | Problemas difíceis, análise         |
| Gemini 2.5 Flash | `gemini-2.5-flash`     | Muito responsivo   | Chat em tempo real, tarefas em lote |

**GPT**

| Nome do modelo | ID do modelo  | Características | Bom para                     |
| -------------- | ------------- | --------------- | ---------------------------- |
| GPT-5          | `gpt-5`       | Topo de linha   | Raciocínio, escrita criativa |
| GPT-4o         | `gpt-4o`      | Alta qualidade  | Chat geral, conteúdo         |
| GPT-4o Mini    | `gpt-4o-mini` | Econômico       | Tarefas simples, alto volume |

**Claude**

| Nome do modelo    | ID do modelo                 | Características  | Bom para                     |
| ----------------- | ---------------------------- | ---------------- | ---------------------------- |
| Claude Sonnet 4.5 | `claude-sonnet-4-5-20250929` | Raciocínio forte | Código, lógica               |
| Claude Haiku 4.5  | `claude-haiku-4-5-20251001`  | Muito rápido     | Q\&A, chat de baixa latência |

<Tip>
  **Escolhas rápidas:** - 🚀 **Stack estilo Google:** `gemini-2.0-flash-exp`, `gemini-2.5-pro` - 💡 **Programação:** `claude-sonnet-4-5-20250929`, `gpt-5` - 💰 **Custo:** `gpt-4o-mini`, `claude-haiku-4-5-20251001` - ⚡ **Velocidade:** `gemini-2.0-flash-exp`, `gpt-4o-mini`
</Tip>

## Recursos avançados

### Multimodal (imagens)

Com um modelo multimodal como 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

Transmita tokens conforme chegam:

```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='')
```

### Ajustando parâmetros

Modele aleatoriedade e comprimento:

```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" ou erros de autenticação

1. **Formato da chave**
   * Deve começar com `sk-`
   * Sem espaços extras ao colar

2. **Variáveis de ambiente**

   ```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. **Status da chave**
   * Verifique a chave no [Console do APIMart](https://apimart.ai/keys)
   * Verifique se sua conta tem saldo

### Q2: Como verificar a configuração da API?

```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: Quais linguagens são suportadas?

Qualquer linguagem que possa enviar requisições HTTP funciona com o APIMart:

* ✅ **Python** — OpenAI SDK recomendado
* ✅ **JavaScript / TypeScript** — Node ou navegador
* ✅ **Java** — cliente HTTP
* ✅ **Go** — stdlib ou bibliotecas
* ✅ **PHP** — cURL ou Guzzle
* ✅ **Ruby** — gems HTTP
* ✅ **C# / .NET** — `HttpClient`
* ✅ **Swift** — `URLSession`
* ✅ **Outras** — qualquer uma com HTTP

### Q4: Onde posso ver o uso e o faturamento?

No [Console do APIMart](https://apimart.ai/overview):

* 📊 Estatísticas de chamadas ao vivo
* 💰 Custo e faturas
* 📈 Tendências de uso
* 🔍 Logs de requisições
* ⚙️ Gerenciamento de chave de API

### Q5: Erros comuns de API

| Erro                        | Causa provável                   | O que fazer                                                             |
| --------------------------- | -------------------------------- | ----------------------------------------------------------------------- |
| `401 Unauthorized`          | Chave inválida ou revogada       | Corrija a chave no env / console                                        |
| `429 Too Many Requests`     | Limite de taxa                   | Desacelere ou faça upgrade do plano                                     |
| `500 Internal Server Error` | Problema transitório no servidor | Tente novamente mais tarde; entre em contato com o suporte se persistir |
| `insufficient_quota`        | Saldo baixo                      | Recarregue no console                                                   |

## Melhores práticas

### 1. Retentativas e 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. Controle de custos

```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. Prompts de sistema

```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"
        }
    ]
)
```

## Recursos

Com **Google AI Studio** e **APIMart** você obtém:

* 🤖 **Muitos modelos** — GPT, Claude, Gemini e mais
* 🌍 **Compatível com OpenAI** — formato familiar de requisição/resposta
* ⚡ **Desempenho** — baixa latência, alta concorrência
* 💰 **Preços claros** — pague conforme usar
* 📊 **Observabilidade** — monitore chamadas em tempo real
* 🔒 **Segurança** — proteções voltadas para empresas
* 🚀 **Integração rápida** — chamadas HTTP / SDK simples
* 📚 **Documentação** — guias e exemplos

## Suporte

* 📚 [Documentação do APIMart](https://docs.apimart.ai)
* 📚 [Documentação do Google AI Studio](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="Comece a usar o APIMart" icon="rocket" href="https://apimart.ai">
  Crie uma conta, obtenha uma chave de API e use vários modelos de IA a partir dos fluxos de trabalho do Google AI Studio e além.
</Card>
