SDK AI Chat New
The useChat hook connects your frontend to DYPAI AI agent endpoints with streaming, tool call visibility, chat history, and session management.
useChat understands DYPAI's Vercel AI SDK UI Message Stream responses, including streamed text deltas, tool calls, tool results, and mid-stream errors. It also keeps a legacy fallback for older engines that still emit plain text streams.
Where agent endpoints come from
An "AI agent endpoint" is just an endpoint that runs the agent workflow node. You create it in the API Builder. The model behind it runs as DYPAI Managed (no API key, billed as AI Credits, plan-gated under the org AI Models page) or via BYOK credentials. See AI Agents for the agent node and Managed AI for the billing model.
Quick Start
import { useChat } from '@dypai-ai/client-sdk/react'
function ChatBot() {
const { messages, sendMessage, input, setInput, isLoading, status } = useChat('my_agent_endpoint')
return (
<div>
{messages.map(msg => (
<div key={msg.id}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
<input value={input} onChange={e => setInput(e.target.value)} />
<button onClick={() => sendMessage()} disabled={isLoading}>
Send
</button>
</div>
)
}
useChat Options
| Parameter | Type | Description |
|---|---|---|
endpointrequired | string | Name of your AI agent endpoint (created in API Builder) |
id | string | Chat session ID. Auto-generated if not provided |
initialMessages | ChatMessage[] | Messages to show before loading history |
loadHistory | boolean= true | Load previous messages from server on mount |
body | object | Extra fields sent with every message (e.g. session_id) |
onFinish | function | Called when the assistant finishes responding |
onError | function | Called on error |
onToolCall | function | Called when a tool call is received |
useChat Return
| Parameter | Type | Description |
|---|---|---|
messages | ChatMessage[] | All messages in the conversation |
status | string | Current status: ready, submitted, streaming, error |
input | string | Current input value (controlled) |
setInput | function | Set the input value |
sendMessage(text?) | async | Send a message. Uses input value if no text provided |
stop() | function | Stop the current streaming response |
isLoading | boolean | Whether the assistant is currently responding |
error | Error | null | Last error |
chatId | string | The session ID |
newChat() | function | Clear messages and start a new session |
Message Format
Each message has:
interface ChatMessage {
id: string
role: 'user' | 'assistant' | 'system' | 'tool'
content: string
parts?: MessagePart[] // Rich content: text, tool-calls, tool-results, images
createdAt?: Date
}
content is the accumulated assistant text. parts contains richer streamed events such as text, tool-call, and tool-result, so you can build a simple text chat or a richer UI that shows what the agent is doing.
Tool calls
When the agent calls tools (your workflow endpoints), you can see them in parts:
{messages.map(msg => (
<div key={msg.id}>
{msg.parts?.map((part, i) => {
if (part.type === 'tool-call') {
return <div key={i}>🔧 Calling {part.toolName}...</div>
}
if (part.type === 'tool-result') {
return <div key={i}>✅ {part.toolName} done</div>
}
if (part.type === 'text') {
return <span key={i}>{part.text}</span>
}
})}
</div>
))}
Resuming a Conversation
Pass an id in the options to continue an existing chat (loads its history):
const { messages, sendMessage } = useChat('my_agent_endpoint', { id: 'conv-123' })
The option is id (not sessionId). At the raw HTTP level the request body field is session_id.
Chat History
useChatList takes an options object and returns helpers to manage past conversations:
import { useChatList } from '@dypai-ai/client-sdk/react'
function ChatSidebar() {
const { chats, isLoading, deleteChat, renameChat, refetch } = useChatList({
endpointId: '<endpoint_id>',
limit: 20,
})
return (
<ul>
{chats?.map(chat => (
<li key={chat.id}>
{chat.title} ({chat.messageCount} messages)
<button onClick={() => renameChat(chat.id, 'Renamed')}>Rename</button>
<button onClick={() => deleteChat(chat.id)}>Delete</button>
</li>
))}
</ul>
)
}
| Parameter | Type | Description |
|---|---|---|
useChatList({ endpointId, limit, enabled }) | Hook | Options object — endpointId scopes the list, limit caps results, enabled toggles fetching |
chats | Chat[] | Previous conversations for the endpoint |
deleteChat(chatId) | async | Delete a conversation (the primary way to clear a chat) |
renameChat(chatId, title) | async | Rename a conversation |
refetch() | async | Reload the conversation list |
isLoading / error | state | Loading and error state |
Structured output
If the agent endpoint defines an output_schema, the structured result arrives in the message's object field (matching your schema), not content.
Helper Functions
import { generateChatId, getMessageText, getToolCalls } from '@dypai-ai/client-sdk/react'
// Generate a new chat ID
const id = generateChatId()
// Extract plain text from a message (ignores tool calls)
const text = getMessageText(message)
// Get tool calls from a message
const tools = getToolCalls(message) // [{ toolName: 'list_orders', args: {...} }]