Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Build a SaaS CRM AI Assistant with Tenant Scoped Agents

· 5 min read · Smart Home

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through building a multi-tenant SaaS CRM with an AI assistant where each tenant (customer organization) gets its own isolated AI agent. The agent has access only to that tenant's CRM data, ensuring data privacy and relevance. You'll end up with a working architecture that you can extend with your own features.

What You'll Need

  • Node.js 18+ and npm installed
  • A PostgreSQL database (local or hosted)
  • An OpenAI API key (or any LLM API) for the AI agent
  • Basic familiarity with Express.js, React (or any frontend), and SQL
  • A code editor and terminal

Step-by-Step

  1. Set up the project structure. Create a new directory and initialize a Node.js project: mkdir saas-crm-ai && cd saas-crm-ai && npm init -y. Install core dependencies: npm install express pg dotenv cors openai.
  2. Create the database schema. Design tables for tenants, users, contacts, deals, and messages. Use a foreign key tenant_id on every CRM table. Example SQL: CREATE TABLE tenants (id SERIAL PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE contacts (id SERIAL PRIMARY KEY, tenant_id INTEGER REFERENCES tenants(id), name TEXT, email TEXT); Run this schema in your PostgreSQL instance.
  3. Build the Express server. Create server.js that connects to PostgreSQL using pg Pool. Set up middleware for JSON parsing and CORS. Add a simple health check endpoint.
  4. Implement tenant authentication. Create a middleware that extracts an API key or JWT from the request headers. Look up the tenant from the token and attach req.tenantId to the request. For simplicity, use a hardcoded tenant for now, but design it to be dynamic.
  5. Create the CRM CRUD endpoints. Implement REST endpoints for contacts and deals, each scoped by req.tenantId. For example, GET /contacts returns only contacts where tenant_id = req.tenantId. Use parameterized queries to prevent SQL injection.
  6. Set up the AI agent service. Create a module aiService.js that initializes the OpenAI client. Write a function askAgent(tenantId, userMessage) that will later use the tenant context.
  7. Build the tenant-scoped agent logic. The core idea: before calling the LLM, gather the tenant's data. For example, fetch all contacts and deals for that tenant. Then construct a system prompt that includes this data as context. Call the LLM with the user's question and the context. The agent only knows about this tenant's data.
  8. Create the chat endpoint. Add POST /api/chat that takes a user message, calls askAgent(req.tenantId, message), and returns the response. Make sure the endpoint is protected by the tenant middleware.
  9. Build a simple frontend. Create a basic HTML page or React app that lets a user type a question and see the agent's reply. Include a way to select the tenant (for demo purposes) or use the authenticated tenant.
  10. Test the full flow. Run the server, send a chat message like "How many contacts do I have?" and verify the agent answers based on that tenant's data only. Try with two different tenants to confirm isolation.

Common Mistakes

  • Not scoping queries by tenant. Forgetting to add WHERE tenant_id = ? to every SQL query can leak data across tenants.
  • Exposing the LLM API key. Never put the API key in frontend code or in client-side requests. Always keep it server-side.
  • Ignoring rate limits. LLM APIs have rate limits. Implement throttling or queuing for chat requests to avoid errors.
  • Putting too much data in the prompt. If a tenant has thousands of contacts, sending all of them to the LLM will exceed token limits and slow down responses. Use summarization or retrieval (e.g., embeddings) instead.

Tips

  • Use connection pooling. The pg Pool helps manage database connections efficiently.
  • Log agent interactions. Store user messages and agent responses in a messages table with tenant_id for audit and debugging.
  • Make the system prompt dynamic. Include the tenant name and recent activity to make the agent feel more personalized.
  • Consider streaming responses. Use the OpenAI streaming API to show the agent's reply as it's generated, improving user experience.
  • Add a fallback for empty data. If a tenant has no contacts, the agent should still respond gracefully, e.g., "You have no contacts yet."

Troubleshooting

  • Agent returns irrelevant answers. Check that the tenant context is being passed correctly. Log the system prompt to see what data the agent sees.
  • Database connection errors. Verify your DATABASE_URL environment variable and that PostgreSQL is running.
  • LLM API errors (401, 429). Check your API key and usage limits. Ensure you have billing enabled on your OpenAI account.
  • Cross-tenant data leak. Review all SQL queries for the tenant_id filter. Add a test that creates two tenants and ensures one cannot see the other's data.
  • Frontend can't reach the API. Check CORS settings and that the server is listening on the expected port.

Frequently Asked Questions

How do I handle multiple LLM providers?

Abstract the LLM call behind an interface. Use environment variables to switch between OpenAI, Anthropic, or others without changing your core logic.

What if a tenant has too much data for the prompt?

Use a retrieval-augmented generation approach: embed the tenant's data, store vectors, and retrieve only the relevant chunks for each user question.

Can I let tenants customize their agent's behavior?

Yes, add a settings column to the tenants table where you store custom instructions, tone, or allowed actions, and include them in the system prompt.

How do I secure the chat endpoint?

Use the same authentication as your CRM API. Require a valid session or API key, and always derive the tenant from the authenticated user, never from client input.

Should I use a vector database?

Only if you need semantic search over large datasets. For small CRM data, a simple SQL query to fetch recent items is sufficient.

How do I deploy this?

Containerize with Docker, deploy to a platform like Heroku or AWS, and set environment variables for the database URL and API key. Use a managed PostgreSQL for production.