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:
Get an Access Token: Exchange your Client ID and Client Secret for a temporary bearer token, refreshing it when needed.
Make an API Call: Use the access token to make an authenticated request to the /chat/completions endpoint.
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.
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.
Copy
Ask AI
import timeimport requestsdef 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()
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:
import requestsimport timeimport base64import osfrom dotenv import load_dotenv#- Load environment variables from .env fileload_dotenv()#- --- Configuration ---#- It's recommended to load credentials from environment variablesCLIENT_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 informationaccess_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_datadef 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}")