summaryrefslogtreecommitdiff
path: root/backend/api/src/chat.zig
blob: 1200562c865f2e52ff5d1c2ddc46a7f13fc1620a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
const z = @import( "std" );
const zap = @import( "zap" );
const api = @import( "api.zig" );
const req = @import( "req.zig" );
const net = @import( "net-util.zig" );
const model = @import( "model.zig" );

const u = struct {
  usingnamespace @import( "util.zig" );
  usingnamespace @import( "userdefs.zig" );
  usingnamespace @import( "user.zig" );
  usingnamespace @import( "userdata.zig" );
};

// --------------------------------------------------------------------------------------------------------
// some docs because this is becoming a little complex:
// the api is mostly a proxy between the user and model instances
// user sends ChatReq to api, api forwards a ModelInstanceChatReq to instance after verifying user acc etc
// instance replies with a ChatStream defined in typescript [api-defs.ts](file://../instance/api-defs.ts#L58)
// api simply forwards this ChatStream to the client, only parsing it to check for a title.
// if a title is present, it's updated in the user db entry.
//
// the situation looks similar for the generate endpoint except there are no title checks.
// the msg is simply proxied to the user.
//
// legend:
// (source) - message source
// [type] - message type
// {target} - message target
// @/ - route
//
// chat route:
// (user) [ChatReq] req @/chat --> (api) [ModelInstanceChatReq] req @/chat --> {instance}
// (instance) [ChatStream] res --> (api) proxy --> {user}
//
// generate route:
// (user) [GenerateReq] req @/generate --> (api) [ModelInstanceGenerateReq] req @/generate --> {instance}
// (instance) [undefined in zig] res --> (api) proxy --> {user}
// --------------------------------------------------------------------------------------------------------

const ArrayList = z.ArrayList;
const ErrRes = net.ErrorResponse;
const OkRes = net.OkResponse;
const Request = zap.Request;

const memeql = z.mem.eql;

const alloc = u.alloc;

pub const title_gen_model = "qwen2.5-1.5b";
pub const routes = .{
  .@"chat" = chat,
  .@"get-chat" = getChat,
  .@"generate" = generate,
  .@"create-chat" = createChat,
  .@"delete-chat" = deleteChat,
  .@"get-chat-name" = getChatName
};

const ToolCall = struct {
  name: []const u8,
  parameters: struct {
    pub const @"getty.db" = u.@"json.ignore.unknown";
  }// processed either by instance or client, we dont care abt the contents
};

const MsgFile = struct {
  name: []const u8,
  type: []const u8,
  content: []const u8
};

const Msg = struct {
  content: []const u8,
  role: []const u8,
  timestamp: []const u8,
  toolCall: ?ToolCall = null,
  images: ?[][]const u8 = null,
  files: ?[]MsgFile = null,

  pub const @"getty.db" = u.@"json.ignore.unknown";
};

const ClientOptions = struct {
  seed: ?u32,
  temperature: ?f32,

  pub const @"getty.db" = u.@"json.ignore.unknown";
};

const ChatReq = struct {
  model: []const u8,
  messages: []Msg,
  system: ?[]const u8,
  chatfile: ?[]const u8 = null,
  options: ?ClientOptions = null,
  generateTitle: ?bool = null,

  pub const @"getty.db" = u.@"json.ignore.unknown";
};

const ChatStream = struct {
  status: []const u8,
  done: bool,
  title: ?[]const u8,

  pub const @"getty.db" = u.@"json.ignore.unknown";
};

const GenerateReq = struct {
  model: []const u8,
  prompt: []const u8,
  suffix: ?[]const u8 = "",
  options: ?ClientOptions = null,

  pub const @"getty.db" = u.@"json.ignore.unknown";
};

const GetChatReq = struct {
  chatId: []const u8,

  pub const @"getty.db" = u.@"json.ignore.unknown";
};

const ChatMsgContext = struct {
  uuid: []const u8,
  chatfile: []const u8
};


// theres no reason for these to be split up other than the frontend being suck
// todo later: fix
const ModelInstanceChatOptions = struct {
  system: ?struct {
    model: ?[]const u8 = null,
    user: ?[]const u8 = null,
  },
  model: model.Model,
  uuid: []const u8,
  chatfile: ?[]const u8 = null,
  generateTitle: ?bool = null,
};

const ModelInstanceChatReq = struct {
  messages: []Msg,
  options: ModelInstanceChatOptions,
};

const ModelInstanceGenerateOptions = struct {
  model: model.Model,
  system: ?struct {
    model: ?[]const u8 = null,
    user: ?[]const u8 = null,
  } = null,
};

const ModelInstanceGenerateReq = struct {
  options: ModelInstanceGenerateOptions,
  prompt: []const u8,
  suffix: ?[]const u8,
};

///forwards the instance error to client if reported
///sends a 500 otherwise
fn handleInstanceError( r: Request, q: *const req.Result ) void {
  if( q.body ) |body| {
    const msg = u.jsonParse( struct { status: []const u8, msg: []const u8 }, body ) catch null;
    if( msg != null ) {
      z.debug.print( "res err status [{any}]: {s}\n", .{ q.status, body } );
      r.sendChunk( body ) catch {};
    }
  } else {
    net.sendJsonChunk( r, .internal_server_error, ErrRes{ .msg = "could not contact server" } );
  }
}


// -------------------------------------------------------------------------------------------
// chat --------------------------------------------------------------------------------------

fn chatChunkFn( chunk: []const u8, r: Request ) void {
  const ctx = r.getUserContext( ChatMsgContext );
  var parts = z.mem.split( u8, chunk, "\n" );
  var part: ?[]const u8 = parts.first();
  while( part ) |p| : (part = parts.next()) {
    if( p.len == 0 )
      continue;

    var buf = alloc.alloc( u8, p.len + 1 ) catch return;
    defer alloc.free( buf );
    @memcpy( buf[0..p.len], p );
    buf[p.len] = '\n';

    if( ctx ) |_ctx| {
      if( u.jsonParse( ChatStream, buf ) catch null ) |parsed| {
        if( parsed.v.done and parsed.v.title != null ) {
          setChatTitle( _ctx.uuid, _ctx.chatfile, parsed.v.title.? );
        }

        parsed.deinit();
      }
    }

    r.sendChunk( buf ) catch |e| {
      z.debug.print( "error sending chunk: {any}\n", .{e} );
    };
  }
}

fn startChat( r: Request, address: []const u8, params: ChatReq, uuid: []const u8, user: *u.UserEntry ) void {
  const _model = model.getModelByDisplayName( params.model ) catch {
    return net.sendJsonChunk( r, .bad_request, ErrRes{ .msg = "invalid model" } );
  };

  if( !model.canBeUsedByUser( _model.*, user ) ) {
    return net.sendJson( r, .unauthorized, ErrRes{ .msg = "user is not authorized to use this model" } );
  }

  const chat_req = ModelInstanceChatReq{
    .messages = params.messages,
    .options = ModelInstanceChatOptions{
      .model = _model.*,
      .system = .{
        .model = _model.system,
        .user = params.system,
      },
      .uuid = uuid,
      .chatfile = params.chatfile,
      .generateTitle = params.generateTitle
    },
  };

  if( params.chatfile ) |chatfile| {
    var ctx = ChatMsgContext{
      .uuid = uuid,
      .chatfile = chatfile
    };
    r.setUserContext( &ctx );
  }

  const params_str = u.jsonStringify( chat_req ) catch {
    return net.sendJson( r, .bad_request, ErrRes{ .msg = "invalid request format" } );
  }; defer alloc.free( params_str );

  r.setChunked() catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "internal server error" } );
  };
  const q = req.sendWithData( Request, .{
    .method = .POST,
    .url = address,
    .headers = &[_]z.http.Header{ .{ .name = "Content-Type", .value = "application/json" } },
    .body = params_str,
    .chunk_fn = chatChunkFn,
    .chunk_data = r
  }, alloc );
  defer q.deinit();

  if( !q.ok )
    handleInstanceError( r, &q );
  r.endStream() catch |e| {
    return z.debug.print( "error closing connection {any} {any}", .{e, @errorReturnTrace() } );
  };
}

///route @/chat
fn chat( r: Request ) void {
  if( net.handleInvalidPostReq( r ) ) return;
  u.checkDbOnThread() catch return;

  const uuid = u.uuidFromApiOrAuthToken( r ) catch return;
  defer alloc.free( uuid );

  const params = u.jsonParse( ChatReq, r.body.? ) catch |e| {
    z.debug.print( "err: {any}\n", .{e} );
    return net.sendJson( r, .bad_request, ErrRes{ .msg = "invalid request format" } );
  }; defer params.deinit();

  var user = u.getEntry( uuid ) catch {
    return net.sendJson( r, .unauthorized, ErrRes{ .msg = "user not found" } );
  }; defer user.db_entry.?.deinit();

  u.checkSubscription( &user ) catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "internal server error" } );
  };

  var prefs = u.getSettings( uuid ) catch {
    return net.sendJson( r, .unauthorized, ErrRes{ .msg = "error getting user data" } );
  }; defer prefs.db_entry.?.deinit();

  if( params.v.chatfile != null and !u.hasChat( &prefs, params.v.chatfile.? ) )
    return net.sendJson( r, .bad_request, ErrRes{ .msg = "specified chat file does not exist" } );

  const serv = api.getAvailableServer( params.v.model, alloc ) orelse {
    return net.sendJson( r, .service_unavailable, ErrRes{ .msg = "no server available" } );
  }; defer alloc.free( serv );

  api.markServerAsBusy( serv ) catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "internal server error" } );
  };

  const address = z.fmt.allocPrintZ( alloc, "{s}/chat", .{serv} ) catch return;
  defer alloc.free( address );
  startChat( r, address, params.v, uuid, &user );
}

fn setChatTitle( uuid: []const u8, chatfile: []const u8, title: []const u8 ) void {
  var prefs = u.getSettings( uuid ) catch {
    return z.debug.print( "setChatTitle called for invalid uuid: {s}\n", .{uuid} );
  }; defer prefs.db_entry.?.deinit();

  if( prefs.chat_files == null and prefs.chat_files.?.files == null )
    return;

  const files = prefs.chat_files.?.files.?;
  for( files ) |*f| {
    if( memeql( u8, f.id, chatfile ) ) {
      f.name = title;
      break;
    }
  }
  prefs.chat_files = u.ChatFiles{ .files = files };
  u.updateSettings( &prefs ) catch {};
}

// -------------------------------------------------------------------------------------------
// generate ----------------------------------------------------------------------------------

fn generateChunkFn( chunk: []const u8, r: Request ) void {
  var parts = z.mem.split( u8, chunk, "\n" );
  var part: ?[]const u8 = parts.first();
  while( part ) |p| : (part = parts.next()) {
    if( p.len == 0 )
      continue;

    var buf = alloc.alloc( u8, p.len + 1 ) catch return;
    defer alloc.free( buf );
    @memcpy( buf[0..p.len], p );
    buf[p.len] = '\n';

    r.sendChunk( buf ) catch |e| {
      z.debug.print( "error sending chunk: {any}\n", .{e} );
    };
  }
}

fn startGenerate( r: Request, address: []const u8, params: GenerateReq, user: *u.UserEntry ) void {
  const _model = model.getModelByDisplayName( params.model ) catch {
    const json = u.jsonStringify( ErrRes{ .msg = "invalid model" } ) catch "";
    defer alloc.free( json );
    return r.sendChunk( json ) catch {};
  };

  if( !model.canBeUsedByUser( _model.*, user ) ) {
    return net.sendJson( r, .unauthorized, ErrRes{ .msg = "user is not authorized to use this model" } );
  }

  const gen_req = ModelInstanceGenerateReq{
    .options = ModelInstanceGenerateOptions{
      .model = _model.*,
    },
    .prompt = params.prompt,
    .suffix = params.suffix,
  };

  const params_str = u.jsonStringify( gen_req ) catch {
    return net.sendJsonChunk( r, .bad_request, ErrRes{ .msg = "invalid request format" } );
  }; defer alloc.free( params_str );

  r.setChunked() catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "internal server error" } );
  };
  const q = req.sendWithData( Request, .{
    .method = .POST,
    .url = address,
    .headers = &[_]z.http.Header{ .{ .name = "Content-Type", .value = "application/json" } },
    .body = params_str,
    .chunk_fn = generateChunkFn,
    .chunk_data = r
  }, alloc );
  defer q.deinit();

  if( !q.ok )
    handleInstanceError( r, &q );
  r.endStream() catch |e| {
    return z.debug.print( "error closing connection {any} {any}", .{e, @errorReturnTrace() } );
  };
}

///route @/generate
fn generate( r: Request ) void {
  if( net.handleInvalidPostReq( r ) ) return;
  u.checkDbOnThread() catch return;

  const uuid = u.uuidFromApiOrAuthToken( r ) catch return;
  defer alloc.free( uuid );

  const params = u.jsonParse( GenerateReq, r.body.? ) catch |e| {
    z.debug.print( "error parsing request {any}", .{e} );
    return net.sendJson( r, .bad_request, ErrRes{ .msg = "invalid request format" } );
  }; defer params.deinit();

  var user = u.getEntry( uuid ) catch {
    return net.sendJson( r, .not_found, ErrRes{ .msg = "user not found" } );
  }; defer user.db_entry.?.deinit();

  u.checkSubscription( &user ) catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "internal server error" } );
  };

  const serv = api.getAvailableServer( params.v.model, alloc ) orelse {
    return net.sendJson( r, .service_unavailable, ErrRes{ .msg = "no server available" } );
  }; defer alloc.free( serv );

  api.markServerAsBusy( serv ) catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "internal server error" } );
  };

  const address = z.fmt.allocPrintZ( alloc, "{s}/generate", .{serv} ) catch return;
  defer alloc.free( address );
  startGenerate( r, address, params.v, &user );
}



// -------------------------------------------------------------------------------------------
// chat management (create-chat, delete-chat, get-chat, get-chat-name) -----------------------

///route @/create-chat
fn createChat( r: Request ) void {
  if( net.handleInvalidPostReq( r ) ) return;
  u.checkDbOnThread() catch return;

  const uuid = u.uuidFromApiOrAuthToken( r ) catch return;
  defer alloc.free( uuid );

  var userdata = u.getSettings( uuid ) catch {
    return net.sendJson( r, .not_found, ErrRes{ .msg = "user not found" } );
  }; defer userdata.db_entry.?.deinit();

  var chats = userdata.chat_files;
  if( chats == null )
    chats = u.ChatFiles{ .files = &[_]u.ChatEntry{} };

  const files = chats.?.files;
  var list = ArrayList( u.ChatEntry ).init( alloc );
  defer list.deinit();

  if( files != null and files.?.len > 0 )
    list.appendSlice( files.? ) catch {};

  const chat_uuid = net.uuidv4();
  var buf = [_]u8{ 0 } ** 64;
  const dup = z.fmt.bufPrintZ( &buf, "{s}", .{chat_uuid} ) catch &chat_uuid;
  const new_entry = u.ChatEntry{
    .id = dup,
    .name = "new chat"
  };

  list.append( new_entry ) catch {};
  chats.?.files = list.items;
  userdata.chat_files = chats;
  u.updateSettings( &userdata ) catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "internal server error" } );
  };

  return net.sendJson( r, .ok, OkRes( .{ .chatId = dup } ) );
}

///route @/get-chat
fn getChat( r: Request ) void {
  if( net.handleInvalidPostReq( r ) ) return;
  u.checkDbOnThread() catch return;

  const uuid = u.uuidFromApiOrAuthToken( r ) catch return;
  defer alloc.free( uuid );

  const params = u.jsonParse( GetChatReq, r.body.? ) catch {
    return net.sendJson( r, .bad_request, ErrRes{ .msg = "invalid request format" } );
  }; defer params.deinit();

  const userdata = u.getSettings( uuid ) catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "user not found" } );
  }; defer userdata.db_entry.?.deinit();

  const chats = userdata.chat_files;
  if( chats == null or chats.?.files == null )
    return net.sendJson( r, .not_found, ErrRes{ .msg = "chat not found" } );

  for( chats.?.files.? ) |file| {
    const id = file.id;
    if( memeql( u8, id, params.v.chatId ) ) {
      var pathbuf: [256]u8 = undefined;
      const slice = z.fmt.bufPrint( &pathbuf, "../data/chats/{s}.json", .{id} ) catch "";
      const contents = u.readFileCrypto( slice ) catch {
        return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "error reading file" } );
      }; defer alloc.free( contents );

      return net.sendJson( r, .ok, OkRes( .{ .name = file.name, .contents = contents } ) );
    }
  }

  return net.sendJson( r, .not_found, ErrRes{ .msg = "chat not found" } );
}

///route @/delete-chat
fn deleteChat( r: Request ) void {
  if( net.handleInvalidPostReq( r ) ) return;
  u.checkDbOnThread() catch return;

  const uuid = u.uuidFromApiOrAuthToken( r ) catch return;
  defer alloc.free( uuid );

  const params = u.jsonParse( GetChatReq, r.body.? ) catch {
    return net.sendJson( r, .bad_request, ErrRes{ .msg = "invalid request format" } );
  }; defer params.deinit();

  var userdata = u.getSettings( uuid ) catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "user not found" } );
  }; defer userdata.db_entry.?.deinit();

  const chats = userdata.chat_files;
  if( chats == null or chats.?.files == null )
    return net.sendJson( r, .not_found, ErrRes{ .msg = "chat not found" } );

  var updated_list = ArrayList( u.ChatEntry ).init( alloc );
  defer updated_list.deinit();

  var found = false;
  for( chats.?.files.? ) |file| {
    const id = file.id;
    if( memeql( u8, id, params.v.chatId ) ) {
      var pathbuf: [256]u8 = undefined;
      const slice = z.fmt.bufPrint( &pathbuf, "../data/chats/{s}.json", .{id} ) catch "";
      if( !u.fileExists( slice ) ) {
        found = true; continue;
      }

      u.deleteFile( slice ) catch continue;
      found = true;
    }
    else {
      updated_list.append( file ) catch {};
    }
  }

  if( found ) {
    userdata.chat_files.?.files = updated_list.items;
    u.updateSettings( &userdata ) catch {
      return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "error updating user data" } );
    };

    return net.sendJson( r, .ok, OkRes( .{} ) );
  }

  return net.sendJson( r, .not_found, ErrRes{ .msg = "chat not found" } );
}

///route @/get-chat-name
fn getChatName( r: Request ) void {
  if( net.handleInvalidPostReq( r ) ) return;
  u.checkDbOnThread() catch return;

  const uuid = u.uuidFromApiOrAuthToken( r ) catch return;
  defer alloc.free( uuid );

  const params = u.jsonParse( GetChatReq, r.body.? ) catch {
    return net.sendJson( r, .bad_request, ErrRes{ .msg = "invalid request format" } );
  }; defer params.deinit();

  const userdata = u.getSettings( uuid ) catch {
    return net.sendJson( r, .internal_server_error, ErrRes{ .msg = "user not found" } );
  }; defer userdata.db_entry.?.deinit();

  const chats = userdata.chat_files;
  if( chats == null or chats.?.files == null )
    return net.sendJson( r, .not_found, ErrRes{ .msg = "chat not found" } );

  for( chats.?.files.? ) |file| {
    const id = file.id;
    if( memeql( u8, id, params.v.chatId ) ) {
      return net.sendJson( r, .ok, OkRes( .{ .name = file.name } ) );
    }
  }

  return net.sendJson( r, .not_found, ErrRes{ .msg = "file not found" } );
}