AI Code Block

The AI Code Block element extends the standard code block with features purpose-built for AI-generated code: streaming-aware rendering, automatic language detection, and inline code actions.

Overview

Unlike a standard CodeBlock, the AI Code Block handles partially-streamed code gracefully. It defers syntax highlighting until the code is complete, preventing visual flicker during streaming.

typescript — streaming
Copy
interface StreamdownConfig {
  plugins: Record<string, Plugin>
  animated: boolean
}

export function createRenderer(config: StreamdownConfig) {
  return new StreamdownRenderer(config)
}

Streaming code

When isStreaming is true, the component uses lightweight text rendering. Once streaming completes, it transitions to full syntax highlighting:

components/ai-code.tsx
import { AiCodeBlock } from "@/components/ui/ai-code-block"

export function StreamingCode({
  code,
  isStreaming,
}: {
  code: string
  isStreaming: boolean
}) {
  return (
    <AiCodeBlock
      code={code}
      language="typescript"
      isStreaming={isStreaming}
      showCopy
      showLineNumbers
    />
  )
}

Language detection

When language is not specified, the component attempts to detect the language from the code content. You can also pass it explicitly:

tsx
<AiCodeBlock code={generatedCode} language="python" />
<AiCodeBlock code={generatedCode} /> {/* Auto-detected */}

Code actions

The AI Code Block supports custom action buttons that appear on hover. Common actions include copy, apply to editor, and run:

Custom actions
<AiCodeBlock
  code={code}
  language="typescript"
  actions={[
    { label: "Copy", onClick: () => copyToClipboard(code) },
    { label: "Apply", onClick: () => applyToEditor(code) },
    { label: "Run", onClick: () => executeCode(code) },
  ]}
/>

Pairs with Streamdown

The AI Code Block component pairs naturally with the @streamdown/code plugin. When rendering full markdown responses, Streamdown handles code blocks automatically.