Menu

API reference

<CopilotProvider>

The CopilotProvider is a headless React provider that allows its children to control the Copilot via useCopilot hook. The CopilotProvider is typically used:

  • As a wrapper around the CopilotChat component, if you're using the default chat UI.
  • As a wrapper around your own UI implementation, which relies on useCopilot() to talk to the backend.
// Example.jsx
import { CopilotProvider, CopilotChat } from '@copilotjs/react'

export default function Example() {
  return (
    <CopilotProvider appId="..." userId="..." companyId="..." context={...}>
      // All children can useCopilot().
      // Place here the CopilotChat component, or your own UI:
      <MyChat />
    </CopilotProvider>
  )
}

Props

Use these properties to configure the CopilotProvider component.

PropDescriptionTypeRequired
appIdThe ID of your application, obtained when you create a Copilot account.stringyes
userIdThe ID of the user who's logged into your app. Set it to the user.id in your database.stringyes
companyIdThe ID of the organization your user belongs to. Set it to the user.company.id in your database.stringyes
contextThe actions and state of your app. See details below.objectyes
inferenceThe properties of the AI inference engine. See details below.objectno
onReadyFunction invoked when the component first connects to backend, and is ready to accept method calls. See ready example.(event) => voidno
onThreadCreatedFunction invoked when a new conversation thread is created. See thread.created example.(event) => voidno
onMessageCompletedFunction invoked when a user or assistant message is completed. See message.completed example.(event) => voidno
onMessageIncompleteFunction invoked when a user or assistant message was not completed, due to cancellation or other reasons. See message.incomplete example.(event) => voidno
onErrorFunction invoked when an error occurs. See error example.(event) => voidno
onIsReadyChangedFunction invoked when component readiness changes. See isReady.changed example.(event) => voidno
onSnapshotChangedFunction invoked when the undo snapshot of the Copilot changes. See snapshot.changed example.(event) => voidno
onThreadsChangedFunction invoked when the list of available threads changes. See threads.changed example.(event) => voidno
onSelectedThreadIdChangedFunction invoked when a different thread is selected. See selectedThreadId.changed example.(event) => voidno
onStatusChangedFunction invoked when the status of the selected thread changes. See status.changed example.(event) => voidno
onMessagesChangedFunction invoked when the messages of the selected thread change. See messages.changed example.(event) => voidno

context

KeyDescriptionTypeRequired
actionsA map of functions that Copilot is allowed to invoke, in your particular app. See actions example.objectyes
actionTypesThe type definitions for all available actions, in Typescript. See action types example.stringyes
stateA subset of your app's state, to optionally improve AI performance. See state example.Stateno
undoHistoryYour app's undo history, to optionally allow the user to undo actions performed by the assistant. See undo example.objectno

inference

KeyDescriptionTypeRequired
providerThe name of company providing AI inference.stringno, default is openai
modelThe name of AI model used.stringno, default is gpt-4-0125-preview

The supported inference providers and models are:

ProviderModelComment
openaigpt-4-0125-previewRecommended.
openaigpt-4

Example

<CopilotProvider
  appId="aaa1f9b9-56c2-45de-a466-64fadc8120d0"
  userId="u"
  companyId="c"
  context={{
    actions: {
      createShape: (shape) => {},
      updateShape: (shapeId, shape) => {},
      deleteShape: (shapeId) => {},
      getShape: (shapeId) => {},
      listShapes: (filters) => {},
      deleteAllShapes: () => {},
    },
    actionTypes:
      "type createShape = (shape: Shape) => ShapeWithId\ntype updateShape = (shapeId: string, updatedShape: Partial<Shape>) => void\ntype deleteShape = (shapeId: string) => void\ntype getShape = (shapeId: string) => ShapeWithId\ntype listShapes = (filters: Partial<ShapeWithId>) => ShapeWithId[]\ntype deleteAllShapes = () => void\n\ntype Shape = Square | Circle\ntype Circle = { type: 'circle'; x: number; y: number; radius: number }\ntype Square = { type: 'square'; x: number; y: number; length: number }\n\ntype ShapeWithId = SquareWithId | CircleWithId\ntype CircleWithId = Circle & { id: string }\ntype SquareWithId = Square & { id: string }\n\ntype State = {\n  visibleArea: { x: number; y: number; width: number; height: number }\n  countShapes: number\n  countSelectedShapes: number\n}\n",
    state: {
      visibleArea: { x: 0, y: 0, width: 100, height: 100 },
      countShapes: 80,
      countSelectedShapes: 2,
    },
    undoHistory: { past: [], present: {}, future: [] },
  }}
  inference={{
    provider: 'openai',
    model: 'gpt-4-0125-preview',
  }}
  onReady={(event) => console.log('The component was initialized.')}
  onThreadCreated={(event) => console.log('A new thread was created.')}
  onMessageCompleted={(event) => console.log('A message was completed.')}
  onMessageIncomplete={(event) => console.log('A message was incomplete.')}
  onError={(event) => console.log('An error occurred.')}
  onIsReadyChanged={(event) => console.log('The component readiness changed')}
  onSnapshotChanged={(event) => console.log('The undo snapshot changed.')}
  onThreadsChanged={(event) => console.log('The available threads changed.')}
  onSelectedThreadIdChanged={(event) => console.log('A different thread was selected.')}
  onStatusChanged={(event) => console.log('The status of selected thread changed.')}
  onMessagesChanged={(event) => console.log('The messages of selected thread changed.')}
>
  // Place here the CopilotChat component, or your own UI implementation.
</CopilotProvider>

Events

The CopilotProvider emits multiple types of events, described below.

ready

When the component first connects to the backend, and is ready to accept method calls, the onReady handler is invoked with an event such as:

{
  "type": "ready",
  "data": {
    "jwt": "eyJh...",
    "assistant": {
      "id": "asst_bhpr2F2MD8GJYEA88UbdzuQ9",
      "object": "assistant",
      "createdAt": 1693587139
    },
    "thread": {
      "id": "thread_4n5gAb9PEPIOZ7XiorEXVO3N",
      "object": "thread",
      "createdAt": 1727894570
    }
  }
}

thread.created

When a new conversation thread is created, the onThreadCreated handler is invoked with an event such as:

{
  "type": "thread.created",
  "data": {
    "id": "thread_9SxkGHNKxfQWCLVCJPFTtFV2",
    "object": "thread",
    "createdAt": 1725298848,
    "metadata": {},
    "toolResources": {}
  }
}

message.completed

When a user or assistant message is completed, the onMessageCompleted handler is invoked with an event such as:

{
  "type": "message.completed",
  "data": {
    "id": "msg_yNN0jKCEcLR1IBYXkcpioP1u",
    "object": "thread.message",
    "createdAt": 1725298681,
    "assistantId": "asst_bhpr2F2MD8GJYEA88UbdzuQ9",
    "threadId": "thread_MyR6ntVmF2IkndJUd1IbQTVc",
    "runId": "run_tZlPsFrTSaGmOPNCGAVCT1nH",
    "status": "completed",
    "incompleteDetails": null,
    "incompleteAt": null,
    "completedAt": 1725298681,
    "role": "assistant",
    "content": [
      {
        "type": "text",
        "text": {
          "value": "I'm just a digital assistant, so I don't have feelings, but thanks for asking! How can I assist you today?",
          "annotations": []
        }
      }
    ],
    "attachments": [],
    "metadata": {}
  }
}

message.incomplete

When a user or assistant message was not completed, due to cancellation or other reasons, the onMessageIncomplete handler is invoked with an event such as:

{
  "type": "message.incomplete",
  "data": {
    "id": "msg_K5d00uQu2ir4Tzr05AMR7Alo",
    "object": "thread.message",
    "createdAt": 1725298815,
    "assistantId": "asst_bhpr2F2MD8GJYEA88UbdzuQ9",
    "threadId": "thread_dueTrbCApJ5JRRyV4LXURF1T",
    "runId": "run_tNwx4jyAwRqrCysSmWEKbwL2",
    "status": "incomplete",
    "incompleteDetails": {
      "reason": "run_cancelled"
    },
    "incompleteAt": 1725298815,
    "completedAt": null,
    "role": "assistant",
    "content": [
      {
        "type": "text",
        "text": {
          "value": "I'm just",
          "annotations": []
        }
      }
    ],
    "attachments": [],
    "metadata": {}
  }
}

error

When an error occurs, the onError handler is invoked with an event such as:

{
  "type": "error",
  "data": {
    "id": "error_PLbBDGdPS35TrEVaygnPwq9k",
    "object": "error",
    "threadId": null,
    "type": "invalid_options_error",
    "message": "The provided appId was not found."
  }
}

The possible error types are:

Error typeDescription
invalid_options_errorThe properties passed to the component are invalid.
insufficient_balance_errorThe dollar balance on the account is insufficient to proceed.
server_errorThe request failed due to a server error.

isReady.changed

When the component readiness changes, the onIsReadyChanged handler is invoked with an event such as:

{
  "type": "isReady.changed",
  "data": {
    "oldIsReady": false,
    "newIsReady": true
  }
}

snapshot.changed

When the undo snapshot of Copilot changes, the onSnapshotChanged handler is invoked with an event such as:

{
  "type": "snapshot.changed",
  "data": {
    "oldSnapshot": {
      "isRunning": true,
      "lastOkRunId": null
    },
    "newSnapshot": {
      "isRunning": false,
      "lastOkRunId": "run_Xi2ITZrAox1HgE1zfKxU1liw"
    }
  }
}

threads.changed

When the list of available threads changes, the onThreadsChanged handler is invoked with an event such as:

{
  "type": "threads.changed",
  "data": {
    "oldThreads": [],
    "newThreads": [
      {
        "id": "thread_GA19uVFVDPhImtwdjqwdbAe3",
        "object": "thread",
        "createdAt": 1727894463
      }
    ]
  }
}

selectedThreadId.changed

When a different thread is selected, the onSelectedThreadIdChanged handler is invoked with an event such as:

{
  "type": "selectedThreadId.changed",
  "data": {
    "oldSelectedThreadId": "thread_GA19uVFVDPhImtwdjqwdbAe3",
    "newSelectedThreadId": "thread_6QA4JF3PfhlsEqf08oWYEjbI"
  }
}

status.changed

When the status of the selected thread changes, the onStatusChanged handler is invoked with an event such as:

{
  "type": "status.changed",
  "data": {
    "oldStatus": "idle",
    "newStatus": "working"
  }
}

messages.changed

When the messages of the selected thread change, the onMessagesChanged handler is invoked with an event such as:

{
  "type": "messages.changed",
  "data": {
    "oldMessages": [],
    "newMessages": [
      {
        "status": "completed",
        "id": "msg_z9J4jxQVB3qmri503kT7CJmV",
        "object": "thread.message",
        "threadId": "thread_dueTrbCApJ5JRRyV4LXURF1T",
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": {
              "value": "Add 2 circles.",
              "annotations": []
            }
          }
        ],
        "isUndoable": null,
        "isRedoable": null
      }
    ]
  }
}
Previous
Headless