# Best Practices

### 1. API Key Management

```typescript
// ✅ Good - Environment variables
const ai = AIModel.createFromEnv('openai');

// ✅ Good - Secure config service
const ai = new AIModel({
  apiKey: configService.getAIKey(),
  provider: 'openai'
});

// ❌ Avoid - Hardcoded keys
const ai = new AIModel({
  apiKey: 'sk-12345...',  // Don't do this!
  provider: 'openai'
});
```

### 2. Error Handling

```typescript
// ✅ Good - Comprehensive error handling
try {
  const response = await ai.sendTextMessage(userInput);
  return response.content;
} catch (error) {
  if (error.message.includes('context length')) {
    // Handle context window issues
    await ai.clearMessages();
    return await ai.sendTextMessage('Please summarize your previous question: ' + userInput);
  }
  throw error; // Re-throw unexpected errors
}

// ❌ Avoid - Silent failures
const response = await ai.sendTextMessage(input); // No error handling
```

### 3. Token Management

```typescript
// ✅ Good - Monitor token usage
const response = await ai.sendTextMessage(largeText);
console.log(`Used ${response.usage.totalTokens} tokens`);

// Estimate costs (rough calculation)
const cost = (response.usage.totalTokens / 1000) * 0.002; // Adjust per model
console.log(`Estimated cost: $${cost.toFixed(4)}`);

// ❌ Avoid - Uncontrolled token usage
// No monitoring of token consumption
```

### 4. Conversation Management

```typescript
// ✅ Good - Manage context window
function isConversationTooLong(ai: AIModel): boolean {
  const messages = ai.getMessages();
  const totalLength = messages.reduce((sum, msg) => {
    return sum + (typeof msg.content === 'string' ? msg.content.length : 1000);
  }, 0);
  return totalLength > 8000; // Approximate token limit
}

// Reset if conversation gets too long
if (isConversationTooLong(ai)) {
  ai.clearMessages();
  ai.addSystemPrompt('Previous conversation was cleared due to length limits.');
}
```