briyah 1.0.1 → 1.0.3

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 (177) hide show
  1. package/dist/server/src/ai/LLM/deepseek.service.js +1 -1
  2. package/package.json +2 -2
  3. package/dist/ai/LLM/anthropic.module.d.ts +0 -2
  4. package/dist/ai/LLM/anthropic.module.js +0 -21
  5. package/dist/ai/LLM/anthropic.service.d.ts +0 -27
  6. package/dist/ai/LLM/anthropic.service.js +0 -329
  7. package/dist/ai/LLM/base-ai.service.d.ts +0 -45
  8. package/dist/ai/LLM/base-ai.service.js +0 -409
  9. package/dist/ai/LLM/deepseek.module.d.ts +0 -2
  10. package/dist/ai/LLM/deepseek.module.js +0 -21
  11. package/dist/ai/LLM/deepseek.service.d.ts +0 -15
  12. package/dist/ai/LLM/deepseek.service.js +0 -279
  13. package/dist/ai/LLM/fal.module.d.ts +0 -2
  14. package/dist/ai/LLM/fal.module.js +0 -21
  15. package/dist/ai/LLM/fal.service.d.ts +0 -17
  16. package/dist/ai/LLM/fal.service.js +0 -314
  17. package/dist/ai/LLM/googleai.module.d.ts +0 -2
  18. package/dist/ai/LLM/googleai.module.js +0 -21
  19. package/dist/ai/LLM/googleai.service.d.ts +0 -20
  20. package/dist/ai/LLM/googleai.service.js +0 -271
  21. package/dist/ai/LLM/grok.module.d.ts +0 -2
  22. package/dist/ai/LLM/grok.module.js +0 -21
  23. package/dist/ai/LLM/grok.service.d.ts +0 -14
  24. package/dist/ai/LLM/grok.service.js +0 -263
  25. package/dist/ai/LLM/mock.module.d.ts +0 -2
  26. package/dist/ai/LLM/mock.module.js +0 -21
  27. package/dist/ai/LLM/mock.service.d.ts +0 -13
  28. package/dist/ai/LLM/mock.service.js +0 -194
  29. package/dist/ai/LLM/openai.module.d.ts +0 -2
  30. package/dist/ai/LLM/openai.module.js +0 -21
  31. package/dist/ai/LLM/openai.service.d.ts +0 -21
  32. package/dist/ai/LLM/openai.service.js +0 -421
  33. package/dist/ai/LLM/together.module.d.ts +0 -2
  34. package/dist/ai/LLM/together.module.js +0 -21
  35. package/dist/ai/LLM/together.service.d.ts +0 -18
  36. package/dist/ai/LLM/together.service.js +0 -285
  37. package/dist/ai/LLM/vertexai.module.d.ts +0 -2
  38. package/dist/ai/LLM/vertexai.module.js +0 -21
  39. package/dist/ai/LLM/vertexai.service.d.ts +0 -17
  40. package/dist/ai/LLM/vertexai.service.js +0 -323
  41. package/dist/ai/agent-config.d.ts +0 -32
  42. package/dist/ai/agent-config.js +0 -2
  43. package/dist/ai/agent-factory.d.ts +0 -15
  44. package/dist/ai/agent-factory.js +0 -24
  45. package/dist/ai/agent-message.service.d.ts +0 -9
  46. package/dist/ai/agent-message.service.js +0 -56
  47. package/dist/ai/agent-store.module.d.ts +0 -2
  48. package/dist/ai/agent-store.module.js +0 -21
  49. package/dist/ai/agent-store.service.d.ts +0 -31
  50. package/dist/ai/agent-store.service.js +0 -352
  51. package/dist/ai/agent.d.ts +0 -75
  52. package/dist/ai/agent.js +0 -174
  53. package/dist/ai/ai-factory.module.d.ts +0 -2
  54. package/dist/ai/ai-factory.module.js +0 -40
  55. package/dist/ai/ai-factory.service.d.ts +0 -24
  56. package/dist/ai/ai-factory.service.js +0 -94
  57. package/dist/ai/artifact.module.d.ts +0 -2
  58. package/dist/ai/artifact.module.js +0 -22
  59. package/dist/ai/artifact.service.d.ts +0 -21
  60. package/dist/ai/artifact.service.js +0 -239
  61. package/dist/ai/attached-file.module.d.ts +0 -2
  62. package/dist/ai/attached-file.module.js +0 -22
  63. package/dist/ai/attached-file.service.d.ts +0 -35
  64. package/dist/ai/attached-file.service.js +0 -253
  65. package/dist/ai/model_prices.d.ts +0 -2
  66. package/dist/ai/model_prices.js +0 -54
  67. package/dist/ai/published-agents.service.d.ts +0 -13
  68. package/dist/ai/published-agents.service.js +0 -118
  69. package/dist/app/balance-message.service.d.ts +0 -8
  70. package/dist/app/balance-message.service.js +0 -45
  71. package/dist/app/balance.module.d.ts +0 -2
  72. package/dist/app/balance.module.js +0 -20
  73. package/dist/app/balance.service.d.ts +0 -18
  74. package/dist/app/balance.service.js +0 -158
  75. package/dist/app/stripe.controller.d.ts +0 -31
  76. package/dist/app/stripe.controller.js +0 -150
  77. package/dist/app/stripe.module.d.ts +0 -2
  78. package/dist/app/stripe.module.js +0 -22
  79. package/dist/app/stripe.service.d.ts +0 -28
  80. package/dist/app/stripe.service.js +0 -198
  81. package/dist/app/transaction.service.d.ts +0 -15
  82. package/dist/app/transaction.service.js +0 -139
  83. package/dist/app/user-service-factory.d.ts +0 -21
  84. package/dist/app/user-service-factory.js +0 -81
  85. package/dist/app/user-service-manager.d.ts +0 -28
  86. package/dist/app/user-service-manager.js +0 -102
  87. package/dist/app.controller.d.ts +0 -232
  88. package/dist/app.controller.js +0 -2536
  89. package/dist/app.module.d.ts +0 -2
  90. package/dist/app.module.js +0 -45
  91. package/dist/app.service.d.ts +0 -186
  92. package/dist/app.service.js +0 -1334
  93. package/dist/auth/agent-access.decorator.d.ts +0 -2
  94. package/dist/auth/agent-access.decorator.js +0 -10
  95. package/dist/auth/auth.controller.d.ts +0 -38
  96. package/dist/auth/auth.controller.js +0 -356
  97. package/dist/auth/auth.module.d.ts +0 -2
  98. package/dist/auth/auth.module.js +0 -55
  99. package/dist/auth/auth.service.d.ts +0 -14
  100. package/dist/auth/auth.service.js +0 -84
  101. package/dist/auth/dto/bot-login.dto.d.ts +0 -4
  102. package/dist/auth/dto/bot-login.dto.js +0 -2
  103. package/dist/auth/dto/password-reset.dto.d.ts +0 -11
  104. package/dist/auth/dto/password-reset.dto.js +0 -2
  105. package/dist/auth/dto/phone-login.dto.d.ts +0 -8
  106. package/dist/auth/dto/phone-login.dto.js +0 -2
  107. package/dist/auth/dto/phone-verification.dto.d.ts +0 -9
  108. package/dist/auth/dto/phone-verification.dto.js +0 -2
  109. package/dist/auth/jwt-auth.guard.d.ts +0 -13
  110. package/dist/auth/jwt-auth.guard.js +0 -143
  111. package/dist/auth/jwt.strategy.d.ts +0 -17
  112. package/dist/auth/jwt.strategy.js +0 -45
  113. package/dist/auth/phone-validation.service.d.ts +0 -7
  114. package/dist/auth/phone-validation.service.js +0 -50
  115. package/dist/auth/public.decorator.d.ts +0 -2
  116. package/dist/auth/public.decorator.js +0 -7
  117. package/dist/auth/rate-limit.service.d.ts +0 -16
  118. package/dist/auth/rate-limit.service.js +0 -84
  119. package/dist/auth/room-access.decorator.d.ts +0 -2
  120. package/dist/auth/room-access.decorator.js +0 -10
  121. package/dist/auth/scopes.decorator.d.ts +0 -2
  122. package/dist/auth/scopes.decorator.js +0 -7
  123. package/dist/auth/scopes.guard.d.ts +0 -9
  124. package/dist/auth/scopes.guard.js +0 -82
  125. package/dist/auth/session.guard.d.ts +0 -7
  126. package/dist/auth/session.guard.js +0 -55
  127. package/dist/auth/twilio.service.d.ts +0 -15
  128. package/dist/auth/twilio.service.js +0 -139
  129. package/dist/auth/users.service.d.ts +0 -24
  130. package/dist/auth/users.service.js +0 -149
  131. package/dist/common/errors.d.ts +0 -12
  132. package/dist/common/errors.js +0 -43
  133. package/dist/config/configuration.module.d.ts +0 -2
  134. package/dist/config/configuration.module.js +0 -20
  135. package/dist/config/configuration.service.d.ts +0 -26
  136. package/dist/config/configuration.service.js +0 -131
  137. package/dist/main.js +0 -15749
  138. package/dist/room/artifact-store.service.d.ts +0 -15
  139. package/dist/room/artifact-store.service.js +0 -226
  140. package/dist/room/artifact.d.ts +0 -6
  141. package/dist/room/artifact.js +0 -2
  142. package/dist/room/message.d.ts +0 -19
  143. package/dist/room/message.js +0 -70
  144. package/dist/room/published-rooms.service.d.ts +0 -12
  145. package/dist/room/published-rooms.service.js +0 -108
  146. package/dist/room/room-config.d.ts +0 -12
  147. package/dist/room/room-config.js +0 -2
  148. package/dist/room/room-factory.d.ts +0 -7
  149. package/dist/room/room-factory.js +0 -16
  150. package/dist/room/room-message.module.d.ts +0 -2
  151. package/dist/room/room-message.module.js +0 -21
  152. package/dist/room/room-message.service.d.ts +0 -8
  153. package/dist/room/room-message.service.js +0 -44
  154. package/dist/room/room-store.module.d.ts +0 -2
  155. package/dist/room/room-store.module.js +0 -25
  156. package/dist/room/room-store.service.d.ts +0 -38
  157. package/dist/room/room-store.service.js +0 -353
  158. package/dist/room/room.d.ts +0 -107
  159. package/dist/room/room.js +0 -833
  160. package/dist/sdk/briyah-config.d.ts +0 -13
  161. package/dist/sdk/briyah-config.js +0 -32
  162. package/dist/sdk/briyah.d.ts +0 -36
  163. package/dist/sdk/briyah.js +0 -122
  164. package/dist/sdk/index.d.ts +0 -6
  165. package/dist/sdk/index.js +0 -11
  166. package/dist/shared/shared.module.d.ts +0 -2
  167. package/dist/shared/shared.module.js +0 -46
  168. package/dist/story/story-message.service.d.ts +0 -10
  169. package/dist/story/story-message.service.js +0 -57
  170. package/dist/story/story-progress.service.d.ts +0 -8
  171. package/dist/story/story-progress.service.js +0 -44
  172. package/dist/story/story-store.module.d.ts +0 -2
  173. package/dist/story/story-store.module.js +0 -22
  174. package/dist/story/story-store.service.d.ts +0 -23
  175. package/dist/story/story-store.service.js +0 -392
  176. package/dist/story/story.service.d.ts +0 -94
  177. package/dist/story/story.service.js +0 -1797
@@ -15,7 +15,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.DeepSeekAiService = void 0;
16
16
  const common_1 = require("@nestjs/common");
17
17
  const deepseek_1 = require("@ai-sdk/deepseek");
18
- const ai_1 = require("../../../../ai");
18
+ const ai_1 = require("ai");
19
19
  const base_ai_service_1 = require("./base-ai.service");
20
20
  const zod_1 = require("zod");
21
21
  const model_prices_1 = __importDefault(require("../model_prices"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "briyah",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Briyah multi-agent AI SDK",
5
5
  "private": false,
6
6
  "main": "dist/server/src/sdk/index.js",
@@ -15,7 +15,7 @@
15
15
  "scripts": {
16
16
  "prebuild": "rimraf dist",
17
17
  "build": "nest build",
18
- "build:sdk": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
18
+ "build:sdk": "rimraf dist && tsc -p tsconfig.build.json",
19
19
  "prepublishOnly": "npm run build:sdk",
20
20
  "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
21
21
  "start": "nest start",
@@ -1,2 +0,0 @@
1
- export declare class AnthropicAiModule {
2
- }
@@ -1,21 +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
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.AnthropicAiModule = void 0;
10
- const common_1 = require("@nestjs/common");
11
- const anthropic_service_1 = require("./anthropic.service");
12
- let AnthropicAiModule = class AnthropicAiModule {
13
- };
14
- exports.AnthropicAiModule = AnthropicAiModule;
15
- exports.AnthropicAiModule = AnthropicAiModule = __decorate([
16
- (0, common_1.Module)({
17
- imports: [],
18
- providers: [anthropic_service_1.AnthropicAiService],
19
- exports: [anthropic_service_1.AnthropicAiService],
20
- })
21
- ], AnthropicAiModule);
@@ -1,27 +0,0 @@
1
- import { Anthropic } from '@anthropic-ai/sdk';
2
- import { Agent } from '../agent';
3
- import { BaseAiService } from './base-ai.service';
4
- import { ConfigurationService } from '../../config/configuration.service';
5
- import { AgentStoreService } from '../agent-store.service';
6
- import { BalanceService } from '../../app/balance.service';
7
- import { ArtifactService } from '../artifact.service';
8
- import { ModelInfo } from '../../shared/types/app.types';
9
- export declare class AnthropicAiService extends BaseAiService {
10
- protected anthropic: Anthropic;
11
- constructor();
12
- createAgent(configService: ConfigurationService, agentStoreService: AgentStoreService, balanceService: BalanceService, artifactService: ArtifactService, agentName: string, agentNickname: string, description: string, promptFolder: string, modelName: string, storageDir?: string): Agent;
13
- getServiceName(): string;
14
- supportsImageGeneration(): boolean;
15
- supportsPromptCaching(): boolean;
16
- getCacheConfig(agent: Agent, cacheMessage: boolean): {
17
- type: string;
18
- ttl: string;
19
- } | {
20
- type: string;
21
- ttl?: undefined;
22
- };
23
- fetchModelsFromApi(): Promise<ModelInfo[]>;
24
- addToConversationHistory(agent: Agent, message: string, fromSelf?: boolean): void;
25
- textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, cacheConfig?: any, maxOutputChars?: number): Promise<any>;
26
- private computeMessageCost;
27
- }
@@ -1,329 +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
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.AnthropicAiService = void 0;
16
- const common_1 = require("@nestjs/common");
17
- const sdk_1 = require("@anthropic-ai/sdk");
18
- const base_ai_service_1 = require("./base-ai.service");
19
- const model_prices_1 = __importDefault(require("../model_prices"));
20
- const errors_1 = require("../../common/errors");
21
- let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.BaseAiService {
22
- anthropic;
23
- constructor() {
24
- super();
25
- try {
26
- const apiKey = process.env['ANTHROPIC_API_KEY'];
27
- if (!apiKey) {
28
- console.warn('ANTHROPIC_API_KEY environment variable not set. Anthropic service will not be available.');
29
- this._isAvailable = false;
30
- return;
31
- }
32
- this.anthropic = new sdk_1.Anthropic({
33
- apiKey: apiKey,
34
- timeout: 1200000,
35
- maxRetries: 3,
36
- });
37
- }
38
- catch (error) {
39
- console.error('Error initializing Anthropic service:', error);
40
- this._isAvailable = false;
41
- }
42
- }
43
- createAgent(configService, agentStoreService, balanceService, artifactService, agentName, agentNickname, description, promptFolder, modelName, storageDir = '') {
44
- let agent = super.createAgent(configService, agentStoreService, balanceService, artifactService, agentName, agentNickname, description, promptFolder, modelName, storageDir);
45
- agent.promptCacheTTL = 5;
46
- return agent;
47
- }
48
- getServiceName() {
49
- return 'Anthropic';
50
- }
51
- supportsImageGeneration() {
52
- return false;
53
- }
54
- supportsPromptCaching() {
55
- return true;
56
- }
57
- getCacheConfig(agent, cacheMessage) {
58
- if (!cacheMessage)
59
- return null;
60
- if (agent.promptCacheTTL === 0)
61
- return null;
62
- if (agent.promptCacheTTL > 5)
63
- return { type: 'ephemeral', ttl: '1h' };
64
- return { type: 'ephemeral' };
65
- }
66
- async fetchModelsFromApi() {
67
- try {
68
- const modelsResponse = await this.anthropic.models.list();
69
- return modelsResponse.data.map((model) => ({
70
- name: model.id,
71
- description: model.id,
72
- model: model.id,
73
- service: 'Anthropic',
74
- }));
75
- }
76
- catch (error) {
77
- console.error('Error fetching Anthropic models:', error);
78
- }
79
- }
80
- addToConversationHistory(agent, message, fromSelf = false) {
81
- if (!agent.history) {
82
- agent.history = [];
83
- }
84
- if (!message)
85
- return;
86
- agent.history.push({
87
- role: fromSelf ? 'assistant' : 'user',
88
- content: message,
89
- });
90
- agent.trimHistoryIfNeeded(10);
91
- }
92
- async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null, cacheConfig = false, maxOutputChars = 0) {
93
- if (agent.balanceService && !agent.disableBalanceCheck) {
94
- const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
95
- if (!hasSufficientBalance) {
96
- throw new errors_1.InsufficientBalanceError('Insufficient balance. Please add funds to continue using AI services.');
97
- }
98
- }
99
- const attachedFiles = agent.attachedFiles.filter((file) => file.serviceMetadata?.fileData);
100
- let documentMessages = [];
101
- for (const file of attachedFiles) {
102
- if (file.serviceMetadata?.fileData) {
103
- const fileData = new Uint8Array(file.serviceMetadata.fileData);
104
- let fileContent;
105
- if (file.mimeType === 'application/pdf') {
106
- const base64Data = Buffer.from(fileData).toString('base64');
107
- fileContent = {
108
- type: 'document',
109
- source: {
110
- type: 'base64',
111
- media_type: 'application/pdf',
112
- data: base64Data,
113
- },
114
- };
115
- }
116
- else {
117
- const textContent = Buffer.from(fileData).toString('utf-8');
118
- fileContent = {
119
- type: 'text',
120
- text: `Attached file "${file.fileName}":\n\n${textContent}`,
121
- };
122
- }
123
- documentMessages.push({ role: 'user', content: [fileContent] });
124
- }
125
- }
126
- if (agent.attachedArtifacts && agent.attachedArtifacts.length > 0) {
127
- for (const artifactId of agent.attachedArtifacts) {
128
- const content = agent.artifactService.getArtifact(artifactId);
129
- if (content && typeof content === 'string') {
130
- const metadata = agent.artifactService.getArtifactMetadata(artifactId);
131
- const fileName = metadata ? `${metadata.name}.md` : 'artifact.md';
132
- const artifactMessage = {
133
- role: 'user',
134
- content: [
135
- {
136
- type: 'text',
137
- text: `Document: ${fileName}\n\n${content}`,
138
- },
139
- ],
140
- };
141
- documentMessages.push(artifactMessage);
142
- }
143
- }
144
- }
145
- if (cacheConfig &&
146
- documentMessages.length > 0 &&
147
- documentMessages[documentMessages.length - 1].content &&
148
- documentMessages[documentMessages.length - 1].content.length > 0) {
149
- documentMessages[documentMessages.length - 1].content[0]['cache_control'] = cacheConfig;
150
- }
151
- let instructionText = promptInstructions || agent.systemInstruction;
152
- if (jsonSchema) {
153
- instructionText +=
154
- '\n\nIMPORTANT: You MUST respond with ONLY valid JSON that conforms to the provided schema. Do not include any explanatory text, markdown formatting, or other content before or after the JSON. Your entire response should be parseable as JSON.\n\nJSON Schema:\n' +
155
- JSON.stringify(jsonSchema, null, 2);
156
- }
157
- const systemBlocks = [];
158
- if (instructionText)
159
- systemBlocks.push({ type: 'text', text: instructionText });
160
- systemBlocks.push({
161
- type: 'text',
162
- text: `Your agent identity is ${agent.agentName}: ${agent.description}`,
163
- cache_control: cacheConfig,
164
- });
165
- const messageHistory = agent.history.map((msg) => ({
166
- role: msg.role,
167
- content: [{ type: 'text', text: msg.content }],
168
- }));
169
- if (cacheConfig && messageHistory && messageHistory.length > 0) {
170
- messageHistory[messageHistory.length - 1].content[0]['cache_control'] = cacheConfig;
171
- }
172
- const messages = [...documentMessages, ...messageHistory];
173
- if (prompt) {
174
- messages.push({
175
- role: 'user',
176
- content: [{ type: 'text', text: prompt }],
177
- });
178
- }
179
- const tools = [];
180
- if (agent.allowSearch) {
181
- tools.push({
182
- type: 'web_search_20250305',
183
- name: 'web_search',
184
- max_uses: 5,
185
- });
186
- }
187
- const maxRetries = 3;
188
- let lastError = null;
189
- let thinkingTokens = 0;
190
- if (agent.reasoningEffort === 'low')
191
- thinkingTokens = 1024;
192
- else if (agent.reasoningEffort === 'medium')
193
- thinkingTokens = 2048;
194
- else if (agent.reasoningEffort === 'high')
195
- thinkingTokens = 4096;
196
- const modelInfo = model_prices_1.default[agent.modelName];
197
- if (modelInfo && !modelInfo.supports_reasoning)
198
- thinkingTokens = 0;
199
- let maxOutputTokens;
200
- if (modelInfo && modelInfo.max_output_tokens) {
201
- if (agent.maxOutputTokens > 0)
202
- maxOutputTokens = Math.min(modelInfo.max_output_tokens, agent.maxOutputTokens);
203
- else
204
- maxOutputTokens = modelInfo.max_output_tokens;
205
- }
206
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
207
- try {
208
- const response = await this.anthropic.messages.create({
209
- model: agent.modelName,
210
- messages: messages,
211
- system: systemBlocks,
212
- max_tokens: maxOutputTokens,
213
- temperature: thinkingTokens > 0 ? undefined : 0,
214
- thinking: {
215
- type: thinkingTokens > 0 ? 'enabled' : 'disabled',
216
- budget_tokens: thinkingTokens > 0 ? thinkingTokens : undefined,
217
- },
218
- tools: tools.length > 0 ? tools : undefined,
219
- });
220
- let responseText = '';
221
- if (response.content && response.content.length > 0) {
222
- for (let i = 0; i < response.content.length; i++) {
223
- const content = response.content[i];
224
- if ('text' in content) {
225
- responseText += content.text;
226
- }
227
- }
228
- }
229
- if (jsonSchema) {
230
- responseText = this.trimToJson(responseText);
231
- responseText = this.sanitizeJsonString(responseText);
232
- }
233
- if (response.usage) {
234
- this.computeMessageCost(agent, response.usage);
235
- }
236
- let parsedResponse;
237
- if (jsonSchema) {
238
- try {
239
- parsedResponse = JSON.parse(responseText);
240
- if (saveResponse) {
241
- agent.addToConversationHistory(prompt, false);
242
- agent.addToConversationHistory(responseText, true);
243
- }
244
- return parsedResponse;
245
- }
246
- catch (parseError) {
247
- lastError = parseError;
248
- console.warn(`JSON parse attempt ${attempt}/${maxRetries} failed:`, parseError);
249
- console.warn('Raw response:', responseText);
250
- if (attempt < maxRetries) {
251
- const retryMessage = `Your previous response was not valid JSON. Please respond with ONLY valid JSON that can be parsed. No explanatory text, no markdown, no formatting - just pure JSON that conforms to the schema. Here was the parsing error: ${parseError.message}`;
252
- messages.push({
253
- role: 'assistant',
254
- content: [{ type: 'text', text: responseText }],
255
- });
256
- messages.push({
257
- role: 'user',
258
- content: [{ type: 'text', text: retryMessage }],
259
- });
260
- }
261
- }
262
- }
263
- else {
264
- if (responseText.length > maxOutputChars && maxOutputChars > 0) {
265
- const retryMessage = `Your previous response exceeded the character limit of ${maxOutputChars}. Please try again with a shorter response.`;
266
- messages.push({
267
- role: 'assistant',
268
- content: [{ type: 'text', text: responseText }],
269
- });
270
- messages.push({
271
- role: 'user',
272
- content: [{ type: 'text', text: retryMessage }],
273
- });
274
- }
275
- else {
276
- if (saveResponse) {
277
- agent.addToConversationHistory(prompt, false);
278
- agent.addToConversationHistory(responseText, true);
279
- }
280
- return responseText;
281
- }
282
- }
283
- }
284
- catch (apiError) {
285
- lastError = apiError;
286
- console.error(`API call attempt ${attempt}/${maxRetries} failed:`, apiError);
287
- if (attempt < maxRetries) {
288
- await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
289
- }
290
- }
291
- }
292
- throw new Error(`Failed to get valid response after ${maxRetries} attempts. Last error: ${lastError?.message || 'Unknown error'}`);
293
- }
294
- computeMessageCost(agent, usage) {
295
- const modelInfo = model_prices_1.default[agent.modelName];
296
- if (!modelInfo) {
297
- console.error(`No price info found for model ${agent.modelName}`);
298
- return 0;
299
- }
300
- const cacheCreationTokens = usage.cache_creation_input_tokens || 0;
301
- const cacheReadTokens = usage.cache_read_input_tokens || 0;
302
- const standardInputTokens = usage.input_tokens || 0;
303
- const outputTokens = usage.output_tokens || 0;
304
- const standardCost = standardInputTokens * modelInfo.input_cost_per_token;
305
- const cacheCreationCost = cacheCreationTokens *
306
- (modelInfo.cache_creation_input_token_cost || modelInfo.input_cost_per_token * 1.25);
307
- const cacheReadCost = cacheReadTokens *
308
- (modelInfo.cache_read_input_token_cost || modelInfo.input_cost_per_token * 0.1);
309
- const outputCost = outputTokens * modelInfo.output_cost_per_token;
310
- const markup = agent.disableMarkup ? 0 : outputCost * agent.markupRate;
311
- const cost = standardCost + cacheCreationCost + cacheReadCost + outputCost + markup;
312
- agent.totalInputTokens += standardInputTokens + cacheCreationTokens + cacheReadTokens;
313
- agent.totalOutputTokens += outputTokens;
314
- agent.totalCost += cost;
315
- agent.totalMarkup += markup;
316
- console.log(`Cost for ${agent.agentName} message: ${cost.toFixed(4)}, markup: ${markup.toFixed(4)}`);
317
- if (agent.balanceService && cost > 0) {
318
- agent.balanceService.decrementBalance(cost, markup);
319
- }
320
- if (cacheCreationTokens > 0 || cacheReadTokens > 0) {
321
- console.log(`Cache metrics for ${agent.agentName}: creation=${cacheCreationTokens}, read=${cacheReadTokens}, standard=${standardInputTokens}`);
322
- }
323
- }
324
- };
325
- exports.AnthropicAiService = AnthropicAiService;
326
- exports.AnthropicAiService = AnthropicAiService = __decorate([
327
- (0, common_1.Injectable)(),
328
- __metadata("design:paramtypes", [])
329
- ], AnthropicAiService);
@@ -1,45 +0,0 @@
1
- import { Agent } from '../agent';
2
- import { ConfigurationService } from '../../config/configuration.service';
3
- import { ArtifactService } from '../artifact.service';
4
- import { AgentStoreService } from '../agent-store.service';
5
- import { BalanceService } from '../../app/balance.service';
6
- import { ModelInfo } from '../../shared/types/app.types';
7
- export interface ImageGenerationOptions {
8
- model?: string;
9
- size?: '1024x1024' | '1536x1024' | '1024x1536' | 'auto';
10
- quality?: 'auto' | 'high' | 'medium' | 'low';
11
- format?: 'png' | 'jpeg' | 'webp';
12
- }
13
- export declare class BaseAiService {
14
- protected modelsCache: ModelInfo[];
15
- protected _isAvailable: boolean;
16
- constructor();
17
- get isAvailable(): boolean;
18
- getServiceName(): string;
19
- supportsImageGeneration(): boolean;
20
- supportsPromptCaching(): boolean;
21
- getCacheConfig(_agent: Agent, _cacheMessage: boolean): any;
22
- stripQuotes(quotedText: string): string;
23
- protected findPromptFile(agent: Agent, fileName: string, extension: string): string | null;
24
- getPreparedPrompt(agent: Agent, promptFileName: string, variables: any): string;
25
- protected getPreparedSchema(agent: Agent, promptFileName: string): any;
26
- listModels(): Promise<ModelInfo[]>;
27
- protected fetchModelsFromApi(): Promise<ModelInfo[]>;
28
- createAgent(configService: ConfigurationService, agentStoreService: AgentStoreService, balanceService: BalanceService, artifactService: ArtifactService, agentName: string, agentNickname: string, description: string, promptFolder: string, modelName: string, storageDir?: string): Agent;
29
- textPrompt(agent: Agent, prompt: string, _jsonSchema?: any, _saveResponse?: boolean, _promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
30
- generateImage(_agent: Agent, _prompt: string, _width: number, _height: number, _quality: string, _referenceImageArtifactIds?: string[], _options?: ImageGenerationOptions): Promise<{
31
- artifactId?: string;
32
- error?: any;
33
- }>;
34
- protected loadReferenceImages(agent: Agent, artifactIds: string[]): Promise<File[]>;
35
- protected saveImageAsArtifact(agent: Agent, base64Data: string, prompt: string): Promise<string>;
36
- preparedPrompt(agent: Agent, promptFileName: string, variables: any, saveResponse?: boolean, cacheConfig?: any, maxOutputChars?: number): Promise<any>;
37
- instructedPrompt(agent: Agent, prompt: string, instructionFileName: string, variables: any, saveResponse?: boolean, cacheConfig?: any, maxOutputChars?: number): Promise<any>;
38
- attachDocument(agent: Agent, fileName: string, fileData: Uint8Array): Promise<string>;
39
- finishAgent(_agent: Agent): Promise<void>;
40
- addToConversationHistory(agent: Agent, message: string, fromSelf?: boolean, developer?: boolean): void;
41
- formatMessage(message: any): string;
42
- trimResponseText(str: string): string;
43
- trimToJson(str: string): string;
44
- sanitizeJsonString(str: string): string;
45
- }