This guide provides a practical, step-by-step guide for authenticating with the Gloo AI API and making a basic call to the Chat Completions endpoint. The process involves two main steps:
  1. Get an Access Token: Exchange your Client ID and Client Secret for a temporary bearer token, refreshing it when needed.
  2. Make an API Call: Use the access token to make an authenticated request to the /chat/completions endpoint.

Prerequisites

Before starting, ensure you have:
The Completions API requires Bearer token authentication. If you haven’t set up authentication yet, follow the Authentication Tutorial to learn how to exchange your credentials for access tokens and manage token expiration.

Make a Chat Completion Call

Once you have a valid access token (using the authentication methods from the Authentication Tutorial), you can call the Completions API. The examples below show a basic request.
import time
import requests

def is_token_expired(token_info):
    """Checks if the token is expired or close to expiring."""
    if not token_info or 'expires_at' not in token_info:
        return True
    #- Check if expired, with a 60-second buffer
    return time.time() > (token_info['expires_at'] - 60)

def make_chat_completion_request(token_info):
    """Makes a chat completion request, refreshing the token if needed."""

    if is_token_expired(token_info):
        print("Token is expired or missing. Fetching a new one...")
        token_info = get_access_token()

    api_url = "https://platform.ai.gloo.com/ai/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {token_info['access_token']}",
        "Content-Type": "application/json"
    }

    payload = {
        "model": "us.anthropic.claude-sonnet-4-20250514-v1:0",
        "messages": [
            {"role": "user", "content": "How can I be joyful in hard times?"}
        ]
    }

    response = requests.post(api_url, headers=headers, json=payload)
    response.raise_for_status()

    return response.json()

Complete Examples

The following examples combine token retrieval, expiration checking, and the API call into a single, runnable script for each language. You’ll want to first set up your environment variables in either an .env file:
GLOO_CLIENT_ID=YOUR_CLIENT_ID
GLOO_CLIENT_SECRET=YOUR_CLIENT_SECRET
Or export them in your shell for Go and Java:
export GLOO_CLIENT_ID="your_actual_client_id_here"
export GLOO_CLIENT_SECRET="your_actual_client_secret_here"
import requests
import time
import base64
import os
from dotenv import load_dotenv

#- Load environment variables from .env file
load_dotenv()

#- --- Configuration ---
#- It's recommended to load credentials from environment variables
CLIENT_ID = os.getenv("GLOO_CLIENT_ID", "YOUR_CLIENT_ID")
CLIENT_SECRET = os.getenv("GLOO_CLIENT_SECRET", "YOUR_CLIENT_SECRET")
TOKEN_URL = "https://platform.ai.gloo.com/oauth2/token"
API_URL = "https://platform.ai.gloo.com/ai/v1/chat/completions"

#- --- State Management ---
#- In a real application, you would persist this token information
access_token_info = {}

#- --- Function Definitions ---
def get_access_token():
    """Retrieves a new access token."""
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    data = {"grant_type": "client_credentials", "scope": "api/access"}
    response = requests.post(TOKEN_URL, headers=headers, data=data, auth=(CLIENT_ID, CLIENT_SECRET))
    response.raise_for_status()
    token_data = response.json()
    token_data['expires_at'] = int(time.time()) + token_data['expires_in']
    return token_data

def is_token_expired(token_info):
    """Checks if the token is expired or close to expiring."""
    if not token_info or 'expires_at' not in token_info:
        return True
    return time.time() > (token_info['expires_at'] - 60)

def make_chat_completion_request():
    """Makes a chat completion request, refreshing the token if needed."""
    global access_token_info
    if is_token_expired(access_token_info):
        print("Token is expired or missing. Fetching a new one...")
        access_token_info = get_access_token()

    headers = {
        "Authorization": f"Bearer {access_token_info['access_token']}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": "us.anthropic.claude-sonnet-4-20250514-v1:0",
        "messages": [{"role": "user", "content": "How can I be joyful in hard times?"}]
    }
    response = requests.post(API_URL, headers=headers, json=payload)
    response.raise_for_status()
    return response.json()

#- --- Main Execution ---
if __name__ == "__main__":
    try:
        print("Making first API call...")
        completion1 = make_chat_completion_request()
        print("First call successful:", completion1['choices'][0]['message']['content'])

        print("\nMaking second API call (should use cached token)...")
        completion2 = make_chat_completion_request()
        print("Second call successful:", completion2['choices'][0]['message']['content'])
    except requests.exceptions.HTTPError as err:
        print(f"An HTTP error occurred: {err}")
    except Exception as err:
        print(f"An error occurred: {err}")

Next Steps

Now that you understand how to use the Completions API, consider exploring:
  1. Authentication Tutorial - For detailed authentication setup
  2. Completions API - For additional API information
  3. Chat Tutorial - For stateful chat interactions
  4. Tool Use - For enhanced completion capabilities