Skip to content

layercodedev/ai-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@layercode/ai-sdk

ChatTransport implementation for the Vercel AI SDK that connects to Layercode agents via WebSocket.

Installation

npm install @layercode/ai-sdk ai

Usage

import { 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>
  );
}

Configuration

LayercodeTransportOptions

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

LayercodeStatus

The connection status can be one of:

  • "disconnected" - Not connected
  • "connecting" - Connection in progress
  • "connected" - Connected and ready
  • "error" - Connection error occurred

Server-side Authorization Endpoint

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);
}

Methods

disconnect()

Manually disconnect from the WebSocket.

transport.disconnect();

getConversationId()

Get the current conversation ID.

const conversationId = transport.getConversationId();

getStatus()

Get the current connection status.

const status = transport.getStatus();

reconnectToStream()

Attempt to reconnect to an interrupted stream.

const stream = await transport.reconnectToStream();

License

MIT

About

Some helpers for working with Layercode and ai sdk

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors