OpenAI ChatGPT Integration With Dialog Flow

Srimathi Jagadeesan
hackgenius
Published in
4 min readFeb 16, 2023

--

Hi Everyone ! I trust you are doing well.

In this blog , We’ll be exploring OpenAI ChatGPT Integration .

ChatGPT

We’re going to create a chatbot integrating withOpenAI(ChatGPT 3) APIs’ & Dialog Flow Framework.

What is OpenAI ChatGPT?

ChatGPT is a conversational chatbot created by OpenAI & it’s been launched in November 2022. It depends on the GPT-3 group of language models and has acquired fame because of its capacity to answer inquiries in an apparently human way.

What is Dialog Flow?

Dialog flow is a Natural Language Understanding (NLU) Platform, where we can develop chatbots connecting with Node js. And the amazing part is we could be able to integrate chatbots with various social media platforms using their APIs.

ChatGPT + DialogFlow

The First step is to create a new agent in Google dialog flow, for that head over to the below link & Create your new agent.

Next, You should have your own OpenAI API Key,

Click this link, head over to API, and Hit Create new secret Key. Then you can generate your API Key and integrate it with other applications.

Now it’s time to create your node js app, You can use replit , to execute your app. Nextly, You have to configure your Open AI API Key

const express = require('express');
const { Configuration, OpenAIApi } = require("openai");
require('dotenv');

//Open API Key


const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);


const textGeneration = async (prompt) => {

try {
const response = await openai.createCompletion({
model: 'code-davinci-002',
prompt: `Human: ${prompt}\nAI: `,
temperature: 0.8,
max_tokens: 300,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0.9,
stop: ['Human:', 'AI:']
});

return {
status: 1,
response: `${response.data.choices[0].text}`
};
} catch (error) {
return {
status: 0,
response: ''
};
}
};


const webApp = express();

const PORT = process.env.PORT;

webApp.use(express.urlencoded({ extended: true }));
webApp.use(express.json());
webApp.use((req, res, next) => {
console.log(`Path ${req.path} with Method ${req.method}`);
next();
});


webApp.get('/', (req, res) => {
res.sendStatus(200);
});


webApp.post('/dialogflow', async (req, res) => {

let action = req.body.queryResult.action;
let queryText = req.body.queryResult.queryText;

if (action === 'input.unknown') {
let result = await textGeneration(queryText);
if (result.status == 1) {
res.send(
{
fulfillmentText: result.response
}
);
} else {
res.send(
{
fulfillmentText: `I am not getting , can you repea it again?`
}
);
}
} else {
res.send(
{
fulfillmentText: `No handler for the action ${action}.`
}
);
}
});;

//Port


webApp.listen(PORT, () => {
console.log(`Server is up and running at 8080);
});

Create Secrets in your app,

API

In the value section, paste your OPEN_AI_API_KEY! Run Your code and you’ll get an URL. Just paste the URL in the Dialogflow fulfillment section, Like below.

URL
DF-Fulfillment

Make sure to enable webhook in your Fallback Intent.

Fallback_intent

Connecting chatbot & website. I am attaching the code for website integration.


<!DOCTYPE html>

<html lang="en" dir="ltr">
<head>
<link rel="stylesheet" href="app.css">
<script src="https://www.gstatic.com/dialogflow-console/fast/messenger/bootstrap.js?v=1"></script>

<df-messenger
chat-icon="https:&#x2F;&#x2F;cdn-icons-png.flaticon.com&#x2F;512&#x2F;1698&#x2F;1698535.png"
intent="WELCOME"
chat-title="ChatGpt"
agent-id="b315b3f9-e9d4-412f-a27b-9493eab6d4f6"
language-code="en"
></df-messenger>
df-messenger {
--df-messenger-bot-message:white;
--df-messenger-input-font-color:black;
--df-messenger-button-titlebar-color:purple;
--df-messenger-maximized-chat-close-icon:white;
--df-messenger-top-navbar-icon:blue;
--df-messenger-menu-icon:yellow;
--df-messenger-chat-background-color: #0c0b0b;
--df-messenger-minimized-chat-close-icon-color:blue;
--df-messenger-input-box-color:white;
--df-messenger-font-color:black;
--df-messenger-send-icon: #6bd12f;
--df-messenger-minimize-icon:orange;
--df-messenger-bot-header-rich-icon:pink;
--df-messenger-input-placeholder-font-color:black;
--df-messenger-chip-button:pink;

}

<!-- Jquery CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
//To minimise the height of chatbox
$(document).ready(function() {
window.addEventListener('dfMessengerLoaded', function (event) {
$r1 = document.querySelector("df-messenger");
$r2 = $r1.shadowRoot.querySelector("df-messenger-chat");
$r3 = $r2.shadowRoot.querySelector("df-messenger-user-input"); //for other mods
var sheet = new CSSStyleSheet;


// manage box height from here
sheet.replaceSync( `div.chat-wrapper[opened="true"] { height: 470px}`);





$r2.shadowRoot.adoptedStyleSheets = [ sheet ];
});
});
</script>

</head>

I am inserting the code into my GitHub, you can check it there.

Let’s check with the chatbot response, I am attaching the snap of the bot response.

Bot_Initial Conversation.
Bot_Response
Math_Calculation
Bot_Response

Finally, I truly want to believe that you find this blog valuable:)

Follow my blogs to get more updates on Chatbots & Voice apps!

Stay Tuned!

</HAPPY LEARNING>

--

--

Srimathi Jagadeesan
hackgenius

Conversational AI || Mentored 500+ Students || Bot Builder|| Tech blogger|| Technical Trainer || Self learner.