UNPKG

@brian-ai/sdk

Version:

Official Typescript SDK for Brian AI.

504 lines (500 loc) 13.8 kB
// src/sdk.ts import ky2 from "ky"; // 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 import ky from "ky"; 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 ky.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 ky.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 ky.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 ky.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 ky2.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 ky2.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 ky2.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 ky2.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 ky2.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 ky2.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 ky2.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 ky2.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; } }; export { BadRequestError, BrianSDK, BrianSDKError, InternalServerError, NotFoundError, RateLimitError, SDKInitializationError };