This API is deprecated. Follow the Completions V2 API tutorial instead.
- Get an API Key: Create an API key in Gloo AI Studio.
- Make an API Call: Use the API key to make an authenticated request to the
/chat/completionsendpoint.
Prerequisites
Before starting, ensure you have:- A Gloo AI Studio account
- Your API key from the API Credentials page
- Authentication setup - Complete the Authentication Tutorial first
The Completions API requires an API key for authentication.
Make a Chat Completion Call
Once you have a valid API key (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 make_chat_completion_request(api_key="YOUR_API_KEY"):
"""Makes a chat completion request using the API key."""
api_url = "https://platform.ai.gloo.com/ai/v1/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"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()
const axios = require('axios');
// const API_KEY = process.env.GLOO_API_KEY;
async function makeChatCompletionRequest() {
try {
const apiUrl = "https://platform.ai.gloo.com/ai/v1/chat/completions";
const payload = {
model: "us.anthropic.claude-sonnet-4-20250514-v1:0",
messages: [
{ role: "user", content: "How can I be joyful in hard times?" },
],
};
const response = await axios.post(apiUrl, payload, {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
});
return response.data;
} catch (error) {
console.error("Error making chat completion request:", error.response ? error.response.data : error.message);
throw error;
}
}
import axios from 'axios';
// Type definitions
interface ChatCompletionRequest {
model: string;
messages: Array<{ role: string; content: string }>;
}
interface ChatCompletionResponse {
choices: Array<{
message: {
role: string;
content: string;
};
}>;
}
// const API_KEY = process.env.GLOO_API_KEY;
async function makeChatCompletionRequest(): Promise<ChatCompletionResponse> {
try {
const apiUrl = "https://platform.ai.gloo.com/ai/v1/chat/completions";
const payload: ChatCompletionRequest = {
model: "us.anthropic.claude-sonnet-4-20250514-v1:0",
messages: [
{ role: "user", content: "How can I be joyful in hard times?" },
],
};
const response = await axios.post<ChatCompletionResponse>(apiUrl, payload, {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
});
return response.data;
} catch (error: any) {
console.error("Error making chat completion request:", error.response ? error.response.data : error.message);
throw error;
}
}
<?php
function makeChatCompletionRequest($apiKey) {
$apiUrl = 'https://platform.ai.gloo.com/ai/v1/chat/completions';
$payload = json_encode([
'model' => 'us.anthropic.claude-sonnet-4-20250514-v1:0',
'messages' => [
['role' => 'user', 'content' => 'How can I be joyful in hard times?']
]
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception(curl_error($ch));
}
curl_close($ch);
return json_decode($result, true);
}
?>
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func makeChatCompletionRequest() (map[string]interface{}, error) {
apiUrl := "https://platform.ai.gloo.com/ai/v1/chat/completions"
payload := map[string]interface{}{
"model": "us.anthropic.claude-sonnet-4-20250514-v1:0",
"messages": []map[string]string{
{"role": "user", "content": "How can I be joyful in hard times?"},
},
}
jsonPayload, _ := json.Marshal(payload)
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonPayload))
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+apiKey)
req.Header.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API call failed: %s - %s", resp.Status, string(body))
}
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.google.gson.Gson;
public class GlooApiClient {
public static String makeChatCompletionRequest() throws IOException, InterruptedException {
String apiUrl = "https://platform.ai.gloo.com/ai/v1/chat/completions";
String payload = """
{
"model": "us.anthropic.claude-sonnet-4-20250514-v1:0",
"messages": [
{
"role": "user",
"content": "How can I be joyful in hard times?"
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + API_KEY)
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IOException("API call failed: " + response.body());
}
return response.body();
}
}
Complete Examples
The following examples combine the API key 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_API_KEY=YOUR_API_KEY
export GLOO_API_KEY="your_actual_api_key_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
API_KEY = os.getenv("GLOO_API_KEY", "YOUR_API_KEY")
API_URL = "https://platform.ai.gloo.com/ai/v1/chat/completions"
# --- Function Definitions ---
def make_chat_completion_request():
"""Makes a chat completion request using the API key."""
headers = {
"Authorization": f"Bearer {API_KEY}",
"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...")
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}")
// Load environment variables from .env file
require('dotenv').config();
const axios = require('axios');
// --- Configuration ---
const API_KEY = process.env.GLOO_API_KEY || "YOUR_API_KEY";
const API_URL = "https://platform.ai.gloo.com/ai/v1/chat/completions";
// --- Function Definitions ---
async function makeChatCompletionRequest() {
const payload = {
model: "us.anthropic.claude-sonnet-4-20250514-v1:0",
messages: [{ role: "user", content: "How can I be joyful in hard times?" }],
};
const response = await axios.post(API_URL, payload, {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
});
return response.data;
}
// --- Main Execution ---
async function main() {
try {
console.log("Making first API call...");
const completion1 = await makeChatCompletionRequest();
console.log("First call successful:", completion1.choices[0].message.content);
console.log("\nMaking second API call...");
const completion2 = await makeChatCompletionRequest();
console.log("Second call successful:", completion2.choices[0].message.content);
} catch (error) {
console.error("An error occurred:", error.response ? error.response.data : error.message);
}
}
main();
import axios from 'axios';
import * as dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();
// Type definitions
interface ChatCompletionRequest {
model: string;
messages: Array<{ role: string; content: string }>;
}
interface ChatCompletionResponse {
choices: Array<{
message: {
role: string;
content: string;
};
}>;
}
// --- Configuration ---
const API_KEY = process.env.GLOO_API_KEY || "YOUR_API_KEY";
const API_URL = "https://platform.ai.gloo.com/ai/v1/chat/completions";
// --- Function Definitions ---
async function makeChatCompletionRequest(): Promise<ChatCompletionResponse> {
const payload: ChatCompletionRequest = {
model: "us.anthropic.claude-sonnet-4-20250514-v1:0",
messages: [{ role: "user", content: "How can I be joyful in hard times?" }],
};
const response = await axios.post<ChatCompletionResponse>(API_URL, payload, {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
});
return response.data;
}
// --- Main Execution ---
async function main(): Promise<void> {
try {
console.log("Making first API call...");
const completion1 = await makeChatCompletionRequest();
console.log("First call successful:", completion1.choices[0].message.content);
console.log("\nMaking second API call...");
const completion2 = await makeChatCompletionRequest();
console.log("Second call successful:", completion2.choices[0].message.content);
} catch (error: any) {
console.error("An error occurred:", error.response ? error.response.data : error.message);
}
}
main();
<?php
// --- main.php ---
require_once 'vendor/autoload.php';
// Load .env file
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
// --- Configuration ---
$API_KEY = getenv('GLOO_API_KEY') ?: 'YOUR_API_KEY';
$API_URL = 'https://platform.ai.gloo.com/ai/v1/chat/completions';
// --- Function Definitions ---
function makeChatCompletionRequest($apiUrl, $apiKey) {
$payload = json_encode([
'model' => 'us.anthropic.claude-sonnet-4-20250514-v1:0',
'messages' => [['role' => 'user', 'content' => 'How can I be joyful in hard times?']]
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
]);
$result = curl_exec($ch);
if (curl_errno($ch)) throw new Exception(curl_error($ch));
curl_close($ch);
return json_decode($result, true);
}
// --- Main Execution ---
try {
echo "Making first API call...\n";
$completion1 = makeChatCompletionRequest($API_URL, $API_KEY);
echo "First call successful: " . $completion1['choices'][0]['message']['content'] . "\n";
echo "\nMaking second API call...\n";
$completion2 = makeChatCompletionRequest($API_URL, $API_KEY);
echo "Second call successful: " . $completion2['choices'][0]['message']['content'] . "\n";
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
// --- Configuration ---
var (
apiKey = getEnv("GLOO_API_KEY", "YOUR_API_KEY")
apiURL = "https://platform.ai.gloo.com/ai/v1/chat/completions"
)
// --- Function Definitions ---
func makeChatCompletionRequest() (map[string]interface{}, error) {
payload := map[string]interface{}{
"model": "us.anthropic.claude-sonnet-4-20250514-v1:0",
"messages": []map[string]string{
{"role": "user", "content": "How can I be joyful in hard times?"},
},
}
jsonPayload, _ := json.Marshal(payload)
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonPayload))
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+apiKey)
req.Header.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API call failed: %s - %s", resp.Status, string(body))
}
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
// Helper to get environment variables
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
// --- Main Execution ---
func main() {
fmt.Println("Making first API call...")
completion1, err := makeChatCompletionRequest()
if err != nil {
fmt.Println("Error on first call:", err)
return
}
// Safely parse the response
if choices, ok := completion1["choices"].([]interface{}); ok && len(choices) > 0 {
if choice, ok := choices[0].(map[string]interface{}); ok {
if message, ok := choice["message"].(map[string]interface{}); ok {
fmt.Println("First call successful:", message["content"])
}
}
}
fmt.Println("\nMaking second API call...")
completion2, err := makeChatCompletionRequest()
if err != nil {
fmt.Println("Error on second call:", err)
return
}
if choices, ok := completion2["choices"].([]interface{}); ok && len(choices) > 0 {
if choice, ok := choices[0].(map[string]interface{}); ok {
if message, ok := choice["message"].(map[string]interface{}); ok {
fmt.Println("Second call successful:", message["content"])
}
}
}
}
import com.google.gson.Gson;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
// --- Main Application Class ---
public class Main {
public static void main(String[] args) {
GlooApiClient client = new GlooApiClient();
try {
System.out.println("Making first API call...");
String content1 = client.getChatCompletionContent();
System.out.println("First call successful: " + content1);
System.out.println("\nMaking second API call...");
String content2 = client.getChatCompletionContent();
System.out.println("Second call successful: " + content2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// --- API Client Class (GlooApiClient.java) ---
class GlooApiClient {
private static final String API_KEY = System.getenv().getOrDefault("GLOO_API_KEY", "YOUR_API_KEY");
private static final String API_URL = "https://platform.ai.gloo.com/ai/v1/chat/completions";
private final HttpClient httpClient = HttpClient.newHttpClient();
private final Gson gson = new Gson();
// --- Public Method ---
public String getChatCompletionContent() throws IOException, InterruptedException {
String payload = "{\"model\": \"us.anthropic.claude-sonnet-4-20250514-v1:0\", \"messages\": [{\"role\": \"user\", \"content\": \"How can I be joyful in hard times?\"}]}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + API_KEY)
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) throw new IOException("API call failed: " + response.body());
// Parse the response to extract the message content
Map<String, Object> responseMap = gson.fromJson(response.body(), Map.class);
List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
return (String) message.get("content");
}
}
Working Code Sample
View Complete Code
Clone or browse the complete working examples for all 6 languages (JavaScript, TypeScript, Python, PHP, Go, Java) with setup instructions.
Next Steps
Now that you understand how to use the Completions API, consider exploring:- Authentication Tutorial - For detailed authentication setup
- Completions API - For additional API information
- Chat Tutorial - For stateful chat interactions
- Tool Use - For enhanced completion capabilities

