Getting Started
Quickstart
This guide will help you make your first API call and build a simple chat application using the AI API. We'll cover text-only conversations, image analysis, and streaming responses.
Prerequisites
Before starting, make sure you have:
- Installed the SDK for your preferred language
- Your API key:
YOUR_API_KEY
(during beta) - Basic knowledge of your chosen programming language
Your First API Call
Let's start with a simple text completion:
JavaScript/Node.js
import OpenAI from "openai";
const openai = new OpenAI({
baseURL: "https://api.akbxr.com/v1",
apiKey: "YOUR_API_KEY",
});
async function firstCall() {
try {
const completion = await openai.chat.completions.create({
model: "auto",
messages: [
{ role: "user", content: "Hello! Can you tell me a joke?" }
],
});
console.log(completion.choices[0].message.content);
} catch (error) {
console.error("Error:", error);
}
}
firstCall();
Python
import openai
client = openai.OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.akbxr.com/v1"
)
try:
response = client.chat.completions.create(
model="auto",
messages=[
{"role": "user", "content": "Hello! Can you tell me a joke?"}
]
)
print(response.choices[0].message.content)
except Exception as error:
print(f"Error: {error}")
cURL
curl -X POST https://api.akbxr.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "auto",
"messages": [
{
"role": "user",
"content": "Hello! Can you tell me a joke?"
}
],
"stream": false
}'
Building a Simple Chat Application
Let's build a more interactive chat application:
JavaScript Chat Bot
import OpenAI from "openai";
import readline from "readline";
const openai = new OpenAI({
baseURL: "https://api.akbxr.com/v1",
apiKey: "YOUR_API_KEY",
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Store conversation history
let messages = [
{ role: "system", content: "You are a helpful assistant." }
];
async function chat() {
console.log("🤖 AI Assistant started! Type 'quit' to exit.\n");
const askQuestion = () => {
rl.question("You: ", async (input) => {
if (input.toLowerCase() === "quit") {
console.log("👋 Goodbye!");
rl.close();
return;
}
// Add user message to history
messages.push({ role: "user", content: input });
try {
const completion = await openai.chat.completions.create({
model: "auto",
messages: messages,
temperature: 0.7,
});
const assistantMessage = completion.choices[0].message.content;
// Add assistant response to history
messages.push({ role: "assistant", content: assistantMessage });
console.log(`🤖 Assistant: ${assistantMessage}\n`);
} catch (error) {
console.error("❌ Error:", error.message);
}
askQuestion(); // Continue the conversation
});
};
askQuestion();
}
chat();
Python Chat Bot
import openai
client = openai.OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.akbxr.com/v1"
)
# Store conversation history
messages = [
{"role": "system", "content": "You are a helpful assistant."}
]
def chat():
print("🤖 AI Assistant started! Type 'quit' to exit.\n")
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
print("👋 Goodbye!")
break
# Add user message to history
messages.append({"role": "user", "content": user_input})
try:
response = client.chat.completions.create(
model="auto",
messages=messages,
temperature=0.7
)
assistant_message = response.choices[0].message.content
# Add assistant response to history
messages.append({"role": "assistant", "content": assistant_message})
print(f"🤖 Assistant: {assistant_message}\n")
except Exception as error:
print(f"❌ Error: {error}")
if __name__ == "__main__":
chat()
Image Analysis
The AI API supports image analysis. Here's how to analyze images:
JavaScript Image Analysis
import OpenAI from "openai";
import fs from "fs";
const openai = new OpenAI({
baseURL: "https://api.akbxr.com/v1",
apiKey: "YOUR_API_KEY",
});
async function analyzeImage() {
try {
// Convert image to base64
const imageBuffer = fs.readFileSync("path/to/your/image.jpg");
const base64Image = imageBuffer.toString("base64");
const completion = await openai.chat.completions.create({
model: "auto",
messages: [
{
role: "user",
content: [
{
type: "image_url",
image_url: {
url: `data:image/jpeg;base64,${base64Image}`,
},
},
{
type: "text",
text: "What's in this image?",
},
],
},
],
});
console.log(completion.choices[0].message.content);
} catch (error) {
console.error("Error:", error);
}
}
analyzeImage();
Python Image Analysis
import openai
import base64
client = openai.OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.akbxr.com/v1"
)
def analyze_image(image_path):
try:
# Read and encode image
with open(image_path, "rb") as image_file:
base64_image = base64.b64encode(image_file.read()).decode("utf-8")
response = client.chat.completions.create(
model="auto",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
},
{
"type": "text",
"text": "What's in this image?"
}
]
}
]
)
print(response.choices[0].message.content)
except Exception as error:
print(f"Error: {error}")
# Usage
analyze_image("path/to/your/image.jpg")
cURL Image Analysis
# First, convert your image to base64
base64 -i your-image.jpg | pbcopy # macOS
# or
base64 your-image.jpg > image.b64 # Linux
curl -X POST https://api.akbxr.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "auto",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD..."
}
},
{
"type": "text",
"text": "What is in this image?"
}
]
}
]
}'
Streaming Responses
For real-time responses, use streaming:
JavaScript Streaming
import OpenAI from "openai";
const openai = new OpenAI({
baseURL: "https://api.akbxr.com/v1",
apiKey: "YOUR_API_KEY",
});
async function streamResponse() {
try {
const stream = await openai.chat.completions.create({
model: "auto",
messages: [{ role: "user", content: "Write a short story about AI" }],
stream: true,
});
console.log("🤖 Assistant: ");
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || "";
if (content) {
process.stdout.write(content);
}
}
console.log("\n");
} catch (error) {
console.error("Error:", error);
}
}
streamResponse();
Python Streaming
import openai
client = openai.OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.akbxr.com/v1"
)
def stream_response():
try:
stream = client.chat.completions.create(
model="auto",
messages=[{"role": "user", "content": "Write a short story about AI"}],
stream=True
)
print("🤖 Assistant: ", end="")
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)
print("\n")
except Exception as error:
print(f"Error: {error}")
stream_response()
Error Handling
Always implement proper error handling:
JavaScript Error Handling
async function robustAPICall() {
try {
const completion = await openai.chat.completions.create({
model: "auto",
messages: [{ role: "user", content: "Hello!" }],
});
return completion.choices[0].message.content;
} catch (error) {
if (error.status === 401) {
console.error("❌ Authentication failed: Check your API key");
} else if (error.status === 429) {
console.error("❌ Rate limit exceeded: Try again later");
} else if (error.status === 500) {
console.error("❌ Server error: Try again later");
} else {
console.error("❌ Unexpected error:", error.message);
}
throw error;
}
}
Python Error Handling
import openai
from openai import OpenAIError
def robust_api_call():
try:
response = client.chat.completions.create(
model="auto",
messages=[{"role": "user", "content": "Hello!"}]
)
return response.choices[0].message.content
except openai.AuthenticationError:
print("❌ Authentication failed: Check your API key")
except openai.RateLimitError:
print("❌ Rate limit exceeded: Try again later")
except openai.APIError as e:
print(f"❌ API error: {e}")
except Exception as e:
print(f"❌ Unexpected error: {e}")
return None
That's it! You're now ready to build amazing AI-powered applications with our API. Happy coding! 🚀