### SKILL.md Example for QR Code Generator Source: https://octavus.ai/docs/protocol/skills-advanced This markdown file defines the metadata and usage instructions for a QR code generation skill. It includes the skill's name, a detailed description of its purpose, when to use it, and a placeholder for quick start examples, following the recommended structure for skill documentation. ```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] ``` -------------------------------- ### Install Octavus SDK Dependencies Source: https://octavus.ai/docs/examples/nextjs-chat 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://octavus.ai/docs/protocol/skills-advanced This markdown snippet shows how to guide an LLM by providing context about its capabilities, specifically for QR code generation. It outlines when to use the 'qr-code' skill. ```markdown 1 2 3You are a helpful assistant that can generate QR codes. 4 5## When to Generate QR Codes 6 7Generate QR codes when users want to: 8 9- Share URLs easily 10- Provide contact information 11- Share WiFi credentials 12- Create scannable data 13 14Use the qr-code skill for all QR code generation tasks. ``` -------------------------------- ### Install Server Dependencies with npm Source: https://octavus.ai/docs/examples/socket-chat Installs the necessary Octavus server SDK, SockJS, Express, and their corresponding TypeScript types for server-side development. ```bash npm install @octavus/server-sdk sockjs express npm install -D @types/sockjs @types/express ``` -------------------------------- ### Install Octavus SDKs (npm) Source: https://octavus.ai/docs/getting-started/quickstart Installs the necessary Octavus SDKs for backend (server-sdk) and frontend (react) integration using npm. Ensure Node.js 18+ is installed. ```bash npm install @octavus/server-sdk npm install @octavus/react ``` -------------------------------- ### Install Client Dependencies with npm Source: https://octavus.ai/docs/examples/socket-chat Installs the Octavus React SDK and SockJS client library, along with their TypeScript types, for frontend development. ```bash npm install @octavus/react sockjs-client npm install -D @types/sockjs-client ``` -------------------------------- ### QR Code Generation Example (YAML) Source: https://octavus.ai/docs/protocol/skills 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 shows how user messages are processed to trigger responses. ```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 ``` -------------------------------- ### Implement Interactive Client Tools with useOctavusChat (React/TypeScript) Source: https://octavus.ai/docs/migration/v1-to-v2 Illustrates the setup for interactive client-side tools using `useOctavusChat`. This example configures 'request-confirmation' and 'select-option' as interactive tools and shows how to render UI elements (like `ConfirmationModal`) to handle pending tools, allowing users to confirm or cancel actions. Requires '@octavus/react'. ```typescript import { useOctavusChat, createHttpTransport } from '@octavus/react'; function Chat() { const { messages, send, status, pendingClientTools } = useOctavusChat({ transport: createHttpTransport({ request: (payload, options) => fetch('/api/trigger', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId, ...payload }), signal: options?.signal, }), }), clientTools: { 'request-confirmation': 'interactive', 'select-option': 'interactive', }, }); // Render UI for pending interactive tools const confirmationTools = pendingClientTools['request-confirmation'] ?? []; return (
{/* Chat messages */} {/* Interactive tool UI */} {confirmationTools.map((tool) => ( tool.submit({ confirmed: true })} onCancel={() => tool.cancel('User declined')} /> ))}
); } ``` -------------------------------- ### Octavus Server SDK Installation Source: https://octavus.ai/docs/server-sdk/overview Instructions for installing the Octavus Server SDK and the CLI for agent management. ```APIDOC ## Installation Install the server SDK: ```bash npm install @octavus/server-sdk ``` Install the CLI as a dev dependency for agent management: ```bash npm install --save-dev @octavus/cli ``` ``` -------------------------------- ### Generate and Return Pattern Example Source: https://octavus.ai/docs/protocol/skills-advanced This YAML snippet outlines a common pattern in agentic workflows: 'Generate and Return'. It describes a user request for a QR code, the LLM's generation of the code, and the subsequent availability of the generated file for download, representing a typical output flow. ```yaml # User asks for QR code # LLM generates QR code # File automatically available for download ``` -------------------------------- ### Install Octavus Client SDK (Other Frameworks) Source: https://octavus.ai/docs/client-sdk/overview Installs the `@octavus/client-sdk` package, providing framework-agnostic core functionality for integrating Octavus AI with Vue, Svelte, vanilla JS, or custom solutions. ```bash npm install @octavus/client-sdk ``` -------------------------------- ### Basic YAML Configuration for Agent Skills Source: https://octavus.ai/docs/protocol/skills-advanced This YAML snippet illustrates a common pattern where an agent is configured to use specific skills. It shows a simple setup where the agent has access to the 'qr-code' skill, implying that the sandbox for this skill will be created upon its first use. ```yaml agent: skills: [qr-code] # Sandbox created on first use ``` -------------------------------- ### Example Session Input Variables (TypeScript) Source: https://octavus.ai/docs/examples/nextjs-chat Demonstrates how to provide input variables when creating a new session. These variables are defined in your agent's protocol. ```typescript const sessionId = await octavus.agentSessions.create(agentId, { COMPANY_NAME: 'Acme Corp', USER_ID: user.id, }); ``` -------------------------------- ### Install Octavus React SDK Source: https://octavus.ai/docs/client-sdk/overview Installs the `@octavus/react` package, which includes React hooks and bindings for Octavus AI. This is the recommended package for React applications as it bundles the core client SDK. ```bash npm install @octavus/react ``` -------------------------------- ### Install Octavus Server SDK (npm) Source: https://octavus.ai/docs/server-sdk/overview Installs the Octavus Server SDK package for Node.js using npm. This is the primary package for backend integration. ```bash npm install @octavus/server-sdk ``` -------------------------------- ### Server-Side Tool Handlers (TypeScript) Source: https://octavus.ai/docs/examples/socket-chat Shows how to define handlers for server-side tools within an agent's protocol. This example includes a handler for 'get-user-account' which interacts with a database, and notes that tools like 'get-browser-location' are handled on the client. ```typescript 1// Server tool handlers (only for server tools) 2tools: { 3 'get-user-account': async (args) => { 4 const userId = args.userId as string; 5 return await db.users.find(userId); 6 }, 7 // get-browser-location has no handler - forwarded to client 8} ``` -------------------------------- ### Full Octavus Worker Execution Example (TypeScript) Source: https://octavus.ai/docs/server-sdk/workers A comprehensive example demonstrating how to initialize the Octavus client, execute a 'research-assistant-id' worker with specific inputs and tools, and process various stream events including start, block, text delta, worker results, and errors. It also shows how to handle potential errors during execution. ```typescript import { OctavusClient, type StreamEvent } from '@octavus/server-sdk'; const client = new OctavusClient({ baseUrl: 'https://octavus.ai', apiKey: process.env.OCTAVUS_API_KEY!, }); async function runResearchWorker(topic: string) { console.log(`Researching: ${topic}\n`); const events = client.workers.execute( 'research-assistant-id', { TOPIC: topic, DEPTH: 'detailed', }, { tools: { 'web-search': async ({ query }) => { console.log(`Searching: ${query}`); return await performWebSearch(query); }, }, }, ); let output: unknown; for await (const event of events) { switch (event.type) { case 'worker-start': console.log(`Started: ${event.workerSlug}`); break; case 'block-start': console.log(`Step: ${event.blockName}`); break; case 'text-delta': process.stdout.write(event.delta); break; case 'worker-result': if (event.error) { throw new Error(event.error); } output = event.output; break; case 'error': throw new Error(event.message); } } console.log('\n\nResearch complete!'); return output; } // Run the worker const result = await runResearchWorker('AI safety best practices'); console.log('Result:', result); ``` -------------------------------- ### Local Skill Testing Command Source: https://octavus.ai/docs/protocol/skills-advanced This bash command provides an example of how to test a skill locally before deploying it. It executes a Python script (`generate.py`) with a sample data argument, allowing developers to verify functionality and catch errors early in the development cycle. ```bash # Test skill locally python scripts/generate.py --data "test" ``` -------------------------------- ### Full Octavus AI Agent Configuration Example Source: https://octavus.ai/docs/protocol/agent-config A comprehensive example demonstrating the integration of various Octavus AI configuration options, including input parameters, resources, tools, skills, agent settings (model, system, tools, skills, agentic behavior, max steps, thinking), provider-specific options, and handler definitions for triggers and message processing. ```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 ``` -------------------------------- ### Create Octavus Client Instance (TypeScript) Source: https://octavus.ai/docs/examples/socket-chat Initializes the OctavusClient using environment variables for API configuration on the server-side. ```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!; ``` -------------------------------- ### Install Octavus CLI (npm) Source: https://octavus.ai/docs/server-sdk/overview Installs the Octavus CLI as a development dependency using npm. The CLI is used for agent management tasks such as synchronization and validation. ```bash npm install --save-dev @octavus/cli ``` -------------------------------- ### Configure Octavus Environment Variables Source: https://octavus.ai/docs/examples/socket-chat Sets up essential environment variables for the Octavus client, including the API URL, API key, and agent ID. ```env # .env OCTAVUS_API_URL=https://octavus.ai OCTAVUS_API_KEY=your-api-key OCTAVUS_AGENT_ID=your-agent-id ``` -------------------------------- ### Agent Settings JSON Schema Source: https://octavus.ai/docs/server-sdk/cli Example of the `settings.json` file, which contains essential metadata for an Octavus agent, including its slug, name, description, and format. ```json { "slug": "my-agent", "name": "My Agent", "description": "A helpful assistant", "format": "interactive" } ``` -------------------------------- ### Tool Handlers Source: https://octavus.ai/docs/server-sdk/overview Example of defining and attaching custom tools to an agent session. ```APIDOC ## Tool Handlers Attach tools to a session to run custom logic: ```typescript const session = client.agentSessions.attach(sessionId, { tools: { 'get-user-account': async (args) => { // Access your database, APIs, etc. return await db.users.findById(args.userId); }, }, }); ``` ``` -------------------------------- ### Server-Side Tool Handlers Example (TypeScript) Source: https://octavus.ai/docs/server-sdk/workers Illustrates how to provide server-side tool handlers when executing a worker. This example shows handlers for 'web-search' and 'get-user-data' tools, demonstrating asynchronous execution and database interaction. ```typescript const events = client.workers.execute( agentId, { TOPIC: 'AI safety' }, { tools: { 'web-search': async (args) => { const results = await searchWeb(args.query); return results; }, 'get-user-data': async (args) => { return await db.users.findById(args.userId); }, }, }, ); ``` -------------------------------- ### Example Fetch Request Implementation (TypeScript) Source: https://octavus.ai/docs/client-sdk/http-transport Provides an example implementation of the `request` function within `HttpTransportOptions` using the `fetch` API. This function sends a POST request to a '/api/trigger' endpoint, serializing the payload and including the session ID and optional signal. ```typescript request: (payload, options) => fetch('/api/trigger', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId, ...payload }), signal: options?.signal, }); ``` -------------------------------- ### Agent Management CLI Source: https://octavus.ai/docs/server-sdk/overview Example of using the Octavus CLI to sync agent definitions. ```APIDOC ## Agent Management Sync agent from local files using the CLI: ```bash octavus sync ./agents/support-chat # Output: # Created: support-chat # Agent ID: clxyz123abc456 ``` ``` -------------------------------- ### Agent Session Management Source: https://octavus.ai/docs/server-sdk/overview Code examples for creating and retrieving agent sessions. ```APIDOC ## Session Management Create a new session: ```typescript // Use agent ID obtained from CLI sync const sessionId = await client.agentSessions.create('clxyz123abc456', { COMPANY_NAME: 'Acme Corp', PRODUCT_NAME: 'Widget Pro', }); // Get UI-ready session messages for session restore: const session = await client.agentSessions.getMessages(sessionId); ``` ``` -------------------------------- ### Sync Agents with Octavus CLI (Bash) Source: https://octavus.ai/docs/getting-started/quickstart Installs the Octavus CLI as a development dependency and syncs local agent definitions from the './agents/support-chat' directory. This command outputs the agent ID, useful for version-controlled agent management. ```bash npm install --save-dev @octavus/cli octavus sync ./agents/support-chat # Output: Agent ID: clxyz123abc456 ``` -------------------------------- ### Client-Side Basic Setup Source: https://octavus.ai/docs/client-sdk/http-transport Demonstrates how to set up the HTTP transport on the client-side using React and the `@octavus/react` library. It includes creating the transport with a custom fetch request and initializing the `useOctavusChat` hook. ```APIDOC ## Client-Side Basic Setup ### Description This example shows how to initialize the Octavus chat client using the HTTP transport. It defines a custom `fetch` request function that sends chat payloads to a server endpoint. ### Method N/A (Client-side setup) ### Endpoint N/A (Client-side setup) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```tsx import { useMemo } from 'react'; import { useOctavusChat, createHttpTransport } from '@octavus/react'; function Chat({ sessionId }: { sessionId: string }) { const transport = useMemo( () => createHttpTransport({ request: (payload, options) => fetch('/api/trigger', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId, ...payload }), signal: options?.signal, }), }), [sessionId], ); const { messages, status, error, send, stop } = useOctavusChat({ transport }); const sendMessage = async (text: string) => { await send('user-message', { USER_MESSAGE: text }, { userMessage: { content: text } }); }; // ... render chat } ``` ### Response #### Success Response (200) N/A (Client-side setup) #### Response Example N/A (Client-side setup) ``` -------------------------------- ### OctavusClient Initialization Source: https://octavus.ai/docs/server-sdk/overview Demonstrates how to initialize the OctavusClient with your API key and base URL. ```APIDOC ## Basic Usage Initialize the client: ```typescript import { OctavusClient } from '@octavus/server-sdk'; const client = new OctavusClient({ baseUrl: 'https://octavus.ai', apiKey: 'your-api-key', }); ``` ``` -------------------------------- ### Get Agent cURL Example Source: https://octavus.ai/docs/api-reference/agents This cURL command demonstrates how to make a GET request to the /api/agents/:agentId endpoint to retrieve a specific agent, including the Authorization header. ```bash curl https://octavus.ai/api/agents/:agentId \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Full Example Configuration for Octavus Skills Source: https://octavus.ai/docs/protocol/provider-options This YAML configuration demonstrates how to set up tools, skills, agent models, and triggers within the Octavus framework. It includes Anthropic-specific options for tools and skills, showcasing provider-agnostic code execution. ```yaml 1input: 2 COMPANY_NAME: { type: string } 3 USER_ID: { type: string, optional: true } 4 5tools: 6 get-user-account: 7 description: Looking up your account 8 parameters: 9 userId: { type: string } 10 11agent: 12 model: anthropic/claude-sonnet-4-5 13 system: system 14 input: [COMPANY_NAME, USER_ID] 15 tools: [get-user-account] # External tools 16 agentic: true 17 thinking: medium 18 19 # Anthropic-specific options 20 anthropic: 21 # Provider tools (server-side) 22 tools: 23 web-search: 24 display: description 25 description: Searching the web 26 code-execution: 27 display: description 28 description: Running code 29 30 # Skills (knowledge packages) 31 skills: 32 pdf: 33 type: anthropic 34 display: description 35 description: Processing PDF document 36 xlsx: 37 type: anthropic 38 display: description 39 description: Analyzing spreadsheet 40 triggers: 41 user-message: 42 input: 43 USER_MESSAGE: { type: string } 44 handlers: 45 user-message: 46 Add message: 47 block: add-message 48 role: user 49 prompt: user-message 50 input: [USER_MESSAGE] 51 display: hidden 52 53 Respond: 54 block: next-message ``` -------------------------------- ### Get Agent API Response Example Source: https://octavus.ai/docs/api-reference/agents This JSON structure represents the response when retrieving a single agent, including its ID, settings, protocol definition, and prompts. ```json { "id": "cm5xvz7k80001abcd", "settings": { "slug": "support-chat", "name": "Support Chat", "description": "Customer support agent", "format": "interactive" }, "protocol": "input:\n COMPANY_NAME: { type: string }\n...", "prompts": [ { "name": "system", "content": "You are a support agent for {{COMPANY_NAME}}..." }, { "name": "user-message", "content": "{{USER_MESSAGE}}" } ] } ``` -------------------------------- ### List Agents cURL Example Source: https://octavus.ai/docs/api-reference/agents This cURL command demonstrates how to make a GET request to the /api/agents endpoint to retrieve all agents, including the necessary Authorization header. ```bash curl https://octavus.ai/api/agents \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Set Up Express Server with SockJS (TypeScript) Source: https://octavus.ai/docs/examples/socket-chat Configures an Express server to handle static frontend files and integrates SockJS for real-time communication, setting up the socket endpoint for Octavus. ```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'); }); ``` -------------------------------- ### Get Session - cURL Example Source: https://octavus.ai/docs/api-reference/sessions This cURL command shows how to retrieve the state of an existing agent session using its unique session ID. An API key is required for authorization. ```bash curl https://octavus.ai/api/agent-sessions/:sessionId \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Initialize Octavus Client (TypeScript) Source: https://octavus.ai/docs/getting-started/quickstart Initializes the Octavus client in the backend using environment variables for the API URL and key. This client is used to interact with the Octavus API. ```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!, }); ``` -------------------------------- ### Octavus AI Environment Variables Configuration (Bash) Source: https://octavus.ai/docs/getting-started/quickstart Specifies the environment variables required for Octavus AI integration. These variables, `OCTAVUS_API_URL` and `OCTAVUS_API_KEY`, should be added to the `.env.local` file for authentication and configuration. ```bash 1OCTAVUS_API_URL=https://octavus.ai 2OCTAVUS_API_KEY=your-api-key-here ``` -------------------------------- ### Configure Octavus CLI with Environment Variables Source: https://octavus.ai/docs/server-sdk/cli Demonstrates setting up API keys and API URL for the Octavus CLI using environment variables. It shows a recommended two-key strategy for production deployments and how to use separate environment files for different deployment targets. ```bash # CI/CD or .env.local (not committed) OCTAVUS_CLI_API_KEY=oct_sk_... # "Agents" permission only # Production .env OCTAVUS_API_KEY=oct_sk_... # "Sessions" permission only ``` ```bash # .env.staging (syncs to your staging project) OCTAVUS_CLI_API_KEY=oct_sk_staging_project_key... # .env.production (syncs to your production project) OCTAVUS_CLI_API_KEY=oct_sk_production_project_key... ``` -------------------------------- ### Server-Sent Events (SSE) Stream Example Source: https://octavus.ai/docs/api-reference/sessions This illustrates the format of Server-Sent Events (SSE) received when triggering an agent session. It includes various event types like 'start', 'block-start', 'text-delta', and 'finish', which represent the progression of the agent's response. ```text data: {"type":"start","messageId":"msg-123"} data: {"type":"block-start","blockId":"b1","blockName":"Add user message","blockType":"add-message","display":"hidden"} data: {"type":"block-end","blockId":"b1"} data: {"type":"block-start","blockId":"b2","blockName":"Respond to user","blockType":"next-message","display":"stream","outputToChat":true} data: {"type":"text-start","id":"t1"} data: {"type":"text-delta","id":"t1","delta":"I"} data: {"type":"text-delta","id":"t1","delta":" can"} data: {"type":"text-delta","id":"t1","delta":" help"} data: {"type":"text-delta","id":"t1","delta":" you"} data: {"type":"text-delta","id":"t1","delta":" reset"} data: {"type":"text-delta","id":"t1","delta":" your"} data: {"type":"text-delta","id":"t1","delta":" password"} data: {"type":"text-delta","id":"t1","delta":"!"} data: {"type":"text-end","id":"t1"} data: {"type":"block-end","blockId":"b2"} data: {"type":"finish","finishReason":"stop"} data: [DONE] ``` -------------------------------- ### Create Chat Component with HTTP Transport (TypeScript/React) Source: https://octavus.ai/docs/getting-started/quickstart Implements a chat component using the `useOctavusChat` hook and a custom HTTP transport. It handles user input, displays messages, and manages chat status. Dependencies include `@octavus/react` and React. ```tsx 1// components/chat.tsx 2'use client'; 3 4import { useState, useMemo } from 'react'; 5import { useOctavusChat, createHttpTransport, type UIMessage } from '@octavus/react'; 6 7interface ChatProps { 8 sessionId: string; 9} 10 11export function Chat({ sessionId }: ChatProps) { 12 const [inputValue, setInputValue] = useState(''); 13 14 // Create a stable transport instance 15 const transport = useMemo( 16 () => 17 createHttpTransport({ 18 request: (payload, options) => 19 fetch('/api/trigger', { 20 method: 'POST', 21 headers: { 'Content-Type': 'application/json' }, 22 body: JSON.stringify({ sessionId, ...payload }), 23 signal: options?.signal, 24 }), 25 }), 26 [sessionId], 27 ); 28 29 const { messages, status, error, send } = useOctavusChat({ transport }); 30 31 const isStreaming = status === 'streaming'; 32 33 const handleSubmit = async (e: React.FormEvent) => { 34 e.preventDefault(); 35 if (!inputValue.trim() || isStreaming) return; 36 37 const message = inputValue.trim(); 38 setInputValue(''); 39 40 // Add user message and trigger in one call 41 await send('user-message', { USER_MESSAGE: message }, { userMessage: { content: message } }); 42 }; 43 44 return ( 45
46 {/* Messages */} 47
48 {messages.map((msg) => ( 49 50 ))} 51
52 53 {/* Input */} 54
55
56 setInputValue(e.target.value)} 60 placeholder="Type a message..." 61 className="flex-1 px-4 py-2 border rounded-lg" 62 disabled={isStreaming} 63 /> 64 71
72
73
74 ); 75} 76 77function MessageBubble({ message }: { message: UIMessage }) { 78 const isUser = message.role === 'user'; 79 80 return ( 81
82
85 {message.parts.map((part, i) => { 86 if (part.type === 'text') { 87 return

{part.text}

; 88 } 89 return null; 90 })} 91 92 {/* Streaming indicator */} 93 {message.status === 'streaming' && ( 94 95 )} 96
97
98 ); 99} ``` -------------------------------- ### Adjust Schema Imports from Octavus Core (TypeScript) Source: https://octavus.ai/docs/migration/v1-to-v2 This example illustrates changes in how Zod schemas are imported from the Octavus SDK. Some schemas previously re-exported by `@octavus/server-sdk` must now be imported directly from `@octavus/core` to ensure compatibility with v2. Type imports remain unchanged. ```typescript // After (v2) - import from core if needed import { fileReferenceSchema } from '@octavus/core'; ``` -------------------------------- ### Create Session and Render Chat Page (TypeScript/React) Source: https://octavus.ai/docs/getting-started/quickstart Sets up a chat page that first creates a session by calling an API endpoint and then renders the `Chat` component with the obtained session ID. It uses React's `useEffect` and `useState` hooks. Dependencies include React. ```tsx 1// app/chat/page.tsx 2'use client'; 3 4import { useEffect, useState } from 'react'; 5import { Chat } from '@/components/chat'; 6 7export default function ChatPage() { 8 const [sessionId, setSessionId] = useState(null); 9 10 useEffect(() => { 11 async function createSession() { 12 const response = await fetch('/api/chat/create', { 13 method: 'POST', 14 headers: { 'Content-Type': 'application/json' }, 15 body: JSON.stringify({ 16 input: { 17 COMPANY_NAME: 'Acme Corp', 18 PRODUCT_NAME: 'Widget Pro', 19 }, 20 }), 21 }); 22 const { sessionId } = await response.json(); 23 setSessionId(sessionId); 24 } 25 26 createSession(); 27 }, []); 28 29 if (!sessionId) { 30 return
Loading...
; 31 } 32 33 return ; 34} ``` -------------------------------- ### Create Session Endpoint (Next.js API Route - TypeScript) Source: https://octavus.ai/docs/getting-started/quickstart An API endpoint in Next.js that creates a new Octavus agent session. It takes user input, uses the initialized Octavus client to create a session with a specified agent ID, and returns the session ID. ```typescript // app/api/chat/create/route.ts import { NextResponse } from 'next/server'; import { octavus } from '@/lib/octavus'; // Agent ID - get from platform or CLI (see below) const SUPPORT_AGENT_ID = process.env.OCTAVUS_SUPPORT_AGENT_ID!; export async function POST(request: Request) { const { input } = await request.json(); // Create a new session using the agent ID const sessionId = await octavus.agentSessions.create(SUPPORT_AGENT_ID, input); return NextResponse.json({ sessionId }); } ``` -------------------------------- ### Initialize Octavus Client (TypeScript) Source: https://octavus.ai/docs/server-sdk/overview Initializes the OctavusClient, which is the main entry point for interacting with the Octavus API from a Node.js backend. Requires configuration with the base URL and an API key. ```typescript import { OctavusClient } from '@octavus/server-sdk'; const client = new OctavusClient({ baseUrl: 'https://octavus.ai', apiKey: 'your-api-key', }); ``` -------------------------------- ### Trigger Endpoint with Tool Handlers (Next.js API Route - TypeScript) Source: https://octavus.ai/docs/getting-started/quickstart An API endpoint that handles triggers from an Octavus session and streams responses. It attaches to an existing session, defines server-side tool handlers (e.g., 'get-user-account', 'create-support-ticket'), executes the payload, and returns a Server-Sent Events (SSE) stream. ```typescript // app/api/trigger/route.ts import { toSSEStream } from '@octavus/server-sdk'; import { octavus } from '@/lib/octavus'; export async function POST(request: Request) { const body = await request.json(); const { sessionId, ...payload } = body; // Attach to session with tool handlers const session = octavus.agentSessions.attach(sessionId, { tools: { // Define tool handlers that run on your server 'get-user-account': async (args) => { const userId = args.userId as string; // Fetch from your database return { name: 'Demo User', email: 'demo@example.com', plan: 'pro', }; }, 'create-support-ticket': async (args) => { // Create ticket in your system return { ticketId: 'TICKET-123', estimatedResponse: '24 hours', }; }, }, }); // Execute the request and convert to SSE stream const events = session.execute(payload, { signal: request.signal }); // Return as streaming response return new Response(toSSEStream(events), { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', }, }); } ``` -------------------------------- ### Building a Streaming UI with Octavus React SDK Source: https://octavus.ai/docs/client-sdk/streaming Provides a comprehensive example of building a chat UI using the Octavus React SDK. It shows how to create an HTTP transport, utilize the `useOctavusChat` hook, and render messages, handle errors, and control streaming with a stop button. ```tsx 1import { useMemo } from 'react'; 2import { useOctavusChat, createHttpTransport } from '@octavus/react'; 3 4function Chat({ sessionId }: { sessionId: string }) { 5 const transport = useMemo( 6 () => 7 createHttpTransport({ 8 request: (payload, options) => 9 fetch('/api/trigger', { 10 method: 'POST', 11 headers: { 'Content-Type': 'application/json' }, 12 body: JSON.stringify({ sessionId, ...payload }), 13 signal: options?.signal, 14 }), 15 }), 16 [sessionId], 17 ); 18 19 const { messages, status, error, send, stop } = useOctavusChat({ transport }); 20 21 return ( 22
23 {/* Messages with streaming parts */} 24 {messages.map((msg) => ( 25 26 ))} 27 28 {/* Error state */} 29 {error &&
{error.message}
} 30 31 {/* Stop button during streaming */} 32 {status === 'streaming' && } 33
34 ); 35} ``` -------------------------------- ### Variable Usage in Prompts (Markdown) Source: https://octavus.ai/docs/protocol/overview Demonstrates how to reference variables within prompt template files using double curly braces. This example shows a system prompt that dynamically includes company name and product information, which are replaced at runtime. ```markdown 1 2 You are a support agent for {{COMPANY_NAME}}. 3 4Help users with their {{PRODUCT_NAME}} questions. 5 6## Support Policies 7 8{{SUPPORT_POLICIES}} ``` -------------------------------- ### Implement Automatic Client Tools with useOctavusChat (React/TypeScript) Source: https://octavus.ai/docs/migration/v1-to-v2 Demonstrates how to configure and use automatic client-side tools within a React component using the `useOctavusChat` hook. It shows the setup of a custom HTTP transport and defines handlers for 'get-browser-location' and 'get-clipboard' tools, leveraging browser APIs. Requires '@octavus/react' and standard browser APIs. ```typescript import { useOctavusChat, createHttpTransport } from '@octavus/react'; function Chat() { const { messages, send, status } = useOctavusChat({ transport: createHttpTransport({ request: (payload, options) => fetch('/api/trigger', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId, ...payload }), signal: options?.signal, }), }), clientTools: { 'get-browser-location': async (args, ctx) => { const pos = await new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition(resolve, reject); }); return { lat: pos.coords.latitude, lng: pos.coords.longitude }; }, 'get-clipboard': async () => { return await navigator.clipboard.readText(); }, }, }); // ... rest of component } ``` -------------------------------- ### Implementing Tools (TypeScript) Source: https://octavus.ai/docs/protocol/tools Provides a TypeScript example of implementing custom tools for an agent session. It shows how to define asynchronous functions for tools like 'get-user-account' and 'create-support-ticket', interacting with a database and a ticket service. ```typescript 1const session = client.agentSessions.attach(sessionId, { 2 tools: { 3 'get-user-account': async (args) => { 4 const userId = args.userId as string; 5 const user = await db.users.findById(userId); 6 7 return { 8 name: user.name, 9 email: user.email, 10 plan: user.subscription.plan, 11 createdAt: user.createdAt.toISOString(), 12 }; 13 }, 14 15 'create-support-ticket': async (args) => { 16 const ticket = await ticketService.create({ 17 summary: args.summary as string, 18 priority: args.priority as string, 19 }); 20 21 return { 22 ticketId: ticket.id, 23 estimatedResponse: getEstimatedTime(args.priority), 24 }; 25 }, 26 }, 27}); ``` -------------------------------- ### Octavus Server SDK: Files API Usage (TypeScript) Source: https://octavus.ai/docs/client-sdk/file-uploads Demonstrates how to use the Octavus Server SDK to interact with the Files API. This example shows how to obtain presigned upload URLs for files and outlines how to use the returned information. ```typescript import { OctavusClient } from '@octavus/server-sdk'; const client = new OctavusClient({ baseUrl: 'https://octavus.ai', apiKey: 'your-api-key', }); // Get presigned upload URLs const { files } = await client.files.getUploadUrls(sessionId, [ { filename: 'photo.jpg', mediaType: 'image/jpeg', size: 102400 }, { filename: 'doc.pdf', mediaType: 'application/pdf', size: 204800 }, ]); // files[0].id - Use in FileReference // files[0].uploadUrl - PUT to this URL to upload // files[0].downloadUrl - Use as FileReference.url ``` -------------------------------- ### Octavus Stream Event Types (TypeScript) Source: https://octavus.ai/docs/server-sdk/streaming Illustrates the various event types emitted during an Octavus stream, including lifecycle events (start, finish, error), block events (start, end), text events (start, delta, end), reasoning events, and tool interaction events. ```typescript // Stream started { type: 'start', messageId: '...', executionId: '...' } // Stream completed { type: 'finish', finishReason: 'stop' } // Possible finish reasons: // - 'stop': Normal completion // - 'tool-calls': Waiting for server tool execution (handled by SDK internally) // - 'client-tool-calls': Waiting for client tool execution // - '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...' } ``` -------------------------------- ### HTTP Transport Client Setup (TypeScript) Source: https://octavus.ai/docs/client-sdk/client-tools Sets up an HTTP transport for client tool continuation using a unified request pattern. It utilizes the `fetch` API to send POST requests to '/api/trigger' with JSON payloads and supports cancellation via AbortSignal. ```typescript const transport = createHttpTransport({ // Single request handler for both triggers and continuations request: (payload, options) => fetch('/api/trigger', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId, ...payload }), signal: options?.signal, }), }); ``` -------------------------------- ### Model Configuration Examples (YAML) Source: https://octavus.ai/docs/protocol/agent-config Demonstrates how to configure different LLM models from various providers (Anthropic, Google, OpenAI) within the agent configuration. Model IDs follow the 'provider/model-id' format. ```yaml # Anthropic Claude 4.5 agent: model: anthropic/claude-sonnet-4-5 # Google Gemini 3 agent: model: google/gemini-3-flash-preview # OpenAI GPT-5 agent: model: openai/gpt-5 # OpenAI reasoning models agent: model: openai/o3-mini ``` -------------------------------- ### YAML Skill Description Example Source: https://octavus.ai/docs/protocol/skills This YAML snippet illustrates how to define a skill with a clear, purpose-driven description. It shows the 'qr-code' skill with a descriptive text, contrasting it with a vague 'utility' skill description. This format is used to inform the agent about the skill's functionality. ```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 ```