briyah 1.3.3 → 1.3.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/README.md +65 -0
- package/data/common/config/comfyui-workflows/flux-kontext.edit.json +98 -0
- package/data/common/config/comfyui-workflows/flux-kontext.t2i.json +80 -0
- package/data/common/config/comfyui-workflows/flux2-dev.edit.json +125 -0
- package/data/common/config/comfyui-workflows/flux2-dev.t2i.json +96 -0
- package/data/common/config/image_models_full.json +186 -99
- package/data/common/config/markup +1 -1
- package/data/common/config/story_models.json +23 -3
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +1 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +4 -2
- package/dist-sdk/server/src/ai/LLM/base-ai.service.spec.d.ts +1 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.spec.js +89 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +29 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-client.js +142 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-client.spec.d.ts +1 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-client.spec.js +143 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +19 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +217 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.spec.d.ts +1 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.spec.js +207 -0
- package/dist-sdk/server/src/ai/LLM/comfyui.module.d.ts +2 -0
- package/dist-sdk/server/src/ai/LLM/comfyui.module.js +21 -0
- package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +26 -0
- package/dist-sdk/server/src/ai/LLM/comfyui.service.js +191 -0
- package/dist-sdk/server/src/ai/LLM/mock.service.d.ts +1 -0
- package/dist-sdk/server/src/ai/LLM/mock.service.js +3 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.module.d.ts +2 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.module.js +21 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +13 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +205 -0
- package/dist-sdk/server/src/ai/ai-factory.module.js +4 -0
- package/dist-sdk/server/src/ai/ai-factory.service.d.ts +5 -1
- package/dist-sdk/server/src/ai/ai-factory.service.js +16 -2
- package/dist-sdk/server/src/app.service.js +1 -1
- package/dist-sdk/server/src/sdk/briyah.js +9 -3
- package/dist-sdk/server/src/story/story.service.js +11 -0
- package/docs/classes/Agent.html +15 -15
- package/docs/classes/Briyah.html +14 -14
- package/docs/classes/BriyahConfigService.html +5 -5
- package/docs/classes/Room.html +27 -27
- package/docs/classes/RoomMessage.html +10 -10
- package/docs/enums/MessageAction.html +3 -3
- package/docs/hierarchy.html +1 -1
- package/docs/index.html +47 -3
- package/docs/interfaces/AgentInfo.html +2 -2
- package/docs/interfaces/AgentMessagesResponse.html +2 -2
- package/docs/interfaces/AppService.html +119 -119
- package/docs/interfaces/Artifact.html +3 -3
- package/docs/interfaces/ArtifactMetadata.html +2 -2
- package/docs/interfaces/AttachDocumentResponse.html +2 -2
- package/docs/interfaces/BriyahConfigOptions.html +9 -9
- package/docs/interfaces/ChapterInfo.html +2 -2
- package/docs/interfaces/Character.html +2 -2
- package/docs/interfaces/CreateAgentResponse.html +2 -2
- package/docs/interfaces/CreateRoomResponse.html +2 -2
- package/docs/interfaces/CreateStoryResponse.html +2 -2
- package/docs/interfaces/FileList.html +2 -2
- package/docs/interfaces/FileMetadata.html +3 -3
- package/docs/interfaces/IConfigService.html +3 -3
- package/docs/interfaces/LoggingOptions.html +6 -6
- package/docs/interfaces/Message.html +2 -2
- package/docs/interfaces/ModelInfo.html +2 -2
- package/docs/interfaces/NativeToolDefinition.html +7 -7
- package/docs/interfaces/PreparedPromptResponse.html +2 -2
- package/docs/interfaces/ProcessTextResponse.html +2 -2
- package/docs/interfaces/PromptFile.html +2 -2
- package/docs/interfaces/PromptFileContent.html +2 -2
- package/docs/interfaces/PromptFilesResponse.html +2 -2
- package/docs/interfaces/PromptFolder.html +2 -2
- package/docs/interfaces/PromptFoldersResponse.html +2 -2
- package/docs/interfaces/RoomDetails.html +2 -2
- package/docs/interfaces/RoomInfo.html +2 -2
- package/docs/interfaces/RoomMessageUpdate.html +2 -2
- package/docs/interfaces/RoomMessagesResponse.html +2 -2
- package/docs/interfaces/SendMessageResult.html +2 -2
- package/docs/interfaces/StoryErrorEvent.html +3 -3
- package/docs/interfaces/StoryIdea.html +2 -2
- package/docs/interfaces/StoryInfo.html +3 -3
- package/docs/interfaces/StoryIntroduceCharacterEvent.html +3 -3
- package/docs/interfaces/StoryProgressChapterEvent.html +3 -3
- package/docs/interfaces/StoryState.html +5 -5
- package/docs/interfaces/StoryStateEvent.html +3 -3
- package/docs/interfaces/ToolDefinition.html +2 -2
- package/docs/interfaces/ToolHelpers.html +3 -3
- package/docs/interfaces/ToolParameter.html +2 -2
- package/docs/interfaces/ToolSummary.html +2 -2
- package/docs/interfaces/ToolsResponse.html +2 -2
- package/docs/interfaces/Transaction.html +2 -2
- package/docs/interfaces/TransactionHistoryResponse.html +2 -2
- package/docs/modules.html +1 -1
- package/docs/types/PromptScope.html +1 -1
- package/docs/types/ToolContext.html +2 -2
- package/docs/types/ToolRunResult.html +1 -1
- package/package.json +2 -1
|
@@ -0,0 +1,191 @@
|
|
|
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.ComfyUiAiService = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const crypto_1 = require("crypto");
|
|
15
|
+
const base_ai_service_1 = require("./base-ai.service");
|
|
16
|
+
const comfyui_client_1 = require("./comfyui-client");
|
|
17
|
+
const comfyui_workflow_1 = require("./comfyui-workflow");
|
|
18
|
+
const errors_1 = require("../../common/errors");
|
|
19
|
+
const logger_1 = require("../../common/logger");
|
|
20
|
+
let ComfyUiAiService = class ComfyUiAiService extends base_ai_service_1.BaseAiService {
|
|
21
|
+
client;
|
|
22
|
+
constructor() {
|
|
23
|
+
super();
|
|
24
|
+
try {
|
|
25
|
+
const baseUrl = process.env['COMFYUI_BASE_URL'];
|
|
26
|
+
if (!baseUrl) {
|
|
27
|
+
this._isAvailable = false;
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
let extraHeaders;
|
|
31
|
+
const rawHeaders = process.env['COMFYUI_EXTRA_HEADERS'];
|
|
32
|
+
if (rawHeaders) {
|
|
33
|
+
try {
|
|
34
|
+
extraHeaders = JSON.parse(rawHeaders);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
logger_1.logger.error('COMFYUI_EXTRA_HEADERS is not valid JSON, ignoring:', error.message);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
this.client = new comfyui_client_1.ComfyUiClient({
|
|
41
|
+
baseUrl,
|
|
42
|
+
extraHeaders,
|
|
43
|
+
timeoutMs: parseInt(process.env['COMFYUI_TIMEOUT_MS'], 10) || undefined,
|
|
44
|
+
pollIntervalMs: parseInt(process.env['COMFYUI_POLL_INTERVAL_MS'], 10) || undefined,
|
|
45
|
+
});
|
|
46
|
+
logger_1.logger.debug('ComfyUI service initialized successfully');
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
logger_1.logger.error('Error initializing ComfyUI service:', error);
|
|
50
|
+
this._isAvailable = false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
getServiceName() {
|
|
54
|
+
return 'ComfyUI';
|
|
55
|
+
}
|
|
56
|
+
supportsImageGeneration() {
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
requiresKnownModel() {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
async fetchModelsFromApi() {
|
|
63
|
+
return (0, comfyui_workflow_1.listWorkflowPairs)().map((pair) => ({
|
|
64
|
+
name: pair.name,
|
|
65
|
+
description: `ComfyUI workflow (${pair.variants.join(', ')})`,
|
|
66
|
+
model: pair.name,
|
|
67
|
+
service: 'ComfyUI',
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
async textPrompt(_agent, _prompt, _jsonSchema = null, _saveResponse = true, _promptInstructions = null, _cacheConfig = null, _maxOutputChars = 0) {
|
|
71
|
+
throw new Error('ComfyUI agents are image-generation only. Use generateImage/editImage, ' +
|
|
72
|
+
'or choose a text provider for chat agents.');
|
|
73
|
+
}
|
|
74
|
+
async generateImage(agent, prompt, imageProperties) {
|
|
75
|
+
try {
|
|
76
|
+
const { centsPerImage, width = 1024, height = 1024, seed } = imageProperties ?? {};
|
|
77
|
+
const balanceError = this.checkBalance(agent, centsPerImage);
|
|
78
|
+
if (balanceError)
|
|
79
|
+
throw balanceError;
|
|
80
|
+
const workflow = this.prepareWorkflow(agent, 't2i', {
|
|
81
|
+
prompt,
|
|
82
|
+
seed: seed ?? (0, crypto_1.randomInt)(0, 2 ** 31 - 1),
|
|
83
|
+
width,
|
|
84
|
+
height,
|
|
85
|
+
});
|
|
86
|
+
const artifactId = await this.runWorkflow(agent, workflow, prompt, centsPerImage);
|
|
87
|
+
return { artifactId };
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
if (error instanceof errors_1.InsufficientBalanceError)
|
|
91
|
+
throw error;
|
|
92
|
+
logger_1.logger.error('ComfyUI generateImage failed:', error.message || error);
|
|
93
|
+
return { error };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async editImage(agent, prompt, imageProperties, referenceImageArtifactIds) {
|
|
97
|
+
try {
|
|
98
|
+
const { centsPerImage, width = 1024, height = 1024, seed } = imageProperties ?? {};
|
|
99
|
+
if (!referenceImageArtifactIds || referenceImageArtifactIds.length === 0) {
|
|
100
|
+
return this.generateImage(agent, prompt, imageProperties);
|
|
101
|
+
}
|
|
102
|
+
const balanceError = this.checkBalance(agent, centsPerImage);
|
|
103
|
+
if (balanceError)
|
|
104
|
+
throw balanceError;
|
|
105
|
+
const references = this.loadReferenceBuffers(agent, referenceImageArtifactIds);
|
|
106
|
+
const refImages = [];
|
|
107
|
+
for (const reference of references) {
|
|
108
|
+
const uploaded = await this.client.uploadImage(reference.buffer, `briyah-ref-${(0, crypto_1.randomUUID)()}.png`);
|
|
109
|
+
refImages.push(uploaded.subfolder ? `${uploaded.subfolder}/${uploaded.name}` : uploaded.name);
|
|
110
|
+
}
|
|
111
|
+
const effectivePrompt = references.length > 1
|
|
112
|
+
? this.buildMultiRefPreamble(references.length) + prompt
|
|
113
|
+
: prompt;
|
|
114
|
+
let workflow = this.prepareWorkflow(agent, 'edit', {
|
|
115
|
+
prompt: effectivePrompt,
|
|
116
|
+
seed: seed ?? (0, crypto_1.randomInt)(0, 2 ** 31 - 1),
|
|
117
|
+
width,
|
|
118
|
+
height,
|
|
119
|
+
refImage: refImages[0],
|
|
120
|
+
});
|
|
121
|
+
workflow = (0, comfyui_workflow_1.chainReferenceImages)(workflow, refImages.slice(1));
|
|
122
|
+
const artifactId = await this.runWorkflow(agent, workflow, prompt, centsPerImage);
|
|
123
|
+
return { artifactId };
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (error instanceof errors_1.InsufficientBalanceError)
|
|
127
|
+
throw error;
|
|
128
|
+
logger_1.logger.error('ComfyUI editImage failed:', error.message || error);
|
|
129
|
+
return { error };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
checkBalance(agent, centsPerImage) {
|
|
133
|
+
if (!centsPerImage || centsPerImage <= 0)
|
|
134
|
+
return null;
|
|
135
|
+
if (agent.balanceService && !agent.disableBalanceCheck) {
|
|
136
|
+
if (!agent.balanceService.hasSufficientBalance()) {
|
|
137
|
+
return new errors_1.InsufficientBalanceError('Insufficient balance for image generation. Please add funds to continue.');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
prepareWorkflow(agent, variant, values) {
|
|
143
|
+
const templateFile = (0, comfyui_workflow_1.resolveWorkflowFile)(agent.modelName, variant, agent.userPaths);
|
|
144
|
+
if (!templateFile) {
|
|
145
|
+
throw new Error(`No ComfyUI ${variant} workflow "${agent.modelName}.${variant}.json" found in the ` +
|
|
146
|
+
'user or common comfyui-workflows directory.');
|
|
147
|
+
}
|
|
148
|
+
const template = (0, comfyui_workflow_1.loadWorkflowTemplate)(templateFile);
|
|
149
|
+
return (0, comfyui_workflow_1.patchWorkflow)(template, values);
|
|
150
|
+
}
|
|
151
|
+
async runWorkflow(agent, workflow, prompt, centsPerImage) {
|
|
152
|
+
this.debugLogRequest(agent.agentName, workflow);
|
|
153
|
+
const promptId = await this.client.queuePrompt(workflow);
|
|
154
|
+
const imageRef = await this.client.waitForCompletion(promptId);
|
|
155
|
+
const imageBuffer = await this.client.fetchOutput(imageRef);
|
|
156
|
+
this.computeImageCost(agent, centsPerImage);
|
|
157
|
+
return this.saveImageAsArtifact(agent, imageBuffer.toString('base64'), prompt);
|
|
158
|
+
}
|
|
159
|
+
computeImageCost(agent, centsPerImage) {
|
|
160
|
+
if (!centsPerImage || centsPerImage <= 0)
|
|
161
|
+
return;
|
|
162
|
+
const cost = centsPerImage / 100;
|
|
163
|
+
agent.totalCost += cost;
|
|
164
|
+
logger_1.logger.log(`Image cost for ${agent.agentName}: $${cost.toFixed(4)}`);
|
|
165
|
+
if (agent.balanceService) {
|
|
166
|
+
agent.balanceService.decrementBalance(cost, 0);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
loadReferenceBuffers(agent, artifactIds) {
|
|
170
|
+
const references = [];
|
|
171
|
+
for (const artifactId of artifactIds) {
|
|
172
|
+
const imageData = agent.artifactService.getArtifact(artifactId);
|
|
173
|
+
if (!imageData || !Buffer.isBuffer(imageData)) {
|
|
174
|
+
throw new Error(`Reference image artifact '${artifactId}' is missing or not an image; ` +
|
|
175
|
+
'refusing to generate with an incomplete reference set.');
|
|
176
|
+
}
|
|
177
|
+
references.push({ buffer: imageData, artifactId });
|
|
178
|
+
}
|
|
179
|
+
return references;
|
|
180
|
+
}
|
|
181
|
+
buildMultiRefPreamble(referenceCount) {
|
|
182
|
+
return (`${referenceCount} reference images are provided in order. ` +
|
|
183
|
+
'Reference Image 1 is the scene/setting; each subsequent reference image is a character portrait. ' +
|
|
184
|
+
"Any mention of 'Image k' below refers to the k-th reference image. ONLY produce one output image depicting a single scene.\n\n");
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
exports.ComfyUiAiService = ComfyUiAiService;
|
|
188
|
+
exports.ComfyUiAiService = ComfyUiAiService = __decorate([
|
|
189
|
+
(0, common_1.Injectable)(),
|
|
190
|
+
__metadata("design:paramtypes", [])
|
|
191
|
+
], ComfyUiAiService);
|
|
@@ -4,6 +4,7 @@ import { ModelInfo } from '../../../../shared/types/app.types';
|
|
|
4
4
|
export declare class MockAiService extends BaseAiService {
|
|
5
5
|
constructor();
|
|
6
6
|
getServiceName(): string;
|
|
7
|
+
requiresKnownModel(): boolean;
|
|
7
8
|
protected fetchModelsFromApi(): Promise<ModelInfo[]>;
|
|
8
9
|
preparedPrompt(agent: Agent, promptFileName: string, variables: any, saveResponse?: boolean, _cacheConfig?: any): Promise<any>;
|
|
9
10
|
getMockFile(promptFileName: string, prompt: string, variables: any): string;
|
|
@@ -0,0 +1,21 @@
|
|
|
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.SelfHostedModule = void 0;
|
|
10
|
+
const common_1 = require("@nestjs/common");
|
|
11
|
+
const self_hosted_service_1 = require("./self-hosted.service");
|
|
12
|
+
let SelfHostedModule = class SelfHostedModule {
|
|
13
|
+
};
|
|
14
|
+
exports.SelfHostedModule = SelfHostedModule;
|
|
15
|
+
exports.SelfHostedModule = SelfHostedModule = __decorate([
|
|
16
|
+
(0, common_1.Module)({
|
|
17
|
+
imports: [],
|
|
18
|
+
providers: [self_hosted_service_1.SelfHostedAiService],
|
|
19
|
+
exports: [self_hosted_service_1.SelfHostedAiService],
|
|
20
|
+
})
|
|
21
|
+
], SelfHostedModule);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { BaseAiService } from './base-ai.service';
|
|
2
|
+
import { Agent } from '../agent';
|
|
3
|
+
import { ModelInfo } from '../../../../shared/types/app.types';
|
|
4
|
+
export declare class SelfHostedAiService extends BaseAiService {
|
|
5
|
+
private openai;
|
|
6
|
+
constructor();
|
|
7
|
+
getServiceName(): string;
|
|
8
|
+
requiresKnownModel(): boolean;
|
|
9
|
+
fetchModelsFromApi(): Promise<ModelInfo[]>;
|
|
10
|
+
textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
|
|
11
|
+
addToConversationHistory(agent: Agent, message: string, fromSelf?: boolean, developer?: boolean): void;
|
|
12
|
+
private computeMessageCost;
|
|
13
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
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.SelfHostedAiService = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const openai_1 = require("openai");
|
|
15
|
+
const base_ai_service_1 = require("./base-ai.service");
|
|
16
|
+
const model_prices_1 = require("../model_prices");
|
|
17
|
+
const errors_1 = require("../../common/errors");
|
|
18
|
+
const logger_1 = require("../../common/logger");
|
|
19
|
+
let SelfHostedAiService = class SelfHostedAiService extends base_ai_service_1.BaseAiService {
|
|
20
|
+
openai;
|
|
21
|
+
constructor() {
|
|
22
|
+
super();
|
|
23
|
+
try {
|
|
24
|
+
const baseURL = process.env['SELF_HOSTED_BASE_URL'];
|
|
25
|
+
if (!baseURL) {
|
|
26
|
+
this._isAvailable = false;
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
this.openai = new openai_1.OpenAI({
|
|
30
|
+
apiKey: process.env['SELF_HOSTED_API_KEY'] || 'sk-no-key-required',
|
|
31
|
+
baseURL,
|
|
32
|
+
timeout: 600000,
|
|
33
|
+
maxRetries: 3,
|
|
34
|
+
});
|
|
35
|
+
logger_1.logger.debug('SelfHosted service initialized successfully');
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
logger_1.logger.error('Error initializing SelfHosted service:', error);
|
|
39
|
+
this._isAvailable = false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
getServiceName() {
|
|
43
|
+
return 'SelfHosted';
|
|
44
|
+
}
|
|
45
|
+
requiresKnownModel() {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
async fetchModelsFromApi() {
|
|
49
|
+
const models = await this.openai.models.list();
|
|
50
|
+
return models.data
|
|
51
|
+
.filter((model) => model && model.id)
|
|
52
|
+
.map((model) => ({
|
|
53
|
+
name: model.id,
|
|
54
|
+
description: model.id,
|
|
55
|
+
model: model.id,
|
|
56
|
+
service: 'SelfHosted',
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null, _cacheConfig = null, _maxOutputChars = 0) {
|
|
60
|
+
const modelInfo = (0, model_prices_1.resolveModelInfo)(agent.modelName, this.getModelPricePrefix());
|
|
61
|
+
if (modelInfo && agent.balanceService && !agent.disableBalanceCheck) {
|
|
62
|
+
const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
|
|
63
|
+
if (!hasSufficientBalance) {
|
|
64
|
+
throw new errors_1.InsufficientBalanceError('Insufficient balance. Please add funds to continue using AI services.');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
|
|
68
|
+
const instructions = promptInstructions || agent.systemInstruction;
|
|
69
|
+
const messages = [];
|
|
70
|
+
if (instructions)
|
|
71
|
+
messages.push({
|
|
72
|
+
role: 'system',
|
|
73
|
+
content: [{ type: 'text', text: instructions }],
|
|
74
|
+
});
|
|
75
|
+
messages.push({
|
|
76
|
+
role: 'system',
|
|
77
|
+
content: [{ type: 'text', text: identity }],
|
|
78
|
+
});
|
|
79
|
+
if (agent.attachedFiles && agent.attachedFiles.length > 0) {
|
|
80
|
+
for (const file of agent.attachedFiles) {
|
|
81
|
+
if (!file.serviceMetadata?.fileData)
|
|
82
|
+
continue;
|
|
83
|
+
const fileData = new Uint8Array(file.serviceMetadata.fileData);
|
|
84
|
+
const textContent = Buffer.from(fileData).toString('utf-8');
|
|
85
|
+
messages.push({
|
|
86
|
+
role: 'user',
|
|
87
|
+
content: [
|
|
88
|
+
{
|
|
89
|
+
type: 'text',
|
|
90
|
+
text: `Attached file "${file.fileName}":\n\n${textContent}`,
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (agent.attachedArtifacts && agent.attachedArtifacts.length > 0) {
|
|
97
|
+
for (const artifactId of agent.attachedArtifacts) {
|
|
98
|
+
const content = agent.artifactService.getArtifact(artifactId);
|
|
99
|
+
if (content && typeof content === 'string') {
|
|
100
|
+
const metadata = agent.artifactService.getArtifactMetadata(artifactId);
|
|
101
|
+
const fileName = metadata ? `${metadata.name}.md` : 'artifact.md';
|
|
102
|
+
messages.push({
|
|
103
|
+
role: 'user',
|
|
104
|
+
content: [
|
|
105
|
+
{
|
|
106
|
+
type: 'text',
|
|
107
|
+
text: `Attached document: ${fileName}\n\n${content}`,
|
|
108
|
+
},
|
|
109
|
+
],
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (jsonSchema) {
|
|
115
|
+
messages.push({
|
|
116
|
+
role: 'system',
|
|
117
|
+
content: [
|
|
118
|
+
{
|
|
119
|
+
type: 'text',
|
|
120
|
+
text: `You must respond with valid JSON matching this schema: ${JSON.stringify(jsonSchema)}`,
|
|
121
|
+
},
|
|
122
|
+
],
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
messages.push(...agent.history);
|
|
126
|
+
if (prompt) {
|
|
127
|
+
messages.push({
|
|
128
|
+
role: 'user',
|
|
129
|
+
content: [{ type: 'text', text: prompt }],
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
const requestParams = {
|
|
133
|
+
model: agent.modelName,
|
|
134
|
+
messages: messages,
|
|
135
|
+
};
|
|
136
|
+
this.debugLogRequest(agent.agentName, requestParams);
|
|
137
|
+
let responseText;
|
|
138
|
+
try {
|
|
139
|
+
const response = await this.openai.chat.completions.create(requestParams);
|
|
140
|
+
for (const choice of response.choices) {
|
|
141
|
+
if (choice.message.content)
|
|
142
|
+
responseText = choice.message.content;
|
|
143
|
+
}
|
|
144
|
+
responseText = this.trimResponseText(responseText);
|
|
145
|
+
if (jsonSchema) {
|
|
146
|
+
responseText = this.trimToJson(responseText);
|
|
147
|
+
}
|
|
148
|
+
this.debugLogResponse(agent.agentName, responseText);
|
|
149
|
+
if (response.usage) {
|
|
150
|
+
this.computeMessageCost(agent, response.usage, modelInfo);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
logger_1.logger.error(error);
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
if (saveResponse) {
|
|
158
|
+
this.addToConversationHistory(agent, prompt, false);
|
|
159
|
+
this.addToConversationHistory(agent, responseText, true);
|
|
160
|
+
}
|
|
161
|
+
if (jsonSchema)
|
|
162
|
+
return this.parseStructuredResponse(responseText);
|
|
163
|
+
return responseText;
|
|
164
|
+
}
|
|
165
|
+
addToConversationHistory(agent, message, fromSelf = false, developer = false) {
|
|
166
|
+
if (!agent.history) {
|
|
167
|
+
agent.history = [];
|
|
168
|
+
}
|
|
169
|
+
if (!message)
|
|
170
|
+
return;
|
|
171
|
+
let role = fromSelf ? 'assistant' : 'user';
|
|
172
|
+
if (developer)
|
|
173
|
+
role = 'system';
|
|
174
|
+
agent.history.push({
|
|
175
|
+
role: role,
|
|
176
|
+
content: message,
|
|
177
|
+
});
|
|
178
|
+
agent.trimHistoryIfNeeded();
|
|
179
|
+
}
|
|
180
|
+
computeMessageCost(agent, usage, modelInfo) {
|
|
181
|
+
const promptTokens = usage.prompt_tokens || 0;
|
|
182
|
+
const completionTokens = usage.completion_tokens || 0;
|
|
183
|
+
agent.totalInputTokens += promptTokens;
|
|
184
|
+
agent.totalOutputTokens += completionTokens;
|
|
185
|
+
if (!modelInfo) {
|
|
186
|
+
logger_1.logger.debug(`No price info for self-hosted model ${agent.modelName}; tokens tracked, no cost charged.`);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const inputCost = promptTokens * (modelInfo.input_cost_per_token || 0);
|
|
190
|
+
const outputCost = completionTokens * (modelInfo.output_cost_per_token || 0);
|
|
191
|
+
const markup = agent.disableMarkup ? 0 : outputCost * agent.markupRate;
|
|
192
|
+
const cost = inputCost + outputCost + markup;
|
|
193
|
+
agent.totalCost += cost;
|
|
194
|
+
agent.totalMarkup += markup;
|
|
195
|
+
logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
|
|
196
|
+
if (agent.balanceService && cost > 0) {
|
|
197
|
+
agent.balanceService.decrementBalance(cost, markup);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
exports.SelfHostedAiService = SelfHostedAiService;
|
|
202
|
+
exports.SelfHostedAiService = SelfHostedAiService = __decorate([
|
|
203
|
+
(0, common_1.Injectable)(),
|
|
204
|
+
__metadata("design:paramtypes", [])
|
|
205
|
+
], SelfHostedAiService);
|
|
@@ -17,6 +17,8 @@ const together_module_1 = require("./LLM/together.module");
|
|
|
17
17
|
const mock_module_1 = require("./LLM/mock.module");
|
|
18
18
|
const googleai_module_1 = require("./LLM/googleai.module");
|
|
19
19
|
const fal_module_1 = require("./LLM/fal.module");
|
|
20
|
+
const comfyui_module_1 = require("./LLM/comfyui.module");
|
|
21
|
+
const self_hosted_module_1 = require("./LLM/self-hosted.module");
|
|
20
22
|
let AiFactoryModule = class AiFactoryModule {
|
|
21
23
|
};
|
|
22
24
|
exports.AiFactoryModule = AiFactoryModule;
|
|
@@ -31,6 +33,8 @@ exports.AiFactoryModule = AiFactoryModule = __decorate([
|
|
|
31
33
|
mock_module_1.MockAiModule,
|
|
32
34
|
googleai_module_1.GoogleAiModule,
|
|
33
35
|
fal_module_1.FalAiModule,
|
|
36
|
+
comfyui_module_1.ComfyUiModule,
|
|
37
|
+
self_hosted_module_1.SelfHostedModule,
|
|
34
38
|
],
|
|
35
39
|
providers: [ai_factory_service_1.AiFactoryService],
|
|
36
40
|
exports: [ai_factory_service_1.AiFactoryService],
|
|
@@ -7,6 +7,8 @@ import { TogetherAiService } from './LLM/together.service';
|
|
|
7
7
|
import { MockAiService } from './LLM/mock.service';
|
|
8
8
|
import { GoogleAiService } from './LLM/googleai.service';
|
|
9
9
|
import { FalAiService } from './LLM/fal.service';
|
|
10
|
+
import { ComfyUiAiService } from './LLM/comfyui.service';
|
|
11
|
+
import { SelfHostedAiService } from './LLM/self-hosted.service';
|
|
10
12
|
export declare class AiFactoryService {
|
|
11
13
|
private readonly openAiService;
|
|
12
14
|
private readonly grokAiService;
|
|
@@ -16,7 +18,9 @@ export declare class AiFactoryService {
|
|
|
16
18
|
private readonly mockAiService;
|
|
17
19
|
private readonly googleAiService;
|
|
18
20
|
private readonly falAiService;
|
|
19
|
-
|
|
21
|
+
private readonly comfyUiAiService;
|
|
22
|
+
private readonly selfHostedAiService;
|
|
23
|
+
constructor(openAiService: OpenAiService, grokAiService: GrokAiService, anthropicAiService: AnthropicAiService, deepSeekAiService: DeepSeekAiService, togetherAiService: TogetherAiService, mockAiService: MockAiService, googleAiService: GoogleAiService, falAiService: FalAiService, comfyUiAiService: ComfyUiAiService, selfHostedAiService: SelfHostedAiService);
|
|
20
24
|
createAiService(serviceName: string): BaseAiService;
|
|
21
25
|
getAllAiServices(): BaseAiService[];
|
|
22
26
|
}
|
|
@@ -19,6 +19,8 @@ const together_service_1 = require("./LLM/together.service");
|
|
|
19
19
|
const mock_service_1 = require("./LLM/mock.service");
|
|
20
20
|
const googleai_service_1 = require("./LLM/googleai.service");
|
|
21
21
|
const fal_service_1 = require("./LLM/fal.service");
|
|
22
|
+
const comfyui_service_1 = require("./LLM/comfyui.service");
|
|
23
|
+
const self_hosted_service_1 = require("./LLM/self-hosted.service");
|
|
22
24
|
let AiFactoryService = class AiFactoryService {
|
|
23
25
|
openAiService;
|
|
24
26
|
grokAiService;
|
|
@@ -28,7 +30,9 @@ let AiFactoryService = class AiFactoryService {
|
|
|
28
30
|
mockAiService;
|
|
29
31
|
googleAiService;
|
|
30
32
|
falAiService;
|
|
31
|
-
|
|
33
|
+
comfyUiAiService;
|
|
34
|
+
selfHostedAiService;
|
|
35
|
+
constructor(openAiService, grokAiService, anthropicAiService, deepSeekAiService, togetherAiService, mockAiService, googleAiService, falAiService, comfyUiAiService, selfHostedAiService) {
|
|
32
36
|
this.openAiService = openAiService;
|
|
33
37
|
this.grokAiService = grokAiService;
|
|
34
38
|
this.anthropicAiService = anthropicAiService;
|
|
@@ -37,6 +41,8 @@ let AiFactoryService = class AiFactoryService {
|
|
|
37
41
|
this.mockAiService = mockAiService;
|
|
38
42
|
this.googleAiService = googleAiService;
|
|
39
43
|
this.falAiService = falAiService;
|
|
44
|
+
this.comfyUiAiService = comfyUiAiService;
|
|
45
|
+
this.selfHostedAiService = selfHostedAiService;
|
|
40
46
|
}
|
|
41
47
|
createAiService(serviceName) {
|
|
42
48
|
switch (serviceName) {
|
|
@@ -56,6 +62,10 @@ let AiFactoryService = class AiFactoryService {
|
|
|
56
62
|
return this.googleAiService;
|
|
57
63
|
case this.falAiService.getServiceName():
|
|
58
64
|
return this.falAiService;
|
|
65
|
+
case this.comfyUiAiService.getServiceName():
|
|
66
|
+
return this.comfyUiAiService;
|
|
67
|
+
case this.selfHostedAiService.getServiceName():
|
|
68
|
+
return this.selfHostedAiService;
|
|
59
69
|
default:
|
|
60
70
|
throw new Error(`Unknown AI service: ${serviceName}`);
|
|
61
71
|
}
|
|
@@ -70,6 +80,8 @@ let AiFactoryService = class AiFactoryService {
|
|
|
70
80
|
this.mockAiService,
|
|
71
81
|
this.googleAiService,
|
|
72
82
|
this.falAiService,
|
|
83
|
+
this.comfyUiAiService,
|
|
84
|
+
this.selfHostedAiService,
|
|
73
85
|
];
|
|
74
86
|
}
|
|
75
87
|
};
|
|
@@ -83,5 +95,7 @@ exports.AiFactoryService = AiFactoryService = __decorate([
|
|
|
83
95
|
together_service_1.TogetherAiService,
|
|
84
96
|
mock_service_1.MockAiService,
|
|
85
97
|
googleai_service_1.GoogleAiService,
|
|
86
|
-
fal_service_1.FalAiService
|
|
98
|
+
fal_service_1.FalAiService,
|
|
99
|
+
comfyui_service_1.ComfyUiAiService,
|
|
100
|
+
self_hosted_service_1.SelfHostedAiService])
|
|
87
101
|
], AiFactoryService);
|
|
@@ -86,7 +86,7 @@ class AppService {
|
|
|
86
86
|
this.aiServices = this.aiFactoryService.getAllAiServices();
|
|
87
87
|
}
|
|
88
88
|
getAiServiceNames() {
|
|
89
|
-
return this.aiServices.map((s) => s.getServiceName());
|
|
89
|
+
return this.aiServices.filter((s) => s.isAvailable).map((s) => s.getServiceName());
|
|
90
90
|
}
|
|
91
91
|
getAiServiceFromServiceName(serviceName) {
|
|
92
92
|
return this.aiFactoryService.createAiService(serviceName);
|
|
@@ -56,6 +56,8 @@ const user_service_manager_1 = require("../app/user-service-manager");
|
|
|
56
56
|
const user_service_factory_1 = require("../app/user-service-factory");
|
|
57
57
|
const briyah_config_1 = require("./briyah-config");
|
|
58
58
|
const fal_service_1 = require("../ai/LLM/fal.service");
|
|
59
|
+
const comfyui_service_1 = require("../ai/LLM/comfyui.service");
|
|
60
|
+
const self_hosted_service_1 = require("../ai/LLM/self-hosted.service");
|
|
59
61
|
const native_tool_registry_service_1 = require("../tools/native-tool-registry.service");
|
|
60
62
|
class Briyah {
|
|
61
63
|
configService;
|
|
@@ -93,10 +95,12 @@ class Briyah {
|
|
|
93
95
|
this.configService.get('XAI_API_KEY') ||
|
|
94
96
|
this.configService.get('DEEPSEEK_API_KEY') ||
|
|
95
97
|
this.configService.get('TOGETHER_API_KEY') ||
|
|
96
|
-
this.configService.get('FAL_API_KEY')
|
|
98
|
+
this.configService.get('FAL_API_KEY') ||
|
|
99
|
+
this.configService.get('SELF_HOSTED_BASE_URL') ||
|
|
100
|
+
this.configService.get('COMFYUI_BASE_URL');
|
|
97
101
|
if (!hasAnyProvider) {
|
|
98
102
|
logger_1.logger.warn('[Briyah] No LLM provider API keys configured. Some features will not be available.');
|
|
99
|
-
logger_1.logger.warn('[Briyah] Set one or more of: ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_GENAI_API_KEY, XAI_API_KEY, DEEPSEEK_API_KEY, TOGETHER_API_KEY, FAL_API_KEY');
|
|
103
|
+
logger_1.logger.warn('[Briyah] Set one or more of: ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_GENAI_API_KEY, XAI_API_KEY, DEEPSEEK_API_KEY, TOGETHER_API_KEY, FAL_API_KEY, SELF_HOSTED_BASE_URL, COMFYUI_BASE_URL');
|
|
100
104
|
}
|
|
101
105
|
const startingBalance = this.configService.get('STARTING_BALANCE');
|
|
102
106
|
if (!startingBalance) {
|
|
@@ -112,7 +116,9 @@ class Briyah {
|
|
|
112
116
|
const mockService = new mock_service_1.MockAiService();
|
|
113
117
|
const googleAiService = new googleai_service_1.GoogleAiService();
|
|
114
118
|
const falAiService = new fal_service_1.FalAiService();
|
|
115
|
-
|
|
119
|
+
const comfyUiAiService = new comfyui_service_1.ComfyUiAiService();
|
|
120
|
+
const selfHostedAiService = new self_hosted_service_1.SelfHostedAiService();
|
|
121
|
+
this.aiFactoryService = new ai_factory_service_1.AiFactoryService(openAiService, grokService, anthropicService, deepseekService, togetherService, mockService, googleAiService, falAiService, comfyUiAiService, selfHostedAiService);
|
|
116
122
|
this.agentMessageService = new agent_message_service_1.AgentMessageService();
|
|
117
123
|
this.roomMessageService = new room_message_service_1.RoomMessageService();
|
|
118
124
|
this.storyProgressService = new story_progress_service_1.StoryProgressService();
|
|
@@ -2184,6 +2184,17 @@ let StoryService = class StoryService {
|
|
|
2184
2184
|
logger_1.logger.warn(`Artist agent not found: ${storyInfo.artistAgentId}`);
|
|
2185
2185
|
}
|
|
2186
2186
|
}
|
|
2187
|
+
if (storyInfo.artistEditAgentId) {
|
|
2188
|
+
const artistEditAgent = await this.agentStore.getAgent(storyInfo.artistEditAgentId);
|
|
2189
|
+
if (artistEditAgent) {
|
|
2190
|
+
totalCost += artistEditAgent.totalCost || 0;
|
|
2191
|
+
totalInputTokens += artistEditAgent.totalInputTokens || 0;
|
|
2192
|
+
totalOutputTokens += artistEditAgent.totalOutputTokens || 0;
|
|
2193
|
+
}
|
|
2194
|
+
else {
|
|
2195
|
+
logger_1.logger.warn(`Artist edit agent not found: ${storyInfo.artistEditAgentId}`);
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2187
2198
|
storyInfo.totalCost = totalCost;
|
|
2188
2199
|
storyInfo.totalInputTokens = totalInputTokens;
|
|
2189
2200
|
storyInfo.totalOutputTokens = totalOutputTokens;
|