> ## Documentation Index
> Fetch the complete documentation index at: https://docs.brx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# brx-node SDK

> Official Node.js SDK for BRX

# brx-node SDK

The `brx-node` package is the official Node.js SDK for interacting with the BRX platform. It provides a simple and intuitive interface for creating, managing, and executing BRKs.

![npm version](https://img.shields.io/npm/v/brx-node)
![npm downloads](https://img.shields.io/npm/dt/brx-node)

## Installation

```bash theme={null}
# Using npm
npm install brx-node --save

# Using yarn
yarn add brx-node

# Using pnpm
pnpm add brx-node
```

## Basic Usage

```typescript theme={null}
import BRX, { BRK } from 'brx-node';

// Initialize the BRX client with your API key
const brx = new BRX('your-api-key');

// Fetch a BRK schema
const brkSchema = await brx.get('brk-id');

// Initialize a BRK with the schema
const myBrk = new BRK(brkSchema);

// Set input values
myBrk.input['inputField'] = 'input value';

// Execute the BRK
const result = await brx.run(myBrk);
console.log(result);
```

## API Reference

### BRX Class

The `BRX` class is the main entry point for interacting with the BRX platform.

#### Constructor

```typescript theme={null}
constructor(
  accessToken: string,
  options?: {
    use_brx_key?: boolean;
    verbose?: boolean;
    send_local?: boolean;
    force_client?: boolean;
    silent?: boolean;
  }
)
```

* `accessToken` (required): Your BRX API key
* `options` (optional): Configuration options
  * `use_brx_key` (default: `true`): Whether to use the BRX API key for authentication
  * `verbose` (default: `false`): Enable verbose logging
  * `send_local` (default: `false`): Use local API endpoint (for development)
  * `force_client` (default: `false`): Force client-side WebSocket
  * `silent` (default: `false`): Disable welcome message

#### Methods

##### get

```typescript theme={null}
get(brxID: string): Promise<GetSchemaObject>
```

Fetches a BRK schema by its ID.

* `brxID` (required): The ID of the BRK to fetch
* Returns: A promise that resolves to the BRK schema

##### run

```typescript theme={null}
run(query: BRK, callback?: (message: RunResult) => void): Promise<RunResult[]>
```

Executes a BRK and returns the results.

* `query` (required): The BRK to execute
* `callback` (optional): A callback function that will be called for each result
* Returns: A promise that resolves to an array of results

##### create

```typescript theme={null}
create(modifyRequest: brxModify): Promise<ModifySuccess | ModifyError>
```

Creates a new BRK.

* `modifyRequest` (required): The BRK creation request
* Returns: A promise that resolves to the creation result

##### update

```typescript theme={null}
update(modifyRequest: brxModify): Promise<ModifySuccess | ModifyError>
```

Updates an existing BRK.

* `modifyRequest` (required): The BRK update request
* Returns: A promise that resolves to the update result

##### delete

```typescript theme={null}
delete(modifyRequest: brxModify): Promise<ModifySuccess | ModifyError>
```

Deletes a BRK.

* `modifyRequest` (required): The BRK deletion request
* Returns: A promise that resolves to the deletion result

##### clone

```typescript theme={null}
clone(modifyRequest: brxModify): Promise<ModifySuccess | ModifyError>
```

Clones a BRK.

* `modifyRequest` (required): The BRK clone request
* Returns: A promise that resolves to the clone result

##### execute

```typescript theme={null}
execute(query: BRK | queryStreamRequest, callback?: (message: RunResult) => void): Promise<Array<RunResult>>
```

Low-level method for executing a BRK. In most cases, you should use `run` instead.

* `query` (required): The BRK or query stream request to execute
* `callback` (optional): A callback function that will be called for each result
* Returns: A promise that resolves to an array of results

##### modify

```typescript theme={null}
modify(modifyRequest: brxModify): Promise<ModifySuccess | ModifyError>
```

Low-level method for modifying a BRK. In most cases, you should use `create`, `update`, `delete`, or `clone` instead.

* `modifyRequest` (required): The BRK modification request
* Returns: A promise that resolves to the modification result

### BRK Class

The `BRK` class represents a BRK (BRX Knowledge Representation) that can be executed.

#### Constructor

```typescript theme={null}
constructor(BRKSchema?: GetSchemaObject, BRXClient?: BRX)
```

* `BRKSchema` (optional): The BRK schema
* `BRXClient` (optional): The BRX client to use for execution

#### Properties

##### input

```typescript theme={null}
input: any
```

An object containing the input values for the BRK. You can set input values by assigning to properties of this object.

##### brxQuery

```typescript theme={null}
brxQuery: any
```

The internal representation of the BRK query. You should not modify this directly.

##### inprogress

```typescript theme={null}
inprogress: boolean
```

Whether the BRK is currently being executed.

#### Methods

##### run

```typescript theme={null}
run(callback?: (message: RunResult) => void): Promise<RunResult[]>
```

Executes the BRK using the associated BRX client.

* `callback` (optional): A callback function that will be called for each result
* Returns: A promise that resolves to an array of results

##### updateBRK

```typescript theme={null}
updateBRK(verbose?: boolean): Promise<{ brxQuery: any }>
```

Updates the internal BRK query with the current input values.

* `verbose` (optional): Enable verbose logging
* Returns: A promise that resolves to an object containing the updated BRK query

## Examples

### Creating a BRK

```typescript theme={null}
import BRX, { BRK } from 'brx-node';

const brx = new BRX('your-api-key');

// Define the BRK
const createRequest = {
  modifyBrxMode: 'CREATE',
  brx: {
    brxId: 'hello-world-brk',
    brxName: 'Hello World',
    description: 'A simple Hello World BRK',
    prompt: {
      prompt: new Map([
        ['main', 'Hello, {{name}}!']
      ])
    },
    processParams: {
      processType: 0
    },
    dependantBrxIds: new Map([
      ['main_brx_entry_schema', 'hello-world-brk']
    ])
  },
  schema: {
    schemaFields: new Map([
      ['name', {
        fieldValueDataType: 'string',
        fieldValue: ''
      }]
    ]),
    brxName: 'Hello World',
    brxId: 'hello-world-brk'
  }
};

// Create the BRK
const result = await brx.create(createRequest);
console.log('BRK created:', result);
```

### Using a BRK with Dependencies

```typescript theme={null}
import BRX, { BRK } from 'brx-node';

const brx = new BRX('your-api-key');

// Fetch the BRK schema
const reportGeneratorSchema = await brx.get('report-generator-brk');

// Initialize the BRK
const reportGenerator = new BRK(reportGeneratorSchema);

// Set input values
reportGenerator.input['data'] = 'Raw data to analyze';
reportGenerator.input['format'] = 'markdown';

// Execute the BRK with a callback for streaming results
const results = [];
await brx.run(reportGenerator, (result) => {
  results.push(result);
  console.log(`Received result from ${result.brxName}`);
});

// Print the final result
console.log('Final report:', results[results.length - 1].brxRes.output);
```

### Error Handling

```typescript theme={null}
import BRX, { BRK } from 'brx-node';

const brx = new BRX('your-api-key');

try {
  // Fetch a BRK schema
  const brkSchema = await brx.get('non-existent-brk-id');
  
  // This code will not be reached if the BRK doesn't exist
  const myBrk = new BRK(brkSchema);
  const result = await brx.run(myBrk);
} catch (error) {
  console.error('Error:', error.message);
  
  // Handle specific error types
  if (error.message.includes('Unauthorized')) {
    console.error('Authentication error. Check your API key.');
  } else if (error.message.includes('no permissions')) {
    console.error('You do not have permission to access this BRK.');
  } else {
    console.error('An unexpected error occurred.');
  }
}
```

## Advanced Usage

### WebSocket Connections

The BRX client uses WebSockets for real-time communication with the BRX platform. You can customize the WebSocket behavior using the constructor options.

```typescript theme={null}
const brx = new BRX('your-api-key', {
  verbose: true,       // Enable verbose logging
  force_client: true,  // Force client-side WebSocket
  send_local: true     // Use local API endpoint
});
```

### Custom Processing

You can customize how BRKs are processed by setting the `processType` property in the `processParams` object.

```typescript theme={null}
const createRequest = {
  modifyBrxMode: 'CREATE',
  brx: {
    // ...
    processParams: {
      processType: 1 // Custom processing type
    },
    // ...
  },
  // ...
};
```

### Working with Maps

The BRX SDK uses JavaScript `Map` objects for certain properties. When serializing these objects to JSON, you need to use the `mapReplacer` function.

```typescript theme={null}
import { mapReplacer } from 'brx-node';

const jsonString = JSON.stringify(myObject, mapReplacer);
```

Similarly, when deserializing JSON to objects with `Map` properties, you need to use the `mapReviver` function.

```typescript theme={null}
import { mapReviver } from 'brx-node';

const myObject = JSON.parse(jsonString, mapReviver);
```

## Troubleshooting

### Common Issues

* **Authentication Errors**: Make sure your API key is correct and has not expired.
* **Network Errors**: Check your internet connection and firewall settings.
* **Rate Limiting**: The BRX API has rate limits. If you're making too many requests, you may be temporarily blocked.
* **Invalid BRK IDs**: Make sure the BRK IDs you're using exist and are accessible to your account.

### Debugging

You can enable verbose logging to help debug issues:

```typescript theme={null}
const brx = new BRX('your-api-key', { verbose: true });
```

This will log detailed information about WebSocket connections, requests, and responses.

## Further Reading

* [BRX API Reference](/api-reference/introduction)
* \[Core Concepts: BRK]\(/docs/Core Concepts/BRK)
* \[Core Concepts: BRX Client]\(/docs/Core Concepts/BRXClient)
* \[Core Concepts: Composability]\(/docs/Core Concepts/Composability)
