briyah 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.prettierrc CHANGED
@@ -1,7 +1,7 @@
1
- {
2
- "singleQuote": true,
3
- "trailingComma": "all",
4
- "tabWidth": 4,
5
- "semi": true,
6
- "printWidth": 9999
7
- }
1
+ {
2
+ "singleQuote": true,
3
+ "trailingComma": "all",
4
+ "tabWidth": 4,
5
+ "semi": true,
6
+ "printWidth": 9999
7
+ }
package/README.md ADDED
@@ -0,0 +1,402 @@
1
+ # Briyah SDK
2
+
3
+ The Briyah SDK provides a clean, easy-to-use interface for integrating the Briyah multi-agent AI system into your applications without requiring NestJS dependency injection setup.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install briyah
9
+ ```
10
+
11
+ ```typescript
12
+ import { Briyah } from 'briyah';
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { Briyah } from 'briyah';
19
+
20
+ // 1. Create and initialize Briyah instance
21
+ const briyah = new Briyah({
22
+ dataPath: './my-briyah-data',
23
+ userServiceCacheTimeoutMinutes: 30,
24
+ startingBalance: 10.00
25
+ });
26
+
27
+ await briyah.init();
28
+
29
+ // 2. Get user-specific service (userId managed by your app)
30
+ const appService = briyah.getAppService('user-123');
31
+
32
+ // 3. Use full Briyah functionality
33
+ // createAgent() registers the agent in memory immediately — agent.id is usable right away.
34
+ // Call agent.save() when you want to persist it to disk.
35
+ const agent = appService.createAgent(
36
+ 'Anthropic',
37
+ 'Assistant',
38
+ 'Assistant',
39
+ 'A helpful AI assistant',
40
+ 'claude-3-5-sonnet-20241022'
41
+ );
42
+
43
+ if (!agent.id) throw new Error('Agent creation failed');
44
+ const result = await appService.processText(agent.id, 'Hello! How are you?');
45
+ console.log(result.result);
46
+
47
+ agent.save(); // persist to disk
48
+
49
+ // 4. Cleanup when done
50
+ await briyah.shutdown();
51
+ ```
52
+
53
+ ## Configuration
54
+
55
+ ### BriyahConfigOptions
56
+
57
+ ```typescript
58
+ interface BriyahConfigOptions {
59
+ /**
60
+ * Base directory for Briyah data storage
61
+ * Default: './data' relative to process.cwd()
62
+ */
63
+ dataPath?: string;
64
+
65
+ /**
66
+ * Timeout in minutes for cached user services
67
+ * Default: 30 minutes
68
+ */
69
+ userServiceCacheTimeoutMinutes?: number;
70
+
71
+ /**
72
+ * Starting balance for new users (in dollars)
73
+ * Default: value from process.env.STARTING_BALANCE
74
+ */
75
+ startingBalance?: number;
76
+
77
+ /**
78
+ * Override environment variables
79
+ * Useful for testing or multi-instance configurations
80
+ */
81
+ envOverrides?: Record<string, string>;
82
+ }
83
+ ```
84
+
85
+ ### Environment Variables
86
+
87
+ Briyah requires certain environment variables to be set:
88
+
89
+ **Required:**
90
+ - `STARTING_BALANCE` - Starting balance for new users (e.g., "10.00")
91
+
92
+ **LLM Provider API Keys** (at least one required):
93
+ - `ANTHROPIC_API_KEY` - For Claude models
94
+ - `OPENAI_API_KEY` - For GPT models
95
+ - `GOOGLE_VERTEX_PROJECT_ID` - For Google Vertex AI
96
+ - `XAI_API_KEY` - For Grok models
97
+ - `DEEPSEEK_API_KEY` - For DeepSeek models
98
+ - `TOGETHER_API_KEY` - For Together AI models
99
+
100
+ **Optional:**
101
+ - `SERVER_DATA_PATH` - Global default data path (overridden by constructor `dataPath`)
102
+ - `USER_SERVICE_CACHE_TIMEOUT_MINUTES` - Cache timeout (overridden by constructor option)
103
+
104
+ ## API Reference
105
+
106
+ ### Briyah Class
107
+
108
+ #### constructor(options?: BriyahConfigOptions)
109
+
110
+ Creates a new Briyah SDK instance.
111
+
112
+ ```typescript
113
+ const briyah = new Briyah({
114
+ dataPath: './briyah-data',
115
+ startingBalance: 10.00
116
+ });
117
+ ```
118
+
119
+ #### async init(): Promise\<void\>
120
+
121
+ Initializes the Briyah system. Must be called before using `getAppService()`.
122
+
123
+ ```typescript
124
+ await briyah.init();
125
+ ```
126
+
127
+ #### getAppService(userId: string): AppService
128
+
129
+ Gets the AppService instance for a specific user. The AppService provides full access to:
130
+ - Agent management
131
+ - Room conversations
132
+ - Story generation
133
+ - Text processing
134
+ - File attachments
135
+
136
+ ```typescript
137
+ const appService = briyah.getAppService('user-123');
138
+ ```
139
+
140
+ **Throws:** Error if `init()` has not been called.
141
+
142
+ #### removeUserService(userId: string): void
143
+
144
+ Manually removes a user's service from the cache. Useful for:
145
+ - Forcing a fresh AppService instance
146
+ - Cleaning up when a user logs out
147
+
148
+ ```typescript
149
+ briyah.removeUserService('user-123');
150
+ ```
151
+
152
+ #### getCacheStats()
153
+
154
+ Returns statistics about cached user services.
155
+
156
+ ```typescript
157
+ const stats = briyah.getCacheStats();
158
+ console.log(`Cached users: ${stats.cachedUsers}`);
159
+ ```
160
+
161
+ #### async shutdown(): Promise\<void\>
162
+
163
+ Shuts down the Briyah system and cleans up resources.
164
+
165
+ ```typescript
166
+ await briyah.shutdown();
167
+ ```
168
+
169
+ #### isInitialized(): boolean
170
+
171
+ Checks if Briyah has been initialized.
172
+
173
+ ```typescript
174
+ if (briyah.isInitialized()) {
175
+ const appService = briyah.getAppService('user-123');
176
+ }
177
+ ```
178
+
179
+ ### AppService
180
+
181
+ The AppService provides full access to Briyah functionality.
182
+
183
+ **Common operations:**
184
+
185
+ ```typescript
186
+ // Agent Management
187
+ const agent = appService.createAgent(provider, name, nickname, description, model);
188
+ const agents = await appService.listAgents();
189
+ await appService.deleteAgent(agentId);
190
+
191
+ // Room Management
192
+ const room = await appService.createRoom(name, goal, agentIds);
193
+ const rooms = await appService.listRooms();
194
+ await appService.sendRoomMessage(roomId, content, sender, action?);
195
+
196
+ // Story Management
197
+ const story = await appService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, storyModel?);
198
+ await appService.progressStory(storyId);
199
+
200
+ // Text Processing
201
+ const result = await appService.processText(agentId, text);
202
+
203
+ // File Attachments
204
+ const attachment = await appService.attachDocument(agentId, fileName, fileData);
205
+ await appService.deleteAttachedFile(agentId, fileName); // by filename
206
+ await appService.deleteAttachedFileById(documentId); // by document ID
207
+ ```
208
+
209
+ ## Usage Examples
210
+
211
+ ### Example 1: Multi-User Setup
212
+
213
+ ```typescript
214
+ import { Briyah } from 'briyah';
215
+
216
+ // Initialize once at application startup
217
+ const briyah = new Briyah({
218
+ dataPath: './data/briyah',
219
+ startingBalance: 10.00
220
+ });
221
+
222
+ await briyah.init();
223
+
224
+ // In your route handler or service
225
+ async function handleUserRequest(userId: string, message: string) {
226
+ const appService = briyah.getAppService(userId);
227
+
228
+ // Each user gets their own isolated AppService
229
+ const agents = await appService.listAgents();
230
+
231
+ // ... process user request
232
+ }
233
+
234
+ // Cleanup at application shutdown
235
+ process.on('SIGINT', async () => {
236
+ await briyah.shutdown();
237
+ process.exit(0);
238
+ });
239
+ ```
240
+
241
+ ### Example 2: Custom Data Path
242
+
243
+ ```typescript
244
+ import { Briyah } from 'briyah';
245
+ import path from 'path';
246
+
247
+ const briyah = new Briyah({
248
+ dataPath: path.join(__dirname, '..', 'user-data', 'briyah'),
249
+ userServiceCacheTimeoutMinutes: 60 // 1 hour cache
250
+ });
251
+
252
+ await briyah.init();
253
+ ```
254
+
255
+ ### Example 3: Testing Configuration
256
+
257
+ ```typescript
258
+ import { Briyah } from 'briyah';
259
+
260
+ const testBriyah = new Briyah({
261
+ dataPath: './test-data',
262
+ startingBalance: 100.00,
263
+ userServiceCacheTimeoutMinutes: 5,
264
+ envOverrides: {
265
+ ANTHROPIC_API_KEY: process.env.TEST_ANTHROPIC_KEY,
266
+ OPENAI_API_KEY: process.env.TEST_OPENAI_KEY
267
+ }
268
+ });
269
+
270
+ await testBriyah.init();
271
+
272
+ // Run tests...
273
+
274
+ await testBriyah.shutdown();
275
+ ```
276
+
277
+ ### Example 4: Agent Creation and Text Processing
278
+
279
+ ```typescript
280
+ const appService = briyah.getAppService('user-123');
281
+
282
+ // Create an agent
283
+ const agent = appService.createAgent(
284
+ 'Anthropic', // provider
285
+ 'Assistant', // name
286
+ 'Assistant', // nickname
287
+ 'Helpful AI', // description
288
+ 'claude-3-5-sonnet-20241022' // model
289
+ );
290
+
291
+ if (!agent.id) throw new Error('Agent creation failed');
292
+ console.log(`Created agent: ${agent.id}`);
293
+
294
+ // Process text with the agent
295
+ const result = await appService.processText(
296
+ agent.id,
297
+ 'What is the capital of France?'
298
+ );
299
+
300
+ console.log(`Response: ${result.result}`);
301
+ console.log(`Cost: $${result.totalCost}`);
302
+ console.log(`Tokens: ${(result.totalInputTokens ?? 0) + (result.totalOutputTokens ?? 0)}`);
303
+ ```
304
+
305
+ ### Example 5: Multi-Agent Room Conversation
306
+
307
+ ```typescript
308
+ const appService = briyah.getAppService('user-123');
309
+
310
+ // Create agents
311
+ const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
312
+ const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-3-5-sonnet-20241022');
313
+
314
+ if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
315
+
316
+ // Create a room with both agents
317
+ const room = await appService.createRoom(
318
+ 'Analysis Session',
319
+ 'Analyze sales data and produce a written summary',
320
+ [analyst.id, writer.id]
321
+ );
322
+
323
+ // Send a message to start the conversation
324
+ await appService.sendRoomMessage(
325
+ room.roomId,
326
+ 'Please analyze the sales data for Q4',
327
+ 'Analyst',
328
+ 'speak'
329
+ );
330
+
331
+ // The agents will automatically respond and interact
332
+ // Check room messages to see the conversation
333
+ const messages = await appService.getRoomMessages(room.roomId);
334
+ console.log(`Messages: ${messages.messages.length}`);
335
+ ```
336
+
337
+ ## Data Storage
338
+
339
+ Briyah stores data in the following structure:
340
+
341
+ ```
342
+ {dataPath}/
343
+ ├── common/ # Shared across all users
344
+ │ ├── creds/ # Service account credentials
345
+ │ ├── prices/ # LLM pricing data
346
+ │ ├── prompts/ # Global prompt templates
347
+ │ └── published-agents.json # Published agent mappings
348
+ └── user/
349
+ └── {userId}/ # Per-user data
350
+ ├── prompts/ # User-specific prompts
351
+ ├── upload/ # User file attachments
352
+ └── userconfig/ # User configuration files
353
+ ├── agents.json # User's agents
354
+ ├── rooms.json # User's rooms
355
+ ├── stories.json # User's stories
356
+ └── balance.json # User's balance
357
+ ```
358
+
359
+ ## Multi-Instance Support
360
+
361
+ You can create multiple Briyah instances with different configurations:
362
+
363
+ ```typescript
364
+ const briyah1 = new Briyah({ dataPath: './data1' });
365
+ const briyah2 = new Briyah({ dataPath: './data2' });
366
+
367
+ await briyah1.init();
368
+ await briyah2.init();
369
+
370
+ // Each instance has isolated data
371
+ const user1Service = briyah1.getAppService('user-123');
372
+ const user2Service = briyah2.getAppService('user-123');
373
+ // These are completely separate services with different data paths
374
+ ```
375
+
376
+ **Note:** Singleton services (LLM providers, message emitters) are shared across all Briyah instances within the same process. This is safe because they are stateless or keyed by ID.
377
+
378
+ ## Backward Compatibility
379
+
380
+ The Briyah SDK is fully backward compatible with the existing NestJS application. The NestJS app continues to work without any changes, while new applications can use the SDK for simplified integration.
381
+
382
+ ## Troubleshooting
383
+
384
+ ### "Must call init() before getAppService()"
385
+
386
+ Make sure to call `await briyah.init()` before calling `getAppService()`.
387
+
388
+ ### "No LLM provider API keys configured"
389
+
390
+ Set at least one of the required API key environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.).
391
+
392
+ ### "STARTING_BALANCE environment variable is required"
393
+
394
+ Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the constructor options.
395
+
396
+ ### Cache not working as expected
397
+
398
+ Check the cache statistics with `getCacheStats()` and adjust `userServiceCacheTimeoutMinutes` in the constructor options.
399
+
400
+ ## Support
401
+
402
+ For issues or questions, please refer to the main Briyah documentation or create an issue in the repository.
@@ -16,6 +16,7 @@ export declare class AgentStoreService {
16
16
  private loadPromise;
17
17
  constructor(aiFactoryService: AiFactoryService, configService: ConfigurationService, attachedFileService: AttachedFileService, balanceService: BalanceService, artifactService: ArtifactService);
18
18
  getDefaultStorageDir(): string;
19
+ registerAgent(agent: Agent): void;
19
20
  storeAgent(agent: Agent, storageDir?: string): string;
20
21
  getAgent(id: string): Promise<Agent | undefined>;
21
22
  removeAgent(id: string): boolean;
@@ -74,6 +74,12 @@ let AgentStoreService = class AgentStoreService {
74
74
  getDefaultStorageDir() {
75
75
  return this.defaultStorageDir;
76
76
  }
77
+ registerAgent(agent) {
78
+ if (!agent.id) {
79
+ agent.id = (0, crypto_1.randomUUID)();
80
+ }
81
+ this.agents.set(agent.id, agent);
82
+ }
77
83
  storeAgent(agent, storageDir) {
78
84
  if (!agent.id) {
79
85
  agent.id = (0, crypto_1.randomUUID)();
@@ -170,6 +170,7 @@ class AppService {
170
170
  agent.beginInstruction = beginInstruction;
171
171
  }
172
172
  this.setupAgentStateCallback(agent);
173
+ this.agentStore.registerAgent(agent);
173
174
  return agent;
174
175
  }
175
176
  async processText(agentId, text) {
@@ -210,10 +210,10 @@ let ArtifactStoreService = ArtifactStoreService_1 = class ArtifactStoreService {
210
210
  const viewersStr = artifact.viewers && artifact.viewers.length > 0
211
211
  ? artifact.viewers.join(', ')
212
212
  : artifact.creator;
213
- return `# name: ${artifact.name}
214
- # creator: ${artifact.creator}
215
- # viewers: ${viewersStr}
216
-
213
+ return `# name: ${artifact.name}
214
+ # creator: ${artifact.creator}
215
+ # viewers: ${viewersStr}
216
+
217
217
  ${artifact.body}`;
218
218
  }
219
219
  getArtifactFilePath(roomId, storageDir, sanitizedName) {
package/eslint.config.js CHANGED
@@ -1,29 +1,29 @@
1
- const tseslint = require('@typescript-eslint/eslint-plugin');
2
- const tsparser = require('@typescript-eslint/parser');
3
-
4
- module.exports = [
5
- {
6
- ignores: ['dist/**', 'node_modules/**', 'data/**', 'coverage/**'],
7
- },
8
- {
9
- files: ['**/*.ts'],
10
- languageOptions: {
11
- parser: tsparser,
12
- parserOptions: {
13
- project: './tsconfig.json',
14
- tsconfigRootDir: __dirname,
15
- sourceType: 'module',
16
- },
17
- },
18
- plugins: {
19
- '@typescript-eslint': tseslint,
20
- },
21
- rules: {
22
- ...tseslint.configs['recommended'].rules,
23
- '@typescript-eslint/interface-name-prefix': 'off',
24
- '@typescript-eslint/explicit-function-return-type': 'off',
25
- '@typescript-eslint/explicit-module-boundary-types': 'off',
26
- '@typescript-eslint/no-explicit-any': 'off',
27
- },
28
- },
29
- ];
1
+ const tseslint = require('@typescript-eslint/eslint-plugin');
2
+ const tsparser = require('@typescript-eslint/parser');
3
+
4
+ module.exports = [
5
+ {
6
+ ignores: ['dist/**', 'node_modules/**', 'data/**', 'coverage/**'],
7
+ },
8
+ {
9
+ files: ['**/*.ts'],
10
+ languageOptions: {
11
+ parser: tsparser,
12
+ parserOptions: {
13
+ project: './tsconfig.json',
14
+ tsconfigRootDir: __dirname,
15
+ sourceType: 'module',
16
+ },
17
+ },
18
+ plugins: {
19
+ '@typescript-eslint': tseslint,
20
+ },
21
+ rules: {
22
+ ...tseslint.configs['recommended'].rules,
23
+ '@typescript-eslint/interface-name-prefix': 'off',
24
+ '@typescript-eslint/explicit-function-return-type': 'off',
25
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
26
+ '@typescript-eslint/no-explicit-any': 'off',
27
+ },
28
+ },
29
+ ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "briyah",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "Briyah multi-agent AI SDK",
5
5
  "private": false,
6
6
  "main": "dist/server/src/sdk/index.js",
@@ -16,6 +16,7 @@
16
16
  "prebuild": "rimraf dist",
17
17
  "build": "nest build",
18
18
  "build:sdk": "rimraf dist && tsc -p tsconfig.build.json",
19
+ "publish:sdk": "npm run build:sdk && npm publish",
19
20
  "prepublishOnly": "npm run build:sdk",
20
21
  "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
21
22
  "start": "nest start",