CRM×AI
← BlogTutorials

How to Use ChatGPT with Salesforce Flow: A Step-by-Step Guide

A complete step-by-step guide to integrating ChatGPT with Salesforce Flow using HTTP callouts — no Apex required. Covers real-world use cases, common mistakes, and troubleshooting for admins.

October 15, 2025·11 min read
#chatgpt#salesforce-flow#automation#no-code

Salesforce Flow is one of the most powerful automation tools in the Salesforce ecosystem. ChatGPT is one of the most powerful AI tools ever built. Together, they can save your team dozens of hours per week.

In this guide, you'll learn exactly how to connect ChatGPT with Salesforce Flow using simple HTTP callouts — no Apex required.

What You'll Build

By the end of this tutorial, you'll have a working Salesforce Flow that:

  • Triggers when a new Lead is created
  • Sends the lead's details to ChatGPT via an HTTP callout
  • Receives a personalized follow-up email draft
  • Saves the draft to a custom field on the Lead record

Prerequisites

  • A Salesforce org (Developer Edition works)
  • An OpenAI API key (get one here)
  • Basic familiarity with Salesforce Flow Builder

Step 1: Get Your OpenAI API Key

  1. Go to platform.openai.com
  2. Click API Keys in the left sidebar
  3. Click Create new secret key and copy it

Security note: Never paste your API key directly into a Flow. Always store it in a Named Credential or Custom Setting.

Step 2: Create a Named Credential in Salesforce

Named Credentials let you safely store API endpoints and keys without hardcoding them anywhere in your automation logic. This is critical — any API key embedded directly in a Flow body is visible to any admin who opens that Flow, and it travels in plain text through exported metadata.

  1. Go to Setup → Named Credentials → New
  2. Set the Label to OpenAI API
  3. Set the URL to https://api.openai.com
  4. Set Authentication Protocol to No Authentication (we'll pass the Bearer token manually in the request header)
  5. Save

Now create a Custom Setting to store your API key:

  1. Go to Setup → Custom Settings → New
  2. Set the Setting Type to Hierarchy
  3. Create a field called OpenAI_API_Key__c (Text, 255)
  4. Go to Manage, click New under Default Organization Level Value, and paste your key

Using a Custom Setting instead of a hardcoded string means you can rotate your API key in one place without touching any Flow. It also keeps your key out of version control if you use Salesforce DX.

Step 3: Build the Salesforce Flow

  1. Go to Setup → Flow Builder → New Flow
  2. Choose Record-Triggered Flow
  3. Set Object to Lead, trigger on Record Created

Add a Get Records Element

Pull the lead's FirstName, LastName, Company, and Title into flow variables. Even though the trigger is on the Lead record, you often need a Get Records step to access fields that weren't populated at creation time — for example, AnnualRevenue or a lookup field populated by another automation running in the same transaction. Store each value in a separate Text variable so you can reference them cleanly in your prompt string.

Add an HTTP Callout Action

  1. Add an Action element
  2. Search for HTTP Callout (available in Spring '23+)
  3. Configure:
    • Named Credential: OpenAI API
    • URL Path: /v1/chat/completions
    • Method: POST
    • Headers: Content-Type: application/json, Authorization: Bearer {!$CustomSetting.OpenAI_API_Key__c}
    • Body:
    {
      "model": "gpt-4o-mini",
      "messages": [{
        "role": "user",
        "content": "Write a short, personalized follow-up email for this lead: {!Lead.FirstName} {!Lead.LastName}, {!Lead.Title} at {!Lead.Company}."
      }]
    }
    

Parse the Response

Use an Assignment element to extract the email text from the response JSON using outputs.body.choices[0].message.content. Before doing this, add a Decision element to check that the HTTP response status code is 200. If it's anything else — a 429 rate-limit error, a 500 server error, or an auth failure — route to a Fault path that logs the error to a custom object or sends a Slack notification to the admin. Parsing a failed response will return a null value and silently write nothing to the field, which is harder to debug than an explicit failure log.

Update the Lead Record

Add an Update Records element to save the generated email to a custom field like AI_Follow_Up_Draft__c. Create this field as a Long Text Area (32,768 characters) on the Lead object — a standard Text field's 255-character limit will truncate most AI-generated content.

Step 4: Test Your Flow

  1. Activate the Flow
  2. Create a test Lead record
  3. Check the AI_Follow_Up_Draft__c field — you should see a personalized email draft

Tips for Better Results

  • Be specific in your prompts. Include industry, company size, and use case for more relevant emails. A prompt like "Write a 3-sentence follow-up email for a VP of Sales at a 500-person manufacturing company who downloaded our pricing page" produces dramatically better output than one with just a name and company.
  • Add a character limit. Add "Keep it under 100 words" to avoid long outputs that overflow your UI or email templates.
  • Rate limit awareness. OpenAI has rate limits — add error handling with a Fault path in your Flow. On the free tier, you're limited to 3 requests per minute; paid tiers are much higher but still finite. For high-volume flows, consider queuing via Platform Events.
  • Temperature control. In the API body, add "temperature": 0.5 to make outputs more consistent and professional. The default temperature of 1.0 produces more creative (and less predictable) responses.

Real-World Use Cases

Use Case 1: AI-Assisted Lead Routing with Context Summaries

A common pain point in lead routing is that routed leads arrive in a sales rep's queue with no context beyond raw form fields. You can solve this with a Flow that triggers on Lead creation, sends the lead's job title, company size (mapped from a picklist), and the campaign source to ChatGPT, and asks it to write a one-paragraph "why this lead matters" summary for the rep.

The Flow logic: trigger on Lead: Created → Get Records to pull Campaign.Name from the lead's CampaignId → build a prompt string using an Assignment element → HTTP Callout to OpenAI → write the response to a Rep_Context_Summary__c Long Text Area field → that field appears in the Lead list view and the rep's notification email.

The prompt to use:

You are a sales intelligence assistant. Based on the following lead data, write a 2-sentence summary explaining why this lead is worth calling today. Lead: {!Lead.FirstName} {!Lead.LastName}, {!Lead.Title} at {!Lead.Company} ({!Lead.NumberOfEmployees} employees). They came from the campaign: {!campaignName}. Their industry is {!Lead.Industry}.

This pairs naturally with a lead scoring flow — see our guide on automating lead scoring in Salesforce with AI for how to combine both into a single automation.

Use Case 2: AI-Generated Case Response Drafts for Support Teams

When a new Case is created with Origin = Email and Priority = High, you can trigger a Flow that sends the case subject and description to ChatGPT and asks for a first-draft reply. The draft gets written to a Draft_Response__c field on the Case, and an email alert notifies the assigned agent that a draft is ready to review.

The Flow logic: trigger on Case: Created with entry condition Origin = Email AND Priority = High → HTTP Callout → parse response → Update Records on Case → Send Email Action to assigned agent.

The prompt structure matters here. Wrap the case description in clear delimiters so ChatGPT doesn't mistake it for an instruction:

You are a support agent at a SaaS company. Write a professional, empathetic reply to the following customer case. Do not promise specific resolution timelines. Case subject: {!Case.Subject}. Case description: ---{!Case.Description}---

The triple-dash delimiters around the case description prevent prompt injection — a real security concern when user-submitted text is passed directly into an AI prompt. Never pass raw case descriptions without sanitizing or delimiting them first.

Troubleshooting and Common Mistakes

1. Using a Text Field Instead of Long Text Area

The most common silent failure: you build the flow, it runs without errors, but the field on the record shows only the first 255 characters — or nothing. Salesforce Text fields cap at 255 characters. Always use a Long Text Area field (minimum 32,768 characters) to store AI-generated content.

2. Not Handling Null Responses from the API

ChatGPT won't always return a clean response. If the model hits a content filter, if the prompt is malformed, or if the API returns an error, choices[0].message.content will be null. Assigning a null value to a required field, or trying to use it in a string concatenation later in the Flow, will throw a runtime error. Always add a null-check Decision element after parsing: if the variable is null, route to an error path.

3. Hitting API Rate Limits at Scale

OpenAI's API limits are per-minute and per-day. If your flow triggers on every Lead creation and your org processes 500 leads per hour in a marketing blitz, you will hit your rate limit and start getting 429 Too Many Requests responses. The fix is two-pronged: add a Fault path that stores failed requests in a custom object for retry, and consider moving high-volume callouts to a scheduled Apex batch job instead of a real-time Flow trigger. For moderate volume, the gpt-4o-mini model has significantly higher rate limits than gpt-4o at a fraction of the cost.

4. Passing Unformatted or Overly Long Text to the API

The OpenAI API has a context window limit (128k tokens for GPT-4o, 16k for GPT-4o-mini). If you pass a multi-page case description or a full email thread into your prompt, you may exceed the limit and get a 400 Bad Request. Trim inputs before sending: use a Formula field to truncate long text fields to a reasonable length (e.g., LEFT(Case.Description, 2000)), and reference that formula field in your prompt instead of the raw field.

5. Storing the API Key in the Flow Body

It's tempting to hardcode sk-proj-abc123... directly in the Authorization header of your HTTP Callout during testing. This is a serious security mistake. The key is stored in plain text in the Flow metadata, visible to any Salesforce admin with access to Flow Builder, and it will be included if someone exports metadata using the Metadata API or Salesforce CLI. Always use a Custom Setting or Named Credential with a proper External Credential for production keys.

Frequently Asked Questions

Does this require Apex or developer access? No. The HTTP Callout action in Flow Builder (available since Spring '23) handles the API request entirely within Flow, with no code. You need Admin access to create Named Credentials and Custom Settings, but no developer license or sandboxed code deployment is required.

Which OpenAI model should I use in a Salesforce Flow? For most admin use cases, gpt-4o-mini is the right choice. It's fast, cheap (roughly $0.15 per million input tokens), and accurate enough for drafting emails, summarizing records, and classifying text. Reserve gpt-4o for tasks that require nuanced reasoning or where output quality directly affects customer experience.

Can I use this with Salesforce Einstein instead of OpenAI? Yes, and in many cases you should — especially if your data is sensitive and you don't want it leaving Salesforce's trust boundary. Einstein's Prompt Builder (available in the Einstein 1 platform) offers similar functionality with data residency guarantees. The trade-off is that Einstein models may lag behind frontier models on pure language quality. See our full breakdown in Salesforce Einstein vs ChatGPT: Which AI Wins for CRM?.

How do I make the AI output consistent across runs? Two levers control consistency: the temperature parameter (set to 0.30.5 for deterministic outputs vs. the default 1.0) and prompt specificity. Vague prompts produce variable outputs. If you need the same structure every time — for example, always output three bullet points — specify the exact format in the prompt and validate the output with a Decision element before writing to the record. For a library of prompts optimized for Salesforce workflows, see 10 AI Prompts Every Salesforce Admin Should Know.

Affiliate Tools We Recommend

If you want a no-code solution that handles all this for you, check out Zapier AI or Make.com — both have native ChatGPT + Salesforce integrations.

Conclusion

Connecting ChatGPT to Salesforce Flow opens up a world of automation possibilities. Start with this email draft example, then explore generating meeting summaries, case responses, or even data enrichment.

Have questions? Drop them in the comments — or subscribe to our newsletter for weekly AI + Salesforce tips.


📬 Enjoyed this article?

Subscribe to our free weekly digest — AI tools, Salesforce tips, and prompts every week.