Skip to content

Run executable typescript files with tsx

License

Notifications You must be signed in to change notification settings

lgrammel/tsx-ai

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tsx-ai

Quick guide how to use the Vercel AI SDK with TSX to create executable Node.js scripts that use AI.

  1. Install tsx globally
    npm install -g tsx
  2. Install node modules
    npm i ai @ai-sdk/openai dotenv @types/node
  3. Add OpenAI API key to .env (OPENAI_API_KEY)
  4. 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);
    }
  5. Make executable: chmod +x hello-world.mts
  6. Run: ./hello-world.mts

About

Run executable typescript files with tsx

Resources

License

Stars

Watchers

Forks