Building A Chatbot With Angular and OpenAI API
Building A Chatbot With Angular and OpenAI API
Building a Chatbot with Angular and OpenAI API: A Step-by-Step Guide | by Tharindu Yasantha | Engineering at 99x
151 2
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
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
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.
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
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
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
require('dotenv').config();
const express = require("express");
const { Configuration, OpenAIApi } = require("openai");
const cors = require("cors");
app.use(express.json());
app.use(cors());
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.
Working from me!!! hopefully working for you as well (wink wink)
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
3. Updating the chat UI component to use the service and display messages.
@NgModule({
declarations: [
AppComponent,
ChatbotComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<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.
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 }[] = [];
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:
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.
6. Pushes the assistant’s reply to the chatMessages array with the role set to 'assistant'.
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.
.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;
}
Okay, now our application is complete. It’s time to run the application.
node server.js
ng serve
Enjoy!!
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