briyah 1.1.1 → 1.1.2

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.
Files changed (57) hide show
  1. package/README.md +3 -3
  2. package/dist-sdk/server/src/ai/ai-factory.module.js +0 -2
  3. package/dist-sdk/server/src/ai/ai-factory.service.d.ts +1 -3
  4. package/dist-sdk/server/src/ai/ai-factory.service.js +1 -8
  5. package/dist-sdk/server/src/config/configuration.service.d.ts +0 -2
  6. package/dist-sdk/server/src/config/configuration.service.js +0 -8
  7. package/dist-sdk/server/src/sdk/briyah.js +5 -7
  8. package/docs/classes/Agent.html +14 -14
  9. package/docs/classes/Briyah.html +12 -12
  10. package/docs/classes/BriyahConfigService.html +5 -5
  11. package/docs/classes/Room.html +23 -23
  12. package/docs/classes/RoomMessage.html +10 -10
  13. package/docs/enums/MessageAction.html +3 -3
  14. package/docs/hierarchy.html +1 -1
  15. package/docs/index.html +5 -4
  16. package/docs/interfaces/AgentInfo.html +2 -2
  17. package/docs/interfaces/AgentMessagesResponse.html +2 -2
  18. package/docs/interfaces/AppService.html +109 -109
  19. package/docs/interfaces/Artifact.html +3 -3
  20. package/docs/interfaces/ArtifactMetadata.html +2 -2
  21. package/docs/interfaces/AttachDocumentResponse.html +2 -2
  22. package/docs/interfaces/BriyahConfigOptions.html +6 -6
  23. package/docs/interfaces/ChapterInfo.html +2 -2
  24. package/docs/interfaces/Character.html +2 -2
  25. package/docs/interfaces/CreateAgentResponse.html +2 -2
  26. package/docs/interfaces/CreateRoomResponse.html +2 -2
  27. package/docs/interfaces/CreateStoryResponse.html +2 -2
  28. package/docs/interfaces/FileList.html +2 -2
  29. package/docs/interfaces/LoggingOptions.html +5 -5
  30. package/docs/interfaces/Message.html +2 -2
  31. package/docs/interfaces/ModelInfo.html +2 -2
  32. package/docs/interfaces/PreparedPromptResponse.html +2 -2
  33. package/docs/interfaces/ProcessTextResponse.html +2 -2
  34. package/docs/interfaces/PromptFile.html +2 -2
  35. package/docs/interfaces/PromptFileContent.html +2 -2
  36. package/docs/interfaces/PromptFilesResponse.html +2 -2
  37. package/docs/interfaces/PromptFolder.html +2 -2
  38. package/docs/interfaces/PromptFoldersResponse.html +2 -2
  39. package/docs/interfaces/RoomDetails.html +2 -2
  40. package/docs/interfaces/RoomInfo.html +2 -2
  41. package/docs/interfaces/RoomMessagesResponse.html +2 -2
  42. package/docs/interfaces/StoryErrorEvent.html +3 -3
  43. package/docs/interfaces/StoryIdea.html +2 -2
  44. package/docs/interfaces/StoryInfo.html +3 -3
  45. package/docs/interfaces/StoryIntroduceCharacterEvent.html +3 -3
  46. package/docs/interfaces/StoryProgressChapterEvent.html +3 -3
  47. package/docs/interfaces/StoryState.html +5 -5
  48. package/docs/interfaces/StoryStateEvent.html +3 -3
  49. package/docs/interfaces/Transaction.html +2 -2
  50. package/docs/interfaces/TransactionHistoryResponse.html +2 -2
  51. package/docs/modules.html +1 -1
  52. package/docs/types/PromptScope.html +1 -1
  53. package/package.json +1 -4
  54. package/dist-sdk/server/src/ai/LLM/vertexai.module.d.ts +0 -2
  55. package/dist-sdk/server/src/ai/LLM/vertexai.module.js +0 -21
  56. package/dist-sdk/server/src/ai/LLM/vertexai.service.d.ts +0 -17
  57. package/dist-sdk/server/src/ai/LLM/vertexai.service.js +0 -321
@@ -1,321 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.VertexAiService = void 0;
13
- const common_1 = require("@nestjs/common");
14
- const vertexai_1 = require("@google-cloud/vertexai");
15
- const storage_1 = require("@google-cloud/storage");
16
- const crypto_1 = require("crypto");
17
- const base_ai_service_1 = require("./base-ai.service");
18
- const model_prices_1 = require("../model_prices");
19
- const errors_1 = require("../../common/errors");
20
- const logger_1 = require("../../common/logger");
21
- let VertexAiService = class VertexAiService extends base_ai_service_1.BaseAiService {
22
- vertexAI = null;
23
- constructor() {
24
- super();
25
- try {
26
- if (!process.env.GOOGLE_PROJECT_ID || !process.env.GOOGLE_CLOUD_LOCATION) {
27
- this._isAvailable = false;
28
- return;
29
- }
30
- this.vertexAI = new vertexai_1.VertexAI({
31
- project: process.env.GOOGLE_PROJECT_ID,
32
- location: process.env.GOOGLE_CLOUD_LOCATION,
33
- });
34
- logger_1.logger.debug('Vertex AI service initialized successfully');
35
- }
36
- catch (error) {
37
- logger_1.logger.error('Error initializing Vertex AI service:', error);
38
- this._isAvailable = false;
39
- }
40
- }
41
- getServiceName() {
42
- return 'Vertex AI';
43
- }
44
- async fetchModelsFromApi() {
45
- return [
46
- {
47
- name: 'gemini-3-pro-preview',
48
- description: 'gemini-3-pro-preview',
49
- model: 'gemini-3-pro-preview',
50
- service: 'Vertex AI',
51
- },
52
- {
53
- name: 'gemini-2.5-pro',
54
- description: 'gemini-2.5-pro',
55
- model: 'gemini-2.5-pro',
56
- service: 'Vertex AI',
57
- },
58
- {
59
- name: 'gemini-2.5-flash',
60
- description: 'gemini-2.5-flash',
61
- model: 'gemini-2.5-flash',
62
- service: 'Vertex AI',
63
- },
64
- {
65
- name: 'gemini-2.5-flash-lite',
66
- description: 'gemini-2.5-flash-lite',
67
- model: 'gemini-2.5-flash-lite',
68
- service: 'Vertex AI',
69
- },
70
- {
71
- name: 'gemini-2.0-flash-lite',
72
- description: 'gemini-2.0-flash-lite',
73
- model: 'gemini-2.0-flash-lite',
74
- service: 'Vertex AI',
75
- },
76
- {
77
- name: 'gemini-2.0-flash',
78
- description: 'gemini-2.0-flash',
79
- model: 'gemini-2.0-flash',
80
- service: 'Vertex AI',
81
- },
82
- ];
83
- }
84
- async uploadFile(fileContents) {
85
- let cloudStorage = new storage_1.Storage();
86
- let bucketName = process.env.GOOGLE_CLOUD_STORAGE_BUCKET;
87
- const bucket = cloudStorage.bucket(bucketName);
88
- const fileName = `${(0, crypto_1.randomUUID)()}.pdf`;
89
- const file = bucket.file(fileName);
90
- await file.save(Buffer.from(fileContents), {
91
- metadata: { contentType: 'application/octet-stream' },
92
- });
93
- logger_1.logger.log(`Successfully uploaded ${fileName} to ${bucketName}`);
94
- return `gs://${bucketName}/${fileName}`;
95
- }
96
- addToConversationHistory(agent, message, fromSelf = false) {
97
- if (!agent.history) {
98
- agent.history = [];
99
- }
100
- if (!message)
101
- return;
102
- agent.history.push({
103
- role: fromSelf ? 'model' : 'user',
104
- parts: [{ text: message }],
105
- });
106
- agent.trimHistoryIfNeeded();
107
- }
108
- async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null, _cacheConfig = null, maxOutputChars = 0) {
109
- if (agent.balanceService && !agent.disableBalanceCheck) {
110
- const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
111
- if (!hasSufficientBalance) {
112
- throw new errors_1.InsufficientBalanceError('Insufficient balance. Please add funds to continue using AI services.');
113
- }
114
- }
115
- let generationConfig = {
116
- candidateCount: 1,
117
- maxOutputTokens: 16384,
118
- temperature: 0,
119
- };
120
- let instructions = promptInstructions || agent.systemInstruction;
121
- if (jsonSchema) {
122
- generationConfig.responseMimeType = 'application/json';
123
- if (jsonSchema.description) {
124
- instructions +=
125
- '\n\nPlease generate only valid JSON according to the schema.\n' +
126
- jsonSchema.description;
127
- }
128
- delete jsonSchema.name;
129
- delete jsonSchema.description;
130
- generationConfig.responseSchema = jsonSchema;
131
- }
132
- let generativeModel = this.vertexAI.getGenerativeModel({
133
- model: agent.modelName,
134
- generationConfig: generationConfig,
135
- systemInstruction: instructions,
136
- });
137
- const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
138
- const messages = [{ role: 'user', parts: [{ text: identity }] }];
139
- if (agent.attachedFiles && agent.attachedFiles.length > 0) {
140
- for (const file of agent.attachedFiles) {
141
- if (file.serviceMetadata?.uri) {
142
- const ext = file.fileName.split('.').pop() || 'pdf';
143
- messages.push({
144
- role: 'user',
145
- parts: [
146
- {
147
- fileData: {
148
- mimeType: 'application/' + ext,
149
- fileUri: file.serviceMetadata.uri,
150
- },
151
- },
152
- {
153
- text: `This document will be referenced as ${file.fileName}.`,
154
- },
155
- ],
156
- });
157
- }
158
- else {
159
- const fileData = new Uint8Array(file.serviceMetadata.fileData);
160
- const textContent = Buffer.from(fileData).toString('utf-8');
161
- messages.push({
162
- role: 'user',
163
- parts: [{ text: textContent }],
164
- });
165
- }
166
- }
167
- }
168
- if (agent.attachedArtifacts && agent.attachedArtifacts.length > 0) {
169
- for (const artifactId of agent.attachedArtifacts) {
170
- const content = agent.artifactService.getArtifact(artifactId);
171
- if (content && typeof content === 'string') {
172
- const metadata = agent.artifactService.getArtifactMetadata(artifactId);
173
- const fileName = metadata ? `${metadata.name}.md` : 'artifact.md';
174
- messages.push({
175
- role: 'user',
176
- parts: [{ text: `Attached document: ${fileName}\n\n${content}` }],
177
- });
178
- }
179
- }
180
- }
181
- messages.push(...agent.history);
182
- if (prompt) {
183
- messages.push({ role: 'user', parts: [{ text: prompt }] });
184
- }
185
- let resp;
186
- try {
187
- resp = await generativeModel.generateContent({ contents: messages });
188
- }
189
- catch (error) {
190
- logger_1.logger.error(error);
191
- return error.message;
192
- }
193
- let responseText = resp.response.candidates[0].content.parts[0].text;
194
- if (jsonSchema) {
195
- responseText = this.trimToJson(responseText);
196
- responseText = this.sanitizeJsonString(responseText);
197
- }
198
- let usage = resp.response.usageMetadata;
199
- if (usage) {
200
- this.computeMessageCost(agent, usage);
201
- }
202
- if (saveResponse) {
203
- this.addToConversationHistory(agent, prompt, false);
204
- this.addToConversationHistory(agent, responseText, true);
205
- }
206
- if (jsonSchema) {
207
- return JSON.parse(responseText);
208
- }
209
- return responseText;
210
- }
211
- computeMessageCost(agent, usage) {
212
- const inputTokens = usage.promptTokenCount || 0;
213
- const outputTokens = usage.candidatesTokenCount || 0;
214
- const modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
215
- if (!modelInfo) {
216
- logger_1.logger.error(`No price info found for model ${agent.modelName}`);
217
- return;
218
- }
219
- const inputCost = inputTokens * modelInfo.input_cost_per_token;
220
- const outputCost = outputTokens * modelInfo.output_cost_per_token;
221
- const markup = agent.disableMarkup ? 0 : outputCost * agent.markupRate;
222
- const cost = inputCost + outputCost + markup;
223
- agent.totalInputTokens += inputTokens;
224
- agent.totalOutputTokens += outputTokens;
225
- agent.totalCost += cost;
226
- agent.totalMarkup += markup;
227
- logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
228
- if (agent.balanceService && cost > 0) {
229
- agent.balanceService.decrementBalance(cost, markup);
230
- }
231
- }
232
- async attachDocument(agent, fileName, fileData) {
233
- if (agent === null) {
234
- throw new Error('Shared document attachment not supported by Vertex AI service');
235
- }
236
- if (agent.fullContextFiles) {
237
- return super.attachDocument(agent, fileName, fileData);
238
- }
239
- let ext = fileName.split('.').pop();
240
- const existingMetadata = agent.attachedFiles.find((f) => f.fileName === fileName &&
241
- f.serviceMetadata?.serviceName === this.getServiceName() &&
242
- f.serviceMetadata?.uri);
243
- let gsUri;
244
- if (existingMetadata?.serviceMetadata?.uri) {
245
- gsUri = existingMetadata.serviceMetadata.uri;
246
- logger_1.logger.log(`Using existing Google Cloud Storage file: ${gsUri}`);
247
- }
248
- else {
249
- gsUri = await this.uploadFile(fileData);
250
- const additionalMetadata = {
251
- mimeType: 'application/' + ext,
252
- serviceMetadata: {
253
- serviceName: this.getServiceName(),
254
- uri: gsUri,
255
- },
256
- };
257
- const fileMetadataIndex = agent.attachedFiles.findIndex((f) => f.fileName === fileName);
258
- if (fileMetadataIndex >= 0) {
259
- agent.attachedFiles[fileMetadataIndex] = {
260
- ...agent.attachedFiles[fileMetadataIndex],
261
- ...additionalMetadata,
262
- };
263
- }
264
- }
265
- return existingMetadata?.serviceMetadata?.uri
266
- ? `Using existing file ${fileName} from Google Cloud Storage`
267
- : `Uploaded ${fileName} to Google Cloud Storage`;
268
- }
269
- formatMessage(message) {
270
- if (!message) {
271
- return 'No message';
272
- }
273
- if (message.role && message.parts) {
274
- const parts = message.parts
275
- .map((part) => {
276
- if (part.text) {
277
- return part.text;
278
- }
279
- else if (part.fileData) {
280
- return `[File: ${part.fileData.fileUri || 'attached file'}]`;
281
- }
282
- else {
283
- return JSON.stringify(part);
284
- }
285
- })
286
- .join('\n');
287
- return `${message.role}: ${parts}`;
288
- }
289
- return super.formatMessage(message);
290
- }
291
- async finishAgent(agent) {
292
- if (!agent)
293
- return;
294
- for (const metadata of agent.attachedFiles) {
295
- if (metadata.serviceMetadata?.serviceName === this.getServiceName() &&
296
- metadata.serviceMetadata?.uri) {
297
- try {
298
- const uri = metadata.serviceMetadata.uri;
299
- const match = uri.match(/gs:\/\/([^\/]+)\/(.+)/);
300
- if (match) {
301
- const bucketName = match[1];
302
- const fileName = match[2];
303
- const storage = new storage_1.Storage();
304
- const bucket = storage.bucket(bucketName);
305
- const file = bucket.file(fileName);
306
- await file.delete();
307
- logger_1.logger.log(`Deleted Google Cloud Storage file ${uri} for agent ${agent.id}`);
308
- }
309
- }
310
- catch (error) {
311
- logger_1.logger.error(`Error deleting Google Cloud Storage file ${metadata.serviceMetadata.uri}:`, error);
312
- }
313
- }
314
- }
315
- }
316
- };
317
- exports.VertexAiService = VertexAiService;
318
- exports.VertexAiService = VertexAiService = __decorate([
319
- (0, common_1.Injectable)(),
320
- __metadata("design:paramtypes", [])
321
- ], VertexAiService);