Learn how to integrate with the Completions V2 API: pin a model, choose a model family, or opt in to auto-routing.
This step-by-step tutorial covers the Gloo AI Completions V2 API and its model selection options.Want the concepts first? Read the Concepts guide.
Why V2? Completions V2 lets you pin a specific model, choose a model family, or opt in to auto-routing, and supports tradition-aware responses—all while maintaining compatibility with the standard chat completions format.
What you’ll build
A small script that sends one chat request per model-selection mode, then reads the routing metadata and streams the answer:
Pin a model
Choose a model family
Opt in to auto-routing
Read the routing metadata in the response
Stream the response
Completions V2 offers three ways to select the model. Provide exactly one of model, model_family, or auto_routing; they are mutually exclusive.
Mode
Use Case
Parameter
AI Select (pinned model, recommended)
Specify an exact model for predictable, reproducible behavior
"model": "gloo-anthropic-claude-opus-5.5"
AI Core Select (model family)
Choose a provider family, let Gloo pick the model within it
"model_family": "anthropic"
AI Core (auto-routing, opt-in)
Let Gloo select the model for each request; the model can change between calls
Available model families: openai, anthropic, google, open source
Step 3: Opt in to auto-routing
Let Gloo select the model for each request:
import requestsdef make_v2_completion_auto(api_key): """Makes a V2 completion request with opt-in auto-routing.""" api_url = "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions" headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } payload = { "messages": [ {"role": "user", "content": "How does the Old Testament connect to the New Testament?"} ], "auto_routing": True, "tradition": "evangelical" # Optional: evangelical, catholic, or mainline } response = requests.post(api_url, headers=headers, json=payload) response.raise_for_status() return response.json()
async function makeV2CompletionAuto() { const apiUrl = "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions"; const payload = { messages: [ { role: "user", content: "How does the Old Testament connect to the New Testament?" } ], auto_routing: true, tradition: "evangelical" // Optional: evangelical, catholic, or mainline }; const response = await fetch(apiUrl, { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify(payload) }); return response.json();}
async function makeV2CompletionAuto(): Promise<any> { const apiUrl = "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions"; const payload = { messages: [ { role: "user", content: "How does the Old Testament connect to the New Testament?" } ], auto_routing: true, tradition: "evangelical" // Optional: evangelical, catholic, or mainline }; const response = await fetch(apiUrl, { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify(payload) }); return response.json();}
<?phpfunction makeV2CompletionAuto() { $apiUrl = 'https://platform.ai.gloo.com/ai/v2/guarded/chat/completions'; $apiKey = getenv('GLOO_API_KEY') ?: throw new RuntimeException('Set the GLOO_API_KEY environment variable'); $payload = json_encode([ 'messages' => [ ['role' => 'user', 'content' => 'How does the Old Testament connect to the New Testament?'] ], 'auto_routing' => true, 'tradition' => 'evangelical' // Optional: evangelical, catholic, or mainline ]); $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);}?>
func makeV2CompletionAuto() (map[string]interface{}, error) { apiUrl := "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions" payload := map[string]interface{}{ "messages": []map[string]string{ {"role": "user", "content": "How does the Old Testament connect to the New Testament?"}, }, "auto_routing": true, "tradition": "evangelical", // Optional: evangelical, catholic, or mainline } 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) var result map[string]interface{} json.Unmarshal(body, &result) return result, nil}
public String makeV2CompletionAuto() throws IOException, InterruptedException { String apiUrl = "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions"; String payload = """ { "messages": [ {"role": "user", "content": "How does the Old Testament connect to the New Testament?"} ], "auto_routing": true, "tradition": "evangelical" } """; 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()); return response.body();}
With auto-routing, Gloo may select a different model from one call to the next. Avoid it when you need reproducible output or consistent tool-calling behavior; pin a model instead.
routing_mechanism: How the model was selected (auto_routing, model_family, or direct_model_selection)
routing_tier and routing_confidence: Returned when you opt in to auto-routing. routing_tier is the complexity tier Gloo determined (tier_1, tier_2, tier_3) and routing_confidence is the confidence score for that routing decision (0.0-1.0)
tradition: The theological perspective applied (if specified)
Clone or browse the complete working examples for all 6 languages (JavaScript, TypeScript, Python, PHP, Go, Java) with setup instructions.
These examples combine all three model selection options into one runnable script per language.First set your environment variables in an .env file:
GLOO_API_KEY=YOUR_API_KEY
Or export them in your shell for Go and Java:
export GLOO_API_KEY="your_actual_api_key_here"
Complete example
import requestsimport osfrom dotenv import load_dotenv# Load environment variables from .env fileload_dotenv()# --- Configuration ---API_KEY = os.environ["GLOO_API_KEY"]API_URL = "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions"# --- V2 Completion Functions ---def make_v2_pinned_model(message, model="gloo-anthropic-claude-opus-5.5"): """Example 1: Pinned model - Specify an exact model.""" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } payload = { "messages": [{"role": "user", "content": message}], "model": model, "max_tokens": 8192 } response = requests.post(API_URL, headers=headers, json=payload) response.raise_for_status() return response.json()def make_v2_model_family(message, model_family="anthropic"): """Example 2: Model family selection - Choose a provider family.""" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } payload = { "messages": [{"role": "user", "content": message}], "model_family": model_family } response = requests.post(API_URL, headers=headers, json=payload) response.raise_for_status() return response.json()def make_v2_auto_routing(message, tradition="evangelical"): """Example 3: Auto-routing (opt-in) - Let Gloo select the model.""" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } payload = { "messages": [{"role": "user", "content": message}], "auto_routing": True, "tradition": tradition } response = requests.post(API_URL, headers=headers, json=payload) response.raise_for_status() return response.json()# --- Main Execution ---if __name__ == "__main__": try: # Example 1: Pinned model print("=== Example 1: Pinned Model ===") result1 = make_v2_pinned_model("Summarize the book of Romans in 3 sentences.") print(f"Model used: {result1.get('model')}") print(f"Response: {result1['choices'][0]['message']['content'][:200]}...") # Example 2: Model family selection print("\n=== Example 2: Model Family Selection ===") result2 = make_v2_model_family("Draft a short sermon outline on forgiveness.", "anthropic") print(f"Model used: {result2.get('model')}") print(f"Response: {result2['choices'][0]['message']['content'][:200]}...") # Example 3: Auto-routing (opt-in) print("\n=== Example 3: Auto-Routing (Opt-in) ===") result3 = make_v2_auto_routing("How does the Old Testament connect to the New Testament?") print(f"Model used: {result3.get('model')}") print(f"Routing: {result3.get('routing_mechanism')}") print(f"Response: {result3['choices'][0]['message']['content'][:200]}...") 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 filerequire('dotenv').config();const axios = require('axios');// --- Configuration ---if (!process.env.GLOO_API_KEY) throw new Error("Set GLOO_API_KEY in your environment");const API_KEY = process.env.GLOO_API_KEY;const API_URL = "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions";// --- V2 Completion Functions ---async function makeV2PinnedModel(message, model = "gloo-anthropic-claude-opus-5.5") { // Example 1: Pinned model - Specify an exact model const response = await axios.post(API_URL, { messages: [{ role: "user", content: message }], model: model, max_tokens: 8192 }, { headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, }); return response.data;}async function makeV2ModelFamily(message, modelFamily = "anthropic") { // Example 2: Model family selection - Choose a provider family const response = await axios.post(API_URL, { messages: [{ role: "user", content: message }], model_family: modelFamily }, { headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, }); return response.data;}async function makeV2AutoRouting(message, tradition = "evangelical") { // Example 3: Auto-routing (opt-in) - Let Gloo select the model const response = await axios.post(API_URL, { messages: [{ role: "user", content: message }], auto_routing: true, tradition: tradition }, { headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, }); return response.data;}// --- Main Execution ---async function main() { try { // Example 1: Pinned model console.log("=== Example 1: Pinned Model ==="); const result1 = await makeV2PinnedModel("Summarize the book of Romans in 3 sentences."); console.log(`Model used: ${result1.model}`); console.log(`Response: ${result1.choices[0].message.content.substring(0, 200)}...`); // Example 2: Model family selection console.log("\n=== Example 2: Model Family Selection ==="); const result2 = await makeV2ModelFamily("Draft a short sermon outline on forgiveness.", "anthropic"); console.log(`Model used: ${result2.model}`); console.log(`Response: ${result2.choices[0].message.content.substring(0, 200)}...`); // Example 3: Auto-routing (opt-in) console.log("\n=== Example 3: Auto-Routing (Opt-in) ==="); const result3 = await makeV2AutoRouting("How does the Old Testament connect to the New Testament?"); console.log(`Model used: ${result3.model}`); console.log(`Routing: ${result3.routing_mechanism}`); console.log(`Response: ${result3.choices[0].message.content.substring(0, 200)}...`); } 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 filedotenv.config();// --- Type Definitions ---interface V2CompletionResponse { model: string; routing_mechanism?: string; routing_tier?: string; routing_confidence?: number; tradition?: string; choices: Array<{ message: { role: string; content: string; }; }>;}// --- Configuration ---if (!process.env.GLOO_API_KEY) throw new Error("Set GLOO_API_KEY in your environment");const API_KEY = process.env.GLOO_API_KEY;const API_URL = "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions";// --- V2 Completion Functions ---async function makeV2PinnedModel(message: string, model: string = "gloo-anthropic-claude-opus-5.5"): Promise<V2CompletionResponse> { // Example 1: Pinned model - Specify an exact model const response = await axios.post<V2CompletionResponse>(API_URL, { messages: [{ role: "user", content: message }], model: model, max_tokens: 8192 }, { headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, }); return response.data;}async function makeV2ModelFamily(message: string, modelFamily: string = "anthropic"): Promise<V2CompletionResponse> { // Example 2: Model family selection - Choose a provider family const response = await axios.post<V2CompletionResponse>(API_URL, { messages: [{ role: "user", content: message }], model_family: modelFamily }, { headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, }); return response.data;}async function makeV2AutoRouting(message: string, tradition: string = "evangelical"): Promise<V2CompletionResponse> { // Example 3: Auto-routing (opt-in) - Let Gloo select the model const response = await axios.post<V2CompletionResponse>(API_URL, { messages: [{ role: "user", content: message }], auto_routing: true, tradition: tradition }, { headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, }); return response.data;}// --- Main Execution ---async function main(): Promise<void> { try { // Example 1: Pinned model console.log("=== Example 1: Pinned Model ==="); const result1 = await makeV2PinnedModel("Summarize the book of Romans in 3 sentences."); console.log(`Model used: ${result1.model}`); console.log(`Response: ${result1.choices[0].message.content.substring(0, 200)}...`); // Example 2: Model family selection console.log("\n=== Example 2: Model Family Selection ==="); const result2 = await makeV2ModelFamily("Draft a short sermon outline on forgiveness.", "anthropic"); console.log(`Model used: ${result2.model}`); console.log(`Response: ${result2.choices[0].message.content.substring(0, 200)}...`); // Example 3: Auto-routing (opt-in) console.log("\n=== Example 3: Auto-Routing (Opt-in) ==="); const result3 = await makeV2AutoRouting("How does the Old Testament connect to the New Testament?"); console.log(`Model used: ${result3.model}`); console.log(`Routing: ${result3.routing_mechanism}`); console.log(`Response: ${result3.choices[0].message.content.substring(0, 200)}...`); } catch (error: any) { console.error("An error occurred:", error.response ? error.response.data : error.message); }}main();
<?phprequire_once 'vendor/autoload.php';// Load .env file$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);$dotenv->load();// --- Configuration ---$API_KEY = $_ENV['GLOO_API_KEY'] ?? getenv('GLOO_API_KEY') ?: throw new RuntimeException('Set the GLOO_API_KEY environment variable');$API_URL = 'https://platform.ai.gloo.com/ai/v2/guarded/chat/completions';// --- V2 Completion Functions ---function makeV2PinnedModel($message, $model, $apiUrl) { global $API_KEY; // Example 1: Pinned model - Specify an exact model $payload = json_encode([ 'messages' => [['role' => 'user', 'content' => $message]], 'model' => $model, 'max_tokens' => 8192 ]); return makeRequest($apiUrl, $payload, $API_KEY);}function makeV2ModelFamily($message, $modelFamily, $apiUrl) { global $API_KEY; // Example 2: Model family selection - Choose a provider family $payload = json_encode([ 'messages' => [['role' => 'user', 'content' => $message]], 'model_family' => $modelFamily ]); return makeRequest($apiUrl, $payload, $API_KEY);}function makeV2AutoRouting($message, $tradition, $apiUrl) { global $API_KEY; // Example 3: Auto-routing (opt-in) - Let Gloo select the model $payload = json_encode([ 'messages' => [['role' => 'user', 'content' => $message]], 'auto_routing' => true, 'tradition' => $tradition ]); return makeRequest($apiUrl, $payload, $API_KEY);}function makeRequest($apiUrl, $payload, $apiKey) { $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 { // Example 1: Pinned model echo "=== Example 1: Pinned Model ===\n"; $result1 = makeV2PinnedModel( "Summarize the book of Romans in 3 sentences.", "gloo-anthropic-claude-opus-5.5", $API_URL ); echo "Model used: " . $result1['model'] . "\n"; echo "Response: " . substr($result1['choices'][0]['message']['content'], 0, 200) . "...\n"; // Example 2: Model family selection echo "\n=== Example 2: Model Family Selection ===\n"; $result2 = makeV2ModelFamily( "Draft a short sermon outline on forgiveness.", "anthropic", $API_URL ); echo "Model used: " . $result2['model'] . "\n"; echo "Response: " . substr($result2['choices'][0]['message']['content'], 0, 200) . "...\n"; // Example 3: Auto-routing (opt-in) echo "\n=== Example 3: Auto-Routing (Opt-in) ===\n"; $result3 = makeV2AutoRouting( "How does the Old Testament connect to the New Testament?", "evangelical", $API_URL ); echo "Model used: " . $result3['model'] . "\n"; echo "Routing: " . $result3['routing_mechanism'] . "\n"; echo "Response: " . substr($result3['choices'][0]['message']['content'], 0, 200) . "...\n";} catch (Exception $e) { echo 'Error: ' . $e->getMessage();}?>
package mainimport ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "os")// --- Configuration ---var ( apiKey = mustGetEnv("GLOO_API_KEY") apiURL = "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions")// --- V2 Completion Functions ---func makeV2PinnedModel(message, model string) (map[string]interface{}, error) { // Example 1: Pinned model - Specify an exact model payload := map[string]interface{}{ "messages": []map[string]string{{"role": "user", "content": message}}, "model": model, "max_tokens": 8192, } return makeRequest(payload)}func makeV2ModelFamily(message, modelFamily string) (map[string]interface{}, error) { // Example 2: Model family selection - Choose a provider family payload := map[string]interface{}{ "messages": []map[string]string{{"role": "user", "content": message}}, "model_family": modelFamily, } return makeRequest(payload)}func makeV2AutoRouting(message, tradition string) (map[string]interface{}, error) { // Example 3: Auto-routing (opt-in) - Let Gloo select the model payload := map[string]interface{}{ "messages": []map[string]string{{"role": "user", "content": message}}, "auto_routing": true, "tradition": tradition, } return makeRequest(payload)}func makeRequest(payload map[string]interface{}) (map[string]interface{}, error) { 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}func getEnv(key, fallback string) string { if value, ok := os.LookupEnv(key); ok { return value } return fallback}func mustGetEnv(key string) string { value, ok := os.LookupEnv(key) if !ok || value == "" { panic(key + " is not set") } return value}func getResponseContent(result map[string]interface{}) string { if choices, ok := result["choices"].([]interface{}); ok && len(choices) > 0 { if choice, ok := choices[0].(map[string]interface{}); ok { if message, ok := choice["message"].(map[string]interface{}); ok { if content, ok := message["content"].(string); ok { if len(content) > 200 { return content[:200] + "..." } return content } } } } return ""}// --- Main Execution ---func main() { // Example 1: Pinned model fmt.Println("=== Example 1: Pinned Model ===") result1, err := makeV2PinnedModel("Summarize the book of Romans in 3 sentences.", "gloo-anthropic-claude-opus-5.5") if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Model used: %v\n", result1["model"]) fmt.Printf("Response: %s\n", getResponseContent(result1)) // Example 2: Model family selection fmt.Println("\n=== Example 2: Model Family Selection ===") result2, err := makeV2ModelFamily("Draft a short sermon outline on forgiveness.", "anthropic") if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Model used: %v\n", result2["model"]) fmt.Printf("Response: %s\n", getResponseContent(result2)) // Example 3: Auto-routing (opt-in) fmt.Println("\n=== Example 3: Auto-Routing (Opt-in) ===") result3, err := makeV2AutoRouting("How does the Old Testament connect to the New Testament?", "evangelical") if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Model used: %v\n", result3["model"]) fmt.Printf("Routing: %v\n", result3["routing_mechanism"]) fmt.Printf("Response: %s\n", getResponseContent(result3))}
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.time.Instant;import java.util.HashMap;import java.util.List;import java.util.Map;public class GlooV2Example { // --- Configuration ---private static final String API_KEY = java.util.Objects.requireNonNull(System.getenv("GLOO_API_KEY"), "Set the GLOO_API_KEY environment variable"); private static final String API_URL = "https://platform.ai.gloo.com/ai/v2/guarded/chat/completions"; private final HttpClient httpClient = HttpClient.newHttpClient(); private final Gson gson = new Gson(); // --- V2 Completion Functions --- public Map<String, Object> makeV2PinnedModel(String message, String model) throws IOException, InterruptedException { // Example 1: Pinned model - Specify an exact model Map<String, Object> payload = new HashMap<>(); Map<String, String> messageEntry = new HashMap<>(); messageEntry.put("role", "user"); messageEntry.put("content", message); payload.put("messages", List.of(messageEntry)); payload.put("model", model); payload.put("max_tokens", 8192); return makeRequest(gson.toJson(payload)); } public Map<String, Object> makeV2ModelFamily(String message, String modelFamily) throws IOException, InterruptedException { // Example 2: Model family selection - Choose a provider family Map<String, Object> payload = new HashMap<>(); Map<String, String> messageEntry = new HashMap<>(); messageEntry.put("role", "user"); messageEntry.put("content", message); payload.put("messages", List.of(messageEntry)); payload.put("model_family", modelFamily); return makeRequest(gson.toJson(payload)); } public Map<String, Object> makeV2AutoRouting(String message, String tradition) throws IOException, InterruptedException { // Example 3: Auto-routing (opt-in) - Let Gloo select the model Map<String, Object> payload = new HashMap<>(); Map<String, String> messageEntry = new HashMap<>(); messageEntry.put("role", "user"); messageEntry.put("content", message); payload.put("messages", List.of(messageEntry)); payload.put("auto_routing", true); payload.put("tradition", tradition); return makeRequest(gson.toJson(payload)); } private Map<String, Object> makeRequest(String payload) throws IOException, InterruptedException { 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()); return gson.fromJson(response.body(), Map.class); } private String getResponseContent(Map<String, Object> result) { List<Map<String, Object>> choices = (List<Map<String, Object>>) result.get("choices"); Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message"); String content = (String) message.get("content"); return content.length() > 200 ? content.substring(0, 200) + "..." : content; } // --- Main Execution --- public static void main(String[] args) { GlooV2Example client = new GlooV2Example(); try { // Example 1: Pinned model System.out.println("=== Example 1: Pinned Model ==="); Map<String, Object> result1 = client.makeV2PinnedModel( "Summarize the book of Romans in 3 sentences.", "gloo-anthropic-claude-opus-5.5"); System.out.println("Model used: " + result1.get("model")); System.out.println("Response: " + client.getResponseContent(result1)); // Example 2: Model family selection System.out.println("\n=== Example 2: Model Family Selection ==="); Map<String, Object> result2 = client.makeV2ModelFamily( "Draft a short sermon outline on forgiveness.", "anthropic"); System.out.println("Model used: " + result2.get("model")); System.out.println("Response: " + client.getResponseContent(result2)); // Example 3: Auto-routing (opt-in) System.out.println("\n=== Example 3: Auto-Routing (Opt-in) ==="); Map<String, Object> result3 = client.makeV2AutoRouting( "How does the Old Testament connect to the New Testament?", "evangelical"); System.out.println("Model used: " + result3.get("model")); System.out.println("Routing: " + result3.get("routing_mechanism")); System.out.println("Response: " + client.getResponseContent(result3)); } catch (Exception e) { e.printStackTrace(); } }}
Troubleshooting
400: Exactly one routing mechanism must be specified
Cause: The request sent more than one of model, model_family and auto_routing, or none of them.Solution: Send exactly one. See Step 1, Step 2 and Step 3.
422: messages field required
Cause: The request body has no messages array.Solution: Send messages with at least one user message.
401 Unauthorized
Cause: The API key is missing, wrong or revoked.Solution: Check the key and the Authorization: Bearer header. See the Authentication Tutorial.