# AI SDK Frontend Integration
## 1. Overview
This guide covers frontend integration with the Vercel AI SDK using `@ai-sdk/react`. Key topics include:
- Using `@ai-sdk/react` for React integration
- Streaming chat with the `useChat` hook
- Tool call handling with proper format detection
## 2. Basic Chat with useChat
The `useChat` hook provides a simple interface for chat functionality:
```typescript
"use client";
import { useChat } from "@ai-sdk/react";
export function ChatPanel() {
const { messages, input, handleInputChange, handleSubmit, status } = useChat({
api: "/api/chat",
});
return (
{messages.map((message) => (
{message.role}: {message.content}
))}
);
}
```
## 3. Custom Transport with oRPC
When using oRPC instead of standard fetch:
```typescript
import { useChat } from "@ai-sdk/react";
import { eventIteratorToStream } from "@orpc/client";
import { orpcClient } from "@/lib/orpc-client";
export function ChatPanel({ sessionId }: { sessionId: string }) {
const { messages, sendMessage, status } = useChat({
id: sessionId,
transport: {
async sendMessages(options) {
return eventIteratorToStream(
await orpcClient.chat.send(
{
sessionId,
messages: options.messages,
},
{ signal: options.abortSignal }
)
);
},
reconnectToStream() {
throw new Error("Reconnect not supported");
},
},
});
// ... rest of component
}
```
## 4. Tool Calls Handling
**CRITICAL**: Tool calls have TWO different formats that must both be handled:
### Format 1: Real-time Streaming
During streaming, tool results appear as:
```typescript
{
type: "tool-createTask", // tool-{toolName}
toolCallId: "call_abc123",
state: "output-available",
input: { title: "...", priority: "high" },
output: { success: true, taskId: "task_xyz" } // Direct object
}
```
### Format 2: History Restore
When loading from history/database:
```typescript
{
type: "tool-result",
toolName: "createTask",
toolCallId: "call_abc123",
output: {
type: "json",
value: { success: true, taskId: "task_xyz" } // Nested in value
}
}
```
### Unified Handling Pattern
```typescript
import { useChat } from "@ai-sdk/react";
import { useEffect, useState, useRef } from "react";
export function AssistantPanel({ sessionId }: { sessionId: string }) {
const [createdItems, setCreatedItems] = useState