@sylix/sdk
v1.0.1
Published
Charlie AI SDK - sylixide-style API for Charles models
Downloads
10
Maintainers
Readme
Sylix SDK
An Sylix-style SDK for accessing Charles models via the Sylix API. Built for performance, simplicity, and developer ergonomics.
Current Version: 1.0.0
Status: Ready for production
License: MIT
🎯 Features
- Sylix-Compatible API: Familiar interface for
chat.completions.create(),vision.process(), and more - Strong TypeScript Types: Full type coverage with zero runtime dependencies (except axios)
- Model Management: Easy access to Charles model constants and metadata
- Error Handling: Helpful error messages with model validation and API error details
- Minimal & Fast: Optimized for small bundle size and performance
- Retry Logic: Automatic exponential backoff for 5xx server errors
📦 Installation
npm install @sylix/sdkRequirements
- Node.js >= 18.0.0
- npm/yarn/pnpm
🚀 Quick Start
Basic Chat Completion
import { Sylix, CHARLES_MODELS } from "@sylix/sdk";
const sylix = new Sylix({
apiKey: process.env.SYLIX_API_KEY!,
baseURL: "https://api.sylixide.com/v1", // optional, uses this by default
});
// Simple chat completion
const response = await sylix.chat.completions.create({
model: CHARLES_MODELS.MINI,
messages: [
{ role: "user", content: "What is 2 + 2?" }
],
});
console.log(response.choices[0].message.content);
// Output: "2 + 2 = 4"Vision (Image Processing)
import { Sylix, CHARLES_MODELS } from "@sylix/sdk";
import { readFile } from "@sylix/sdk";
const sylix = new Sylix({ apiKey: process.env.SYLIX_API_KEY! });
// Process an image file
const response = await sylix.vision.process({
model: CHARLES_MODELS.S1,
image: "/path/to/image.jpg", // File path
prompt: "Describe what you see in this image",
});
console.log(response.result);
// Or use base64 directly
const response2 = await sylix.vision.process({
model: CHARLES_MODELS.V1,
image: "data:image/jpeg;base64,/9j/4AAQSkZJRg...", // Base64
prompt: "Describe this image",
});Code Generation
const response = await sylix.code.generate({
model: CHARLES_MODELS.V1,
prompt: "Write a TypeScript function to calculate factorial",
language: "typescript",
max_tokens: 500,
});
console.log(response.code);Reasoning
const response = await sylix.reason.process({
model: CHARLES_MODELS.MINI,
prompt: "Explain the concept of recursion",
reasoning_type: "step-by-step",
});
console.log(response.reasoning);
console.log(response.conclusion);📚 API Reference
Sylix Configuration
interface SylixConfig {
apiKey: string; // Required: Your API key from https://sylixide.com
baseURL?: string; // Optional: API base URL (default: https://api.sylixide.com/v1)
timeout?: number; // Optional: Request timeout in ms (default: 30000)
headers?: Record<string, string>; // Optional: Extra headers
}
const sylix = new Sylix({
apiKey: "sk-...",
baseURL: "http://localhost:5001/v1",
timeout: 60000,
});Chat Completions
interface ChatRequest {
model: string; // Required: Model ID (use CHARLES_MODELS)
messages: ChatMessage[]; // Required: Conversation messages
max_tokens?: number; // Optional: Max response tokens
temperature?: number; // Optional: Sampling temperature (0-2)
stream?: boolean; // Optional: Enable streaming (v1.1+)
}
interface ChatMessage {
role: "system" | "user" | "assistant";
content: string;
}
const response = await sylix.chat.completions.create({
model: CHARLES_MODELS.S1,
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello!" },
],
temperature: 0.7,
max_tokens: 1000,
});Vision Processing
interface VisionRequest {
model: string; // Required: Model ID
image: Buffer | string; // Required: Image (Buffer, base64, or file path)
prompt: string; // Required: What to analyze in the image
}
const response = await sylix.vision.process({
model: CHARLES_MODELS.V1,
image: "./photo.jpg",
prompt: "Identify objects in this image",
});Models
// Get all available models
const models = sylix.models();
// Returns: ModelInfo[]
// Get a single model
const model = sylix.getModel("charles-mini");
// or
const model = sylix.getModel("charles-mini:latest");
interface ModelInfo {
id: string;
name: string;
displayName: string;
description: string;
capabilities: string[];
tier: string;
}Available Models (v1.0.0)
| Name | ID | Display Name | Tier | Best For |
|------|-----|--------------|------|----------|
| Charles Mini | charles-mini | charles-mini:latest | Free | Quick, lightweight tasks |
| Charles S1 | charles-s1 | charles-s1:latest | Standard | Reasoning, code generation |
| Charles V1 | charles-v1 | charles-v1:latest | Advanced | Complex analysis, deep reasoning |
| Charles 2.9 | charles-2.9 | charles-2.9:latest | Premium | State-of-the-art performance |
🔐 Security
API Key Management
Never hardcode API keys. Use environment variables:
// ✓ Good
const apiKey = process.env.SYLIX_API_KEY;
const sylix = new Sylix({ apiKey });
// ✗ Bad
const sylix = new Sylix({ apiKey: "sk-..." });Headers
The SDK automatically adds required authentication headers:
Content-Type: application/jsonx-api-key: <your-api-key>
Custom headers can be provided:
const sylix = new Sylix({
apiKey: "sk-...",
headers: {
"User-Agent": "my-app/1.0.0",
"X-Custom-Header": "value",
},
});⚠️ Error Handling
Errors are thrown as SylixError with useful context:
import { Sylix, SylixError } from "@sylix/sdk";
try {
const response = await sylix.chat.completions.create({
model: "gpt-4", // ← Invalid model
messages: [{ role: "user", content: "hi" }],
});
} catch (error) {
if (error instanceof SylixError) {
console.error(`[${error.code}] ${error.message}`);
console.error("Raw response:", error.raw);
}
}Common Errors
| Code | Meaning | Solution |
|------|---------|----------|
| MISSING_API_KEY | No API key provided | Provide apiKey in config |
| INVALID_MODEL | Model not in v1.0.0 | Use a model from CHARLES_MODELS |
| AUTH_ERROR | Authentication failed | Check your API key |
| SERVER_ERROR | Sylix API error | Retries automatically, check status |
🔄 Operational Guide
Swapping Models
To change models, simply update the model ID:
// Switch from mini to v1
const response = await sylix.chat.completions.create({
model: CHARLES_MODELS.V1, // Changed from CHARLES_MODELS.MINI
messages: [{ role: "user", content: "..." }],
});Use sylix.models() to list available options.
Versioning Best Practices
- Pin versions in package.json:
"@sylix/sdk": "^1.0.0" - Test new models before production: Always validate new model responses
- Monitor usage: Track which models are being used
- Plan upgrades: Review v1.1+ releases before updating
Timeout Configuration
Adjust timeouts for different scenarios:
// Short timeout for quick responses
const fast = new Sylix({
apiKey: process.env.SYLIX_API_KEY!,
timeout: 10000, // 10 seconds
});
// Long timeout for complex reasoning
const thorough = new Sylix({
apiKey: process.env.SYLIX_API_KEY!,
timeout: 120000, // 2 minutes
});🛠️ Adding Custom Models
To add custom models beyond v1.0.0 models:
1. Update Your Backend
Edit infra/models.json in your Sylix backend:
{
"models": [
{
"id": "charles-custom",
"name": "Charles Custom",
"displayName": "charles-custom:latest",
"description": "Custom fine-tuned model",
"capabilities": ["code", "chat"],
"tier": "custom"
}
]
}2. Create a Modelfile
Create infra/Modelfile.charles-custom:
FROM charles-custom:latest
PARAMETER temperature 0.7
SYSTEM """
You are a custom Charles model...
"""3. Update SDK (Roadmap for v1.1+)
Once v1.1 supports dynamic model loading, you'll be able to:
// Future API (v1.1+)
const sylix = new Sylix({
apiKey: process.env.SYLIX_API_KEY!,
customModels: ["charles-custom:latest"],
});
await sylix.chat.completions.create({
model: "charles-custom:latest",
messages: [...],
});For now, fork the SDK or wait for v1.1.
📖 Examples
Example 1: Interactive Chat
import { Sylix, CHARLES_MODELS } from "@sylix/sdk";
import * as readline from "readline";
const sylix = new Sylix({ apiKey: process.env.SYLIX_API_KEY! });
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const messages: Array<{ role: "user" | "assistant"; content: string }> = [];
const chat = async () => {
rl.question("You: ", async (input) => {
messages.push({ role: "user", content: input });
const response = await sylix.chat.completions.create({
model: CHARLES_MODELS.S1,
messages: messages as any,
});
const assistantMessage = response.choices[0].message.content;
messages.push({ role: "assistant", content: assistantMessage });
console.log(`Assistant: ${assistantMessage}\n`);
chat(); // Continue conversation
});
};
chat();Example 2: Batch Processing
import { Sylix, CHARLES_MODELS } from "@sylix/sdk";
const sylix = new Sylix({ apiKey: process.env.SYLIX_API_KEY! });
const prompts = [
"What is machine learning?",
"Explain blockchain in simple terms",
"How does photosynthesis work?",
];
const responses = await Promise.all(
prompts.map((prompt) =>
sylix.chat.completions.create({
model: CHARLES_MODELS.MINI,
messages: [{ role: "user", content: prompt }],
})
)
);
responses.forEach((response, index) => {
console.log(`[${prompts[index]}]`);
console.log(response.choices[0].message.content);
console.log("---");
});Example 3: Error Handling
import { Sylix, SylixError, CHARLES_MODELS } from "@sylix/sdk";
const sylix = new Sylix({ apiKey: process.env.SYLIX_API_KEY! });
try {
const response = await sylix.chat.completions.create({
model: CHARLES_MODELS.V1,
messages: [{ role: "user", content: "Complex reasoning task..." }],
max_tokens: 2000,
});
console.log(response.choices[0].message.content);
} catch (error) {
if (error instanceof SylixError) {
if (error.code === "INVALID_MODEL") {
console.error(`Invalid model. Available: ${CHARLES_MODELS}`);
} else if (error.code.includes("AUTH")) {
console.error("Authentication failed. Check your API key.");
} else {
console.error(`Error [${error.code}]: ${error.message}`);
}
} else {
console.error("Unexpected error:", error);
}
}🧪 Testing
Running Tests
npm test # Run all tests once
npm run test:watch # Watch modeWriting Tests
Tests use Vitest and should mock axios:
import { describe, it, expect, vi } from "vitest";
import { Sylix } from "./index";
describe("Sylix", () => {
it("should validate models", () => {
const sylix = new Sylix({ apiKey: "test" });
expect(() => {
sylix.chat.completions.create({
model: "invalid-model",
messages: [],
});
}).toThrow();
});
});🔨 Development
Building from Source
git clone https://github.com/sylix-ide/sylix-sdk.git
cd sylix-sdk
npm install
npm run build
npm testProject Structure
sylix-sdk/
├── src/
│ ├── index.ts # Main export
│ ├── types.ts # TypeScript types
│ ├── client.ts # HTTP client
│ ├── utils.ts # Utilities
│ └── *.test.ts # Tests
├── dist/ # Compiled output
├── infra/
│ ├── models.json # Model configuration
│ ├── ollama-pull.sh # Setup script
│ └── Modelfile.* # Ollama modelfiles
├── .github/workflows/
│ ├── ci.yml # Build & test
│ └── publish.yml # NPM publish
└── package.json📦 Publishing
Local Testing
npm run build
npm pack
# Creates sylix-sdk-1.0.0.tgz
# In another project:
npm install ../sylix-sdk/sylix-sdk-1.0.0.tgzPublishing to NPM
Ensure you have an NPM account and are logged in:
npm loginUpdate version in
package.jsonif neededPublish:
npm publish --access public
Or use the GitHub Actions workflow with NPM_TOKEN secret.
🗺️ Roadmap (v1.1+)
Streaming (v1.1)
- [ ] Server-Sent Events (SSE) for
stream: true - [ ] Async iterator support
- [ ] Long-polling fallback
File Uploads
- [ ]
vision.process()with multipart/form-data - [ ] Batch file processing
- [ ] File chunking for large files
Extended Endpoints
- [ ] Full
code.generate()implementation - [ ] Full
reason.process()implementation - [ ] Embeddings endpoint
- [ ] Fine-tuning API
Dynamic Model Loading
- [ ] Load models from server
- [ ] Custom model validation
- [ ] Model discovery API
Developer Tools
- [ ] CLI tool for testing
- [ ] Telemetry & logging (optional)
- [ ] Rate limiting client-side
- [ ] Mock server for testing
🤝 Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Commit changes:
git commit -am 'Add feature' - Push to branch:
git push origin feature/my-feature - Submit a Pull Request
📄 License
MIT © 2025 Sylix IDE. See LICENSE for details.
🙋 Support & Questions
- Documentation: https://github.com/sylix-ide/sylix-sdk#readme
- Issues: https://github.com/sylix-ide/sylix-sdk/issues
- Website: https://sylixide.com
- Email: [email protected]
🔗 Resources
- Sylix API Documentation
- Sylix API Reference (for API style reference)
- Ollama Documentation
- TypeScript Handbook
Built with ❤️ by the Sylix team
