├── .changeset ├── README.md └── config.json ├── .eslintrc ├── .github └── workflows │ ├── main.yml │ └── publish.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── api ├── CCatAPI.ts ├── client.ts ├── core │ ├── ApiError.ts │ ├── ApiRequestOptions.ts │ ├── ApiResult.ts │ ├── AxiosHttpRequest.ts │ ├── BaseHttpRequest.ts │ ├── CancelablePromise.ts │ ├── OpenAPI.ts │ └── request.ts ├── models │ ├── AuthPermission.ts │ ├── AuthResource.ts │ ├── BodyInstallPlugin.ts │ ├── BodyUploadFile.ts │ ├── BodyUploadMemory.ts │ ├── BodyUploadUrl.ts │ ├── CatMessage.ts │ ├── Collection.ts │ ├── CollectionData.ts │ ├── CollectionsList.ts │ ├── ConversationMessage.ts │ ├── DeleteResponse.ts │ ├── FileResponse.ts │ ├── HTTPValidationError.ts │ ├── JWTResponse.ts │ ├── MemoryRecall.ts │ ├── MessageWhy.ts │ ├── Metadata.ts │ ├── Plugin.ts │ ├── PluginsList.ts │ ├── QueryData.ts │ ├── Setting.ts │ ├── SettingBody.ts │ ├── SettingsResponse.ts │ ├── Status.ts │ ├── UserCreate.ts │ ├── UserCredentials.ts │ ├── UserResponse.ts │ ├── UserUpdate.ts │ ├── VectorsData.ts │ └── WebResponse.ts ├── services │ ├── AuthHandlerService.ts │ ├── EmbedderService.ts │ ├── LlmService.ts │ ├── MemoryService.ts │ ├── PluginsService.ts │ ├── RabbitHoleService.ts │ ├── SettingsService.ts │ ├── StatusService.ts │ ├── UserAuthService.ts │ └── UsersService.ts └── utils.ts ├── catapi.json ├── dist ├── index.d.mts ├── index.d.ts ├── index.js └── index.mjs ├── index.ts ├── package.json ├── pnpm-lock.yaml └── tsconfig.json /.changeset/README.md: -------------------------------------------------------------------------------- 1 | # Changesets 2 | 3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works 4 | with multi-package repos, or single-package repos to help you version and publish your code. You can 5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets) 6 | 7 | We have a quick list of common questions to get you started engaging with this project in 8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) 9 | -------------------------------------------------------------------------------- /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@2.3.0/schema.json", 3 | "changelog": "@changesets/cli/changelog", 4 | "commit": false, 5 | "fixed": [], 6 | "linked": [], 7 | "access": "public", 8 | "baseBranch": "main", 9 | "updateInternalDependencies": "patch", 10 | "ignore": [] 11 | } 12 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "eslint:recommended", 4 | "plugin:@typescript-eslint/recommended-type-checked", 5 | "plugin:@typescript-eslint/stylistic-type-checked" 6 | ], 7 | "ignorePatterns": ["**/dist/*"], 8 | "parser": "@typescript-eslint/parser", 9 | "parserOptions": { 10 | "project": true 11 | }, 12 | "plugins": [ 13 | "@typescript-eslint" 14 | ], 15 | "rules": { 16 | "no-throw-literal": "off", 17 | "@typescript-eslint/no-throw-literal": "error", 18 | "@typescript-eslint/no-explicit-any": "off", 19 | "@typescript-eslint/ban-tslint-comment": "off" 20 | }, 21 | "root": true 22 | } -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: 5 | - "**" 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | permissions: 11 | contents: write 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: pnpm/action-setup@v4 15 | with: 16 | version: 9 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: '18' 20 | cache: 'pnpm' 21 | - run: pnpm install --frozen-lockfile 22 | - run: pnpm lint 23 | - run: pnpm build 24 | - uses: stefanzweifel/git-auto-commit-action@v5 25 | with: 26 | commit_message: Build package 27 | commit_user_name: Builder Bot 28 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | on: 3 | workflow_run: 4 | workflows: [CI] 5 | branches: [main] 6 | types: [completed] 7 | 8 | concurrency: ${{ github.workflow }}-${{ github.ref }} 9 | 10 | permissions: 11 | contents: write 12 | pull-requests: write 13 | 14 | jobs: 15 | publish: 16 | if: ${{ github.event.workflow_run.conclusion == 'success' }} 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v4 20 | - uses: pnpm/action-setup@v4 21 | with: 22 | version: 9 23 | - uses: actions/setup-node@v4 24 | with: 25 | node-version: '18' 26 | cache: 'pnpm' 27 | - run: pnpm install --frozen-lockfile 28 | - name: Create Release Pull Request or Publish 29 | id: changesets 30 | uses: changesets/action@v1 31 | with: 32 | publish: pnpm run release 33 | env: 34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vscode -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # ccat-api 2 | 3 | ## 0.12.1 4 | 5 | ### Patch Changes 6 | 7 | - 9c31f33: fix chat_token check response 8 | 9 | ## 0.12.0 10 | 11 | ### Minor Changes 12 | 13 | - 4d7425b: update send method to work with multimodality 14 | 15 | ## 0.11.3 16 | 17 | ### Patch Changes 18 | 19 | - d4e7ee8: add missing params to file upload 20 | 21 | ## 0.11.2 22 | 23 | ### Patch Changes 24 | 25 | - 54fc277: fix types in auth handler endpoints 26 | 27 | ## 0.11.1 28 | 29 | ### Patch Changes 30 | 31 | - df6a9e9: renamed `baseUrl` to `host` for better understanding. 32 | 33 | ## 0.11.0 34 | 35 | ### Minor Changes 36 | 37 | - 1f4e778: - Added new auth endpoints 38 | - Removed unused `ws`, `query` and `headers` parameters 39 | - Renamed `authKey` to `credential` for better understanding 40 | - Renamed `largeLanguageModel` service to `llm` 41 | - Reset retries on WS connection open 42 | 43 | ### Patch Changes 44 | 45 | - 6da4693: Update SocketResponse interface 46 | 47 | ## 0.10.6 48 | 49 | ### Patch Changes 50 | 51 | - 95d692f: Fix type module in package.json 52 | 53 | ## 0.10.5 54 | 55 | ### Patch Changes 56 | 57 | - 6cf38ba: Add `when` in chat history, update deps 58 | 59 | ## 0.10.4 60 | 61 | ### Patch Changes 62 | 63 | - de5799b: Improve types, renamed `user` to `userId` 64 | 65 | ## 0.10.3 66 | 67 | ### Patch Changes 68 | 69 | - 36d3183: Fix websocket scheme not supported in the browser 70 | 71 | ## 0.10.2 72 | 73 | ### Patch Changes 74 | 75 | - 00c4b3d: Add custom headers 76 | 77 | ## 0.10.1 78 | 79 | ### Patch Changes 80 | 81 | - 648db68: Fix websocket default values 82 | 83 | ## 0.10.0 84 | 85 | ### Minor Changes 86 | 87 | - 312facd: 88 | - Fix code formatting 89 | - Add `query` parameter setting to the `WebSocketSettings` 90 | - Change `readyState` to be a getter and renamed to `socketState` 91 | - Rename `MetaData` interface to `Metadata` 92 | - Update dependencies 93 | - Add union type of strings for `SocketError` name 94 | 95 | ## 0.9.3 96 | 97 | ### Patch Changes 98 | 99 | - aa0729b: Add upgrade key to plugins 100 | 101 | ## 0.9.2 102 | 103 | ### Patch Changes 104 | 105 | - 0564669: remove trailing slashes in endpoints 106 | 107 | ## 0.9.1 108 | 109 | ### Patch Changes 110 | 111 | - a38c6df: Re-added custom data object in websocket message 112 | 113 | ## 0.9.0 114 | 115 | ### Minor Changes 116 | 117 | - ebc7f00: Update to work with Cat v1.4.0 118 | 119 | ## 0.8.1 120 | 121 | ### Patch Changes 122 | 123 | - b195a49: Fixed response of conversation history endpoint 124 | 125 | ## 0.8.0 126 | 127 | ### Minor Changes 128 | 129 | - 90d2696: 130 | - Added endpoint to install from registry. 131 | - Removed everything related to prompt settings. 132 | - Fixed authKey change behaviour. 133 | - Added hooks and tools in plugins schema 134 | - Added endpoint to get conversation history. 135 | - Added endpoint to wipe memory points by metadata. 136 | 137 | ## 0.7.3 138 | 139 | ### Patch Changes 140 | 141 | - 34f7752: Added endpoint for allowed mimetypes 142 | 143 | ## 0.7.2 144 | 145 | ### Patch Changes 146 | 147 | - af856df: Added user id argument in send method 148 | 149 | ## 0.7.1 150 | 151 | ### Patch Changes 152 | 153 | - 16d1ae7: Added link property in JSON Schema 154 | 155 | ## 0.7.0 156 | 157 | ### Minor Changes 158 | 159 | - 65e0659: Sync with new ccat's endpoints 160 | 161 | - Fixed typos 162 | - Added generic to PromptSettings 163 | - Improved endpoints response types 164 | 165 | ## 0.6.2 166 | 167 | ### Patch Changes 168 | 169 | - 6e8b315: Now the port is a number 170 | 171 | ## 0.6.1 172 | 173 | ### Patch Changes 174 | 175 | - c97d9b8: Fixed DefaultPromptSettings exported interface name 176 | 177 | ## 0.6.0 178 | 179 | ### Minor Changes 180 | 181 | - ab329b4: Refactored models 182 | 183 | - Added new plugin settings endpoints 184 | 185 | ## 0.5.1 186 | 187 | ### Patch Changes 188 | 189 | - 9400f12: Sync with Cheshire Cat Core 190 | 191 | ## 0.5.0 192 | 193 | ### Minor Changes 194 | 195 | - 693df12: Added reset method 196 | 197 | - Updated error handling 198 | - Now api getter and websocket can be undefined 199 | - Added summary parameter in file and url upload 200 | 201 | ## 0.4.5 202 | 203 | ### Patch Changes 204 | 205 | - 467c9fe: Sync with cat's backend: 206 | 207 | - Updated /memory/delete endpoint 208 | - Updated packages 209 | 210 | ## 0.4.4 211 | 212 | ### Patch Changes 213 | 214 | - c5fe613: Changed AcceptedFileContentTypes -> AcceptedFileTypes 215 | 216 | - Added accepted memory types 217 | - Added accepted plugin types 218 | 219 | ## 0.4.3 220 | 221 | ### Patch Changes 222 | 223 | - bf53aa8: Privatized unused code in services 224 | 225 | - Added AcceptedFileContentTypes const for file upload 226 | - Added enumator WebSocketState for .readyState 227 | 228 | ## 0.4.2 229 | 230 | ### Patch Changes 231 | 232 | - 9cdfd68: Added possibility to put custom keys in PromptSettings (ex. for plugins) 233 | 234 | - Added documentation for client settings 235 | 236 | ## 0.4.1 237 | 238 | ### Patch Changes 239 | 240 | - 7f7c81f: 241 | - Added setter to change auth key at runtime 242 | - Added getter to get the state of the websocket 243 | - PromptSettings passed in send() are now Partial 244 | 245 | ## 0.4.0 246 | 247 | ### Minor Changes 248 | 249 | - b2b8832: 250 | - Switched from options to single arguments 251 | - Updated types to sync with backend 252 | 253 | ## 0.3.1 254 | 255 | ### Patch Changes 256 | 257 | - 371d3bc: Fixed delete plugin endpoint 258 | 259 | ## 0.3.0 260 | 261 | ### Minor Changes 262 | 263 | - ffec775: 264 | - Documented code 265 | - Fixed typos 266 | - Added WebSocket settings (delay, path, retries, onFailed) 267 | 268 | ## 0.2.3 269 | 270 | ### Patch Changes 271 | 272 | - 41e6da6: Added delete plugin endpoint 273 | 274 | ## 0.2.2 275 | 276 | ### Patch Changes 277 | 278 | - 850bd81: 279 | - Added types for websocket. 280 | - Added eslint. 281 | - Now throwing error codes instead of strings. 282 | 283 | ## 0.2.1 284 | 285 | ### Patch Changes 286 | 287 | - 16b9513: - The default port is now '1865' 288 | - init() now returns the class instance 289 | 290 | ## 0.2.0 291 | 292 | ### Minor Changes 293 | 294 | - 8a9a740: 295 | - Added missing types to services. 296 | - Fixed types for CatClient. 297 | - Exported models from index. 298 | 299 | ## 0.1.1 300 | 301 | ### Patch Changes 302 | 303 | - ab42e0c: The authKey is now optional 304 | 305 | ## 0.1.0 306 | 307 | ### Minor Changes 308 | 309 | - 8389485: Created the Cheshire Cat API Client. 310 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Dany 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | GitHub Stars 3 | 4 | 5 | Discord Server 6 | 7 | 8 | NPM Version 9 | 10 | 11 | NPM Downloads 12 | 13 | 14 | Bundle Size 15 | 16 | 17 | # Cheshire Cat AI API Client 18 | 19 | API Client made in TypeScript to communicate with the [Cheshire Cat AI](https://github.com/cheshire-cat-ai/core).\ 20 | The package provides a class to interface with the Cheshire Cat AI backend.\ 21 | It can be used both in Browser and NodeJS environments. 22 | 23 | Every endpoint is a `CancelablePromise`, which means you can cancel the request if you want. 24 | 25 | ## Installation 26 | 27 | ```bash 28 | npm i ccat-api 29 | # OR 30 | yarn add ccat-api 31 | # OR 32 | pnpm i ccat-api 33 | # OR 34 | bun i ccat-api 35 | ``` 36 | 37 | ## Getting started 38 | 39 | To set up the client, you must first import the `CatClient` class: 40 | 41 | ```ts 42 | import { CatClient } from 'ccat-api' 43 | 44 | const cat = new CatClient({ 45 | host: 'localhost', 46 | userId: 'user', 47 | //... other settings 48 | }) 49 | 50 | cat.send('Hello from a user!') // this will send a message to the /ws/user 51 | 52 | cat.userId = 'new_user' 53 | 54 | cat.send('Hello from a new user!') // this will send a message to the /ws/new_user 55 | ``` 56 | 57 | ## Client settings 58 | 59 | **CCAT_API_KEY**, **CCAT_CORE_HOST**, **CCAT_CORE_PORT** and **CCAT_CORE_USE_SECURE_PROTOCOLS** refer to the CCAT Core [.env file](https://github.com/cheshire-cat-ai/core/blob/main/.env.example). 60 | 61 | | **Property** | **Type** | **Default** | **Description** | 62 | |:--------------:|:--------:|:------------:|:--------------------------------------------------------------------------------:| 63 | | **host** | string | **Required** | The same of **CCAT_CORE_HOST** | 64 | | **credential** | string | undefined | The same of **CCAT_API_KEY** or the JWT token | 65 | | **port** | number | 1865 | The same of the **CCAT_CORE_PORT** | 66 | | **secure** | boolean | false | The same of the **CCAT_CORE_USE_SECURE_PROTOCOLS** | 67 | | **user** | string | 'user' | The user ID to use for the WebSocket and the API client | 68 | | **instant** | boolean | true | Instantly initialize the WebSocket and the API client, or later with **.init()** | 69 | | **timeout** | number | 10000 | Timeout for the endpoints, in milliseconds | 70 | | **ws** | string | undefined | An object of type [WebSocketSettings](#websocket-settings) | 71 | 72 | ### WebSocket settings 73 | 74 | | **Property** | **Type** | **Default** | **Description** | 75 | |:------------:|:--------:|:-----------:|:---------------------------------------------------------:| 76 | | **retries** | number | 3 | The maximum number of retries before calling **onFailed** | 77 | | **delay** | number | 3000 | The delay for reconnect, in milliseconds | 78 | | **onFailed** | function | undefined | The function to call after failing all the retries | 79 | 80 | Then, for example, you can configure the LLM like this: 81 | 82 | ```ts 83 | cat.api.llm.upsertLlmSetting('LLMOpenAIConfig', { 84 | openai_api_key: 'OPEN_API_KEY' 85 | }) 86 | ``` 87 | 88 | To send a message to the cat, you can: 89 | 90 | ```ts 91 | cat.send('Hello my friend!') 92 | ``` 93 | 94 | You can listen to the WebSocket events: 95 | 96 | ```ts 97 | cat.onConnected(() => { 98 | console.log('Socket connected') 99 | }).onMessage(msg => { 100 | console.log(msg) 101 | }).onError((err, e) => { 102 | console.error(err, e) 103 | }).onDisconnected(() => { 104 | console.log('Socket disconnected') 105 | }) 106 | ``` 107 | 108 | For example, you can get the list of plugins like this: 109 | 110 | ```ts 111 | cat.api.plugins.listAvailablePlugins().then(plugins => { 112 | console.log(plugins) 113 | }) 114 | ``` 115 | 116 | ## Credits 117 | 118 | Made for the [Cheshire Cat AI](https://github.com/cheshire-cat-ai) organization. 119 | 120 | This was possible thanks to [openapi-typescript-codegen](https://github.com/ferdikoomen/openapi-typescript-codegen). 121 | -------------------------------------------------------------------------------- /api/CCatAPI.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { BaseHttpRequest } from './core/BaseHttpRequest'; 6 | import type { OpenAPIConfig } from './core/OpenAPI'; 7 | import { AxiosHttpRequest } from './core/AxiosHttpRequest'; 8 | import { AuthHandlerService } from './services/AuthHandlerService'; 9 | import { EmbedderService } from './services/EmbedderService'; 10 | import { LlmService } from './services/LlmService'; 11 | import { MemoryService } from './services/MemoryService'; 12 | import { PluginsService } from './services/PluginsService'; 13 | import { RabbitHoleService } from './services/RabbitHoleService'; 14 | import { SettingsService } from './services/SettingsService'; 15 | import { StatusService } from './services/StatusService'; 16 | import { UserAuthService } from './services/UserAuthService'; 17 | import { UsersService } from './services/UsersService'; 18 | type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest; 19 | export class CCatAPI { 20 | public readonly authHandler: AuthHandlerService; 21 | public readonly embedder: EmbedderService; 22 | public readonly llm: LlmService; 23 | public readonly memory: MemoryService; 24 | public readonly plugins: PluginsService; 25 | public readonly rabbitHole: RabbitHoleService; 26 | public readonly settings: SettingsService; 27 | public readonly status: StatusService; 28 | public readonly userAuth: UserAuthService; 29 | public readonly users: UsersService; 30 | public readonly request: BaseHttpRequest; 31 | constructor(config?: Partial, HttpRequest: HttpRequestConstructor = AxiosHttpRequest) { 32 | this.request = new HttpRequest({ 33 | BASE: config?.BASE ?? '', 34 | VERSION: config?.VERSION ?? '1.6.2', 35 | WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false, 36 | CREDENTIALS: config?.CREDENTIALS ?? 'include', 37 | TOKEN: config?.TOKEN, 38 | USERNAME: config?.USERNAME, 39 | PASSWORD: config?.PASSWORD, 40 | HEADERS: config?.HEADERS, 41 | ENCODE_PATH: config?.ENCODE_PATH, 42 | }); 43 | this.authHandler = new AuthHandlerService(this.request); 44 | this.embedder = new EmbedderService(this.request); 45 | this.llm = new LlmService(this.request); 46 | this.memory = new MemoryService(this.request); 47 | this.plugins = new PluginsService(this.request); 48 | this.rabbitHole = new RabbitHoleService(this.request); 49 | this.settings = new SettingsService(this.request); 50 | this.status = new StatusService(this.request); 51 | this.userAuth = new UserAuthService(this.request); 52 | this.users = new UsersService(this.request); 53 | } 54 | } 55 | 56 | -------------------------------------------------------------------------------- /api/client.ts: -------------------------------------------------------------------------------- 1 | import WebSocket from 'isomorphic-ws' 2 | import { CCatAPI } from './CCatAPI' 3 | import { 4 | SocketResponse, SocketError, 5 | WebSocketState, WebSocketSettings, 6 | isMessageResponse, CatSettings, 7 | SocketRequest, 8 | isTokenResponse, 9 | } from './utils' 10 | 11 | /** 12 | * The class to communicate with the Cheshire Cat AI 13 | */ 14 | export class CatClient { 15 | private config!: CatSettings 16 | private apiClient: CCatAPI | undefined 17 | private ws: WebSocket | undefined 18 | private connectedHandler?: () => void 19 | private disconnectedHandler?: () => void 20 | private messageHandler?: (data: SocketResponse) => void 21 | private errorHandler?: (error: SocketError, event?: WebSocket.ErrorEvent) => void 22 | private explicitlyClosed = false 23 | private retried = 0 24 | 25 | /** 26 | * Initialize the class with the specified settings 27 | * @param settings The settings to pass 28 | */ 29 | constructor(settings: CatSettings) { 30 | this.config = { 31 | secure: false, 32 | instant: true, 33 | timeout: 10000, 34 | port: 1865, 35 | userId: 'user', 36 | ...settings 37 | } 38 | if (this.config.instant) this.init() 39 | } 40 | 41 | private initWebSocket() { 42 | const wsConfig = this.config.ws = { 43 | delay: 3000, 44 | retries: 3, 45 | ...this.config.ws 46 | } satisfies WebSocketSettings 47 | const userId = this.config.userId ?? 'user' 48 | const url = this.url.replace(/http/g, 'ws') 49 | const query = this.config.credential ? `?token=${this.config.credential}` : '' 50 | this.ws = new WebSocket(`${url}/ws/${userId}${query}`) 51 | this.ws.onopen = () => { 52 | this.retried = 0 53 | this.connectedHandler?.() 54 | } 55 | this.ws.onclose = () => { 56 | if (!this.explicitlyClosed) { 57 | this.retried += 1 58 | if (wsConfig.retries < 0 || this.retried < wsConfig.retries) { 59 | setTimeout(() => this.initWebSocket(), wsConfig.delay) 60 | } else wsConfig.onFailed?.({ 61 | name: 'FailedRetry', 62 | description: `Failed to connect WebSocket after ${wsConfig.retries} retries.` 63 | }) 64 | } 65 | this.disconnectedHandler?.() 66 | } 67 | this.ws.onmessage = (event) => { 68 | if (typeof event.data != 'string') return 69 | const data = JSON.parse(event.data) as SocketError | SocketResponse 70 | if (isMessageResponse(data)) { 71 | this.messageHandler?.(data) 72 | return 73 | } else if (isTokenResponse(data)) { 74 | this.messageHandler?.(data) 75 | return 76 | } 77 | this.errorHandler?.(data) 78 | } 79 | this.ws.onerror = (event) => { 80 | this.errorHandler?.({ 81 | name: 'SocketError', 82 | description: 'Something went wrong while connecting to the server' 83 | }, event) 84 | } 85 | } 86 | 87 | /** 88 | * Resets the current `CatClient` instance. 89 | * @returns The updated `CatClient` instance. 90 | */ 91 | reset(): CatClient { 92 | this.retried = 0 93 | this.close() 94 | this.ws = undefined 95 | this.apiClient = undefined 96 | return this 97 | } 98 | 99 | /** 100 | * Initialize the WebSocket and the API Client 101 | * @returns The current `CatClient` class instance 102 | */ 103 | init(): CatClient { 104 | if (!this.ws && !this.apiClient) { 105 | this.initWebSocket() 106 | this.apiClient = new CCatAPI({ 107 | BASE: `${this.url}`, 108 | HEADERS: { 109 | ...this.config.credential ? { 110 | 'access_token': this.config.credential, 111 | 'Authorization': `Bearer ${this.config.credential}`, 112 | } : {}, 113 | 'user_id': this.config.userId ?? 'user', 114 | } 115 | }) 116 | } 117 | return this 118 | } 119 | 120 | /** 121 | * Sends a message to the Cat through the WebSocket connection. 122 | * @param msg The message to send to the Cat. 123 | * @param userId The ID of the user sending the message. Defaults to "user". 124 | * @throws If the message does not contain text, audio or image. 125 | * @returns The `CatClient` instance. 126 | */ 127 | send(msg: SocketRequest, userId?: string): CatClient { 128 | if (this.ws?.readyState !== WebSocket.OPEN) { 129 | this.errorHandler?.({ 130 | name: 'SocketClosed', 131 | description: 'The connection to the server was closed' 132 | }) 133 | return this 134 | } 135 | if ('text' in msg || 'audio' in msg || 'image' in msg) { 136 | const jsonMessage = JSON.stringify({ 137 | ...msg, 138 | user_id: userId ?? (this.config.userId ?? 'user'), 139 | }) 140 | this.ws.send(jsonMessage) 141 | } else throw new Error('The message argument must contain either text, audio or image.') 142 | return this 143 | } 144 | 145 | /** 146 | * @returns The API Client 147 | */ 148 | get api(): CCatAPI | undefined { 149 | return this.apiClient 150 | } 151 | 152 | /** 153 | * Setter for the authentication key or token used by the client. This will also reset the client. 154 | * @param key The authentication key or token to be set. 155 | */ 156 | set credential(key: string | undefined) { 157 | this.config.credential = key 158 | this.reset().init() 159 | } 160 | 161 | /** 162 | * Setter for the user ID used by the client. This will also reset the client. 163 | * @param user The user ID to be set. 164 | */ 165 | set userId(user: string) { 166 | this.config.userId = user 167 | this.reset().init() 168 | } 169 | 170 | /** 171 | * Closes the WebSocket connection. 172 | * @returns The `CatClient` instance. 173 | */ 174 | close(): CatClient { 175 | this.ws?.close() 176 | this.explicitlyClosed = true 177 | return this 178 | } 179 | 180 | /** 181 | * Returns the current state of the WebSocket connection. 182 | * @returns The WebSocketState enum value representing the current state of the WebSocket connection. 183 | */ 184 | get socketState(): WebSocketState { 185 | return this.ws?.readyState ?? WebSocketState.CLOSED 186 | } 187 | 188 | /** 189 | * Calls the handler when the WebSocket is connected 190 | * @param handler The function to call 191 | * @returns The current `CatClient` class instance 192 | */ 193 | onConnected(handler: () => void): CatClient { 194 | this.connectedHandler = handler 195 | return this 196 | } 197 | 198 | /** 199 | * Calls the handler when the WebSocket is disconnected 200 | * @param handler The function to call 201 | * @returns The current `CatClient` class instance 202 | */ 203 | onDisconnected(handler: () => void): CatClient { 204 | this.disconnectedHandler = handler 205 | return this 206 | } 207 | 208 | /** 209 | * Calls the handler when a new message arrives from the WebSocket 210 | * @param handler The function to call 211 | * @returns The current `CatClient` class instance 212 | */ 213 | onMessage(handler: (data: SocketResponse) => void): CatClient { 214 | this.messageHandler = handler 215 | return this 216 | } 217 | 218 | /** 219 | * Calls the handler when the WebSocket catches an exception 220 | * @param handler The function to call 221 | * @returns The current `CatClient` class instance 222 | */ 223 | onError(handler: (error: SocketError, event?: WebSocket.ErrorEvent) => void): CatClient { 224 | this.errorHandler = handler 225 | return this 226 | } 227 | 228 | private get url() { 229 | return `http${this.config.secure ? 's' : ''}:// 230 | ${this.config.host} 231 | ${this.config.port ? `:${this.config.port}` : ''} 232 | `.replace(/\s/g, '') 233 | } 234 | } -------------------------------------------------------------------------------- /api/core/ApiError.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { ApiRequestOptions } from './ApiRequestOptions'; 6 | import type { ApiResult } from './ApiResult'; 7 | 8 | export class ApiError extends Error { 9 | public readonly url: string; 10 | public readonly status: number; 11 | public readonly statusText: string; 12 | public readonly body: any; 13 | public readonly request: ApiRequestOptions; 14 | 15 | constructor(request: ApiRequestOptions, response: ApiResult, message: string) { 16 | super(message); 17 | 18 | this.name = 'ApiError'; 19 | this.url = response.url; 20 | this.status = response.status; 21 | this.statusText = response.statusText; 22 | this.body = response.body; 23 | this.request = request; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /api/core/ApiRequestOptions.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type ApiRequestOptions = { 6 | readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'; 7 | readonly url: string; 8 | readonly path?: Record; 9 | readonly cookies?: Record; 10 | readonly headers?: Record; 11 | readonly query?: Record; 12 | readonly formData?: Record; 13 | readonly body?: any; 14 | readonly mediaType?: string; 15 | readonly responseHeader?: string; 16 | readonly errors?: Record; 17 | }; 18 | -------------------------------------------------------------------------------- /api/core/ApiResult.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type ApiResult = { 6 | readonly url: string; 7 | readonly ok: boolean; 8 | readonly status: number; 9 | readonly statusText: string; 10 | readonly body: any; 11 | }; 12 | -------------------------------------------------------------------------------- /api/core/AxiosHttpRequest.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { ApiRequestOptions } from './ApiRequestOptions'; 6 | import { BaseHttpRequest } from './BaseHttpRequest'; 7 | import type { CancelablePromise } from './CancelablePromise'; 8 | import type { OpenAPIConfig } from './OpenAPI'; 9 | import { request as __request } from './request'; 10 | 11 | export class AxiosHttpRequest extends BaseHttpRequest { 12 | 13 | constructor(config: OpenAPIConfig) { 14 | super(config); 15 | } 16 | 17 | /** 18 | * Request method 19 | * @param options The request options from the service 20 | * @returns CancelablePromise 21 | * @throws ApiError 22 | */ 23 | public override request(options: ApiRequestOptions): CancelablePromise { 24 | return __request(this.config, options); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /api/core/BaseHttpRequest.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { ApiRequestOptions } from './ApiRequestOptions'; 6 | import type { CancelablePromise } from './CancelablePromise'; 7 | import type { OpenAPIConfig } from './OpenAPI'; 8 | 9 | export abstract class BaseHttpRequest { 10 | 11 | constructor(public readonly config: OpenAPIConfig) {} 12 | 13 | public abstract request(options: ApiRequestOptions): CancelablePromise; 14 | } 15 | -------------------------------------------------------------------------------- /api/core/CancelablePromise.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export class CancelError extends Error { 6 | 7 | constructor(message: string) { 8 | super(message); 9 | this.name = 'CancelError'; 10 | } 11 | 12 | public get isCancelled(): boolean { 13 | return true; 14 | } 15 | } 16 | 17 | export interface OnCancel { 18 | readonly isResolved: boolean; 19 | readonly isRejected: boolean; 20 | readonly isCancelled: boolean; 21 | 22 | (cancelHandler: () => void): void; 23 | } 24 | 25 | export class CancelablePromise implements Promise { 26 | #isResolved: boolean; 27 | #isRejected: boolean; 28 | #isCancelled: boolean; 29 | readonly #cancelHandlers: (() => void)[]; 30 | readonly #promise: Promise; 31 | #resolve?: (value: T | PromiseLike) => void; 32 | #reject?: (reason?: any) => void; 33 | 34 | constructor( 35 | executor: ( 36 | resolve: (value: T | PromiseLike) => void, 37 | reject: (reason?: any) => void, 38 | onCancel: OnCancel 39 | ) => void 40 | ) { 41 | this.#isResolved = false; 42 | this.#isRejected = false; 43 | this.#isCancelled = false; 44 | this.#cancelHandlers = []; 45 | this.#promise = new Promise((resolve, reject) => { 46 | this.#resolve = resolve; 47 | this.#reject = reject; 48 | 49 | const onResolve = (value: T | PromiseLike): void => { 50 | if (this.#isResolved || this.#isRejected || this.#isCancelled) { 51 | return; 52 | } 53 | this.#isResolved = true; 54 | if (this.#resolve) this.#resolve(value); 55 | }; 56 | 57 | const onReject = (reason?: any): void => { 58 | if (this.#isResolved || this.#isRejected || this.#isCancelled) { 59 | return; 60 | } 61 | this.#isRejected = true; 62 | if (this.#reject) this.#reject(reason); 63 | }; 64 | 65 | const onCancel = (cancelHandler: () => void): void => { 66 | if (this.#isResolved || this.#isRejected || this.#isCancelled) { 67 | return; 68 | } 69 | this.#cancelHandlers.push(cancelHandler); 70 | }; 71 | 72 | Object.defineProperty(onCancel, 'isResolved', { 73 | get: (): boolean => this.#isResolved, 74 | }); 75 | 76 | Object.defineProperty(onCancel, 'isRejected', { 77 | get: (): boolean => this.#isRejected, 78 | }); 79 | 80 | Object.defineProperty(onCancel, 'isCancelled', { 81 | get: (): boolean => this.#isCancelled, 82 | }); 83 | 84 | return executor(onResolve, onReject, onCancel as OnCancel); 85 | }); 86 | } 87 | 88 | get [Symbol.toStringTag]() { 89 | return "Cancellable Promise"; 90 | } 91 | 92 | public then( 93 | onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, 94 | onRejected?: ((reason: any) => TResult2 | PromiseLike) | null 95 | ): Promise { 96 | return this.#promise.then(onFulfilled, onRejected); 97 | } 98 | 99 | public catch( 100 | onRejected?: ((reason: any) => TResult | PromiseLike) | null 101 | ): Promise { 102 | return this.#promise.catch(onRejected); 103 | } 104 | 105 | public finally(onFinally?: (() => void) | null): Promise { 106 | return this.#promise.finally(onFinally); 107 | } 108 | 109 | public cancel(): void { 110 | if (this.#isResolved || this.#isRejected || this.#isCancelled) { 111 | return; 112 | } 113 | this.#isCancelled = true; 114 | if (this.#cancelHandlers.length) { 115 | try { 116 | for (const cancelHandler of this.#cancelHandlers) { 117 | cancelHandler(); 118 | } 119 | } catch (error) { 120 | console.warn('Cancellation threw an error', error); 121 | return; 122 | } 123 | } 124 | this.#cancelHandlers.length = 0; 125 | if (this.#reject) this.#reject(new CancelError('Request aborted')); 126 | } 127 | 128 | public get isCancelled(): boolean { 129 | return this.#isCancelled; 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /api/core/OpenAPI.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { ApiRequestOptions } from './ApiRequestOptions'; 6 | 7 | type Resolver = (options: ApiRequestOptions) => Promise; 8 | type Headers = Record; 9 | 10 | export type OpenAPIConfig = { 11 | BASE: string; 12 | VERSION: string; 13 | WITH_CREDENTIALS: boolean; 14 | CREDENTIALS: 'include' | 'omit' | 'same-origin'; 15 | TOKEN?: string | Resolver | undefined; 16 | USERNAME?: string | Resolver | undefined; 17 | PASSWORD?: string | Resolver | undefined; 18 | HEADERS?: Headers | Resolver | undefined; 19 | ENCODE_PATH?: ((path: string) => string) | undefined; 20 | }; 21 | 22 | export const OpenAPI: OpenAPIConfig = { 23 | BASE: '', 24 | VERSION: '1.6.2', 25 | WITH_CREDENTIALS: false, 26 | CREDENTIALS: 'include', 27 | TOKEN: undefined, 28 | USERNAME: undefined, 29 | PASSWORD: undefined, 30 | HEADERS: undefined, 31 | ENCODE_PATH: undefined, 32 | }; 33 | -------------------------------------------------------------------------------- /api/core/request.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import axios from 'axios'; 6 | import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'; 7 | import FormData from 'form-data'; 8 | 9 | import { ApiError } from './ApiError'; 10 | import type { ApiRequestOptions } from './ApiRequestOptions'; 11 | import type { ApiResult } from './ApiResult'; 12 | import { CancelablePromise } from './CancelablePromise'; 13 | import type { OnCancel } from './CancelablePromise'; 14 | import type { OpenAPIConfig } from './OpenAPI'; 15 | 16 | export const isDefined = (value: T | null | undefined): value is Exclude => { 17 | return value !== undefined && value !== null; 18 | }; 19 | 20 | export const isString = (value: any): value is string => { 21 | return typeof value === 'string'; 22 | }; 23 | 24 | export const isStringWithValue = (value: any): value is string => { 25 | return isString(value) && value !== ''; 26 | }; 27 | 28 | export const isBlob = (value: any): value is Blob => { 29 | return ( 30 | typeof value === 'object' && 31 | typeof value.type === 'string' && 32 | typeof value.stream === 'function' && 33 | typeof value.arrayBuffer === 'function' && 34 | typeof value.constructor === 'function' && 35 | typeof value.constructor.name === 'string' && 36 | /^(Blob|File)$/.test(value.constructor.name) && 37 | /^(Blob|File)$/.test(value[Symbol.toStringTag]) 38 | ); 39 | }; 40 | 41 | export const isFormData = (value: any): value is FormData => { 42 | return value instanceof FormData; 43 | }; 44 | 45 | export const isSuccess = (status: number): boolean => { 46 | return status >= 200 && status < 300; 47 | }; 48 | 49 | export const base64 = (str: string): string => { 50 | try { 51 | return btoa(str); 52 | } catch (err) { 53 | // @ts-ignore 54 | return Buffer.from(str).toString('base64'); 55 | } 56 | }; 57 | 58 | export const getQueryString = (params: Record): string => { 59 | const qs: string[] = []; 60 | 61 | const append = (key: string, value: any) => { 62 | qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); 63 | }; 64 | 65 | const process = (key: string, value: any) => { 66 | if (isDefined(value)) { 67 | if (Array.isArray(value)) { 68 | value.forEach(v => { 69 | process(key, v); 70 | }); 71 | } else if (typeof value === 'object') { 72 | Object.entries(value).forEach(([k, v]) => { 73 | process(`${key}[${k}]`, v); 74 | }); 75 | } else { 76 | append(key, value); 77 | } 78 | } 79 | }; 80 | 81 | Object.entries(params).forEach(([key, value]) => { 82 | process(key, value); 83 | }); 84 | 85 | if (qs.length > 0) { 86 | return `?${qs.join('&')}`; 87 | } 88 | 89 | return ''; 90 | }; 91 | 92 | const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { 93 | const encoder = config.ENCODE_PATH || encodeURI; 94 | 95 | const path = options.url 96 | .replace('{api-version}', config.VERSION) 97 | .replace(/{(.*?)}/g, (substring: string, group: string) => { 98 | if (options.path?.hasOwnProperty(group)) { 99 | return encoder(String(options.path[group])); 100 | } 101 | return substring; 102 | }); 103 | 104 | const url = `${config.BASE}${path}`; 105 | if (options.query) { 106 | return `${url}${getQueryString(options.query)}`; 107 | } 108 | return url; 109 | }; 110 | 111 | export const getFormData = (options: ApiRequestOptions): FormData | undefined => { 112 | if (options.formData) { 113 | const formData = new FormData(); 114 | 115 | const process = (key: string, value: any) => { 116 | if (isString(value) || isBlob(value)) { 117 | formData.append(key, value); 118 | } else { 119 | formData.append(key, JSON.stringify(value)); 120 | } 121 | }; 122 | 123 | Object.entries(options.formData) 124 | .filter(([_, value]) => isDefined(value)) 125 | .forEach(([key, value]) => { 126 | if (Array.isArray(value)) { 127 | value.forEach(v => process(key, v)); 128 | } else { 129 | process(key, value); 130 | } 131 | }); 132 | 133 | return formData; 134 | } 135 | return undefined; 136 | }; 137 | 138 | type Resolver = (options: ApiRequestOptions) => Promise; 139 | 140 | export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { 141 | if (typeof resolver === 'function') { 142 | return (resolver as Resolver)(options); 143 | } 144 | return resolver; 145 | }; 146 | 147 | export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions, formData?: FormData): Promise> => { 148 | const [token, username, password, additionalHeaders] = await Promise.all([ 149 | resolve(options, config.TOKEN), 150 | resolve(options, config.USERNAME), 151 | resolve(options, config.PASSWORD), 152 | resolve(options, config.HEADERS), 153 | ]); 154 | 155 | const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {} 156 | 157 | const headers = Object.entries({ 158 | Accept: 'application/json', 159 | ...additionalHeaders, 160 | ...options.headers, 161 | ...formHeaders, 162 | }) 163 | .filter(([_, value]) => isDefined(value)) 164 | .reduce((headers, [key, value]) => ({ 165 | ...headers, 166 | [key]: String(value), 167 | }), {} as Record); 168 | 169 | if (isStringWithValue(token)) { 170 | headers['Authorization'] = `Bearer ${token}`; 171 | } 172 | 173 | if (isStringWithValue(username) && isStringWithValue(password)) { 174 | const credentials = base64(`${username}:${password}`); 175 | headers['Authorization'] = `Basic ${credentials}`; 176 | } 177 | 178 | if (options.body !== undefined) { 179 | if (options.mediaType) { 180 | headers['Content-Type'] = options.mediaType; 181 | } else if (isBlob(options.body)) { 182 | headers['Content-Type'] = options.body.type || 'application/octet-stream'; 183 | } else if (isString(options.body)) { 184 | headers['Content-Type'] = 'text/plain'; 185 | } else if (!isFormData(options.body)) { 186 | headers['Content-Type'] = 'application/json'; 187 | } 188 | } 189 | 190 | return headers; 191 | }; 192 | 193 | export const getRequestBody = (options: ApiRequestOptions): any => { 194 | if (options.body) { 195 | return options.body; 196 | } 197 | return undefined; 198 | }; 199 | 200 | export const sendRequest = async ( 201 | config: OpenAPIConfig, 202 | options: ApiRequestOptions, 203 | url: string, 204 | body: any, 205 | formData: FormData | undefined, 206 | headers: Record, 207 | onCancel: OnCancel, 208 | axiosClient: AxiosInstance 209 | ): Promise> => { 210 | const source = axios.CancelToken.source(); 211 | 212 | const requestConfig: AxiosRequestConfig = { 213 | url, 214 | headers, 215 | data: body ?? formData, 216 | method: options.method, 217 | withCredentials: config.WITH_CREDENTIALS, 218 | withXSRFToken: config.CREDENTIALS === 'include' ? config.WITH_CREDENTIALS : false, 219 | cancelToken: source.token, 220 | }; 221 | 222 | onCancel(() => source.cancel('The user aborted a request.')); 223 | 224 | try { 225 | return await axiosClient.request(requestConfig); 226 | } catch (error) { 227 | const axiosError = error as AxiosError; 228 | if (axiosError.response) { 229 | return axiosError.response; 230 | } 231 | throw error; 232 | } 233 | }; 234 | 235 | export const getResponseHeader = (response: AxiosResponse, responseHeader?: string): string | undefined => { 236 | if (responseHeader) { 237 | const content = response.headers[responseHeader]; 238 | if (isString(content)) { 239 | return content; 240 | } 241 | } 242 | return undefined; 243 | }; 244 | 245 | export const getResponseBody = (response: AxiosResponse): any => { 246 | if (response.status !== 204) { 247 | return response.data; 248 | } 249 | return undefined; 250 | }; 251 | 252 | export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { 253 | const errors: Record = { 254 | 400: 'Bad Request', 255 | 401: 'Unauthorized', 256 | 403: 'Forbidden', 257 | 404: 'Not Found', 258 | 500: 'Internal Server Error', 259 | 502: 'Bad Gateway', 260 | 503: 'Service Unavailable', 261 | ...options.errors, 262 | } 263 | 264 | const error = errors[result.status]; 265 | if (error) { 266 | throw new ApiError(options, result, error); 267 | } 268 | 269 | if (!result.ok) { 270 | const errorStatus = result.status ?? 'unknown'; 271 | const errorStatusText = result.statusText ?? 'unknown'; 272 | const errorBody = (() => { 273 | try { 274 | return JSON.stringify(result.body, null, 2); 275 | } catch (e) { 276 | return undefined; 277 | } 278 | })(); 279 | 280 | throw new ApiError(options, result, 281 | `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` 282 | ); 283 | } 284 | }; 285 | 286 | /** 287 | * Request method 288 | * @param config The OpenAPI configuration object 289 | * @param options The request options from the service 290 | * @param axiosClient The axios client instance to use 291 | * @returns CancelablePromise 292 | * @throws ApiError 293 | */ 294 | export const request = (config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise => { 295 | return new CancelablePromise(async (resolve, reject, onCancel) => { 296 | try { 297 | const url = getUrl(config, options); 298 | const formData = getFormData(options); 299 | const body = getRequestBody(options); 300 | const headers = await getHeaders(config, options, formData); 301 | 302 | if (!onCancel.isCancelled) { 303 | const response = await sendRequest(config, options, url, body, formData, headers, onCancel, axiosClient); 304 | const responseBody = getResponseBody(response); 305 | const responseHeader = getResponseHeader(response, options.responseHeader); 306 | 307 | const result: ApiResult = { 308 | url, 309 | ok: isSuccess(response.status), 310 | status: response.status, 311 | statusText: response.statusText, 312 | body: responseHeader ?? responseBody, 313 | }; 314 | 315 | catchErrorCodes(options, result); 316 | 317 | resolve(result.body); 318 | } 319 | } catch (error) { 320 | reject(error); 321 | } 322 | }); 323 | }; 324 | -------------------------------------------------------------------------------- /api/models/AuthPermission.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type AuthPermission = 'WRITE' | 'EDIT' | 'LIST' | 'READ' | 'DELETE'; 6 | -------------------------------------------------------------------------------- /api/models/AuthResource.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type AuthResource = 'STATUS' | 'MEMORY' | 'CONVERSATION' | 'SETTINGS' | 'LLM' | 'EMBEDDER' | 'AUTH_HANDLER' | 'USERS' | 'UPLOAD' | 'PLUGINS' | 'STATIC'; 6 | -------------------------------------------------------------------------------- /api/models/BodyInstallPlugin.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type BodyInstallPlugin = { 6 | file: Blob; 7 | }; 8 | 9 | -------------------------------------------------------------------------------- /api/models/BodyUploadFile.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type BodyUploadFile = { 6 | file: Blob; 7 | /** 8 | * Maximum length of each chunk after the document is split (in tokens) 9 | */ 10 | chunk_size?: (number | null); 11 | /** 12 | * Chunk overlap (in tokens) 13 | */ 14 | chunk_overlap?: (number | null); 15 | /** 16 | * Metadata to be stored with each chunk (e.g. author, category, etc.). Since we are passing this along side form data, must be a JSON string. 17 | */ 18 | metadata?: string; 19 | }; 20 | 21 | -------------------------------------------------------------------------------- /api/models/BodyUploadMemory.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type BodyUploadMemory = { 6 | file: Blob; 7 | }; 8 | 9 | -------------------------------------------------------------------------------- /api/models/BodyUploadUrl.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type BodyUploadUrl = { 6 | /** 7 | * URL of the website to which you want to save the content 8 | */ 9 | url: string; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /api/models/CatMessage.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { MessageWhy } from './MessageWhy'; 6 | export type CatMessage = { 7 | content: string; 8 | user_id: string; 9 | type?: string; 10 | why?: (MessageWhy | null); 11 | }; 12 | 13 | -------------------------------------------------------------------------------- /api/models/Collection.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type Collection = { 6 | name: string; 7 | vectors_count: number; 8 | }; 9 | 10 | -------------------------------------------------------------------------------- /api/models/CollectionData.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { Metadata } from './Metadata'; 6 | export type CollectionData = { 7 | page_content: string; 8 | metadata: Metadata; 9 | id: string; 10 | score: number; 11 | vector: Array; 12 | }; 13 | 14 | -------------------------------------------------------------------------------- /api/models/CollectionsList.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { Collection } from './Collection'; 6 | export type CollectionsList = { 7 | collections: Array; 8 | }; 9 | 10 | -------------------------------------------------------------------------------- /api/models/ConversationMessage.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type ConversationMessage = { 6 | who: string; 7 | message: string; 8 | why?: Record; 9 | when: number; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /api/models/DeleteResponse.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type DeleteResponse = { 6 | deleted: (string | boolean | Record | any[]); 7 | }; 8 | 9 | -------------------------------------------------------------------------------- /api/models/FileResponse.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type FileResponse = { 6 | filename: string; 7 | content_type: string; 8 | info: string; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /api/models/HTTPValidationError.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type HTTPValidationError = { 6 | detail?: { 7 | error: string; 8 | }; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /api/models/JWTResponse.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type JWTResponse = { 6 | access_token: string; 7 | token_type?: string; 8 | }; 9 | 10 | -------------------------------------------------------------------------------- /api/models/MemoryRecall.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { QueryData } from './QueryData'; 6 | import type { VectorsData } from './VectorsData'; 7 | export type MemoryRecall = { 8 | query: QueryData; 9 | vectors: VectorsData; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /api/models/MessageWhy.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | /** 6 | * Class for wrapping message why 7 | * 8 | * Variables: 9 | * input (str): input message 10 | * intermediate_steps (List): intermediate steps 11 | * memory (dict): memory 12 | */ 13 | export type MessageWhy = { 14 | input: string; 15 | intermediate_steps: Array; 16 | memory: Record; 17 | }; 18 | 19 | -------------------------------------------------------------------------------- /api/models/Metadata.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type Metadata = { 6 | source: string; 7 | when: number; 8 | docstring?: string; 9 | name?: string; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /api/models/Plugin.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type Plugin = { 6 | id: string; 7 | name: string; 8 | description: string; 9 | author_name: string; 10 | author_url: string; 11 | plugin_url: string; 12 | tags: string; 13 | thumb: string; 14 | version: string; 15 | min_cat_version?: string; 16 | max_cat_version?: string; 17 | active?: boolean; 18 | url?: string; 19 | upgrade?: string; 20 | hooks?: Array<{ 21 | name: string; 22 | priority: number; 23 | }>; 24 | tools?: Array<{ 25 | name: string; 26 | }>; 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /api/models/PluginsList.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { Plugin } from './Plugin'; 6 | export type PluginsList = { 7 | filters: { 8 | query?: string | null; 9 | }; 10 | installed: Array; 11 | registry: Array; 12 | }; 13 | 14 | -------------------------------------------------------------------------------- /api/models/QueryData.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type QueryData = { 6 | text: string; 7 | vector: Array; 8 | }; 9 | 10 | -------------------------------------------------------------------------------- /api/models/Setting.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type Setting = { 6 | name: string; 7 | value: Record; 8 | schema?: Record; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /api/models/SettingBody.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type SettingBody = { 6 | name: string; 7 | value: Record; 8 | category?: string; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /api/models/SettingsResponse.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { Setting } from './Setting'; 6 | export type SettingsResponse = { 7 | settings: Array; 8 | selected_configuration?: string; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /api/models/Status.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type Status = { 6 | status: string; 7 | version: string; 8 | }; 9 | 10 | -------------------------------------------------------------------------------- /api/models/UserCreate.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { AuthPermission } from './AuthPermission'; 6 | export type UserCreate = { 7 | username: string; 8 | permissions?: Record>; 9 | password: string; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /api/models/UserCredentials.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type UserCredentials = { 6 | username: string; 7 | password: string; 8 | }; 9 | 10 | -------------------------------------------------------------------------------- /api/models/UserResponse.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { AuthPermission } from './AuthPermission'; 6 | export type UserResponse = { 7 | username: string; 8 | permissions?: Record>; 9 | id: string; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /api/models/UserUpdate.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { AuthPermission } from './AuthPermission'; 6 | export type UserUpdate = { 7 | username?: string; 8 | permissions?: Record>; 9 | password?: string; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /api/models/VectorsData.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { CollectionData } from './CollectionData'; 6 | export type VectorsData = { 7 | embedder: string; 8 | collections: Record>; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /api/models/WebResponse.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | export type WebResponse = { 6 | url: string; 7 | info: string; 8 | }; 9 | 10 | -------------------------------------------------------------------------------- /api/services/AuthHandlerService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { Setting } from '../models/Setting'; 6 | import type { SettingsResponse } from '../models/SettingsResponse'; 7 | import type { CancelablePromise } from '../core/CancelablePromise'; 8 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 9 | export class AuthHandlerService { 10 | constructor(private readonly httpRequest: BaseHttpRequest) {} 11 | /** 12 | * Get Auth Handler Settings 13 | * Get the list of the AuthHandlers 14 | * @returns SettingsResponse Successful Response 15 | * @throws ApiError 16 | */ 17 | public getAuthHandlerSettings(): CancelablePromise { 18 | return this.httpRequest.request({ 19 | method: 'GET', 20 | url: '/auth_handler/settings', 21 | }); 22 | } 23 | /** 24 | * Get Auth Handler Setting 25 | * Get the settings of a specific AuthHandler 26 | * @param authHandlerName 27 | * @returns Setting Successful Response 28 | * @throws ApiError 29 | */ 30 | public getAuthHandlerSetting( 31 | authHandlerName: string, 32 | ): CancelablePromise { 33 | return this.httpRequest.request({ 34 | method: 'GET', 35 | url: '/auth_handler/settings/{auth_handler_name}', 36 | path: { 37 | 'auth_handler_name': authHandlerName, 38 | }, 39 | errors: { 40 | 422: `Validation Error`, 41 | }, 42 | }); 43 | } 44 | /** 45 | * Upsert Authenticator Setting 46 | * Upsert the settings of a specific AuthHandler 47 | * @param authHandlerName 48 | * @param requestBody 49 | * @returns Setting Successful Response 50 | * @throws ApiError 51 | */ 52 | public upsertAuthenticatorSetting( 53 | authHandlerName: string, 54 | requestBody: Record, 55 | ): CancelablePromise { 56 | return this.httpRequest.request({ 57 | method: 'PUT', 58 | url: '/auth_handler/settings/{auth_handler_name}', 59 | path: { 60 | 'auth_handler_name': authHandlerName, 61 | }, 62 | body: requestBody, 63 | mediaType: 'application/json', 64 | errors: { 65 | 422: `Validation Error`, 66 | }, 67 | }); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /api/services/EmbedderService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { Setting } from '../models/Setting'; 6 | import type { SettingsResponse } from '../models/SettingsResponse'; 7 | import type { CancelablePromise } from '../core/CancelablePromise'; 8 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 9 | export class EmbedderService { 10 | constructor(private readonly httpRequest: BaseHttpRequest) {} 11 | /** 12 | * Get Embedders Settings 13 | * Get the list of the Embedders 14 | * @returns SettingsResponse Successful Response 15 | * @throws ApiError 16 | */ 17 | public getEmbeddersSettings(): CancelablePromise { 18 | return this.httpRequest.request({ 19 | method: 'GET', 20 | url: '/embedder/settings', 21 | }); 22 | } 23 | /** 24 | * Get Embedder Settings 25 | * Get settings and schema of the specified Embedder 26 | * @param languageEmbedderName 27 | * @returns Setting Successful Response 28 | * @throws ApiError 29 | */ 30 | public getEmbedderSettings( 31 | languageEmbedderName: string, 32 | ): CancelablePromise { 33 | return this.httpRequest.request({ 34 | method: 'GET', 35 | url: '/embedder/settings/{languageEmbedderName}', 36 | path: { 37 | 'languageEmbedderName': languageEmbedderName, 38 | }, 39 | errors: { 40 | 422: `Validation Error`, 41 | }, 42 | }); 43 | } 44 | /** 45 | * Upsert Embedder Setting 46 | * Upsert the Embedder setting 47 | * @param languageEmbedderName 48 | * @param requestBody 49 | * @returns Setting Successful Response 50 | * @throws ApiError 51 | */ 52 | public upsertEmbedderSetting( 53 | languageEmbedderName: string, 54 | requestBody: Record, 55 | ): CancelablePromise { 56 | return this.httpRequest.request({ 57 | method: 'PUT', 58 | url: '/embedder/settings/{languageEmbedderName}', 59 | path: { 60 | 'languageEmbedderName': languageEmbedderName, 61 | }, 62 | body: requestBody, 63 | mediaType: 'application/json', 64 | errors: { 65 | 422: `Validation Error`, 66 | }, 67 | }); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /api/services/LlmService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { Setting } from '../models/Setting'; 6 | import type { SettingsResponse } from '../models/SettingsResponse'; 7 | import type { CancelablePromise } from '../core/CancelablePromise'; 8 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 9 | export class LlmService { 10 | constructor(private readonly httpRequest: BaseHttpRequest) {} 11 | /** 12 | * Get LLMs Settings 13 | * Get the list of the Large Language Models 14 | * @returns SettingsResponse Successful Response 15 | * @throws ApiError 16 | */ 17 | public getLlmsSettings(): CancelablePromise { 18 | return this.httpRequest.request({ 19 | method: 'GET', 20 | url: '/llm/settings', 21 | }); 22 | } 23 | /** 24 | * Get Llm Settings 25 | * Get settings and schema of the specified Large Language Model 26 | * @param languageModelName 27 | * @returns Setting Successful Response 28 | * @throws ApiError 29 | */ 30 | public getLlmSettings( 31 | languageModelName: string, 32 | ): CancelablePromise { 33 | return this.httpRequest.request({ 34 | method: 'GET', 35 | url: '/llm/settings/{languageModelName}', 36 | path: { 37 | 'languageModelName': languageModelName, 38 | }, 39 | errors: { 40 | 422: `Validation Error`, 41 | }, 42 | }); 43 | } 44 | /** 45 | * Upsert LLM Setting 46 | * Upsert the Large Language Model setting 47 | * @param languageModelName 48 | * @param requestBody 49 | * @returns Setting Successful Response 50 | * @throws ApiError 51 | */ 52 | public upsertLlmSetting( 53 | languageModelName: string, 54 | requestBody: Record, 55 | ): CancelablePromise { 56 | return this.httpRequest.request({ 57 | method: 'PUT', 58 | url: '/llm/settings/{languageModelName}', 59 | path: { 60 | 'languageModelName': languageModelName, 61 | }, 62 | body: requestBody, 63 | mediaType: 'application/json', 64 | errors: { 65 | 422: `Validation Error`, 66 | }, 67 | }); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /api/services/MemoryService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { CollectionsList } from '../models/CollectionsList'; 6 | import type { ConversationMessage } from '../models/ConversationMessage'; 7 | import type { DeleteResponse } from '../models/DeleteResponse'; 8 | import type { MemoryRecall } from '../models/MemoryRecall'; 9 | import type { CancelablePromise } from '../core/CancelablePromise'; 10 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 11 | export class MemoryService { 12 | constructor(private readonly httpRequest: BaseHttpRequest) {} 13 | /** 14 | * Recall Memories From Text 15 | * Search k memories similar to given text. 16 | * @param text Find memories similar to this text. 17 | * @param k How many memories to return. 18 | * @returns MemoryRecall Successful Response 19 | * @throws ApiError 20 | */ 21 | public recallMemoriesFromText( 22 | text: string, 23 | k: number = 100, 24 | ): CancelablePromise { 25 | return this.httpRequest.request({ 26 | method: 'GET', 27 | url: '/memory/recall', 28 | query: { 29 | 'text': text, 30 | 'k': k, 31 | }, 32 | errors: { 33 | 422: `Validation Error`, 34 | }, 35 | }); 36 | } 37 | /** 38 | * Get Collections 39 | * Get list of available collections 40 | * @returns CollectionsList Successful Response 41 | * @throws ApiError 42 | */ 43 | public getCollections(): CancelablePromise { 44 | return this.httpRequest.request({ 45 | method: 'GET', 46 | url: '/memory/collections', 47 | }); 48 | } 49 | /** 50 | * Wipe Collections 51 | * Delete and create all collections 52 | * @returns DeleteResponse Successful Response 53 | * @throws ApiError 54 | */ 55 | public wipeCollections(): CancelablePromise { 56 | return this.httpRequest.request({ 57 | method: 'DELETE', 58 | url: '/memory/collections', 59 | }); 60 | } 61 | /** 62 | * Wipe Single Collection 63 | * Delete and recreate a collection 64 | * @param collectionId 65 | * @returns DeleteResponse Successful Response 66 | * @throws ApiError 67 | */ 68 | public wipeSingleCollection( 69 | collectionId: string, 70 | ): CancelablePromise { 71 | return this.httpRequest.request({ 72 | method: 'DELETE', 73 | url: '/memory/collections/{collection_id}', 74 | path: { 75 | 'collection_id': collectionId, 76 | }, 77 | errors: { 78 | 422: `Validation Error`, 79 | }, 80 | }); 81 | } 82 | /** 83 | * Delete Point In Memory 84 | * Delete specific point in memory 85 | * @param collectionId 86 | * @param memoryId 87 | * @returns DeleteResponse Successful Response 88 | * @throws ApiError 89 | */ 90 | public deletePointInMemory( 91 | collectionId: string, 92 | memoryId: string, 93 | ): CancelablePromise { 94 | return this.httpRequest.request({ 95 | method: 'DELETE', 96 | url: '/memory/collections/{collection_id}/points/{memory_id}', 97 | path: { 98 | 'collection_id': collectionId, 99 | 'memory_id': memoryId, 100 | }, 101 | errors: { 102 | 422: `Validation Error`, 103 | }, 104 | }); 105 | } 106 | /** 107 | * Wipe Memory Points By Metadata 108 | * Delete points in memory by filter 109 | * @param collectionId 110 | * @param requestBody 111 | * @returns DeleteResponse Successful Response 112 | * @throws ApiError 113 | */ 114 | public wipeMemoryPoints( 115 | collectionId: string, 116 | requestBody?: Record, 117 | ): CancelablePromise { 118 | return this.httpRequest.request({ 119 | method: 'DELETE', 120 | url: '/memory/collections/{collection_id}/points', 121 | path: { 122 | 'collection_id': collectionId, 123 | }, 124 | body: requestBody, 125 | mediaType: 'application/json', 126 | errors: { 127 | 422: `Validation Error`, 128 | }, 129 | }); 130 | } 131 | /** 132 | * Get Conversation History 133 | * Get the specified user's conversation history from working memory 134 | * @returns any Successful Response 135 | * @throws ApiError 136 | */ 137 | public getConversationHistory(): CancelablePromise<{ 138 | history: Array; 139 | }> { 140 | return this.httpRequest.request({ 141 | method: 'GET', 142 | url: '/memory/conversation_history', 143 | }); 144 | } 145 | /** 146 | * Wipe Conversation History 147 | * Delete the specified user's conversation history from working memory 148 | * @returns DeleteResponse Successful Response 149 | * @throws ApiError 150 | */ 151 | public wipeConversationHistory(): CancelablePromise { 152 | return this.httpRequest.request({ 153 | method: 'DELETE', 154 | url: '/memory/conversation_history', 155 | }); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /api/services/PluginsService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { BodyInstallPlugin } from '../models/BodyInstallPlugin'; 6 | import type { BodyUploadUrl } from '../models/BodyUploadUrl'; 7 | import type { DeleteResponse } from '../models/DeleteResponse'; 8 | import type { FileResponse } from '../models/FileResponse'; 9 | import type { Plugin } from '../models/Plugin'; 10 | import type { PluginsList } from '../models/PluginsList'; 11 | import type { Setting } from '../models/Setting'; 12 | import type { SettingsResponse } from '../models/SettingsResponse'; 13 | import type { CancelablePromise } from '../core/CancelablePromise'; 14 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 15 | export class PluginsService { 16 | constructor(private readonly httpRequest: BaseHttpRequest) {} 17 | /** 18 | * List Available Plugins 19 | * List both installed and registry plugins 20 | * @param query 21 | * @returns PluginsList Successful Response 22 | * @throws ApiError 23 | */ 24 | public listAvailablePlugins( 25 | query?: string, 26 | ): CancelablePromise { 27 | return this.httpRequest.request({ 28 | method: 'GET', 29 | url: '/plugins', 30 | query: { 31 | 'query': query, 32 | }, 33 | }); 34 | } 35 | /** 36 | * Install Plugin 37 | * Install a new plugin from a zip file 38 | * @param formData 39 | * @returns FileResponse Successful Response 40 | * @throws ApiError 41 | */ 42 | public installPlugin( 43 | formData: BodyInstallPlugin, 44 | ): CancelablePromise { 45 | return this.httpRequest.request({ 46 | method: 'POST', 47 | url: '/plugins/upload', 48 | formData: formData, 49 | mediaType: 'multipart/form-data', 50 | errors: { 51 | 422: `Validation Error`, 52 | }, 53 | }); 54 | } 55 | /** 56 | * Install Plugin From Registry 57 | * Install a new plugin from external repository 58 | * @param requestBody 59 | * @returns FileResponse Successful Response 60 | * @throws ApiError 61 | */ 62 | public installPluginFromRegistry( 63 | requestBody: BodyUploadUrl, 64 | ): CancelablePromise { 65 | return this.httpRequest.request({ 66 | method: 'POST', 67 | url: '/plugins/upload/registry', 68 | body: requestBody, 69 | mediaType: 'application/json', 70 | errors: { 71 | 422: `Validation Error`, 72 | }, 73 | }); 74 | } 75 | /** 76 | * Toggle Plugin 77 | * Enable or disable a single plugin 78 | * @param pluginId 79 | * @returns any Successful Response 80 | * @throws ApiError 81 | */ 82 | public togglePlugin( 83 | pluginId: string, 84 | ): CancelablePromise<{ 85 | info: string; 86 | }> { 87 | return this.httpRequest.request({ 88 | method: 'PUT', 89 | url: '/plugins/toggle/{plugin_id}', 90 | path: { 91 | 'plugin_id': pluginId, 92 | }, 93 | errors: { 94 | 422: `Validation Error`, 95 | }, 96 | }); 97 | } 98 | /** 99 | * Get Plugin Details 100 | * Returns information on a single plugin 101 | * @param pluginId 102 | * @returns Plugin Successful Response 103 | * @throws ApiError 104 | */ 105 | public getPluginDetails( 106 | pluginId: string, 107 | ): CancelablePromise { 108 | return this.httpRequest.request({ 109 | method: 'GET', 110 | url: '/plugins/{plugin_id}', 111 | path: { 112 | 'plugin_id': pluginId, 113 | }, 114 | errors: { 115 | 422: `Validation Error`, 116 | }, 117 | }); 118 | } 119 | /** 120 | * Delete Plugin 121 | * Physically remove a plugin 122 | * @param pluginId 123 | * @returns DeleteResponse Successful Response 124 | * @throws ApiError 125 | */ 126 | public deletePlugin( 127 | pluginId: string, 128 | ): CancelablePromise { 129 | return this.httpRequest.request({ 130 | method: 'DELETE', 131 | url: '/plugins/{plugin_id}', 132 | path: { 133 | 'plugin_id': pluginId, 134 | }, 135 | errors: { 136 | 422: `Validation Error`, 137 | }, 138 | }); 139 | } 140 | /** 141 | * Get Plugins Settings 142 | * Returns the settings of all the plugins 143 | * @returns SettingsResponse Successful Response 144 | * @throws ApiError 145 | */ 146 | public getPluginsSettings(): CancelablePromise { 147 | return this.httpRequest.request({ 148 | method: 'GET', 149 | url: '/plugins/settings', 150 | }); 151 | } 152 | /** 153 | * Get Plugin Settings 154 | * Returns the settings of a specific plugin 155 | * @param pluginId 156 | * @returns any Successful Response 157 | * @throws ApiError 158 | */ 159 | public getPluginSettings( 160 | pluginId: string, 161 | ): CancelablePromise<(Setting & { 162 | schema: Record; 163 | })> { 164 | return this.httpRequest.request({ 165 | method: 'GET', 166 | url: '/plugins/settings/{plugin_id}', 167 | path: { 168 | 'plugin_id': pluginId, 169 | }, 170 | errors: { 171 | 422: `Validation Error`, 172 | }, 173 | }); 174 | } 175 | /** 176 | * Upsert Plugin Settings 177 | * Updates the settings of a specific plugin 178 | * @param pluginId 179 | * @param requestBody 180 | * @returns Setting Successful Response 181 | * @throws ApiError 182 | */ 183 | public upsertPluginSettings( 184 | pluginId: string, 185 | requestBody: Record, 186 | ): CancelablePromise { 187 | return this.httpRequest.request({ 188 | method: 'PUT', 189 | url: '/plugins/settings/{plugin_id}', 190 | path: { 191 | 'plugin_id': pluginId, 192 | }, 193 | body: requestBody, 194 | mediaType: 'application/json', 195 | errors: { 196 | 422: `Validation Error`, 197 | }, 198 | }); 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /api/services/RabbitHoleService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { BodyUploadFile } from '../models/BodyUploadFile'; 6 | import type { BodyUploadMemory } from '../models/BodyUploadMemory'; 7 | import type { BodyUploadUrl } from '../models/BodyUploadUrl'; 8 | import type { FileResponse } from '../models/FileResponse'; 9 | import type { WebResponse } from '../models/WebResponse'; 10 | import type { CancelablePromise } from '../core/CancelablePromise'; 11 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 12 | export class RabbitHoleService { 13 | constructor(private readonly httpRequest: BaseHttpRequest) {} 14 | /** 15 | * Upload File 16 | * Upload a file containing text (.txt, .md, .pdf, etc.). File content will be extracted and segmented into chunks. 17 | * Chunks will be then vectorized and stored into documents memory. 18 | * @param formData 19 | * @returns FileResponse Successful Response 20 | * @throws ApiError 21 | */ 22 | public uploadFile( 23 | formData: BodyUploadFile, 24 | ): CancelablePromise { 25 | return this.httpRequest.request({ 26 | method: 'POST', 27 | url: '/rabbithole', 28 | formData: formData, 29 | mediaType: 'multipart/form-data', 30 | errors: { 31 | 422: `Validation Error`, 32 | }, 33 | }); 34 | } 35 | /** 36 | * Upload URL 37 | * Upload a URL. Website content will be extracted and segmented into chunks. 38 | * Chunks will be then vectorized and stored into documents memory. 39 | * @param requestBody 40 | * @returns WebResponse Successful Response 41 | * @throws ApiError 42 | */ 43 | public uploadUrl( 44 | requestBody: BodyUploadUrl, 45 | ): CancelablePromise { 46 | return this.httpRequest.request({ 47 | method: 'POST', 48 | url: '/rabbithole/web', 49 | body: requestBody, 50 | mediaType: 'application/json', 51 | errors: { 52 | 422: `Validation Error`, 53 | }, 54 | }); 55 | } 56 | /** 57 | * Upload Memory 58 | * Upload a memory json file to the cat memory 59 | * @param formData 60 | * @returns any Successful Response 61 | * @throws ApiError 62 | */ 63 | public uploadMemory( 64 | formData: BodyUploadMemory, 65 | ): CancelablePromise> { 66 | return this.httpRequest.request({ 67 | method: 'POST', 68 | url: '/rabbithole/memory', 69 | formData: formData, 70 | mediaType: 'multipart/form-data', 71 | errors: { 72 | 422: `Validation Error`, 73 | }, 74 | }); 75 | } 76 | /** 77 | * Get Allowed Mimetypes 78 | * Retrieve the allowed mimetypes that can be ingested by the Rabbit Hole 79 | * @returns any Successful Response 80 | * @throws ApiError 81 | */ 82 | public getAllowedMimetypes(): CancelablePromise<{ 83 | allowed?: Array; 84 | }> { 85 | return this.httpRequest.request({ 86 | method: 'GET', 87 | url: '/rabbithole/allowed-mimetypes', 88 | }); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /api/services/SettingsService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { Setting } from '../models/Setting'; 6 | import type { SettingBody } from '../models/SettingBody'; 7 | import type { SettingsResponse } from '../models/SettingsResponse'; 8 | import type { CancelablePromise } from '../core/CancelablePromise'; 9 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 10 | export class SettingsService { 11 | constructor(private readonly httpRequest: BaseHttpRequest) {} 12 | /** 13 | * Get Settings 14 | * Get the entire list of settings available in the database 15 | * @param search The setting to search 16 | * @returns SettingsResponse Successful Response 17 | * @throws ApiError 18 | */ 19 | public getSettings( 20 | search: string = '', 21 | ): CancelablePromise { 22 | return this.httpRequest.request({ 23 | method: 'GET', 24 | url: '/settings', 25 | query: { 26 | 'search': search, 27 | }, 28 | errors: { 29 | 422: `Validation Error`, 30 | }, 31 | }); 32 | } 33 | /** 34 | * Create Setting 35 | * Create a new setting in the database 36 | * @param requestBody 37 | * @returns Setting Successful Response 38 | * @throws ApiError 39 | */ 40 | public createSetting( 41 | requestBody: SettingBody, 42 | ): CancelablePromise { 43 | return this.httpRequest.request({ 44 | method: 'POST', 45 | url: '/settings', 46 | body: requestBody, 47 | mediaType: 'application/json', 48 | errors: { 49 | 422: `Validation Error`, 50 | }, 51 | }); 52 | } 53 | /** 54 | * Get Setting 55 | * Get the a specific setting from the database 56 | * @param settingId 57 | * @returns Setting Successful Response 58 | * @throws ApiError 59 | */ 60 | public getSetting( 61 | settingId: string, 62 | ): CancelablePromise { 63 | return this.httpRequest.request({ 64 | method: 'GET', 65 | url: '/settings/{settingId}', 66 | path: { 67 | 'settingId': settingId, 68 | }, 69 | errors: { 70 | 422: `Validation Error`, 71 | }, 72 | }); 73 | } 74 | /** 75 | * Delete Setting 76 | * Delete a specific setting in the database 77 | * @param settingId 78 | * @returns any Successful Response 79 | * @throws ApiError 80 | */ 81 | public deleteSetting( 82 | settingId: string, 83 | ): CancelablePromise { 84 | return this.httpRequest.request({ 85 | method: 'DELETE', 86 | url: '/settings/{settingId}', 87 | path: { 88 | 'settingId': settingId, 89 | }, 90 | errors: { 91 | 422: `Validation Error`, 92 | }, 93 | }); 94 | } 95 | /** 96 | * Update Setting 97 | * Update a specific setting in the database if it exists 98 | * @param settingId 99 | * @param requestBody 100 | * @returns Setting Successful Response 101 | * @throws ApiError 102 | */ 103 | public updateSetting( 104 | settingId: string, 105 | requestBody: SettingBody, 106 | ): CancelablePromise { 107 | return this.httpRequest.request({ 108 | method: 'PUT', 109 | url: '/settings/{settingId}', 110 | path: { 111 | 'settingId': settingId, 112 | }, 113 | body: requestBody, 114 | mediaType: 'application/json', 115 | errors: { 116 | 422: `Validation Error`, 117 | }, 118 | }); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /api/services/StatusService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { CatMessage } from '../models/CatMessage'; 6 | import type { Status } from '../models/Status'; 7 | import type { CancelablePromise } from '../core/CancelablePromise'; 8 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 9 | export class StatusService { 10 | constructor(private readonly httpRequest: BaseHttpRequest) {} 11 | /** 12 | * Home 13 | * Server status 14 | * @returns Status Successful Response 15 | * @throws ApiError 16 | */ 17 | public home(): CancelablePromise { 18 | return this.httpRequest.request({ 19 | method: 'GET', 20 | url: '/', 21 | }); 22 | } 23 | /** 24 | * Message With Cat 25 | * Get a response from the Cat 26 | * @param requestBody 27 | * @returns CatMessage Successful Response 28 | * @throws ApiError 29 | */ 30 | public messageWithCat( 31 | requestBody?: { 32 | text: string; 33 | }, 34 | ): CancelablePromise { 35 | return this.httpRequest.request({ 36 | method: 'POST', 37 | url: '/message', 38 | body: requestBody, 39 | mediaType: 'application/json', 40 | errors: { 41 | 422: `Validation Error`, 42 | }, 43 | }); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /api/services/UserAuthService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { AuthPermission } from '../models/AuthPermission'; 6 | import type { JWTResponse } from '../models/JWTResponse'; 7 | import type { UserCredentials } from '../models/UserCredentials'; 8 | import type { CancelablePromise } from '../core/CancelablePromise'; 9 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 10 | export class UserAuthService { 11 | constructor(private readonly httpRequest: BaseHttpRequest) {} 12 | /** 13 | * Get Available Permissions 14 | * Returns all available resources and permissions. 15 | * @returns AuthPermission Successful Response 16 | * @throws ApiError 17 | */ 18 | public getAvailablePermissions(): CancelablePromise>> { 19 | return this.httpRequest.request({ 20 | method: 'GET', 21 | url: '/auth/available-permissions', 22 | }); 23 | } 24 | /** 25 | * Auth Token 26 | * Endpoint called from client to get a JWT from local identity provider. 27 | * This endpoint receives username and password as form-data, validates credentials and issues a JWT. 28 | * @param requestBody 29 | * @returns JWTResponse Successful Response 30 | * @throws ApiError 31 | */ 32 | public authToken( 33 | requestBody: UserCredentials, 34 | ): CancelablePromise { 35 | return this.httpRequest.request({ 36 | method: 'POST', 37 | url: '/auth/token', 38 | body: requestBody, 39 | mediaType: 'application/json', 40 | errors: { 41 | 422: `Validation Error`, 42 | }, 43 | }); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /api/services/UsersService.ts: -------------------------------------------------------------------------------- 1 | /* generated using openapi-typescript-codegen -- do not edit */ 2 | /* istanbul ignore file */ 3 | /* tslint:disable */ 4 | /* eslint-disable */ 5 | import type { UserCreate } from '../models/UserCreate'; 6 | import type { UserResponse } from '../models/UserResponse'; 7 | import type { UserUpdate } from '../models/UserUpdate'; 8 | import type { CancelablePromise } from '../core/CancelablePromise'; 9 | import type { BaseHttpRequest } from '../core/BaseHttpRequest'; 10 | export class UsersService { 11 | constructor(private readonly httpRequest: BaseHttpRequest) {} 12 | /** 13 | * Create User 14 | * @param requestBody 15 | * @returns UserResponse Successful Response 16 | * @throws ApiError 17 | */ 18 | public createUser( 19 | requestBody: UserCreate, 20 | ): CancelablePromise { 21 | return this.httpRequest.request({ 22 | method: 'POST', 23 | url: '/users/', 24 | body: requestBody, 25 | mediaType: 'application/json', 26 | errors: { 27 | 422: `Validation Error`, 28 | }, 29 | }); 30 | } 31 | /** 32 | * Read Users 33 | * @param skip 34 | * @param limit 35 | * @returns UserResponse Successful Response 36 | * @throws ApiError 37 | */ 38 | public readUsers( 39 | skip?: number, 40 | limit: number = 100, 41 | ): CancelablePromise> { 42 | return this.httpRequest.request({ 43 | method: 'GET', 44 | url: '/users/', 45 | query: { 46 | 'skip': skip, 47 | 'limit': limit, 48 | }, 49 | errors: { 50 | 422: `Validation Error`, 51 | }, 52 | }); 53 | } 54 | /** 55 | * Read User 56 | * @param userId 57 | * @returns UserResponse Successful Response 58 | * @throws ApiError 59 | */ 60 | public readUser( 61 | userId: string, 62 | ): CancelablePromise { 63 | return this.httpRequest.request({ 64 | method: 'GET', 65 | url: '/users/{user_id}', 66 | path: { 67 | 'user_id': userId, 68 | }, 69 | errors: { 70 | 422: `Validation Error`, 71 | }, 72 | }); 73 | } 74 | /** 75 | * Update User 76 | * @param userId 77 | * @param requestBody 78 | * @returns UserResponse Successful Response 79 | * @throws ApiError 80 | */ 81 | public updateUser( 82 | userId: string, 83 | requestBody: UserUpdate, 84 | ): CancelablePromise { 85 | return this.httpRequest.request({ 86 | method: 'PUT', 87 | url: '/users/{user_id}', 88 | path: { 89 | 'user_id': userId, 90 | }, 91 | body: requestBody, 92 | mediaType: 'application/json', 93 | errors: { 94 | 422: `Validation Error`, 95 | }, 96 | }); 97 | } 98 | /** 99 | * Delete User 100 | * @param userId 101 | * @returns UserResponse Successful Response 102 | * @throws ApiError 103 | */ 104 | public deleteUser( 105 | userId: string, 106 | ): CancelablePromise { 107 | return this.httpRequest.request({ 108 | method: 'DELETE', 109 | url: '/users/{user_id}', 110 | path: { 111 | 'user_id': userId, 112 | }, 113 | errors: { 114 | 422: `Validation Error`, 115 | }, 116 | }); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /api/utils.ts: -------------------------------------------------------------------------------- 1 | import { MessageWhy } from "./models/MessageWhy" 2 | 3 | export interface WebSocketSettings { 4 | /** 5 | * The maximum number of retries before calling {@link WebSocketSettings.onFailed} 6 | * @default 3 7 | */ 8 | retries?: number 9 | /** 10 | * The delay for reconnect, in milliseconds 11 | * @default 5000 12 | */ 13 | delay?: number 14 | /** 15 | * The function to call after failing all the retries 16 | * @default undefined 17 | */ 18 | onFailed?: (error: SocketError) => void 19 | } 20 | 21 | export interface CatSettings { 22 | /** The hostname to which connect to the Cat 23 | * @example 'localhost' 24 | */ 25 | host: string 26 | /** 27 | * The token or key to authenticate the Cat endpoints 28 | * @default undefined 29 | */ 30 | credential?: string 31 | /** 32 | * The user ID to use for Websocket connection 33 | * @default 'user' 34 | */ 35 | userId?: string 36 | /** 37 | * The port to which connect to the Cat 38 | * @default 1865 39 | */ 40 | port?: number 41 | /** 42 | * Choose to either initialize the client instantly or not 43 | * @default true 44 | */ 45 | instant?: boolean 46 | /** 47 | * Choose to either use the secure protocol or not 48 | * @default false 49 | */ 50 | secure?: boolean 51 | /** 52 | * Timeout for the endpoints, in milliseconds 53 | * @default 10000 54 | */ 55 | timeout?: number 56 | /** An object of type {@link WebSocketSettings} */ 57 | ws?: WebSocketSettings 58 | } 59 | 60 | export const AcceptedMemoryTypes = [ 61 | 'application/json' 62 | ] as const 63 | 64 | export type AcceptedMemoryType = typeof AcceptedMemoryTypes[number] 65 | 66 | export const AcceptedPluginTypes = [ 67 | 'application/zip', 68 | 'application/x-tar' 69 | ] as const 70 | 71 | export type AcceptedPluginType = typeof AcceptedPluginTypes[number] 72 | 73 | export enum WebSocketState { 74 | CONNECTING, OPEN, CLOSING, CLOSED 75 | } 76 | 77 | export interface SocketRequest { 78 | text?: string 79 | audio?: string 80 | image?: string 81 | [key: string]: any 82 | } 83 | 84 | export interface SocketResponse extends SocketRequest { 85 | type: 'notification' | 'chat' | 'chat_token' 86 | user_id: string 87 | who: string 88 | why?: MessageWhy & Record 89 | } 90 | 91 | export interface SocketError { 92 | name: 'SocketError' | 'FailedRetry' | 'SocketClosed' 93 | description: string 94 | } 95 | 96 | export const isTokenResponse = (value: unknown): value is SocketResponse => { 97 | return !!(value && typeof value === 'object' 98 | && 'content' in value 99 | && 'type' in value 100 | && value.type !== 'error' 101 | ) 102 | } 103 | 104 | export const isMessageResponse = (value: unknown): value is SocketResponse => { 105 | return !!(value && typeof value === 'object' 106 | && ('text' in value || 'audio' in value || 'image' in value) 107 | && 'user_id' in value 108 | && 'who' in value 109 | && 'type' in value 110 | && value.type !== 'error' 111 | ) 112 | } -------------------------------------------------------------------------------- /dist/index.d.mts: -------------------------------------------------------------------------------- 1 | import WebSocket from 'isomorphic-ws'; 2 | 3 | type ApiRequestOptions = { 4 | readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'; 5 | readonly url: string; 6 | readonly path?: Record; 7 | readonly cookies?: Record; 8 | readonly headers?: Record; 9 | readonly query?: Record; 10 | readonly formData?: Record; 11 | readonly body?: any; 12 | readonly mediaType?: string; 13 | readonly responseHeader?: string; 14 | readonly errors?: Record; 15 | }; 16 | 17 | declare class CancelError extends Error { 18 | constructor(message: string); 19 | get isCancelled(): boolean; 20 | } 21 | interface OnCancel { 22 | readonly isResolved: boolean; 23 | readonly isRejected: boolean; 24 | readonly isCancelled: boolean; 25 | (cancelHandler: () => void): void; 26 | } 27 | declare class CancelablePromise implements Promise { 28 | #private; 29 | constructor(executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void, onCancel: OnCancel) => void); 30 | get [Symbol.toStringTag](): string; 31 | then(onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, onRejected?: ((reason: any) => TResult2 | PromiseLike) | null): Promise; 32 | catch(onRejected?: ((reason: any) => TResult | PromiseLike) | null): Promise; 33 | finally(onFinally?: (() => void) | null): Promise; 34 | cancel(): void; 35 | get isCancelled(): boolean; 36 | } 37 | 38 | type Resolver = (options: ApiRequestOptions) => Promise; 39 | type Headers = Record; 40 | type OpenAPIConfig = { 41 | BASE: string; 42 | VERSION: string; 43 | WITH_CREDENTIALS: boolean; 44 | CREDENTIALS: 'include' | 'omit' | 'same-origin'; 45 | TOKEN?: string | Resolver | undefined; 46 | USERNAME?: string | Resolver | undefined; 47 | PASSWORD?: string | Resolver | undefined; 48 | HEADERS?: Headers | Resolver | undefined; 49 | ENCODE_PATH?: ((path: string) => string) | undefined; 50 | }; 51 | 52 | declare abstract class BaseHttpRequest { 53 | readonly config: OpenAPIConfig; 54 | constructor(config: OpenAPIConfig); 55 | abstract request(options: ApiRequestOptions): CancelablePromise; 56 | } 57 | 58 | type Setting = { 59 | name: string; 60 | value: Record; 61 | schema?: Record; 62 | }; 63 | 64 | type SettingsResponse = { 65 | settings: Array; 66 | selected_configuration?: string; 67 | }; 68 | 69 | declare class AuthHandlerService { 70 | private readonly httpRequest; 71 | constructor(httpRequest: BaseHttpRequest); 72 | /** 73 | * Get Auth Handler Settings 74 | * Get the list of the AuthHandlers 75 | * @returns SettingsResponse Successful Response 76 | * @throws ApiError 77 | */ 78 | getAuthHandlerSettings(): CancelablePromise; 79 | /** 80 | * Get Auth Handler Setting 81 | * Get the settings of a specific AuthHandler 82 | * @param authHandlerName 83 | * @returns Setting Successful Response 84 | * @throws ApiError 85 | */ 86 | getAuthHandlerSetting(authHandlerName: string): CancelablePromise; 87 | /** 88 | * Upsert Authenticator Setting 89 | * Upsert the settings of a specific AuthHandler 90 | * @param authHandlerName 91 | * @param requestBody 92 | * @returns Setting Successful Response 93 | * @throws ApiError 94 | */ 95 | upsertAuthenticatorSetting(authHandlerName: string, requestBody: Record): CancelablePromise; 96 | } 97 | 98 | declare class EmbedderService { 99 | private readonly httpRequest; 100 | constructor(httpRequest: BaseHttpRequest); 101 | /** 102 | * Get Embedders Settings 103 | * Get the list of the Embedders 104 | * @returns SettingsResponse Successful Response 105 | * @throws ApiError 106 | */ 107 | getEmbeddersSettings(): CancelablePromise; 108 | /** 109 | * Get Embedder Settings 110 | * Get settings and schema of the specified Embedder 111 | * @param languageEmbedderName 112 | * @returns Setting Successful Response 113 | * @throws ApiError 114 | */ 115 | getEmbedderSettings(languageEmbedderName: string): CancelablePromise; 116 | /** 117 | * Upsert Embedder Setting 118 | * Upsert the Embedder setting 119 | * @param languageEmbedderName 120 | * @param requestBody 121 | * @returns Setting Successful Response 122 | * @throws ApiError 123 | */ 124 | upsertEmbedderSetting(languageEmbedderName: string, requestBody: Record): CancelablePromise; 125 | } 126 | 127 | declare class LlmService { 128 | private readonly httpRequest; 129 | constructor(httpRequest: BaseHttpRequest); 130 | /** 131 | * Get LLMs Settings 132 | * Get the list of the Large Language Models 133 | * @returns SettingsResponse Successful Response 134 | * @throws ApiError 135 | */ 136 | getLlmsSettings(): CancelablePromise; 137 | /** 138 | * Get Llm Settings 139 | * Get settings and schema of the specified Large Language Model 140 | * @param languageModelName 141 | * @returns Setting Successful Response 142 | * @throws ApiError 143 | */ 144 | getLlmSettings(languageModelName: string): CancelablePromise; 145 | /** 146 | * Upsert LLM Setting 147 | * Upsert the Large Language Model setting 148 | * @param languageModelName 149 | * @param requestBody 150 | * @returns Setting Successful Response 151 | * @throws ApiError 152 | */ 153 | upsertLlmSetting(languageModelName: string, requestBody: Record): CancelablePromise; 154 | } 155 | 156 | type Collection = { 157 | name: string; 158 | vectors_count: number; 159 | }; 160 | 161 | type CollectionsList = { 162 | collections: Array; 163 | }; 164 | 165 | type ConversationMessage = { 166 | who: string; 167 | message: string; 168 | why?: Record; 169 | when: number; 170 | }; 171 | 172 | type DeleteResponse = { 173 | deleted: (string | boolean | Record | any[]); 174 | }; 175 | 176 | type QueryData = { 177 | text: string; 178 | vector: Array; 179 | }; 180 | 181 | type Metadata = { 182 | source: string; 183 | when: number; 184 | docstring?: string; 185 | name?: string; 186 | }; 187 | 188 | type CollectionData = { 189 | page_content: string; 190 | metadata: Metadata; 191 | id: string; 192 | score: number; 193 | vector: Array; 194 | }; 195 | 196 | type VectorsData = { 197 | embedder: string; 198 | collections: Record>; 199 | }; 200 | 201 | type MemoryRecall = { 202 | query: QueryData; 203 | vectors: VectorsData; 204 | }; 205 | 206 | declare class MemoryService { 207 | private readonly httpRequest; 208 | constructor(httpRequest: BaseHttpRequest); 209 | /** 210 | * Recall Memories From Text 211 | * Search k memories similar to given text. 212 | * @param text Find memories similar to this text. 213 | * @param k How many memories to return. 214 | * @returns MemoryRecall Successful Response 215 | * @throws ApiError 216 | */ 217 | recallMemoriesFromText(text: string, k?: number): CancelablePromise; 218 | /** 219 | * Get Collections 220 | * Get list of available collections 221 | * @returns CollectionsList Successful Response 222 | * @throws ApiError 223 | */ 224 | getCollections(): CancelablePromise; 225 | /** 226 | * Wipe Collections 227 | * Delete and create all collections 228 | * @returns DeleteResponse Successful Response 229 | * @throws ApiError 230 | */ 231 | wipeCollections(): CancelablePromise; 232 | /** 233 | * Wipe Single Collection 234 | * Delete and recreate a collection 235 | * @param collectionId 236 | * @returns DeleteResponse Successful Response 237 | * @throws ApiError 238 | */ 239 | wipeSingleCollection(collectionId: string): CancelablePromise; 240 | /** 241 | * Delete Point In Memory 242 | * Delete specific point in memory 243 | * @param collectionId 244 | * @param memoryId 245 | * @returns DeleteResponse Successful Response 246 | * @throws ApiError 247 | */ 248 | deletePointInMemory(collectionId: string, memoryId: string): CancelablePromise; 249 | /** 250 | * Wipe Memory Points By Metadata 251 | * Delete points in memory by filter 252 | * @param collectionId 253 | * @param requestBody 254 | * @returns DeleteResponse Successful Response 255 | * @throws ApiError 256 | */ 257 | wipeMemoryPoints(collectionId: string, requestBody?: Record): CancelablePromise; 258 | /** 259 | * Get Conversation History 260 | * Get the specified user's conversation history from working memory 261 | * @returns any Successful Response 262 | * @throws ApiError 263 | */ 264 | getConversationHistory(): CancelablePromise<{ 265 | history: Array; 266 | }>; 267 | /** 268 | * Wipe Conversation History 269 | * Delete the specified user's conversation history from working memory 270 | * @returns DeleteResponse Successful Response 271 | * @throws ApiError 272 | */ 273 | wipeConversationHistory(): CancelablePromise; 274 | } 275 | 276 | type BodyInstallPlugin = { 277 | file: Blob; 278 | }; 279 | 280 | type BodyUploadUrl = { 281 | /** 282 | * URL of the website to which you want to save the content 283 | */ 284 | url: string; 285 | }; 286 | 287 | type FileResponse = { 288 | filename: string; 289 | content_type: string; 290 | info: string; 291 | }; 292 | 293 | type Plugin = { 294 | id: string; 295 | name: string; 296 | description: string; 297 | author_name: string; 298 | author_url: string; 299 | plugin_url: string; 300 | tags: string; 301 | thumb: string; 302 | version: string; 303 | min_cat_version?: string; 304 | max_cat_version?: string; 305 | active?: boolean; 306 | url?: string; 307 | upgrade?: string; 308 | hooks?: Array<{ 309 | name: string; 310 | priority: number; 311 | }>; 312 | tools?: Array<{ 313 | name: string; 314 | }>; 315 | }; 316 | 317 | type PluginsList = { 318 | filters: { 319 | query?: string | null; 320 | }; 321 | installed: Array; 322 | registry: Array; 323 | }; 324 | 325 | declare class PluginsService { 326 | private readonly httpRequest; 327 | constructor(httpRequest: BaseHttpRequest); 328 | /** 329 | * List Available Plugins 330 | * List both installed and registry plugins 331 | * @param query 332 | * @returns PluginsList Successful Response 333 | * @throws ApiError 334 | */ 335 | listAvailablePlugins(query?: string): CancelablePromise; 336 | /** 337 | * Install Plugin 338 | * Install a new plugin from a zip file 339 | * @param formData 340 | * @returns FileResponse Successful Response 341 | * @throws ApiError 342 | */ 343 | installPlugin(formData: BodyInstallPlugin): CancelablePromise; 344 | /** 345 | * Install Plugin From Registry 346 | * Install a new plugin from external repository 347 | * @param requestBody 348 | * @returns FileResponse Successful Response 349 | * @throws ApiError 350 | */ 351 | installPluginFromRegistry(requestBody: BodyUploadUrl): CancelablePromise; 352 | /** 353 | * Toggle Plugin 354 | * Enable or disable a single plugin 355 | * @param pluginId 356 | * @returns any Successful Response 357 | * @throws ApiError 358 | */ 359 | togglePlugin(pluginId: string): CancelablePromise<{ 360 | info: string; 361 | }>; 362 | /** 363 | * Get Plugin Details 364 | * Returns information on a single plugin 365 | * @param pluginId 366 | * @returns Plugin Successful Response 367 | * @throws ApiError 368 | */ 369 | getPluginDetails(pluginId: string): CancelablePromise; 370 | /** 371 | * Delete Plugin 372 | * Physically remove a plugin 373 | * @param pluginId 374 | * @returns DeleteResponse Successful Response 375 | * @throws ApiError 376 | */ 377 | deletePlugin(pluginId: string): CancelablePromise; 378 | /** 379 | * Get Plugins Settings 380 | * Returns the settings of all the plugins 381 | * @returns SettingsResponse Successful Response 382 | * @throws ApiError 383 | */ 384 | getPluginsSettings(): CancelablePromise; 385 | /** 386 | * Get Plugin Settings 387 | * Returns the settings of a specific plugin 388 | * @param pluginId 389 | * @returns any Successful Response 390 | * @throws ApiError 391 | */ 392 | getPluginSettings(pluginId: string): CancelablePromise<(Setting & { 393 | schema: Record; 394 | })>; 395 | /** 396 | * Upsert Plugin Settings 397 | * Updates the settings of a specific plugin 398 | * @param pluginId 399 | * @param requestBody 400 | * @returns Setting Successful Response 401 | * @throws ApiError 402 | */ 403 | upsertPluginSettings(pluginId: string, requestBody: Record): CancelablePromise; 404 | } 405 | 406 | type BodyUploadFile = { 407 | file: Blob; 408 | /** 409 | * Maximum length of each chunk after the document is split (in tokens) 410 | */ 411 | chunk_size?: (number | null); 412 | /** 413 | * Chunk overlap (in tokens) 414 | */ 415 | chunk_overlap?: (number | null); 416 | /** 417 | * Metadata to be stored with each chunk (e.g. author, category, etc.). Since we are passing this along side form data, must be a JSON string. 418 | */ 419 | metadata?: string; 420 | }; 421 | 422 | type BodyUploadMemory = { 423 | file: Blob; 424 | }; 425 | 426 | type WebResponse = { 427 | url: string; 428 | info: string; 429 | }; 430 | 431 | declare class RabbitHoleService { 432 | private readonly httpRequest; 433 | constructor(httpRequest: BaseHttpRequest); 434 | /** 435 | * Upload File 436 | * Upload a file containing text (.txt, .md, .pdf, etc.). File content will be extracted and segmented into chunks. 437 | * Chunks will be then vectorized and stored into documents memory. 438 | * @param formData 439 | * @returns FileResponse Successful Response 440 | * @throws ApiError 441 | */ 442 | uploadFile(formData: BodyUploadFile): CancelablePromise; 443 | /** 444 | * Upload URL 445 | * Upload a URL. Website content will be extracted and segmented into chunks. 446 | * Chunks will be then vectorized and stored into documents memory. 447 | * @param requestBody 448 | * @returns WebResponse Successful Response 449 | * @throws ApiError 450 | */ 451 | uploadUrl(requestBody: BodyUploadUrl): CancelablePromise; 452 | /** 453 | * Upload Memory 454 | * Upload a memory json file to the cat memory 455 | * @param formData 456 | * @returns any Successful Response 457 | * @throws ApiError 458 | */ 459 | uploadMemory(formData: BodyUploadMemory): CancelablePromise>; 460 | /** 461 | * Get Allowed Mimetypes 462 | * Retrieve the allowed mimetypes that can be ingested by the Rabbit Hole 463 | * @returns any Successful Response 464 | * @throws ApiError 465 | */ 466 | getAllowedMimetypes(): CancelablePromise<{ 467 | allowed?: Array; 468 | }>; 469 | } 470 | 471 | type SettingBody = { 472 | name: string; 473 | value: Record; 474 | category?: string; 475 | }; 476 | 477 | declare class SettingsService { 478 | private readonly httpRequest; 479 | constructor(httpRequest: BaseHttpRequest); 480 | /** 481 | * Get Settings 482 | * Get the entire list of settings available in the database 483 | * @param search The setting to search 484 | * @returns SettingsResponse Successful Response 485 | * @throws ApiError 486 | */ 487 | getSettings(search?: string): CancelablePromise; 488 | /** 489 | * Create Setting 490 | * Create a new setting in the database 491 | * @param requestBody 492 | * @returns Setting Successful Response 493 | * @throws ApiError 494 | */ 495 | createSetting(requestBody: SettingBody): CancelablePromise; 496 | /** 497 | * Get Setting 498 | * Get the a specific setting from the database 499 | * @param settingId 500 | * @returns Setting Successful Response 501 | * @throws ApiError 502 | */ 503 | getSetting(settingId: string): CancelablePromise; 504 | /** 505 | * Delete Setting 506 | * Delete a specific setting in the database 507 | * @param settingId 508 | * @returns any Successful Response 509 | * @throws ApiError 510 | */ 511 | deleteSetting(settingId: string): CancelablePromise; 512 | /** 513 | * Update Setting 514 | * Update a specific setting in the database if it exists 515 | * @param settingId 516 | * @param requestBody 517 | * @returns Setting Successful Response 518 | * @throws ApiError 519 | */ 520 | updateSetting(settingId: string, requestBody: SettingBody): CancelablePromise; 521 | } 522 | 523 | /** 524 | * Class for wrapping message why 525 | * 526 | * Variables: 527 | * input (str): input message 528 | * intermediate_steps (List): intermediate steps 529 | * memory (dict): memory 530 | */ 531 | type MessageWhy = { 532 | input: string; 533 | intermediate_steps: Array; 534 | memory: Record; 535 | }; 536 | 537 | type CatMessage = { 538 | content: string; 539 | user_id: string; 540 | type?: string; 541 | why?: (MessageWhy | null); 542 | }; 543 | 544 | type Status = { 545 | status: string; 546 | version: string; 547 | }; 548 | 549 | declare class StatusService { 550 | private readonly httpRequest; 551 | constructor(httpRequest: BaseHttpRequest); 552 | /** 553 | * Home 554 | * Server status 555 | * @returns Status Successful Response 556 | * @throws ApiError 557 | */ 558 | home(): CancelablePromise; 559 | /** 560 | * Message With Cat 561 | * Get a response from the Cat 562 | * @param requestBody 563 | * @returns CatMessage Successful Response 564 | * @throws ApiError 565 | */ 566 | messageWithCat(requestBody?: { 567 | text: string; 568 | }): CancelablePromise; 569 | } 570 | 571 | type AuthPermission = 'WRITE' | 'EDIT' | 'LIST' | 'READ' | 'DELETE'; 572 | 573 | type JWTResponse = { 574 | access_token: string; 575 | token_type?: string; 576 | }; 577 | 578 | type UserCredentials = { 579 | username: string; 580 | password: string; 581 | }; 582 | 583 | declare class UserAuthService { 584 | private readonly httpRequest; 585 | constructor(httpRequest: BaseHttpRequest); 586 | /** 587 | * Get Available Permissions 588 | * Returns all available resources and permissions. 589 | * @returns AuthPermission Successful Response 590 | * @throws ApiError 591 | */ 592 | getAvailablePermissions(): CancelablePromise>>; 593 | /** 594 | * Auth Token 595 | * Endpoint called from client to get a JWT from local identity provider. 596 | * This endpoint receives username and password as form-data, validates credentials and issues a JWT. 597 | * @param requestBody 598 | * @returns JWTResponse Successful Response 599 | * @throws ApiError 600 | */ 601 | authToken(requestBody: UserCredentials): CancelablePromise; 602 | } 603 | 604 | type UserCreate = { 605 | username: string; 606 | permissions?: Record>; 607 | password: string; 608 | }; 609 | 610 | type UserResponse = { 611 | username: string; 612 | permissions?: Record>; 613 | id: string; 614 | }; 615 | 616 | type UserUpdate = { 617 | username?: string; 618 | permissions?: Record>; 619 | password?: string; 620 | }; 621 | 622 | declare class UsersService { 623 | private readonly httpRequest; 624 | constructor(httpRequest: BaseHttpRequest); 625 | /** 626 | * Create User 627 | * @param requestBody 628 | * @returns UserResponse Successful Response 629 | * @throws ApiError 630 | */ 631 | createUser(requestBody: UserCreate): CancelablePromise; 632 | /** 633 | * Read Users 634 | * @param skip 635 | * @param limit 636 | * @returns UserResponse Successful Response 637 | * @throws ApiError 638 | */ 639 | readUsers(skip?: number, limit?: number): CancelablePromise>; 640 | /** 641 | * Read User 642 | * @param userId 643 | * @returns UserResponse Successful Response 644 | * @throws ApiError 645 | */ 646 | readUser(userId: string): CancelablePromise; 647 | /** 648 | * Update User 649 | * @param userId 650 | * @param requestBody 651 | * @returns UserResponse Successful Response 652 | * @throws ApiError 653 | */ 654 | updateUser(userId: string, requestBody: UserUpdate): CancelablePromise; 655 | /** 656 | * Delete User 657 | * @param userId 658 | * @returns UserResponse Successful Response 659 | * @throws ApiError 660 | */ 661 | deleteUser(userId: string): CancelablePromise; 662 | } 663 | 664 | type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest; 665 | declare class CCatAPI { 666 | readonly authHandler: AuthHandlerService; 667 | readonly embedder: EmbedderService; 668 | readonly llm: LlmService; 669 | readonly memory: MemoryService; 670 | readonly plugins: PluginsService; 671 | readonly rabbitHole: RabbitHoleService; 672 | readonly settings: SettingsService; 673 | readonly status: StatusService; 674 | readonly userAuth: UserAuthService; 675 | readonly users: UsersService; 676 | readonly request: BaseHttpRequest; 677 | constructor(config?: Partial, HttpRequest?: HttpRequestConstructor); 678 | } 679 | 680 | interface WebSocketSettings { 681 | /** 682 | * The maximum number of retries before calling {@link WebSocketSettings.onFailed} 683 | * @default 3 684 | */ 685 | retries?: number; 686 | /** 687 | * The delay for reconnect, in milliseconds 688 | * @default 5000 689 | */ 690 | delay?: number; 691 | /** 692 | * The function to call after failing all the retries 693 | * @default undefined 694 | */ 695 | onFailed?: (error: SocketError) => void; 696 | } 697 | interface CatSettings { 698 | /** The hostname to which connect to the Cat 699 | * @example 'localhost' 700 | */ 701 | host: string; 702 | /** 703 | * The token or key to authenticate the Cat endpoints 704 | * @default undefined 705 | */ 706 | credential?: string; 707 | /** 708 | * The user ID to use for Websocket connection 709 | * @default 'user' 710 | */ 711 | userId?: string; 712 | /** 713 | * The port to which connect to the Cat 714 | * @default 1865 715 | */ 716 | port?: number; 717 | /** 718 | * Choose to either initialize the client instantly or not 719 | * @default true 720 | */ 721 | instant?: boolean; 722 | /** 723 | * Choose to either use the secure protocol or not 724 | * @default false 725 | */ 726 | secure?: boolean; 727 | /** 728 | * Timeout for the endpoints, in milliseconds 729 | * @default 10000 730 | */ 731 | timeout?: number; 732 | /** An object of type {@link WebSocketSettings} */ 733 | ws?: WebSocketSettings; 734 | } 735 | declare const AcceptedMemoryTypes: readonly ["application/json"]; 736 | type AcceptedMemoryType = typeof AcceptedMemoryTypes[number]; 737 | declare const AcceptedPluginTypes: readonly ["application/zip", "application/x-tar"]; 738 | type AcceptedPluginType = typeof AcceptedPluginTypes[number]; 739 | declare enum WebSocketState { 740 | CONNECTING = 0, 741 | OPEN = 1, 742 | CLOSING = 2, 743 | CLOSED = 3 744 | } 745 | interface SocketRequest { 746 | text?: string; 747 | audio?: string; 748 | image?: string; 749 | [key: string]: any; 750 | } 751 | interface SocketResponse extends SocketRequest { 752 | type: 'notification' | 'chat' | 'chat_token'; 753 | user_id: string; 754 | who: string; 755 | why?: MessageWhy & Record; 756 | } 757 | interface SocketError { 758 | name: 'SocketError' | 'FailedRetry' | 'SocketClosed'; 759 | description: string; 760 | } 761 | declare const isTokenResponse: (value: unknown) => value is SocketResponse; 762 | declare const isMessageResponse: (value: unknown) => value is SocketResponse; 763 | 764 | /** 765 | * The class to communicate with the Cheshire Cat AI 766 | */ 767 | declare class CatClient { 768 | private config; 769 | private apiClient; 770 | private ws; 771 | private connectedHandler?; 772 | private disconnectedHandler?; 773 | private messageHandler?; 774 | private errorHandler?; 775 | private explicitlyClosed; 776 | private retried; 777 | /** 778 | * Initialize the class with the specified settings 779 | * @param settings The settings to pass 780 | */ 781 | constructor(settings: CatSettings); 782 | private initWebSocket; 783 | /** 784 | * Resets the current `CatClient` instance. 785 | * @returns The updated `CatClient` instance. 786 | */ 787 | reset(): CatClient; 788 | /** 789 | * Initialize the WebSocket and the API Client 790 | * @returns The current `CatClient` class instance 791 | */ 792 | init(): CatClient; 793 | /** 794 | * Sends a message to the Cat through the WebSocket connection. 795 | * @param msg The message to send to the Cat. 796 | * @param userId The ID of the user sending the message. Defaults to "user". 797 | * @throws If the message does not contain text, audio or image. 798 | * @returns The `CatClient` instance. 799 | */ 800 | send(msg: SocketRequest, userId?: string): CatClient; 801 | /** 802 | * @returns The API Client 803 | */ 804 | get api(): CCatAPI | undefined; 805 | /** 806 | * Setter for the authentication key or token used by the client. This will also reset the client. 807 | * @param key The authentication key or token to be set. 808 | */ 809 | set credential(key: string | undefined); 810 | /** 811 | * Setter for the user ID used by the client. This will also reset the client. 812 | * @param user The user ID to be set. 813 | */ 814 | set userId(user: string); 815 | /** 816 | * Closes the WebSocket connection. 817 | * @returns The `CatClient` instance. 818 | */ 819 | close(): CatClient; 820 | /** 821 | * Returns the current state of the WebSocket connection. 822 | * @returns The WebSocketState enum value representing the current state of the WebSocket connection. 823 | */ 824 | get socketState(): WebSocketState; 825 | /** 826 | * Calls the handler when the WebSocket is connected 827 | * @param handler The function to call 828 | * @returns The current `CatClient` class instance 829 | */ 830 | onConnected(handler: () => void): CatClient; 831 | /** 832 | * Calls the handler when the WebSocket is disconnected 833 | * @param handler The function to call 834 | * @returns The current `CatClient` class instance 835 | */ 836 | onDisconnected(handler: () => void): CatClient; 837 | /** 838 | * Calls the handler when a new message arrives from the WebSocket 839 | * @param handler The function to call 840 | * @returns The current `CatClient` class instance 841 | */ 842 | onMessage(handler: (data: SocketResponse) => void): CatClient; 843 | /** 844 | * Calls the handler when the WebSocket catches an exception 845 | * @param handler The function to call 846 | * @returns The current `CatClient` class instance 847 | */ 848 | onError(handler: (error: SocketError, event?: WebSocket.ErrorEvent) => void): CatClient; 849 | private get url(); 850 | } 851 | 852 | type ApiResult = { 853 | readonly url: string; 854 | readonly ok: boolean; 855 | readonly status: number; 856 | readonly statusText: string; 857 | readonly body: any; 858 | }; 859 | 860 | declare class ApiError extends Error { 861 | readonly url: string; 862 | readonly status: number; 863 | readonly statusText: string; 864 | readonly body: any; 865 | readonly request: ApiRequestOptions; 866 | constructor(request: ApiRequestOptions, response: ApiResult, message: string); 867 | } 868 | 869 | type AuthResource = 'STATUS' | 'MEMORY' | 'CONVERSATION' | 'SETTINGS' | 'LLM' | 'EMBEDDER' | 'AUTH_HANDLER' | 'USERS' | 'UPLOAD' | 'PLUGINS' | 'STATIC'; 870 | 871 | type HTTPValidationError = { 872 | detail?: { 873 | error: string; 874 | }; 875 | }; 876 | 877 | export { type AcceptedMemoryType, AcceptedMemoryTypes, type AcceptedPluginType, AcceptedPluginTypes, ApiError, type AuthPermission, type AuthResource, type BodyInstallPlugin, type BodyUploadFile, type BodyUploadMemory, type BodyUploadUrl, CancelError, CancelablePromise, CatClient, type CatMessage, type CatSettings, type Collection, type CollectionData, type CollectionsList, type ConversationMessage, type DeleteResponse, type FileResponse, type HTTPValidationError, type JWTResponse, type MemoryRecall, type MessageWhy, type Metadata, type Plugin, type PluginsList, type QueryData, type Setting, type SettingBody, type SettingsResponse, type SocketError, type SocketRequest, type SocketResponse, type Status, type UserCreate, type UserCredentials, type UserResponse, type UserUpdate, type VectorsData, type WebResponse, type WebSocketSettings, WebSocketState, CatClient as default, isMessageResponse, isTokenResponse }; 878 | -------------------------------------------------------------------------------- /dist/index.d.ts: -------------------------------------------------------------------------------- 1 | import WebSocket from 'isomorphic-ws'; 2 | 3 | type ApiRequestOptions = { 4 | readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'; 5 | readonly url: string; 6 | readonly path?: Record; 7 | readonly cookies?: Record; 8 | readonly headers?: Record; 9 | readonly query?: Record; 10 | readonly formData?: Record; 11 | readonly body?: any; 12 | readonly mediaType?: string; 13 | readonly responseHeader?: string; 14 | readonly errors?: Record; 15 | }; 16 | 17 | declare class CancelError extends Error { 18 | constructor(message: string); 19 | get isCancelled(): boolean; 20 | } 21 | interface OnCancel { 22 | readonly isResolved: boolean; 23 | readonly isRejected: boolean; 24 | readonly isCancelled: boolean; 25 | (cancelHandler: () => void): void; 26 | } 27 | declare class CancelablePromise implements Promise { 28 | #private; 29 | constructor(executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void, onCancel: OnCancel) => void); 30 | get [Symbol.toStringTag](): string; 31 | then(onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, onRejected?: ((reason: any) => TResult2 | PromiseLike) | null): Promise; 32 | catch(onRejected?: ((reason: any) => TResult | PromiseLike) | null): Promise; 33 | finally(onFinally?: (() => void) | null): Promise; 34 | cancel(): void; 35 | get isCancelled(): boolean; 36 | } 37 | 38 | type Resolver = (options: ApiRequestOptions) => Promise; 39 | type Headers = Record; 40 | type OpenAPIConfig = { 41 | BASE: string; 42 | VERSION: string; 43 | WITH_CREDENTIALS: boolean; 44 | CREDENTIALS: 'include' | 'omit' | 'same-origin'; 45 | TOKEN?: string | Resolver | undefined; 46 | USERNAME?: string | Resolver | undefined; 47 | PASSWORD?: string | Resolver | undefined; 48 | HEADERS?: Headers | Resolver | undefined; 49 | ENCODE_PATH?: ((path: string) => string) | undefined; 50 | }; 51 | 52 | declare abstract class BaseHttpRequest { 53 | readonly config: OpenAPIConfig; 54 | constructor(config: OpenAPIConfig); 55 | abstract request(options: ApiRequestOptions): CancelablePromise; 56 | } 57 | 58 | type Setting = { 59 | name: string; 60 | value: Record; 61 | schema?: Record; 62 | }; 63 | 64 | type SettingsResponse = { 65 | settings: Array; 66 | selected_configuration?: string; 67 | }; 68 | 69 | declare class AuthHandlerService { 70 | private readonly httpRequest; 71 | constructor(httpRequest: BaseHttpRequest); 72 | /** 73 | * Get Auth Handler Settings 74 | * Get the list of the AuthHandlers 75 | * @returns SettingsResponse Successful Response 76 | * @throws ApiError 77 | */ 78 | getAuthHandlerSettings(): CancelablePromise; 79 | /** 80 | * Get Auth Handler Setting 81 | * Get the settings of a specific AuthHandler 82 | * @param authHandlerName 83 | * @returns Setting Successful Response 84 | * @throws ApiError 85 | */ 86 | getAuthHandlerSetting(authHandlerName: string): CancelablePromise; 87 | /** 88 | * Upsert Authenticator Setting 89 | * Upsert the settings of a specific AuthHandler 90 | * @param authHandlerName 91 | * @param requestBody 92 | * @returns Setting Successful Response 93 | * @throws ApiError 94 | */ 95 | upsertAuthenticatorSetting(authHandlerName: string, requestBody: Record): CancelablePromise; 96 | } 97 | 98 | declare class EmbedderService { 99 | private readonly httpRequest; 100 | constructor(httpRequest: BaseHttpRequest); 101 | /** 102 | * Get Embedders Settings 103 | * Get the list of the Embedders 104 | * @returns SettingsResponse Successful Response 105 | * @throws ApiError 106 | */ 107 | getEmbeddersSettings(): CancelablePromise; 108 | /** 109 | * Get Embedder Settings 110 | * Get settings and schema of the specified Embedder 111 | * @param languageEmbedderName 112 | * @returns Setting Successful Response 113 | * @throws ApiError 114 | */ 115 | getEmbedderSettings(languageEmbedderName: string): CancelablePromise; 116 | /** 117 | * Upsert Embedder Setting 118 | * Upsert the Embedder setting 119 | * @param languageEmbedderName 120 | * @param requestBody 121 | * @returns Setting Successful Response 122 | * @throws ApiError 123 | */ 124 | upsertEmbedderSetting(languageEmbedderName: string, requestBody: Record): CancelablePromise; 125 | } 126 | 127 | declare class LlmService { 128 | private readonly httpRequest; 129 | constructor(httpRequest: BaseHttpRequest); 130 | /** 131 | * Get LLMs Settings 132 | * Get the list of the Large Language Models 133 | * @returns SettingsResponse Successful Response 134 | * @throws ApiError 135 | */ 136 | getLlmsSettings(): CancelablePromise; 137 | /** 138 | * Get Llm Settings 139 | * Get settings and schema of the specified Large Language Model 140 | * @param languageModelName 141 | * @returns Setting Successful Response 142 | * @throws ApiError 143 | */ 144 | getLlmSettings(languageModelName: string): CancelablePromise; 145 | /** 146 | * Upsert LLM Setting 147 | * Upsert the Large Language Model setting 148 | * @param languageModelName 149 | * @param requestBody 150 | * @returns Setting Successful Response 151 | * @throws ApiError 152 | */ 153 | upsertLlmSetting(languageModelName: string, requestBody: Record): CancelablePromise; 154 | } 155 | 156 | type Collection = { 157 | name: string; 158 | vectors_count: number; 159 | }; 160 | 161 | type CollectionsList = { 162 | collections: Array; 163 | }; 164 | 165 | type ConversationMessage = { 166 | who: string; 167 | message: string; 168 | why?: Record; 169 | when: number; 170 | }; 171 | 172 | type DeleteResponse = { 173 | deleted: (string | boolean | Record | any[]); 174 | }; 175 | 176 | type QueryData = { 177 | text: string; 178 | vector: Array; 179 | }; 180 | 181 | type Metadata = { 182 | source: string; 183 | when: number; 184 | docstring?: string; 185 | name?: string; 186 | }; 187 | 188 | type CollectionData = { 189 | page_content: string; 190 | metadata: Metadata; 191 | id: string; 192 | score: number; 193 | vector: Array; 194 | }; 195 | 196 | type VectorsData = { 197 | embedder: string; 198 | collections: Record>; 199 | }; 200 | 201 | type MemoryRecall = { 202 | query: QueryData; 203 | vectors: VectorsData; 204 | }; 205 | 206 | declare class MemoryService { 207 | private readonly httpRequest; 208 | constructor(httpRequest: BaseHttpRequest); 209 | /** 210 | * Recall Memories From Text 211 | * Search k memories similar to given text. 212 | * @param text Find memories similar to this text. 213 | * @param k How many memories to return. 214 | * @returns MemoryRecall Successful Response 215 | * @throws ApiError 216 | */ 217 | recallMemoriesFromText(text: string, k?: number): CancelablePromise; 218 | /** 219 | * Get Collections 220 | * Get list of available collections 221 | * @returns CollectionsList Successful Response 222 | * @throws ApiError 223 | */ 224 | getCollections(): CancelablePromise; 225 | /** 226 | * Wipe Collections 227 | * Delete and create all collections 228 | * @returns DeleteResponse Successful Response 229 | * @throws ApiError 230 | */ 231 | wipeCollections(): CancelablePromise; 232 | /** 233 | * Wipe Single Collection 234 | * Delete and recreate a collection 235 | * @param collectionId 236 | * @returns DeleteResponse Successful Response 237 | * @throws ApiError 238 | */ 239 | wipeSingleCollection(collectionId: string): CancelablePromise; 240 | /** 241 | * Delete Point In Memory 242 | * Delete specific point in memory 243 | * @param collectionId 244 | * @param memoryId 245 | * @returns DeleteResponse Successful Response 246 | * @throws ApiError 247 | */ 248 | deletePointInMemory(collectionId: string, memoryId: string): CancelablePromise; 249 | /** 250 | * Wipe Memory Points By Metadata 251 | * Delete points in memory by filter 252 | * @param collectionId 253 | * @param requestBody 254 | * @returns DeleteResponse Successful Response 255 | * @throws ApiError 256 | */ 257 | wipeMemoryPoints(collectionId: string, requestBody?: Record): CancelablePromise; 258 | /** 259 | * Get Conversation History 260 | * Get the specified user's conversation history from working memory 261 | * @returns any Successful Response 262 | * @throws ApiError 263 | */ 264 | getConversationHistory(): CancelablePromise<{ 265 | history: Array; 266 | }>; 267 | /** 268 | * Wipe Conversation History 269 | * Delete the specified user's conversation history from working memory 270 | * @returns DeleteResponse Successful Response 271 | * @throws ApiError 272 | */ 273 | wipeConversationHistory(): CancelablePromise; 274 | } 275 | 276 | type BodyInstallPlugin = { 277 | file: Blob; 278 | }; 279 | 280 | type BodyUploadUrl = { 281 | /** 282 | * URL of the website to which you want to save the content 283 | */ 284 | url: string; 285 | }; 286 | 287 | type FileResponse = { 288 | filename: string; 289 | content_type: string; 290 | info: string; 291 | }; 292 | 293 | type Plugin = { 294 | id: string; 295 | name: string; 296 | description: string; 297 | author_name: string; 298 | author_url: string; 299 | plugin_url: string; 300 | tags: string; 301 | thumb: string; 302 | version: string; 303 | min_cat_version?: string; 304 | max_cat_version?: string; 305 | active?: boolean; 306 | url?: string; 307 | upgrade?: string; 308 | hooks?: Array<{ 309 | name: string; 310 | priority: number; 311 | }>; 312 | tools?: Array<{ 313 | name: string; 314 | }>; 315 | }; 316 | 317 | type PluginsList = { 318 | filters: { 319 | query?: string | null; 320 | }; 321 | installed: Array; 322 | registry: Array; 323 | }; 324 | 325 | declare class PluginsService { 326 | private readonly httpRequest; 327 | constructor(httpRequest: BaseHttpRequest); 328 | /** 329 | * List Available Plugins 330 | * List both installed and registry plugins 331 | * @param query 332 | * @returns PluginsList Successful Response 333 | * @throws ApiError 334 | */ 335 | listAvailablePlugins(query?: string): CancelablePromise; 336 | /** 337 | * Install Plugin 338 | * Install a new plugin from a zip file 339 | * @param formData 340 | * @returns FileResponse Successful Response 341 | * @throws ApiError 342 | */ 343 | installPlugin(formData: BodyInstallPlugin): CancelablePromise; 344 | /** 345 | * Install Plugin From Registry 346 | * Install a new plugin from external repository 347 | * @param requestBody 348 | * @returns FileResponse Successful Response 349 | * @throws ApiError 350 | */ 351 | installPluginFromRegistry(requestBody: BodyUploadUrl): CancelablePromise; 352 | /** 353 | * Toggle Plugin 354 | * Enable or disable a single plugin 355 | * @param pluginId 356 | * @returns any Successful Response 357 | * @throws ApiError 358 | */ 359 | togglePlugin(pluginId: string): CancelablePromise<{ 360 | info: string; 361 | }>; 362 | /** 363 | * Get Plugin Details 364 | * Returns information on a single plugin 365 | * @param pluginId 366 | * @returns Plugin Successful Response 367 | * @throws ApiError 368 | */ 369 | getPluginDetails(pluginId: string): CancelablePromise; 370 | /** 371 | * Delete Plugin 372 | * Physically remove a plugin 373 | * @param pluginId 374 | * @returns DeleteResponse Successful Response 375 | * @throws ApiError 376 | */ 377 | deletePlugin(pluginId: string): CancelablePromise; 378 | /** 379 | * Get Plugins Settings 380 | * Returns the settings of all the plugins 381 | * @returns SettingsResponse Successful Response 382 | * @throws ApiError 383 | */ 384 | getPluginsSettings(): CancelablePromise; 385 | /** 386 | * Get Plugin Settings 387 | * Returns the settings of a specific plugin 388 | * @param pluginId 389 | * @returns any Successful Response 390 | * @throws ApiError 391 | */ 392 | getPluginSettings(pluginId: string): CancelablePromise<(Setting & { 393 | schema: Record; 394 | })>; 395 | /** 396 | * Upsert Plugin Settings 397 | * Updates the settings of a specific plugin 398 | * @param pluginId 399 | * @param requestBody 400 | * @returns Setting Successful Response 401 | * @throws ApiError 402 | */ 403 | upsertPluginSettings(pluginId: string, requestBody: Record): CancelablePromise; 404 | } 405 | 406 | type BodyUploadFile = { 407 | file: Blob; 408 | /** 409 | * Maximum length of each chunk after the document is split (in tokens) 410 | */ 411 | chunk_size?: (number | null); 412 | /** 413 | * Chunk overlap (in tokens) 414 | */ 415 | chunk_overlap?: (number | null); 416 | /** 417 | * Metadata to be stored with each chunk (e.g. author, category, etc.). Since we are passing this along side form data, must be a JSON string. 418 | */ 419 | metadata?: string; 420 | }; 421 | 422 | type BodyUploadMemory = { 423 | file: Blob; 424 | }; 425 | 426 | type WebResponse = { 427 | url: string; 428 | info: string; 429 | }; 430 | 431 | declare class RabbitHoleService { 432 | private readonly httpRequest; 433 | constructor(httpRequest: BaseHttpRequest); 434 | /** 435 | * Upload File 436 | * Upload a file containing text (.txt, .md, .pdf, etc.). File content will be extracted and segmented into chunks. 437 | * Chunks will be then vectorized and stored into documents memory. 438 | * @param formData 439 | * @returns FileResponse Successful Response 440 | * @throws ApiError 441 | */ 442 | uploadFile(formData: BodyUploadFile): CancelablePromise; 443 | /** 444 | * Upload URL 445 | * Upload a URL. Website content will be extracted and segmented into chunks. 446 | * Chunks will be then vectorized and stored into documents memory. 447 | * @param requestBody 448 | * @returns WebResponse Successful Response 449 | * @throws ApiError 450 | */ 451 | uploadUrl(requestBody: BodyUploadUrl): CancelablePromise; 452 | /** 453 | * Upload Memory 454 | * Upload a memory json file to the cat memory 455 | * @param formData 456 | * @returns any Successful Response 457 | * @throws ApiError 458 | */ 459 | uploadMemory(formData: BodyUploadMemory): CancelablePromise>; 460 | /** 461 | * Get Allowed Mimetypes 462 | * Retrieve the allowed mimetypes that can be ingested by the Rabbit Hole 463 | * @returns any Successful Response 464 | * @throws ApiError 465 | */ 466 | getAllowedMimetypes(): CancelablePromise<{ 467 | allowed?: Array; 468 | }>; 469 | } 470 | 471 | type SettingBody = { 472 | name: string; 473 | value: Record; 474 | category?: string; 475 | }; 476 | 477 | declare class SettingsService { 478 | private readonly httpRequest; 479 | constructor(httpRequest: BaseHttpRequest); 480 | /** 481 | * Get Settings 482 | * Get the entire list of settings available in the database 483 | * @param search The setting to search 484 | * @returns SettingsResponse Successful Response 485 | * @throws ApiError 486 | */ 487 | getSettings(search?: string): CancelablePromise; 488 | /** 489 | * Create Setting 490 | * Create a new setting in the database 491 | * @param requestBody 492 | * @returns Setting Successful Response 493 | * @throws ApiError 494 | */ 495 | createSetting(requestBody: SettingBody): CancelablePromise; 496 | /** 497 | * Get Setting 498 | * Get the a specific setting from the database 499 | * @param settingId 500 | * @returns Setting Successful Response 501 | * @throws ApiError 502 | */ 503 | getSetting(settingId: string): CancelablePromise; 504 | /** 505 | * Delete Setting 506 | * Delete a specific setting in the database 507 | * @param settingId 508 | * @returns any Successful Response 509 | * @throws ApiError 510 | */ 511 | deleteSetting(settingId: string): CancelablePromise; 512 | /** 513 | * Update Setting 514 | * Update a specific setting in the database if it exists 515 | * @param settingId 516 | * @param requestBody 517 | * @returns Setting Successful Response 518 | * @throws ApiError 519 | */ 520 | updateSetting(settingId: string, requestBody: SettingBody): CancelablePromise; 521 | } 522 | 523 | /** 524 | * Class for wrapping message why 525 | * 526 | * Variables: 527 | * input (str): input message 528 | * intermediate_steps (List): intermediate steps 529 | * memory (dict): memory 530 | */ 531 | type MessageWhy = { 532 | input: string; 533 | intermediate_steps: Array; 534 | memory: Record; 535 | }; 536 | 537 | type CatMessage = { 538 | content: string; 539 | user_id: string; 540 | type?: string; 541 | why?: (MessageWhy | null); 542 | }; 543 | 544 | type Status = { 545 | status: string; 546 | version: string; 547 | }; 548 | 549 | declare class StatusService { 550 | private readonly httpRequest; 551 | constructor(httpRequest: BaseHttpRequest); 552 | /** 553 | * Home 554 | * Server status 555 | * @returns Status Successful Response 556 | * @throws ApiError 557 | */ 558 | home(): CancelablePromise; 559 | /** 560 | * Message With Cat 561 | * Get a response from the Cat 562 | * @param requestBody 563 | * @returns CatMessage Successful Response 564 | * @throws ApiError 565 | */ 566 | messageWithCat(requestBody?: { 567 | text: string; 568 | }): CancelablePromise; 569 | } 570 | 571 | type AuthPermission = 'WRITE' | 'EDIT' | 'LIST' | 'READ' | 'DELETE'; 572 | 573 | type JWTResponse = { 574 | access_token: string; 575 | token_type?: string; 576 | }; 577 | 578 | type UserCredentials = { 579 | username: string; 580 | password: string; 581 | }; 582 | 583 | declare class UserAuthService { 584 | private readonly httpRequest; 585 | constructor(httpRequest: BaseHttpRequest); 586 | /** 587 | * Get Available Permissions 588 | * Returns all available resources and permissions. 589 | * @returns AuthPermission Successful Response 590 | * @throws ApiError 591 | */ 592 | getAvailablePermissions(): CancelablePromise>>; 593 | /** 594 | * Auth Token 595 | * Endpoint called from client to get a JWT from local identity provider. 596 | * This endpoint receives username and password as form-data, validates credentials and issues a JWT. 597 | * @param requestBody 598 | * @returns JWTResponse Successful Response 599 | * @throws ApiError 600 | */ 601 | authToken(requestBody: UserCredentials): CancelablePromise; 602 | } 603 | 604 | type UserCreate = { 605 | username: string; 606 | permissions?: Record>; 607 | password: string; 608 | }; 609 | 610 | type UserResponse = { 611 | username: string; 612 | permissions?: Record>; 613 | id: string; 614 | }; 615 | 616 | type UserUpdate = { 617 | username?: string; 618 | permissions?: Record>; 619 | password?: string; 620 | }; 621 | 622 | declare class UsersService { 623 | private readonly httpRequest; 624 | constructor(httpRequest: BaseHttpRequest); 625 | /** 626 | * Create User 627 | * @param requestBody 628 | * @returns UserResponse Successful Response 629 | * @throws ApiError 630 | */ 631 | createUser(requestBody: UserCreate): CancelablePromise; 632 | /** 633 | * Read Users 634 | * @param skip 635 | * @param limit 636 | * @returns UserResponse Successful Response 637 | * @throws ApiError 638 | */ 639 | readUsers(skip?: number, limit?: number): CancelablePromise>; 640 | /** 641 | * Read User 642 | * @param userId 643 | * @returns UserResponse Successful Response 644 | * @throws ApiError 645 | */ 646 | readUser(userId: string): CancelablePromise; 647 | /** 648 | * Update User 649 | * @param userId 650 | * @param requestBody 651 | * @returns UserResponse Successful Response 652 | * @throws ApiError 653 | */ 654 | updateUser(userId: string, requestBody: UserUpdate): CancelablePromise; 655 | /** 656 | * Delete User 657 | * @param userId 658 | * @returns UserResponse Successful Response 659 | * @throws ApiError 660 | */ 661 | deleteUser(userId: string): CancelablePromise; 662 | } 663 | 664 | type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest; 665 | declare class CCatAPI { 666 | readonly authHandler: AuthHandlerService; 667 | readonly embedder: EmbedderService; 668 | readonly llm: LlmService; 669 | readonly memory: MemoryService; 670 | readonly plugins: PluginsService; 671 | readonly rabbitHole: RabbitHoleService; 672 | readonly settings: SettingsService; 673 | readonly status: StatusService; 674 | readonly userAuth: UserAuthService; 675 | readonly users: UsersService; 676 | readonly request: BaseHttpRequest; 677 | constructor(config?: Partial, HttpRequest?: HttpRequestConstructor); 678 | } 679 | 680 | interface WebSocketSettings { 681 | /** 682 | * The maximum number of retries before calling {@link WebSocketSettings.onFailed} 683 | * @default 3 684 | */ 685 | retries?: number; 686 | /** 687 | * The delay for reconnect, in milliseconds 688 | * @default 5000 689 | */ 690 | delay?: number; 691 | /** 692 | * The function to call after failing all the retries 693 | * @default undefined 694 | */ 695 | onFailed?: (error: SocketError) => void; 696 | } 697 | interface CatSettings { 698 | /** The hostname to which connect to the Cat 699 | * @example 'localhost' 700 | */ 701 | host: string; 702 | /** 703 | * The token or key to authenticate the Cat endpoints 704 | * @default undefined 705 | */ 706 | credential?: string; 707 | /** 708 | * The user ID to use for Websocket connection 709 | * @default 'user' 710 | */ 711 | userId?: string; 712 | /** 713 | * The port to which connect to the Cat 714 | * @default 1865 715 | */ 716 | port?: number; 717 | /** 718 | * Choose to either initialize the client instantly or not 719 | * @default true 720 | */ 721 | instant?: boolean; 722 | /** 723 | * Choose to either use the secure protocol or not 724 | * @default false 725 | */ 726 | secure?: boolean; 727 | /** 728 | * Timeout for the endpoints, in milliseconds 729 | * @default 10000 730 | */ 731 | timeout?: number; 732 | /** An object of type {@link WebSocketSettings} */ 733 | ws?: WebSocketSettings; 734 | } 735 | declare const AcceptedMemoryTypes: readonly ["application/json"]; 736 | type AcceptedMemoryType = typeof AcceptedMemoryTypes[number]; 737 | declare const AcceptedPluginTypes: readonly ["application/zip", "application/x-tar"]; 738 | type AcceptedPluginType = typeof AcceptedPluginTypes[number]; 739 | declare enum WebSocketState { 740 | CONNECTING = 0, 741 | OPEN = 1, 742 | CLOSING = 2, 743 | CLOSED = 3 744 | } 745 | interface SocketRequest { 746 | text?: string; 747 | audio?: string; 748 | image?: string; 749 | [key: string]: any; 750 | } 751 | interface SocketResponse extends SocketRequest { 752 | type: 'notification' | 'chat' | 'chat_token'; 753 | user_id: string; 754 | who: string; 755 | why?: MessageWhy & Record; 756 | } 757 | interface SocketError { 758 | name: 'SocketError' | 'FailedRetry' | 'SocketClosed'; 759 | description: string; 760 | } 761 | declare const isTokenResponse: (value: unknown) => value is SocketResponse; 762 | declare const isMessageResponse: (value: unknown) => value is SocketResponse; 763 | 764 | /** 765 | * The class to communicate with the Cheshire Cat AI 766 | */ 767 | declare class CatClient { 768 | private config; 769 | private apiClient; 770 | private ws; 771 | private connectedHandler?; 772 | private disconnectedHandler?; 773 | private messageHandler?; 774 | private errorHandler?; 775 | private explicitlyClosed; 776 | private retried; 777 | /** 778 | * Initialize the class with the specified settings 779 | * @param settings The settings to pass 780 | */ 781 | constructor(settings: CatSettings); 782 | private initWebSocket; 783 | /** 784 | * Resets the current `CatClient` instance. 785 | * @returns The updated `CatClient` instance. 786 | */ 787 | reset(): CatClient; 788 | /** 789 | * Initialize the WebSocket and the API Client 790 | * @returns The current `CatClient` class instance 791 | */ 792 | init(): CatClient; 793 | /** 794 | * Sends a message to the Cat through the WebSocket connection. 795 | * @param msg The message to send to the Cat. 796 | * @param userId The ID of the user sending the message. Defaults to "user". 797 | * @throws If the message does not contain text, audio or image. 798 | * @returns The `CatClient` instance. 799 | */ 800 | send(msg: SocketRequest, userId?: string): CatClient; 801 | /** 802 | * @returns The API Client 803 | */ 804 | get api(): CCatAPI | undefined; 805 | /** 806 | * Setter for the authentication key or token used by the client. This will also reset the client. 807 | * @param key The authentication key or token to be set. 808 | */ 809 | set credential(key: string | undefined); 810 | /** 811 | * Setter for the user ID used by the client. This will also reset the client. 812 | * @param user The user ID to be set. 813 | */ 814 | set userId(user: string); 815 | /** 816 | * Closes the WebSocket connection. 817 | * @returns The `CatClient` instance. 818 | */ 819 | close(): CatClient; 820 | /** 821 | * Returns the current state of the WebSocket connection. 822 | * @returns The WebSocketState enum value representing the current state of the WebSocket connection. 823 | */ 824 | get socketState(): WebSocketState; 825 | /** 826 | * Calls the handler when the WebSocket is connected 827 | * @param handler The function to call 828 | * @returns The current `CatClient` class instance 829 | */ 830 | onConnected(handler: () => void): CatClient; 831 | /** 832 | * Calls the handler when the WebSocket is disconnected 833 | * @param handler The function to call 834 | * @returns The current `CatClient` class instance 835 | */ 836 | onDisconnected(handler: () => void): CatClient; 837 | /** 838 | * Calls the handler when a new message arrives from the WebSocket 839 | * @param handler The function to call 840 | * @returns The current `CatClient` class instance 841 | */ 842 | onMessage(handler: (data: SocketResponse) => void): CatClient; 843 | /** 844 | * Calls the handler when the WebSocket catches an exception 845 | * @param handler The function to call 846 | * @returns The current `CatClient` class instance 847 | */ 848 | onError(handler: (error: SocketError, event?: WebSocket.ErrorEvent) => void): CatClient; 849 | private get url(); 850 | } 851 | 852 | type ApiResult = { 853 | readonly url: string; 854 | readonly ok: boolean; 855 | readonly status: number; 856 | readonly statusText: string; 857 | readonly body: any; 858 | }; 859 | 860 | declare class ApiError extends Error { 861 | readonly url: string; 862 | readonly status: number; 863 | readonly statusText: string; 864 | readonly body: any; 865 | readonly request: ApiRequestOptions; 866 | constructor(request: ApiRequestOptions, response: ApiResult, message: string); 867 | } 868 | 869 | type AuthResource = 'STATUS' | 'MEMORY' | 'CONVERSATION' | 'SETTINGS' | 'LLM' | 'EMBEDDER' | 'AUTH_HANDLER' | 'USERS' | 'UPLOAD' | 'PLUGINS' | 'STATIC'; 870 | 871 | type HTTPValidationError = { 872 | detail?: { 873 | error: string; 874 | }; 875 | }; 876 | 877 | export { type AcceptedMemoryType, AcceptedMemoryTypes, type AcceptedPluginType, AcceptedPluginTypes, ApiError, type AuthPermission, type AuthResource, type BodyInstallPlugin, type BodyUploadFile, type BodyUploadMemory, type BodyUploadUrl, CancelError, CancelablePromise, CatClient, type CatMessage, type CatSettings, type Collection, type CollectionData, type CollectionsList, type ConversationMessage, type DeleteResponse, type FileResponse, type HTTPValidationError, type JWTResponse, type MemoryRecall, type MessageWhy, type Metadata, type Plugin, type PluginsList, type QueryData, type Setting, type SettingBody, type SettingsResponse, type SocketError, type SocketRequest, type SocketResponse, type Status, type UserCreate, type UserCredentials, type UserResponse, type UserUpdate, type VectorsData, type WebResponse, type WebSocketSettings, WebSocketState, CatClient as default, isMessageResponse, isTokenResponse }; 878 | -------------------------------------------------------------------------------- /dist/index.mjs: -------------------------------------------------------------------------------- 1 | // api/client.ts 2 | import WebSocket from "isomorphic-ws"; 3 | 4 | // api/core/BaseHttpRequest.ts 5 | var BaseHttpRequest = class { 6 | constructor(config) { 7 | this.config = config; 8 | } 9 | }; 10 | 11 | // api/core/request.ts 12 | import axios from "axios"; 13 | import FormData from "form-data"; 14 | 15 | // api/core/ApiError.ts 16 | var ApiError = class extends Error { 17 | url; 18 | status; 19 | statusText; 20 | body; 21 | request; 22 | constructor(request2, response, message) { 23 | super(message); 24 | this.name = "ApiError"; 25 | this.url = response.url; 26 | this.status = response.status; 27 | this.statusText = response.statusText; 28 | this.body = response.body; 29 | this.request = request2; 30 | } 31 | }; 32 | 33 | // api/core/CancelablePromise.ts 34 | var CancelError = class extends Error { 35 | constructor(message) { 36 | super(message); 37 | this.name = "CancelError"; 38 | } 39 | get isCancelled() { 40 | return true; 41 | } 42 | }; 43 | var CancelablePromise = class { 44 | #isResolved; 45 | #isRejected; 46 | #isCancelled; 47 | #cancelHandlers; 48 | #promise; 49 | #resolve; 50 | #reject; 51 | constructor(executor) { 52 | this.#isResolved = false; 53 | this.#isRejected = false; 54 | this.#isCancelled = false; 55 | this.#cancelHandlers = []; 56 | this.#promise = new Promise((resolve2, reject) => { 57 | this.#resolve = resolve2; 58 | this.#reject = reject; 59 | const onResolve = (value) => { 60 | if (this.#isResolved || this.#isRejected || this.#isCancelled) { 61 | return; 62 | } 63 | this.#isResolved = true; 64 | if (this.#resolve) this.#resolve(value); 65 | }; 66 | const onReject = (reason) => { 67 | if (this.#isResolved || this.#isRejected || this.#isCancelled) { 68 | return; 69 | } 70 | this.#isRejected = true; 71 | if (this.#reject) this.#reject(reason); 72 | }; 73 | const onCancel = (cancelHandler) => { 74 | if (this.#isResolved || this.#isRejected || this.#isCancelled) { 75 | return; 76 | } 77 | this.#cancelHandlers.push(cancelHandler); 78 | }; 79 | Object.defineProperty(onCancel, "isResolved", { 80 | get: () => this.#isResolved 81 | }); 82 | Object.defineProperty(onCancel, "isRejected", { 83 | get: () => this.#isRejected 84 | }); 85 | Object.defineProperty(onCancel, "isCancelled", { 86 | get: () => this.#isCancelled 87 | }); 88 | return executor(onResolve, onReject, onCancel); 89 | }); 90 | } 91 | get [Symbol.toStringTag]() { 92 | return "Cancellable Promise"; 93 | } 94 | then(onFulfilled, onRejected) { 95 | return this.#promise.then(onFulfilled, onRejected); 96 | } 97 | catch(onRejected) { 98 | return this.#promise.catch(onRejected); 99 | } 100 | finally(onFinally) { 101 | return this.#promise.finally(onFinally); 102 | } 103 | cancel() { 104 | if (this.#isResolved || this.#isRejected || this.#isCancelled) { 105 | return; 106 | } 107 | this.#isCancelled = true; 108 | if (this.#cancelHandlers.length) { 109 | try { 110 | for (const cancelHandler of this.#cancelHandlers) { 111 | cancelHandler(); 112 | } 113 | } catch (error) { 114 | console.warn("Cancellation threw an error", error); 115 | return; 116 | } 117 | } 118 | this.#cancelHandlers.length = 0; 119 | if (this.#reject) this.#reject(new CancelError("Request aborted")); 120 | } 121 | get isCancelled() { 122 | return this.#isCancelled; 123 | } 124 | }; 125 | 126 | // api/core/request.ts 127 | var isDefined = (value) => { 128 | return value !== void 0 && value !== null; 129 | }; 130 | var isString = (value) => { 131 | return typeof value === "string"; 132 | }; 133 | var isStringWithValue = (value) => { 134 | return isString(value) && value !== ""; 135 | }; 136 | var isBlob = (value) => { 137 | return typeof value === "object" && typeof value.type === "string" && typeof value.stream === "function" && typeof value.arrayBuffer === "function" && typeof value.constructor === "function" && typeof value.constructor.name === "string" && /^(Blob|File)$/.test(value.constructor.name) && /^(Blob|File)$/.test(value[Symbol.toStringTag]); 138 | }; 139 | var isFormData = (value) => { 140 | return value instanceof FormData; 141 | }; 142 | var isSuccess = (status) => { 143 | return status >= 200 && status < 300; 144 | }; 145 | var base64 = (str) => { 146 | try { 147 | return btoa(str); 148 | } catch (err) { 149 | return Buffer.from(str).toString("base64"); 150 | } 151 | }; 152 | var getQueryString = (params) => { 153 | const qs = []; 154 | const append = (key, value) => { 155 | qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); 156 | }; 157 | const process = (key, value) => { 158 | if (isDefined(value)) { 159 | if (Array.isArray(value)) { 160 | value.forEach((v) => { 161 | process(key, v); 162 | }); 163 | } else if (typeof value === "object") { 164 | Object.entries(value).forEach(([k, v]) => { 165 | process(`${key}[${k}]`, v); 166 | }); 167 | } else { 168 | append(key, value); 169 | } 170 | } 171 | }; 172 | Object.entries(params).forEach(([key, value]) => { 173 | process(key, value); 174 | }); 175 | if (qs.length > 0) { 176 | return `?${qs.join("&")}`; 177 | } 178 | return ""; 179 | }; 180 | var getUrl = (config, options) => { 181 | const encoder = config.ENCODE_PATH || encodeURI; 182 | const path = options.url.replace("{api-version}", config.VERSION).replace(/{(.*?)}/g, (substring, group) => { 183 | if (options.path?.hasOwnProperty(group)) { 184 | return encoder(String(options.path[group])); 185 | } 186 | return substring; 187 | }); 188 | const url = `${config.BASE}${path}`; 189 | if (options.query) { 190 | return `${url}${getQueryString(options.query)}`; 191 | } 192 | return url; 193 | }; 194 | var getFormData = (options) => { 195 | if (options.formData) { 196 | const formData = new FormData(); 197 | const process = (key, value) => { 198 | if (isString(value) || isBlob(value)) { 199 | formData.append(key, value); 200 | } else { 201 | formData.append(key, JSON.stringify(value)); 202 | } 203 | }; 204 | Object.entries(options.formData).filter(([_, value]) => isDefined(value)).forEach(([key, value]) => { 205 | if (Array.isArray(value)) { 206 | value.forEach((v) => process(key, v)); 207 | } else { 208 | process(key, value); 209 | } 210 | }); 211 | return formData; 212 | } 213 | return void 0; 214 | }; 215 | var resolve = async (options, resolver) => { 216 | if (typeof resolver === "function") { 217 | return resolver(options); 218 | } 219 | return resolver; 220 | }; 221 | var getHeaders = async (config, options, formData) => { 222 | const [token, username, password, additionalHeaders] = await Promise.all([ 223 | resolve(options, config.TOKEN), 224 | resolve(options, config.USERNAME), 225 | resolve(options, config.PASSWORD), 226 | resolve(options, config.HEADERS) 227 | ]); 228 | const formHeaders = typeof formData?.getHeaders === "function" && formData?.getHeaders() || {}; 229 | const headers = Object.entries({ 230 | Accept: "application/json", 231 | ...additionalHeaders, 232 | ...options.headers, 233 | ...formHeaders 234 | }).filter(([_, value]) => isDefined(value)).reduce((headers2, [key, value]) => ({ 235 | ...headers2, 236 | [key]: String(value) 237 | }), {}); 238 | if (isStringWithValue(token)) { 239 | headers["Authorization"] = `Bearer ${token}`; 240 | } 241 | if (isStringWithValue(username) && isStringWithValue(password)) { 242 | const credentials = base64(`${username}:${password}`); 243 | headers["Authorization"] = `Basic ${credentials}`; 244 | } 245 | if (options.body !== void 0) { 246 | if (options.mediaType) { 247 | headers["Content-Type"] = options.mediaType; 248 | } else if (isBlob(options.body)) { 249 | headers["Content-Type"] = options.body.type || "application/octet-stream"; 250 | } else if (isString(options.body)) { 251 | headers["Content-Type"] = "text/plain"; 252 | } else if (!isFormData(options.body)) { 253 | headers["Content-Type"] = "application/json"; 254 | } 255 | } 256 | return headers; 257 | }; 258 | var getRequestBody = (options) => { 259 | if (options.body) { 260 | return options.body; 261 | } 262 | return void 0; 263 | }; 264 | var sendRequest = async (config, options, url, body, formData, headers, onCancel, axiosClient) => { 265 | const source = axios.CancelToken.source(); 266 | const requestConfig = { 267 | url, 268 | headers, 269 | data: body ?? formData, 270 | method: options.method, 271 | withCredentials: config.WITH_CREDENTIALS, 272 | withXSRFToken: config.CREDENTIALS === "include" ? config.WITH_CREDENTIALS : false, 273 | cancelToken: source.token 274 | }; 275 | onCancel(() => source.cancel("The user aborted a request.")); 276 | try { 277 | return await axiosClient.request(requestConfig); 278 | } catch (error) { 279 | const axiosError = error; 280 | if (axiosError.response) { 281 | return axiosError.response; 282 | } 283 | throw error; 284 | } 285 | }; 286 | var getResponseHeader = (response, responseHeader) => { 287 | if (responseHeader) { 288 | const content = response.headers[responseHeader]; 289 | if (isString(content)) { 290 | return content; 291 | } 292 | } 293 | return void 0; 294 | }; 295 | var getResponseBody = (response) => { 296 | if (response.status !== 204) { 297 | return response.data; 298 | } 299 | return void 0; 300 | }; 301 | var catchErrorCodes = (options, result) => { 302 | const errors = { 303 | 400: "Bad Request", 304 | 401: "Unauthorized", 305 | 403: "Forbidden", 306 | 404: "Not Found", 307 | 500: "Internal Server Error", 308 | 502: "Bad Gateway", 309 | 503: "Service Unavailable", 310 | ...options.errors 311 | }; 312 | const error = errors[result.status]; 313 | if (error) { 314 | throw new ApiError(options, result, error); 315 | } 316 | if (!result.ok) { 317 | const errorStatus = result.status ?? "unknown"; 318 | const errorStatusText = result.statusText ?? "unknown"; 319 | const errorBody = (() => { 320 | try { 321 | return JSON.stringify(result.body, null, 2); 322 | } catch (e) { 323 | return void 0; 324 | } 325 | })(); 326 | throw new ApiError( 327 | options, 328 | result, 329 | `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` 330 | ); 331 | } 332 | }; 333 | var request = (config, options, axiosClient = axios) => { 334 | return new CancelablePromise(async (resolve2, reject, onCancel) => { 335 | try { 336 | const url = getUrl(config, options); 337 | const formData = getFormData(options); 338 | const body = getRequestBody(options); 339 | const headers = await getHeaders(config, options, formData); 340 | if (!onCancel.isCancelled) { 341 | const response = await sendRequest(config, options, url, body, formData, headers, onCancel, axiosClient); 342 | const responseBody = getResponseBody(response); 343 | const responseHeader = getResponseHeader(response, options.responseHeader); 344 | const result = { 345 | url, 346 | ok: isSuccess(response.status), 347 | status: response.status, 348 | statusText: response.statusText, 349 | body: responseHeader ?? responseBody 350 | }; 351 | catchErrorCodes(options, result); 352 | resolve2(result.body); 353 | } 354 | } catch (error) { 355 | reject(error); 356 | } 357 | }); 358 | }; 359 | 360 | // api/core/AxiosHttpRequest.ts 361 | var AxiosHttpRequest = class extends BaseHttpRequest { 362 | constructor(config) { 363 | super(config); 364 | } 365 | /** 366 | * Request method 367 | * @param options The request options from the service 368 | * @returns CancelablePromise 369 | * @throws ApiError 370 | */ 371 | request(options) { 372 | return request(this.config, options); 373 | } 374 | }; 375 | 376 | // api/services/AuthHandlerService.ts 377 | var AuthHandlerService = class { 378 | constructor(httpRequest) { 379 | this.httpRequest = httpRequest; 380 | } 381 | /** 382 | * Get Auth Handler Settings 383 | * Get the list of the AuthHandlers 384 | * @returns SettingsResponse Successful Response 385 | * @throws ApiError 386 | */ 387 | getAuthHandlerSettings() { 388 | return this.httpRequest.request({ 389 | method: "GET", 390 | url: "/auth_handler/settings" 391 | }); 392 | } 393 | /** 394 | * Get Auth Handler Setting 395 | * Get the settings of a specific AuthHandler 396 | * @param authHandlerName 397 | * @returns Setting Successful Response 398 | * @throws ApiError 399 | */ 400 | getAuthHandlerSetting(authHandlerName) { 401 | return this.httpRequest.request({ 402 | method: "GET", 403 | url: "/auth_handler/settings/{auth_handler_name}", 404 | path: { 405 | "auth_handler_name": authHandlerName 406 | }, 407 | errors: { 408 | 422: `Validation Error` 409 | } 410 | }); 411 | } 412 | /** 413 | * Upsert Authenticator Setting 414 | * Upsert the settings of a specific AuthHandler 415 | * @param authHandlerName 416 | * @param requestBody 417 | * @returns Setting Successful Response 418 | * @throws ApiError 419 | */ 420 | upsertAuthenticatorSetting(authHandlerName, requestBody) { 421 | return this.httpRequest.request({ 422 | method: "PUT", 423 | url: "/auth_handler/settings/{auth_handler_name}", 424 | path: { 425 | "auth_handler_name": authHandlerName 426 | }, 427 | body: requestBody, 428 | mediaType: "application/json", 429 | errors: { 430 | 422: `Validation Error` 431 | } 432 | }); 433 | } 434 | }; 435 | 436 | // api/services/EmbedderService.ts 437 | var EmbedderService = class { 438 | constructor(httpRequest) { 439 | this.httpRequest = httpRequest; 440 | } 441 | /** 442 | * Get Embedders Settings 443 | * Get the list of the Embedders 444 | * @returns SettingsResponse Successful Response 445 | * @throws ApiError 446 | */ 447 | getEmbeddersSettings() { 448 | return this.httpRequest.request({ 449 | method: "GET", 450 | url: "/embedder/settings" 451 | }); 452 | } 453 | /** 454 | * Get Embedder Settings 455 | * Get settings and schema of the specified Embedder 456 | * @param languageEmbedderName 457 | * @returns Setting Successful Response 458 | * @throws ApiError 459 | */ 460 | getEmbedderSettings(languageEmbedderName) { 461 | return this.httpRequest.request({ 462 | method: "GET", 463 | url: "/embedder/settings/{languageEmbedderName}", 464 | path: { 465 | "languageEmbedderName": languageEmbedderName 466 | }, 467 | errors: { 468 | 422: `Validation Error` 469 | } 470 | }); 471 | } 472 | /** 473 | * Upsert Embedder Setting 474 | * Upsert the Embedder setting 475 | * @param languageEmbedderName 476 | * @param requestBody 477 | * @returns Setting Successful Response 478 | * @throws ApiError 479 | */ 480 | upsertEmbedderSetting(languageEmbedderName, requestBody) { 481 | return this.httpRequest.request({ 482 | method: "PUT", 483 | url: "/embedder/settings/{languageEmbedderName}", 484 | path: { 485 | "languageEmbedderName": languageEmbedderName 486 | }, 487 | body: requestBody, 488 | mediaType: "application/json", 489 | errors: { 490 | 422: `Validation Error` 491 | } 492 | }); 493 | } 494 | }; 495 | 496 | // api/services/LlmService.ts 497 | var LlmService = class { 498 | constructor(httpRequest) { 499 | this.httpRequest = httpRequest; 500 | } 501 | /** 502 | * Get LLMs Settings 503 | * Get the list of the Large Language Models 504 | * @returns SettingsResponse Successful Response 505 | * @throws ApiError 506 | */ 507 | getLlmsSettings() { 508 | return this.httpRequest.request({ 509 | method: "GET", 510 | url: "/llm/settings" 511 | }); 512 | } 513 | /** 514 | * Get Llm Settings 515 | * Get settings and schema of the specified Large Language Model 516 | * @param languageModelName 517 | * @returns Setting Successful Response 518 | * @throws ApiError 519 | */ 520 | getLlmSettings(languageModelName) { 521 | return this.httpRequest.request({ 522 | method: "GET", 523 | url: "/llm/settings/{languageModelName}", 524 | path: { 525 | "languageModelName": languageModelName 526 | }, 527 | errors: { 528 | 422: `Validation Error` 529 | } 530 | }); 531 | } 532 | /** 533 | * Upsert LLM Setting 534 | * Upsert the Large Language Model setting 535 | * @param languageModelName 536 | * @param requestBody 537 | * @returns Setting Successful Response 538 | * @throws ApiError 539 | */ 540 | upsertLlmSetting(languageModelName, requestBody) { 541 | return this.httpRequest.request({ 542 | method: "PUT", 543 | url: "/llm/settings/{languageModelName}", 544 | path: { 545 | "languageModelName": languageModelName 546 | }, 547 | body: requestBody, 548 | mediaType: "application/json", 549 | errors: { 550 | 422: `Validation Error` 551 | } 552 | }); 553 | } 554 | }; 555 | 556 | // api/services/MemoryService.ts 557 | var MemoryService = class { 558 | constructor(httpRequest) { 559 | this.httpRequest = httpRequest; 560 | } 561 | /** 562 | * Recall Memories From Text 563 | * Search k memories similar to given text. 564 | * @param text Find memories similar to this text. 565 | * @param k How many memories to return. 566 | * @returns MemoryRecall Successful Response 567 | * @throws ApiError 568 | */ 569 | recallMemoriesFromText(text, k = 100) { 570 | return this.httpRequest.request({ 571 | method: "GET", 572 | url: "/memory/recall", 573 | query: { 574 | "text": text, 575 | "k": k 576 | }, 577 | errors: { 578 | 422: `Validation Error` 579 | } 580 | }); 581 | } 582 | /** 583 | * Get Collections 584 | * Get list of available collections 585 | * @returns CollectionsList Successful Response 586 | * @throws ApiError 587 | */ 588 | getCollections() { 589 | return this.httpRequest.request({ 590 | method: "GET", 591 | url: "/memory/collections" 592 | }); 593 | } 594 | /** 595 | * Wipe Collections 596 | * Delete and create all collections 597 | * @returns DeleteResponse Successful Response 598 | * @throws ApiError 599 | */ 600 | wipeCollections() { 601 | return this.httpRequest.request({ 602 | method: "DELETE", 603 | url: "/memory/collections" 604 | }); 605 | } 606 | /** 607 | * Wipe Single Collection 608 | * Delete and recreate a collection 609 | * @param collectionId 610 | * @returns DeleteResponse Successful Response 611 | * @throws ApiError 612 | */ 613 | wipeSingleCollection(collectionId) { 614 | return this.httpRequest.request({ 615 | method: "DELETE", 616 | url: "/memory/collections/{collection_id}", 617 | path: { 618 | "collection_id": collectionId 619 | }, 620 | errors: { 621 | 422: `Validation Error` 622 | } 623 | }); 624 | } 625 | /** 626 | * Delete Point In Memory 627 | * Delete specific point in memory 628 | * @param collectionId 629 | * @param memoryId 630 | * @returns DeleteResponse Successful Response 631 | * @throws ApiError 632 | */ 633 | deletePointInMemory(collectionId, memoryId) { 634 | return this.httpRequest.request({ 635 | method: "DELETE", 636 | url: "/memory/collections/{collection_id}/points/{memory_id}", 637 | path: { 638 | "collection_id": collectionId, 639 | "memory_id": memoryId 640 | }, 641 | errors: { 642 | 422: `Validation Error` 643 | } 644 | }); 645 | } 646 | /** 647 | * Wipe Memory Points By Metadata 648 | * Delete points in memory by filter 649 | * @param collectionId 650 | * @param requestBody 651 | * @returns DeleteResponse Successful Response 652 | * @throws ApiError 653 | */ 654 | wipeMemoryPoints(collectionId, requestBody) { 655 | return this.httpRequest.request({ 656 | method: "DELETE", 657 | url: "/memory/collections/{collection_id}/points", 658 | path: { 659 | "collection_id": collectionId 660 | }, 661 | body: requestBody, 662 | mediaType: "application/json", 663 | errors: { 664 | 422: `Validation Error` 665 | } 666 | }); 667 | } 668 | /** 669 | * Get Conversation History 670 | * Get the specified user's conversation history from working memory 671 | * @returns any Successful Response 672 | * @throws ApiError 673 | */ 674 | getConversationHistory() { 675 | return this.httpRequest.request({ 676 | method: "GET", 677 | url: "/memory/conversation_history" 678 | }); 679 | } 680 | /** 681 | * Wipe Conversation History 682 | * Delete the specified user's conversation history from working memory 683 | * @returns DeleteResponse Successful Response 684 | * @throws ApiError 685 | */ 686 | wipeConversationHistory() { 687 | return this.httpRequest.request({ 688 | method: "DELETE", 689 | url: "/memory/conversation_history" 690 | }); 691 | } 692 | }; 693 | 694 | // api/services/PluginsService.ts 695 | var PluginsService = class { 696 | constructor(httpRequest) { 697 | this.httpRequest = httpRequest; 698 | } 699 | /** 700 | * List Available Plugins 701 | * List both installed and registry plugins 702 | * @param query 703 | * @returns PluginsList Successful Response 704 | * @throws ApiError 705 | */ 706 | listAvailablePlugins(query) { 707 | return this.httpRequest.request({ 708 | method: "GET", 709 | url: "/plugins", 710 | query: { 711 | "query": query 712 | } 713 | }); 714 | } 715 | /** 716 | * Install Plugin 717 | * Install a new plugin from a zip file 718 | * @param formData 719 | * @returns FileResponse Successful Response 720 | * @throws ApiError 721 | */ 722 | installPlugin(formData) { 723 | return this.httpRequest.request({ 724 | method: "POST", 725 | url: "/plugins/upload", 726 | formData, 727 | mediaType: "multipart/form-data", 728 | errors: { 729 | 422: `Validation Error` 730 | } 731 | }); 732 | } 733 | /** 734 | * Install Plugin From Registry 735 | * Install a new plugin from external repository 736 | * @param requestBody 737 | * @returns FileResponse Successful Response 738 | * @throws ApiError 739 | */ 740 | installPluginFromRegistry(requestBody) { 741 | return this.httpRequest.request({ 742 | method: "POST", 743 | url: "/plugins/upload/registry", 744 | body: requestBody, 745 | mediaType: "application/json", 746 | errors: { 747 | 422: `Validation Error` 748 | } 749 | }); 750 | } 751 | /** 752 | * Toggle Plugin 753 | * Enable or disable a single plugin 754 | * @param pluginId 755 | * @returns any Successful Response 756 | * @throws ApiError 757 | */ 758 | togglePlugin(pluginId) { 759 | return this.httpRequest.request({ 760 | method: "PUT", 761 | url: "/plugins/toggle/{plugin_id}", 762 | path: { 763 | "plugin_id": pluginId 764 | }, 765 | errors: { 766 | 422: `Validation Error` 767 | } 768 | }); 769 | } 770 | /** 771 | * Get Plugin Details 772 | * Returns information on a single plugin 773 | * @param pluginId 774 | * @returns Plugin Successful Response 775 | * @throws ApiError 776 | */ 777 | getPluginDetails(pluginId) { 778 | return this.httpRequest.request({ 779 | method: "GET", 780 | url: "/plugins/{plugin_id}", 781 | path: { 782 | "plugin_id": pluginId 783 | }, 784 | errors: { 785 | 422: `Validation Error` 786 | } 787 | }); 788 | } 789 | /** 790 | * Delete Plugin 791 | * Physically remove a plugin 792 | * @param pluginId 793 | * @returns DeleteResponse Successful Response 794 | * @throws ApiError 795 | */ 796 | deletePlugin(pluginId) { 797 | return this.httpRequest.request({ 798 | method: "DELETE", 799 | url: "/plugins/{plugin_id}", 800 | path: { 801 | "plugin_id": pluginId 802 | }, 803 | errors: { 804 | 422: `Validation Error` 805 | } 806 | }); 807 | } 808 | /** 809 | * Get Plugins Settings 810 | * Returns the settings of all the plugins 811 | * @returns SettingsResponse Successful Response 812 | * @throws ApiError 813 | */ 814 | getPluginsSettings() { 815 | return this.httpRequest.request({ 816 | method: "GET", 817 | url: "/plugins/settings" 818 | }); 819 | } 820 | /** 821 | * Get Plugin Settings 822 | * Returns the settings of a specific plugin 823 | * @param pluginId 824 | * @returns any Successful Response 825 | * @throws ApiError 826 | */ 827 | getPluginSettings(pluginId) { 828 | return this.httpRequest.request({ 829 | method: "GET", 830 | url: "/plugins/settings/{plugin_id}", 831 | path: { 832 | "plugin_id": pluginId 833 | }, 834 | errors: { 835 | 422: `Validation Error` 836 | } 837 | }); 838 | } 839 | /** 840 | * Upsert Plugin Settings 841 | * Updates the settings of a specific plugin 842 | * @param pluginId 843 | * @param requestBody 844 | * @returns Setting Successful Response 845 | * @throws ApiError 846 | */ 847 | upsertPluginSettings(pluginId, requestBody) { 848 | return this.httpRequest.request({ 849 | method: "PUT", 850 | url: "/plugins/settings/{plugin_id}", 851 | path: { 852 | "plugin_id": pluginId 853 | }, 854 | body: requestBody, 855 | mediaType: "application/json", 856 | errors: { 857 | 422: `Validation Error` 858 | } 859 | }); 860 | } 861 | }; 862 | 863 | // api/services/RabbitHoleService.ts 864 | var RabbitHoleService = class { 865 | constructor(httpRequest) { 866 | this.httpRequest = httpRequest; 867 | } 868 | /** 869 | * Upload File 870 | * Upload a file containing text (.txt, .md, .pdf, etc.). File content will be extracted and segmented into chunks. 871 | * Chunks will be then vectorized and stored into documents memory. 872 | * @param formData 873 | * @returns FileResponse Successful Response 874 | * @throws ApiError 875 | */ 876 | uploadFile(formData) { 877 | return this.httpRequest.request({ 878 | method: "POST", 879 | url: "/rabbithole", 880 | formData, 881 | mediaType: "multipart/form-data", 882 | errors: { 883 | 422: `Validation Error` 884 | } 885 | }); 886 | } 887 | /** 888 | * Upload URL 889 | * Upload a URL. Website content will be extracted and segmented into chunks. 890 | * Chunks will be then vectorized and stored into documents memory. 891 | * @param requestBody 892 | * @returns WebResponse Successful Response 893 | * @throws ApiError 894 | */ 895 | uploadUrl(requestBody) { 896 | return this.httpRequest.request({ 897 | method: "POST", 898 | url: "/rabbithole/web", 899 | body: requestBody, 900 | mediaType: "application/json", 901 | errors: { 902 | 422: `Validation Error` 903 | } 904 | }); 905 | } 906 | /** 907 | * Upload Memory 908 | * Upload a memory json file to the cat memory 909 | * @param formData 910 | * @returns any Successful Response 911 | * @throws ApiError 912 | */ 913 | uploadMemory(formData) { 914 | return this.httpRequest.request({ 915 | method: "POST", 916 | url: "/rabbithole/memory", 917 | formData, 918 | mediaType: "multipart/form-data", 919 | errors: { 920 | 422: `Validation Error` 921 | } 922 | }); 923 | } 924 | /** 925 | * Get Allowed Mimetypes 926 | * Retrieve the allowed mimetypes that can be ingested by the Rabbit Hole 927 | * @returns any Successful Response 928 | * @throws ApiError 929 | */ 930 | getAllowedMimetypes() { 931 | return this.httpRequest.request({ 932 | method: "GET", 933 | url: "/rabbithole/allowed-mimetypes" 934 | }); 935 | } 936 | }; 937 | 938 | // api/services/SettingsService.ts 939 | var SettingsService = class { 940 | constructor(httpRequest) { 941 | this.httpRequest = httpRequest; 942 | } 943 | /** 944 | * Get Settings 945 | * Get the entire list of settings available in the database 946 | * @param search The setting to search 947 | * @returns SettingsResponse Successful Response 948 | * @throws ApiError 949 | */ 950 | getSettings(search = "") { 951 | return this.httpRequest.request({ 952 | method: "GET", 953 | url: "/settings", 954 | query: { 955 | "search": search 956 | }, 957 | errors: { 958 | 422: `Validation Error` 959 | } 960 | }); 961 | } 962 | /** 963 | * Create Setting 964 | * Create a new setting in the database 965 | * @param requestBody 966 | * @returns Setting Successful Response 967 | * @throws ApiError 968 | */ 969 | createSetting(requestBody) { 970 | return this.httpRequest.request({ 971 | method: "POST", 972 | url: "/settings", 973 | body: requestBody, 974 | mediaType: "application/json", 975 | errors: { 976 | 422: `Validation Error` 977 | } 978 | }); 979 | } 980 | /** 981 | * Get Setting 982 | * Get the a specific setting from the database 983 | * @param settingId 984 | * @returns Setting Successful Response 985 | * @throws ApiError 986 | */ 987 | getSetting(settingId) { 988 | return this.httpRequest.request({ 989 | method: "GET", 990 | url: "/settings/{settingId}", 991 | path: { 992 | "settingId": settingId 993 | }, 994 | errors: { 995 | 422: `Validation Error` 996 | } 997 | }); 998 | } 999 | /** 1000 | * Delete Setting 1001 | * Delete a specific setting in the database 1002 | * @param settingId 1003 | * @returns any Successful Response 1004 | * @throws ApiError 1005 | */ 1006 | deleteSetting(settingId) { 1007 | return this.httpRequest.request({ 1008 | method: "DELETE", 1009 | url: "/settings/{settingId}", 1010 | path: { 1011 | "settingId": settingId 1012 | }, 1013 | errors: { 1014 | 422: `Validation Error` 1015 | } 1016 | }); 1017 | } 1018 | /** 1019 | * Update Setting 1020 | * Update a specific setting in the database if it exists 1021 | * @param settingId 1022 | * @param requestBody 1023 | * @returns Setting Successful Response 1024 | * @throws ApiError 1025 | */ 1026 | updateSetting(settingId, requestBody) { 1027 | return this.httpRequest.request({ 1028 | method: "PUT", 1029 | url: "/settings/{settingId}", 1030 | path: { 1031 | "settingId": settingId 1032 | }, 1033 | body: requestBody, 1034 | mediaType: "application/json", 1035 | errors: { 1036 | 422: `Validation Error` 1037 | } 1038 | }); 1039 | } 1040 | }; 1041 | 1042 | // api/services/StatusService.ts 1043 | var StatusService = class { 1044 | constructor(httpRequest) { 1045 | this.httpRequest = httpRequest; 1046 | } 1047 | /** 1048 | * Home 1049 | * Server status 1050 | * @returns Status Successful Response 1051 | * @throws ApiError 1052 | */ 1053 | home() { 1054 | return this.httpRequest.request({ 1055 | method: "GET", 1056 | url: "/" 1057 | }); 1058 | } 1059 | /** 1060 | * Message With Cat 1061 | * Get a response from the Cat 1062 | * @param requestBody 1063 | * @returns CatMessage Successful Response 1064 | * @throws ApiError 1065 | */ 1066 | messageWithCat(requestBody) { 1067 | return this.httpRequest.request({ 1068 | method: "POST", 1069 | url: "/message", 1070 | body: requestBody, 1071 | mediaType: "application/json", 1072 | errors: { 1073 | 422: `Validation Error` 1074 | } 1075 | }); 1076 | } 1077 | }; 1078 | 1079 | // api/services/UserAuthService.ts 1080 | var UserAuthService = class { 1081 | constructor(httpRequest) { 1082 | this.httpRequest = httpRequest; 1083 | } 1084 | /** 1085 | * Get Available Permissions 1086 | * Returns all available resources and permissions. 1087 | * @returns AuthPermission Successful Response 1088 | * @throws ApiError 1089 | */ 1090 | getAvailablePermissions() { 1091 | return this.httpRequest.request({ 1092 | method: "GET", 1093 | url: "/auth/available-permissions" 1094 | }); 1095 | } 1096 | /** 1097 | * Auth Token 1098 | * Endpoint called from client to get a JWT from local identity provider. 1099 | * This endpoint receives username and password as form-data, validates credentials and issues a JWT. 1100 | * @param requestBody 1101 | * @returns JWTResponse Successful Response 1102 | * @throws ApiError 1103 | */ 1104 | authToken(requestBody) { 1105 | return this.httpRequest.request({ 1106 | method: "POST", 1107 | url: "/auth/token", 1108 | body: requestBody, 1109 | mediaType: "application/json", 1110 | errors: { 1111 | 422: `Validation Error` 1112 | } 1113 | }); 1114 | } 1115 | }; 1116 | 1117 | // api/services/UsersService.ts 1118 | var UsersService = class { 1119 | constructor(httpRequest) { 1120 | this.httpRequest = httpRequest; 1121 | } 1122 | /** 1123 | * Create User 1124 | * @param requestBody 1125 | * @returns UserResponse Successful Response 1126 | * @throws ApiError 1127 | */ 1128 | createUser(requestBody) { 1129 | return this.httpRequest.request({ 1130 | method: "POST", 1131 | url: "/users/", 1132 | body: requestBody, 1133 | mediaType: "application/json", 1134 | errors: { 1135 | 422: `Validation Error` 1136 | } 1137 | }); 1138 | } 1139 | /** 1140 | * Read Users 1141 | * @param skip 1142 | * @param limit 1143 | * @returns UserResponse Successful Response 1144 | * @throws ApiError 1145 | */ 1146 | readUsers(skip, limit = 100) { 1147 | return this.httpRequest.request({ 1148 | method: "GET", 1149 | url: "/users/", 1150 | query: { 1151 | "skip": skip, 1152 | "limit": limit 1153 | }, 1154 | errors: { 1155 | 422: `Validation Error` 1156 | } 1157 | }); 1158 | } 1159 | /** 1160 | * Read User 1161 | * @param userId 1162 | * @returns UserResponse Successful Response 1163 | * @throws ApiError 1164 | */ 1165 | readUser(userId) { 1166 | return this.httpRequest.request({ 1167 | method: "GET", 1168 | url: "/users/{user_id}", 1169 | path: { 1170 | "user_id": userId 1171 | }, 1172 | errors: { 1173 | 422: `Validation Error` 1174 | } 1175 | }); 1176 | } 1177 | /** 1178 | * Update User 1179 | * @param userId 1180 | * @param requestBody 1181 | * @returns UserResponse Successful Response 1182 | * @throws ApiError 1183 | */ 1184 | updateUser(userId, requestBody) { 1185 | return this.httpRequest.request({ 1186 | method: "PUT", 1187 | url: "/users/{user_id}", 1188 | path: { 1189 | "user_id": userId 1190 | }, 1191 | body: requestBody, 1192 | mediaType: "application/json", 1193 | errors: { 1194 | 422: `Validation Error` 1195 | } 1196 | }); 1197 | } 1198 | /** 1199 | * Delete User 1200 | * @param userId 1201 | * @returns UserResponse Successful Response 1202 | * @throws ApiError 1203 | */ 1204 | deleteUser(userId) { 1205 | return this.httpRequest.request({ 1206 | method: "DELETE", 1207 | url: "/users/{user_id}", 1208 | path: { 1209 | "user_id": userId 1210 | }, 1211 | errors: { 1212 | 422: `Validation Error` 1213 | } 1214 | }); 1215 | } 1216 | }; 1217 | 1218 | // api/CCatAPI.ts 1219 | var CCatAPI = class { 1220 | authHandler; 1221 | embedder; 1222 | llm; 1223 | memory; 1224 | plugins; 1225 | rabbitHole; 1226 | settings; 1227 | status; 1228 | userAuth; 1229 | users; 1230 | request; 1231 | constructor(config, HttpRequest = AxiosHttpRequest) { 1232 | this.request = new HttpRequest({ 1233 | BASE: config?.BASE ?? "", 1234 | VERSION: config?.VERSION ?? "1.6.2", 1235 | WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false, 1236 | CREDENTIALS: config?.CREDENTIALS ?? "include", 1237 | TOKEN: config?.TOKEN, 1238 | USERNAME: config?.USERNAME, 1239 | PASSWORD: config?.PASSWORD, 1240 | HEADERS: config?.HEADERS, 1241 | ENCODE_PATH: config?.ENCODE_PATH 1242 | }); 1243 | this.authHandler = new AuthHandlerService(this.request); 1244 | this.embedder = new EmbedderService(this.request); 1245 | this.llm = new LlmService(this.request); 1246 | this.memory = new MemoryService(this.request); 1247 | this.plugins = new PluginsService(this.request); 1248 | this.rabbitHole = new RabbitHoleService(this.request); 1249 | this.settings = new SettingsService(this.request); 1250 | this.status = new StatusService(this.request); 1251 | this.userAuth = new UserAuthService(this.request); 1252 | this.users = new UsersService(this.request); 1253 | } 1254 | }; 1255 | 1256 | // api/utils.ts 1257 | var AcceptedMemoryTypes = [ 1258 | "application/json" 1259 | ]; 1260 | var AcceptedPluginTypes = [ 1261 | "application/zip", 1262 | "application/x-tar" 1263 | ]; 1264 | var WebSocketState = /* @__PURE__ */ ((WebSocketState2) => { 1265 | WebSocketState2[WebSocketState2["CONNECTING"] = 0] = "CONNECTING"; 1266 | WebSocketState2[WebSocketState2["OPEN"] = 1] = "OPEN"; 1267 | WebSocketState2[WebSocketState2["CLOSING"] = 2] = "CLOSING"; 1268 | WebSocketState2[WebSocketState2["CLOSED"] = 3] = "CLOSED"; 1269 | return WebSocketState2; 1270 | })(WebSocketState || {}); 1271 | var isTokenResponse = (value) => { 1272 | return !!(value && typeof value === "object" && "content" in value && "type" in value && value.type !== "error"); 1273 | }; 1274 | var isMessageResponse = (value) => { 1275 | return !!(value && typeof value === "object" && ("text" in value || "audio" in value || "image" in value) && "user_id" in value && "who" in value && "type" in value && value.type !== "error"); 1276 | }; 1277 | 1278 | // api/client.ts 1279 | var CatClient = class { 1280 | config; 1281 | apiClient; 1282 | ws; 1283 | connectedHandler; 1284 | disconnectedHandler; 1285 | messageHandler; 1286 | errorHandler; 1287 | explicitlyClosed = false; 1288 | retried = 0; 1289 | /** 1290 | * Initialize the class with the specified settings 1291 | * @param settings The settings to pass 1292 | */ 1293 | constructor(settings) { 1294 | this.config = { 1295 | secure: false, 1296 | instant: true, 1297 | timeout: 1e4, 1298 | port: 1865, 1299 | userId: "user", 1300 | ...settings 1301 | }; 1302 | if (this.config.instant) this.init(); 1303 | } 1304 | initWebSocket() { 1305 | const wsConfig = this.config.ws = { 1306 | delay: 3e3, 1307 | retries: 3, 1308 | ...this.config.ws 1309 | }; 1310 | const userId = this.config.userId ?? "user"; 1311 | const url = this.url.replace(/http/g, "ws"); 1312 | const query = this.config.credential ? `?token=${this.config.credential}` : ""; 1313 | this.ws = new WebSocket(`${url}/ws/${userId}${query}`); 1314 | this.ws.onopen = () => { 1315 | this.retried = 0; 1316 | this.connectedHandler?.(); 1317 | }; 1318 | this.ws.onclose = () => { 1319 | if (!this.explicitlyClosed) { 1320 | this.retried += 1; 1321 | if (wsConfig.retries < 0 || this.retried < wsConfig.retries) { 1322 | setTimeout(() => this.initWebSocket(), wsConfig.delay); 1323 | } else wsConfig.onFailed?.({ 1324 | name: "FailedRetry", 1325 | description: `Failed to connect WebSocket after ${wsConfig.retries} retries.` 1326 | }); 1327 | } 1328 | this.disconnectedHandler?.(); 1329 | }; 1330 | this.ws.onmessage = (event) => { 1331 | if (typeof event.data != "string") return; 1332 | const data = JSON.parse(event.data); 1333 | if (isMessageResponse(data)) { 1334 | this.messageHandler?.(data); 1335 | return; 1336 | } else if (isTokenResponse(data)) { 1337 | this.messageHandler?.(data); 1338 | return; 1339 | } 1340 | this.errorHandler?.(data); 1341 | }; 1342 | this.ws.onerror = (event) => { 1343 | this.errorHandler?.({ 1344 | name: "SocketError", 1345 | description: "Something went wrong while connecting to the server" 1346 | }, event); 1347 | }; 1348 | } 1349 | /** 1350 | * Resets the current `CatClient` instance. 1351 | * @returns The updated `CatClient` instance. 1352 | */ 1353 | reset() { 1354 | this.retried = 0; 1355 | this.close(); 1356 | this.ws = void 0; 1357 | this.apiClient = void 0; 1358 | return this; 1359 | } 1360 | /** 1361 | * Initialize the WebSocket and the API Client 1362 | * @returns The current `CatClient` class instance 1363 | */ 1364 | init() { 1365 | if (!this.ws && !this.apiClient) { 1366 | this.initWebSocket(); 1367 | this.apiClient = new CCatAPI({ 1368 | BASE: `${this.url}`, 1369 | HEADERS: { 1370 | ...this.config.credential ? { 1371 | "access_token": this.config.credential, 1372 | "Authorization": `Bearer ${this.config.credential}` 1373 | } : {}, 1374 | "user_id": this.config.userId ?? "user" 1375 | } 1376 | }); 1377 | } 1378 | return this; 1379 | } 1380 | /** 1381 | * Sends a message to the Cat through the WebSocket connection. 1382 | * @param msg The message to send to the Cat. 1383 | * @param userId The ID of the user sending the message. Defaults to "user". 1384 | * @throws If the message does not contain text, audio or image. 1385 | * @returns The `CatClient` instance. 1386 | */ 1387 | send(msg, userId) { 1388 | if (this.ws?.readyState !== WebSocket.OPEN) { 1389 | this.errorHandler?.({ 1390 | name: "SocketClosed", 1391 | description: "The connection to the server was closed" 1392 | }); 1393 | return this; 1394 | } 1395 | if ("text" in msg || "audio" in msg || "image" in msg) { 1396 | const jsonMessage = JSON.stringify({ 1397 | ...msg, 1398 | user_id: userId ?? (this.config.userId ?? "user") 1399 | }); 1400 | this.ws.send(jsonMessage); 1401 | } else throw new Error("The message argument must contain either text, audio or image."); 1402 | return this; 1403 | } 1404 | /** 1405 | * @returns The API Client 1406 | */ 1407 | get api() { 1408 | return this.apiClient; 1409 | } 1410 | /** 1411 | * Setter for the authentication key or token used by the client. This will also reset the client. 1412 | * @param key The authentication key or token to be set. 1413 | */ 1414 | set credential(key) { 1415 | this.config.credential = key; 1416 | this.reset().init(); 1417 | } 1418 | /** 1419 | * Setter for the user ID used by the client. This will also reset the client. 1420 | * @param user The user ID to be set. 1421 | */ 1422 | set userId(user) { 1423 | this.config.userId = user; 1424 | this.reset().init(); 1425 | } 1426 | /** 1427 | * Closes the WebSocket connection. 1428 | * @returns The `CatClient` instance. 1429 | */ 1430 | close() { 1431 | this.ws?.close(); 1432 | this.explicitlyClosed = true; 1433 | return this; 1434 | } 1435 | /** 1436 | * Returns the current state of the WebSocket connection. 1437 | * @returns The WebSocketState enum value representing the current state of the WebSocket connection. 1438 | */ 1439 | get socketState() { 1440 | return this.ws?.readyState ?? 3 /* CLOSED */; 1441 | } 1442 | /** 1443 | * Calls the handler when the WebSocket is connected 1444 | * @param handler The function to call 1445 | * @returns The current `CatClient` class instance 1446 | */ 1447 | onConnected(handler) { 1448 | this.connectedHandler = handler; 1449 | return this; 1450 | } 1451 | /** 1452 | * Calls the handler when the WebSocket is disconnected 1453 | * @param handler The function to call 1454 | * @returns The current `CatClient` class instance 1455 | */ 1456 | onDisconnected(handler) { 1457 | this.disconnectedHandler = handler; 1458 | return this; 1459 | } 1460 | /** 1461 | * Calls the handler when a new message arrives from the WebSocket 1462 | * @param handler The function to call 1463 | * @returns The current `CatClient` class instance 1464 | */ 1465 | onMessage(handler) { 1466 | this.messageHandler = handler; 1467 | return this; 1468 | } 1469 | /** 1470 | * Calls the handler when the WebSocket catches an exception 1471 | * @param handler The function to call 1472 | * @returns The current `CatClient` class instance 1473 | */ 1474 | onError(handler) { 1475 | this.errorHandler = handler; 1476 | return this; 1477 | } 1478 | get url() { 1479 | return `http${this.config.secure ? "s" : ""}:// 1480 | ${this.config.host} 1481 | ${this.config.port ? `:${this.config.port}` : ""} 1482 | `.replace(/\s/g, ""); 1483 | } 1484 | }; 1485 | 1486 | // index.ts 1487 | var index_default = CatClient; 1488 | export { 1489 | AcceptedMemoryTypes, 1490 | AcceptedPluginTypes, 1491 | ApiError, 1492 | CancelError, 1493 | CancelablePromise, 1494 | CatClient, 1495 | WebSocketState, 1496 | index_default as default, 1497 | isMessageResponse, 1498 | isTokenResponse 1499 | }; 1500 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import { CatClient } from './api/client'; 2 | 3 | export default CatClient; 4 | 5 | export * from './api/client'; 6 | export * from './api/utils'; 7 | 8 | export { ApiError } from './api/core/ApiError'; 9 | export { CancelablePromise, CancelError } from './api/core/CancelablePromise'; 10 | 11 | export type { AuthPermission } from './api/models/AuthPermission'; 12 | export type { AuthResource } from './api/models/AuthResource'; 13 | export type { BodyInstallPlugin } from './api/models/BodyInstallPlugin'; 14 | export type { BodyUploadFile } from './api/models/BodyUploadFile'; 15 | export type { BodyUploadMemory } from './api/models/BodyUploadMemory'; 16 | export type { BodyUploadUrl } from './api/models/BodyUploadUrl'; 17 | export type { CatMessage } from './api/models/CatMessage'; 18 | export type { Collection } from './api/models/Collection'; 19 | export type { CollectionData } from './api/models/CollectionData'; 20 | export type { CollectionsList } from './api/models/CollectionsList'; 21 | export type { ConversationMessage } from './api/models/ConversationMessage'; 22 | export type { DeleteResponse } from './api/models/DeleteResponse'; 23 | export type { FileResponse } from './api/models/FileResponse'; 24 | export type { HTTPValidationError } from './api/models/HTTPValidationError'; 25 | export type { JWTResponse } from './api/models/JWTResponse'; 26 | export type { MemoryRecall } from './api/models/MemoryRecall'; 27 | export type { MessageWhy } from './api/models/MessageWhy'; 28 | export type { Metadata } from './api/models/Metadata'; 29 | export type { Plugin } from './api/models/Plugin'; 30 | export type { PluginsList } from './api/models/PluginsList'; 31 | export type { QueryData } from './api/models/QueryData'; 32 | export type { Setting } from './api/models/Setting'; 33 | export type { SettingBody } from './api/models/SettingBody'; 34 | export type { SettingsResponse } from './api/models/SettingsResponse'; 35 | export type { Status } from './api/models/Status'; 36 | export type { UserCreate } from './api/models/UserCreate'; 37 | export type { UserCredentials } from './api/models/UserCredentials'; 38 | export type { UserResponse } from './api/models/UserResponse'; 39 | export type { UserUpdate } from './api/models/UserUpdate'; 40 | export type { VectorsData } from './api/models/VectorsData'; 41 | export type { WebResponse } from './api/models/WebResponse'; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ccat-api", 3 | "description": "API Client to communicate with the Cheshire Cat AI", 4 | "license": "MIT", 5 | "version": "0.12.1", 6 | "author": "zAlweNy26", 7 | "main": "dist/index.js", 8 | "module": "dist/index.mjs", 9 | "types": "dist/index.d.ts", 10 | "files": [ 11 | "dist/**" 12 | ], 13 | "keywords": [ 14 | "ccat", 15 | "cheshire-cat", 16 | "api", 17 | "client", 18 | "fastapi", 19 | "openapi", 20 | "ai", 21 | "llm", 22 | "chat", 23 | "bot" 24 | ], 25 | "repository": { 26 | "type": "git", 27 | "url": "https://github.com/zAlweNy26/ccat-api.git" 28 | }, 29 | "bugs": { 30 | "url": "https://github.com/zAlweNy26/ccat-api/issues" 31 | }, 32 | "homepage": "https://github.com/zAlweNy26/ccat-api", 33 | "scripts": { 34 | "build": "tsup index.ts --format cjs,esm --dts", 35 | "release": "pnpm run build && changeset publish", 36 | "lint": "eslint . --ext .js,.ts --fix --ignore-path .gitignore", 37 | "start": "ts-node index.ts", 38 | "generate": "openapi --input ./catapi.json --output ./api --client axios --name CCatAPI --useUnionTypes" 39 | }, 40 | "devDependencies": { 41 | "@changesets/cli": "^2.27.11", 42 | "@types/node": "^22.10.7", 43 | "@typescript-eslint/eslint-plugin": "^7.16.0", 44 | "@typescript-eslint/parser": "^7.16.0", 45 | "eslint": "^8.57.0", 46 | "openapi-typescript-codegen": "^0.29.0", 47 | "ts-node": "^10.9.2", 48 | "tsup": "^8.3.5", 49 | "typescript": "^5.7.3" 50 | }, 51 | "dependencies": { 52 | "@types/ws": "^8.5.13", 53 | "axios": "^1.7.9", 54 | "form-data": "^4.0.1", 55 | "isomorphic-ws": "^5.0.0", 56 | "ws": "^8.18.0" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | ".eslintrc.cjs", 4 | "./api/**/*.ts", 5 | "index.ts" 6 | ], 7 | "compilerOptions": { 8 | "useDefineForClassFields": true, 9 | "lib": [ 10 | "DOM", 11 | "DOM.Iterable", 12 | "ES2022" 13 | ], 14 | "target": "Es2022", 15 | "module": "CommonJS", 16 | "esModuleInterop": true, 17 | "forceConsistentCasingInFileNames": true, 18 | "strict": true, 19 | "skipLibCheck": true, 20 | "resolveJsonModule": true, 21 | "allowJs": true, 22 | "allowSyntheticDefaultImports": true, 23 | "noUncheckedIndexedAccess": true, 24 | "noEmit": true 25 | } 26 | } --------------------------------------------------------------------------------