@cubicler/cubickit-openai
v0.0.1
Published
Adapter for integrating OpenAI's Chat API with the Cubicler orchestration system.
Maintainers
Readme
CubicKit-OpenAI
An adapter for integrating OpenAI's Chat API with the Cubicler orchestration system.
Features
- 🤖 Seamless OpenAI Integration: Uses OpenAI's chat completions API with automatic tool/function calling
- 🔧 Automatic Tool Injection: Fetches function specifications from Cubicler and automatically converts them to OpenAI tools format
- 🔄 Smart Tool Call Routing: Automatically routes OpenAI tool calls to Cubicler's function execution endpoint
- 📦 Built on CubicKit: Leverages CubicKit's caching and fallback mechanisms
- 🎯 Type-Safe: Full TypeScript support with proper type definitions
- ⚡ Easy to Use: Simple API that handles all the complexity behind the scenes
Installation
npm install @cubicler/cubickit-openaiQuick Start
import { OpenAICubicClient } from '@cubicler/cubickit-openai';
// Initialize the kit
const openaiClient = new OpenAICubicClient({
apiKey: 'your-openai-api-key',
cubiclerBaseUrl: 'https://your-cubicler-instance.com',
model: 'gpt-4o', // Optional, defaults to 'gpt-4o'
});
// Start chatting - tools are automatically injected and handled
const response = await openaiClient.chat([
{ role: 'user', content: 'Hello! Can you help me with something?' }
]);
console.log(response.choices[0].message.content);How It Works
- Fetches System Prompt: Automatically retrieves the system prompt from
GET /promptvia CubicKit - Loads Function Specs: Fetches available functions from
GET /specvia CubicKit - Converts to OpenAI Tools: Transforms Cubicler function specs into OpenAI tools format
- Handles Chat: Sends chat requests to OpenAI with injected tools
- Routes Tool Calls: When OpenAI calls a tool, automatically routes it to Cubicler via
POST /call - Continues Conversation: Feeds tool results back to OpenAI to complete the conversation
Configuration
import { OpenAICubicClient, OpenAICubicClientConfigurations } from '@cubicler/cubickit-openai';
const config: OpenAICubicClientConfigurations = {
apiKey: 'your-openai-api-key', // Required: OpenAI API key
cubiclerBaseUrl: 'https://your.cubicler.com', // Required: Cubicler base URL
model: 'gpt-4o', // Optional: OpenAI model (default: 'gpt-4o')
promptCacheTimeout: 600, // Optional: Prompt cache timeout in seconds (default: 600)
specCacheTimeout: 600, // Optional: Spec cache timeout in seconds (default: 600)
};
const openaiClient = new OpenAICubicClient(config);Advanced Usage
Adding Internal Functions
You can add internal functions that will be injected alongside (or override) Cubicler functions:
// Add a single function
openaiClient.addFunction(
{
type: 'function',
function: {
name: 'getCurrentTime',
description: 'Get the current date and time',
parameters: {
type: 'object',
properties: {
timezone: { type: 'string', description: 'Timezone (optional)' },
},
},
},
},
async (parameters) => {
const timezone = parameters.timezone || 'UTC';
return {
currentTime: new Date().toLocaleString('en-US', { timeZone: timezone }),
timezone: timezone,
};
}
);
// Chain multiple functions
openaiClient
.addFunction(spec1, callback1)
.addFunction(spec2, callback2)
.addFunction(spec3, callback3);
// Remove a function
openaiClient.removeFunction('functionName');
// Clear all internal functions
openaiClient.clearFunctions();
// Get all available function names
const functionNames = await openaiClient.getFunctionNames();Priority Rules:
- Internal functions take priority over Cubicler functions with the same name
- This allows you to override or extend Cubicler's functionality
- Internal functions are called directly without going through Cubicler
Custom Chat Options
You can pass any OpenAI chat completion parameters:
const response = await openaiClient.chat(
[{ role: 'user', content: 'Hello!' }],
{
temperature: 0.7,
max_tokens: 1000,
top_p: 0.9,
}
);Access Underlying Clients
// Get the OpenAI client for advanced usage
const openaiClient = openaiClient.getOpenAIClient();
// Get the CubicKit client for direct Cubicler interaction
const cubicKitClient = openaiClient.getCubicKitClient();Force Cache Refresh
// Force refresh both prompt and spec caches
await openaiClient.refreshCache();Error Handling
The kit automatically handles:
- Network failures (falls back to cached data via CubicKit)
- Tool call errors (returns error messages to continue conversation)
- Invalid function parameters (graceful error handling)
try {
const response = await openaiClient.chat([
{ role: 'user', content: 'Execute a complex task' }
]);
} catch (error) {
console.error('Chat failed:', error);
}Examples
Simple Question Answering
const response = await openaiClient.chat([
{ role: 'user', content: 'What is the weather like today?' }
]);Multi-turn Conversation
const messages = [
{ role: 'user', content: 'I need to analyze some data' },
{ role: 'assistant', content: 'I can help with that. What kind of data analysis do you need?' },
{ role: 'user', content: 'Customer sales data for the last quarter' },
];
const response = await openaiClient.chat(messages);Function Calling
The kit automatically handles function calls. When OpenAI decides to call a function:
- OpenAI returns a tool call
- The kit routes it to Cubicler's
/callendpoint - The result is fed back to OpenAI
- OpenAI continues the conversation with the result
// This will automatically trigger function calls if the AI decides they're needed
const response = await openaiClient.chat([
{ role: 'user', content: 'Get me the user details for user ID 12345' }
]);Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Your App │───▶│ OpenAI Kit │───▶│ OpenAI │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐ ┌─────────────────┐
│ CubicKit │───▶│ Cubicler │
└─────────────────┘ └─────────────────┘The OpenAI Kit acts as a bridge between OpenAI's chat API and Cubicler's function execution system, providing a seamless experience for building AI agents that can execute real-world tasks.
License
MIT
