Keep submission state explicit
Validate the draft, prevent duplicate sends while pending and preserve enough state to inspect failures. A network error alone does not prove execution was cancelled.
GALACTRE / CODE EXAMPLES
Explore focused examples for the Galactre browser API, from model discovery to conversation cleanup. Read the requirements, copy the function and run it only when your application is ready.
01 / SELECT AN OPERATION
These are complete function definitions, not background requests. All routes belong to the Galactre origin. Session tokens and private conversation content must stay out of shared code.
These examples use the browser session API. Backend applications can issue model-scoped server keys in API Access and use the separate responses contract.
Review access requirements/api/v1/chat/modelsRead the current GT model catalog before choosing a family. A public model listing is not a generation permission.
// Run on the Galactre origin. Nothing is fetched until you call the function.
async function listGalactreModels() {
const response = await fetch('/api/v1/chat/models', { cache: 'no-store' });
if (!response.ok) throw new Error('Galactre catalog unavailable.');
const catalog = await response.json();
if (!catalog.catalog_available || !Array.isArray(catalog.models)) {
throw new Error('Model availability could not be confirmed.');
}
return {
models: catalog.models.filter(model => model.available === true),
releases: (catalog.releases || []).filter(model => model.available === true)
};
}
// A model returned here still requires session, quota and policy checks.Returns the available catalog entries. This function does not create a session or generate text.
Handle failures explicitly/api/v1/chat/sessionDiscover whether the current browser has guest or account access, and obtain the current mutation token without logging it.
// Run only on a page served by Galactre. Calling this reads session state.
async function discoverGalactreAccess() {
const response = await fetch('/api/v1/chat/session', {
credentials: 'same-origin', cache: 'no-store'
});
const session = await response.json();
if (!response.ok || !session.chat_available || !session.csrf_token) {
throw new Error('GT chat is temporarily unavailable.');
}
// Keep this value in memory. Never print it or put it in a URL.
return {
authenticated: session.authenticated,
guest: session.guest,
limits: session.limits,
mutationHeaders: { 'X-CSRF-Token': session.csrf_token }
};
}
// This example does not send a message or purchase credits.Returns current identity flags, limits and mutation headers. It does not send a message or make a payment.
Handle failures explicitly/api/v1/chat/generateCheck the catalog and session, validate text length, then send one Lunar request. Review the completed answer before using it.
// Run on the Galactre origin. Calling this function sends a generation request.
async function askGalactre(message, conversationId) {
const catalogResponse = await fetch('/api/v1/chat/models');
if (!catalogResponse.ok) throw new Error('Catalog unavailable.');
const catalog = await catalogResponse.json();
if (!catalog.models?.some(m => m.family === 'Lunar' && m.available)) {
throw new Error('Lunar is not currently available.');
}
const sessionResponse = await fetch('/api/v1/chat/session', {
credentials: 'same-origin'
});
const session = await sessionResponse.json();
if (!sessionResponse.ok || !session.chat_available || !session.csrf_token) {
throw new Error('Chat is temporarily unavailable.');
}
const text = message.trim();
const maxLength = session.limits?.max_message_chars ?? 8000;
if (!text || Array.from(text).length > maxLength) {
throw new Error('Check the message length before sending.');
}
// Retain this key for recovery; a retry with changed input must use a new key.
const requestKey = 'quickstart_' + crypto.randomUUID().replaceAll('-', '');
const body = { family: 'Lunar', model: 'gt-lunar', message: text, request_key: requestKey };
if (conversationId) body.conversation_id = conversationId;
const response = await fetch('/api/v1/chat/generate', {
method: 'POST', credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': session.csrf_token
},
body: JSON.stringify(body)
});
const result = await response.json();
if (response.status === 429) {
throw new Error('Rate limited. Retry-After: ' + response.headers.get('Retry-After'));
}
if (!response.ok || result.status !== 'completed') {
throw new Error('Inspect the request outcome before retrying.');
}
return {
text: result.response,
requestId: result.id,
conversationId: result.conversation_id,
historyState: result.history?.state ?? 'not_reported'
};
}
// Review the returned text. This function does not run code or tools.This JSON example returns text, request ID, saved conversation ID when present and history state. The chat interface uses real SSE; signed-in conversations may use selected knowledge and bounded tools.
Handle failures explicitly/api/v1/chat/conversations/{id}List the current identity’s recent conversations, then read one owned ID. The API never grants access merely because an ID is known.
// Same-origin Galactre page. These functions only run when called.
async function recentGalactreConversations() {
const response = await fetch('/api/v1/chat/conversations', {
credentials: 'same-origin', cache: 'no-store'
});
if (!response.ok) throw new Error('Conversation history unavailable.');
const result = await response.json();
return result.conversations;
}
async function readGalactreConversation(id) {
if (!/^[a-f0-9]{32}$/.test(id)) throw new Error('Invalid conversation ID.');
const response = await fetch('/api/v1/chat/conversations/' + id, {
credentials: 'same-origin', cache: 'no-store'
});
if (response.status === 404) throw new Error('Conversation not found.');
if (!response.ok) throw new Error('Conversation history unavailable.');
return response.json(); // { id, messages: [{ id, role, content, created_at }] }
}
// Use textContent for message content; do not inject it as HTML.Returns a recent list or an owned conversation. A missing/inaccessible conversation returns 404.
Handle failures explicitly/api/v1/chat/generateReuse an ID from a saved exchange under the same authorized identity. The model receives bounded recent context, not unlimited saved history.
// Run on the Galactre origin. Calling this function sends a generation request.
async function askGalactre(message, conversationId) {
const catalogResponse = await fetch('/api/v1/chat/models');
if (!catalogResponse.ok) throw new Error('Catalog unavailable.');
const catalog = await catalogResponse.json();
if (!catalog.models?.some(m => m.family === 'Lunar' && m.available)) {
throw new Error('Lunar is not currently available.');
}
const sessionResponse = await fetch('/api/v1/chat/session', {
credentials: 'same-origin'
});
const session = await sessionResponse.json();
if (!sessionResponse.ok || !session.chat_available || !session.csrf_token) {
throw new Error('Chat is temporarily unavailable.');
}
const text = message.trim();
const maxLength = session.limits?.max_message_chars ?? 8000;
if (!text || Array.from(text).length > maxLength) {
throw new Error('Check the message length before sending.');
}
// Retain this key for recovery; a retry with changed input must use a new key.
const requestKey = 'quickstart_' + crypto.randomUUID().replaceAll('-', '');
const body = { family: 'Lunar', model: 'gt-lunar', message: text, request_key: requestKey };
if (conversationId) body.conversation_id = conversationId;
const response = await fetch('/api/v1/chat/generate', {
method: 'POST', credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': session.csrf_token
},
body: JSON.stringify(body)
});
const result = await response.json();
if (response.status === 429) {
throw new Error('Rate limited. Retry-After: ' + response.headers.get('Retry-After'));
}
if (!response.ok || result.status !== 'completed') {
throw new Error('Inspect the request outcome before retrying.');
}
return {
text: result.response,
requestId: result.id,
conversationId: result.conversation_id,
historyState: result.history?.state ?? 'not_reported'
};
}
// Review the returned text. This function does not run code or tools.
async function continueGalactreConversation(message, conversationId) {
if (!/^[a-f0-9]{32}$/.test(conversationId)) {
throw new Error('Use an ID returned by a saved conversation.');
}
return askGalactre(message, conversationId);
}
// Invoke only after a user submits a follow-up in their owned conversation.The askGalactre function accepts an optional conversationId. The additional wrapper validates the saved ID before a follow-up.
Handle failures explicitly/api/v1/chat/conversations/{id}/deleteConfirm the exact conversation before removing it from the active store. Refresh the session and send its current CSRF token.
// Same-origin Galactre page. Supply your UI's explicit confirmation callback.
async function deleteGalactreConversation(id, confirmDelete) {
if (!/^[a-f0-9]{32}$/.test(id)) throw new Error('Invalid conversation ID.');
if (typeof confirmDelete !== 'function') throw new Error('Confirmation required.');
if (await confirmDelete(id) !== true) return false;
const sessionResponse = await fetch('/api/v1/chat/session', {
credentials: 'same-origin', cache: 'no-store'
});
const session = await sessionResponse.json();
if (!sessionResponse.ok || !session.chat_available || !session.csrf_token) {
throw new Error('Refresh your Galactre session.');
}
const response = await fetch('/api/v1/chat/conversations/' + id + '/delete', {
method: 'POST', credentials: 'same-origin',
headers: { 'X-CSRF-Token': session.csrf_token }
});
if (response.status === 404) throw new Error('Conversation not found.');
if (!response.ok) throw new Error('Deletion failed; keep the conversation visible.');
const result = await response.json();
if (result.deleted !== true) throw new Error('Deletion not confirmed.');
return true;
}
// Remove the item from your interface only when this function returns true.Returns false when confirmation is declined and true after verified deletion. A missing/inaccessible ID returns 404.
Handle failures explicitly02 / BUILD AROUND THE REQUEST
The request is one part of the experience. State, rendering, access checks and recovery belong in the application around it.
Validate the draft, prevent duplicate sends while pending and preserve enough state to inspect failures. A network error alone does not prove execution was cancelled.
Honor Retry-After. Refresh the session allowance after an admitted request, and avoid automatically resubmitting after an uncertain outcome.
Use textContent or a properly sanitized renderer. Generated text, conversation titles and error messages should never be inserted as trusted HTML.
A suggested command, test or deployment is not executed by chat. Enforce authorization, validation and review in your own application before taking action.
04 / BEFORE YOU COPY
The model field accepts a family ID or an exact release ID. Replace gt-lunar with an available ID from catalog.releases to pin a version. The older family shorthand continues to follow the current default. Inspect the returned model_id; do not infer the resolved version from your request label.
No. The page only changes the displayed code or copies text. Each function runs only when explicitly called from your application. The examples contain no live credentials.
These browser snippets require the Galactre origin and session. For a backend, issue an expiring, model-scoped key in API Access and call POST /api/v1/responses with Authorization: Bearer and Idempotency-Key. Keep keys on your server; do not copy browser cookies or expose keys to another website.
They are plain JavaScript examples using native fetch, not a separately published SDK package. The Developers page documents the current endpoint contract and limitations.
These minimal examples request completed JSON. Set stream to true for SSE start, delta and completed events. Use the request ID to check status or request cancellation; a disconnect can leave usage needing reconciliation. Signed-in browser conversations support selected private knowledge, calculator and current-time tools. Server keys do not delegate those private sources. Files and image generation are not released.
Treat the completed answer and history persistence independently. A response may report history.state = unavailable. Preserve important non-sensitive results appropriately, and do not assume the exchange will reappear after reload.
No. Discover current session state and use the returned CSRF token only with that session. Keep cookies, credentials and private conversation content out of public examples, URLs and logs.
TRY THE EXPERIENCE