How to Build an AI Sales Development | Replit

How to Build an AI Sales Development Representative (SDR) in Slack - Part 1: AI-Powered Lead Generation

A guide by

Horacio Lopez

Eddie Nuno

Introduction

In this guide, we'll create an AI sales assistant that allows you to request leads using natural language in Slack. The assistant will then translate those queries into valid API calls to the Apollo.io API to fetch a list of leads that fit your request.

This guide is Part 1 of a six-part series for how to build your own AI SDR (Sales Development Representative) in Slack. The subsequent guides are linked at the bottom of this post.

Getting Started

To begin building your AI sales assistant, fork this template below:

Use the template

To power your AI for lead generation, you'll need to set up API keys for Slack, Apollo.io, and OpenAI. Here's how to obtain each:

Slack App

Create a new Slack app

{
    "display_information": {
        "name": "SDR Bot",
        "description": "SDR Bot to prepare a list of leads to reach out to for sales.",
        "background_color": "#2c2d30"
    },
    "features": {
        "bot_user": {
            "display_name": "SDR Bot",
            "always_online": false
        }
    },
    "oauth_config": {
        "scopes": {
            "bot": [
                "app_mentions:read",
                "channels:history",
                "channels:read",
                "chat:write",
                "files:read",
                "files:write",
                "groups:history",
                "im:history",
                "mpim:history",
                "reactions:read",
                "reactions:write",
                "users:read"
            ]
        }
    },
    "settings": {
        "event_subscriptions": {
            "bot_events": [
                "app_mention",
                "message.channels",
                "reaction_added"
            ]
        },
        "interactivity": {
            "is_enabled": true
        },
        "org_deploy_enabled": false,
        "socket_mode_enabled": true,
        "token_rotation_enabled": false
    }
}

Next, you'll need to get your Slack App Token and Slack Bot Token.

Slack App token:

Slack Bot token:

Before you take these steps, you may need to request installation permission from a Slack admin.

In Replit, go to the Secrets tab (Tools > Secrets) and add the credentials to your secrets within SLACK_APP_TOKEN and SLACK_BOT_TOKEN respectively.

If you want a character for your new Slack App, feel free to download this little guy:

Apollo API Key

If you do not see API selection options, you may need to upgrade your account to Apollo’s Basic tier.

OpenAI API Key

Breaking Down the AI Sales Assistant Code

Query Analysis with OpenAI

The analyze_query function in query_analyzer.py uses OpenAI's GPT-4o-mini model to interpret natural language queries and convert them into structured search parameters, enhancing the AI's lead generation capabilities:

def analyze_query(query):
    api_key = os.environ["OPENAI_API_KEY"]
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }

url = 'https://api.openai.com/v1/chat/completions'
    payload = {
        'model': 'gpt-4o-mini',
        'messages': [
            {'role': 'system', 'content': '...'},  # System prompt
            {'role': 'user', 'content': query}
        ],
        'temperature': 0.1,
        'max_tokens': 500
    }

response = requests.post(url, headers=headers, json=payload)
    result = response.json()['choices'][0]['message']['content']

try:
        return json.loads(result)
    except json.JSONDecodeError:
        print(f"Error parsing JSON: {result}")
        return None

This function is crucial for the AI sales assistant to understand and process natural language queries, translating them into actionable search parameters for lead generation.

Apollo.io API Integration for AI-Powered Lead Generation

The utils.py file contains functions for interacting with the Apollo.io API, allowing our AI SDR to fetch relevant leads:

def search_orgs(**kwargs):
    url = "https://api.apollo.io/api/v1/mixed_companies/search"
    data = {k: v for k, v in kwargs.items() if v is not None}
    response = requests.post(url, headers=common_headers(), json=data)
    if response.status_code == 200:
        return [org.get("id") for org in response.json().get('organizations', [])]
    else:
        print(f"Error searching organizations: {response.status_code}")
        return []

def search_people(**kwargs):
    url = "https://api.apollo.io/v1/mixed_people/search"
    data = {k: v for k, v in kwargs.items() if v is not None and v != 'None' and v != []}
    response = requests.post(url, headers=common_headers(), json=data)
    if response.status_code == 200:
        return response.json().get('people', [])
    else:
        print(f"Error searching people: {response.status_code}")
        return []

These functions enable the AI sales assistant to perform targeted searches for organizations and individuals, forming the core of its lead generation capabilities.

Slack Bot Integration for Your AI SDR

The main.py file sets up the Slack bot, allowing your AI sales assistant to interact with users and deliver lead generation results:

@app.event("app_mention")
def handle_mention(event, say):
    user = event["user"]
    ts = event["ts"]
    channel = event["channel"]
    ack = "On it! Processing..."
    say(text=ack, channel=channel, thread_ts=ts)

try:
        user_query = event['text']
        csv_filepath, csv_content = run_leads_search(user_query, ts)
        if csv_filepath and csv_content:
            try:
                result = app.client.files_upload_v2(
                    channel=channel,
                    file=csv_filepath,
                    title=f"Leads-{os.path.basename(csv_filepath)}",
                    initial_comment=f"Hey <@{user}>, here are the leads you requested:",
                    thread_ts=ts
                )
                if not result["ok"]:
                    raise Exception(f"Error uploading file: {result['error']}")

# Delete the file after successful upload
                os.remove(csv_filepath)
            except Exception as e:
                error_message = f"Hey <@{user}>, I encountered an error while uploading the file: {str(e)}"
                say(text=error_message, channel=channel, thread_ts=ts)

# Attempt to delete the file even if upload failed
                if os.path.exists(csv_filepath):
                    os.remove(csv_filepath)
                    print(f"CSV file {csv_filepath} deleted after upload failure.")
        else:
            error_message = f"Hey <@{user}>, I'm sorry, but I encountered an error while processing your request. Please try again later or contact support if the issue persists."
            say(text=error_message, channel=channel, thread_ts=ts)
    except Exception as e:
        print(e)
        error_message = f"Hey <@{user}>, I'm sorry, but I encountered an error while processing your request. Please try again later or contact support if the issue persists."
        say(text=error_message, channel=channel, thread_ts=ts)

This code allows the AI SDR to listen for mentions in Slack, process user queries, generate leads, and deliver results, showcasing the practical application of AI for lead generation in a familiar communication platform.

Deploying Your AI SDR

In order to keep your AI SDR running 24/7 and receive requests whenever someone mentions it in Slack, you'll need to deploy it on a hosted server.

Open a new tab in the Workspace and search for “Deployments” or open the control console by typing ⌘ + K (or Ctrl + K) and type "deploy". You should find a screen like this.

For bots like this that need always need to be up listening to requests, we recommend using a Reserved VM. On the next screen, click Approve and configure build settings most internal bots work fine with the default machine settings but if you need more power later, you can always come back and change these settings later. You can monitor your usage and billing at any time at: replit.com/usage.

On the next screen, you’ll be able to set your primary domain and edit the Secrets that will be in your production deployment. Usually, we keep these settings as they are.

Finally, click Deploy and watch your bot go live!

What's Next for Your AI Sales Assistant

In the next part of this series, we'll be adding the ability for the assistant to enrich the lead list with email addresses using Clay. The other parts of the series include:

If you'd like to discuss how to enable your team to build and implement tools like these, feel free to schedule some time with the Replit team for a quick demo of our product.

Happy coding and selling!