JavaScript / TypeScript
Use the official OpenAI Node SDK, pointed at Astrodyne.
Install
Shell
npm install openai
A request
TypeScript
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.astrodyne.ai/v1",
apiKey: process.env.ASTRODYNE_API_KEY,
});
const resp = await client.chat.completions.create({
model: "YOUR_MODEL_ID",
messages: [{ role: "user", content: "Hello" }],
});
console.log(resp.choices[0].message.content);
Streaming
TypeScript
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.astrodyne.ai/v1",
apiKey: process.env.ASTRODYNE_API_KEY,
});
const stream = await client.chat.completions.create({
model: "YOUR_MODEL_ID",
messages: [{ role: "user", content: "Hello" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
Listing your models
TypeScript
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.astrodyne.ai/v1",
apiKey: process.env.ASTRODYNE_API_KEY,
});
for await (const model of client.models.list()) {
console.log(model.id);
}
Handling errors
TypeScript
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.astrodyne.ai/v1",
apiKey: process.env.ASTRODYNE_API_KEY,
});
try {
const resp = await client.chat.completions.create({
model: "YOUR_MODEL_ID",
messages: [{ role: "user", content: "Hello" }],
});
} catch (err) {
if (err instanceof OpenAI.APIError) {
switch (err.status) {
case 401: break; // key missing, revoked or expired
case 403: break; // model not allowed for this account
case 404: break; // no such model
case 402: break; // insufficient_funds - add funds, do not retry
case 429: break; // rate or spending limit; retry with backoff
}
}
throw err;
}
Never ship a key to the browser
Call Astrodyne from your server. A key in client-side JavaScript is readable by
anyone who opens developer tools.