# AI SDK

In this tutorial you write a Bolt app that answers a direct message by streaming text from the [AI SDK](https://ai-sdk.dev)'s `streamText` into Slack. Its model is OpenAI, through the AI SDK's OpenAI provider (`@ai-sdk/openai`), and in tests that is channelstack's [fake OpenAI](https://channelstack.dev/docs/platforms/openai): each test scripts what the model streams, so every run streams the same answer and needs no API key. Then you test the status line, the stream and the Stop button, and break the agent once. It's a short version of the `openai-ai-sdk` reference agent that channelstack's CI runs.

[Getting started](https://channelstack.dev/docs/getting-started) explains the server, `channelstack env` and a first test in more detail. This page builds on it.

## 1. Create the project

You need Node.js 24 or newer, which runs the TypeScript files below as they are.

```bash
mkdir streaming-agent && cd streaming-agent
npm init -y
npm pkg set type=module
npm i @slack/bolt@5.1.0 ai@7.0.177 @ai-sdk/openai@4.0.124
npm i -D channelstack vitest
```

These are the versions channelstack's CI runs the reference agent with.

## 2. Start channelstack

In a second terminal:

```bash
CHANNELSTACK_SLACK_WEBHOOK_URL=http://localhost:3000/slack/events \
  npx channelstack start --no-portless --port 4500
```

In the first terminal:

```bash
npx channelstack env > .env.local
```

## 3. The model

Among the lines `channelstack env` printed are two for the model:

```ini title=".env.local"
OPENAI_BASE_URL=http://127.0.0.1:4500/openai/v1
OPENAI_API_KEY=sk-proj-…
```

(With portless, the base URL is `https://openai.localhost/v1`.) The AI SDK's `openai` provider reads both by itself, so the agent needs no setting of its own: with them it talks to the fake OpenAI, and in production, without `OPENAI_BASE_URL` and with your real key, to OpenAI.

The fake has no default answer. A model call that no test scripted gets a 400 (`channelstack_no_script`), and the test fails, saying which `openai.respond(…)` would have answered it.

## 4. Write the agent

The agent answers each direct message in three steps: it sets a status line, streams the model's text into one message with `chat.startStream` and `chat.appendStream`, and ends the stream with `chat.stopStream`. When the person presses Stop, Slack sends `agent_session_stopped`, and the agent aborts the model:

```ts title="agent.ts"
import { openai } from "@ai-sdk/openai";
import { App } from "@slack/bolt";
import { streamText } from "ai";

const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  // Unset in production, so the agent talks to Slack itself.
  clientOptions: process.env.SLACK_API_URL ? { slackApiUrl: process.env.SLACK_API_URL } : {},
});

/** What is being written right now, by thread: Stop aborts it. */
const writing = new Map<string, AbortController>();

app.event("agent_session_stopped", async ({ event }) => {
  const { channel, thread_ts: thread } = event as unknown as { channel: string; thread_ts: string };
  writing.get(`${channel}:${thread}`)?.abort();
});

app.message(async ({ message, client }) => {
  // Only what a person newly wrote in a DM: no edits, no bots.
  if (message.subtype !== undefined || "bot_id" in message || message.channel_type !== "im") return;
  const { channel } = message;
  const thread = message.thread_ts ?? message.ts;
  const prompt = message.text ?? "";

  await client.assistant.threads.setStatus({ channel_id: channel, thread_ts: thread, status: "is thinking…" });
  const stop = new AbortController();
  writing.set(`${channel}:${thread}`, stop);
  const { textStream } = streamText({
    model: openai("gpt-5-mini"),
    prompt,
    abortSignal: stop.signal,
    // The person's Slack id as OpenAI's `user`: it tells channelstack whose question the call answers.
    providerOptions: { openai: { user: message.user } },
  });
  let stream: string | undefined;
  try {
    for await (const text of textStream) {
      if (stop.signal.aborted) return;
      if (stream === undefined)
        stream = (await client.chat.startStream({ channel, thread_ts: thread, markdown_text: text })).ts;
      else await client.chat.appendStream({ channel, ts: stream, markdown_text: text });
    }
    if (stream !== undefined && !stop.signal.aborted) await client.chat.stopStream({ channel, ts: stream });
  } catch (error) {
    // After Stop, Slack refuses more text with `stopped_by_user`: that is expected.
    const stopped = (error as { data?: { error?: string } }).data?.error === "stopped_by_user";
    if (!stop.signal.aborted && !stopped) throw error;
  } finally {
    writing.delete(`${channel}:${thread}`);
  }
});

await app.start(3000);
console.log("⚡️ Bolt app is running");
```

It streams in a DM because Slack allows a stream there without more arguments. To stream in a thread of a channel, `chat.startStream` also needs `recipient_user_id` and `recipient_team_id`, and the fake refuses it without them, as Slack does.

Start it in a third terminal:

```bash
node --env-file=.env.local agent.ts
```

## 5. Write the tests

Add the Vitest plugin:

```ts title="vitest.config.ts"
import channelstack from "channelstack/vitest";
import { defineConfig } from "vitest/config";

export default defineConfig({
  plugins: [channelstack()],
});
```

And two tests. Each first scripts what the model answers with the `openai` fixture: the first streams four pieces of release notes, a little slowly, and watches the answer from the status line to the end of the stream; the second holds a long answer after three pieces, presses Stop, and checks that the agent cancelled its model call:

```ts title="TypeScript"
import { expect, test } from "vitest";

/** What the model streams, a piece at a time. */
const notes = [
  "# Release notes for 0.10\n\n",
  "## What changed\n\nThe delivery queue now retries a slow acknowledgement the way the platform does.\n\n",
  "## What to do\n\nUpdate, run the tests once and read the new failure messages.\n\n",
  "## Thanks\n\nTo everyone who sent the transcript of a conversation that went wrong.\n",
];

test("streams a reply and shows a status while working", async ({ slack, openai }) => {
  await openai.respond({ text: notes }, { timing: { firstToken: "700ms", betweenChunks: "250ms" } });
  const ana = await slack.createUser({ name: "Ana" });
  const msg = await ana.say("write the release notes for 0.10", { to: slack.app });

  await expect(msg.thread).toHaveStatus("working");
  await expect(msg.thread).toHaveStatusText(/thinking/i);
  await expect(msg.thread).toHaveStreamingReplyFrom("my-agent");
  await expect(msg.thread).toHaveStatus("idle");

  const reply = await msg.thread.latestReply({ from: "my-agent" });
  const stream = await reply.stream!.ended();
  expect(stream.state).toBe("completed");
  await expect(openai).toHaveSent(msg);
});

test("Stop ends the stream and cancels the model", async ({ slack, openai }) => {
  const ai = await openai.respond({ text: "More detail, for those who asked. ".repeat(40), pauseAfter: 3 });
  const ana = await slack.createUser({ name: "Ana" });
  const msg = await ana.say("write a long report on Q3", { to: slack.app });
  const call = await ai.waitForPause();
  await expect(msg.thread).toHaveStreamingReplyFrom("my-agent");

  await ana.stop({ thread: msg });

  await expect(msg.thread).toHaveStatus("stopped");
  await expect(msg.thread).toHaveRepliesFrom("my-agent", { count: 1 });
  await expect(call).toBeAborted();
});
```

```python title="Python"
import re

from channelstack import OpenAIFixture, OpenAITiming, OpenAITurn, SlackFixture
from pytest_channelstack import expect

# What the model streams, a piece at a time.
NOTES = [
    "# Release notes for 0.10\n\n",
    "## What changed\n\nThe delivery queue now retries a slow acknowledgement the way the platform does.\n\n",
    "## What to do\n\nUpdate, run the tests once and read the new failure messages.\n\n",
    "## Thanks\n\nTo everyone who sent the transcript of a conversation that went wrong.\n",
]


async def test_streams_a_reply_and_shows_a_status_while_working(slack: SlackFixture, openai: OpenAIFixture) -> None:
    await openai.respond(OpenAITurn(text=NOTES), timing=OpenAITiming(first_token="700ms", between_chunks="250ms"))
    ana = await slack.create_user(name="Ana")
    msg = await ana.say("write the release notes for 0.10", to=slack.app)

    await expect(msg.thread).to_have_status("working")
    await expect(msg.thread).to_have_status_text(re.compile("thinking", re.I))
    await expect(msg.thread).to_have_streaming_reply_from("my-agent")
    await expect(msg.thread).to_have_status("idle")

    reply = await msg.thread.latest_reply(from_="my-agent")
    assert reply.stream
    stream = await reply.stream.ended()
    assert stream.state == "completed"
    await expect(openai).to_have_sent(msg)


async def test_stop_ends_the_stream_and_cancels_the_model(slack: SlackFixture, openai: OpenAIFixture) -> None:
    ai = await openai.respond(OpenAITurn(text="More detail, for those who asked. " * 40, pause_after=3))
    ana = await slack.create_user(name="Ana")
    msg = await ana.say("write a long report on Q3", to=slack.app)
    call = await ai.wait_for_pause()
    await expect(msg.thread).to_have_streaming_reply_from("my-agent")

    await ana.stop(thread=msg)

    await expect(msg.thread).to_have_status("stopped")
    await expect(msg.thread).to_have_replies_from("my-agent", count=1)
    await expect(call).to_be_aborted()
```

```rust title="Rust"
/// What the model streams, a piece at a time.
const NOTES: [&str; 4] = [
    "# Release notes for 0.10\n\n",
    "## What changed\n\nThe delivery queue now retries a slow acknowledgement the way the platform does.\n\n",
    "## What to do\n\nUpdate, run the tests once and read the new failure messages.\n\n",
    "## Thanks\n\nTo everyone who sent the transcript of a conversation that went wrong.\n",
];

#[tokio::test]
#[ignore = "needs a running agent"]
async fn streams_a_reply_and_shows_a_status_while_working() -> Result<()> {
    let session = fixtures::session().await?;
    let slack = session.slack().await?;
    let openai = session.openai().await?;
    openai
        .respond(json!({ "text": NOTES }))
        .timing(json!({ "firstToken": "700ms", "betweenChunks": "250ms" }))
        .await?;
    let ana = slack.create_user().name("Ana").await?;
    let msg = ana
        .say("write the release notes for 0.10")
        .to(&slack.app())
        .await?;

    expect(&msg.thread()).to_have_status("working").await?;
    expect(&msg.thread())
        .to_have_status_text(Regex::new("(?i)thinking")?)
        .await?;
    expect(&msg.thread())
        .to_have_streaming_reply_from("my-agent")
        .await?;
    expect(&msg.thread()).to_have_status("idle").await?;

    let reply = msg.thread().latest_reply().from("my-agent").await?;
    let stream = reply.stream().expect("a streamed reply").ended().await?;
    assert_eq!(stream.state(), "completed");
    expect(&openai).to_have_sent(msg.text()).await?;
    session.close().await
}

#[tokio::test]
#[ignore = "needs a running agent"]
async fn stop_ends_the_stream_and_cancels_the_model() -> Result<()> {
    let session = fixtures::session().await?;
    let slack = session.slack().await?;
    let openai = session.openai().await?;
    let ai = openai
        .respond(
            json!({ "text": "More detail, for those who asked. ".repeat(40), "pauseAfter": 3 }),
        )
        .await?;
    let ana = slack.create_user().name("Ana").await?;
    let msg = ana
        .say("write a long report on Q3")
        .to(&slack.app())
        .await?;
    let call = ai.wait_for_pause().await?;
    expect(&msg.thread())
        .to_have_streaming_reply_from("my-agent")
        .await?;

    ana.stop().thread(&msg).await?;

    expect(&msg.thread()).to_have_status("stopped").await?;
    expect(&msg.thread())
        .to_have_replies_from("my-agent", 1)
        .await?;
    expect(&call).to_be_aborted().await?;
    session.close().await
}
```

Run them:

```bash
npx vitest run
```

```
 Test Files  1 passed (1)
      Tests  2 passed (2)
```

`toHaveStatus` reads what a person sees of the agent in that thread: `working` while the status line is set, `streaming` while a stream is open, `idle` once it has ended, and `stopped` after Stop. Each check waits until it holds, so the first test follows the answer through those states in order, and `reply.stream` says how the stream ended: `completed` here. `toHaveSent(msg)` checks that Ana's message is what the agent asked the model. In the second, `pauseAfter: 3` holds the model's stream after three pieces, `ai.waitForPause()` returns that call, `toHaveRepliesFrom` waits until the agent is quiet and then counts (one message, the stream, and nothing after it), and `toBeAborted` checks that Stop cancelled the model's request instead of leaving it running.

## 6. Break it on purpose

Forget to end the stream:

```diff title="agent.ts"
-    if (stream !== undefined && !stop.signal.aborted) await client.chat.stopStream({ channel, ts: stream });
```

Restart the agent and run the tests again. The first test fails once its wait runs out:

```
 FAIL  agent.test.ts > streams a reply and shows a status while working
Error: Expected the thread to be idle, it is streaming
Still open: a stream my-agent started and never stopped: "# Release notes for 0.10"
```

Every piece of text arrived, so the message looks complete in a test that only reads its text. In Slack it would still show as being written. The `Still open:` line is channelstack telling you what the agent left unfinished, which is often the bug itself. Put `stopStream` back, restart the agent, and both tests pass.

## Next steps

- [Slack](https://channelstack.dev/docs/platforms/slack): streams, the status line, Stop and the agent split view, and the errors the fake answers with.
- [OpenAI](https://channelstack.dev/docs/platforms/openai): tool calls, a slow first token, a stream that breaks, errors, and what the agent sent.
- [Waiting and quiet](https://channelstack.dev/docs/guide/waiting-and-quiet): why `toHaveRepliesFrom` waits for quiet and the other checks don't.
- [Standard checks](https://channelstack.dev/docs/guide/standard-checks): `slackChecks({ app: "my-agent", model: "openai" })` adds the model checks to the Slack ones.
- [Chat SDK](https://channelstack.dev/docs/quickstarts/chat-sdk): the same kind of agent on the Chat SDK, where `thread.post(textStream)` streams for you.
