Typescript for OpenAI

Getting started with an OpenAI using Typescript using yarn for package management and nvm for managing node versions.

Set up the environment

nvm install lts/*
npm install -g strip-json-comments-cli
npm install -g yarn

Set up the project directory. I use ~/src/<project>

mkdir <applicationname>
node --version > .nvmrc
yarn init -y

Example package.json for the chatone application.

{
  "name": "chatone",
  "version": "0.1.0",
  "main": "index.js",
  "author": "Mark C Allen <mark@markcallen.com>",
  "license": "MIT"
}

Add typescript

yarn add -D typescript @types/node tsx rimraf dotenv

Create the tsconfig.json file

npx tsc --init --rootDir src --outDir dist \
--esModuleInterop --resolveJsonModule --lib es2021 --target es2021 \
--module nodenext --allowJs true --noImplicitAny true
cat tsconfig.json | strip-json-comments --no-whitespace | jq -r . > tsconfig.pretty.json && mv tsconfig.pretty.json tsconfig.json

tsconfig.json

{
  "compilerOptions": {
    "target": "es2021",
    "lib": [
      "es2021"
    ],
    "module": "nodenext",
    "rootDir": "src",
    "resolveJsonModule": true,
    "allowJs": true,
    "outDir": "dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "skipLibCheck": true
  }
}

Get an OpenAI key add it to your .env file

OPENAI_API_KEY=sk-proj...

Add openai

yarn add openai

Create a simple chat bot in the src/ directory.

mkdir src
import { ChatOpenAI } from "@langchain/openai";
import * as dotenv from "dotenv";

dotenv.config(); // Load environment variables

async function askGPT(question: string) {
    const model = new ChatOpenAI({
        modelName: "gpt-4o-mini",
        temperature: 0.7, // Adjust creativity
    });

    const response = await model.invoke([{ role: "user", content: question }]);
    console.log("Answer:", response.content);
}

const args = process.argv.slice(2);

if (args.length === 0) {
    console.log("Please provide an argument.");
    process.exit(1);
}

askGPT(args.join(" "));

src/index.ts

Add scripts to the package.json

npm pkg set "scripts.clean"="rimraf ./dist"
npm pkg set "scripts.build"="tsc"

Now build and run

yarn build
node dist/index.js write me a haiku about programming

To run without having to explicitly compile the typescript

npm pkg set "scripts.dev"="tsx src/index.ts"

Now run in dev mode

yarn dev its `date` here, what time is it in Auckland, New Zealand

Add everything to git.

git init

cat << EOF > .gitignore
.env
yarn-error.log
dist/
node_modules/
EOF

git add .
git commit -m "First checkin" -a

There we go, a working typescript chatbot that uses Openai.