UNPKG

@brian-ai/sdk

Version:

Official Typescript SDK for Brian AI.

547 lines (541 loc) 15.9 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { BadRequestError: () => BadRequestError, BrianSDK: () => BrianSDK, BrianSDKError: () => BrianSDKError, InternalServerError: () => InternalServerError, NotFoundError: () => NotFoundError, RateLimitError: () => RateLimitError, SDKInitializationError: () => SDKInitializationError }); module.exports = __toCommonJS(src_exports); // src/sdk.ts var import_ky2 = __toESM(require("ky"), 1); // src/errors.ts var BrianSDKError = class extends Error { name; message; cause; /** * @dev The constructor for the SDKInitializationError class. */ constructor({ name, message, cause }) { super(message); this.name = name; this.message = message; this.cause = cause; } }; var SDKInitializationError = class extends BrianSDKError { /** * @dev The constructor for the RateLimitError class. */ constructor({ cause, message }) { super({ name: "SDKInitializationError", message: `Error while initializing SDK: ${message}.`, cause }); } }; var BadRequestError = class extends BrianSDKError { /** * @dev The constructor for the BadRequestError class. */ constructor({ cause }) { super({ name: "BadRequestError", message: "Bad request, check your input body.", cause }); } }; var NotFoundError = class extends BrianSDKError { /** * @dev The constructor for the NotFoundError class. */ constructor({ cause }) { super({ name: "NotFoundError", message: "Requested entity was not found.", cause }); } }; var RateLimitError = class extends BrianSDKError { /** * @dev The constructor for the RateLimitError class. */ constructor({ cause }) { super({ name: "RateLimitError", message: "API rate limit exceeded.", cause }); } }; var InternalServerError = class extends BrianSDKError { /** * @dev The constructor for the InternalServerError class. */ constructor({ cause }) { super({ name: "InternalServerError", message: "Internal server error.", cause }); } }; // src/knowledge-bases/index.ts var import_ky = __toESM(require("ky"), 1); var BrianKnowledgeBaseSDK = class { apiUrl; apiVersion; options; constructor({ apiUrl = "https://api.brianknows.org", apiKey, apiVersion }) { this.apiUrl = apiUrl; if (!apiKey || !apiKey.startsWith("brian_")) { throw new SDKInitializationError({ message: `Invalid API Key: ${apiKey}` }); } this.options = { headers: { accept: "application/json", "Content-Type": "application/json", "x-brian-api-key": apiKey }, throwHttpErrors: false, timeout: 3e4 }; this.apiVersion = apiVersion || "v0"; } /** * @dev Creates a new knowledge base. * @param {CreateKnowledgeBaseBody} body - The body for creating a new knowledge base. * @returns {Promise<KnowledgeBase>} The created knowledge base. */ async createKnowledgeBase({ name, description }) { const response = await import_ky.default.post( `${this.apiUrl}/api/${this.apiVersion}/knowledge-bases`, { body: JSON.stringify({ name, description }), ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { throw new BadRequestError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result } = await response.json(); return result; } /** * @dev Gets all knowledge bases associated with the given API key. * @returns {Promise<KnowledgeBase[]>} The knowledge bases associated with the given API key. */ async getKnowledgeBoxes() { const response = await import_ky.default.get( `${this.apiUrl}/api/${this.apiVersion}/knowledge-bases`, { ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { throw new BadRequestError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result } = await response.json(); return result; } /** * @dev Gets a knowledge base by its ID. * @param {number} kbId - The ID of the knowledge base. * @returns {Promise<KnowledgeBase>} The knowledge base with the given ID. */ async getKnowledgeBox(kbId) { const response = await import_ky.default.get( `${this.apiUrl}/api/${this.apiVersion}/knowledge-bases/${kbId}`, { ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 404) { throw new NotFoundError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result } = await response.json(); return result; } /** * @dev Deletes a knowledge box by its ID. * @param {number} kbId - The ID of the knowledge box. * @returns {Promise<string>} "ok" if everything went smoothly. */ async deleteKnowledgeBox(kbId) { const response = await import_ky.default.delete( `${this.apiUrl}/api/${this.apiVersion}/knowledge-bases/${kbId}`, { ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 404) { throw new NotFoundError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result } = await response.json(); return result; } }; // src/sdk.ts var BrianSDK = class { apiUrl; apiVersion; options; kb; /** * @dev The constructor for the BrianSDK class. * @param {BrianSDKOptions} options - The options for initializing SDK. */ constructor({ apiUrl = "https://api.brianknows.org", apiKey, apiVersion }) { this.apiUrl = apiUrl; if (!apiKey || !apiKey.startsWith("brian_")) { throw new SDKInitializationError({ message: `Invalid API Key: ${apiKey}` }); } this.options = { headers: { accept: "application/json", "Content-Type": "application/json", "x-brian-api-key": apiKey }, throwHttpErrors: false, timeout: 6e4 }; this.apiVersion = apiVersion || "v0"; this.kb = new BrianKnowledgeBaseSDK({ apiUrl, apiKey, apiVersion }); } /** * @dev Chat with the Brian agent via API. * @param {ChatRequestBody} body - The request body sent to the Brian API. * @returns {Promise<TransactionResult[] | AskResult | ChatMissingParameterResponse>} - result of the chat with Brian. */ async chat(body) { try { const response = await import_ky2.default.post( `${this.apiUrl}/api/${this.apiVersion}/agent`, { body: JSON.stringify({ ...body }), ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { return cause; } if (response.status === 429) { throw new RateLimitError({ cause }); } if (response.status === 500) { throw new InternalServerError({ cause }); } } const { result } = await response.json(); return result; } catch (error) { if (error instanceof BadRequestError) { return error.cause; } throw new InternalServerError({ cause: error.cause }); } } /** * @dev Asks the Brian API a question about documents or links. * @param {AskRequestBody} body - The request body sent to the Brian API. * @returns {Promise<AskResult>} The result from the Brian API. */ async ask(body) { const response = await import_ky2.default.post( `${this.apiUrl}/api/${this.apiVersion}/agent/knowledge`, { body: JSON.stringify({ ...body }), ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { throw new BadRequestError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result } = await response.json(); return result; } /** * @dev Extracts parameters from a given text. * @param {ExtractParametersRequestBody} body - The request body sent to the Brian API. * @returns {Promise<ExtractParametersResult>} The result from the Brian API. */ async extract(body) { const response = await import_ky2.default.post( `${this.apiUrl}/api/${this.apiVersion}/agent/parameters-extraction`, { body: JSON.stringify({ ...body }), ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { throw new BadRequestError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result } = await response.json(); return result; } /** * @dev Generates code from a given text. * @param {GenerateCodeRequestBody} body - The request body sent to the Brian API. * @param {boolean} removeMarkdown - Whether to remove markdown from the generated code. * @returns {Promise<string>} The result from the Brian API. */ async generateCode(body, removeMarkdown = true) { const response = await import_ky2.default.post( `${this.apiUrl}/api/${this.apiVersion}/agent/smart-contract`, { body: JSON.stringify({ ...body, compile: !body.compile ? false : true, messages: !body.messages ? [] : body.messages }), ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { throw new BadRequestError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result: { contract, contractName, abi, bytecode, standardJsonInput, version } } = await response.json(); if (removeMarkdown) { return { contract: typeof contract === "object" && "contract" in contract ? contract.contract.replaceAll("```solidity", "").replaceAll("```", "") : typeof contract === "string" ? contract.replaceAll("```solidity", "").replaceAll("```", "") : contract, contractName, abi, bytecode, standardJsonInput, version }; } return { contract, contractName, abi, bytecode, standardJsonInput, version }; } /** * @dev Asks Brian to build one or more transactions. * @param {TransactionRequestBody} body - The request body sent to the Brian API. * @returns {TransactionResult[]} The result from the Brian API. */ async transact(body) { const response = await import_ky2.default.post( `${this.apiUrl}/api/${this.apiVersion}/agent/transaction`, { body: JSON.stringify({ ...body }), ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { throw new BadRequestError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result } = await response.json(); return result; } /** * @dev Compiles a given code. * @param {CompileRequestBody} body - The request body sent to the Brian API. * @returns {CompileResponse} The result from the Brian API. */ async compile(body) { const response = await import_ky2.default.post( `${this.apiUrl}/api/${this.apiVersion}/utils/compile`, { body: JSON.stringify({ ...body }), ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { throw new BadRequestError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } return await response.json(); } /** * @dev Explains a given code. * @param {ExplainRequestBody} body - The request body sent to the Brian API. * @returns {string | null} The result from the Brian API. */ async explain(body) { const response = await import_ky2.default.post( `${this.apiUrl}/api/${this.apiVersion}/utils/explain`, { body: JSON.stringify({ ...body }), ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { throw new BadRequestError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result } = await response.json(); return result; } /** * @dev Returns all the networks supported by the Brian API. * @returns {Network[]} array of networks supported by the Brian API. */ async getNetworks() { const response = await import_ky2.default.get( `${this.apiUrl}/api/${this.apiVersion}/utils/networks`, { ...this.options } ); if (!response.ok) { const cause = await response.json(); if (response.status === 400) { throw new BadRequestError({ cause }); } if (response.status === 429) { throw new RateLimitError({ cause }); } throw new InternalServerError({ cause }); } const { result } = await response.json(); return result; } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { BadRequestError, BrianSDK, BrianSDKError, InternalServerError, NotFoundError, RateLimitError, SDKInitializationError });