@constructive-io/graphql-server 4.36.1 → 4.36.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.
@@ -1,539 +0,0 @@
1
- /**
2
- * LLM API Router
3
- *
4
- * Express router providing REST streaming endpoints for AI agent conversations.
5
- * Uses the agent tables (agent_thread, agent_message) discovered from the
6
- * agent_chat_module config table at runtime.
7
- *
8
- * Hybrid architecture:
9
- * - GraphQL handles CRUD (threads, messages, tasks) via PostGraphile
10
- * - REST handles SSE streaming for chat completions (what GraphQL can't do)
11
- *
12
- * Routes (entity-scoped):
13
- * POST /v1/orgs/:entity_id/threads → create thread
14
- * POST /v1/orgs/:entity_id/threads/:thread_id/messages → send message + stream response
15
- *
16
- * Routes (global — bills to actor_id from JWT):
17
- * POST /v1/threads → create thread (entity_id = user_id)
18
- * POST /v1/threads/:thread_id/messages → send message + stream response
19
- *
20
- * Auth: JWT from the auth middleware (req.token) → pg SET LOCAL context for RLS
21
- * Metering: check_billing_quota → LLM call → record_usage with real token counts
22
- *
23
- * Context: Uses `req.constructive` from @constructive-io/express-context
24
- * for tenant-scoped database access, pgSettings, and withPgClient.
25
- */
26
- import express, { Router } from 'express';
27
- import { Logger } from '@pgpmjs/logger';
28
- import { OllamaAdapter } from '@agentic-kit/ollama';
29
- import { ModuleConfigCache } from 'graphile-cache';
30
- import { getLlmEnvOptions, getAgentDiscovery, getLlmBillingConfig, } from 'graphile-llm';
31
- const log = new Logger('llm-api');
32
- // ─── Helpers ────────────────────────────────────────────────────────────────
33
- function resolveOllamaAdapter() {
34
- const { chat } = getLlmEnvOptions();
35
- if (chat.provider === 'ollama') {
36
- return {
37
- adapter: new OllamaAdapter(chat.baseUrl),
38
- model: chat.model,
39
- baseUrl: chat.baseUrl,
40
- };
41
- }
42
- return null;
43
- }
44
- // ─── Billing Helpers ────────────────────────────────────────────────────────
45
- async function checkQuota(ctx, billing, entityId, meterSlug) {
46
- try {
47
- return await ctx.withPgClient(async (client) => {
48
- const sql = `SELECT "${billing.privateSchema}"."${billing.checkBillingQuotaFunction}"($1, $2::uuid, $3) AS allowed`;
49
- const result = await client.query(sql, [meterSlug, entityId, 1]);
50
- return result.rows[0]?.allowed !== false;
51
- });
52
- }
53
- catch (e) {
54
- const message = e instanceof Error ? e.message : String(e);
55
- log.warn(`[llm-api] check_billing_quota failed (allowing): ${message}`);
56
- return true;
57
- }
58
- }
59
- async function recordUsage(ctx, billing, entityId, meterSlug, amount, metadata) {
60
- try {
61
- await ctx.withPgClient(async (client) => {
62
- const sql = `SELECT "${billing.privateSchema}"."${billing.recordUsageFunction}"($1, $2::uuid, $3, $4::jsonb)`;
63
- await client.query(sql, [meterSlug, entityId, amount, JSON.stringify(metadata)]);
64
- });
65
- }
66
- catch (e) {
67
- const message = e instanceof Error ? e.message : String(e);
68
- log.warn(`[llm-api] record_usage failed (non-fatal): ${message}`);
69
- }
70
- }
71
- async function resolveBilling(ctx) {
72
- if (!ctx.databaseId)
73
- return null;
74
- try {
75
- let billing = null;
76
- await ctx.withPgClient(async (client) => {
77
- const entry = await getLlmBillingConfig(client, ctx.databaseId);
78
- billing = entry.billing;
79
- });
80
- return billing;
81
- }
82
- catch {
83
- return null;
84
- }
85
- }
86
- const INFERENCE_LOG_DISCOVERY_SQL = `
87
- SELECT s.schema_name, ilm.inference_log_table_name
88
- FROM metaschema_modules_public.inference_log_module ilm
89
- JOIN metaschema_public.schema s ON s.id = ilm.schema_id
90
- LIMIT 1
91
- `;
92
- const inferenceLogCache = new ModuleConfigCache({
93
- name: 'inference-log',
94
- ttlMs: 60_000,
95
- });
96
- async function getInferenceLogInfo(pool, dbname) {
97
- const cached = inferenceLogCache.get(dbname);
98
- if (cached !== undefined)
99
- return cached;
100
- let info = null;
101
- try {
102
- const { rows } = await pool.query(INFERENCE_LOG_DISCOVERY_SQL);
103
- if (rows.length > 0) {
104
- info = {
105
- schemaName: rows[0].schema_name,
106
- tableName: rows[0].inference_log_table_name,
107
- };
108
- }
109
- }
110
- catch {
111
- // Module not provisioned
112
- }
113
- inferenceLogCache.set(dbname, info);
114
- return info;
115
- }
116
- async function logInference(ctx, logInfo, data) {
117
- try {
118
- await ctx.withPgClient(async (client) => {
119
- await client.query(`INSERT INTO "${logInfo.schemaName}"."${logInfo.tableName}"
120
- (entity_id, actor_id, model, provider, service, operation, input_tokens, output_tokens, total_tokens, latency_ms, status)
121
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, [
122
- data.entityId,
123
- data.actorId,
124
- data.model,
125
- data.provider,
126
- data.service,
127
- data.operation,
128
- data.inputTokens,
129
- data.outputTokens,
130
- data.totalTokens,
131
- data.latencyMs,
132
- data.status,
133
- ]);
134
- });
135
- }
136
- catch (e) {
137
- const message = e instanceof Error ? e.message : String(e);
138
- log.warn(`[llm-api] inference log INSERT failed (non-fatal): ${message}`);
139
- }
140
- }
141
- // ─── Route Handlers ─────────────────────────────────────────────────────────
142
- async function handleCreateThread(req, res, entityId) {
143
- const ctx = req.constructive;
144
- if (!ctx?.userId) {
145
- res.status(401).json({ error: 'Authentication required' });
146
- return;
147
- }
148
- if (!ctx.api.dbname) {
149
- res.status(400).json({ error: 'Database not resolved' });
150
- return;
151
- }
152
- const discovery = await getAgentDiscovery(ctx.pool, ctx.api.dbname);
153
- if (!discovery?.thread) {
154
- res.status(404).json({ error: 'Agent module not provisioned for this database' });
155
- return;
156
- }
157
- const body = req.body || {};
158
- const { thread } = discovery;
159
- const result = await ctx.withPgClient(async (client) => {
160
- const { rows } = await client.query(`INSERT INTO "${thread.schemaName}"."${thread.tableName}"
161
- (entity_id, owner_id, mode, model, system_prompt, title)
162
- VALUES ($1, $2, $3, $4, $5, $6)
163
- RETURNING id, mode, model, system_prompt, status, created_at`, [
164
- entityId,
165
- ctx.userId,
166
- body.mode ?? 'ask',
167
- body.model ?? null,
168
- body.system_prompt ?? null,
169
- body.title ?? null,
170
- ]);
171
- return rows[0];
172
- });
173
- res.status(201).json({
174
- id: result.id,
175
- mode: result.mode,
176
- model: result.model,
177
- system_prompt: result.system_prompt,
178
- status: result.status,
179
- created_at: result.created_at,
180
- });
181
- }
182
- async function handleSendMessage(req, res, entityId) {
183
- const ctx = req.constructive;
184
- if (!ctx?.userId) {
185
- res.status(401).json({ error: 'Authentication required' });
186
- return;
187
- }
188
- if (!ctx.api.dbname) {
189
- res.status(400).json({ error: 'Database not resolved' });
190
- return;
191
- }
192
- const discovery = await getAgentDiscovery(ctx.pool, ctx.api.dbname);
193
- if (!discovery?.thread || !discovery?.message) {
194
- res.status(404).json({ error: 'Agent module not provisioned for this database' });
195
- return;
196
- }
197
- const body = req.body || {};
198
- if (!body.messages?.length) {
199
- res.status(400).json({ error: 'messages[] is required and must not be empty' });
200
- return;
201
- }
202
- const { thread, message: msgTable } = discovery;
203
- const threadId = req.params.thread_id;
204
- const userId = ctx.userId;
205
- // 1. Verify thread exists and user owns it (RLS enforced)
206
- const threadRow = await ctx.withPgClient(async (client) => {
207
- const { rows } = await client.query(`SELECT id, mode, model, system_prompt, status
208
- FROM "${thread.schemaName}"."${thread.tableName}"
209
- WHERE id = $1`, [threadId]);
210
- return rows[0];
211
- });
212
- if (!threadRow) {
213
- res.status(404).json({ error: 'Thread not found' });
214
- return;
215
- }
216
- // 2. Resolve billing config + inference log discovery
217
- const billing = await resolveBilling(ctx);
218
- const inferenceLog = await getInferenceLogInfo(ctx.pool, ctx.api.dbname);
219
- const ollama = resolveOllamaAdapter();
220
- if (!ollama) {
221
- res.status(503).json({ error: 'No LLM provider configured' });
222
- return;
223
- }
224
- const model = body.model ?? threadRow.model ?? ollama.model;
225
- const meterSlug = model;
226
- if (billing) {
227
- const allowed = await checkQuota(ctx, billing, entityId, meterSlug);
228
- if (!allowed) {
229
- res.status(429).json({
230
- error: 'Token quota exceeded',
231
- meter: meterSlug,
232
- entity_id: entityId,
233
- });
234
- return;
235
- }
236
- }
237
- // 3. Persist user message(s)
238
- await ctx.withPgClient(async (client) => {
239
- for (const msg of body.messages) {
240
- if (msg.role === 'user') {
241
- await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
242
- (thread_id, owner_id, entity_id, author_role, parts)
243
- VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4)`, [
244
- threadId,
245
- userId,
246
- 'user',
247
- JSON.stringify([{ type: 'text', text: msg.content }]),
248
- ]);
249
- }
250
- }
251
- });
252
- // 4. Load full thread history for context
253
- const history = await ctx.withPgClient(async (client) => {
254
- const { rows } = await client.query(`SELECT author_role, parts, created_at
255
- FROM "${msgTable.schemaName}"."${msgTable.tableName}"
256
- WHERE thread_id = $1
257
- ORDER BY created_at ASC`, [threadId]);
258
- return rows;
259
- });
260
- const llmMessages = [];
261
- const systemPrompt = threadRow.system_prompt;
262
- if (systemPrompt) {
263
- llmMessages.push({ role: 'system', content: systemPrompt });
264
- }
265
- for (const row of history) {
266
- const parts = Array.isArray(row.parts) ? row.parts : [];
267
- const textContent = parts
268
- .filter((p) => p.type === 'text')
269
- .map((p) => p.text)
270
- .join('');
271
- if (textContent) {
272
- llmMessages.push({
273
- role: row.author_role === 'user' ? 'user' : 'assistant',
274
- content: textContent,
275
- });
276
- }
277
- }
278
- // 5. Call LLM with token usage tracking
279
- const shouldStream = body.stream !== false;
280
- const startTime = Date.now();
281
- if (shouldStream) {
282
- // ── SSE Streaming via OllamaAdapter ─────────────────────────────────
283
- res.writeHead(200, {
284
- 'Content-Type': 'text/event-stream',
285
- 'Cache-Control': 'no-cache',
286
- 'Connection': 'keep-alive',
287
- 'X-Accel-Buffering': 'no',
288
- });
289
- const messageId = `msg_${Date.now()}`;
290
- try {
291
- const systemMsg = llmMessages.find(m => m.role === 'system');
292
- const nonSystem = llmMessages.filter(m => m.role !== 'system');
293
- const modelDesc = ollama.adapter.createModel(model, {
294
- maxOutputTokens: undefined,
295
- });
296
- const context = {
297
- systemPrompt: systemMsg?.content,
298
- messages: nonSystem.map((m) => ({
299
- role: m.role,
300
- content: m.content,
301
- timestamp: Date.now(),
302
- })),
303
- };
304
- const stream = ollama.adapter.stream(modelDesc, context, {
305
- temperature: body.temperature,
306
- });
307
- let streamedContent = '';
308
- for await (const event of stream) {
309
- if (event.type === 'text_delta') {
310
- streamedContent += event.delta;
311
- const sseEvent = {
312
- id: messageId,
313
- choices: [{
314
- index: 0,
315
- delta: { content: event.delta, role: 'assistant' },
316
- finish_reason: null,
317
- }],
318
- model,
319
- };
320
- res.write(`data: ${JSON.stringify(sseEvent)}\n\n`);
321
- }
322
- }
323
- const result = await stream.result();
324
- const content = streamedContent;
325
- const latencyMs = Date.now() - startTime;
326
- const usage = {
327
- input: result.usage.input,
328
- output: result.usage.output,
329
- reasoning: result.usage.reasoning,
330
- cacheRead: result.usage.cacheRead,
331
- cacheWrite: result.usage.cacheWrite,
332
- totalTokens: result.usage.totalTokens,
333
- };
334
- // Send [DONE] marker
335
- res.write('data: [DONE]\n\n');
336
- res.end();
337
- // 6. Persist assistant message with model (fire-and-forget)
338
- if (content) {
339
- ctx.withPgClient(async (client) => {
340
- await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
341
- (thread_id, owner_id, entity_id, author_role, parts, model)
342
- VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4, $5)`, [
343
- threadId,
344
- userId,
345
- 'assistant',
346
- JSON.stringify([{ type: 'text', text: content }]),
347
- model,
348
- ]);
349
- }).catch((err) => {
350
- log.error('[llm-api] Failed to persist assistant message:', err);
351
- });
352
- }
353
- // 7. Record billing usage (fire-and-forget)
354
- if (billing && usage.totalTokens > 0) {
355
- recordUsage(ctx, billing, entityId, meterSlug, usage.totalTokens, {
356
- input_tokens: usage.input,
357
- output_tokens: usage.output,
358
- cache_read_tokens: usage.cacheRead,
359
- cache_write_tokens: usage.cacheWrite,
360
- model,
361
- latency_ms: latencyMs,
362
- stream: true,
363
- }).catch(() => { });
364
- }
365
- // 8. Inference log (fire-and-forget)
366
- if (inferenceLog) {
367
- logInference(ctx, inferenceLog, {
368
- entityId,
369
- actorId: userId,
370
- model,
371
- provider: 'ollama',
372
- service: 'llm',
373
- operation: 'chat',
374
- inputTokens: usage.input,
375
- outputTokens: usage.output,
376
- totalTokens: usage.totalTokens,
377
- latencyMs,
378
- status: 'ok',
379
- }).catch(() => { });
380
- }
381
- }
382
- catch (streamErr) {
383
- log.error('[llm-api] Streaming error:', streamErr);
384
- const errorEvent = { error: { message: streamErr.message, type: 'stream_error' } };
385
- res.write(`data: ${JSON.stringify(errorEvent)}\n\n`);
386
- res.write('data: [DONE]\n\n');
387
- res.end();
388
- }
389
- }
390
- else {
391
- // ── Non-streaming (batch) via OllamaAdapter ─────────────────────────
392
- const systemMsg = llmMessages.find(m => m.role === 'system');
393
- const nonSystem = llmMessages.filter(m => m.role !== 'system');
394
- const modelDesc = ollama.adapter.createModel(model, {
395
- maxOutputTokens: undefined,
396
- });
397
- const context = {
398
- systemPrompt: systemMsg?.content,
399
- messages: nonSystem.map((m) => ({
400
- role: m.role,
401
- content: m.content,
402
- timestamp: Date.now(),
403
- })),
404
- };
405
- const stream = ollama.adapter.stream(modelDesc, context, {
406
- temperature: body.temperature,
407
- });
408
- const result = await stream.result();
409
- const content = result.content
410
- .filter((block) => block.type === 'text')
411
- .map((block) => block.text)
412
- .join('');
413
- const latencyMs = Date.now() - startTime;
414
- const usage = {
415
- input: result.usage.input,
416
- output: result.usage.output,
417
- reasoning: result.usage.reasoning,
418
- cacheRead: result.usage.cacheRead,
419
- cacheWrite: result.usage.cacheWrite,
420
- totalTokens: result.usage.totalTokens,
421
- };
422
- // Persist assistant message with model
423
- await ctx.withPgClient(async (client) => {
424
- await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
425
- (thread_id, owner_id, entity_id, author_role, parts, model)
426
- VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4, $5)`, [
427
- threadId,
428
- userId,
429
- 'assistant',
430
- JSON.stringify([{ type: 'text', text: content }]),
431
- model,
432
- ]);
433
- });
434
- // Record billing usage
435
- if (billing && usage.totalTokens > 0) {
436
- recordUsage(ctx, billing, entityId, meterSlug, usage.totalTokens, {
437
- input_tokens: usage.input,
438
- output_tokens: usage.output,
439
- cache_read_tokens: usage.cacheRead,
440
- cache_write_tokens: usage.cacheWrite,
441
- model,
442
- latency_ms: latencyMs,
443
- stream: false,
444
- }).catch(() => { });
445
- }
446
- // Inference log
447
- if (inferenceLog) {
448
- logInference(ctx, inferenceLog, {
449
- entityId,
450
- actorId: userId,
451
- model,
452
- provider: 'ollama',
453
- service: 'llm',
454
- operation: 'chat',
455
- inputTokens: usage.input,
456
- outputTokens: usage.output,
457
- totalTokens: usage.totalTokens,
458
- latencyMs,
459
- status: 'ok',
460
- }).catch(() => { });
461
- }
462
- res.json({
463
- id: `msg_${Date.now()}`,
464
- choices: [{
465
- index: 0,
466
- message: { role: 'assistant', content },
467
- finish_reason: 'stop',
468
- }],
469
- model,
470
- usage: {
471
- prompt_tokens: usage.input,
472
- completion_tokens: usage.output,
473
- total_tokens: usage.totalTokens,
474
- },
475
- });
476
- }
477
- }
478
- // ─── Router Factory ─────────────────────────────────────────────────────────
479
- export function createLlmApiRouter() {
480
- const router = Router();
481
- router.use(express.json());
482
- // ── Entity-scoped routes ─────────────────────────────────────────────────
483
- router.post('/v1/orgs/:entity_id/threads', async (req, res) => {
484
- try {
485
- await handleCreateThread(req, res, req.params.entity_id);
486
- }
487
- catch (err) {
488
- log.error('[llm-api] Error creating thread:', err);
489
- if (!res.headersSent) {
490
- res.status(500).json({ error: 'Internal server error' });
491
- }
492
- }
493
- });
494
- router.post('/v1/orgs/:entity_id/threads/:thread_id/messages', async (req, res) => {
495
- try {
496
- await handleSendMessage(req, res, req.params.entity_id);
497
- }
498
- catch (err) {
499
- log.error('[llm-api] Error in messages endpoint:', err);
500
- if (!res.headersSent) {
501
- res.status(500).json({ error: 'Internal server error' });
502
- }
503
- }
504
- });
505
- // ── Global routes (no entity_id — bills to actor_id from JWT) ────────────
506
- router.post('/v1/threads', async (req, res) => {
507
- try {
508
- const userId = req.constructive?.userId;
509
- if (!userId) {
510
- res.status(401).json({ error: 'Authentication required' });
511
- return;
512
- }
513
- await handleCreateThread(req, res, userId);
514
- }
515
- catch (err) {
516
- log.error('[llm-api] Error creating thread:', err);
517
- if (!res.headersSent) {
518
- res.status(500).json({ error: 'Internal server error' });
519
- }
520
- }
521
- });
522
- router.post('/v1/threads/:thread_id/messages', async (req, res) => {
523
- try {
524
- const userId = req.constructive?.userId;
525
- if (!userId) {
526
- res.status(401).json({ error: 'Authentication required' });
527
- return;
528
- }
529
- await handleSendMessage(req, res, userId);
530
- }
531
- catch (err) {
532
- log.error('[llm-api] Error in messages endpoint:', err);
533
- if (!res.headersSent) {
534
- res.status(500).json({ error: 'Internal server error' });
535
- }
536
- }
537
- });
538
- return router;
539
- }