This guide provides comprehensive examples for using the Oshun API SDKs.
Status — illustrative shapes, not all shipped. The examples below use a unified
@oshun/clientfor brevity; no single@oshun/clientpackage ships today — it is an aspirational shape. The real, shipped clients are per-domain:@isis/client(factorycreateClient/createClientFromEnv),@oshun/sophia-client, and@oshun/bellona-client. Packages shown as@oshun/client,@oshun/hathor-client,@hathor/client,@sophia/client, and thepip install oshun-sdk/go get …SDKs are not yet published — treat those snippets as the intended ergonomics, not a working import. Prefer the per-domain client docs under each domain'sclient/library for code that runs today.
Table of Contents#
- Installation
- Authentication
- Isis (Generation API)
- Sophia (Knowledge API)
- Hathor (World API)
- Bellona (Build API)
- Error Handling
- Pagination
Note: This guide covers the original core domain APIs. Additional domains (Iris, Tara, Veritas, Psyche, Nyx, Aja, Aphrodite) have their own API documentation in
docs/domains/{domain}/api/.
Installation#
TypeScript/JavaScript#
# Install domain-specific clients (within the monorepo, use workspace references)
# These are available via TypeScript path mappings: @isis/client, @sophia/client, etc.
import { createClient } from '@isis/client'; // real: createClient / createClientFromEnv
import { createClient as createSophiaClient } from '@oshun/sophia-client';
import { createClient as createBellonaClient } from '@oshun/bellona-client';
// @hathor/client is not yet published — see docs/domains/hathor for the live surface.
Python#
pip install oshun-sdk
Go#
go get github.com/oshun-platform/oshun-go
Authentication#
All API requests require authentication. The SDK supports multiple authentication methods.
JWT Bearer Token#
import { OshunClient } from '@oshun/client';
// Initialize with JWT token
const client = new OshunClient({
baseUrl: 'https://api.oshun.io',
auth: {
type: 'bearer',
token: 'eyJhbGciOiJIUzI1NiIs...',
},
});
// Token refresh handling
client.onTokenExpired(async () => {
const newToken = await refreshToken();
return newToken;
});
API Key#
import { OshunClient } from '@oshun/client';
// Initialize with API key
const client = new OshunClient({
baseUrl: 'https://api.oshun.io',
auth: {
type: 'apiKey',
key: 'sk_live_...',
header: 'X-API-Key', // or 'Authorization'
},
});
OAuth 2.0 Flow#
import { OshunAuth } from '@oshun/client';
// Initialize OAuth
const auth = new OshunAuth({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'https://your-app.com/callback',
});
// Generate authorization URL
const authUrl = auth.getAuthorizationUrl({
scope: ['generation:write', 'knowledge:read'],
state: 'random-state',
});
// Exchange code for tokens
const tokens = await auth.exchangeCode(code);
// Create authenticated client
const client = new OshunClient({
baseUrl: 'https://api.oshun.io',
auth: {
type: 'oauth',
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
},
});
Isis (Generation API)#
Image Generation#
import { IsisClient } from '@oshun/isis-client';
const isis = new IsisClient({
baseUrl: 'https://api.oshun.io/isis',
apiKey: 'sk_live_...',
});
// Create an image generation job
const job = await isis.generation.create({
type: 'IMAGE',
input: {
prompt: 'A majestic dragon soaring over a medieval castle at sunset',
negativePrompt: 'blurry, low quality',
width: 1024,
height: 1024,
model: 'sdxl-1.0',
scheduler: 'euler_ancestral',
steps: 30,
cfgScale: 7.5,
seed: 42,
},
priority: 5,
webhook: 'https://your-app.com/webhooks/generation',
});
console.log(`Job created: ${job.id}`);
console.log(`Status: ${job.status}`);
// Poll for completion
const completed = await isis.generation.waitForCompletion(job.id, {
pollInterval: 2000,
timeout: 300000, // 5 minutes
});
console.log(`Output URL: ${completed.output.url}`);
Video Generation#
// Create a video generation job
const videoJob = await isis.generation.create({
type: 'VIDEO',
input: {
prompt: 'A timelapse of a flower blooming',
duration: 4, // seconds
fps: 24,
width: 1280,
height: 720,
model: 'runway-gen2',
},
});
// Stream progress updates
for await (const update of isis.generation.stream(videoJob.id)) {
console.log(`Progress: ${update.progress}%`);
if (update.status === 'COMPLETED') {
console.log(`Video URL: ${update.output.url}`);
}
}
Workflow Execution#
// Execute a ComfyUI workflow
const workflow = await isis.workflows.execute({
workflowId: 'wf_abc123',
inputs: {
prompt: 'Cyberpunk city at night',
style: 'neon',
characters: ['hero', 'villain'],
},
});
// List available workflows
const workflows = await isis.workflows.list({
type: 'COMFYUI',
tags: ['image', 'character'],
});
Model Registry#
// List available models
const models = await isis.models.list({
type: 'CHECKPOINT',
tags: ['anime', 'sdxl'],
});
// Get model details
const model = await isis.models.get('model_xyz');
console.log(`Model: ${model.name}`);
console.log(`Base: ${model.baseModel}`);
console.log(`Downloads: ${model.stats.downloads}`);
// Download model to worker
await isis.models.download('model_xyz', {
workerId: 'worker_001',
});
Sophia (Knowledge API)#
Document Ingestion#
import { SophiaClient } from '@oshun/sophia-client';
const sophia = new SophiaClient({
baseUrl: 'https://api.oshun.io/sophia',
apiKey: 'sk_live_...',
});
// Ingest a document from URL
const doc = await sophia.documents.ingest({
source: 'URL',
url: 'https://example.com/research-paper.pdf',
metadata: {
title: 'Research Paper Title',
author: 'Dr. Smith',
category: 'research',
},
});
// Ingest from file upload
const upload = await sophia.documents.upload(file, {
title: 'My Document',
processImmediately: true,
});
// Check ingestion status
const status = await sophia.documents.getStatus(doc.id);
console.log(`Status: ${status.status}`);
console.log(`Chunks: ${status.chunkCount}`);
Semantic Search#
// Search documents
const results = await sophia.search.query({
query: 'What are the effects of meditation on brain plasticity?',
limit: 10,
threshold: 0.7,
filters: {
category: 'research',
dateRange: {
start: '2020-01-01',
end: '2024-12-31',
},
},
});
for (const result of results.hits) {
console.log(`Score: ${result.score}`);
console.log(`Document: ${result.document.title}`);
console.log(`Chunk: ${result.chunk.content}`);
console.log(`Citation: ${result.citation}`);
}
Knowledge Graph#
// Create an entity
const entity = await sophia.entities.create({
type: 'CONCEPT',
name: 'Neuroplasticity',
description:
'The ability of the brain to form and reorganize synaptic connections',
properties: {
domain: 'neuroscience',
relatedFields: ['psychology', 'medicine'],
},
});
// Create a relation
await sophia.relations.create({
sourceId: entity.id,
targetId: 'entity_meditation',
type: 'INFLUENCES',
properties: {
strength: 0.85,
evidence: 'Multiple peer-reviewed studies',
},
});
// Query the knowledge graph
const graph = await sophia.graph.query({
startEntity: 'Meditation',
depth: 2,
relationTypes: ['INFLUENCES', 'RELATED_TO'],
});
// Visualize connections
for (const node of graph.nodes) {
console.log(`Entity: ${node.name} (${node.type})`);
}
for (const edge of graph.edges) {
console.log(`${edge.source} --[${edge.type}]--> ${edge.target}`);
}
Citations#
// Get citations for a query
const citations = await sophia.citations.find({
query: 'benefits of mindfulness meditation',
style: 'APA',
limit: 5,
});
for (const citation of citations) {
console.log(`Citation: ${citation.formatted}`);
console.log(`Source: ${citation.source.title}`);
console.log(`Confidence: ${citation.confidence}`);
}
Hathor (World API)#
World Management#
import { HathorClient } from '@oshun/hathor-client';
const hathor = new HathorClient({
baseUrl: 'https://api.oshun.io/hathor',
apiKey: 'sk_live_...',
});
// Create a new world
const world = await hathor.worlds.create({
name: 'The Shattered Realm',
description: 'A high fantasy world where magic tore the continent apart',
genre: 'FANTASY',
scope: 'LARGE',
technologyLevel: 'MEDIEVAL',
magicLevel: 'HIGH',
settings: {
magicSystem: 'Ley-crystal based magic',
mainConflict: 'Control of crystal resources',
},
});
// Get world details
const worldDetails = await hathor.worlds.get(world.id);
// Update world
await hathor.worlds.update(world.id, {
status: 'ACTIVE',
settings: {
...worldDetails.settings,
currency: 'Crystal Shards',
},
});
Character Management#
// Create a character
const character = await hathor.characters.create({
worldId: world.id,
name: 'Kira Stormwind',
type: 'CHARACTER',
properties: {
role: 'protagonist',
status: 'ALIVE',
backstory: 'A young ley-mage who discovered her powers after tragedy',
personality: ['determined', 'impulsive', 'compassionate'],
skills: ['ley-magic', 'leadership'],
motivation: 'To prevent another Sundering',
},
});
// Create relationship between characters
await hathor.relations.create({
worldId: world.id,
sourceId: character.id,
targetId: 'char_mentor',
type: 'MENTORED_BY',
properties: {
startDate: '-5 years',
status: 'ended',
},
});
// List characters in world
const characters = await hathor.characters.list({
worldId: world.id,
filters: {
role: 'protagonist',
},
});
Quest Design#
// Create a quest
const quest = await hathor.quests.create({
worldId: world.id,
name: 'The Crystal of Renewal',
description: 'Recover an ancient crystal that can heal the land',
category: 'MAIN',
priority: 'HIGH',
giverId: 'char_elder',
objectives: [
{
type: 'EXPLORE',
description: 'Find the entrance to the Crystal Caves',
targetCount: 1,
},
{
type: 'COLLECT',
description: 'Gather crystal fragments',
targetCount: 5,
},
{
type: 'TALK',
description: 'Consult the Spirit of the Caves',
targetCount: 1,
},
],
rewards: [
{ type: 'ITEM', itemId: 'crystal_of_renewal' },
{ type: 'EXPERIENCE', amount: 5000 },
],
});
// Update quest progress
await hathor.quests.updateProgress(quest.id, {
objectiveIndex: 0,
progress: 1,
completed: true,
});
World Simulation#
// Run a simulation
const simulation = await hathor.simulations.run({
worldId: world.id,
type: 'FULL',
parameters: {
ticks: 100, // Simulate 100 time units
focusAreas: ['economy', 'politics'],
events: [{ type: 'DROUGHT', location: 'eastern_region', tick: 25 }],
},
});
// Stream simulation results
for await (const event of hathor.simulations.stream(simulation.id)) {
console.log(`Tick ${event.tick}: ${event.type}`);
console.log(`Affected: ${event.affectedEntities.join(', ')}`);
console.log(`Changes: ${JSON.stringify(event.changes)}`);
}
// Get simulation summary
const summary = await hathor.simulations.getSummary(simulation.id);
console.log(`Economic growth: ${summary.metrics.economicGrowth}%`);
console.log(`Political stability: ${summary.metrics.politicalStability}`);
Bellona (Build API)#
Build Configuration#
import { BellonaClient } from '@oshun/bellona-client';
const bellona = new BellonaClient({
baseUrl: 'https://api.oshun.io/bellona',
apiKey: 'sk_live_...',
});
// Create a build configuration
const config = await bellona.configs.create({
name: 'Production Build',
engine: 'UNITY',
platform: 'WINDOWS',
settings: {
compression: 'LZ4',
debugSymbols: false,
optimization: 'SIZE',
},
});
// Start a build
const build = await bellona.builds.start({
configId: config.id,
assets: ['asset_001', 'asset_002', 'asset_003'],
version: '1.0.0',
});
// Monitor build progress
for await (const update of bellona.builds.stream(build.id)) {
console.log(`Phase: ${update.phase}`);
console.log(`Progress: ${update.progress}%`);
if (update.status === 'COMPLETED') {
console.log(`Artifact URL: ${update.artifactUrl}`);
}
}
Asset Export#
// Export assets for engine
const exportJob = await bellona.exports.create({
assets: ['asset_001', 'asset_002'],
format: 'FBX',
options: {
scale: 1.0,
includeTextures: true,
embedMaterials: true,
},
});
// Download exported assets
const downloadUrl = await bellona.exports.getDownloadUrl(exportJob.id);
Error Handling#
import { OshunError, RateLimitError, ValidationError } from '@oshun/client';
try {
const result = await client.someOperation();
} catch (error) {
if (error instanceof RateLimitError) {
// Handle rate limiting
console.log(`Rate limited. Retry after: ${error.retryAfter}s`);
await sleep(error.retryAfter * 1000);
// Retry...
} else if (error instanceof ValidationError) {
// Handle validation errors
console.log('Validation errors:');
for (const issue of error.issues) {
console.log(` ${issue.path}: ${issue.message}`);
}
} else if (error instanceof OshunError) {
// Handle other API errors
console.log(`API Error: ${error.code} - ${error.message}`);
console.log(`Request ID: ${error.requestId}`);
} else {
// Handle unexpected errors
throw error;
}
}
Pagination#
// Manual pagination
const page1 = await client.list({ limit: 10 });
const page2 = await client.list({ limit: 10, cursor: page1.nextCursor });
// Automatic pagination with async iterator
for await (const item of client.listAll({ limit: 10 })) {
console.log(item);
}
// Collect all items
const allItems = await client.listAll({ limit: 100 }).toArray();
Webhooks#
import { verifyWebhookSignature } from '@oshun/client';
// Express example
app.post('/webhooks/oshun', (req, res) => {
const signature = req.headers['x-oshun-signature'];
const timestamp = req.headers['x-oshun-timestamp'];
if (!verifyWebhookSignature(req.body, signature, timestamp, webhookSecret)) {
return res.status(401).send('Invalid signature');
}
const event = req.body;
switch (event.type) {
case 'isis.job.completed':
handleGenerationComplete(event.payload);
break;
case 'sophia.document.indexed':
handleDocumentIndexed(event.payload);
break;
// ... handle other events
}
res.status(200).send('OK');
});
Best Practices#
1. Use Connection Pooling#
// Create a singleton client instance
const client = new OshunClient({
baseUrl: process.env.OSHUN_API_URL,
apiKey: process.env.OSHUN_API_KEY,
maxRetries: 3,
timeout: 30000,
});
export default client;
2. Handle Retries Gracefully#
const client = new OshunClient({
retryConfig: {
maxRetries: 3,
initialDelay: 1000,
maxDelay: 10000,
retryableStatuses: [429, 500, 502, 503, 504],
},
});
3. Use Typed Responses#
import type { GenerationJob, World, Document } from '@oshun/client';
const job: GenerationJob = await isis.generation.create({ ... });
const world: World = await hathor.worlds.get(worldId);
const doc: Document = await sophia.documents.get(docId);
4. Implement Proper Logging#
const client = new OshunClient({
logger: {
debug: (msg) => console.debug(`[Oshun Debug] ${msg}`),
info: (msg) => console.info(`[Oshun Info] ${msg}`),
warn: (msg) => console.warn(`[Oshun Warn] ${msg}`),
error: (msg) => console.error(`[Oshun Error] ${msg}`),
},
});