useCyborg Hook
The useCyborg hook allows components to register context, instructions, tools, and suggested prompts with the chat system. Each component can contribute its own context, and all registered data is automatically merged.
Basic Usage
import { useCyborg } from '@cyborg-sdk/react'
function ProductPage({ product }) {
useCyborg({
context: {
page: 'product',
productId: product.id,
productName: product.name
},
instructions: 'Help users understand this product.',
suggestedPrompts: [
'What are the key features?',
'How does pricing work?'
]
})
return <ProductDetails product={product} />
}Options
| Option | Type | Description |
|---|---|---|
context | CyborgContext | Key-value data about the current page/state |
instructions | string | AI behavior instructions for this component |
tools | ToolDefinition[] | Functions the AI can execute |
suggestedPrompts | string[] | Suggested prompts shown to users |
Context
Provide contextual information about the current page or component:
useCyborg({
context: {
page: 'dashboard',
userId: user.id,
accountStatus: 'premium',
currentTab: 'analytics',
metrics: {
revenue: 45000,
orders: 127
}
}
})The context is sent to the AI with each message, helping it understand what the user is viewing.
Instructions
Guide the AI's behavior for specific pages or components:
useCyborg({
instructions: `
Help users understand their dashboard metrics.
Be concise and use numbers from the context.
Suggest actions based on their data trends.
`
})Instructions from multiple components are concatenated, so you can layer general and specific guidance.
Registering Tools
Tools allow the AI to execute functions in your application:
useCyborg({
tools: [{
name: 'createTicket',
description: 'Create a support ticket',
parameters: {
type: 'object',
properties: {
title: { type: 'string', description: 'Ticket title' },
priority: { type: 'string', enum: ['low', 'medium', 'high'] }
},
required: ['title']
},
handler: async ({ title, priority }) => {
const ticket = await api.createTicket({ title, priority })
return { ticketId: ticket.id }
},
timeout: 30000 // Optional, defaults to 30s
}]
})Tool Definition Interface
interface ToolDefinition {
name: string // Unique identifier
description: string // What the tool does (shown to AI)
parameters: ToolParameter // JSON Schema-like parameter definition
handler: (params: any) => Promise<any> // Function to execute
timeout?: number // Timeout in ms (default: 30000)
}
interface ToolParameter {
type: 'string' | 'number' | 'boolean' | 'object' | 'array'
description?: string
enum?: string[] // For string types
properties?: Record<string, ToolParameter> // For object types
required?: string[] // Required properties
items?: ToolParameter // For array types
}Multiple Tools Example
useCyborg({
tools: [
{
name: 'createTicket',
description: 'Create a support ticket',
parameters: {
type: 'object',
properties: {
title: { type: 'string' },
priority: { type: 'string', enum: ['low', 'medium', 'high'] }
},
required: ['title']
},
handler: async ({ title, priority }) => {
const ticket = await api.createTicket({ title, priority })
return { success: true, ticketId: ticket.id }
}
},
{
name: 'navigateTo',
description: 'Navigate to a page in the app',
parameters: {
type: 'object',
properties: {
page: { type: 'string', enum: ['dashboard', 'settings', 'billing'] }
},
required: ['page']
},
handler: async ({ page }) => {
router.push(`/${page}`)
return { navigated: true, page }
}
}
]
})Suggested Prompts
Provide context-aware prompts that help users get started:
useCyborg({
suggestedPrompts: [
`Tell me about ${product.name}`,
'What are the key features?',
'How does pricing work?',
'Compare with alternatives'
]
})Prompts are displayed in the chat widget's empty state.
Dynamic Updates
The hook returns functions for dynamic updates:
const { setContext, setInstructions, registerTool, setSuggestedPrompts } = useCyborg()
// Update context when data changes
useEffect(() => {
setContext({ cartItems: cart.items.length })
}, [cart.items])
// Register tools dynamically
useEffect(() => {
if (canCreateTickets) {
registerTool({
name: 'createTicket',
// ... tool definition
})
}
}, [canCreateTickets])Return Value
| Method | Type | Description |
|---|---|---|
setContext | (data: CyborgContext) => void | Update context data |
setInstructions | (instructions: string) => void | Update AI instructions |
registerTool | (tool: ToolDefinition) => void | Register a new tool |
setSuggestedPrompts | (prompts: string[]) => void | Update suggested prompts |
setTriggerPrompt | (prompt: string, options?: TriggerPromptOptions) => void | Trigger a prompt programmatically |
Multiple Components
Multiple components can use useCyborg simultaneously. All context, instructions, and tools are automatically merged:
// Layout.tsx - global context
useCyborg({
context: { app: 'MyApp', version: '1.0' },
instructions: 'You are a helpful assistant for MyApp.'
})
// ProductPage.tsx - page-specific context
useCyborg({
context: { page: 'product', productId: '123' },
instructions: 'Focus on product-related questions.'
})
// Both contexts are merged and available to the AICleanup
Context and tools are automatically cleaned up when the component unmounts. No manual cleanup required.
Complete Example
import { useCyborg } from '@cyborg-sdk/react'
function SupportDashboard({ user, tickets }) {
useCyborg({
// Provide context about the current view
context: {
page: 'support-dashboard',
userId: user.id,
openTickets: tickets.filter(t => t.status === 'open').length,
totalTickets: tickets.length
},
// Guide the AI's behavior
instructions: `
You are helping a support agent manage tickets.
The user has ${tickets.length} total tickets.
Prioritize helping with open tickets.
`,
// Provide tools the AI can use
tools: [{
name: 'closeTicket',
description: 'Close a support ticket',
parameters: {
type: 'object',
properties: {
ticketId: { type: 'string', description: 'The ticket ID to close' },
resolution: { type: 'string', description: 'Resolution summary' }
},
required: ['ticketId', 'resolution']
},
handler: async ({ ticketId, resolution }) => {
await api.closeTicket(ticketId, resolution)
return { success: true, message: `Ticket ${ticketId} closed` }
}
}],
// Suggest relevant prompts
suggestedPrompts: [
'Show me open tickets',
'What are the most common issues?',
'Help me write a response'
]
})
return <TicketList tickets={tickets} />
}Error Handling in Tools
Return errors gracefully so the AI can communicate them to users:
handler: async ({ title, priority }) => {
try {
const ticket = await api.createTicket({ title, priority })
return { success: true, ticketId: ticket.id }
} catch (error) {
return {
success: false,
error: 'Unable to create ticket. Please try again.'
}
}
}Result Size Limits
Tool results are limited by maxToolResultSizeKb (default: 100KB). For large data, return summaries or pagination info instead of full datasets.
Context Requirement
The hook must be used within a component wrapped by CyborgProvider:
// ❌ This will fail - not inside CyborgProvider
function InvalidUsage() {
const cyborg = useCyborg() // Error
return null
}
// ✅ This works - inside CyborgProvider
function App() {
return (
<CyborgProvider config={{ publishableKey: 'YOUR_API_KEY' }}>
<ValidUsage />
</CyborgProvider>
)
}
function ValidUsage() {
useCyborg({ context: { page: 'home' } }) // ✅ Works
return <div>Home Page</div>
}Related Documentation
- CyborgProvider - Main provider component
- useChat Hook - Access chat state and methods
- Tool Calling Guide - In-depth tool examples