agentic-server 0.2.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/LICENSE +23 -0
- package/README.md +129 -0
- package/billing.d.ts +24 -0
- package/billing.js +60 -0
- package/cache.d.ts +16 -0
- package/cache.js +39 -0
- package/discovery.d.ts +38 -0
- package/discovery.js +130 -0
- package/env.d.ts +21 -0
- package/env.js +40 -0
- package/esm/billing.js +55 -0
- package/esm/cache.js +35 -0
- package/esm/discovery.js +124 -0
- package/esm/env.js +37 -0
- package/esm/index.js +24 -0
- package/esm/router.js +503 -0
- package/index.d.ts +27 -0
- package/index.js +37 -0
- package/package.json +59 -0
- package/router.d.ts +17 -0
- package/router.js +539 -0
package/esm/discovery.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* discovery — Runtime resolution of agent and billing module tables
|
|
3
|
+
*
|
|
4
|
+
* Queries metaschema_modules_public to find:
|
|
5
|
+
* - agent_chat_module: thread/message/task table names
|
|
6
|
+
* - billing_module: billing function names (check_quota, record_usage)
|
|
7
|
+
* - inference_log_module: inference log table name
|
|
8
|
+
*
|
|
9
|
+
* Results are cached with a TTL to avoid per-request database hits.
|
|
10
|
+
*/
|
|
11
|
+
import { TtlCache } from './cache';
|
|
12
|
+
// ─── SQL ────────────────────────────────────────────────────────────────────
|
|
13
|
+
const AGENT_DISCOVERY_SQL = `
|
|
14
|
+
SELECT
|
|
15
|
+
s.schema_name,
|
|
16
|
+
acm.thread_table_name,
|
|
17
|
+
acm.message_table_name,
|
|
18
|
+
acm.task_table_name
|
|
19
|
+
FROM metaschema_modules_public.agent_chat_module acm
|
|
20
|
+
JOIN metaschema_public.schema s ON s.id = acm.schema_id
|
|
21
|
+
LIMIT 1
|
|
22
|
+
`;
|
|
23
|
+
const SCHEMA_EXISTS_SQL = `
|
|
24
|
+
SELECT 1 FROM information_schema.schemata WHERE schema_name = $1 LIMIT 1
|
|
25
|
+
`;
|
|
26
|
+
const BILLING_MODULE_SQL = `
|
|
27
|
+
SELECT
|
|
28
|
+
s.schema_name AS public_schema,
|
|
29
|
+
ps.schema_name AS private_schema,
|
|
30
|
+
bm.record_usage_function
|
|
31
|
+
FROM metaschema_modules_public.billing_module bm
|
|
32
|
+
JOIN metaschema_public.schema s ON bm.schema_id = s.id
|
|
33
|
+
JOIN metaschema_public.schema ps ON bm.private_schema_id = ps.id
|
|
34
|
+
WHERE bm.database_id = $1
|
|
35
|
+
LIMIT 1
|
|
36
|
+
`;
|
|
37
|
+
const INFERENCE_LOG_MODULE_SQL = `
|
|
38
|
+
SELECT
|
|
39
|
+
s.schema_name AS schema,
|
|
40
|
+
ilm.inference_log_table_name AS table_name
|
|
41
|
+
FROM metaschema_modules_public.inference_log_module ilm
|
|
42
|
+
JOIN metaschema_public.schema s ON ilm.schema_id = s.id
|
|
43
|
+
WHERE ilm.database_id = $1
|
|
44
|
+
LIMIT 1
|
|
45
|
+
`;
|
|
46
|
+
// ─── Caches ─────────────────────────────────────────────────────────────────
|
|
47
|
+
const agentCache = new TtlCache(60_000); // 1 minute
|
|
48
|
+
const configCache = new TtlCache(5 * 60_000); // 5 minutes
|
|
49
|
+
// ─── Agent Discovery ────────────────────────────────────────────────────────
|
|
50
|
+
export async function getAgentDiscovery(pool, dbname) {
|
|
51
|
+
const cached = agentCache.get(dbname);
|
|
52
|
+
if (cached !== undefined)
|
|
53
|
+
return cached;
|
|
54
|
+
let discovery = null;
|
|
55
|
+
try {
|
|
56
|
+
const { rows } = await pool.query(AGENT_DISCOVERY_SQL);
|
|
57
|
+
if (rows.length > 0) {
|
|
58
|
+
const row = rows[0];
|
|
59
|
+
const schemaName = row.schema_name;
|
|
60
|
+
discovery = {
|
|
61
|
+
thread: row.thread_table_name
|
|
62
|
+
? { schemaName, tableName: row.thread_table_name }
|
|
63
|
+
: null,
|
|
64
|
+
message: row.message_table_name
|
|
65
|
+
? { schemaName, tableName: row.message_table_name }
|
|
66
|
+
: null,
|
|
67
|
+
task: row.task_table_name
|
|
68
|
+
? { schemaName, tableName: row.task_table_name }
|
|
69
|
+
: null,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// Module not provisioned in this database
|
|
75
|
+
}
|
|
76
|
+
agentCache.set(dbname, discovery);
|
|
77
|
+
return discovery;
|
|
78
|
+
}
|
|
79
|
+
// ─── Database Config (Billing + Inference Log) ──────────────────────────────
|
|
80
|
+
export async function getDatabaseConfig(pool, databaseId) {
|
|
81
|
+
const cached = configCache.get(databaseId);
|
|
82
|
+
if (cached !== undefined)
|
|
83
|
+
return cached;
|
|
84
|
+
let billing = null;
|
|
85
|
+
let inferenceLog = null;
|
|
86
|
+
try {
|
|
87
|
+
const schemaCheck = await pool.query(SCHEMA_EXISTS_SQL, ['metaschema_modules_public']);
|
|
88
|
+
if (schemaCheck.rows.length > 0) {
|
|
89
|
+
const [billingResult, logResult] = await Promise.all([
|
|
90
|
+
pool.query(BILLING_MODULE_SQL, [databaseId]).catch(() => ({ rows: [] })),
|
|
91
|
+
pool.query(INFERENCE_LOG_MODULE_SQL, [databaseId]).catch(() => ({ rows: [] })),
|
|
92
|
+
]);
|
|
93
|
+
const bRow = billingResult.rows[0];
|
|
94
|
+
if (bRow?.record_usage_function) {
|
|
95
|
+
billing = {
|
|
96
|
+
publicSchema: bRow.public_schema,
|
|
97
|
+
privateSchema: bRow.private_schema,
|
|
98
|
+
recordUsageFunction: bRow.record_usage_function,
|
|
99
|
+
checkBillingQuotaFunction: 'check_billing_quota',
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const lRow = logResult.rows[0];
|
|
103
|
+
if (lRow?.schema && lRow?.table_name) {
|
|
104
|
+
inferenceLog = {
|
|
105
|
+
schema: lRow.schema,
|
|
106
|
+
tableName: lRow.table_name,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
// metaschema not provisioned
|
|
113
|
+
}
|
|
114
|
+
const entry = { billing, inferenceLog };
|
|
115
|
+
configCache.set(databaseId, entry);
|
|
116
|
+
return entry;
|
|
117
|
+
}
|
|
118
|
+
// ─── Cache Management ───────────────────────────────────────────────────────
|
|
119
|
+
export function clearAgentCache() {
|
|
120
|
+
agentCache.clear();
|
|
121
|
+
}
|
|
122
|
+
export function clearConfigCache() {
|
|
123
|
+
configCache.clear();
|
|
124
|
+
}
|
package/esm/env.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* env — LLM provider configuration from environment variables
|
|
3
|
+
*
|
|
4
|
+
* Environment variables:
|
|
5
|
+
* EMBEDDER_PROVIDER - Embedding provider ('ollama')
|
|
6
|
+
* EMBEDDER_MODEL - Embedding model (default: 'nomic-embed-text')
|
|
7
|
+
* EMBEDDER_BASE_URL - Embedding provider URL (default: 'http://localhost:11434')
|
|
8
|
+
* CHAT_PROVIDER - Chat provider ('ollama')
|
|
9
|
+
* CHAT_MODEL - Chat model (default: 'llama3')
|
|
10
|
+
* CHAT_BASE_URL - Chat provider URL (default: 'http://localhost:11434')
|
|
11
|
+
*/
|
|
12
|
+
const DEFAULTS = {
|
|
13
|
+
embedding: {
|
|
14
|
+
provider: 'ollama',
|
|
15
|
+
model: 'nomic-embed-text',
|
|
16
|
+
baseUrl: 'http://localhost:11434',
|
|
17
|
+
},
|
|
18
|
+
chat: {
|
|
19
|
+
provider: 'ollama',
|
|
20
|
+
model: 'llama3',
|
|
21
|
+
baseUrl: 'http://localhost:11434',
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
export function getEnvOptions() {
|
|
25
|
+
return {
|
|
26
|
+
embedding: {
|
|
27
|
+
provider: process.env.EMBEDDER_PROVIDER ?? DEFAULTS.embedding.provider,
|
|
28
|
+
model: process.env.EMBEDDER_MODEL ?? DEFAULTS.embedding.model,
|
|
29
|
+
baseUrl: process.env.EMBEDDER_BASE_URL ?? DEFAULTS.embedding.baseUrl,
|
|
30
|
+
},
|
|
31
|
+
chat: {
|
|
32
|
+
provider: process.env.CHAT_PROVIDER ?? DEFAULTS.chat.provider,
|
|
33
|
+
model: process.env.CHAT_MODEL ?? DEFAULTS.chat.model,
|
|
34
|
+
baseUrl: process.env.CHAT_BASE_URL ?? DEFAULTS.chat.baseUrl,
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
package/esm/index.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agentic-server — Standalone Express LLM service
|
|
3
|
+
*
|
|
4
|
+
* Express-only equivalent of graphile-llm: agent threads, chat streaming,
|
|
5
|
+
* billing metering, and inference logging. Uses @constructive-io/express-context
|
|
6
|
+
* for tenant-scoped database access.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import express from 'express';
|
|
11
|
+
* import { createContextMiddleware } from '@constructive-io/express-context';
|
|
12
|
+
* import { createAgenticRouter } from 'agentic-server';
|
|
13
|
+
*
|
|
14
|
+
* const app = express();
|
|
15
|
+
* app.use(createContextMiddleware());
|
|
16
|
+
* app.use(createAgenticRouter());
|
|
17
|
+
* app.listen(3001);
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export { createAgenticRouter } from './router';
|
|
21
|
+
export { getEnvOptions } from './env';
|
|
22
|
+
export { getAgentDiscovery, getDatabaseConfig, clearAgentCache, clearConfigCache } from './discovery';
|
|
23
|
+
export { checkQuota, recordUsage, logInference } from './billing';
|
|
24
|
+
export { TtlCache } from './cache';
|
package/esm/router.js
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* router — Express router for the agentic-server
|
|
3
|
+
*
|
|
4
|
+
* Provides REST endpoints for AI agent conversations:
|
|
5
|
+
*
|
|
6
|
+
* POST /v1/threads → create thread
|
|
7
|
+
* POST /v1/threads/:thread_id/messages → send message + stream response
|
|
8
|
+
* POST /v1/orgs/:entity_id/threads → create thread (entity-scoped)
|
|
9
|
+
* POST /v1/orgs/:entity_id/threads/:thread_id/messages → send message (entity-scoped)
|
|
10
|
+
* POST /v1/embed → generate embedding
|
|
11
|
+
*
|
|
12
|
+
* All routes require `req.constructive` (from @constructive-io/express-context).
|
|
13
|
+
* Billing (check_quota + record_usage) and inference logging are automatic
|
|
14
|
+
* when the billing/inference_log modules are provisioned.
|
|
15
|
+
*/
|
|
16
|
+
import express, { Router } from 'express';
|
|
17
|
+
import { Logger } from '@pgpmjs/logger';
|
|
18
|
+
import { OllamaAdapter } from '@agentic-kit/ollama';
|
|
19
|
+
import { checkQuota, logInference, recordUsage } from './billing';
|
|
20
|
+
import { getAgentDiscovery, getDatabaseConfig } from './discovery';
|
|
21
|
+
import { getEnvOptions } from './env';
|
|
22
|
+
const log = new Logger('agentic-server');
|
|
23
|
+
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
24
|
+
function resolveOllamaAdapter() {
|
|
25
|
+
const { chat } = getEnvOptions();
|
|
26
|
+
if (chat.provider === 'ollama') {
|
|
27
|
+
return {
|
|
28
|
+
adapter: new OllamaAdapter(chat.baseUrl),
|
|
29
|
+
model: chat.model,
|
|
30
|
+
baseUrl: chat.baseUrl,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
function resolveEmbeddingAdapter() {
|
|
36
|
+
const { embedding } = getEnvOptions();
|
|
37
|
+
if (embedding.provider === 'ollama') {
|
|
38
|
+
return {
|
|
39
|
+
adapter: new OllamaAdapter(embedding.baseUrl),
|
|
40
|
+
model: embedding.model,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
// ─── Route Handlers ─────────────────────────────────────────────────────────
|
|
46
|
+
async function handleCreateThread(req, res, entityId) {
|
|
47
|
+
const ctx = req.constructive;
|
|
48
|
+
if (!ctx?.userId) {
|
|
49
|
+
res.status(401).json({ error: 'Authentication required' });
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (!ctx.api.dbname) {
|
|
53
|
+
res.status(400).json({ error: 'Database not resolved' });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const discovery = await getAgentDiscovery(ctx.pool, ctx.api.dbname);
|
|
57
|
+
if (!discovery?.thread) {
|
|
58
|
+
res.status(404).json({ error: 'Agent module not provisioned for this database' });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const body = req.body || {};
|
|
62
|
+
const { thread } = discovery;
|
|
63
|
+
const result = await ctx.withPgClient(async (client) => {
|
|
64
|
+
const { rows } = await client.query(`INSERT INTO "${thread.schemaName}"."${thread.tableName}"
|
|
65
|
+
(entity_id, owner_id, mode, model, system_prompt, title)
|
|
66
|
+
VALUES ($1, $2, $3, $4, $5, $6)
|
|
67
|
+
RETURNING id, mode, model, system_prompt, status, created_at`, [
|
|
68
|
+
entityId,
|
|
69
|
+
ctx.userId,
|
|
70
|
+
body.mode ?? 'ask',
|
|
71
|
+
body.model ?? null,
|
|
72
|
+
body.system_prompt ?? null,
|
|
73
|
+
body.title ?? null,
|
|
74
|
+
]);
|
|
75
|
+
return rows[0];
|
|
76
|
+
});
|
|
77
|
+
res.status(201).json({
|
|
78
|
+
id: result.id,
|
|
79
|
+
mode: result.mode,
|
|
80
|
+
model: result.model,
|
|
81
|
+
system_prompt: result.system_prompt,
|
|
82
|
+
status: result.status,
|
|
83
|
+
created_at: result.created_at,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async function handleSendMessage(req, res, entityId) {
|
|
87
|
+
const ctx = req.constructive;
|
|
88
|
+
if (!ctx?.userId) {
|
|
89
|
+
res.status(401).json({ error: 'Authentication required' });
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (!ctx.api.dbname) {
|
|
93
|
+
res.status(400).json({ error: 'Database not resolved' });
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const discovery = await getAgentDiscovery(ctx.pool, ctx.api.dbname);
|
|
97
|
+
if (!discovery?.thread || !discovery?.message) {
|
|
98
|
+
res.status(404).json({ error: 'Agent module not provisioned for this database' });
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const body = req.body || {};
|
|
102
|
+
if (!body.messages?.length) {
|
|
103
|
+
res.status(400).json({ error: 'messages[] is required and must not be empty' });
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const { thread, message: msgTable } = discovery;
|
|
107
|
+
const threadId = req.params.thread_id;
|
|
108
|
+
const userId = ctx.userId;
|
|
109
|
+
// Verify thread exists (RLS enforced)
|
|
110
|
+
const threadRow = await ctx.withPgClient(async (client) => {
|
|
111
|
+
const { rows } = await client.query(`SELECT id, mode, model, system_prompt, status
|
|
112
|
+
FROM "${thread.schemaName}"."${thread.tableName}"
|
|
113
|
+
WHERE id = $1`, [threadId]);
|
|
114
|
+
return rows[0];
|
|
115
|
+
});
|
|
116
|
+
if (!threadRow) {
|
|
117
|
+
res.status(404).json({ error: 'Thread not found' });
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
// Resolve billing + inference log config
|
|
121
|
+
const dbConfig = ctx.databaseId
|
|
122
|
+
? await getDatabaseConfig(ctx.pool, ctx.databaseId)
|
|
123
|
+
: { billing: null, inferenceLog: null };
|
|
124
|
+
const ollama = resolveOllamaAdapter();
|
|
125
|
+
if (!ollama) {
|
|
126
|
+
res.status(503).json({ error: 'No LLM provider configured' });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const model = body.model ?? threadRow.model ?? ollama.model;
|
|
130
|
+
const meterSlug = model;
|
|
131
|
+
// Quota check
|
|
132
|
+
if (dbConfig.billing) {
|
|
133
|
+
const allowed = await checkQuota(ctx, dbConfig.billing, entityId, meterSlug);
|
|
134
|
+
if (!allowed) {
|
|
135
|
+
res.status(429).json({
|
|
136
|
+
error: 'Token quota exceeded',
|
|
137
|
+
meter: meterSlug,
|
|
138
|
+
entity_id: entityId,
|
|
139
|
+
});
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// Persist user messages
|
|
144
|
+
await ctx.withPgClient(async (client) => {
|
|
145
|
+
for (const msg of body.messages) {
|
|
146
|
+
if (msg.role === 'user') {
|
|
147
|
+
await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
|
|
148
|
+
(thread_id, owner_id, entity_id, author_role, parts)
|
|
149
|
+
VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4)`, [threadId, userId, 'user', JSON.stringify([{ type: 'text', text: msg.content }])]);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
// Load full thread history
|
|
154
|
+
const history = await ctx.withPgClient(async (client) => {
|
|
155
|
+
const { rows } = await client.query(`SELECT author_role, parts, created_at
|
|
156
|
+
FROM "${msgTable.schemaName}"."${msgTable.tableName}"
|
|
157
|
+
WHERE thread_id = $1
|
|
158
|
+
ORDER BY created_at ASC`, [threadId]);
|
|
159
|
+
return rows;
|
|
160
|
+
});
|
|
161
|
+
const llmMessages = [];
|
|
162
|
+
if (threadRow.system_prompt) {
|
|
163
|
+
llmMessages.push({ role: 'system', content: threadRow.system_prompt });
|
|
164
|
+
}
|
|
165
|
+
for (const row of history) {
|
|
166
|
+
const parts = Array.isArray(row.parts) ? row.parts : [];
|
|
167
|
+
const textContent = parts
|
|
168
|
+
.filter((p) => p.type === 'text')
|
|
169
|
+
.map((p) => p.text)
|
|
170
|
+
.join('');
|
|
171
|
+
if (textContent) {
|
|
172
|
+
llmMessages.push({
|
|
173
|
+
role: row.author_role === 'user' ? 'user' : 'assistant',
|
|
174
|
+
content: textContent,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const startTime = Date.now();
|
|
179
|
+
const shouldStream = body.stream !== false;
|
|
180
|
+
if (shouldStream) {
|
|
181
|
+
await handleStreamingResponse(req, res, {
|
|
182
|
+
ctx, ollama, model, llmMessages, body,
|
|
183
|
+
entityId, userId, threadId,
|
|
184
|
+
thread, msgTable, dbConfig, startTime, meterSlug,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
await handleBatchResponse(req, res, {
|
|
189
|
+
ctx, ollama, model, llmMessages, body,
|
|
190
|
+
entityId, userId, threadId,
|
|
191
|
+
thread, msgTable, dbConfig, startTime, meterSlug,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
async function handleStreamingResponse(_req, res, mc) {
|
|
196
|
+
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, thread, msgTable, dbConfig, startTime, meterSlug } = mc;
|
|
197
|
+
res.writeHead(200, {
|
|
198
|
+
'Content-Type': 'text/event-stream',
|
|
199
|
+
'Cache-Control': 'no-cache',
|
|
200
|
+
'Connection': 'keep-alive',
|
|
201
|
+
'X-Accel-Buffering': 'no',
|
|
202
|
+
});
|
|
203
|
+
const messageId = `msg_${Date.now()}`;
|
|
204
|
+
try {
|
|
205
|
+
const systemMsg = llmMessages.find(m => m.role === 'system');
|
|
206
|
+
const nonSystem = llmMessages.filter(m => m.role !== 'system');
|
|
207
|
+
const modelDesc = ollama.adapter.createModel(model, { maxOutputTokens: undefined });
|
|
208
|
+
const context = {
|
|
209
|
+
systemPrompt: systemMsg?.content,
|
|
210
|
+
messages: nonSystem.map((m) => ({
|
|
211
|
+
role: m.role,
|
|
212
|
+
content: m.content,
|
|
213
|
+
timestamp: Date.now(),
|
|
214
|
+
})),
|
|
215
|
+
};
|
|
216
|
+
const stream = ollama.adapter.stream(modelDesc, context, {
|
|
217
|
+
temperature: body.temperature,
|
|
218
|
+
});
|
|
219
|
+
let streamedContent = '';
|
|
220
|
+
for await (const event of stream) {
|
|
221
|
+
if (event.type === 'text_delta') {
|
|
222
|
+
streamedContent += event.delta;
|
|
223
|
+
const sseEvent = {
|
|
224
|
+
id: messageId,
|
|
225
|
+
choices: [{
|
|
226
|
+
index: 0,
|
|
227
|
+
delta: { content: event.delta, role: 'assistant' },
|
|
228
|
+
finish_reason: null,
|
|
229
|
+
}],
|
|
230
|
+
model,
|
|
231
|
+
};
|
|
232
|
+
res.write(`data: ${JSON.stringify(sseEvent)}\n\n`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const result = await stream.result();
|
|
236
|
+
const content = streamedContent;
|
|
237
|
+
const latencyMs = Date.now() - startTime;
|
|
238
|
+
const usage = {
|
|
239
|
+
input: result.usage.input,
|
|
240
|
+
output: result.usage.output,
|
|
241
|
+
reasoning: result.usage.reasoning,
|
|
242
|
+
cacheRead: result.usage.cacheRead,
|
|
243
|
+
cacheWrite: result.usage.cacheWrite,
|
|
244
|
+
totalTokens: result.usage.totalTokens,
|
|
245
|
+
};
|
|
246
|
+
res.write('data: [DONE]\n\n');
|
|
247
|
+
res.end();
|
|
248
|
+
// Persist assistant message (fire-and-forget)
|
|
249
|
+
if (content) {
|
|
250
|
+
ctx.withPgClient(async (client) => {
|
|
251
|
+
await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
|
|
252
|
+
(thread_id, owner_id, entity_id, author_role, parts, model)
|
|
253
|
+
VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
|
|
254
|
+
}).catch((err) => log.error('Failed to persist assistant message:', err));
|
|
255
|
+
}
|
|
256
|
+
// Record billing usage (fire-and-forget)
|
|
257
|
+
if (dbConfig.billing && usage.totalTokens > 0) {
|
|
258
|
+
recordUsage(ctx, dbConfig.billing, entityId, meterSlug, usage.totalTokens, {
|
|
259
|
+
input_tokens: usage.input,
|
|
260
|
+
output_tokens: usage.output,
|
|
261
|
+
cache_read_tokens: usage.cacheRead,
|
|
262
|
+
cache_write_tokens: usage.cacheWrite,
|
|
263
|
+
model,
|
|
264
|
+
latency_ms: latencyMs,
|
|
265
|
+
stream: true,
|
|
266
|
+
}).catch(() => { });
|
|
267
|
+
}
|
|
268
|
+
// Inference log (fire-and-forget)
|
|
269
|
+
if (dbConfig.inferenceLog) {
|
|
270
|
+
logInference(ctx, dbConfig.inferenceLog, {
|
|
271
|
+
entityId, actorId: userId, model, provider: 'ollama',
|
|
272
|
+
service: 'llm', operation: 'chat',
|
|
273
|
+
inputTokens: usage.input, outputTokens: usage.output,
|
|
274
|
+
totalTokens: usage.totalTokens, latencyMs, status: 'ok',
|
|
275
|
+
}).catch(() => { });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
catch (streamErr) {
|
|
279
|
+
log.error('Streaming error:', streamErr);
|
|
280
|
+
const errorEvent = { error: { message: streamErr.message, type: 'stream_error' } };
|
|
281
|
+
res.write(`data: ${JSON.stringify(errorEvent)}\n\n`);
|
|
282
|
+
res.write('data: [DONE]\n\n');
|
|
283
|
+
res.end();
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async function handleBatchResponse(_req, res, mc) {
|
|
287
|
+
const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, thread, msgTable, dbConfig, startTime, meterSlug } = mc;
|
|
288
|
+
const systemMsg = llmMessages.find(m => m.role === 'system');
|
|
289
|
+
const nonSystem = llmMessages.filter(m => m.role !== 'system');
|
|
290
|
+
const modelDesc = ollama.adapter.createModel(model, { maxOutputTokens: undefined });
|
|
291
|
+
const context = {
|
|
292
|
+
systemPrompt: systemMsg?.content,
|
|
293
|
+
messages: nonSystem.map((m) => ({
|
|
294
|
+
role: m.role,
|
|
295
|
+
content: m.content,
|
|
296
|
+
timestamp: Date.now(),
|
|
297
|
+
})),
|
|
298
|
+
};
|
|
299
|
+
const stream = ollama.adapter.stream(modelDesc, context, {
|
|
300
|
+
temperature: body.temperature,
|
|
301
|
+
});
|
|
302
|
+
const result = await stream.result();
|
|
303
|
+
const content = result.content
|
|
304
|
+
.filter((block) => block.type === 'text')
|
|
305
|
+
.map((block) => block.text)
|
|
306
|
+
.join('');
|
|
307
|
+
const latencyMs = Date.now() - startTime;
|
|
308
|
+
const usage = {
|
|
309
|
+
input: result.usage.input,
|
|
310
|
+
output: result.usage.output,
|
|
311
|
+
reasoning: result.usage.reasoning,
|
|
312
|
+
cacheRead: result.usage.cacheRead,
|
|
313
|
+
cacheWrite: result.usage.cacheWrite,
|
|
314
|
+
totalTokens: result.usage.totalTokens,
|
|
315
|
+
};
|
|
316
|
+
// Persist assistant message
|
|
317
|
+
await ctx.withPgClient(async (client) => {
|
|
318
|
+
await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
|
|
319
|
+
(thread_id, owner_id, entity_id, author_role, parts, model)
|
|
320
|
+
VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
|
|
321
|
+
});
|
|
322
|
+
// Record billing + inference log (fire-and-forget)
|
|
323
|
+
if (dbConfig.billing && usage.totalTokens > 0) {
|
|
324
|
+
recordUsage(ctx, dbConfig.billing, entityId, meterSlug, usage.totalTokens, {
|
|
325
|
+
input_tokens: usage.input,
|
|
326
|
+
output_tokens: usage.output,
|
|
327
|
+
cache_read_tokens: usage.cacheRead,
|
|
328
|
+
cache_write_tokens: usage.cacheWrite,
|
|
329
|
+
model,
|
|
330
|
+
latency_ms: latencyMs,
|
|
331
|
+
stream: false,
|
|
332
|
+
}).catch(() => { });
|
|
333
|
+
}
|
|
334
|
+
if (dbConfig.inferenceLog) {
|
|
335
|
+
logInference(ctx, dbConfig.inferenceLog, {
|
|
336
|
+
entityId, actorId: userId, model, provider: 'ollama',
|
|
337
|
+
service: 'llm', operation: 'chat',
|
|
338
|
+
inputTokens: usage.input, outputTokens: usage.output,
|
|
339
|
+
totalTokens: usage.totalTokens, latencyMs, status: 'ok',
|
|
340
|
+
}).catch(() => { });
|
|
341
|
+
}
|
|
342
|
+
res.json({
|
|
343
|
+
id: `msg_${Date.now()}`,
|
|
344
|
+
choices: [{
|
|
345
|
+
index: 0,
|
|
346
|
+
message: { role: 'assistant', content },
|
|
347
|
+
finish_reason: 'stop',
|
|
348
|
+
}],
|
|
349
|
+
model,
|
|
350
|
+
usage: {
|
|
351
|
+
prompt_tokens: usage.input,
|
|
352
|
+
completion_tokens: usage.output,
|
|
353
|
+
total_tokens: usage.totalTokens,
|
|
354
|
+
},
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
// ─── Embedding Handler ──────────────────────────────────────────────────────
|
|
358
|
+
async function handleEmbed(req, res) {
|
|
359
|
+
const ctx = req.constructive;
|
|
360
|
+
if (!ctx?.userId) {
|
|
361
|
+
res.status(401).json({ error: 'Authentication required' });
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const body = req.body || {};
|
|
365
|
+
if (!body.input) {
|
|
366
|
+
res.status(400).json({ error: 'input is required' });
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const embedder = resolveEmbeddingAdapter();
|
|
370
|
+
if (!embedder) {
|
|
371
|
+
res.status(503).json({ error: 'No embedding provider configured' });
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const model = body.model ?? embedder.model;
|
|
375
|
+
const inputs = Array.isArray(body.input) ? body.input : [body.input];
|
|
376
|
+
const dbConfig = ctx.databaseId
|
|
377
|
+
? await getDatabaseConfig(ctx.pool, ctx.databaseId)
|
|
378
|
+
: { billing: null, inferenceLog: null };
|
|
379
|
+
// Quota check
|
|
380
|
+
if (dbConfig.billing) {
|
|
381
|
+
const allowed = await checkQuota(ctx, dbConfig.billing, ctx.userId, model);
|
|
382
|
+
if (!allowed) {
|
|
383
|
+
res.status(429).json({ error: 'Embedding quota exceeded', meter: model });
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const startTime = Date.now();
|
|
388
|
+
try {
|
|
389
|
+
const results = await Promise.all(inputs.map((text) => embedder.adapter.embed(text, model)));
|
|
390
|
+
const latencyMs = Date.now() - startTime;
|
|
391
|
+
const totalTokens = results.reduce((sum, r) => sum + r.promptTokens, 0);
|
|
392
|
+
// Record usage (fire-and-forget)
|
|
393
|
+
if (dbConfig.billing && totalTokens > 0) {
|
|
394
|
+
recordUsage(ctx, dbConfig.billing, ctx.userId, model, totalTokens, {
|
|
395
|
+
input_tokens: totalTokens,
|
|
396
|
+
model,
|
|
397
|
+
latency_ms: latencyMs,
|
|
398
|
+
batch_size: inputs.length,
|
|
399
|
+
}).catch(() => { });
|
|
400
|
+
}
|
|
401
|
+
if (dbConfig.inferenceLog) {
|
|
402
|
+
logInference(ctx, dbConfig.inferenceLog, {
|
|
403
|
+
entityId: ctx.userId,
|
|
404
|
+
actorId: ctx.userId,
|
|
405
|
+
model,
|
|
406
|
+
provider: 'ollama',
|
|
407
|
+
service: 'embedding',
|
|
408
|
+
operation: 'embed',
|
|
409
|
+
inputTokens: totalTokens,
|
|
410
|
+
outputTokens: 0,
|
|
411
|
+
totalTokens,
|
|
412
|
+
latencyMs,
|
|
413
|
+
status: 'ok',
|
|
414
|
+
}).catch(() => { });
|
|
415
|
+
}
|
|
416
|
+
res.json({
|
|
417
|
+
object: 'list',
|
|
418
|
+
data: results.map((r, i) => ({
|
|
419
|
+
object: 'embedding',
|
|
420
|
+
index: i,
|
|
421
|
+
embedding: r.embedding,
|
|
422
|
+
})),
|
|
423
|
+
model,
|
|
424
|
+
usage: {
|
|
425
|
+
prompt_tokens: totalTokens,
|
|
426
|
+
total_tokens: totalTokens,
|
|
427
|
+
},
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
catch (err) {
|
|
431
|
+
log.error('Embedding error:', err);
|
|
432
|
+
res.status(500).json({ error: err.message ?? 'Embedding failed' });
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
// ─── Router Factory ─────────────────────────────────────────────────────────
|
|
436
|
+
export function createAgenticRouter() {
|
|
437
|
+
const router = Router();
|
|
438
|
+
router.use(express.json());
|
|
439
|
+
// Entity-scoped routes
|
|
440
|
+
router.post('/v1/orgs/:entity_id/threads', async (req, res) => {
|
|
441
|
+
try {
|
|
442
|
+
await handleCreateThread(req, res, req.params.entity_id);
|
|
443
|
+
}
|
|
444
|
+
catch (err) {
|
|
445
|
+
log.error('Error creating thread:', err);
|
|
446
|
+
if (!res.headersSent)
|
|
447
|
+
res.status(500).json({ error: 'Internal server error' });
|
|
448
|
+
}
|
|
449
|
+
});
|
|
450
|
+
router.post('/v1/orgs/:entity_id/threads/:thread_id/messages', async (req, res) => {
|
|
451
|
+
try {
|
|
452
|
+
await handleSendMessage(req, res, req.params.entity_id);
|
|
453
|
+
}
|
|
454
|
+
catch (err) {
|
|
455
|
+
log.error('Error in messages endpoint:', err);
|
|
456
|
+
if (!res.headersSent)
|
|
457
|
+
res.status(500).json({ error: 'Internal server error' });
|
|
458
|
+
}
|
|
459
|
+
});
|
|
460
|
+
// Global routes (entity_id = user_id from JWT)
|
|
461
|
+
router.post('/v1/threads', async (req, res) => {
|
|
462
|
+
try {
|
|
463
|
+
const userId = req.constructive?.userId;
|
|
464
|
+
if (!userId) {
|
|
465
|
+
res.status(401).json({ error: 'Authentication required' });
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
await handleCreateThread(req, res, userId);
|
|
469
|
+
}
|
|
470
|
+
catch (err) {
|
|
471
|
+
log.error('Error creating thread:', err);
|
|
472
|
+
if (!res.headersSent)
|
|
473
|
+
res.status(500).json({ error: 'Internal server error' });
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
router.post('/v1/threads/:thread_id/messages', async (req, res) => {
|
|
477
|
+
try {
|
|
478
|
+
const userId = req.constructive?.userId;
|
|
479
|
+
if (!userId) {
|
|
480
|
+
res.status(401).json({ error: 'Authentication required' });
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
await handleSendMessage(req, res, userId);
|
|
484
|
+
}
|
|
485
|
+
catch (err) {
|
|
486
|
+
log.error('Error in messages endpoint:', err);
|
|
487
|
+
if (!res.headersSent)
|
|
488
|
+
res.status(500).json({ error: 'Internal server error' });
|
|
489
|
+
}
|
|
490
|
+
});
|
|
491
|
+
// Embedding endpoint
|
|
492
|
+
router.post('/v1/embed', async (req, res) => {
|
|
493
|
+
try {
|
|
494
|
+
await handleEmbed(req, res);
|
|
495
|
+
}
|
|
496
|
+
catch (err) {
|
|
497
|
+
log.error('Error in embed endpoint:', err);
|
|
498
|
+
if (!res.headersSent)
|
|
499
|
+
res.status(500).json({ error: 'Internal server error' });
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
return router;
|
|
503
|
+
}
|