@gpt-core/client
v0.10.20
Published
TypeScript SDK for GPT Core Client API - Document extraction, AI agents, and workspace management
Readme
@gpt-core/client
The official TypeScript SDK for the GPT Core Platform - document extraction, AI agents, and workspace management.
For AI Coding Assistants
TL;DR for Claude, Cursor, Copilot, and other AI assistants:
import { GptClient } from '@gpt-core/client'; const client = new GptClient({ baseUrl: 'https://api.example.com', token: 'jwt' });Common operations: | Task | Code | |------|------| | Login |
await client.identity.login(email, password)| | List workspaces |await client.platform.workspaces.mine()| | Upload document |await client.extraction.documents.uploadBase64(name, b64)| | AI search |await client.ai.search(query)| | Create agent |await client.ai.agents.create(name, systemPrompt)| | Send message |await client.ai.threads.sendMessage(threadId, content)|See llms.txt for complete AI-readable SDK reference.
Features
✅ Fully Typed - Complete TypeScript support with auto-generated types from OpenAPI specs ✅ Runtime Validation - Zod schemas for request validation ✅ Smart Error Handling - Custom error classes with detailed context ✅ Automatic Retries - Exponential backoff for transient failures ✅ Pagination Support - Async iterators for easy iteration over large datasets ✅ Streaming Support - Server-Sent Events (SSE) for real-time AI responses ✅ JSON:API Compliant - Automatic envelope unwrapping
Installation
npm install @gpt-core/client
# or
yarn add @gpt-core/client
# or
pnpm add @gpt-core/clientQuick Start
import { GptClient } from '@gpt-core/client';
// Initialize client
const client = new GptClient({
baseUrl: 'https://api.gpt-core.com',
apiKey: 'your-api-key', // For machine-to-machine
token: 'user-jwt-token', // For user-authenticated requests
});
// Authenticate a user
const { user, token } = await client.identity.login(
'[email protected]',
'password'
);
console.log(`Welcome, ${user.attributes.full_name}!`);
// Use the token for subsequent requests
const authenticatedClient = new GptClient({
baseUrl: 'https://api.gpt-core.com',
token: token,
});
// List workspaces
const workspaces = await authenticatedClient.platform.workspaces.mine();API Versioning
The SDK uses Stripe-style API versioning. A default API version is sent with every request via the Accept header.
Default Behavior
Every request automatically includes the SDK's built-in API version:
Accept: application/vnd.api+json; version=2025-12-03No configuration is needed -- the SDK sends DEFAULT_API_VERSION from base-client.ts automatically.
Pinning a Version (Recommended for Production)
Pin a specific API version to protect your integration from breaking changes:
const client = new GptClient({
baseUrl: 'https://api.gpt-core.com',
apiKey: 'sk_live_...',
apiVersion: '2025-12-03', // Pin to this version
});Reading the Active Version
// The version the SDK is configured to send
console.log(client.apiVersion);Response Header
Every API response includes the version that was used to process the request:
x-api-version: 2025-12-03Discovering Available Versions
List all supported API versions and their changelogs:
GET /api-versionsThis returns the full list of versions with descriptions and deprecation status.
Configuration
const client = new GptClient({
// Required: API base URL
baseUrl: 'https://api.gpt-core.com',
// Authentication (provide one or both)
apiKey: 'sk_live_...', // Application API key
token: 'eyJhbGc...', // User JWT token
// API version (optional, uses SDK default if not specified)
apiVersion: '2025-12-03',
// Security configuration (optional)
security: {
requireHttps: false, // Throw error on HTTP (default: warn only)
warnBrowserApiKey: true, // Warn about API keys in browser (default: true)
},
// Retry configuration (optional)
retry: {
maxRetries: 3, // Default: 3
initialDelay: 1000, // Default: 1000ms (renamed from minTimeout)
maxDelay: 32000, // Default: 32000ms (renamed from maxTimeout)
retryableStatusCodes: [429, 500, 502, 503, 504],
totalTimeout: 300000, // Total timeout across all retries (ms)
maxRetryAfter: 60, // Max Retry-After header value (seconds)
},
// Disable retries
retry: false,
});Security Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| requireHttps | boolean | false | Throw InsecureConnectionError on non-HTTPS URLs |
| warnBrowserApiKey | boolean | true | Warn when API key detected in browser environment |
HTTPS Enforcement
// Development: Warns only
const devClient = new GptClient({
baseUrl: 'http://localhost:22222',
apiKey: process.env.API_KEY,
security: { requireHttps: false },
});
// Production: Blocks HTTP
const prodClient = new GptClient({
baseUrl: 'https://api.gpt-core.com',
apiKey: process.env.API_KEY,
security: { requireHttps: true },
});
try {
await prodClient.agents.list();
} catch (error) {
if (error instanceof InsecureConnectionError) {
console.error('Cannot use HTTP in production');
}
}API Key Validation
The SDK validates API key format and warns about elevated privilege keys:
// Valid keys: sk_tenant_*, sk_app_*, sk_srv_*, sk_sys_*
// sk_sys_* keys trigger warnings (elevated privileges)
const client = new GptClient({
apiKey: 'sk_sys_abc123',
});
// [GPT Core SDK] Using system-level API key (sk_sys_).
// Ensure this is intended for platform operations.API Reference
Identity
Manage users, authentication, and API keys.
// Login
const { user, token } = await client.identity.login(email, password);
// Register
const user = await client.identity.register(email, password, passwordConfirmation);
// Get current user
const user = await client.identity.me();
// Get user profile
const profile = await client.identity.profile();
// API Keys
const keys = await client.identity.apiKeys.list();
const newKey = await client.identity.apiKeys.create('Production Key');
await client.identity.apiKeys.allocate('key-id', 1000, 'Monthly credits');Platform
Manage applications, workspaces, and tenants.
// Applications
const apps = await client.platform.applications.list();
const app = await client.platform.applications.create({
name: 'My App',
slug: 'my-app',
});
const app = await client.platform.applications.getBySlug('my-app');
// Workspaces
const workspaces = await client.platform.workspaces.list();
const myWorkspaces = await client.platform.workspaces.mine();
const workspace = await client.platform.workspaces.create('New Workspace', 'new-workspace');
// Invitations
await client.platform.invitations.invite(
'[email protected]',
'editor',
'workspace',
'workspace-id'
);AI
Interact with agents, threads, and semantic search.
// Agents
const agents = await client.ai.agents.list();
const agent = await client.ai.agents.create(
'Support Agent',
'You are a helpful customer support agent'
);
// Threads (Conversations)
const threads = await client.ai.threads.list();
const thread = await client.ai.threads.create('Bug Report Discussion');
const message = await client.ai.threads.sendMessage(thread.id, 'Hello AI!');
// Search
const results = await client.ai.search('quarterly earnings', 10);
// Embeddings
const embedding = await client.ai.embed('text to embed');Extraction
Upload and analyze documents.
// Documents
const documents = await client.extraction.documents.list();
// Upload (base64)
const doc = await client.extraction.documents.uploadBase64(
'report.pdf',
base64Content
);
// Analyze
await client.extraction.documents.analyze(doc.id);
// Retrieve
const doc = await client.extraction.documents.get('doc-id');
// Delete
await client.extraction.documents.delete('doc-id');
// Results
const results = await client.extraction.results.list();Storage
Manage buckets and files.
// Buckets
const buckets = await client.storage.buckets.list();
const bucket = await client.storage.buckets.create('uploads', false);
// Presigned URLs
const uploadUrl = await client.storage.presigned.upload(
'image.png',
'image/png'
);
const downloadUrl = await client.storage.presigned.download('file-id');Billing
Access wallet and plan information.
// Wallet
const wallet = await client.billing.wallet.get();
// Plans
const plans = await client.billing.plans.list();Advanced Features
Error Handling
The SDK provides detailed error classes:
import {
AuthenticationError,
AuthorizationError,
NotFoundError,
ValidationError,
RateLimitError,
ServerError,
} from '@gpt-core/client';
try {
await client.identity.login('[email protected]', 'wrong-password');
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid credentials:', error.message);
console.error('Request ID:', error.requestId);
} else if (error instanceof ValidationError) {
console.error('Validation errors:', error.errors);
} else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter}s`);
}
}Pagination
Easily iterate over large datasets with built-in memory protection:
import { paginateAll } from '@gpt-core/client';
// Using async iteration
for await (const workspace of client.platform.workspaces.listAll()) {
console.log(workspace.attributes.name);
}
// With limit (default: 10,000)
for await (const doc of client.extraction.documents.listAll({ limit: 100 })) {
console.log(doc.attributes.filename);
}
// Custom page size
for await (const item of paginateAll(fetcher, { pageSize: 50, limit: 1000 })) {
// Process items
}Pagination Safety:
- Default Limit: 10,000 items max (prevents memory exhaustion)
- Warning: Shows warning when fetching > 1,000 items
- Configurable: Set custom
limitfor your use case
Streaming
Stream AI responses in real-time:
import { streamMessage } from '@gpt-core/client';
// Make streaming request
const response = await fetch(streamingEndpoint, {
method: 'POST',
headers: { 'Accept': 'text/event-stream' },
body: JSON.stringify({ content: 'Hello AI' }),
});
// Stream the response
for await (const chunk of streamMessage(response)) {
if (chunk.type === 'content') {
process.stdout.write(chunk.content); // Real-time output
}
}Retry Logic
Automatic retries with exponential backoff and circuit breaker:
// Retries are enabled by default with circuit breaker protection
const client = new GptClient({
baseUrl: 'https://api.gpt-core.com',
token: 'token',
retry: {
maxRetries: 5, // Retry up to 5 times
initialDelay: 1000, // Start with 1s delay
maxDelay: 32000, // Max delay between retries
totalTimeout: 300000, // Total timeout (5 min) prevents infinite loops
maxRetryAfter: 60, // Cap Retry-After header to 60s
},
});
// Disable retries for specific operations
const noRetryClient = new GptClient({
baseUrl: 'https://api.gpt-core.com',
token: 'token',
retry: false,
});Retry Behavior:
- Circuit Breaker: Total timeout prevents unbounded retry loops
- Retry-After Validation: Server Retry-After headers capped at 60 seconds
- Jitter: Random delay added to prevent thundering herd
- Protected Status Codes: 429, 500, 502, 503, 504
import { RetryTimeoutError } from '@gpt-core/client';
try {
await client.agents.list();
} catch (error) {
if (error instanceof RetryTimeoutError) {
console.error('Retry timeout exceeded:', error.message);
}
}TypeScript Support
The SDK is written in TypeScript and provides full type safety:
import type { user, workspace, document } from '@gpt-core/client';
const user: user = await client.identity.me();
// TypeScript knows: user.attributes.email, user.id, etc.
const workspace: workspace = await client.platform.workspaces.create('Test');
// TypeScript enforces correct parametersLicense
MIT © GPT Integrators
Support
- 📧 Email: [email protected]
- 📚 Documentation: https://docs.gpt-core.com
- 🐛 Issues: https://github.com/GPT-Integrators/gpt-core-sdks/issues
