Stream Object

Open core/stream-object.ts. You should see the following code already:

core/stream-object.ts
import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";
import dotenv from "dotenv";

dotenv.config();

async function main() {
  const result = await streamText({
    model: openai("gpt-4o"),
    prompt: "Tell me a joke.",
  });

  for await (const textPart of result.textStream) {
    process.stdout.write(textPart);
  }
}

main().catch(console.error);

First, change the streamText function to streamObject.

core/stream-object.ts
import { openai } from "@ai-sdk/openai";
import { streamObject } from "ai";
import dotenv from "dotenv";

dotenv.config();

async function main() {
  const result = await streamObject({
    model: openai("gpt-4o"),
    prompt: "Tell me a joke.",
  });

  for await (const textPart of result.textStream) {
    process.stdout.write(textPart);
  }
}

main().catch(console.error);

Next, import Zod, define a Zod schema and then pass it to the schema key.

core/stream-object.ts
import { openai } from "@ai-sdk/openai";
import { streamObject } from "ai";
import dotenv from "dotenv";
import { z } from "zod"; 

dotenv.config();

async function main() {
  const result = await streamObject({
    model: openai("gpt-4o"),
    prompt: "Tell me a joke.",
    schema: z.object({ setup: z.string(), punchline: z.string() }), 
  });

  for await (const textPart of result.textStream) {
    process.stdout.write(textPart);
  }
}

main().catch(console.error);

Update the asynchronous for-loop to iterate over the partialObjectStream instead of textStream.

core/stream-object.ts
import { openai } from "@ai-sdk/openai";
import { streamObject } from "ai";
import dotenv from "dotenv";
import { z } from "zod";

dotenv.config();

async function main() {
  const result = await streamObject({
    model: openai("gpt-4o"),
    prompt: "Tell me a joke.",
    schema: z.object({ setup: z.string(), punchline: z.string() }),
  });

  for await (const partialObject of result.partialObjectStream) { 

    process.stdout.write(textPart);
  }
}

main().catch(console.error);

Finally, log out the model's response.

core/stream-object.ts
import { openai } from "@ai-sdk/openai";
import { streamObject } from "ai";
import dotenv from "dotenv";
import { z } from "zod";

dotenv.config();

async function main() {
  const result = await streamObject({
    model: openai("gpt-4o"),
    prompt: "Tell me a joke.",
    schema: z.object({ setup: z.string(), punchline: z.string() }),
  });

  for await (const partialObject of result.partialObjectStream) {
    console.clear(); 
    console.log(partialObject); 
  }
}

main().catch(console.error);

Run the script in the terminal, and see what happens.

npx tsx core/stream-object.ts