> ## Documentation Index
> Fetch the complete documentation index at: https://docs.context.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Powering Generative AI

> Keep AI-generated content on-brand by injecting real brand data into your generative AI workflows

<img src="https://mintcdn.com/branddev/JTvSrAMAd7UkFxMq/guides/image-5.png?fit=max&auto=format&n=JTvSrAMAd7UkFxMq&q=85&s=7a0d0055ee5a376cefd0491ad1be7ab1" alt="alt text" width="978" height="836" data-path="guides/image-5.png" />

## Overview

Generative AI is transforming how we create content—from email templates and social media graphics to landing pages and marketing copy. But without brand context, AI outputs are generic and require manual customization to match a company's visual identity.

Context.dev bridges this gap by providing real-time brand intelligence that your AI can use to generate on-brand content from the start:

* **Color palettes** for themed designs and consistent styling
* **Typography** for correct font choices in generated layouts
* **Logos** for proper brand asset placement
* **Style guides** for design system alignment
* **Company context** for accurate tone and messaging

We'll walk through how to integrate Context.dev with foundational AI models to create brand-aware generative experiences.

### Prerequisites

1. A [Context.dev](https://context.dev) API key
2. Access to a generative AI provider (OpenAI, Anthropic, etc.)
3. An application that generates content for users

### Concept

The workflow connects user input to brand-aware AI generation:

1. **User provides input** - "Create an email template for my company"
2. **Extract company identifier** - Parse domain or company name from context
3. **Fetch brand data** - Call Context.dev APIs for colors, fonts, logos, styleguide
4. **Inject into AI context** - Include brand data in your prompt to the AI model
5. **Generate on-brand content** - AI produces output that matches the brand

## Architecture

### 1. Extracting Brand Context from User Input

Users may reference their company in various ways. Use your AI to extract the relevant identifier:

```typescript theme={null}
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();

async function extractBrandContext(userMessage: string) {
  const response = await anthropic.messages.create({
    model: "claude-sonnet-4-20250514",
    max_tokens: 256,
    messages: [{
      role: "user",
      content: `Extract the company domain or name from this request. 
      Return JSON with "domain" or "companyName" field, or null if not found.
      
      User request: "${userMessage}"`
    }]
  });
  
  return JSON.parse(response.content[0].text);
}

// Example usage
const context = await extractBrandContext(
  "Create a welcome email for Acme Corp customers"
);
// Returns: { companyName: "Acme Corp" }
```

<Tip>
  If your users are authenticated, you may already know their company domain from their account profile - skip the extraction step and fetch brand data directly.
</Tip>

### 2. Fetching Brand Data

Once you have a domain or company name, fetch comprehensive brand data:

```typescript theme={null}
import ContextDev from "context.dev";

const brandClient = new ContextDev({ apiKey: process.env.CONTEXT_DEV_API_KEY });

async function getBrandContext(identifier: { domain?: string; companyName?: string }) {
  // Fetch by domain if available
  if (identifier.domain) {
    const [brandResponse, styleguideResponse] = await Promise.all([
      brandClient.brand.retrieve({ domain: identifier.domain }),
      brandClient.styleguide.retrieve({ url: `https://${identifier.domain}` })
    ]);
    
    return {
      brand: brandResponse.brand,
      styleguide: styleguideResponse.styleguide
    };
  }
  
  // Fall back to company name search
  if (identifier.companyName) {
    const brandResponse = await brandClient.brand.retrieveByName({
      name: identifier.companyName
    });
    return { brand: brandResponse.brand };
  }
  
  return null;
}
```

**Key data to fetch for generative AI:**

| API                                                                                                      | Data Retrieved                  | Use Case                         |
| -------------------------------------------------------------------------------------------------------- | ------------------------------- | -------------------------------- |
| [Brand API](/api-reference/retrieve-brand/retrieve-brand-data-by-domain)                                 | Logos, colors, company info     | Visual branding, company context |
| [Styleguide API](/api-reference/screenshot-styleguide/extract-design-system-and-styleguide-from-website) | Typography, spacing, components | Design system alignment          |

### 3. Formatting Brand Data for AI Context

Structure the brand data as clear instructions for your AI model:

```typescript theme={null}
function formatBrandContext(brandData: any) {
  const { brand, styleguide } = brandData;
  
  return `
## Brand Guidelines for ${brand.title}

### Company Information
- Name: ${brand.title}
- Description: ${brand.description || 'N/A'}
- Industry: ${brand.industries?.join(', ') || 'N/A'}

### Color Palette
${brand.colors?.map((c: any, i: number) => 
  `- ${i === 0 ? 'Primary' : i === 1 ? 'Secondary' : 'Accent'}: ${c.hex} (${c.name})`
).join('\n') || 'No colors available'}

### Typography
${styleguide?.typography?.fonts?.map((f: any) => 
  `- ${f.family} (${f.weights?.join(', ')})`
).join('\n') || 'Use clean, modern sans-serif fonts'}

### Logo URLs
${brand.logos?.slice(0, 3).map((l: any) => 
  `- ${l.type} (${l.mode}): ${l.url}`
).join('\n') || 'No logos available'}

### Brand Voice
Based on the company description, maintain a tone that is professional and aligned with their industry.
`.trim();
}
```

### 4. Generating On-Brand Content

Inject the brand context into your AI generation prompt:

```typescript theme={null}
async function generateBrandedContent(
  userRequest: string,
  brandContext: string,
  contentType: 'email' | 'social' | 'landing-page'
) {
  const systemPrompt = `You are a brand-aware content generator. 
You create ${contentType} content that strictly adheres to brand guidelines.

${brandContext}

When generating content:
1. Use the exact hex colors provided for any color specifications
2. Reference the specified fonts for typography
3. Maintain the brand voice based on company description
4. Include logo URLs where appropriate for image placeholders`;

  const response = await anthropic.messages.create({
    model: "claude-sonnet-4-20250514",
    max_tokens: 4096,
    system: systemPrompt,
    messages: [{
      role: "user",
      content: userRequest
    }]
  });
  
  return response.content[0].text;
}
```

### 5. Complete Integration Example

Here's a full example of a brand-aware email template generator:

```typescript theme={null}
import Anthropic from "@anthropic-ai/sdk";
import ContextDev from "context.dev";

const anthropic = new Anthropic();
const brandClient = new ContextDev({ apiKey: process.env.CONTEXT_DEV_API_KEY });

async function generateBrandedEmail(userRequest: string, userDomain?: string) {
  // Step 1: Extract or use known domain
  let domain = userDomain;
  if (!domain) {
    const extracted = await extractBrandContext(userRequest);
    domain = extracted?.domain;
  }
  
  if (!domain) {
    throw new Error("Could not identify company. Please specify your domain.");
  }
  
  // Step 2: Fetch brand data
  const [brandResponse, styleguideResponse] = await Promise.all([
    brandClient.brand.retrieve({ domain }),
    brandClient.styleguide.retrieve({ url: `https://${domain}` })
  ]);
  
  // Step 3: Format brand context
  const brandContext = formatBrandContext({
    brand: brandResponse.brand,
    styleguide: styleguideResponse.styleguide
  });
  
  // Step 4: Generate branded email
  const emailTemplate = await generateBrandedContent(
    userRequest,
    brandContext,
    'email'
  );
  
  return {
    template: emailTemplate,
    brand: {
      name: brandResponse.brand.title,
      primaryColor: brandResponse.brand.colors?.[0]?.hex,
      logo: brandResponse.brand.logos?.[0]?.url
    }
  };
}

// Usage
const result = await generateBrandedEmail(
  "Create a welcome email for new customers that highlights our key features",
  "acme.com"
);
```

<Warning>
  Always validate AI-generated content before sending to end users. Brand data improves accuracy but doesn't guarantee perfect results.
</Warning>

## Outputting Structured Content

For design applications, have your AI output structured data rather than plain text:

```typescript theme={null}
const structuredPrompt = `Generate an email template as JSON with this structure:
{
  "subject": "string",
  "preheader": "string",
  "sections": [
    {
      "type": "header" | "text" | "cta" | "image",
      "content": "string",
      "style": {
        "backgroundColor": "hex from brand colors",
        "textColor": "hex from brand colors",
        "fontFamily": "from brand typography"
      }
    }
  ]
}

Use ONLY colors from the provided brand palette.`;
```

This allows your application to render the generated content with precise styling control.

## Best Practices

### 1. Cache Brand Data

> Fetch brand data once per session or user, not per generation. Cache the formatted brand context to reduce API calls and improve response times.

```typescript theme={null}
const brandCache = new Map<string, { data: any; timestamp: number }>();
const CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours

async function getCachedBrandContext(domain: string) {
  const cached = brandCache.get(domain);
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.data;
  }
  
  const brandData = await getBrandContext({ domain });
  brandCache.set(domain, { data: brandData, timestamp: Date.now() });
  return brandData;
}
```

### 2. Provide Fallback Styling

> Not all brands have complete data. Define sensible defaults so AI generation doesn't fail:

```typescript theme={null}
function formatBrandContextWithFallbacks(brandData: any) {
  const colors = brandData?.brand?.colors || [
    { hex: '#3B82F6', name: 'Blue' },
    { hex: '#1F2937', name: 'Dark Gray' }
  ];
  
  const fonts = brandData?.styleguide?.typography?.fonts || [
    { family: 'Inter', weights: ['400', '600'] }
  ];
  
  // ... format with guaranteed values
}
```

### 3. Validate Color Usage

> AI models may occasionally invent colors. Post-process generated content to ensure only brand colors are used:

```typescript theme={null}
function validateBrandColors(generatedHtml: string, brandColors: string[]) {
  const hexPattern = /#[0-9A-Fa-f]{6}/g;
  const usedColors = generatedHtml.match(hexPattern) || [];
  
  const invalidColors = usedColors.filter(
    color => !brandColors.includes(color.toUpperCase())
  );
  
  if (invalidColors.length > 0) {
    console.warn('Non-brand colors detected:', invalidColors);
    // Optionally replace with nearest brand color
  }
  
  return generatedHtml;
}
```

### 4. Let Users Override

> Allow users to adjust or regenerate if the AI output doesn't match their expectations. Provide easy editing of colors, fonts, and content.

### 5. Use Styleguide for Complex Layouts

> For design-heavy outputs (landing pages, complex emails), fetch the full styleguide for spacing, shadows, and component styles—not just colors and fonts.

## Example Use Cases

### AI Email Template Generators

Generate complete email templates with correct brand colors, fonts, and logo placement—ready to send without manual design work.

### Social Media Content Tools

Create on-brand social graphics with proper color schemes and typography that match the user's existing brand presence.

### Landing Page Builders

Generate landing page sections that automatically use the brand's design system for buttons, headers, and backgrounds.

### Marketing Copy Assistants

Produce copy that matches brand voice while suggesting color and typography pairings for visual presentation.

### Design Asset Generators

Create branded presentations, documents, and graphics that maintain visual consistency across all outputs.

## Related Resources

<CardGroup cols={2}>
  <Card title="Brand API Reference" icon="palette" href="/api-reference/retrieve-brand/retrieve-brand-data-by-domain">
    Retrieve logos, colors, and brand assets
  </Card>

  <Card title="Styleguide API" icon="paintbrush" href="/api-reference/screenshot-styleguide/extract-design-system-and-styleguide-from-website">
    Extract typography, spacing, and design tokens
  </Card>

  <Card title="Automating Brand Kits" icon="wand-magic-sparkles" href="/guides/use-cases/automating-brand-kits">
    Pre-generate brand kits for design tools
  </Card>

  <Card title="Core Concepts" icon="book" href="/guides/get-started/core-concepts">
    Understanding brand data structure
  </Card>
</CardGroup>
