Documentation Index
Fetch the complete documentation index at: https://docs.plazbot.com/llms.txt
Use this file to discover all available pages before exploring further.
Los hooks te permiten construir una interfaz de chat completamente personalizada. En lugar de usar <Chat /> o <ChatWidget />, puedes acceder directamente al estado de la conversacion, la informacion del agente y la sesion.
Todos los hooks deben usarse dentro de un <PlazbotProvider>.
useChat
Controla mensajes, estados de carga y errores de la conversacion.
import { useChat } from 'plazbot/react'
function MiChat() {
const {
messages,
isLoading,
error,
sendMessage,
clearMessages,
retry,
} = useChat({
onResponse: (msg) => console.log('Respuesta:', msg),
onError: (err) => console.error('Error:', err),
})
return (
<div>
{messages.map((msg) => (
<div key={msg.id}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
{isLoading && <p>Escribiendo...</p>}
{error && (
<p>
Error: {error}
<button onClick={retry}>Reintentar</button>
</p>
)}
<button onClick={() => sendMessage('Hola!')}>Enviar</button>
<button onClick={clearMessages}>Limpiar</button>
</div>
)
}
Opciones
| Opcion | Tipo | Descripcion |
|---|
onResponse | (msg: ChatMessage) => void | Callback cuando el agente responde. |
onError | (err: string) => void | Callback cuando ocurre un error. |
Retorno
| Propiedad | Tipo | Descripcion |
|---|
messages | ChatMessage[] | Todos los mensajes de la conversacion. |
isLoading | boolean | El agente esta procesando una respuesta. |
error | string | null | Ultimo mensaje de error. |
sendMessage | (content: string, file?: string) => Promise<void> | Envia un mensaje. Opcionalmente con URL de archivo. |
clearMessages | () => void | Limpia todos los mensajes. |
retry | () => Promise<void> | Reintenta el ultimo mensaje fallido. |
ChatMessage
interface ChatMessage {
id: string
role: 'user' | 'agent'
content: string
timestamp: Date
sources?: AgentSource[]
actionsExecuted?: ActionExecuted[]
file?: ChatFile
isStreaming?: boolean
error?: string
}
useAgent
Obtiene la informacion y configuracion del agente conectado.
import { useAgent } from 'plazbot/react'
function AgentInfo() {
const { agent, isLoading, error, refetch } = useAgent()
if (isLoading) return <p>Cargando agente...</p>
if (error) return <p>Error: {error}</p>
return (
<div>
<h2>{agent?.person?.name ?? agent?.name}</h2>
<p>Color: {agent?.color}</p>
<p>Zona: {agent?.zone}</p>
</div>
)
}
Retorno
| Propiedad | Tipo | Descripcion |
|---|
agent | AgentData | null | Configuracion y metadata del agente. |
isLoading | boolean | Estado de carga. |
error | string | null | Mensaje de error. |
refetch | () => void | Recarga la informacion del agente. |
Campos utiles de AgentData
| Campo | Tipo | Descripcion |
|---|
agent.name | string | Nombre del agente. |
agent.person?.name | string | Nombre de la persona/avatar del agente. |
agent.person?.role | string | Rol del agente. |
agent.color | string | Color del agente (blue, orange, green, gray, white). |
agent.zone | string | Zona (LA o EU). |
agent.iconWidget | string | Icono del widget. |
agent.instructions?.greeting | string | Saludo configurado. |
agent.examples | AgentExample[] | Preguntas sugeridas del agente. |
useSession
Genera y persiste un ID de sesion en localStorage. Cada sesion mantiene el contexto de la conversacion.
import { useSession } from 'plazbot/react'
function SessionInfo() {
const sessionId = useSession()
// sessionId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
return <p>Session: {sessionId}</p>
}
Parametros
| Parametro | Tipo | Default | Descripcion |
|---|
storageKey | string | "plazbot_session_id" | Clave de localStorage donde se guarda el ID. |
Retorno
| Tipo | Descripcion |
|---|
string | UUID v4 persistido en localStorage. Se genera una vez y se reutiliza. |
Ejemplo Completo
Un chat completamente custom usando los tres hooks:
import { Plazbot } from 'plazbot'
import {
PlazbotProvider,
useChat,
useAgent,
useSession,
PoweredBy,
} from 'plazbot/react'
import { useState } from 'react'
const sdk = new Plazbot({
workspaceId: 'YOUR_WORKSPACE_ID',
apiKey: 'YOUR_API_KEY',
zone: 'LA',
})
function CustomChat() {
const { agent, isLoading: agentLoading } = useAgent()
const sessionId = useSession()
const { messages, isLoading, error, sendMessage, clearMessages, retry } = useChat()
const [input, setInput] = useState('')
const handleSend = async () => {
if (!input.trim()) return
const text = input
setInput('')
await sendMessage(text)
}
if (agentLoading) return <p>Cargando...</p>
return (
<div>
<h2>{agent?.person?.name ?? agent?.name}</h2>
<small>Session: {sessionId.slice(0, 8)}...</small>
<button onClick={clearMessages}>Limpiar</button>
<div>
{messages.map((msg) => (
<div key={msg.id} style={{
textAlign: msg.role === 'user' ? 'right' : 'left',
marginBottom: 8,
}}>
<span style={{
display: 'inline-block',
padding: '8px 12px',
borderRadius: 6,
background: msg.role === 'user' ? '#2D84C7' : '#f3f4f6',
color: msg.role === 'user' ? '#fff' : '#111',
}}>
{msg.content}
</span>
</div>
))}
{isLoading && <p>Escribiendo...</p>}
{error && <p>Error: {error} <button onClick={retry}>Reintentar</button></p>}
</div>
<div style={{ display: 'flex', gap: 8 }}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSend()}
placeholder="Escribe aqui..."
/>
<button onClick={handleSend} disabled={isLoading}>Enviar</button>
</div>
<PoweredBy label="Powered by" brandName="Mi Empresa" href="https://miempresa.com" />
</div>
)
}
export default function App() {
return (
<PlazbotProvider sdk={sdk} agentId="YOUR_AGENT_ID">
<CustomChat />
</PlazbotProvider>
)
}