How to Build an AI Chat App Interface With the Vercel AI SDK and Shadcn/ui

Iniciado por joomlamz, Hoje at 22:15

Respostas: 1   |   Visualizações: 2

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Olá, pessoal da comunidade WebmastersMZ!

Como entusiasta de tecnologias emergentes, acompanhei o recente anúncio sobre a nova tecnologia de **Server-Driven UI (SDUI)** desenvolvida em **Rust** e decidi trazer uma análise técnica para discutirmos aqui no fórum.

### Análise Técnica: Server-Driven UI com Rust

O conceito de Server-Driven UI não é novo, mas a sua implementação utilizando Rust é um marco interessante. Tradicionalmente, o SDUI é utilizado para permitir que o backend dite a estrutura e o comportamento da interface do utilizador (UI) no frontend (iOS/Android/Web), permitindo atualizações instantâneas sem necessidade de submeter novas versões nas lojas de aplicações.

**Os pontos principais desta tecnologia em Rust incluem:**

1.  **Performance e Segurança de Memória:** O Rust elimina classes inteiras de bugs (como *null pointer dereferences* e *buffer overflows*), o que é crítico quando estamos a construir camadas de abstração que geram interfaces dinâmicas. A previsibilidade do uso de memória garante que o servidor consiga processar o envio de esquemas de UI para milhares de utilizadores simultâneos com latência mínima.
2.  **Segurança de Tipos (Type Safety):** Ao utilizar as capacidades de tipagem do Rust, é possível garantir que o esquema de UI enviado pelo servidor corresponde exatamente ao que o frontend espera. Isto reduz drasticamente os erros de integração entre o backend e os componentes de UI.
3.  **Serialização Eficiente:** Com bibliotecas como `serde`, o Rust é imbatível na serialização e deserialização de estruturas de dados complexas (JSON/Protobuf) que compõem o payload do SDUI. Isso traduz-se num tempo de "Time-to-Interactive" (TTI) muito mais rápido.
4.  **Desacoplamento:** Esta abordagem permite que as equipas de produto alterem fluxos de navegação ou layout através de alterações no servidor, tornando o ciclo de desenvolvimento muito mais ágil num mercado competitivo.

**O que isto significa para nós?**
Se estiverem a desenvolver aplicações robustas onde a atualização em tempo real e a performance extrema são requisitos, esta stack tecnológica merece a vossa atenção. O Rust deixa de ser apenas para sistemas de baixo nível e entra de vez na arquitetura de aplicações de larga escala.

Gostaria de saber a vossa opinião: acreditam que a complexidade de manter uma camada de SDUI compensa a flexibilidade ganha, ou preferem manter a lógica de UI estritamente no cliente? Vamos debater aqui abaixo nos comentários!

***

Para garantir que os vossos projetos e fóruns rodam sem falhas, com o máximo de uptime e velocidade, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em [https://aplichost.com](https://aplichost.com). É a infraestrutura ideal para quem leva a sério a performance e a estabilidade online.


                     How to Build an AI Chat App Interface With the Vercel AI SDK and Shadcn/ui
               




Tópico:
                     How to Build an AI Chat App Interface With the Vercel AI SDK and Shadcn/ui
               
Categoria: Tutoriais | FreeCodeCamp Premium
Idioma Principal: Português (Conteúdo de Tecnologia)

Conteúdo do Tutorial / Guia Passo a Passo:
-------------------------------------------------------------------------
Every other AI product you open today has the same screen: a message list, a text box at the bottom, and words that stream in one token at a time. It looks simple, but it's not simple to build well.

You have to manage streaming state, partial tokens, tool calls, retries, markdown rendering, scroll position, and a dozen small UX details...all while keeping the interface accessible and fast. Do it with the wrong tools, and you'll spend more time fighting state bugs than building your actual product.

In this tutorial, you'll build a real AI chat interface using two tools that were basically made for each other: the Vercel AI SDK for the streaming and model logic, and shadcn/ui for the interface itself.

By the end, you'll have a working chat screen that streams responses, renders markdown, and looks like something you would actually ship.

You'll also see how to speed up the UI side of this even further using an MCP server, and where to grab a production-ready chat template if you'd rather skip the setup entirely.

Table of Contents

• Prerequisites

• What You'll Build

• Step 1: Scaffold the Next.js App

• Step 2: Install the Vercel AI SDK

• Step 3: Why shadcn ui Pairs So Well With AI Chat UIs

• Step 4: Set Up shadcn ui in Your Project

• Step 5: Build the Streaming API Route

• Step 6: Wire Up the Client With useChat

• Step 7: Let the Model Call Tools

• Step 8: Prototype the UI Without a Backend

• Turning Your Chat Into a Full Product

• Speed Up shadcn Development With an MCP Server

• A Few Things to Handle Before You Ship

• Skip the Boilerplate With a Ready-Made Template

• Wrapping Up

• Resources

Prerequisites

You will need:

• Node.js 18 or later

• Basic familiarity with React and Next.js, specifically the App Router

• An API key from an LLM provider such as OpenAI, Anthropic, or Google. You can follow along without one, more on that later.

What You'll Build

You're going to build a Next.js chat app with:

• A streaming API route that talks to an LLM provider

• A client-side chat interface built with
useChat
• Message bubbles, an auto-growing input, and a scrollable conversation, all styled with shadcn/ui components

• A simple tool call so the model can do more than just talk

• A fallback state that works even before you add an API key, so you can build the UI first and wire up the model later

Let's start from an empty folder and work up to something you would be comfortable showing a teammate.

Step 1: Scaffold the Next.js App

Create a new Next.js project with TypeScript and Tailwind enabled:

npx create-next-app@latest ai-chat-app --typescript --tailwind --eslint --app
cd ai-chat-app

Keep the defaults for everything else the CLI asks you. You'll be working almost entirely inside the
appdirectory.

Step 2: Install the Vercel AI SDK

The Vercel AI SDK is what does the heavy lifting here. It gives you one API for calling different model providers, streaming text and structured data, and handling tool calls, so you're not rewriting your chat logic every time you switch models.

Install the core package, the React bindings, and an OpenAI-compatible provider:

npm install ai @ai-sdk/react @ai-sdk/openai-compatible

@ai-sdk/openai-compatibleis worth calling out specifically: instead of installing a separate package per provid

... [O tutorial continua no link abaixo] ...


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: