### Install Octavus JS SDKs Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/01-getting-started/02-quickstart.md Installs the necessary Octavus SDK packages for backend and frontend integration using npm. ```bash # Server SDK for backend npm install @octavus/server-sdk # React bindings for frontend npm install @octavus/react ``` -------------------------------- ### Install Octavus SDK Dependencies Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/02-nextjs-chat.md Installs the necessary Octavus server SDK and React components for your Next.js project. Ensure you have Node.js and npm/yarn installed. ```bash npm install @octavus/server-sdk @octavus/react ``` -------------------------------- ### System Prompt Integration Example (Markdown) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/04-protocol/09-skills-advanced.md This markdown snippet shows how to guide an LLM's behavior within a system prompt, specifically for QR code generation tasks. It outlines when to generate QR codes and explicitly directs the LLM to use the `qr-code` skill. ```markdown You are a helpful assistant that can generate QR codes. ## When to Generate QR Codes Generate QR codes when users want to: - Share URLs easily - Provide contact information - Share WiFi credentials - Create scannable data Use the qr-code skill for all QR code generation tasks. ``` -------------------------------- ### Install Server Dependencies Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/03-socket-chat.md Installs necessary npm packages for the server-side components, including the Octavus server SDK, SockJS, and Express, along with their TypeScript type definitions. ```bash npm install @octavus/server-sdk sockjs express npm install -D @types/sockjs @types/express ``` -------------------------------- ### Install Client Dependencies Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/03-socket-chat.md Installs necessary npm packages for the client-side components, including the Octavus React SDK and the SockJS client, along with its TypeScript type definitions. ```bash npm install @octavus/react sockjs-client npm install -D @types/sockjs-client ``` -------------------------------- ### Octavus SDK Development Setup Commands Source: https://github.com/octavus-ai/js-sdk/blob/main/README.md Provides essential commands for setting up and managing the Octavus AI JavaScript SDK during development. This includes installing dependencies, building packages, running linters, performing type checks, and formatting code. ```bash # Install dependencies pnpm install # Build all packages pnpm build # Run linting pnpm lint # Run type checking pnpm type-check # Format code pnpm format ``` -------------------------------- ### Example: QR Code Generation Protocol Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/04-protocol/05-skills.md This YAML example illustrates a complete protocol setup for QR code generation. It defines the `qr-code` skill and configures an agent to use it. The `handlers` section specifies how user messages are processed, enabling the agent to respond to requests like 'Create a QR code for octavus.ai' by utilizing the `qr-code` skill. ```yaml skills: qr-code: display: description description: Generating QR codes agent: model: anthropic/claude-sonnet-4-5 system: system skills: [qr-code] agentic: true handlers: user-message: Add message: block: add-message role: user prompt: user-message input: [USER_MESSAGE] Respond: block: next-message ``` -------------------------------- ### Skill Documentation Structure (SKILL.md) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/04-protocol/09-skills-advanced.md This Markdown snippet outlines the recommended structure for a `SKILL.md` file, used for documenting skills. It includes frontmatter for the skill's name and description, followed by a detailed explanation of 'When to Use' and a 'Quick Start' section with examples. This format helps users understand the skill's purpose and usage. ```markdown --- name: qr-code description: > Generate QR codes from text, URLs, or data. Use when the user needs to create a QR code for any purpose - sharing links, contact information, WiFi credentials, or any text data that should be scannable. --- # QR Code Generator ## When to Use Use this skill when users want to: - Share URLs easily - Provide contact information - Create scannable data ## Quick Start [Clear examples of how to use the skill] ``` -------------------------------- ### YAML Skill Description Example Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/04-protocol/05-skills.md This YAML snippet shows a well-defined skill description for a QR code generator. It includes metadata like name, description, version, license, and author, followed by a Markdown-formatted overview and quick start guide. This format is crucial for the Agent Skills standard. ```yaml --- name: qr-code description: > Generate QR codes from text, URLs, or data. Use when the user needs to create a QR code for any purpose - sharing links, contact information, WiFi credentials, or any text data that should be scannable. version: 1.0.0 license: MIT author: Octavus Team --- # QR Code Generator ## Overview This skill creates QR codes from text data using Python... ``` -------------------------------- ### Quick Start: Octavus Server SDK Integration Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/server-sdk/README.md Demonstrates a quick start for integrating the Octavus Server SDK. It shows how to initialize the client, create an agent session, attach tool handlers, trigger an event, and stream the response as an SSE stream. ```typescript import { OctavusClient, toSSEStream } from '@octavus/server-sdk'; // Initialize client const client = new OctavusClient({ baseUrl: process.env.OCTAVUS_BASE_URL!, apiKey: process.env.OCTAVUS_API_KEY, }); // Create a session const sessionId = await client.agentSessions.create(agentId, { COMPANY_NAME: 'Acme Corp', }); // Attach to session with tool handlers const session = client.agentSessions.attach(sessionId, { tools: { 'get-user': async (args) => { return await db.users.findById(args.userId); }, 'create-ticket': async (args) => { return await ticketService.create(args); }, }, }); // Trigger and stream response const events = session.trigger('user-message', { USER_MESSAGE: 'Hello!' }); return new Response(toSSEStream(events), { headers: { 'Content-Type': 'text/event-stream' }, }); ``` -------------------------------- ### Quick Start: Initialize and use OctavusChat with HTTP Transport Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/client-sdk/README.md Demonstrates the basic setup for using the OctavusChat client with an HTTP transport. It covers creating the transport, initializing the chat client, subscribing to state changes, sending a message, and cleaning up the subscription. ```typescript import { OctavusChat, createHttpTransport } from '@octavus/client-sdk'; // Create transport const transport = createHttpTransport({ triggerRequest: (triggerName, input, options) => fetch('/api/octavus', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId, triggerName, input }), signal: options?.signal, }), }); // Create chat client const chat = new OctavusChat({ transport }); // Subscribe to state changes const unsubscribe = chat.subscribe(() => { console.log('Messages:', chat.messages); console.log('Status:', chat.status); }); // Send a message await chat.send('user-message', { USER_MESSAGE: 'Hello!' }, { userMessage: { content: 'Hello!' } }); // Cleanup unsubscribe(); ``` -------------------------------- ### Chat Component Setup Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/02-nextjs-chat.md This component handles the chat interface, including message display and user input. It utilizes the `useOctavusChat` hook to manage chat state and interactions. ```APIDOC ## POST /api/trigger ### Description Sends a trigger event to the Octavus agent, typically used for user messages or custom actions. ### Method POST ### Endpoint /api/trigger ### Parameters #### Request Body - **sessionId** (string) - Required - The unique identifier for the chat session. - **triggerName** (string) - Required - The name of the trigger to activate. - **input** (object) - Required - The input data for the trigger. ### Request Example ```json { "sessionId": "your-session-id", "triggerName": "user-message", "input": { "USER_MESSAGE": "Hello, Octavus!" } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the operation. - **messages** (array) - An array of message objects representing the conversation history. #### Response Example ```json { "status": "success", "messages": [ { "id": "msg_1", "role": "user", "parts": [ { "type": "text", "text": "Hello, Octavus!" } ] } ] } ``` ``` -------------------------------- ### Define Tools in YAML and TypeScript Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/03-socket-chat.md Shows how to define tools in a `protocol.yaml` file, including descriptions and parameters. It also provides a TypeScript example for the server-side tool handler implementation, mapping tool names to asynchronous functions that process arguments and interact with a database. ```yaml # protocol.yaml tools: get-user-account: description: Fetch user details parameters: userId: type: string ``` ```typescript // Server tool handler tools: { 'get-user-account': async (args) => { const userId = args.userId as string; return await db.users.find(userId); }, } ``` -------------------------------- ### CI/CD Sync Example Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/cli/README.md Example script for syncing an agent definition to a staging environment in a CI/CD pipeline. It sets the API URL using an environment variable and uses JSON output for the sync command. ```bash # Deploy to staging OCTAVUS_API_URL=https://staging.octavus.ai octavus sync ./agents/support-chat --json ``` -------------------------------- ### Install Octavus Server SDK Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/02-server-sdk/01-overview.md Installs the Octavus Server SDK package using npm. This is the primary package for backend integration. ```bash npm install @octavus/server-sdk ``` -------------------------------- ### Install @octavus/docs Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/README.md Installs the @octavus/docs package using npm. This is the first step to using the documentation content in your project. ```bash npm install @octavus/docs ``` -------------------------------- ### Install Octavus Client SDK (Framework-Agnostic) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/03-client-sdk/01-overview.md Installs the `@octavus/client-sdk` package, providing framework-agnostic core functionality for integrating Octavus chat into various JavaScript environments, including Vue, Svelte, or vanilla JS. ```bash npm install @octavus/client-sdk ``` -------------------------------- ### Full Octavus AI SDK Agent Configuration Example Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/04-protocol/07-agent-config.md This comprehensive example demonstrates a complete agent configuration, including input parameters, resource definitions, available tools, skills, agent settings (model, system prompt, input, tools, skills, agentic mode, max steps, thinking), and handler definitions for user messages. ```yaml input: COMPANY_NAME: { type: string } PRODUCT_NAME: { type: string } USER_ID: { type: string, optional: true } resources: CONVERSATION_SUMMARY: type: string default: '' tools: get-user-account: description: Look up user account parameters: userId: { type: string } search-docs: description: Search help documentation parameters: query: { type: string } create-support-ticket: description: Create a support ticket parameters: summary: { type: string } priority: { type: string } # low, medium, high skills: qr-code: display: description description: Generating QR codes agent: model: anthropic/claude-sonnet-4-5 system: system input: - COMPANY_NAME - PRODUCT_NAME tools: - get-user-account - search-docs - create-support-ticket skills: [qr-code] # Octavus skills agentic: true maxSteps: 10 thinking: medium # Anthropic-specific options anthropic: tools: web-search: display: description description: Searching the web skills: pdf: type: anthropic description: Processing PDF triggers: user-message: input: USER_MESSAGE: { type: string } handlers: user-message: Add message: block: add-message role: user prompt: user-message input: [USER_MESSAGE] display: hidden Respond: block: next-message ``` -------------------------------- ### Install @octavus/cli Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/cli/README.md Installs the Octavus CLI globally using npm. This command is typically run once to set up the CLI on your system. ```bash npm install -g @octavus/cli ``` -------------------------------- ### Install Octavus CLI Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/02-server-sdk/01-overview.md Installs the Octavus CLI as a development dependency, used for agent management tasks like syncing and validation. ```bash npm install --save-dev @octavus/cli ``` -------------------------------- ### Full Example with Anthropic Tools and Skills (YAML) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/04-protocol/08-provider-options.md A comprehensive YAML configuration for an agent, including input parameters, external tools, agent settings, and Anthropic-specific tools and skills. This example illustrates how to integrate web search, code execution, PDF processing, and spreadsheet analysis. ```yaml input: COMPANY_NAME: { type: string } USER_ID: { type: string, optional: true } tools: get-user-account: description: Looking up your account parameters: userId: { type: string } agent: model: anthropic/claude-sonnet-4-5 system: system input: [COMPANY_NAME, USER_ID] tools: [get-user-account] # External tools agentic: true thinking: medium # Anthropic-specific options anthropic: # Provider tools (server-side) tools: web-search: display: description description: Searching the web code-execution: display: description description: Running code # Skills (knowledge packages) skills: pdf: type: anthropic display: description description: Processing PDF document xlsx: type: anthropic display: description description: Analyzing spreadsheet triggers: user-message: input: USER_MESSAGE: { type: string } handlers: user-message: Add message: block: add-message role: user prompt: user-message input: [USER_MESSAGE] display: hidden Respond: block: next-message ``` -------------------------------- ### Agent Directory Structure Example Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/02-server-sdk/05-cli.md Illustrates the expected directory structure for an agent definition, including required files like settings.json and protocol.yaml, and optional prompt templates. ```json { "slug": "my-agent", "name": "My Agent", "description": "A helpful assistant", "format": "interactive" } ``` -------------------------------- ### Install Octavus React SDK Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/03-client-sdk/01-overview.md Installs the `@octavus/react` package, which includes React hooks and bindings for building chat interfaces in React applications. This package also bundles the core framework-agnostic functionality. ```bash npm install @octavus/react ``` -------------------------------- ### POST /api/sessions Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/02-nextjs-chat.md Endpoint to create a new chat session with the Octavus Platform. Sessions manage conversation state. ```APIDOC ## POST /api/sessions ### Description Creates a new chat session on the Octavus Platform. Sessions are essential for maintaining conversation history and state. This endpoint should be called when a user initiates a chat. ### Method POST ### Endpoint /api/sessions ### Parameters #### Request Body - **agentId** (string) - Required - The unique identifier of the Octavus agent to use for the session. - **input** (object) - Optional - An object containing initial input variables defined in the agent's protocol. For example, `{"COMPANY_NAME": "Acme Corp", "USER_ID": "user_123"}`. ### Request Example ```json { "agentId": "agent_def456", "input": { "COMPANY_NAME": "Example Inc.", "USER_ID": "usr_789" } } ``` ### Response #### Success Response (200) - **sessionId** (string) - The unique identifier for the newly created session. #### Response Example ```json { "sessionId": "sess_ghi012" } ``` ``` -------------------------------- ### Agent Settings Structure (JSON) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/cli/README.md Example JSON structure for the `settings.json` file, which defines agent metadata such as slug, name, description, and format. ```json { "slug": "support-chat", "name": "Support Chat", "description": "Customer support agent with escalation", "format": "interactive" } ``` -------------------------------- ### Chat Page Creation Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/02-nextjs-chat.md This page component initializes a new chat session and renders the `Chat` component. It fetches a `sessionId` from the backend before rendering the chat interface. ```APIDOC ## POST /api/sessions ### Description Creates a new chat session with the Octavus agent. ### Method POST ### Endpoint /api/sessions ### Parameters #### Request Body - **agentId** (string) - Required - The ID of the Octavus agent to initiate the session with. - **input** (object) - Optional - Initial input data for the agent. ### Request Example ```json { "agentId": "your-agent-id", "input": { "COMPANY_NAME": "Acme Corp" } } ``` ### Response #### Success Response (200) - **sessionId** (string) - The unique identifier for the newly created chat session. #### Response Example ```json { "sessionId": "new-session-12345" } ``` ``` -------------------------------- ### Octavus CLI Commands Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/02-server-sdk/05-cli.md Demonstrates common Octavus CLI commands for managing agent definitions. These commands include syncing, validating, listing, and getting agent details. ```bash octavus sync ./agents/my-agent octavus validate ./agents/my-agent octavus list octavus get support-chat ``` -------------------------------- ### Agent Protocol Structure (YAML) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/cli/README.md Example YAML structure for the `protocol.yaml` file, defining agent logic, input parameters, triggers, model configuration, and handlers. ```yaml input: COMPANY_NAME: { type: string } triggers: user-message: input: USER_MESSAGE: { type: string } agent: model: anthropic/claude-sonnet-4-5 system: system input: [COMPANY_NAME] handlers: user-message: Add user message: block: add-message role: user prompt: user-message input: [USER_MESSAGE] Respond: block: next-message ``` -------------------------------- ### Get Session State (cURL) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/05-api-reference/02-sessions.md Example using cURL to retrieve session state. This demonstrates how to send a GET request to the session endpoint. ```bash curl https://octavus.ai/api/agent-sessions/:sessionId \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Upload Files for OctavusChat Messages Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/client-sdk/README.md Demonstrates the process of uploading files separately to get references that can be used in subsequent messages. It includes an example of tracking upload progress. ```typescript // Upload files separately (for progress tracking) const fileRefs = await chat.uploadFiles(fileInput.files, (index, progress) => { console.log(`File ${index}: ${progress}%`); }); // Use the references in a message await chat.send('user-message', { FILES: fileRefs }, { userMessage: { files: fileRefs } }); Note: File uploads require configuring `requestUploadUrls` in the chat options. ``` -------------------------------- ### OctavusClient Configuration Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/server-sdk/README.md Initialize the OctavusClient with your base URL and an optional API key for authenticated requests. ```APIDOC ## OctavusClient Configuration ### Description Configure the Octavus client with the base URL of the Octavus API and an optional API key for authentication. ### Method Constructor ### Endpoint N/A ### Parameters #### Request Body - **baseUrl** (string) - Required - The base URL for the Octavus API (e.g., `https://api.octavus.ai` or your self-hosted URL). - **apiKey** (string) - Optional - Your API key for authenticated requests. ### Request Example ```typescript const client = new OctavusClient({ baseUrl: 'https://api.octavus.ai', apiKey: 'your-api-key' }); ``` ### Response N/A (Client initialization) ``` -------------------------------- ### OctavusClient Initialization Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/02-server-sdk/01-overview.md Initialize the OctavusClient with your configuration, including the base URL and API key. ```APIDOC ## OctavusClient The main entry point for interacting with Octavus. ### Class Definition ```typescript interface OctavusClientConfig { baseUrl: string; // Octavus API URL apiKey?: string; // Your API key } class OctavusClient { readonly agents: AgentsApi; readonly agentSessions: AgentSessionsApi; readonly files: FilesApi; constructor(config: OctavusClientConfig); } ``` ### Basic Usage Example ```typescript import { OctavusClient } from '@octavus/server-sdk'; const client = new OctavusClient({ baseUrl: 'https://octavus.ai', apiKey: 'your-api-key', }); ``` ``` -------------------------------- ### Get Agent ID using Octavus CLI (Bash) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/01-getting-started/02-quickstart.md Demonstrates how to use the Octavus CLI to synchronize local agent definitions and retrieve the agent ID. This method is suitable for version-controlled agent definitions and CI/CD pipelines. ```bash npm install --save-dev @octavus/cli octavus sync ./agents/support-chat # Output: Agent ID: clxyz123abc456 ``` -------------------------------- ### Express Server for SSE Streaming Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/03-client-sdk/06-http-transport.md Provides an example of an Express.js server setup for handling AI agent triggers and streaming responses using Server-Sent Events (SSE). It utilizes the `@octavus/server-sdk` to manage sessions and convert events to an SSE stream. Ensure to set appropriate SSE headers for the client. ```typescript import express from 'express'; import { OctavusClient, toSSEStream } from '@octavus/server-sdk'; const app = express(); const client = new OctavusClient({ baseUrl: process.env.OCTAVUS_API_URL!, apiKey: process.env.OCTAVUS_API_KEY!, }); app.post('/api/trigger', async (req, res) => { const { sessionId, triggerName, input } = req.body; const session = client.agentSessions.attach(sessionId, { tools: { // Your tool handlers }, }); const events = session.trigger(triggerName, input); const stream = toSSEStream(events); // Set SSE headers res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); // Pipe the stream to the response const reader = stream.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) break; res.write(value); } } finally { reader.releaseLock(); res.end(); } }); ``` -------------------------------- ### Initialize OctavusClient and List Agents (TypeScript) Source: https://context7.com/octavus-ai/js-sdk/llms.txt Demonstrates how to initialize the OctavusClient for server-side integration and list available agents. Requires an API key and base URL for the Octavus platform. ```typescript import { OctavusClient } from '@octavus/server-sdk'; // Initialize the client const client = new OctavusClient({ baseUrl: 'https://octavus.ai', apiKey: process.env.OCTAVUS_API_KEY, }); // List all agents in the project const agents = await client.agents.list(); console.log('Available agents:', agents.map(a => a.settings.slug)); // Get a specific agent by ID const agent = await client.agents.get('agent_123'); console.log('Agent name:', agent.settings.name); ``` -------------------------------- ### Create SockJS Socket Handler (Server-Side) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/03-socket-chat.md Defines a function to create a SockJS connection handler. This handler manages incoming data, processes messages, interacts with the Octavus agent sessions, and sends events back to the client. It supports starting, stopping, and triggering agent sessions with custom tools. ```typescript // server/octavus/socket-handler.ts import type { Connection } from 'sockjs'; import { OctavusClient, type AgentSession } from '@octavus/server-sdk'; const octavus = new OctavusClient({ baseUrl: process.env.OCTAVUS_API_URL!, apiKey: process.env.OCTAVUS_API_KEY!, }); const AGENT_ID = process.env.OCTAVUS_AGENT_ID!; export function createSocketHandler() { return (conn: Connection) => { let session: AgentSession | null = null; let abortController: AbortController | null = null; conn.on('data', (rawData: string) => { void handleMessage(rawData); }); async function handleMessage(rawData: string) { const msg = JSON.parse(rawData); // Handle stop request if (msg.type === 'stop') { abortController?.abort(); return; } // Handle trigger if (msg.type === 'trigger') { // Create session lazily on first trigger if (!session) { const sessionId = await octavus.agentSessions.create(AGENT_ID, { // Initial input variables from your protocol COMPANY_NAME: 'Acme Corp', }); session = octavus.agentSessions.attach(sessionId, { tools: { 'get-user-account': async () => { // Fetch from your database return { name: 'Demo User', plan: 'pro' }; }, 'create-support-ticket': async () => { return { ticketId: 'TKT-123', estimatedResponse: '24h' }; }, }, }); } abortController = new AbortController(); // trigger() returns parsed events — iterate directly const events = session.trigger(msg.triggerName, msg.input); try { for await (const event of events) { if (abortController.signal.aborted) break; conn.write(JSON.stringify(event)); } } catch { // Handle errors } } } conn.on('close', () => { abortController?.abort(); }); }; } ``` -------------------------------- ### Client: Configure File Uploads (React/TypeScript) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/03-client-sdk/08-file-uploads.md This React component example shows how to configure the Octavus chat hook on the client-side to handle file uploads. It involves creating an HTTP transport and defining a `requestUploadUrls` callback function that communicates with your backend API. This setup allows the SDK to manage the file upload process. ```typescript import { useMemo, useCallback } from 'react'; import { useOctavusChat, createHttpTransport } from '@octavus/react'; function Chat({ sessionId }: { sessionId: string }) { const transport = useMemo( () => createHttpTransport({ triggerRequest: (triggerName, input) => fetch('/api/trigger', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId, triggerName, input }), }), }), [sessionId], ); // Request upload URLs from your backend const requestUploadUrls = useCallback( async (files: { filename: string; mediaType: string; size: number }[]) => { const response = await fetch('/api/upload-urls', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId, files }), }); return response.json(); }, [sessionId], ); const { messages, status, send, uploadFiles } = useOctavusChat({ transport, requestUploadUrls, }); // ... } ``` -------------------------------- ### CLI: List and Get Agents Source: https://context7.com/octavus-ai/js-sdk/llms.txt Commands `octavus list` and `octavus get` are used for managing agents. `list` displays all agents in the project, while `get` retrieves details for a specific agent by its slug. Both commands support JSON output. ```bash # List all agents octavus list # Example output # Agents in project: # support-bot agent_abc123 # sales-assistant agent_def456 # onboarding-flow agent_ghi789 # Get agent details by slug octavus get support-bot # Example output # Agent: support-bot # ID: agent_abc123 # Name: Customer Support Bot # Description: Handles customer inquiries and support tickets # Triggers: user-message, escalate, close-ticket # Tools: get-user, create-ticket, search-kb # JSON output octavus list --json # { "agents": [{ "slug": "support-bot", "id": "agent_abc123", ... }] } octavus get support-bot --json # { "slug": "support-bot", "id": "agent_abc123", "settings": { ... } } ``` -------------------------------- ### YAML Skill Description Best Practice Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/04-protocol/05-skills.md This YAML example illustrates a best practice for skill descriptions within a configuration. It contrasts a clear, purpose-driven description for a 'qr-code' skill with a vague description for a 'utility' skill, emphasizing the importance of descriptive language for agent understanding. ```yaml skills: # Good - clear purpose qr-code: description: Generating QR codes for URLs, contact info, or any text data # Avoid - vague utility: description: Does stuff ``` -------------------------------- ### OctavusClient Configuration Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/server-sdk/README.md Initializes the OctavusClient with configuration options. Requires baseUrl and optionally accepts an apiKey for authenticated requests. ```typescript const client = new OctavusClient({ baseUrl: 'https://api.octavus.ai', // Or your self-hosted URL apiKey: 'your-api-key', // Optional: for authenticated requests }); ``` -------------------------------- ### Install @octavus/core Package Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/core/README.md Installs the @octavus/core package using npm. This package contains shared types and utilities for Octavus SDK communication. ```bash npm install @octavus/core ``` -------------------------------- ### Model Selection Examples Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/04-protocol/07-agent-config.md Demonstrates how to specify different LLM models from various providers (Anthropic, Google, OpenAI) using the 'provider/model-id' format. Ensure the chosen model is supported by the respective provider's SDK. ```yaml # Anthropic Claude 4.5 agent: model: anthropic/claude-sonnet-4-5 # Google Gemini 3 agent: model: google/gemini-3-flash # OpenAI GPT-5 agent: model: openai/gpt-5 # OpenAI reasoning models agent: model: openai/o3-mini ``` -------------------------------- ### CI/CD Validation Example Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/cli/README.md Example script for validating an agent definition in a CI/CD pipeline. It checks the exit code of the `octavus validate` command and fails the pipeline if validation errors occur. ```bash # Validate in CI octavus validate ./agents/support-chat --json if [ $? -ne 0 ]; then echo "Validation failed" exit 1 fi ``` -------------------------------- ### Octavus Stream Event Types (TypeScript) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/02-server-sdk/04-streaming.md This code defines the structure of various events emitted during an Octavus AI stream. It includes lifecycle events (start, finish, error), block events (start, end), text events (start, delta, end), reasoning events, tool interaction events, and resource updates. These types are crucial for handling real-time updates from the SDK. ```typescript // Stream started { type: 'start', messageId: '...' } // Stream completed { type: 'finish', finishReason: 'stop' } // Possible finish reasons: // - 'stop': Normal completion // - 'tool-calls': Waiting for tool execution (handled by SDK) // - 'length': Max tokens reached // - 'content-filter': Content filtered // - 'error': Error occurred // - 'other': Other reason // Error event (see Error Handling docs for full structure) { type: 'error', errorType: 'internal_error', message: 'Something went wrong', source: 'platform', retryable: false } // Block started { type: 'block-start', blockId: '...', blockName: 'Respond to user', blockType: 'next-message', display: 'stream', thread: 'main' } // Block completed { type: 'block-end', blockId: '...', summary: 'Generated response' } // Text generation started { type: 'text-start', id: '...' } // Incremental text (most common event) { type: 'text-delta', id: '...', delta: 'Hello' } { type: 'text-delta', id: '...', delta: '!' } { type: 'text-delta', id: '...', delta: ' How' } { type: 'text-delta', id: '...', delta: ' can' } { type: 'text-delta', id: '...', delta: ' I' } { type: 'text-delta', id: '...', delta: ' help?' } // Text generation ended { type: 'text-end', id: '...' } // Reasoning started { type: 'reasoning-start', id: '...' } // Reasoning content { type: 'reasoning-delta', id: '...', delta: 'Let me analyze this request...' } // Reasoning ended { type: 'reasoning-end', id: '...' } // Tool input started { type: 'tool-input-start', toolCallId: '...', toolName: 'get-user-account', title: 'Looking up account' } // Tool input/arguments streaming { type: 'tool-input-delta', toolCallId: '...', inputTextDelta: '{"userId":"user-123"}' } // Tool input streaming ended { type: 'tool-input-end', toolCallId: '...' } // Tool input is complete and available { type: 'tool-input-available', toolCallId: '...', toolName: 'get-user-account', input: { userId: 'user-123' } } // Tool output available (success) { type: 'tool-output-available', toolCallId: '...', output: { name: 'Demo User', email: '...' } } // Tool output error (failure) { type: 'tool-output-error', toolCallId: '...', error: 'User not found' } // Resource updates { type: 'resource-update', name: 'CONVERSATION_SUMMARY', value: 'User asked about...' } ``` -------------------------------- ### Map YAML Protocol Tool Definition Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/02-nextjs-chat.md Defines a 'get-user-account' tool within an agent's `protocol.yaml` file. This YAML structure outlines the tool's description and its required parameters, such as `userId`, specifying its type and description. ```yaml # In your agent's protocol.yaml tools: get-user-account: description: Fetch user account details parameters: userId: type: string description: The user ID to look up ``` -------------------------------- ### Get Agent (API Request) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/05-api-reference/03-agents.md Retrieves a specific agent by its unique ID. This is a GET request to the /api/agents/:id endpoint. The response includes the agent's settings, protocol, and prompts. ```bash curl https://octavus.ai/api/agents/:agentId \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Initialize Octavus Client Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/02-server-sdk/01-overview.md Initializes the OctavusClient with configuration, including the base URL of the Octavus API and an API key for authentication. ```typescript import { OctavusClient } from '@octavus/server-sdk'; const client = new OctavusClient({ baseUrl: 'https://octavus.ai', apiKey: 'your-api-key', }); ``` -------------------------------- ### Initialize Octavus Client (TypeScript) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/01-getting-started/02-quickstart.md Initializes the Octavus client instance in the backend using environment variables for API URL and key. This client is used to interact with Octavus services. ```typescript // lib/octavus.ts import { OctavusClient } from '@octavus/server-sdk'; export const octavus = new OctavusClient({ baseUrl: process.env.OCTAVUS_API_URL!, apiKey: process.env.OCTAVUS_API_KEY!, }); ``` -------------------------------- ### Get Documentation Content with @octavus/docs Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/README.md Demonstrates how to retrieve documentation content using functions from the @octavus/docs package. It shows how to get all sections, all document slugs for static generation, and a specific document by its slug. These functions are essential for dynamically displaying documentation. ```typescript import { getDocBySlug, getDocSlugs, getDocSections } from '@octavus/docs'; // Get all sections with their docs const sections = getDocSections(); // [{ slug: 'getting-started', title: 'Getting Started', docs: [...] }, ...] // Get all doc slugs (for static generation) const slugs = getDocSlugs(); // ['getting-started/introduction', 'getting-started/quickstart', ...] // Get a specific doc by slug const doc = getDocBySlug('getting-started/introduction'); // { slug, section, title, description, content, excerpt } ``` -------------------------------- ### Sandbox Initialization Trigger Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/04-protocol/09-skills-advanced.md This YAML configuration illustrates lazy initialization for sandboxes in an agent's skill configuration. The sandbox for the 'qr-code' skill is only created when the LLM first calls this skill tool, optimizing resource usage and startup time. This ensures no cost if skills are unused and provides a fast startup. ```yaml agent: skills: [qr-code] # Sandbox created on first use ``` -------------------------------- ### Initialize Octavus Client (Server-Side) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/03-socket-chat.md Initializes the Octavus client on the server using environment variables for configuration. This client is used to interact with the Octavus platform for AI agent functionalities. ```typescript // server/octavus/client.ts import { OctavusClient } from '@octavus/server-sdk'; export const octavus = new OctavusClient({ baseUrl: process.env.OCTAVUS_API_URL!, apiKey: process.env.OCTAVUS_API_KEY!, }); export const AGENT_ID = process.env.OCTAVUS_AGENT_ID!; ``` -------------------------------- ### Send Custom Socket Events (Server - TypeScript) Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/03-socket-chat.md Illustrates how to send custom events from the server to the client using the socket connection. The example shows sending a 'typing-indicator' event by stringifying a JSON object containing the event type and relevant data (`isTyping: true`). This enables real-time feedback mechanisms. ```typescript // Server - send custom events conn.write( JSON.stringify({ type: 'typing-indicator', isTyping: true, }), ); ``` -------------------------------- ### Configure Octavus Environment Variables Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/03-socket-chat.md Sets up environment variables for the Octavus client, including the API URL, API key, and agent ID, which are essential for authenticating and connecting to the Octavus platform. ```env # .env OCTAVUS_API_URL=https://octavus.ai OCTAVUS_API_KEY=your-api-key OCTAVUS_AGENT_ID=your-agent-id ``` -------------------------------- ### Set Up Express Server with SockJS Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/docs/content/06-examples/03-socket-chat.md Configures an Express server to handle HTTP requests and integrates SockJS for WebSocket-like communication. It sets up the SockJS server, attaches the custom socket handler, and serves the frontend application. ```typescript // server/index.ts import express from 'express'; import http from 'http'; import sockjs from 'sockjs'; import { createSocketHandler } from './octavus/socket-handler'; const app = express(); const server = http.createServer(app); // Create SockJS server const sockServer = sockjs.createServer({ prefix: '/octavus', log: () => {}, // Silence logs }); // Attach handler sockServer.on('connection', createSocketHandler()); sockServer.installHandlers(server); // Serve your frontend app.use(express.static('dist/client')); server.listen(3001, () => { console.log('Server running on http://localhost:3001'); }); ``` -------------------------------- ### Files API Source: https://github.com/octavus-ai/js-sdk/blob/main/packages/server-sdk/README.md Manage file uploads, including getting presigned URLs and uploading files. ```APIDOC ## Files API ### Description Handles file uploads by providing presigned URLs for direct uploads to cloud storage (e.g., S3). It also allows for the use of uploaded file URLs in trigger inputs. ### Methods #### Get Upload URLs - **Method**: `client.files.getUploadUrls(sessionId, files)` - **Description**: Requests presigned URLs for uploading files associated with a session. - **Parameters**: - `sessionId` (string): The ID of the session. - `files` (Array): An array of file objects, each with `filename`, `mediaType`, and `size`. - `filename` (string) - Required - The name of the file. - `mediaType` (string) - Required - The MIME type of the file (e.g., `image/jpeg`). - `size` (number) - Required - The size of the file in bytes. - **Returns**: `Promise<{ files: Array<{ id: string, uploadUrl: string, downloadUrl: string }> }>` - An object containing file IDs and their respective upload/download URLs. ### Uploading Files After obtaining the `uploadUrl` from `getUploadUrls`: ```typescript // Assuming 'files' is the response from getUploadUrls // Assuming 'imageFile' is your file data (e.g., Blob, Buffer) await fetch(files[0].uploadUrl, { method: 'PUT', body: imageFile, headers: { 'Content-Type': 'image/jpeg' } // Use the correct mediaType }); ``` ### Using Files in Triggers ```typescript // Assuming 'session' is an attached AgentSession // Assuming 'files' is the response from getUploadUrls await session.trigger('user-message', { FILES: [ { id: files[0].id, url: files[0].downloadUrl, mediaType: 'image/jpeg' } ] }); ``` ```