Skip to main content

OpenAI Integration

OpenAI provides powerful language models including GPT-4, GPT-3.5, and assistants with advanced capabilities. You can integrate OpenAI with Evolution API to deploy AI-powered conversational experiences on WhatsApp.

What is OpenAI?

OpenAI offers:
  • GPT-4 and GPT-3.5-turbo models for chat completions
  • Assistants API with code interpreter and retrieval
  • Function calling capabilities
  • Vision and image understanding
  • Text-to-speech and speech-to-text
  • Fine-tuning for custom models

Enable OpenAI Integration

Add this environment variable to your .env file:
# Enable OpenAI integration
OPENAI_ENABLED=true

OpenAI Credentials Management

Before creating bots, you need to register your OpenAI API credentials.

Create OpenAI Credentials

1

Get OpenAI API Key

Visit OpenAI Platform and create an API key.
2

Register credentials in Evolution API

Store your API key securely in Evolution API.
3

Use credentials when creating bots

Reference the credential ID when configuring OpenAI bots.
curl -X POST https://your-api.com/openai/creds/{instance} \
  -H "apikey: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production OpenAI",
    "apiKey": "sk-your-openai-api-key"
  }'
name
string
required
Friendly name to identify this credential set
apiKey
string
required
Your OpenAI API key (starts with “sk-”)

Fetch OpenAI Credentials

Retrieve all registered OpenAI credentials:
curl -X GET https://your-api.com/openai/creds/{instance} \
  -H "apikey: your-api-key"

Delete OpenAI Credentials

curl -X DELETE https://your-api.com/openai/creds/{instance}/{credsId} \
  -H "apikey: your-api-key"

Configuration Settings

Create Default Settings

Configure default behavior settings for your instance.
curl -X POST https://your-api.com/openai/settings/{instance} \
  -H "apikey: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "openaiCredsId": "creds-id-from-previous-step",
    "expire": 300,
    "keywordFinish": "#EXIT",
    "delayMessage": 1000,
    "unknownMessage": "I did not understand your message.",
    "listeningFromMe": false,
    "stopBotFromMe": false,
    "keepOpen": false,
    "debounceTime": 10,
    "ignoreJids": [],
    "openaiIdFallback": "",
    "speechToText": false
  }'
openaiCredsId
string
required
ID of the OpenAI credentials to use by default
speechToText
boolean
Enable automatic speech-to-text for voice messages. Default: false
openaiIdFallback
string
Fallback OpenAI bot ID to use when primary bot fails

OpenAI Bot Types

Evolution API supports two OpenAI bot types:

Chat Completion

Use GPT models directly with custom prompts:
  • GPT-4, GPT-4-turbo
  • GPT-3.5-turbo
  • Custom system messages
  • Conversation history
  • Function calling

Assistant

Use OpenAI Assistants API:
  • Pre-configured assistants
  • Code interpreter
  • Knowledge retrieval
  • File support
  • Advanced tools

Create Chat Completion Bot

curl -X POST https://your-api.com/openai/create/{instance} \
  -H "apikey: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "enabled": true,
    "description": "Customer Support AI",
    "openaiCredsId": "your-creds-id",
    "botType": "chatCompletion",
    "model": "gpt-4-turbo-preview",
    "maxTokens": 1000,
    "systemMessages": [
      "You are a helpful customer support assistant.",
      "Always be polite and professional.",
      "Keep responses concise for WhatsApp."
    ],
    "assistantMessages": [
      "Hello! How can I help you today?"
    ],
    "userMessages": [
      "I need help with my order."
    ],
    "triggerType": "keyword",
    "triggerOperator": "equals",
    "triggerValue": "support",
    "expire": 300,
    "keywordFinish": "#EXIT",
    "delayMessage": 1000,
    "unknownMessage": "Sorry, I encountered an error.",
    "listeningFromMe": false,
    "stopBotFromMe": false,
    "keepOpen": false,
    "debounceTime": 10
  }'

Chat Completion Parameters

botType
string
required
Must be “chatCompletion” for this bot type
openaiCredsId
string
required
ID of the OpenAI credentials to use
model
string
required
OpenAI model: “gpt-4”, “gpt-4-turbo-preview”, “gpt-3.5-turbo”, etc.
maxTokens
number
required
Maximum tokens for the response (controls response length and cost)
systemMessages
array
System prompts that define the AI’s behavior and personality
assistantMessages
array
Example assistant responses for few-shot learning
userMessages
array
Example user messages paired with assistant messages
functionUrl
string
Webhook URL for function calling responses

Create Assistant Bot

curl -X POST https://your-api.com/openai/create/{instance} \
  -H "apikey: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "enabled": true,
    "description": "Sales Assistant",
    "openaiCredsId": "your-creds-id",
    "botType": "assistant",
    "assistantId": "asst_your-assistant-id",
    "triggerType": "keyword",
    "triggerOperator": "startsWith",
    "triggerValue": "sales",
    "expire": 600,
    "keywordFinish": "bye",
    "delayMessage": 1500,
    "unknownMessage": "Sorry, something went wrong.",
    "listeningFromMe": false,
    "stopBotFromMe": true,
    "keepOpen": true,
    "debounceTime": 5
  }'

Assistant Parameters

botType
string
required
Must be “assistant” for this bot type
assistantId
string
required
OpenAI Assistant ID (starts with “asst_”). Create assistants in OpenAI Platform.

Available Models

Retrieve all available OpenAI models for your credentials:
curl -X GET https://your-api.com/openai/models/{instance}?openaiCredsId={credsId} \
  -H "apikey: your-api-key"

Trigger Types

All Messages

Respond to every message:
{
  "triggerType": "all"
}

Keyword Trigger

Trigger based on specific keywords:
{
  "triggerType": "keyword",
  "triggerOperator": "contains",
  "triggerValue": "help"
}
Operators: equals, contains, startsWith, endsWith, regex

Advanced Trigger

Use regex patterns:
{
  "triggerType": "advanced",
  "triggerValue": "^(question|ask|inquire)\\s"
}

Update OpenAI Bot

curl -X PUT https://your-api.com/openai/update/{instance}/{botId} \
  -H "apikey: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "enabled": true,
    "description": "Updated Support Bot",
    "maxTokens": 1500
  }'

Delete OpenAI Bot

curl -X DELETE https://your-api.com/openai/delete/{instance}/{botId} \
  -H "apikey: your-api-key"

Fetch OpenAI Bots

curl -X GET https://your-api.com/openai/fetch/{instance} \
  -H "apikey: your-api-key"

Session Management

Change Session Status

curl -X POST https://your-api.com/openai/changeStatus/{instance} \
  -H "apikey: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "remoteJid": "[email protected]",
    "status": "closed"
  }'

Fetch Sessions

curl -X GET https://your-api.com/openai/fetchSessions/{instance} \
  -H "apikey: your-api-key"

Speech to Text

Enable automatic transcription of voice messages:
{
  "speechToText": true
}
When enabled, voice messages sent to the bot are automatically:
  1. Transcribed using OpenAI Whisper
  2. Processed as text by the bot
  3. Responded to normally

Use Cases

Deploy AI support agents:
  • Answer common questions instantly
  • Provide product information
  • Troubleshoot issues step-by-step
  • Escalate to humans when needed
Automate sales conversations:
  • Qualify leads with intelligent questions
  • Provide product recommendations
  • Schedule demos and calls
  • Capture contact information
Help users create content:
  • Generate social media posts
  • Write email responses
  • Create marketing copy
  • Brainstorm ideas
Daily helper bot:
  • Answer general questions
  • Provide recommendations
  • Set reminders and tasks
  • Get quick information

Best Practices

Use GPT-3.5-turbo for cost-effective, fast responses. Reserve GPT-4 for complex reasoning tasks.
Monitor your OpenAI API usage carefully. Set reasonable maxTokens limits to control costs.
  • Craft clear system messages: Define personality, tone, and constraints
  • Keep responses concise: WhatsApp users prefer short messages
  • Use few-shot examples: Provide example conversations to guide behavior
  • Set appropriate token limits: Balance quality with cost
  • Handle voice messages: Enable speech-to-text for better UX
  • Monitor conversations: Review bot interactions regularly
  • Implement safety: Use OpenAI’s moderation API for sensitive use cases

Troubleshooting

  • Verify OPENAI_ENABLED=true in environment
  • Check bot is enabled and credentials are valid
  • Ensure OpenAI API key has sufficient credits
  • Verify trigger conditions match messages
  • Check OpenAI API status
  • Use GPT-3.5-turbo instead of GPT-4 for faster responses
  • Reduce maxTokens for quicker completions
  • Check your internet connection to OpenAI
  • Monitor OpenAI API latency
  • Reduce maxTokens to limit response length
  • Use GPT-3.5-turbo instead of GPT-4
  • Implement stricter triggers to reduce activations
  • Set shorter session expiration times
  • Monitor usage in OpenAI dashboard
  • Increase expire time for longer sessions
  • Set keepOpen: true for persistent conversations
  • Verify conversation history is being sent
  • Check maxTokens isn’t too low for context
  • Dify - LLM orchestration platform
  • Flowise - Visual LLM workflow builder
  • EvoAI - Evolution AI platform

Build docs developers (and LLMs) love