Guides
Use and adapt AI-Model-Wrapper-for-OpenAI
Use and adapt AI-Model-Wrapper-for-OpenAI: A clean, TypeScript-based wrapper for the OpenAI API with built-in conversation management, streaming support, and optional debug logging.
Use the documented interfaces and source layout for AI-Model-Wrapper-for-OpenAI. The sections below retain the README’s examples and configuration details.
Usage Examples
1. Basic Text Conversations
// Method 1: One-liner approach
const response1 = await ai.sendTextMessage('Tell me a joke about programming');
// Method 2: Conversation chain
const response2 = await ai
.addUserMessage('Hello!')
.addAssistantMessage('Hi there! How can I help you?')
.addUserMessage('What is the capital of France?')
.send();
// Method 3: Multiple messages at once
const response3 = await ai.sendMultipleMessages([
{ role: 'user', content: 'Hello' },
{ role: 'assistant', content: 'Hi! How can I help?' },
{ role: 'user', content: 'Tell me about TypeScript' }
]);2. Image Analysis
// Analyze image with text question
const imageResponse = await ai.sendImageMessage(
'What do you see in this image? Describe the main elements.',
'https://example.com/image.jpg'
);
// Or use the chain method
const imageAnalysis = await ai
.addImageMessage('Analyze this image', 'https://example.com/photo.jpg')
.send();3. Streaming Responses
// Stream response in real-time
const fullResponse = await ai.stream((chunk) => {
process.stdout.write(chunk); // Print as it comes
});
// Streaming with custom options
const streamedText = await ai.stream(
(chunk) => console.log('Chunk:', chunk),
{ temperature: 0.9, maxTokens: 500 }
);4. System Prompts and Context
// Set AI personality/behavior
const aiWithPersonality = new AIModel({
apiKey: 'your-key',
provider: 'openai'
}).setSystemPrompt(`
You are a knowledgeable historian specializing in European history.
Provide detailed, accurate information with dates and context.
Be engaging but factual in your responses.
`);
const historyResponse = await aiWithPersonality
.addUserMessage('Tell me about the Renaissance period')
.send();5. Configuration Management
import { ConfigManager } from './ai-model-lib';
// Global configuration
const config = ConfigManager.getInstance();
config.setDefaultConfig({
temperature: 0.7,
maxTokens: 1500,
debug: process.env.NODE_ENV === 'development',
retryAttempts: 5
});
// Create pre-configured models
const ai = config.createModel({
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4'
});6. Error Handling and Retries
try {
const response = await ai
.addUserMessage('Generate a long story about space exploration')
.send({ maxTokens: 2000 });
console.log('Success:', response.content);
} catch (error) {
if (error.message.includes('API key')) {
console.error('Authentication failed - check your API key');
} else if (error.message.includes('rate limit')) {
console.error('Rate limit exceeded - try again later');
} else if (error.message.includes('timeout')) {
console.error('Request timed out - check your connection');
} else {
console.error('Unexpected error:', error.message);
}
}7. Advanced Conversation Management
// Complex conversation with context
const conversation = await ai
.setSystemPrompt('You are a helpful travel assistant. Provide concise, practical advice.')
.addUserMessage('I want to visit Japan next month')
.addAssistantMessage('Great choice! Japan is wonderful. What cities are you thinking of visiting?')
.addUserMessage('Tokyo and Kyoto for 10 days')
.addAssistantMessage('Excellent itinerary. Tokyo for modern experiences, Kyoto for tradition.')
.addUserMessage('What should I pack for April?')
.send();
console.log('Travel advice:', conversation.content);
// Check conversation history
const messages = ai.getMessages();
messages.forEach((msg, index) => {
console.log(`${index + 1}. ${msg.role}: ${msg.content}`);
});Configuration
Model Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
apiKey | string | Required | Provider API key |
provider | string | "openrouter" | Provider ID |
model | string | Provider default | Specific model name |
temperature | number | 0.7 | Creativity (0.0-1.0) |
maxTokens | number | 1000 | Response length limit |
systemPrompt | string | "" | AI context/behavior |
debug | boolean | false | Enable logging |
timeout | number | 30000 | Request timeout (ms) |
retryAttempts | number | 3 | Retry attempts on failure |
Provider Configuration
import { ProviderRegistry } from './ai-model-lib';
// Register custom provider
ProviderRegistry.registerProvider('my-provider', {
name: 'My AI Service',
baseURL: 'https://api.my-ai.com/v1',
defaultModel: 'my-model-v1',
headers: {
'X-Custom-Header': 'value'
}
});Core Concepts
Message Types
| Type | Description | Example |
|---|---|---|
| Text Message | Simple text content | "Hello world" |
| Image Message | Text + image URL | { text: "Describe this", imageUrl: "..." } |
| System Prompt | AI behavior/context | "You are a helpful assistant" |
| Structured Message | Multiple content parts | [{ type: "text", text: "..." }, { type: "image_url", ... }] |
Provider Support
| Provider | Default Model | Base URL | Features |
|---|---|---|---|
| OpenRouter | mistralai/mistral-small-3.1-24b-instruct:free | https://openrouter.ai/api/v1 | Multiple models, free tier |
| OpenAI | gpt-3.5-turbo | https://api.openai.com/v1 | GPT models, vision |
| Anthropic | claude-3-haiku-20240307 | https://api.anthropic.com/v1 | Claude models |
| Custom | User-defined | User-defined | Any OpenAI-compatible API |
API Reference
AIModel Class
Constructor
new AIModel(config: AIModelConfig, logger?: Logger)| Parameter | Type | Required | Description |
|---|---|---|---|
config | AIModelConfig | Yes | Model configuration |
logger | Logger | No | Custom logger instance |
Core Methods
| Method | Returns | Description |
|---|---|---|
send(options?) | Promise<AIResponse> | Send conversation and get response |
stream(onChunk, options?) | Promise<string> | Stream response in real-time |
sendTextMessage(text, options?) | Promise<AIResponse> | Quick text message and response |
sendImageMessage(text, imageUrl, options?) | Promise<AIResponse> | Quick image analysis |
sendMultipleMessages(messages, options?) | Promise<AIResponse> | Send multiple messages at once |
Message Management
| Method | Returns | Description |
|---|---|---|
addMessage(content, role) | this | Add message to conversation |
addUserMessage(content) | this | Add user message |
addAssistantMessage(content) | this | Add assistant message |
addTextMessage(text, role) | this | Add text message |
addImageMessage(text, imageUrl) | this | Add image with text |
getMessages() | Message[] | Get all messages |
clearMessages() | this | Clear conversation history |
reset() | this | Reset model (messages + system prompt) |
Configuration Methods
| Method | Returns | Description |
|---|---|---|
setSystemPrompt(prompt) | this | Set/update system prompt |
getSystemPrompt() | string | Get current system prompt |
updateConfig(config) | this | Update model configuration |
getConfig() | AIModelConfig | Get current configuration |
enableDebug(enable) | this | Enable/disable debug logging |
Static Factory Methods
| Method | Returns | Description |
|---|---|---|
create(config, logger?) | AIModel | Create new instance |
createFromEnv(provider?, overrides?, logger?) | AIModel | Create from environment variables |
createForProvider(providerId, apiKey, overrides?, logger?) | AIModel | Create for specific provider |
AIResponse Interface
| Property | Type | Description |
|---|---|---|
content | string | Generated text response |
usage.promptTokens | number | Input tokens used |
usage.completionTokens | number | Output tokens used |
usage.totalTokens | number | Total tokens used |
model | string | Model that generated response |
finishReason | string | Reason generation stopped |
ProviderRegistry Class
| Method | Returns | Description |
|---|---|---|
registerProvider(id, config) | void | Register new provider |
getProvider(id) | `AIProviderConfig | undefined` |
getAllProviders() | Map<string, AIProviderConfig> | Get all providers |
updateProvider(id, config) | boolean | Update provider config |
hasProvider(id) | boolean | Check if provider exists |
removeProvider(id) | boolean | Remove provider |
Error Handling
Common Error Types
| Error Type | Cause | Solution |
|---|---|---|
| AuthenticationError | Invalid API key | Check API key validity |
| RateLimitError | Too many requests | Implement backoff, upgrade plan |
| TimeoutError | Request timeout | Increase timeout, check network |
| ModelNotFound | Invalid model name | Check provider model list |
| ProviderNotFound | Unknown provider | Register provider or check spelling |
Retry Configuration
const resilientAI = new AIModel({
apiKey: 'your-key',
provider: 'openai',
retryAttempts: 5, // 5 retry attempts
timeout: 60000, // 60 second timeout
debug: true
});
// Automatic retry with exponential backoff:
// Attempt 1: Immediate
// Attempt 2: 2 second delay
// Attempt 3: 4 second delay
// Attempt 4: 8 second delay
// Attempt 5: 16 second delayTroubleshooting
Common Issues
| Issue | Solution |
|---|---|
| Module not found | Check import path, ensure dependencies installed |
| API key errors | Verify API key, check provider requirements |
| Network timeouts | Increase timeout setting, check firewall |
| Model not available | Check provider documentation for available models |
| TypeScript errors | Ensure proper types are imported |
Debug Mode
// Enable debug logging
const ai = new AIModel({
apiKey: 'your-key',
provider: 'openai',
debug: true // Enable detailed logging
});
// Or enable later
ai.enableDebug(true);Source and help
Source captured: 2026-10-11
