Skip to content

Commit

Permalink
Add Dialogflow
Browse files Browse the repository at this point in the history
  • Loading branch information
vladaskorohodova committed Jan 7, 2025
1 parent e9fdfb9 commit e661764
Show file tree
Hide file tree
Showing 4 changed files with 152 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Google [Dialogflow](https://cloud.google.com/products/conversational-agents) is an AI service that allows you to build hybrid conversational agents with both deterministic and generative functionality.

This help topic explains how to integrate Dialogflow with the DevExtreme Chat component.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Before building your application, ensure you have:

- Google Cloud Platform (GCP) account
Sign up at [Google Cloud Console](http://console.cloud.google.com/) if you do not have an account.

- Dialogflow CX agent
You need to [create](https://cloud.google.com/dialogflow/cx/docs/concept/agent#create) and configure an agent for Dialogflow.

Authenticate with Dialogflow through a Service Account and key from Google Cloud:

Create a service account and key:
1. Go to Google Cloud Console -> IAM & Admin -> Service Accounts.
2. Create a service account or use an existing one.
3. Generate a key (JSON) for this account.
4. Save the JSON file.

Place the key file `your_json_key.json` in the project root directory or the path specified in your code. Ensure the key path matches the parameter in `dialogflow.js`:

const keyFilePath = path.join(__dirname, './your_json_key.json');

Specify project ID (found in the agent settings in GCP):

const projectId = 'your-project-id';

#####See Also#####
- [Dialogflow documentation](https://cloud.google.com/dialogflow/docs)
- [Dialogflow ES documentation](https://cloud.google.com/dialogflow/es/docs)
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
To integrate your application with Dialogflow, use the [`@google-cloud/dialogflow`](https://www.npmjs.com/package/@google-cloud/dialogflow) package.

Install `@google-cloud/dialogflow`:

npm install @google-cloud/dialogflow

For server dependencies, install [`express`](https://www.npmjs.com/package/express) and [`body-parser`](https://www.npmjs.com/package/body-parser):

npm install express body-parser

#### Additional Packages

The code uses the following packages to convert markdown to HTML:

- [`unified`](https://unifiedjs.com/)
- `remark-parse`
- `remark-rehype`
- `rehype-stringify`

Use npm or CDN to install these packages. They can also be installed locally for customized builds.

<!-- tab: npm -->npm install unified, remark-parse remark-rehype rehype-stringify

<!-- tab: ESM CDN -->import { unified } from 'https://esm.sh/unified@11?bundle';
import remarkParse from 'https://esm.sh/remark-parse@11?bundle';
import remarkRehype from 'https://esm.sh/remark-rehype@11?bundle';
import rehypeStringify from 'https://esm.sh/rehype-stringify@10?bundle';
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#### Customizing Parameters

The `dialogflow.js` includes the following customizable parameters:

const keyFilePath = path.join(__dirname, '../your_json_key.json');
const projectId = 'your_project_id';

- `keyFilePath`: Path to your service account key.
- `projectId`: Identifier of your GCP project in which the Dialogflow agent is created.

#### Configure Requests to Dialogflow

The `dialogflow.js` file contains the `detectIntent(message, sessionId)` function:

async function detectIntent(message, sessionId) {
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);

const params = {
session: sessionPath,
queryInput: {
text: {
text: message,
languageCode: 'en',
},
},
};

const responses = await sessionClient.detectIntent(params);
const result = responses[0]?.queryResult;

if (!result || !result.fulfillmentText) {
throw new Error('No response from Dialogflow');
}

return result.fulfillmentText;
}

The function performs the following steps:

- Forms a request to Dialogflow API with the received message and `sessionId`.
- Sets the request language to `'en'`.
- Generates `fulfillmentText` as the agent response.

`sessionId` saves the dialog context. In this example (in `index.html`), a random string serves this purpose.

#### Using Server

With Dialogflow, use a server layer to ensure application security and reliability. You cannot use this library only on the client due to Google's CORS policy blocking all requests.

To send a POST request to `/webhook`, the server calls `detectIntent` and returns the agent's response:

<!-- tab: server.js -->
app.post('/webhook', async (request, response) => {
const { message, sessionId } = request.body;
if (!message || !sessionId) {
return response.status(400).json({ error: 'Message and sessionId are required' });
}

try {
const result = await detectIntent(message, sessionId);
response.json({ response: result });
} catch (error) {
console.error(error);
response.status(500).send('Error processing request');
}
});

#### Sending and Receiving Messages

The `processMessageSending` function is called when a user sends a new message. The main purpose of this function is the following:

- To send a request for the server to get a response from Dialogflow.
- To add the received reply to the message list and display it in the chat.

The `getAIResponse` function handles the primary interaction with the API:

async function getAIResponse(messages) {
const response = await fetch(`${YOUR_SERVER_URI}/webhook`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: text, sessionId }),
});

const data = await response.json();

return data.response;
};

The user message and `sessionId` are passed in the body of the request. The function returns the assistant’s new response text.

`DevExpress.data.CustomStore` and `DevExpress.data.DataSource` manage and render message states. The functions `renderAssistantMessage` and `updateLastMessage` insert or update messages in the interface, and adjust button states (copy text, regenerate response).

The "Regenerate" button allows you to request a new response from the assistant for the last message. This replaces the previous unsuccessful response. The `regenerate` function calls `getAIResponse` again.

0 comments on commit e661764

Please sign in to comment.