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

# Obtener información de la cuenta vía API

> Gestiona claves, consulta cuentas y listas de modelos disponibles desde la línea de comandos usando el script utilitario CLI de AiHubMix.

El CLI de AiHubMix es una colección de scripts utilitarios que te permite gestionar tus claves API de AiHubMix, consultar información de la cuenta y usar los servicios de IA sin necesidad de pasar por una interfaz web. En esencia, encapsula las llamadas a la API (usando curl o requests de Python) para mayor comodidad en la línea de comandos.

<Tip>
  Se recomienda usar la nueva generación de herramienta de línea de comandos [AIHubMix CLI (herramienta de línea de comandos)](/es/api/aihubmix-cli): un único binario, sin dependencias de tiempo de ejecución (no requiere Python), con comandos orientados a recursos como `aihubmix keys list` y salida amigable para `jq` y agentes de IA. Esta página conserva el uso del script Python antiguo como referencia.
</Tip>

## Requisitos previos

Antes de usar el CLI de AiHubMix necesitas:

1. Una [cuenta de AIHubMix](https://aihubmix.com)
2. Generar un Access Token haciendo clic en "Generate System Access Token" en la [página de Ajustes de AIHubMix](https://aihubmix.com/setting);
3. Instalar las dependencias de Python necesarias:

```bash theme={null}
pip install -U requests openai
```

<Info>
  El script aihubmix\_cli.py puede [descargarse aquí](https://github.com/jerlinn/inferHub)
</Info>

## Descripción general de funciones

El CLI de AIHubMix ofrece las siguientes funcionalidades clave:

### Resumen de endpoints de la API

| Endpoint                     | Método HTTP | Descripción                                                    |
| ---------------------------- | ----------- | -------------------------------------------------------------- |
| `/api/user/self`             | GET         | Obtener información del usuario actual y saldo de la cuenta    |
| `/api/token/`                | GET         | Obtener una lista de todas las claves                          |
| `/api/token/`                | POST        | Crear una nueva clave API                                      |
| `/api/token/`                | PUT         | Actualizar una clave API existente                             |
| `/api/token/{token_id}`      | GET         | Obtener información detallada de una clave específica          |
| `/api/token/{token_id}`      | DELETE      | Eliminar una clave específica                                  |
| `/api/token/search`          | GET         | Buscar claves (usa `?keyword=search_term`)                     |
| `/api/user/token`            | GET         | Obtener claves del usuario                                     |
| `/api/user/available_models` | GET         | Obtener la lista de modelos disponibles para el usuario actual |

### Obtener información del saldo

<CodeGroup>
  ```shell theme={null}
  # Using curl to retrieve balance, balance is quota / 500000
  curl -X GET "https://aihubmix.com/api/user/self" \
    -H "Authorization: YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```py theme={null}
  import requests
  import json

  # API Configuration
  api_url = "https://aihubmix.com"
  access_token = "YOUR_ACCESS_TOKEN"
  headers = {
      "Authorization": access_token,
      "Content-Type": "application/json"
  }

  # Retrieve account balance
  response = requests.get(f"{api_url}/api/user/self", headers=headers)
  if response.status_code == 200:
      data = response.json()
      if data.get("success", False):
          user_data = data.get("data", {})
          quota = user_data.get('quota', 0)
          usd_balance = quota / 500000  # $1 equals 500,000 quota
          print(f"Username: {user_data.get('username', 'Unknown')}")
          print(f"Display Name: {user_data.get('display_name', 'Unknown')}")
          print(f"Current Quota: {quota}")
          print(f"Available USD: ${usd_balance:.2f}")
      else:
          print(f"Request failed: {data.get('message', 'Unknown error')}")
  else:
      print(f"Request failed, status code: {response.status_code}")
  ```

  ```shell theme={null}
  python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_balance
  ```

  ```shell theme={null}
  # Retrieve remaining quota for Key
  curl 'https://aihubmix.com/dashboard/billing/remain' \
    -H 'authorization: Bearer sk-***' \
  ```
</CodeGroup>

### Gestión de claves

#### Crear una nueva clave

<CodeGroup>
  ```shell theme={null}
  curl -X POST "https://aihubmix.com/api/token/" \
    -H "Authorization: YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "New Key Name",
      "expired_time": -1,
      "remain_quota": 500000,
      "unlimited_quota": false,
      "subnet": ""
    }'
  ```

  ```py theme={null}
  import requests
  import json

  # API Configuration
  api_url = "https://aihubmix.com"
  access_token = "YOUR_ACCESS_TOKEN"
  headers = {
      "Authorization": access_token,
      "Content-Type": "application/json"
  }

  # Create New Key
  payload = {
      "name": "New Key Name",
      "expired_time": -1,  # Never expires
      "remain_quota": 500000,
      "unlimited_quota": False,
      "subnet": ""
  }

  response = requests.post(f"{api_url}/api/token/", headers=headers, json=payload)
  if response.status_code == 200:
      data = response.json()
      if data.get("success", False):
          token_data = data.get("data", {})
          print(f"New Key: {token_data.get('key', 'Unknown')}")
          print(f"Key ID: {token_data.get('id', 'Unknown')}")
      else:
          print(f"Failed to create Key: {data.get('message', 'Unknown error')}")
  else:
      print(f"Request failed, status code: {response.status_code}")
  ```

  ```shell theme={null}
  python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action create_token --name "New Key Name" --expires -1 --quota 500000
  ```
</CodeGroup>

#### Obtener la lista de claves

<CodeGroup>
  ```shell theme={null}
  curl -X GET "https://aihubmix.com/api/token/?num=20" \ # Adjust num parameter to change the number of output data.
    -H "Authorization: YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```py theme={null}
  import requests
  import json

  # API Configuration
  api_url = "https://aihubmix.com"
  access_token = "YOUR_ACCESS_TOKEN"
  headers = {
      "Authorization": access_token,
      "Content-Type": "application/json"
  }

  # Retrieve Key List
  response = requests.get(f"{api_url}/api/token/", headers=headers)
  if response.status_code == 200:
      data = response.json()
      if data.get("success", False):
          tokens_data = data.get("data", [])
          print(f"Key List (Total {len(tokens_data)}):")
          for token in tokens_data:
              print(f"Key ID: {token.get('id', 'Unknown')}")
              print(f"Key Name: {token.get('name', 'Unknown')}")
              print(f"Key: {token.get('key', 'Unknown')}")
              print("---")
      else:
          print(f"Failed to retrieve Key list: {data.get('message', 'Unknown error')}")
  else:
      print(f"Request failed, status code: {response.status_code}")
  ```

  ```shell theme={null}
  python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_tokens
  ```
</CodeGroup>

#### Buscar una clave

<CodeGroup>
  ```shell theme={null}
  curl -X GET "https://aihubmix.com/api/token/search?keyword=search_term" \
    -H "Authorization: YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```py theme={null}
  import requests
  import json

  # API Configuration
  api_url = "https://aihubmix.com"
  access_token = "YOUR_ACCESS_TOKEN"
  headers = {
      "Authorization": access_token,
      "Content-Type": "application/json"
  }

  # Search Keyword
  query = "search_term"

  # Search Key
  response = requests.get(f"{api_url}/api/token/search?keyword={query}", headers=headers)
  if response.status_code == 200:
      data = response.json()
      if data.get("success", False):
          tokens_data = data.get("data", [])
          print(f"Search Results (Total {len(tokens_data)}):")
          for token in tokens_data:
              print(f"Key ID: {token.get('id', 'Unknown')}")
              print(f"Key Name: {token.get('name', 'Unknown')}")
              print(f"Key: {token.get('key', 'Unknown')}")
              print("---")
      else:
          print(f"Failed to search Key: {data.get('message', 'Unknown error')}")
  else:
      print(f"Request failed, status code: {response.status_code}")
  ```

  ```shell theme={null}
  python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action search_tokens --query "search_term"
  ```
</CodeGroup>

#### Actualizar una clave

<CodeGroup>
  ```shell theme={null}
  curl -X PUT "https://aihubmix.com/api/token/" \
    -H "Authorization: YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "id": "Key_ID",
      "name": "New Name",
      "expired_time": 86400,
      "remain_quota": 100000,
      "status": 1
    }'
  ```

  ```py theme={null}
  import requests
  import json

  # API Configuration
  api_url = "https://aihubmix.com"
  access_token = "YOUR_ACCESS_TOKEN"
  headers = {
      "Authorization": access_token,
      "Content-Type": "application/json"
  }

  # Update Key
  key_id = "Key_ID"  # Replace with the actual Key ID
  payload = {
      "id": key_id,
      "name": "New Name",
      "expired_time": 86400,  # Expires after 24 hours
      "remain_quota": 100000,
      "status": 1  # 1-Enabled, 0-Disabled
  }

  response = requests.put(f"{api_url}/api/token/", headers=headers, json=payload)
  if response.status_code == 200:
      data = response.json()
      if data.get("success", False):
          print(f"Key updated successfully")
          if "data" in data:
              token_data = data.get("data", {})
              print(f"Name: {token_data.get('name', 'Unknown')}")
              print(f"Expiration Time: {token_data.get('expired_time', 'Unknown')}")
      else:
          print(f"Failed to update Key: {data.get('message', 'Unknown error')}")
  else:
      print(f"Request failed, status code: {response.status_code}")
  ```

  ```shell theme={null}
  python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action update_token --id "Key_ID" --name "New Name" --expires 86400 --quota 100000 --status 1
  ```
</CodeGroup>

#### Eliminar una clave

<CodeGroup>
  ```shell theme={null}
  curl -X DELETE "https://aihubmix.com/api/token/Key_ID" \
    -H "Authorization: YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```py theme={null}
  import requests
  import json

  # API Configuration
  api_url = "https://aihubmix.com"
  access_token = "YOUR_ACCESS_TOKEN"
  headers = {
      "Authorization": access_token,
      "Content-Type": "application/json"
  }

  # Delete Key
  key_id = "Key_ID"  # Replace with the actual Key ID

  response = requests.delete(f"{api_url}/api/token/{key_id}", headers=headers)
  if response.status_code == 200:
      data = response.json()
      if data.get("success", False):
          print(f"Key deleted successfully")
      else:
          print(f"Failed to delete Key: {data.get('message', 'Unknown error')}")
  else:
      print(f"Request failed, status code: {response.status_code}")
  ```

  ```shell theme={null}
  python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action delete_token --id "Key_ID"
  ```
</CodeGroup>

#### Obtener la clave del usuario

<CodeGroup>
  ```shell theme={null}
  curl -X GET "https://aihubmix.com/api/user/token" \
    -H "Authorization: YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```py theme={null}
  import requests
  import json

  # API Configuration
  api_url = "https://aihubmix.com"
  access_token = "YOUR_ACCESS_TOKEN"
  headers = {
      "Authorization": access_token,
      "Content-Type": "application/json"
  }

  # Retrieve User Key
  response = requests.get(f"{api_url}/api/user/token", headers=headers)
  if response.status_code == 200:
      data = response.json()
      if data.get("success", False):
          user_token = data.get("data", {}).get("token")
          print(f"User Key: {user_token}")
      else:
          print(f"Failed to retrieve User Key: {data.get('message', 'Unknown error')}")
  else:
      print(f"Request failed, status code: {response.status_code}")
  ```

  ```shell theme={null}
  python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_user_token
  ```
</CodeGroup>

### Gestión de modelos

#### Obtener los modelos disponibles del usuario

<CodeGroup>
  ```shell theme={null}
  curl -X GET "https://aihubmix.com/api/user/available_models" \
    -H "Authorization: YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```py theme={null}
  import requests
  import json

  # API Configuration
  api_url = "https://aihubmix.com"
  access_token = "YOUR_ACCESS_TOKEN"
  headers = {
      "Authorization": access_token,
      "Content-Type": "application/json"
  }

  # Retrieve User's Available Models
  response = requests.get(f"{api_url}/api/user/available_models", headers=headers)
  if response.status_code == 200:
      data = response.json()
      if data.get("success", False):
          models_data = data.get("data", [])
          print(f"User's Available Model List (Total {len(models_data)}):")
          for i, model in enumerate(models_data, 1):
              print(f"  {i}. {model}")
      else:
          print(f"Failed to retrieve user's available models: {data.get('message', 'Unknown error')}")
  else:
      print(f"Request failed, status code: {response.status_code}")
  ```

  ```shell theme={null}
  python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_available_models
  ```
</CodeGroup>

## Salida en formato JSON

Todos los comandos del CLI admiten la salida de resultados en formato JSON, lo que facilita su procesamiento programático:

```bash theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_balance --json
```

## Resolución de problemas

Si encuentras problemas, puedes probar las siguientes soluciones:

1. **Problemas de conexión**: Si falla la conexión al dominio principal, intenta usar un dominio alternativo:

   ```bash theme={null}
   python aihubmix_cli.py --url "https://api.aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_balance
   ```
2. **Access Token no válido**: Asegúrate de que el access token proporcionado sea una clave válida obtenida del sitio web de AIHubMix. El formato del access token suele ser similar a `fd***`.
3. **Permisos insuficientes**: Algunas operaciones pueden requerir permisos específicos; asegúrate de que tu cuenta tenga los permisos adecuados.
4. **Fallo de la solicitud**: Comprueba tu conexión de red o inténtalo más tarde.

## Notas

* El access token es distinto de la clave API regular utilizada para acceder a los modelos de IA.
* Cada usuario tiene su propio access token del sistema, y el nivel de acceso lo determina el rol del usuario (usuario regular, administrador o usuario root).

***

Última actualización: 2026-06-01
