In this tutorial, we'll create a chatbot using the OpenAI API with TypeScript and Node.js. TypeScript adds strong typing to JavaScript, enhancing code quality and readability.
Prerequisites
- Basic understanding of Node.js and TypeScript.
- Node.js and TypeScript installed on your machine.
- An OpenAI API key (available on OpenAI's website).
Setup Your TypeScript Project
First, initialize a new Node.js project and install the necessary packages:
mkdir openai-chatbot-ts
cd openai-chatbot-ts
npm init -y
npm install openai express body-parser --save
npm install typescript ts-node @types/express @types/body-parser @types/node --save-dev
Create a tsconfig.json
for TypeScript configuration:
{
"compilerOptions": {
"target": "ES2018",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}
Implementing the Chatbot
Create a file chatbot.ts
:
import express, { Request, Response } from "express";
import bodyParser from "body-parser";
import { OpenAIApi, Configuration } from "openai";
const app = express();
app.use(bodyParser.json());
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY, // Set your API key in environment variables
});
const openai = new OpenAIApi(configuration);
app.post("/message", async (req: Request, res: Response) => {
const prompt = req.body.message;
try {
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: `Human: ${prompt}\nAI:`,
temperature: 0.9,
max_tokens: 150,
stop: [" Human:", " AI:"],
});
res.send({ reply: response.data.choices[0].text.trim() });
} catch (error) {
res.status(500).send(error.message);
}
});
const port = 3000;
app.listen(port, () => {
console.log(`Chatbot server running on http://localhost:${port}`);
});
This TypeScript script sets up an Express server and uses the OpenAI API to respond to messages. TypeScript enhances this setup with type safety and better tooling support.
Running the Chatbot
Compile and run the TypeScript application:
npx ts-node chatbot.ts
Test the chatbot by sending POST requests to http://localhost:3000/message
with a JSON body containing a message
field.
Conclusion
You now have a basic chatbot running with TypeScript and the OpenAI API. TypeScript adds an extra layer of reliability and maintainability to your Node.js applications.