Node.js SDK
SovereignEG is fully compatible with the official OpenAI Node.js SDK.
Installation
npm install openaiSetup
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'sk-...',
baseURL: 'https://sovereigneg.com/v1',
});Or use environment variables:
export OPENAI_API_KEY=sk-...
export OPENAI_BASE_URL=https://sovereigneg.com/v1const client = new OpenAI(); // reads from env varsChat completions
const response = await client.chat.completions.create({
model: '...',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Hello from Node.js!' }
],
temperature: 0.7,
max_tokens: 256,
});
console.log(response.choices[0].message.content);Streaming
const stream = await client.chat.completions.create({
model: '...',
messages: [{ role: 'user', content: 'Write a haiku' }],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}Next.js API route
// app/api/chat/route.ts
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
baseURL: 'https://sovereigneg.com/v1',
});
export async function POST(req: Request) {
const { messages } = await req.json();
const stream = await client.chat.completions.create({
model: '...',
messages,
stream: true,
});
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
controller.enqueue(encoder.encode(content));
}
controller.close();
},
});
return new Response(readable, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
}Error handling
try {
const response = await client.chat.completions.create({...});
} catch (error) {
if (error instanceof OpenAI.AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof OpenAI.RateLimitError) {
console.error('Rate limited, retry later');
} else if (error instanceof OpenAI.APIError) {
console.error(`API error: ${error.message}`);
}
}TypeScript support
The OpenAI SDK is fully typed:
import OpenAI from 'openai';
import type { ChatCompletionMessageParam } from 'openai/resources';
const messages: ChatCompletionMessageParam[] = [
{ role: 'system', content: 'You are helpful.' },
{ role: 'user', content: 'Hello!' },
];