0% found this document useful (0 votes)
64 views

Building A Chatbot With Angular and OpenAI API

Uploaded by

Marlon Leandro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Building A Chatbot With Angular and OpenAI API

Uploaded by

Marlon Leandro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

25/8/24, 5:51 p.m.

Building a Chatbot with Angular and OpenAI API: A Step-by-Step Guide | by Tharindu Yasantha | Engineering at 99x

Building a Chatbot with Angular and OpenAI API: A


Step-by-Step Guide
Tharindu Yasantha · Follow
Published in Engineering at 99x · 6 min read · Jul 24, 2023

151 2

Angular logo (left), OpenAI logo (right)

Summary
In this guide, we will walk through the process of building a chatbot UI using Angular and integrating it with the
OpenAI API. By following these step-by-step instructions, you’ll be able to create a functional chat interface where
users can interact with the chatbot powered by the OpenAI GPT-3 model.

Pre-Requisites:
1. OpenAI API Key:
You need to create an OpenAI account and go to the link below and create a secret key, and that will be your API
key to this project.
https://platform.openai.com/account/api-keys

2. Node.js and npm are installed on your computer.

3. Angular CLI is installed on your computer. If you haven’t installed it, you can do so by running npm install -g

@angular/cli

Step 01: Create an Angular Application

The first thing you need to do is create a new Angular application. If you have installed Angular CLI, this is as simple
as running a quick search on the internet.

I will simply add commands so it will be easier for you to set up the application quickly.

Open the VS Code and open the folder you wish to create the angular application and get a new Terminal to execute
the below commands.
https://engineering.99x.io/building-a-chatbot-with-angular-and-openai-api-a-step-by-step-guide-6a0f153e0924 2/8
25/8/24, 5:51 p.m. Building a Chatbot with Angular and OpenAI API: A Step-by-Step Guide | by Tharindu Yasantha | Engineering at 99x

1) ng new chatbot-app
2) cd chatbot-app
3) ng generate component chatbot
4) ng generate service service/open-ai-api.service
5) mkdir src/environments
6) Create a new file and save it as environment.ts
inside the 'environments' folder

Now all the component needed to function in the Angular app is done.
While Angular handles the client-side rendering, I prefer using Express.js as the back-end server framework.

Step 02: Setting Up the Express.js Server

1. Open your command-line interface (CLI) or terminal.

2. Navigate to the root directory of your project where you want to create the server.js file.

1) npm init -y
2) npm install express
3) Create server.js file inside the server folder

3. Once you have created the server.js file add the below code to it

const express = require('express');


const app = express();
const port = 3000;

// Define API routes and handlers here

app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

4. Go to the location of the file in your VS Code terminal and execute the below command to verify whether the server
is up or not.

node server.js

If it’s up you are almost there!

Step 03: Integrating the OpenAI API with Express.js


Before jumping into this you can refer to the API Documentation provided by OpenAI
refer: https://platform.openai.com/docs/api-reference/chat

We are using its chat/completions endpoint and they have already built a node package integrated with all the
endpoints to the OpenAI API.
https://engineering.99x.io/building-a-chatbot-with-angular-and-openai-api-a-step-by-step-guide-6a0f153e0924 3/8
25/8/24, 5:51 p.m. Building a Chatbot with Angular and OpenAI API: A Step-by-Step Guide | by Tharindu Yasantha | Engineering at 99x

refer:
https://www.npmjs.com/package/openai
https://platform.openai.com/docs/libraries

Okay, let’s start.

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

const app = express();


const port = 3000;

const configuration = new Configuration({


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

app.use(express.json());
app.use(cors());

app.post("/chat", async (req, res) => {


const { message } = req.body;

const completion = await openai.createChatCompletion({


model: "gpt-3.5-turbo",
messages: [{ role: "system", content: "You are a helpful assistant." }, { role: "user", content: message }],
});

const reply = completion.data.choices[0].message.content;

res.json({ reply });


});

app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

As you can see, I have created a .env file and stored my API Key, and created a post request which gonna send our
chat message to chat/completions endpoint.

You can run the server and invoke a Postman request to test whether it’s working or not.

Request format in Postman

Working from me!!! hopefully working for you as well (wink wink)

Step 04: Connecting the Angular App to the Express.js Server

In this step, we will focus on connecting the Angular app to the Express.js server we created in Step 03. We will cover
the following tasks:
https://engineering.99x.io/building-a-chatbot-with-angular-and-openai-api-a-step-by-step-guide-6a0f153e0924 4/8
25/8/24, 5:51 p.m. Building a Chatbot with Angular and OpenAI API: A Step-by-Step Guide | by Tharindu Yasantha | Engineering at 99x

1. Modifying the service we already created in Step 01 to handle API requests.

2. Implementing methods in the service to send and receive chat messages.

3. Updating the chat UI component to use the service and display messages.

4. Handling user input and sending messages to the server.

5. Receiving and displaying the assistant’s replies in real-time.

Since we are communicating with the server, we need HttpClientModule

let’s import it to the app.module.ts


Also,

I’m hoping to use a FormsModule so I can submit users’ messages!

Update your app.module.ts with the below code.

import { NgModule } from '@angular/core';


import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';


import { ChatbotComponent } from './chatbot/chatbot.component';
import { FormsModule } from '@angular/forms';

@NgModule({
declarations: [
AppComponent,
ChatbotComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

and then I add below code segment

<app-chatbot></app-chatbot>

to my app.component.html. so my chatbot component will be rendered as part of the main component’s template.

Now let’s update the chatbot.component.ts file by adding the following code to it.

import { Component } from '@angular/core';


import { OpenAiApiService } from '../services/open-ai-api.service';

https://engineering.99x.io/building-a-chatbot-with-angular-and-openai-api-a-step-by-step-guide-6a0f153e0924 5/8
25/8/24, 5:51 p.m. Building a Chatbot with Angular and OpenAI API: A Step-by-Step Guide | by Tharindu Yasantha | Engineering at 99x
@Component({
selector: 'app-chatbot',
templateUrl: './chatbot.component.html',
styleUrls: ['./chatbot.component.css']
})
export class ChatbotComponent {
userMessage!: string;
assistantReply!: string;
chatMessages: { role: string, content: string }[] = [];

constructor(private openAiApiService: OpenAiApiService){}

sendMessage() {
const userMessage = this.userMessage;
this.chatMessages.push({ role: 'user', content: userMessage });
this.openAiApiService.sendMessage(this.userMessage)
.subscribe(response => {
this.assistantReply = response.reply;
this.chatMessages.push({ role: 'assistant', content: this.assistantReply });
this.userMessage = '';
});
}
}

In here,

userMessage : Represents the current input message entered by the user in the chatbot interface.

assistantReply : Stores the response received from the OpenAI API after sending the user's message.

chatMessages : An array that holds the chat messages exchanged between the user and the assistant. Each message
is an object with two properties: role (indicating the sender's role, either 'user' or 'assistant') and content (the
actual message content).

sendMessage() : This method is triggered when the user clicks the "Send" button in the chatbot interface. It performs
the following actions:

1. Stores the current value of userMessage in a local variable userMessage .

2. Pushes the user’s message to the chatMessages array with the role set to 'user'.

3. Calls the sendMessage() method of the OpenAiApiService and passes the user's message.

4. Subscribes to the response from the API and executes the callback function with the response.

5. Stores the assistant’s reply in the assistantReply variable.

6. Pushes the assistant’s reply to the chatMessages array with the role set to 'assistant'.

7. Clears the userMessage by setting it to an empty string.

And now, let’s create the HTML template by adding the following code to chatbot.component.html

<div class="chat-container">
<div *ngFor="let message of chatMessages" [ngClass]="message.role">
{{ message.content }}
</div>

https://engineering.99x.io/building-a-chatbot-with-angular-and-openai-api-a-step-by-step-guide-6a0f153e0924 6/8
25/8/24, 5:51 p.m. Building a Chatbot with Angular and OpenAI API: A Step-by-Step Guide | by Tharindu Yasantha | Engineering at 99x
</div>

<div class="input-container">
<input [(ngModel)]="userMessage" placeholder="Enter your message" />
<button (click)="sendMessage()">Send</button>
</div>

We are only a single step away from finishing our chatbot application.

Let’s add a few styles to our chatbot UI,

.chat-container {
height: 300px;
overflow-y: auto;
padding: 10px;
}

.message {
background-color: #f7f7f7;
color: #000;
padding: 5px;
margin-bottom: 10px;
}

.user {
background-color: #d0edff;
}

.assistant-reply {
margin-top: 10px;
font-style: italic;
}

.input-container {
margin-top: 10px;
}

.input-container input {
padding: 5px;
}

.input-container button {
padding: 5px 10px;
margin-left: 10px;
}

Step 05: Finishing up!!!

Okay, now our application is complete. It’s time to run the application.

First, we run the express server.


Go to the server folder through your terminal and run the below command.

node server.js

Then we run our angular application.


Go to the angular applications route folder through your terminal and run the below command.
https://engineering.99x.io/building-a-chatbot-with-angular-and-openai-api-a-step-by-step-guide-6a0f153e0924 7/8
25/8/24, 5:51 p.m. Building a Chatbot with Angular and OpenAI API: A Step-by-Step Guide | by Tharindu Yasantha | Engineering at 99x

ng serve

Enjoy!!

Initiating a conversation with the chatbot

Find the whole project here!

https://github.com/tharinduyasantha/openai-chatbot-angular-express

Conclusion
In conclusion, the combination of Angular, Express.js, and the OpenAI API provides a powerful platform for creating
chatbot applications. By leveraging Angular for the front end, Express.js for the back end, and the OpenAI API for
intelligent responses, developers can build interactive chatbots that offer personalized experiences and enhance user
interactions. The possibilities for innovation and customization using this template are endless, making it an ideal
choice for developing sophisticated chatbot applications.

https://engineering.99x.io/building-a-chatbot-with-angular-and-openai-api-a-step-by-step-guide-6a0f153e0924 8/8

You might also like