Advanced Usage Examples
Explore the platform's advanced capabilities with these in-depth examples. You will learn how to use batch processing, context-aware analysis, and specialized modes.
Each example below shows two things: the code you want to analyze and the SDK call that sends it to the API. Read the explanation card at the bottom of each example to see what the AI found.
Batch Processing
Here is how you can send several files at once and get a single set of results back. This saves time when you need to understand an entire module.
Code to Analyze
Source Code
interface User {
id: string;
name: string;
email: string;
role: 'admin' | 'user';
}
const processUsers = async (users: User[]) => {
const results = await Promise.all(
users.map(async user => {
try {
await validateUser(user);
await updateUserRole(user);
return { success: true, user };
} catch (error) {
return { success: false, error, user };
}
})
);
return {
successful: results.filter(r => r.success),
failed: results.filter(r => !r.success),
};
};Advanced API Usage
SDK Usage
import { ExplainThis } from '@explainthis/sdk';
const explainThis = new ExplainThis(process.env.EXPLAINTHIS_API_KEY);
// Prepare multiple code snippets
const snippets = [
{ code: validateUser.toString(), context: 'User validation' },
{ code: updateUserRole.toString(), context: 'Role update' },
{ code: processUsers.toString(), context: 'Main process' },
];
// Get batch explanations
const explanations = await explainThis.batchExplain({
snippets,
mode: 'performance',
language: 'typescript',
});
// Process each explanation
explanations.forEach((exp, i) => {
console.log(`Explanation for ${snippets[i].context}:`);
console.log(exp);
});Analysis Details
This example shows batch processing of user data with TypeScript. It runs all operations at once using Promise.all and handles errors for each user. The result splits into successes and failures. The API call sends several related functions in one batch for better context.
Custom Analysis with Context
Sometimes the AI needs more background to give a good answer. In this example, you attach related files and dependency versions so the analysis is as accurate as possible.
Code to Analyze
Source Code
from typing import List, Dict, Optional
from datetime import datetime
import pandas as pd
class DataAnalyzer:
def __init__(self, config: Dict[str, any]):
self.config = config
self.cache: Dict[str, pd.DataFrame] = {}
def analyze_time_series(
self,
data: pd.DataFrame,
metrics: List[str],
window: Optional[int] = None
) -> Dict[str, pd.Series]:
"""
Analyze time series data with rolling windows and custom metrics.
Args:
data: Time series data
metrics: List of metrics to calculate
window: Rolling window size
"""
results = {}
for metric in metrics:
if window:
result = data.rolling(window).agg(metric)
else:
result = data.agg(metric)
results[metric] = result
return resultsAdvanced API Usage
SDK Usage
from explainthis import ExplainThis, AnalysisContext
client = ExplainThis(api_key='your_api_key')
# Create analysis context
context = AnalysisContext(
imports=['pandas', 'numpy'],
related_code={
'config.py': 'Configuration settings',
'metrics.py': 'Custom metric definitions'
},
dependencies={
'pandas': '2.0.0',
'numpy': '1.24.0'
}
)
# Get detailed explanation
explanation = client.explain(
code=code,
mode='performance',
language='python',
context=context,
include_suggestions=True
)
print(explanation)Analysis Details
This example shows a data analysis class that uses pandas for time series work. The code includes type hints, docstrings, and flexible config. The API call adds context about related files and dependencies. This helps the analyzer give more accurate results, including notes on how pandas operations affect performance.
Security Analysis Mode
Want to find security holes before they reach production? This example runs a full security scan on an authentication endpoint, checking for common mistakes.
Code to Analyze
Source Code
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const app = express();
app.use(express.json());
app.post('/api/auth', async (req, res) => {
const { username, password } = req.body;
try {
// Get user from database
const user = await db.collection('users')
.findOne({ username });
if (!user) {
return res.status(401).json({
error: 'Invalid credentials'
});
}
// Verify password
const valid = await bcrypt.compare(
password,
user.password
);
if (!valid) {
return res.status(401).json({
error: 'Invalid credentials'
});
}
// Generate token
const token = jwt.sign(
{ userId: user._id },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({ token });
} catch (error) {
res.status(500).json({
error: 'Internal server error'
});
}
});Advanced API Usage
SDK Usage
import { ExplainThis } from '@explainthis/sdk';
const explainThis = new ExplainThis(process.env.EXPLAINTHIS_API_KEY);
const securityAnalysis = await explainThis.explain({
code: code,
mode: 'security',
language: 'javascript',
options: {
checkDependencies: true,
scanVulnerabilities: true,
suggestFixes: true,
}
});
console.log('Security Analysis:');
console.log(securityAnalysis.vulnerabilities);
console.log('Suggested Fixes:');
console.log(securityAnalysis.fixes);Analysis Details
This authentication endpoint covers several security topics. The security mode checks for: proper password hashing with bcrypt, JWT token creation, error messages that don't leak info, and use of environment variables for secrets. It also scans dependencies for known flaws and suggests fixes.
Advanced Features
Here is a quick summary of what you can do beyond the basics:
- Batch processing — Send several snippets at once and get all the results back in a single response.
- Context-aware analysis — Attach related files and dependency info so the AI gives more accurate results.
- Security scanning — Ask the AI to hunt for vulnerabilities and suggest fixes before you ship.
- Custom options — Fine-tune the analysis by choosing focus areas, audience level, and output detail.
- Performance mode — Get tips on how to make your code run faster and use less memory.