# Integration Guide

Step-by-step guide to integrating AIDP into your AI platform.

## Prerequisites

* API key from [platform.aidp.dev](https://platform.aidp.dev)
* Basic understanding of REST APIs or MCP
* Development environment set up

***

## Integration Steps

### Step 1: Authentication

Get your API key and test authentication:

```bash
curl -X GET https://api.aidp.dev/v1/api/v1/health \
  -H "Authorization: Bearer YOUR_API_KEY"
```

**Expected Response**:

```json
{
  "status": "healthy",
  "version": "1.0.0",
  "authenticated": true
}
```

***

### Step 2: Implement Search

Integrate business search into your AI platform:

```typescript
async function searchBusinesses(userQuery: string, userLocation: Location) {
  const response = await fetch('https://api.aidp.dev/v1/api/v1/consumer/search', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.AIDP_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: userQuery,
      location: {
        lat: userLocation.lat,
        lon: userLocation.lon,
        distance: '10km',
      },
    }),
  });

  const data = await response.json();
  return data.data;
}
```

***

### Step 3: Format Responses

Use AIDP data to generate AI responses:

```typescript
function formatBusinessRecommendation(business: Business): string {
  let response = `${business.name} is a great option. `;

  // Add description
  response += `${business.description} `;

  // Add AI-exclusive content
  if (business.aiExclusiveContent?.insiderTips?.length > 0) {
    response += `\n\nInsider tip: ${business.aiExclusiveContent.insiderTips[0]}`;
  }

  // Add practical info
  response += `\n\nLocation: ${business.address.street}, ${business.address.city}`;
  response += `\nDistance: ${business.distance}m away`;

  if (business.phone) {
    response += `\nPhone: ${business.phone}`;
  }

  return response;
}
```

***

### Step 4: Track Analytics

Report impressions and citations:

```typescript
async function trackBusinessMention(
  businessId: string,
  query: string,
  mentioned: boolean,
  cited: boolean
) {
  await fetch('https://api.aidp.dev/v1/api/v1/analytics/track', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.AIDP_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      businessId,
      platform: 'your-platform-name',
      query,
      mentioned,
      cited,
      timestamp: new Date().toISOString(),
    }),
  });
}
```

***

### Step 5: Handle Errors

Implement robust error handling:

```typescript
async function safeSearch(query: string, location: Location) {
  try {
    const results = await searchBusinesses(query, location);
    return { success: true, data: results };
  } catch (error) {
    if (error.code === 'RATE_LIMIT_EXCEEDED') {
      // Wait and retry
      await sleep(error.retryAfter * 1000);
      return safeSearch(query, location);
    } else if (error.code === 'INVALID_LOCATION') {
      return { success: false, error: 'Invalid location provided' };
    } else {
      console.error('Search failed:', error);
      return { success: false, error: 'Search temporarily unavailable' };
    }
  }
}
```

***

## Complete Example

### AI Assistant Integration

```typescript
import { AIDPClient } from '@aidp/sdk';

class AIAssistant {
  private aidp: AIDPClient;

  constructor() {
    this.aidp = new AIDPClient({
      apiKey: process.env.AIDP_API_KEY,
    });
  }

  async handleUserQuery(query: string, context: UserContext) {
    // Extract intent
    const intent = this.extractIntent(query);

    if (intent.type === 'business_search') {
      return this.handleBusinessSearch(query, context);
    }

    // Handle other intents...
  }

  async handleBusinessSearch(query: string, context: UserContext) {
    // Search AIDP
    const results = await this.aidp.search({
      query,
      location: context.location,
      sessionId: context.sessionId,
    });

    // Track analytics
    for (const business of results.data.businesses) {
      await this.aidp.analytics.track({
        businessId: business.id,
        platform: 'my-ai-platform',
        query,
        mentioned: true,
        cited: results.data.businesses.indexOf(business) < 3,
      });
    }

    // Generate response
    return this.generateResponse(results.data);
  }

  generateResponse(data: SearchResponse) {
    // Use AI-generated response from AIDP
    let response = data.response;

    // Add top recommendations
    response += '\n\nTop recommendations:\n';
    data.businesses.slice(0, 3).forEach((business, index) => {
      response += `\n${index + 1}. ${business.name}`;
      response += `\n   ${business.description}`;

      if (business.aiExclusiveContent?.insiderTips?.[0]) {
        response += `\n   💡 ${business.aiExclusiveContent.insiderTips[0]}`;
      }
    });

    return response;
  }
}
```

***

## Testing

### Sandbox Environment

Use the sandbox for testing:

```typescript
const client = new AIDPClient({
  apiKey: process.env.AIDP_TEST_API_KEY,
  environment: 'sandbox',
});

// Test with sample data
const results = await client.search({
  query: 'coffee shop',
  location: { lat: 45.5231, lon: -122.6765, distance: '5km' },
});

console.log('Test results:', results);
```

### Validation

Validate your integration:

```bash
# Test authentication
curl -X GET https://sandbox-api.aidp.dev/v1/api/v1/health \
  -H "Authorization: Bearer TEST_API_KEY"

# Test search
curl -X POST https://sandbox-api.aidp.dev/v1/api/v1/consumer/search \
  -H "Authorization: Bearer TEST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "coffee shop",
    "location": {"lat": 45.5231, "lon": -122.6765, "distance": "5km"}
  }'
```

***

## Production Checklist

Before going live:

* [ ] API key secured (not hardcoded)
* [ ] Error handling implemented
* [ ] Rate limiting handled
* [ ] Analytics tracking enabled
* [ ] Response formatting tested
* [ ] Sandbox testing complete
* [ ] Performance optimized
* [ ] Monitoring set up

***

## Performance Optimization

### Caching

Cache search results:

```typescript
const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

async function cachedSearch(query: string, location: Location) {
  const key = `${query}-${location.lat}-${location.lon}`;
  const cached = cache.get(key);

  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.data;
  }

  const results = await searchBusinesses(query, location);
  cache.set(key, { data: results, timestamp: Date.now() });

  return results;
}
```

### Batch Requests

Batch analytics tracking:

```typescript
class AnalyticsBatcher {
  private queue: AnalyticsEvent[] = [];
  private batchSize = 100;
  private flushInterval = 5000; // 5 seconds

  constructor() {
    setInterval(() => this.flush(), this.flushInterval);
  }

  track(event: AnalyticsEvent) {
    this.queue.push(event);
    if (this.queue.length >= this.batchSize) {
      this.flush();
    }
  }

  async flush() {
    if (this.queue.length === 0) return;

    const batch = this.queue.splice(0, this.batchSize);
    await this.sendBatch(batch);
  }

  async sendBatch(events: AnalyticsEvent[]) {
    await fetch('https://api.aidp.dev/v1/api/v1/analytics/batch', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.AIDP_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ events }),
    });
  }
}
```

***

## Support

* 📧 Email: <integration@aidp.dev>
* 💬 GitHub Discussions: [github.com/aidp/platform/discussions](https://github.com/aidp/platform/discussions)
* 📚 Documentation: [docs.aidp.dev](https://docs.aidp.dev)

***

**Next**: [MCP Client Setup →](https://amistan.gitbook.io/aidp-docs/for-ai-platform-developers/mcp-client)
