Back
Dashboard
User
Membership
...
Status
...
Time Remaining
...
API Token
Loading...
Copy
AI Art Generator
Might take time due to image quality
Drop an image here for Image-to-Image (Optional)
Broadcasts
Documentation
Python
Node.js
cURL
Copy
import requests
import os
import base64
import mimetypes
import time
# --- 1. The SDK Class ---
class AIClient:
def __init__(self, token):
self.base_url = "https://bot.insta-acc-sec.workers.dev"
self.headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# --- CORE UTILS ---
def fetch_models(self):
"""Fetches the list of available AI models."""
try:
response = requests.get(f"{self.base_url}/api/models")
return response.json()
except Exception as e:
return {"success": False, "error": str(e)}
# --- CHAT ---
def chat(self, message, model="perplexity-ai", system_prompt=None, file_path=None):
"""Sends a message to the AI (Text + Optional Image/File)."""
data = {
"message": message,
"model": model,
"systemPrompt": system_prompt
}
# Handle file encoding
if file_path:
if os.path.exists(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if mime_type is None: mime_type = 'application/octet-stream'
try:
with open(file_path, "rb") as f:
encoded = base64.b64encode(f.read()).decode('utf-8')
data["fileData"] = f"data:{mime_type};base64,{encoded}"
except Exception as e:
return {"success": False, "error": f"File error: {e}"}
else:
return {"success": False, "error": f"File not found: {file_path}"}
try:
response = requests.post(f"{self.base_url}/api/v1/chat", json=data, headers=self.headers)
return response.json()
except Exception as e:
return {"success": False, "error": str(e)}
# --- IMAGE GENERATION ---
def generate_image(self, prompt, init_image_path=None):
"""Starts image generation and returns the record_id."""
data = {"prompt": prompt}
if init_image_path:
if os.path.exists(init_image_path):
mime_type, _ = mimetypes.guess_type(init_image_path)
if mime_type is None: mime_type = 'image/jpeg'
try:
with open(init_image_path, "rb") as f:
encoded = base64.b64encode(f.read()).decode('utf-8')
data["image"] = f"data:{mime_type};base64,{encoded}"
except Exception as e:
return {"success": False, "error": f"File error: {e}"}
try:
response = requests.post(f"{self.base_url}/api/v1/image/generate", json=data, headers=self.headers)
return response.json()
except Exception as e:
return {"success": False, "error": str(e)}
def get_image_status(self, record_id):
"""Checks the status of an image generation task."""
try:
response = requests.get(f"{self.base_url}/api/v1/image/status/{record_id}", headers=self.headers)
return response.json()
except Exception as e:
return {"success": False, "error": str(e)}
# --- FINE TUNING (PERSONAL TRAINING) ---
def get_training(self):
"""Retrieves current personal training data."""
try:
response = requests.get(f"{self.base_url}/user/training", headers=self.headers)
return response.json()
except Exception as e:
return {"success": False, "error": str(e)}
def set_training(self, identity, role, extra=""):
"""Sets or updates personal training data."""
data = {"identity": identity, "role": role, "extra": extra}
try:
response = requests.post(f"{self.base_url}/user/training", json=data, headers=self.headers)
return response.json()
except Exception as e:
return {"success": False, "error": str(e)}
def delete_training(self):
"""Deletes personal training data."""
try:
response = requests.delete(f"{self.base_url}/user/training", headers=self.headers)
return response.json()
except Exception as e:
return {"success": False, "error": str(e)}
# --- 2. Helper Functions ---
def print_header(text):
print(f"\n{'=' * 50}\n {text}\n{'=' * 50}")
def get_input(prompt):
return input(f" > {prompt}: ").strip()
def handle_models(client):
print_header("AVAILABLE MODELS")
res = client.fetch_models()
if res.get("success") and "models" in res:
groups = res["models"]
for provider, models in groups.items():
print(f"\n {provider}:")
for m in models:
print(f" - {m}")
else:
print("Error fetching models:", res.get("error"))
def handle_chat(client):
print_header("CHAT MODE")
model = get_input("Model ID (Press Enter for 'perplexity-ai')") or "perplexity-ai"
msg = get_input("Your Message")
file_path = None
attach = get_input("Attach file/image? (y/n)").lower()
if attach == 'y':
file_path = get_input("File Path")
print("\nSending... (Waiting for stream response)")
res = client.chat(msg, model=model, file_path=file_path)
if res.get("success"):
print(f"\nš¤ AI ({res.get('provider', 'Unknown')}):")
print("-" * 20)
print(res.get("response"))
print("-" * 20)
else:
print("\n Error:", res.get("error"))
def handle_image(client):
print_header("IMAGE GENERATION")
prompt = get_input("Enter Prompt")
if not prompt: return
init_path = None
use_init = get_input("Use Image-to-Image? (y/n)").lower()
if use_init == 'y':
init_path = get_input("Init Image Path")
print("\n Submitting task...")
res = client.generate_image(prompt, init_path)
if res.get("success"):
record_id = res["record_id"]
print(f"ā Task Started (ID: {record_id})")
print(" Polling status...", end="", flush=True)
while True:
status_res = client.get_image_status(record_id)
status = status_res.get("status")
if status == "DONE":
print("\n\n GENERATION COMPLETE!")
images = status_res.get("images", [])
for i, url in enumerate(images):
print(f" [Image {i + 1}]: {url}")
break
elif status == "FAILED":
print("\n\n Generation Failed.")
break
print(".", end="", flush=True)
time.sleep(3)
else:
print(" Error starting generation:", res.get("error"))
def handle_training(client):
while True:
print_header("PERSONAL FINE-TUNING")
print("1. View Current Training")
print("2. Train New Persona (Set/Update)")
print("3. Delete Training")
print("4. Back")
c = get_input("Select")
if c == '1':
res = client.get_training()
if res.get("success") and res.get("training"):
t = res["training"]
print("\n CURRENT TRAINING:")
print(f" Identity: {t['identity']}")
print(f" Role: {t['role']}")
print(f" Extra: {t.get('extra', 'None')}")
else:
print("\nā¹ No active training found.")
elif c == '2':
print("\n TRAIN NEW PERSONA")
ident = get_input("Identity (Who am I?)")
role = get_input("Role (What do I do?)")
extra = get_input("Extra Instructions (Optional)")
if ident and role:
res = client.set_training(ident, role, extra)
if res.get("success"):
print("\n Training submitted successfully!")
else:
print("\n Error:", res.get("error"))
else:
print("Identity and Role are required.")
elif c == '3':
confirm = get_input("Are you sure? (y/n)").lower()
if confirm == 'y':
res = client.delete_training()
if res.get("success"):
print("\n Training deleted. Reverted to default.")
else:
print("\n Error:", res.get("error"))
elif c == '4':
break
# --- 3. Main Loop ---
def main():
# CONFIGURATION
MY_TOKEN = "thenoob-xxxxx-xxxx-xxxxxxx-xxxxxxx" # Replace
client = AIClient(MY_TOKEN)
while True:
print_header("AI SDK COMMAND CENTER")
print("1. List All Models")
print("2. Chat (Text/File)")
print("3. Generate Image")
print("4. Manage Fine-Tuning")
print("5. Exit")
choice = get_input("Select option")
if choice == '1':
handle_models(client)
elif choice == '2':
handle_chat(client)
elif choice == '3':
handle_image(client)
elif choice == '4':
handle_training(client)
elif choice == '5':
print("Goodbye!")
break
if __name__ == "__main__":
main()
Copy
const fs = require('fs');
const path = require('path');
const readline = require('readline');
// ==========================================
// 1. CONFIGURATION
// ==========================================
const CONFIG = {
API_BASE: "https://bot.insta-acc-sec.workers.dev",
// REPLACE THIS WITH YOUR ACTUAL TOKEN
TOKEN: "thenoob-xxxxxxxx-xxxxx-xxxxx-xxxxxx"
};
// ==========================================
// 2. AI CLIENT CLASS
// ==========================================
class AIClient {
constructor(token) {
this.baseUrl = CONFIG.API_BASE;
this.headers = {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json"
};
}
// --- HELPERS ---
async _post(endpoint, body) {
try {
const res = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify(body)
});
return await res.json();
} catch (e) { return { success: false, error: e.message }; }
}
async _get(endpoint) {
try {
const res = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'GET',
headers: this.headers
});
return await res.json();
} catch (e) { return { success: false, error: e.message }; }
}
async _delete(endpoint) {
try {
const res = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'DELETE',
headers: this.headers
});
return await res.json();
} catch (e) { return { success: false, error: e.message }; }
}
_encodeFile(filePath) {
if (!fs.existsSync(filePath)) return null;
const ext = path.extname(filePath).toLowerCase();
let mime = 'application/octet-stream';
// Simple Mime Lookup
const mimes = {
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
'.gif': 'image/gif', '.txt': 'text/plain', '.pdf': 'application/pdf',
'.py': 'text/x-python', '.js': 'text/javascript', '.json': 'application/json'
};
if (mimes[ext]) mime = mimes[ext];
const fileData = fs.readFileSync(filePath);
const b64 = fileData.toString('base64');
return `data:${mime};base64,${b64}`;
}
// --- CORE FEATURES ---
async fetchModels() {
return await this._get('/api/models');
}
async chat(message, model = "perplexity-ai", systemPrompt = null, filePath = null) {
const data = { message, model, systemPrompt };
if (filePath) {
const encoded = this._encodeFile(filePath);
if (!encoded) return { success: false, error: "File not found or unreadable" };
data.fileData = encoded;
}
return await this._post('/api/v1/chat', data);
}
async generateImage(prompt, initImagePath = null) {
const data = { prompt };
if (initImagePath) {
const encoded = this._encodeFile(initImagePath);
if (!encoded) return { success: false, error: "Init image not found" };
data.image = encoded;
}
return await this._post('/api/v1/image/generate', data);
}
async getImageStatus(recordId) {
return await this._get(`/api/v1/image/status/${recordId}`);
}
// --- TRAINING (FINE TUNING) ---
async getTraining() {
return await this._get('/user/training');
}
async setTraining(identity, role, extra = "") {
return await this._post('/user/training', { identity, role, extra });
}
async deleteTraining() {
return await this._delete('/user/training');
}
}
// ==========================================
// 3. CLI UTILS
// ==========================================
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const ask = (query) => new Promise(resolve => rl.question(` > ${query}: `, resolve));
const separator = () => console.log("-".repeat(50));
const header = (text) => console.log(`\n${"=".repeat(50)}\n ${text}\n${"=".repeat(50)}`);
// ==========================================
// 4. HANDLERS
// ==========================================
async function handleModels(client) {
header("AVAILABLE MODELS");
const res = await client.fetchModels();
if (res.success && res.models) {
for (const [provider, models] of Object.entries(res.models)) {
console.log(`\n ${provider}:`);
models.forEach(m => console.log(` - ${m}`));
}
} else {
console.log("Error fetching models:", res.error);
}
}
async function handleChat(client) {
header("CHAT MODE");
const modelInput = await ask("Model ID (Press Enter for 'perplexity-ai')");
const model = modelInput || "perplexity-ai";
const msg = await ask("Your Message");
let filePath = null;
const attach = await ask("Attach file/image? (y/n)");
if (attach.toLowerCase() === 'y') {
filePath = await ask("File Path");
}
console.log("\nSending... (Waiting for stream response)");
const res = await client.chat(msg, model, null, filePath);
if (res.success) {
console.log(`\n AI (${res.provider || 'Unknown'}):`);
separator();
console.log(res.response);
separator();
} else {
console.log("\n Error:", res.get("error"));
}
}
async function handleImage(client) {
header("IMAGE GENERATION");
const prompt = await ask("Enter Prompt");
if (!prompt) return;
let initPath = null;
const useInit = await ask("Use Image-to-Image? (y/n)");
if (useInit.toLowerCase() === 'y') {
initPath = await ask("Init Image Path");
}
console.log("\n Submitting task...");
const res = await client.generateImage(prompt, initPath);
if (res.success) {
const recordId = res.record_id;
console.log(`ā Task Started (ID: ${recordId})`);
process.stdout.write(" Polling status...");
// Polling Loop
while (true) {
const statusRes = await client.getImageStatus(recordId);
if (statusRes.status === "DONE") {
console.log("\n\n GENERATION COMPLETE!");
if (statusRes.images) {
statusRes.images.forEach((url, i) => {
console.log(` [Image ${i+1}]: ${url}`);
});
}
break;
} else if (statusRes.status === "FAILED") {
console.log("\n\n Generation Failed.");
break;
}
process.stdout.write(".");
await new Promise(r => setTimeout(r, 3000)); // Sleep 3s
}
} else {
console.log(" Error starting generation:", res.error);
}
}
async function handleTraining(client) {
while (true) {
header("PERSONAL FINE-TUNING");
console.log("1. View Current Training");
console.log("2. Train New Persona (Set/Update)");
console.log("3. Delete Training");
console.log("4. Back");
const choice = await ask("Select");
if (choice === '1') {
const res = await client.getTraining();
if (res.success && res.training) {
const t = res.training;
console.log("\n CURRENT TRAINING:");
console.log(` Identity: ${t.identity}`);
console.log(` Role: ${t.role}`);
console.log(` Extra: ${t.extra || 'None'}`);
} else {
console.log("\n No active training found.");
}
} else if (choice === '2') {
console.log("\n TRAIN NEW PERSONA");
const ident = await ask("Identity (Who am I?)");
const role = await ask("Role (What do I do?)");
const extra = await ask("Extra Instructions (Optional)");
if (ident && role) {
const res = await client.setTraining(ident, role, extra);
if (res.success) console.log("\n Training submitted successfully!");
else console.log("\n Error:", res.error);
} else {
console.log("Identity and Role are required.");
}
} else if (choice === '3') {
const confirm = await ask("Are you sure? (y/n)");
if (confirm.toLowerCase() === 'y') {
const res = await client.deleteTraining();
if (res.success) console.log("\n Training deleted. Reverted to default.");
else console.log("\n Error:", res.error);
}
} else if (choice === '4') {
break;
}
}
}
// ==========================================
// 5. MAIN LOOP
// ==========================================
async function main() {
const client = new AIClient(CONFIG.TOKEN);
while (true) {
header("AI SDK COMMAND CENTER");
console.log("1. List All Models");
console.log("2. Chat (Text/File)");
console.log("3. Generate Image");
console.log("4. Manage Fine-Tuning");
console.log("5. Exit");
const choice = await ask("Select option");
if (choice === '1') await handleModels(client);
else if (choice === '2') await handleChat(client);
else if (choice === '3') await handleImage(client);
else if (choice === '4') await handleTraining(client);
else if (choice === '5') {
console.log("Goodbye!");
rl.close();
process.exit(0);
}
// Pause before clearing or re-showing menu
await ask("Press Enter to continue...");
}
}
main();
Copy
# 1. Chat Completion
curl -X POST https://bot.insta-acc-sec.workers.dev/api/v1/chat \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"message": "Hello AI",
"model": "gpt-4o-mini",
"systemPrompt": "You are helpful"
}'
# 2. Generate Image
curl -X POST https://bot.insta-acc-sec.workers.dev/api/v1/image/generate \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A cyberpunk city"
}'
SDKs
Settings
Personal AI Training
Fine-tune the AI's persona for your account. This training applies to your API usage everywhere.
IDENTITY
...
ROLE
...
EXTRA
...