Quick guide how to use the Vercel AI SDK with TSX to create executable Node.js scripts that use AI.
- Install tsx globally
npm install -g tsx
- Install node modules
npm i ai @ai-sdk/openai dotenv @types/node
- Add OpenAI API key to
.env
(OPENAI_API_KEY
) - Write a
.mts
script (e.g.hello-world.mts
)#!/usr/bin/env tsx import { openai } from "@ai-sdk/openai"; import { streamText } from "ai"; import { configDotenv } from "dotenv"; configDotenv(); const { textStream } = await streamText({ model: openai("gpt-4o"), prompt: "How can I list files in bash?", }); for await (const textPart of textStream) { process.stdout.write(textPart); }
- Make executable:
chmod +x hello-world.mts
- Run:
./hello-world.mts