Skip to content

Chain of Thought

The agent's steps as one summary line that opens into each search, read and result, with failures marked.

Why is the checkout deploy so slow?

Image optimization takes almost four minutes because its cache key includes the commit hash. Key it on the image directory instead.

Installation

pnpm dlx shadcn@latest add @silkware/ai-chain-of-thought

To copy the pattern by hand, install the components it composes:

pnpm dlx shadcn@latest add @silkware/badge @silkware/bubble @silkware/button @silkware/code-block @silkware/message @silkware/trace

Then install the packages it imports and copy the pattern into components/ai-elements/chain-of-thought.tsx:

pnpm add ai @ai-sdk/react @shadcn/helpers lucide-react

The pattern also imports @/lib/ai, which holds the scripted streams.

components/ai-elements/chain-of-thought.tsx
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"import type { UIDataTypes, UIMessage } from "ai"import {  ArrowUpRightIcon,  CircleAlertIcon,  CircleCheckIcon,  GlobeIcon,  LoaderCircleIcon,} from "lucide-react"
import { createChat, getMessageText } from "@/lib/ai"import { Badge } from "@/components/ui/badge"import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Button } from "@/components/ui/button"import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import { Message, MessageContent } from "@/components/ui/message"import {  Trace,  TraceCollapsible,  TraceCollapsibleContent,  TraceCollapsibleTrigger,  TraceIcon,  TraceLine,  TraceTitle,} from "@/components/ui/trace"
type ChatMessage = UIMessage<  unknown,  UIDataTypes,  {    searchWeb: {      input: { query: string }      output: { results: { title: string; url: string }[] }    }    readBuildLog: {      input: { deployment: string }      output: { log: string }    }    searchCode: {      input: { query: string }      output: { files: string[] }    }  }>
type StepPart = Extract<  ChatMessage["parts"][number],  { type: "tool-searchWeb" | "tool-readBuildLog" | "tool-searchCode" }>
const chat = createChat<ChatMessage>()  .user("Why is the checkout deploy so slow?")  .assistant(({ writer }) => {    writer      .tool("readBuildLog", { input: { deployment: "dpl_8Kx2" } })      .sleep(900)      .output({        log: "install    41s\ncompile    38s\nimages   3m 52s",      })    writer      .tool("searchWeb", { input: { query: "next.js image cache key" } })      .sleep(900)      .output({        results: [          {            title: "Image component | nextjs.org",            url: "https://nextjs.org/docs/app/api-reference/components/image",          },          {            title: "Build cache | vercel.com",            url: "https://vercel.com/docs/deployments/troubleshoot-a-build",          },        ],      })    writer      .tool("searchCode", { input: { query: "cacheKey" } })      .sleep(900)      .output({ files: ["next.config.ts", "scripts/optimize-images.ts"] })    writer.text(      "Image optimization takes almost four minutes because its cache key includes the commit hash. Key it on the image directory instead."    )  })
const transcript = chat.get()const [question] = chat.get(1)const transport = chat.transport({ delayMs: 20 })
function StatusIcon({ status }: { status?: "running" | "error" }) {  if (status === "running") {    return <LoaderCircleIcon className="animate-spin" />  }
  return status === "error" ? <CircleAlertIcon /> : <CircleCheckIcon />}
function Step({  title,  status,  defaultExpanded,  children,}: {  title: string  status?: "running" | "error"  defaultExpanded?: boolean  children?: React.ReactNode}) {  const line = (    <TraceLine status={status}>      <TraceIcon>        <StatusIcon status={status} />      </TraceIcon>      <TraceTitle>{title}</TraceTitle>    </TraceLine>  )
  if (!children) {    return line  }
  return (    <TraceCollapsible defaultExpanded={defaultExpanded}>      <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>      <TraceCollapsibleContent>{children}</TraceCollapsibleContent>    </TraceCollapsible>  )}
function StepRow({ part, streaming }: { part: StepPart; streaming: boolean }) {  const status =    part.state === "output-available"      ? undefined      : part.state === "output-error" || !streaming        ? "error"        : "running"  const verb = (running: string, done: string, failed: string) =>    status === "running" ? running : status === "error" ? failed : done  const error = part.state === "output-error" && (    <CodeBlock size="sm" variant="destructive">      <CodeBlockContent wrap className="max-h-64">        {part.errorText}      </CodeBlockContent>    </CodeBlock>  )
  if (part.type === "tool-searchWeb") {    return (      <Step        status={status}        title={`${verb("Searching", "Searched", "Failed to search")} the web for ${part.input?.query}`}      >        {error ||          (part.state === "output-available" && (            <Trace>              {part.output.results.map((result) => (                <a                  key={result.url}                  href={result.url}                  target="_blank"                  rel="noreferrer"                >                  <TraceLine>                    <TraceIcon>                      <GlobeIcon />                    </TraceIcon>                    <TraceTitle>                      {result.title}                      <span className="sr-only"> (opens in a new tab)</span>                    </TraceTitle>                    <TraceIcon>                      <ArrowUpRightIcon />                    </TraceIcon>                  </TraceLine>                </a>              ))}            </Trace>          ))}      </Step>    )  }
  if (part.type === "tool-readBuildLog") {    return (      <Step        status={status}        defaultExpanded        title={`${verb("Reading", "Read", "Failed to read")} the build log for ${part.input?.deployment}`}      >        {error ||          (part.state === "output-available" && (            <CodeBlock size="sm">              <CodeBlockContent wrap className="max-h-64">                {part.output.log}              </CodeBlockContent>            </CodeBlock>          ))}      </Step>    )  }
  return (    <Step      status={status}      title={`${verb("Searching", "Searched", "Failed to search")} the code for ${part.input?.query}`}    >      {error ||        (part.state === "output-available" && (          <div className="flex flex-wrap gap-1.5">            {part.output.files.map((file) => (              <Badge key={file} variant="secondary" className="font-mono">                {file}              </Badge>            ))}          </div>        ))}    </Step>  )}
function ChainOfThought({  steps,  streaming,  answering,}: {  steps: StepPart[]  streaming: boolean  answering: boolean}) {  const [open, setOpen] = React.useState<boolean>()  const running = streaming && !answering  const failed = steps.filter((part) => part.state === "output-error").length  const status = running ? "running" : failed > 0 ? "error" : undefined
  return (    <Trace>      <TraceCollapsible isExpanded={open ?? running} onExpandedChange={setOpen}>        <TraceCollapsibleTrigger>          <TraceLine status={status}>            <TraceIcon>              <StatusIcon status={status} />            </TraceIcon>            <TraceTitle>              {running                ? "Researching"                : `Researched in ${steps.length} steps${failed > 0 ? `, ${failed} failed` : ""}`}            </TraceTitle>          </TraceLine>        </TraceCollapsibleTrigger>        <TraceCollapsibleContent>          <Trace>            {steps.map((part) => (              <StepRow                key={part.toolCallId}                part={part}                streaming={streaming}              />            ))}          </Trace>        </TraceCollapsibleContent>      </TraceCollapsible>    </Trace>  )}
export function ChainOfThoughtDemo() {  const { messages, sendMessage, setMessages, status } = useChat({    messages: transcript,    transport,  })  const busy = status === "submitted" || status === "streaming"
  return (    <div className="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">      {messages.map((message) => {        if (message.role === "user") {          return (            <Message key={message.id} align="end">              <MessageContent>                <Bubble align="end" variant="muted">                  <BubbleContent>{getMessageText(message)}</BubbleContent>                </Bubble>              </MessageContent>            </Message>          )        }
        const streaming = busy && message === messages.at(-1)        const steps = message.parts.filter(          (part) =>            part.type === "tool-searchWeb" ||            part.type === "tool-readBuildLog" ||            part.type === "tool-searchCode"        )        const text = getMessageText(message)
        return (          <Message key={message.id}>            <MessageContent className="gap-4">              {steps.length > 0 && (                <ChainOfThought                  steps={steps}                  streaming={streaming}                  answering={text.length > 0}                />              )}              {text && <p>{text}</p>}            </MessageContent>          </Message>        )      })}      {!busy && (        <Button          variant="outline"          size="sm"          className="mt-auto self-start"          onPress={() => {            setMessages([])            sendMessage(question)          }}        >          Replay        </Button>      )}    </div>  )}

Usage

import {  Trace,  TraceCollapsible,  TraceCollapsibleContent,  TraceCollapsibleTrigger,  TraceIcon,  TraceLine,  TraceTitle,} from "@/components/ui/trace"
<Trace>  <TraceCollapsible isExpanded={open ?? running} onExpandedChange={setOpen}>    <TraceCollapsibleTrigger>      <TraceLine status={status}>        <TraceIcon>          <StatusIcon status={status} />        </TraceIcon>        <TraceTitle>Researched in {steps.length} steps</TraceTitle>      </TraceLine>    </TraceCollapsibleTrigger>    <TraceCollapsibleContent>      <Trace>{steps.map((part) => <StepRow key={part.toolCallId} part={part} />)}</Trace>    </TraceCollapsibleContent>  </TraceCollapsible></Trace>

The outer line is a summary. While the agent works it reads "Researching", with a spinner, and is open. When the reply starts it closes and reads "Researched in 3 steps", plus ", 1 failed" if any step failed. A Trace nested in the content holds one row per step. As in Reasoning, open is undefined until the person decides, and then their choice wins.

Each step is a TraceCollapsible of its own when it has something to show: a list of links, a block of log text, or a set of file badges. A step with no result is a plain line.

Examples

Three kinds of step

The demo reads a build log (open by default, in a Code Block), searches the web (a list of links that open in a new tab) and searches the code (file names as badges). Each tool has its own typed input and output in ChatMessage, and StepRow branches on part.type.

A failed step

A step that fails turns its line and the summary red, and shows the error in a destructive code block. Colour is not the only signal: the verb changes to "Failed to read", and the summary counts failures.

Read the open orders for Brevia Manufacturing
Price list v12 is locked by Marco. Try again when it is closed.

AI SDK

Each step is a tool part. A tool part moves through input-streaming, input-available, output-available and output-error. The pattern maps those to three line states: running (spinner and shimmer), done, and error.

const status =  part.state === "output-available"    ? undefined    : part.state === "output-error" || !streaming      ? "error"      : "running"

The last branch matters: a tool part that has no output while the turn is no longer streaming never finished, so it is shown as failed rather than as running forever.

Type the message once and use it for createChat and useChat:

type ChatMessage = UIMessage<  unknown,  UIDataTypes,  {    readBuildLog: {      input: { deployment: string }      output: { log: string }    }  }>
const { messages } = useChat<ChatMessage>()

Filter a message's parts to the tool types you want as steps, then render the rest as the reply. The route defines the same tools with streamText({ tools }). For tools the model can add at run time, parts have the type dynamic-tool and a toolName; narrow them with isToolUIPart and getToolName from ai.

Offline, createChat scripts a step with writer.tool("readBuildLog", { input }).sleep(900).output({ log }). Use .error() for a failed step, and use the handle's .sleep to give the running state some time on screen.

Accessibility

KeyAction
EnterOpens or closes the focused summary or step.
SpaceOpens or closes the focused summary or step.
TabMoves to the next summary, step, link or log block inside an open step. The log block is focusable so it can be scrolled.

The composed components provide:

  • React Aria disclosures: real buttons with aria-expanded, and a visible focus ring.
  • A spinner and shimmer for the running state, which stop under the global reduced-motion rule.

You provide:

  • Titles that say the state in words ("Searching", "Searched", "Failed to search"), not by icon or colour alone.
  • Links that open in a new tab with that said to screen readers. The demo adds a visually hidden "(opens in a new tab)".
  • A live region if the person must know when the research ends. The summary text changes, but it is not announced on its own.

Guidelines

When to use

  • When the agent takes several steps that the person may want to audit: searches, file reads, checks.
  • To keep the reply uncluttered while leaving every step one press away.

When not to use

  • For a single step with an approval. Use Tool and Confirmation.
  • For the agent's plan before it acts. Use Plan.
  • For a task list that runs in the background. Use Task or Queue.

Content

  • Start step titles with a verb in the present tense while running, and past tense when done.
  • Name the object in the title: "Searched the web for next.js image cache key".
  • Show results as they are: log text, links, file names. Do not summarise them in the title.

Human in the loop

Steps are the person's evidence. Keep failed steps visible and open the failed one by default, so a problem is never hidden behind a tidy summary. If a step changes data, ask first, and put the approval on the step (see Confirmation).

Do

Say "Researched in 3 steps, 1 failed" and let the person open the failure.

Don’t

Don’t collapse everything into "Done" when a step failed. The person trusts a result that was not reached.

Composition

ComponentWhat it does here
TraceThe summary line, the nested list and each step: lines, icons, titles and collapsibles.
Code BlockShows log output and errors in a step.
BadgeShows the files a code search found.
Message and BubbleThe turn around the steps in the demo.
ButtonThe Replay button in the demo.

The pattern exports one component, ChainOfThoughtDemo. ChainOfThought, Step, StepRow and StatusIcon are internal to the file: copy them to reuse the chain in your own thread.