Skip to content

AI Integration Patterns ​

Common patterns for integrating AI into your applications effectively and safely.

Pattern Categories ​

  1. Code Generation Patterns
  2. Code Review Patterns
  3. Documentation Patterns
  4. Testing Patterns
  5. Data Processing Patterns

Code Generation Patterns ​

Pattern: Scaffold Generator ​

Generate boilerplate code based on specifications.

typescript
interface ScaffoldSpec {
  type: 'api' | 'component' | 'service';
  name: string;
  fields?: Array<{ name: string; type: string }>;
  methods?: string[];
}

async function generateScaffold(spec: ScaffoldSpec): Promise<string> {
  const prompt = `
Generate a ${spec.type} named ${spec.name}.
${spec.fields ? `Fields: ${JSON.stringify(spec.fields)}` : ''}
${spec.methods ? `Methods: ${spec.methods.join(', ')}` : ''}

Requirements:
- Use TypeScript
- Include JSDoc comments
- Add error handling
- Follow enterprise coding standards
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return response.content;
}

Pattern: Code Completion ​

Context-aware code completion.

typescript
interface CodeContext {
  precedingCode: string;
  followingCode: string;
  cursor: number;
}

async function completeCode(context: CodeContext): Promise<string[]> {
  const prompt = `
Complete the code at the cursor position.

Preceding code:
${context.precedingCode}

[CURSOR]

Following code:
${context.followingCode}

Provide 3 alternative completions.
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return parseCompletions(response.content);
}

Code Review Patterns ​

Pattern: Automated Review ​

Automated code review with AI.

typescript
interface ReviewResult {
  issues: Issue[];
  suggestions: Suggestion[];
  score: number;
}

interface Issue {
  severity: 'low' | 'medium' | 'high' | 'critical';
  category: string;
  description: string;
  line?: number;
}

async function reviewCode(
  code: string,
  language: string
): Promise<ReviewResult> {
  const prompt = `
Review this ${language} code for:
1. Bugs and logic errors
2. Security vulnerabilities
3. Performance issues
4. Code style and best practices

Format response as JSON:
{
  "issues": [{"severity": "...", "category": "...", "description": "...", "line": ...}],
  "suggestions": ["..."],
  "score": 0-100
}

Code:
${code}
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return JSON.parse(extractJSON(response.content));
}

Pattern: PR Summary Generator ​

Generate pull request summaries.

typescript
interface PRSummary {
  title: string;
  description: string;
  changes: string[];
  impact: string;
  testing: string;
}

async function generatePRSummary(
  diff: string,
  commits: string[]
): Promise<PRSummary> {
  const prompt = `
Analyze this pull request and generate a summary.

Commits:
${commits.join('\n')}

Diff:
${diff}

Generate a JSON summary with:
- title: Concise PR title
- description: What changed and why
- changes: List of key changes
- impact: Impact on the codebase
- testing: Testing recommendations
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return JSON.parse(extractJSON(response.content));
}

Documentation Patterns ​

Pattern: API Doc Generator ​

Generate API documentation from code.

typescript
async function generateAPIDocs(code: string): Promise<string> {
  const prompt = `
Generate comprehensive API documentation for this code.

Include:
- Overview and purpose
- Parameters with types and descriptions
- Return values
- Usage examples
- Error conditions
- Notes and warnings

Format in Markdown.

Code:
${code}
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return response.content;
}

Pattern: README Generator ​

Generate README files for projects.

typescript
interface ProjectInfo {
  name: string;
  description: string;
  files: string[];
  packageJson?: any;
}

async function generateREADME(info: ProjectInfo): Promise<string> {
  const prompt = `
Generate a comprehensive README.md for this project.

Project: ${info.name}
Description: ${info.description}
Key files: ${info.files.join(', ')}
${info.packageJson ? `Dependencies: ${Object.keys(info.packageJson.dependencies || {}).join(', ')}` : ''}

Include:
- Project title and description
- Installation instructions
- Usage examples
- API documentation
- Contributing guidelines
- License information
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return response.content;
}

Testing Patterns ​

Pattern: Test Case Generator ​

Generate test cases from code.

typescript
interface TestSuite {
  framework: string;
  tests: string;
}

async function generateTests(
  code: string,
  framework: 'jest' | 'mocha' | 'vitest'
): Promise<TestSuite> {
  const prompt = `
Generate comprehensive test cases for this code using ${framework}.

Include:
- Happy path tests
- Edge cases
- Error conditions
- Mock external dependencies

Code to test:
${code}
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return {
    framework,
    tests: response.content,
  };
}

Pattern: Test Data Generator ​

Generate realistic test data.

typescript
interface TestDataSpec {
  schema: any;
  count: number;
  constraints?: Record<string, any>;
}

async function generateTestData(spec: TestDataSpec): Promise<any[]> {
  const prompt = `
Generate ${spec.count} realistic test data records matching this schema:

${JSON.stringify(spec.schema, null, 2)}

${spec.constraints ? `Constraints: ${JSON.stringify(spec.constraints)}` : ''}

Return as JSON array.
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return JSON.parse(extractJSON(response.content));
}

Data Processing Patterns ​

Pattern: Data Transformation ​

Transform data between formats.

typescript
async function transformData(
  data: string,
  sourceFormat: string,
  targetFormat: string
): Promise<string> {
  const prompt = `
Transform this data from ${sourceFormat} to ${targetFormat}.

Source data:
${data}

Requirements:
- Preserve all information
- Use proper ${targetFormat} formatting
- Handle edge cases
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return response.content;
}

Pattern: Data Validation ​

Validate data against rules.

typescript
interface ValidationResult {
  valid: boolean;
  errors: string[];
  warnings: string[];
}

async function validateData(
  data: any,
  rules: string[]
): Promise<ValidationResult> {
  const prompt = `
Validate this data against these rules:
${rules.map((r, i) => `${i + 1}. ${r}`).join('\n')}

Data:
${JSON.stringify(data, null, 2)}

Return JSON with:
{
  "valid": boolean,
  "errors": ["..."],
  "warnings": ["..."]
}
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return JSON.parse(extractJSON(response.content));
}

Advanced Patterns ​

Pattern: Chain of Thought ​

Break complex tasks into steps.

typescript
async function solveComplex(problem: string): Promise<string> {
  const prompt = `
Solve this problem step by step:

${problem}

Think through:
1. What is being asked?
2. What information do we have?
3. What steps are needed?
4. What is the solution?

Provide detailed reasoning for each step.
`;

  const response = await llm.complete({
    model: 'claude-3-5-sonnet-20241022',
    messages: [{ role: 'user', content: prompt }],
  });

  return response.content;
}

Pattern: Iterative Refinement ​

Refine output through multiple passes.

typescript
async function refineOutput(
  initial: string,
  criteria: string[]
): Promise<string> {
  let current = initial;

  for (const criterion of criteria) {
    const prompt = `
Refine this output to better meet this criterion: ${criterion}

Current output:
${current}

Provide the refined version.
`;

    const response = await llm.complete({
      model: 'claude-3-5-sonnet-20241022',
      messages: [{ role: 'user', content: prompt }],
    });

    current = response.content;
  }

  return current;
}

Pattern: Multi-Agent Collaboration ​

Use multiple AI agents with different roles.

typescript
interface Agent {
  role: string;
  instructions: string;
}

async function collaborate(
  agents: Agent[],
  task: string
): Promise<Record<string, string>> {
  const results: Record<string, string> = {};

  for (const agent of agents) {
    const prompt = `
You are a ${agent.role}.
${agent.instructions}

Task: ${task}

Previous results:
${Object.entries(results).map(([role, result]) =>
  `${role}: ${result}`
).join('\n\n')}

Provide your analysis.
`;

    const response = await llm.complete({
      model: 'claude-3-5-sonnet-20241022',
      messages: [{ role: 'user', content: prompt }],
    });

    results[agent.role] = response.content;
  }

  return results;
}

// Usage
const result = await collaborate([
  { role: 'Architect', instructions: 'Focus on system design' },
  { role: 'Security Expert', instructions: 'Identify security issues' },
  { role: 'Performance Engineer', instructions: 'Analyze performance' },
], 'Review this API design');

Helper Functions ​

typescript
function extractJSON(text: string): string {
  const match = text.match(/```json\n([\s\S]*?)\n```/) ||
                text.match(/\{[\s\S]*\}/);
  return match ? match[1] || match[0] : text;
}

function parseCompletions(text: string): string[] {
  // Extract multiple code blocks or numbered completions
  const blocks = text.match(/```[\s\S]*?```/g) || [];
  return blocks.map(b => b.replace(/```\w*\n?|\n?```/g, ''));
}

Best Practices ​

  1. Validate outputs: Always review AI-generated code
  2. Sanitize inputs: Remove sensitive data before sending
  3. Handle errors: Implement proper error handling
  4. Cache results: Cache when appropriate to reduce costs
  5. Test thoroughly: Test AI-integrated features extensively
  6. Monitor usage: Track costs and performance
  7. Version control: Track prompt versions like code
  8. Document patterns: Document which patterns work best

Anti-Patterns ​

❌ Don't: Blindly Trust Output ​

typescript
// Bad: Use without validation
const code = await generateCode(spec);
await deployToProduction(code);  // Dangerous!

✅ Do: Validate and Test ​

typescript
// Good: Validate before use
const code = await generateCode(spec);
await validateCode(code);
await runTests(code);
if (testsPass && securityCheck) {
  await deployToProduction(code);
}

❌ Don't: Share Sensitive Data ​

typescript
// Bad: Includes production credentials
await reviewCode(productionConfig);

✅ Do: Sanitize First ​

typescript
// Good: Remove sensitive data
const sanitized = sanitizeCode(productionConfig);
await reviewCode(sanitized);

Resources ​


Remember: These patterns are starting points. Adapt them to your specific needs and always validate AI-generated content before use.

Enterprise AI Documentation Hub