├── .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 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
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