agentic-server 0.2.0 → 0.3.0
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 +12 -0
- package/billing.d.ts +1 -2
- package/esm/router.js +33 -35
- package/package.json +6 -4
- package/router.js +33 -35
package/README.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# agentic-server
|
|
2
2
|
|
|
3
|
+
<p align="center" width="100%">
|
|
4
|
+
<img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center" width="100%">
|
|
8
|
+
<a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
|
|
9
|
+
<img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://github.com/constructive-io/constructive/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
|
|
12
|
+
<a href="https://www.npmjs.com/package/agentic-server"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=packages%2Fagentic-server%2Fpackage.json"/></a>
|
|
13
|
+
</p>
|
|
14
|
+
|
|
3
15
|
Standalone Express LLM service — agent threads, chat streaming, billing metering, and inference logging via `@constructive-io/express-context`.
|
|
4
16
|
|
|
5
17
|
## Overview
|
package/billing.d.ts
CHANGED
|
@@ -4,8 +4,7 @@
|
|
|
4
4
|
* Calls the billing functions discovered from billing_module.
|
|
5
5
|
* Gracefully allows requests if billing is not provisioned or errors.
|
|
6
6
|
*/
|
|
7
|
-
import type { ConstructiveContext } from '@constructive-io/express-context';
|
|
8
|
-
import type { BillingConfig, InferenceLogConfig } from './discovery';
|
|
7
|
+
import type { BillingConfig, ConstructiveContext, InferenceLogConfig } from '@constructive-io/express-context';
|
|
9
8
|
export declare function checkQuota(ctx: ConstructiveContext, billing: BillingConfig, entityId: string, meterSlug: string): Promise<boolean>;
|
|
10
9
|
export declare function recordUsage(ctx: ConstructiveContext, billing: BillingConfig, entityId: string, meterSlug: string, amount: number, metadata: Record<string, unknown>): Promise<void>;
|
|
11
10
|
export interface InferenceLogEntry {
|
package/esm/router.js
CHANGED
|
@@ -17,7 +17,6 @@ import express, { Router } from 'express';
|
|
|
17
17
|
import { Logger } from '@pgpmjs/logger';
|
|
18
18
|
import { OllamaAdapter } from '@agentic-kit/ollama';
|
|
19
19
|
import { checkQuota, logInference, recordUsage } from './billing';
|
|
20
|
-
import { getAgentDiscovery, getDatabaseConfig } from './discovery';
|
|
21
20
|
import { getEnvOptions } from './env';
|
|
22
21
|
const log = new Logger('agentic-server');
|
|
23
22
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
@@ -49,19 +48,15 @@ async function handleCreateThread(req, res, entityId) {
|
|
|
49
48
|
res.status(401).json({ error: 'Authentication required' });
|
|
50
49
|
return;
|
|
51
50
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
const discovery = await getAgentDiscovery(ctx.pool, ctx.api.dbname);
|
|
57
|
-
if (!discovery?.thread) {
|
|
51
|
+
const agentChat = await ctx.useModule('agentChat');
|
|
52
|
+
if (!agentChat?.threadTableName) {
|
|
58
53
|
res.status(404).json({ error: 'Agent module not provisioned for this database' });
|
|
59
54
|
return;
|
|
60
55
|
}
|
|
61
56
|
const body = req.body || {};
|
|
62
|
-
const {
|
|
57
|
+
const { schemaName, threadTableName } = agentChat;
|
|
63
58
|
const result = await ctx.withPgClient(async (client) => {
|
|
64
|
-
const { rows } = await client.query(`INSERT INTO "${
|
|
59
|
+
const { rows } = await client.query(`INSERT INTO "${schemaName}"."${threadTableName}"
|
|
65
60
|
(entity_id, owner_id, mode, model, system_prompt, title)
|
|
66
61
|
VALUES ($1, $2, $3, $4, $5, $6)
|
|
67
62
|
RETURNING id, mode, model, system_prompt, status, created_at`, [
|
|
@@ -89,12 +84,8 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
89
84
|
res.status(401).json({ error: 'Authentication required' });
|
|
90
85
|
return;
|
|
91
86
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
const discovery = await getAgentDiscovery(ctx.pool, ctx.api.dbname);
|
|
97
|
-
if (!discovery?.thread || !discovery?.message) {
|
|
87
|
+
const agentChat = await ctx.useModule('agentChat');
|
|
88
|
+
if (!agentChat?.threadTableName || !agentChat?.messageTableName) {
|
|
98
89
|
res.status(404).json({ error: 'Agent module not provisioned for this database' });
|
|
99
90
|
return;
|
|
100
91
|
}
|
|
@@ -103,13 +94,13 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
103
94
|
res.status(400).json({ error: 'messages[] is required and must not be empty' });
|
|
104
95
|
return;
|
|
105
96
|
}
|
|
106
|
-
const {
|
|
97
|
+
const { schemaName, threadTableName, messageTableName } = agentChat;
|
|
107
98
|
const threadId = req.params.thread_id;
|
|
108
99
|
const userId = ctx.userId;
|
|
109
100
|
// Verify thread exists (RLS enforced)
|
|
110
101
|
const threadRow = await ctx.withPgClient(async (client) => {
|
|
111
102
|
const { rows } = await client.query(`SELECT id, mode, model, system_prompt, status
|
|
112
|
-
FROM "${
|
|
103
|
+
FROM "${schemaName}"."${threadTableName}"
|
|
113
104
|
WHERE id = $1`, [threadId]);
|
|
114
105
|
return rows[0];
|
|
115
106
|
});
|
|
@@ -117,10 +108,12 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
117
108
|
res.status(404).json({ error: 'Thread not found' });
|
|
118
109
|
return;
|
|
119
110
|
}
|
|
120
|
-
// Resolve billing + inference log config
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
111
|
+
// Resolve billing + inference log config via loaders
|
|
112
|
+
const [billing, inferenceLog] = await Promise.all([
|
|
113
|
+
ctx.useModule('billing'),
|
|
114
|
+
ctx.useModule('inferenceLog'),
|
|
115
|
+
]);
|
|
116
|
+
const dbConfig = { billing: billing ?? null, inferenceLog: inferenceLog ?? null };
|
|
124
117
|
const ollama = resolveOllamaAdapter();
|
|
125
118
|
if (!ollama) {
|
|
126
119
|
res.status(503).json({ error: 'No LLM provider configured' });
|
|
@@ -144,16 +137,16 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
144
137
|
await ctx.withPgClient(async (client) => {
|
|
145
138
|
for (const msg of body.messages) {
|
|
146
139
|
if (msg.role === 'user') {
|
|
147
|
-
await client.query(`INSERT INTO "${
|
|
140
|
+
await client.query(`INSERT INTO "${schemaName}"."${messageTableName}"
|
|
148
141
|
(thread_id, owner_id, entity_id, author_role, parts)
|
|
149
|
-
VALUES ($1, $2, (SELECT entity_id FROM "${
|
|
142
|
+
VALUES ($1, $2, (SELECT entity_id FROM "${schemaName}"."${threadTableName}" WHERE id = $1), $3, $4)`, [threadId, userId, 'user', JSON.stringify([{ type: 'text', text: msg.content }])]);
|
|
150
143
|
}
|
|
151
144
|
}
|
|
152
145
|
});
|
|
153
146
|
// Load full thread history
|
|
154
147
|
const history = await ctx.withPgClient(async (client) => {
|
|
155
148
|
const { rows } = await client.query(`SELECT author_role, parts, created_at
|
|
156
|
-
FROM "${
|
|
149
|
+
FROM "${schemaName}"."${messageTableName}"
|
|
157
150
|
WHERE thread_id = $1
|
|
158
151
|
ORDER BY created_at ASC`, [threadId]);
|
|
159
152
|
return rows;
|
|
@@ -181,19 +174,21 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
181
174
|
await handleStreamingResponse(req, res, {
|
|
182
175
|
ctx, ollama, model, llmMessages, body,
|
|
183
176
|
entityId, userId, threadId,
|
|
184
|
-
|
|
177
|
+
schemaName, threadTableName, messageTableName,
|
|
178
|
+
dbConfig, startTime, meterSlug,
|
|
185
179
|
});
|
|
186
180
|
}
|
|
187
181
|
else {
|
|
188
182
|
await handleBatchResponse(req, res, {
|
|
189
183
|
ctx, ollama, model, llmMessages, body,
|
|
190
184
|
entityId, userId, threadId,
|
|
191
|
-
|
|
185
|
+
schemaName, threadTableName, messageTableName,
|
|
186
|
+
dbConfig, startTime, meterSlug,
|
|
192
187
|
});
|
|
193
188
|
}
|
|
194
189
|
}
|
|
195
190
|
async function handleStreamingResponse(_req, res, mc) {
|
|
196
|
-
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId,
|
|
191
|
+
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, schemaName, threadTableName, messageTableName, dbConfig, startTime, meterSlug } = mc;
|
|
197
192
|
res.writeHead(200, {
|
|
198
193
|
'Content-Type': 'text/event-stream',
|
|
199
194
|
'Cache-Control': 'no-cache',
|
|
@@ -248,9 +243,9 @@ async function handleStreamingResponse(_req, res, mc) {
|
|
|
248
243
|
// Persist assistant message (fire-and-forget)
|
|
249
244
|
if (content) {
|
|
250
245
|
ctx.withPgClient(async (client) => {
|
|
251
|
-
await client.query(`INSERT INTO "${
|
|
246
|
+
await client.query(`INSERT INTO "${schemaName}"."${messageTableName}"
|
|
252
247
|
(thread_id, owner_id, entity_id, author_role, parts, model)
|
|
253
|
-
VALUES ($1, $2, (SELECT entity_id FROM "${
|
|
248
|
+
VALUES ($1, $2, (SELECT entity_id FROM "${schemaName}"."${threadTableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
|
|
254
249
|
}).catch((err) => log.error('Failed to persist assistant message:', err));
|
|
255
250
|
}
|
|
256
251
|
// Record billing usage (fire-and-forget)
|
|
@@ -284,7 +279,7 @@ async function handleStreamingResponse(_req, res, mc) {
|
|
|
284
279
|
}
|
|
285
280
|
}
|
|
286
281
|
async function handleBatchResponse(_req, res, mc) {
|
|
287
|
-
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId,
|
|
282
|
+
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, schemaName, threadTableName, messageTableName, dbConfig, startTime, meterSlug } = mc;
|
|
288
283
|
const systemMsg = llmMessages.find(m => m.role === 'system');
|
|
289
284
|
const nonSystem = llmMessages.filter(m => m.role !== 'system');
|
|
290
285
|
const modelDesc = ollama.adapter.createModel(model, { maxOutputTokens: undefined });
|
|
@@ -315,9 +310,9 @@ async function handleBatchResponse(_req, res, mc) {
|
|
|
315
310
|
};
|
|
316
311
|
// Persist assistant message
|
|
317
312
|
await ctx.withPgClient(async (client) => {
|
|
318
|
-
await client.query(`INSERT INTO "${
|
|
313
|
+
await client.query(`INSERT INTO "${schemaName}"."${messageTableName}"
|
|
319
314
|
(thread_id, owner_id, entity_id, author_role, parts, model)
|
|
320
|
-
VALUES ($1, $2, (SELECT entity_id FROM "${
|
|
315
|
+
VALUES ($1, $2, (SELECT entity_id FROM "${schemaName}"."${threadTableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
|
|
321
316
|
});
|
|
322
317
|
// Record billing + inference log (fire-and-forget)
|
|
323
318
|
if (dbConfig.billing && usage.totalTokens > 0) {
|
|
@@ -373,9 +368,12 @@ async function handleEmbed(req, res) {
|
|
|
373
368
|
}
|
|
374
369
|
const model = body.model ?? embedder.model;
|
|
375
370
|
const inputs = Array.isArray(body.input) ? body.input : [body.input];
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
371
|
+
// Resolve billing + inference log config via loaders
|
|
372
|
+
const [billing, inferenceLog] = await Promise.all([
|
|
373
|
+
ctx.useModule('billing'),
|
|
374
|
+
ctx.useModule('inferenceLog'),
|
|
375
|
+
]);
|
|
376
|
+
const dbConfig = { billing: billing ?? null, inferenceLog: inferenceLog ?? null };
|
|
379
377
|
// Quota check
|
|
380
378
|
if (dbConfig.billing) {
|
|
381
379
|
const allowed = await checkQuota(ctx, dbConfig.billing, ctx.userId, model);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentic-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Standalone Express LLM service — agent threads, chat streaming, billing metering, and inference logging via express-context",
|
|
5
5
|
"author": "Constructive <developers@constructive.io>",
|
|
6
6
|
"homepage": "https://github.com/constructive-io/constructive",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
32
|
"@agentic-kit/ollama": "^2.0.0",
|
|
33
|
-
"@constructive-io/express-context": "^0.
|
|
33
|
+
"@constructive-io/express-context": "^0.3.0",
|
|
34
34
|
"@pgpmjs/logger": "^2.11.0",
|
|
35
35
|
"pg": "^8.21.0",
|
|
36
36
|
"pg-cache": "^3.11.0"
|
|
@@ -39,8 +39,10 @@
|
|
|
39
39
|
"@types/express": "^5.0.6",
|
|
40
40
|
"@types/node": "^22.19.11",
|
|
41
41
|
"@types/pg": "^8.20.0",
|
|
42
|
+
"@types/supertest": "^7.2.0",
|
|
42
43
|
"express": "^5.2.1",
|
|
43
|
-
"makage": "^0.3.0"
|
|
44
|
+
"makage": "^0.3.0",
|
|
45
|
+
"supertest": "^7.2.2"
|
|
44
46
|
},
|
|
45
47
|
"peerDependencies": {
|
|
46
48
|
"express": "^5.0.0"
|
|
@@ -55,5 +57,5 @@
|
|
|
55
57
|
"metering",
|
|
56
58
|
"constructive"
|
|
57
59
|
],
|
|
58
|
-
"gitHead": "
|
|
60
|
+
"gitHead": "0d63238f2186b997a69a3287fa6cd35ebd93dda6"
|
|
59
61
|
}
|
package/router.js
CHANGED
|
@@ -53,7 +53,6 @@ const express_1 = __importStar(require("express"));
|
|
|
53
53
|
const logger_1 = require("@pgpmjs/logger");
|
|
54
54
|
const ollama_1 = require("@agentic-kit/ollama");
|
|
55
55
|
const billing_1 = require("./billing");
|
|
56
|
-
const discovery_1 = require("./discovery");
|
|
57
56
|
const env_1 = require("./env");
|
|
58
57
|
const log = new logger_1.Logger('agentic-server');
|
|
59
58
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
@@ -85,19 +84,15 @@ async function handleCreateThread(req, res, entityId) {
|
|
|
85
84
|
res.status(401).json({ error: 'Authentication required' });
|
|
86
85
|
return;
|
|
87
86
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
const discovery = await (0, discovery_1.getAgentDiscovery)(ctx.pool, ctx.api.dbname);
|
|
93
|
-
if (!discovery?.thread) {
|
|
87
|
+
const agentChat = await ctx.useModule('agentChat');
|
|
88
|
+
if (!agentChat?.threadTableName) {
|
|
94
89
|
res.status(404).json({ error: 'Agent module not provisioned for this database' });
|
|
95
90
|
return;
|
|
96
91
|
}
|
|
97
92
|
const body = req.body || {};
|
|
98
|
-
const {
|
|
93
|
+
const { schemaName, threadTableName } = agentChat;
|
|
99
94
|
const result = await ctx.withPgClient(async (client) => {
|
|
100
|
-
const { rows } = await client.query(`INSERT INTO "${
|
|
95
|
+
const { rows } = await client.query(`INSERT INTO "${schemaName}"."${threadTableName}"
|
|
101
96
|
(entity_id, owner_id, mode, model, system_prompt, title)
|
|
102
97
|
VALUES ($1, $2, $3, $4, $5, $6)
|
|
103
98
|
RETURNING id, mode, model, system_prompt, status, created_at`, [
|
|
@@ -125,12 +120,8 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
125
120
|
res.status(401).json({ error: 'Authentication required' });
|
|
126
121
|
return;
|
|
127
122
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
const discovery = await (0, discovery_1.getAgentDiscovery)(ctx.pool, ctx.api.dbname);
|
|
133
|
-
if (!discovery?.thread || !discovery?.message) {
|
|
123
|
+
const agentChat = await ctx.useModule('agentChat');
|
|
124
|
+
if (!agentChat?.threadTableName || !agentChat?.messageTableName) {
|
|
134
125
|
res.status(404).json({ error: 'Agent module not provisioned for this database' });
|
|
135
126
|
return;
|
|
136
127
|
}
|
|
@@ -139,13 +130,13 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
139
130
|
res.status(400).json({ error: 'messages[] is required and must not be empty' });
|
|
140
131
|
return;
|
|
141
132
|
}
|
|
142
|
-
const {
|
|
133
|
+
const { schemaName, threadTableName, messageTableName } = agentChat;
|
|
143
134
|
const threadId = req.params.thread_id;
|
|
144
135
|
const userId = ctx.userId;
|
|
145
136
|
// Verify thread exists (RLS enforced)
|
|
146
137
|
const threadRow = await ctx.withPgClient(async (client) => {
|
|
147
138
|
const { rows } = await client.query(`SELECT id, mode, model, system_prompt, status
|
|
148
|
-
FROM "${
|
|
139
|
+
FROM "${schemaName}"."${threadTableName}"
|
|
149
140
|
WHERE id = $1`, [threadId]);
|
|
150
141
|
return rows[0];
|
|
151
142
|
});
|
|
@@ -153,10 +144,12 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
153
144
|
res.status(404).json({ error: 'Thread not found' });
|
|
154
145
|
return;
|
|
155
146
|
}
|
|
156
|
-
// Resolve billing + inference log config
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
|
|
147
|
+
// Resolve billing + inference log config via loaders
|
|
148
|
+
const [billing, inferenceLog] = await Promise.all([
|
|
149
|
+
ctx.useModule('billing'),
|
|
150
|
+
ctx.useModule('inferenceLog'),
|
|
151
|
+
]);
|
|
152
|
+
const dbConfig = { billing: billing ?? null, inferenceLog: inferenceLog ?? null };
|
|
160
153
|
const ollama = resolveOllamaAdapter();
|
|
161
154
|
if (!ollama) {
|
|
162
155
|
res.status(503).json({ error: 'No LLM provider configured' });
|
|
@@ -180,16 +173,16 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
180
173
|
await ctx.withPgClient(async (client) => {
|
|
181
174
|
for (const msg of body.messages) {
|
|
182
175
|
if (msg.role === 'user') {
|
|
183
|
-
await client.query(`INSERT INTO "${
|
|
176
|
+
await client.query(`INSERT INTO "${schemaName}"."${messageTableName}"
|
|
184
177
|
(thread_id, owner_id, entity_id, author_role, parts)
|
|
185
|
-
VALUES ($1, $2, (SELECT entity_id FROM "${
|
|
178
|
+
VALUES ($1, $2, (SELECT entity_id FROM "${schemaName}"."${threadTableName}" WHERE id = $1), $3, $4)`, [threadId, userId, 'user', JSON.stringify([{ type: 'text', text: msg.content }])]);
|
|
186
179
|
}
|
|
187
180
|
}
|
|
188
181
|
});
|
|
189
182
|
// Load full thread history
|
|
190
183
|
const history = await ctx.withPgClient(async (client) => {
|
|
191
184
|
const { rows } = await client.query(`SELECT author_role, parts, created_at
|
|
192
|
-
FROM "${
|
|
185
|
+
FROM "${schemaName}"."${messageTableName}"
|
|
193
186
|
WHERE thread_id = $1
|
|
194
187
|
ORDER BY created_at ASC`, [threadId]);
|
|
195
188
|
return rows;
|
|
@@ -217,19 +210,21 @@ async function handleSendMessage(req, res, entityId) {
|
|
|
217
210
|
await handleStreamingResponse(req, res, {
|
|
218
211
|
ctx, ollama, model, llmMessages, body,
|
|
219
212
|
entityId, userId, threadId,
|
|
220
|
-
|
|
213
|
+
schemaName, threadTableName, messageTableName,
|
|
214
|
+
dbConfig, startTime, meterSlug,
|
|
221
215
|
});
|
|
222
216
|
}
|
|
223
217
|
else {
|
|
224
218
|
await handleBatchResponse(req, res, {
|
|
225
219
|
ctx, ollama, model, llmMessages, body,
|
|
226
220
|
entityId, userId, threadId,
|
|
227
|
-
|
|
221
|
+
schemaName, threadTableName, messageTableName,
|
|
222
|
+
dbConfig, startTime, meterSlug,
|
|
228
223
|
});
|
|
229
224
|
}
|
|
230
225
|
}
|
|
231
226
|
async function handleStreamingResponse(_req, res, mc) {
|
|
232
|
-
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId,
|
|
227
|
+
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, schemaName, threadTableName, messageTableName, dbConfig, startTime, meterSlug } = mc;
|
|
233
228
|
res.writeHead(200, {
|
|
234
229
|
'Content-Type': 'text/event-stream',
|
|
235
230
|
'Cache-Control': 'no-cache',
|
|
@@ -284,9 +279,9 @@ async function handleStreamingResponse(_req, res, mc) {
|
|
|
284
279
|
// Persist assistant message (fire-and-forget)
|
|
285
280
|
if (content) {
|
|
286
281
|
ctx.withPgClient(async (client) => {
|
|
287
|
-
await client.query(`INSERT INTO "${
|
|
282
|
+
await client.query(`INSERT INTO "${schemaName}"."${messageTableName}"
|
|
288
283
|
(thread_id, owner_id, entity_id, author_role, parts, model)
|
|
289
|
-
VALUES ($1, $2, (SELECT entity_id FROM "${
|
|
284
|
+
VALUES ($1, $2, (SELECT entity_id FROM "${schemaName}"."${threadTableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
|
|
290
285
|
}).catch((err) => log.error('Failed to persist assistant message:', err));
|
|
291
286
|
}
|
|
292
287
|
// Record billing usage (fire-and-forget)
|
|
@@ -320,7 +315,7 @@ async function handleStreamingResponse(_req, res, mc) {
|
|
|
320
315
|
}
|
|
321
316
|
}
|
|
322
317
|
async function handleBatchResponse(_req, res, mc) {
|
|
323
|
-
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId,
|
|
318
|
+
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, schemaName, threadTableName, messageTableName, dbConfig, startTime, meterSlug } = mc;
|
|
324
319
|
const systemMsg = llmMessages.find(m => m.role === 'system');
|
|
325
320
|
const nonSystem = llmMessages.filter(m => m.role !== 'system');
|
|
326
321
|
const modelDesc = ollama.adapter.createModel(model, { maxOutputTokens: undefined });
|
|
@@ -351,9 +346,9 @@ async function handleBatchResponse(_req, res, mc) {
|
|
|
351
346
|
};
|
|
352
347
|
// Persist assistant message
|
|
353
348
|
await ctx.withPgClient(async (client) => {
|
|
354
|
-
await client.query(`INSERT INTO "${
|
|
349
|
+
await client.query(`INSERT INTO "${schemaName}"."${messageTableName}"
|
|
355
350
|
(thread_id, owner_id, entity_id, author_role, parts, model)
|
|
356
|
-
VALUES ($1, $2, (SELECT entity_id FROM "${
|
|
351
|
+
VALUES ($1, $2, (SELECT entity_id FROM "${schemaName}"."${threadTableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
|
|
357
352
|
});
|
|
358
353
|
// Record billing + inference log (fire-and-forget)
|
|
359
354
|
if (dbConfig.billing && usage.totalTokens > 0) {
|
|
@@ -409,9 +404,12 @@ async function handleEmbed(req, res) {
|
|
|
409
404
|
}
|
|
410
405
|
const model = body.model ?? embedder.model;
|
|
411
406
|
const inputs = Array.isArray(body.input) ? body.input : [body.input];
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
407
|
+
// Resolve billing + inference log config via loaders
|
|
408
|
+
const [billing, inferenceLog] = await Promise.all([
|
|
409
|
+
ctx.useModule('billing'),
|
|
410
|
+
ctx.useModule('inferenceLog'),
|
|
411
|
+
]);
|
|
412
|
+
const dbConfig = { billing: billing ?? null, inferenceLog: inferenceLog ?? null };
|
|
415
413
|
// Quota check
|
|
416
414
|
if (dbConfig.billing) {
|
|
417
415
|
const allowed = await (0, billing_1.checkQuota)(ctx, dbConfig.billing, ctx.userId, model);
|