Key Concepts

Core concepts for understanding the Sunny Agents SDK
View as Markdown

Understanding these core concepts will help you build effective healthcare concierge experiences with the Sunny Agents SDK. Whether you’re building provider search, appointment booking, or health information tools, these concepts form the foundation of your application.

Environments

The SDK connects to different endpoints depending on your environment:

EnvironmentWebSocket (Chat API)Sunny Central (Partner Portal)
Stagingwss://chat.api.sunnyhealthai-staging.complatform.sunnyhealthai-staging.com
Productionwss://chat.api.sunnyhealthai.complatform.sunnyhealthai.com

The default websocketUrl is the staging URL. Override it for production via the websocketUrl option in createSunnyChat. Use the same environment for Sunny Central and the WebSocket URL (staging credentials with staging chat, production with production).

Conversations

A conversation is a collection of messages between a patient (or healthcare user) and the AI concierge. Each conversation has:

  • ID: A unique identifier (UUID)
  • Title: Optional human-readable title (can be auto-generated)
  • Messages: Array of messages in chronological order
  • Quick Responses: Optional suggested responses for the user

When authenticated via createSunnyChat, conversations are automatically persisted on the server.

1interface ConversationState {
2 id: string;
3 title?: string | null;
4 messages: SunnyAgentMessage[];
5 quickResponses?: string[];
6}

Messages

A message represents a single exchange in a conversation. Messages have:

  • ID: Unique identifier
  • Role: 'user', 'assistant', or 'system'
  • Text: The message content
  • Created At: Timestamp
  • Is Streaming: Whether the message is currently being streamed
  • Output Items: Rich content items (artifacts, approval requests, etc.)
  • Feedback: Optional user feedback (positive/negative)
1interface SunnyAgentMessage {
2 id: string;
3 role: 'user' | 'assistant' | 'system';
4 text: string;
5 createdAt: string;
6 isStreaming?: boolean;
7 outputItems?: SunnyAgentMessageItem[];
8 feedback?: boolean | null;
9}

Message Roles

  • User: Messages sent by the user
  • Assistant: Messages generated by the AI
  • System: System-level messages (rarely used)

Artifacts

Artifacts are rich content objects delivered inline in message text via the WebSocket. Common examples include:

  • Doctor Profiles: Healthcare provider information with NPI, specialty, ratings, etc.
  • Structured Data: Custom data objects specific to your use case

Artifacts are delivered inline in message text via the WebSocket. The backend expands artifact tags JIT during streaming; clients receive the full artifact JSON (item_content, item_type) embedded in message text—no separate fetch required.

Authentication

The SDK supports two authentication modes, both configured through createSunnyChat:

Token Exchange

For applications with custom authentication providers. Your app provides an ID token and the SDK exchanges it for an access token:

  1. Your app provides an ID token via idTokenProvider
  2. SDK exchanges it for an access token
  3. Access token is used for WebSocket authentication
  4. Token is automatically refreshed when expired
1const chat = createSunnyChat({
2 container: document.getElementById("chat"),
3 partnerIdentifier: "acme-health",
4 publicKey: "pk-sunnyagents_abc_xyz",
5 authType: "tokenExchange",
6 idTokenProvider: async () => localStorage.getItem("id_token"),
7});

Passwordless

Email or SMS-based authentication without passwords. The SDK renders a verification UI in the chat:

1const chat = createSunnyChat({
2 container: document.getElementById("chat"),
3 partnerIdentifier: "acme-health",
4 publicKey: "pk-sunnyagents_abc_xyz",
5 authType: "passwordless",
6});

Connection Lifecycle

The SDK manages WebSocket connections automatically:

  1. Config fetch: createSunnyChat calls GET /sdk/config to retrieve auth settings
  2. Auth activation: SDK activates the chosen auth mode (token exchange or passwordless)
  3. Connection: WebSocket connects when the user sends their first message
  4. Authentication: SDK sends auth.upgrade message with credentials
  5. Messaging: Send/receive messages in real-time
  6. Reconnection: Automatically reconnect on failure
  7. Cleanup: Close connection when chat.destroy() is called

Events

The SDK uses an event-driven architecture. Subscribe to events via chat.client to update your UI:

  • snapshot: Emitted when state changes
  • conversationCreated: New conversation created
  • messagesUpdated: Messages updated
  • streamingDelta: Text streaming in real-time
  • streamingDone: Streaming completed
  • quickResponses: Quick response suggestions available
1const chat = createSunnyChat({
2 container: document.getElementById("chat"),
3 partnerIdentifier: "acme-health",
4 publicKey: "pk-sunnyagents_abc_xyz",
5 authType: "passwordless",
6});
7
8chat.client.on("snapshot", (snapshot) => {
9 // Update UI with latest state
10});
11
12chat.client.on("streamingDelta", ({ conversationId, messageId, text }) => {
13 // Update UI with streaming text
14});

MCP Approvals

MCP (Model Context Protocol) Approvals allow users to approve or reject tool execution requests. When the AI needs to execute a tool, it sends an approval request:

1await chat.client.sendMcpApproval(
2 conversationId,
3 approvalRequestId,
4 true,
5 "Looks good"
6);
7
8await chat.client.sendMcpApproval(
9 conversationId,
10 approvalRequestId,
11 false,
12 "Not needed"
13);

The approvalRequestId is the id field of the mcp_approval_request output item in the message’s outputItems array.

File Attachments

Send files as base64-encoded attachments:

1await chat.client.sendMessage("Analyze this image", {
2 files: [
3 {
4 filename: "image.png",
5 content: "base64-encoded-content",
6 },
7 ],
8});

State Management

The SDK maintains state internally. Access it via chat.client:

1const snapshot = chat.client.getSnapshot();
2// {
3// conversations: ConversationState[],
4// activeConversationId: string | null
5// }

State updates trigger events, allowing you to keep your UI in sync.

Learn more