Open core/generate-text.ts. You should see the following code already:
core/generate-text.ts
import dotenv from "dotenv";dotenv.config();async function main() {}main().catch(console.error);
First, import and call the generateText function.
core/generate-text.ts
import { generateText } from "ai"; import dotenv from "dotenv";dotenv.config();async function main() { const result = await generateText({}); }main().catch(console.error);
Next, specify which model you want to use. First, import the official OpenAI provider from @ai-sdk/openai, and then pass it to the model key.
core/generate-text.ts
import { openai } from "@ai-sdk/openai"; import { generateText } from "ai";import dotenv from "dotenv";dotenv.config();async function main() { const result = await generateText({ model: openai("gpt-4o"), });}main().catch(console.error);
Note: the OpenAI provider will look for the OPENAI_API_KEY in your .env file by default.
Now, add a prompt.
core/generate-text.ts
import { openai } from "@ai-sdk/openai";import { generateText } from "ai";import dotenv from "dotenv";dotenv.config();async function main() { const result = await generateText({ model: openai("gpt-4o"), prompt: "Tell me a joke.", });}main().catch(console.error);
Finally, log out the models response.
core/generate-text.ts
import { openai } from "@ai-sdk/openai";import { generateText } from "ai";import dotenv from "dotenv";dotenv.config();async function main() { const result = await generateText({ model: openai("gpt-4o"), prompt: "Tell me a joke.", }); console.log(result.text); }main().catch(console.error);
Run the script in the terminal, and see what happens.