1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
17 small wins to finish your pathNext lesson →
generateText: a first model call
generateText sends a prompt to a model and waits for the whole answer. The result has the text, why the model stopped, and how many tokens it used.
import { generateText } from "ai";
import { MockLanguageModelV4 } from "ai/test";
const model = new MockLanguageModelV4({
doGenerate: async () => ({
content: [{ type: "text", text: "Hello from a model." }],
finishReason: { unified: "stop", raw: undefined },
usage: {
inputTokens: { total: 4, noCache: 4, cacheRead: undefined, cacheWrite: undefined },
outputTokens: { total: 4, text: 4, reasoning: undefined },
},
warnings: [],
}),
});
const result = await generateText({ model, prompt: "Say hello." });
console.log(result.text);
console.log(result.finishReason, result.usage.totalTokens);npx tsx hello.tsgenerateText takes a model and a prompt. It is async, so you await it; tsx allows await at the top level of a file. result.text is the answer, finishReason is why the model stopped, stop meaning it was done, and usage counts tokens.
MockLanguageModelV4 from ai/test is a model whose doGenerate you write. It returns exactly what a provider's model returns to the SDK: a list of content parts, a finish reason and usage. Every provider package implements that same interface, which is why the rest of your code does not care which model it has.
Try it yourself
- Change the text and run again.
- Return
finishReason: { unified: "length", raw: undefined }and print it. - Add a second text part to
contentand printresult.text.
You understood something today that you didn't yesterday.