ChatTransport implementation for the Vercel AI SDK that connects to Layercode agents via WebSocket.
npm install @layercode/ai-sdk aiimport { useChat } from "ai/react";
import { LayercodeTransport } from "@layercode/ai-sdk";
const transport = new LayercodeTransport({
agentId: "your-agent-id",
authorizeSessionEndpoint: "/api/layercode/authorize",
onStatusChange: (status) => {
console.log("Connection status:", status);
},
onConnect: ({ conversationId }) => {
console.log("Connected with conversation:", conversationId);
},
onError: (error) => {
console.error("Transport error:", error);
},
});
function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
transport,
});
return (
<div>
{messages.map((message) => (
<div key={message.id}>
<strong>{message.role}:</strong> {message.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input value={input} onChange={handleInputChange} />
<button type="submit">Send</button>
</form>
</div>
);
}| Option | Type | Required | Description |
|---|---|---|---|
agentId |
string |
Yes | Your Layercode agent ID |
authorizeSessionEndpoint |
string |
Yes | Endpoint to authorize WebSocket sessions |
metadata |
Record<string, unknown> |
No | Custom metadata to send with the session |
conversationId |
string | null |
No | Existing conversation ID to resume |
onStatusChange |
(status: LayercodeStatus) => void |
No | Callback when connection status changes |
onConnect |
(info: { conversationId: string | null }) => void |
No | Callback when connected |
onDisconnect |
() => void |
No | Callback when disconnected |
onError |
(error: Error) => void |
No | Callback when an error occurs |
The connection status can be one of:
"disconnected"- Not connected"connecting"- Connection in progress"connected"- Connected and ready"error"- Connection error occurred
You need to create an API endpoint that authorizes WebSocket sessions. Example using Next.js:
// app/api/layercode/authorize/route.ts
import { NextResponse } from "next/server";
export async function POST(request: Request) {
const body = await request.json();
const response = await fetch(
"https://api.layercode.com/v1/agents/web/authorize_session",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.LAYERCODE_API_KEY}`,
},
body: JSON.stringify({
agent_id: body.agent_id,
metadata: body.metadata,
conversation_id: body.conversation_id,
}),
}
);
const data = await response.json();
return NextResponse.json(data);
}Manually disconnect from the WebSocket.
transport.disconnect();Get the current conversation ID.
const conversationId = transport.getConversationId();Get the current connection status.
const status = transport.getStatus();Attempt to reconnect to an interrupted stream.
const stream = await transport.reconnectToStream();MIT