Skip to content

Reasoning

A line for the agent's thinking that opens while it thinks and closes when it is done.

Why is the checkout deploy so slow?
The deploy log has three phases. Install takes 38s and next build takes 52s, both normal for this repo. Image optimization takes 3m 50s. It reruns on every deploy because its cache key includes the commit hash, so the cache never hits.

Image optimization is the bottleneck. Key its cache on the lockfile and the image directory instead of the commit hash, and the deploy should take under two minutes.

Installation

pnpm dlx shadcn@latest add @silkware/ai-reasoning

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

pnpm dlx shadcn@latest add @silkware/bubble @silkware/button @silkware/message @silkware/trace

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

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

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

components/ai-elements/reasoning.tsx
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"
import { createChat, getMessageText } from "@/lib/ai"import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Button } from "@/components/ui/button"import { Message, MessageContent } from "@/components/ui/message"import {  Trace,  TraceCollapsible,  TraceCollapsibleContent,  TraceCollapsibleTrigger,  TraceLine,  TraceTitle,} from "@/components/ui/trace"
const chat = createChat()  .user("Why is the checkout deploy so slow?")  .assistant(({ writer }) => {    writer.reasoning(      "The deploy log has three phases. Install takes 38s and next build takes 52s, both normal for this repo.\n\nImage optimization takes 3m 50s. It reruns on every deploy because its cache key includes the commit hash, so the cache never hits.",      { delayMs: 40 }    )    writer.sleep(400)    writer.text(      "Image optimization is the bottleneck. Key its cache on the lockfile and the image directory instead of the commit hash, and the deploy should take under two minutes."    )  })
const transcript = chat.get()const [question] = chat.get(1)const transport = chat.transport({ delayMs: 20 })
function ReasoningRow({  text,  running,  defaultExpanded,}: {  text: string  running: boolean  defaultExpanded?: boolean}) {  const [open, setOpen] = React.useState(defaultExpanded)
  const line = (    <TraceLine status={running ? "running" : undefined}>      <TraceTitle>{running ? "Thinking" : "Thought for 5s"}</TraceTitle>    </TraceLine>  )
  if (text.length === 0) {    return line  }
  return (    <TraceCollapsible isExpanded={open ?? running} onExpandedChange={setOpen}>      <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>      <TraceCollapsibleContent className="whitespace-pre-wrap">        {text}      </TraceCollapsibleContent>    </TraceCollapsible>  )}
export function ReasoningDemo() {  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 reasoning = message.parts.filter(          (part) => part.type === "reasoning"        )        const text = getMessageText(message)
        return (          <Message key={message.id}>            <MessageContent className="gap-4">              {reasoning.length > 0 && (                <Trace>                  {reasoning.map((part, index) => (                    <ReasoningRow                      key={index}                      text={part.text}                      running={streaming && part.state === "streaming"}                      defaultExpanded={busy ? undefined : true}                    />                  ))}                </Trace>              )}              {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,  TraceLine,  TraceTitle,} from "@/components/ui/trace"
function ReasoningRow({ text, running }: { text: string; running: boolean }) {  const [open, setOpen] = React.useState<boolean>()
  const line = (    <TraceLine status={running ? "running" : undefined}>      <TraceTitle>{running ? "Thinking" : "Thought"}</TraceTitle>    </TraceLine>  )
  if (text.length === 0) {    return line  }
  return (    <TraceCollapsible isExpanded={open ?? running} onExpandedChange={setOpen}>      <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>      <TraceCollapsibleContent className="whitespace-pre-wrap">        {text}      </TraceCollapsibleContent>    </TraceCollapsible>  )}

open starts as undefined, which means "follow the agent": the row opens while it thinks and closes when it is done. Once the person opens or closes it, open holds their choice and it wins. Until the first text arrives the row is a plain TraceLine with nothing to open. Wrap every row in one Trace, which stacks them.

Examples

Duration

The AI SDK does not time reasoning. Measure it on your server, send it as message metadata, and show it in a TraceDescription after the title.

Waiting and thinking

Before text arrives the row is a shimmering line with no chevron. When text arrives it gains one and opens by itself.

Thinking
Two suppliers raised steel prices in the new list. Before comparing totals I need the quantities from the open orders.

AI SDK

Render each reasoning part of an agent message as one row. Some models send several parts in one message, so map all of them into the same Trace.

const { messages, status } = useChat()const busy = status === "submitted" || status === "streaming"
{messages.map((message) => {  const streaming = busy && message === messages.at(-1)  const parts = message.parts.filter((part) => part.type === "reasoning")
  return (    parts.length > 0 && (      <Trace key={message.id}>        {parts.map((part, index) => (          <ReasoningRow            key={index}            text={part.text}            running={streaming && part.state === "streaming"}          />        ))}      </Trace>    )  )})}

A reasoning part has text and a state of streaming or done. The route must send it: toUIMessageStreamResponse({ sendReasoning: true }) (this is the default). For the duration, use messageMetadata, which runs on the start and finish events:

let startedAt = 0
return result.toUIMessageStreamResponse({  messageMetadata: ({ part }) => {    if (part.type === "start") {      startedAt = Date.now()    }    if (part.type === "finish") {      return { thinkingMs: Date.now() - startedAt }    }  },})

Offline, createChat streams reasoning with writer.reasoning("..."), and delayMs sets how fast it types. The demo replays one scripted answer with its Replay button.

Accessibility

KeyAction
EnterOpens or closes the thinking when the row has focus.
SpaceOpens or closes the thinking when the row has focus.
TabMoves focus to the next control.

The composed components provide:

  • A disclosure built on React Aria: the trigger is a real button, aria-expanded follows the open state and the panel is tied to it.
  • A chevron that turns with the state and a visible focus ring.

You provide:

  • A title that says what the state is: "Thinking" while it runs, "Thought" when done.
  • A live announcement for long runs if the person needs it. The shimmer is visual only.
  • Reasoning text with sufficient contrast: the trace content is muted by design, so keep it at body size.

Guidelines

When to use

  • When the model sends reasoning and the person may want to read how it got to the answer.
  • Above the reply, as one of the agent's steps.

When not to use

  • For steps that have inputs and outputs, such as reading a file. Use Chain of Thought or Tool.
  • For the answer itself. Reasoning is the working, not the result.

Content

  • Show the text as the model wrote it, unedited. Do not summarise it unless you say so.
  • Keep it closed once finished, so the reply is what people see first.
  • Show the duration when the run took long enough to notice.

Human in the loop

Reasoning is how the person checks the agent before it acts. Keep it available after the run, never remove it from the thread, and do not present it as a certain explanation: it describes what the model wrote, not a guarantee of why it answered.

Do

Let the person open and close the row, and keep their choice while the agent keeps thinking.

Don’t

Don’t force the thinking open or shut each time new text arrives. It fights the reader.

Composition

ComponentWhat it does here
TraceTrace stacks the rows, TraceLine and TraceTitle draw one, TraceCollapsible with its trigger and content opens the text.
Message and BubbleThe turn around the row in the demo.
ButtonThe Replay button in the demo.

The pattern exports one component, ReasoningDemo. ReasoningRow is internal to the file: copy it into your own module to reuse it.