4
|
1 local Luan = require "luan:Luan.luan"
|
|
2 local error = Luan.error
|
|
3 local ipairs = Luan.ipairs or error()
|
|
4 local Number = require "luan:Number.luan"
|
|
5 local long = Number.long or error()
|
|
6 local Time = require "luan:Time.luan"
|
|
7 local time_now = Time.now or error()
|
|
8 local Html = require "luan:Html.luan"
|
|
9 local html_encode = Html.encode or error()
|
|
10 local Db = require "site:/lib/Db.luan"
|
5
|
11 local run_in_transaction = Db.run_in_transaction or error()
|
|
12 local Ai = require "site:/lib/ai/Ai.luan"
|
4
|
13
|
|
14
|
|
15 local Chat = {}
|
|
16
|
|
17 local function from_doc(doc)
|
|
18 doc.type == "chat" or error "wrong type"
|
|
19 return Chat.new {
|
|
20 id = doc.id
|
|
21 user_id = doc.chat_user_id
|
|
22 updated = doc.chat_updated
|
|
23 name = doc.name
|
5
|
24 ai_name = doc.ai_name
|
|
25 ai_thread = doc.ai_thread
|
4
|
26 }
|
|
27 end
|
|
28
|
|
29 local function to_doc(chat)
|
|
30 return {
|
|
31 type = "chat"
|
|
32 id = chat.id
|
|
33 chat_user_id = long(chat.user_id)
|
|
34 chat_updated = long(chat.updated)
|
|
35 name = chat.name or error()
|
5
|
36 ai_name = chat.ai_name or error()
|
|
37 ai_thread = chat.ai_thread -- or error()
|
4
|
38 }
|
|
39 end
|
|
40
|
|
41 function Chat.new(chat)
|
|
42 chat.updated = chat.updated or time_now()
|
6
|
43 chat.ai_name = chat.ai_name or "claude"
|
5
|
44 chat.ai = Ai[chat.ai_name]["Chat.luan"] or error()
|
4
|
45
|
|
46 function chat.save()
|
|
47 local doc = to_doc(chat)
|
|
48 Db.save(doc)
|
|
49 chat.id = doc.id
|
|
50 end
|
|
51
|
5
|
52 function chat.reload()
|
|
53 return Chat.get_by_id(chat.id) or error(chat.id)
|
|
54 end
|
|
55
|
4
|
56 function chat.delete()
|
|
57 Db.delete("id:"..chat.id)
|
|
58 end
|
|
59
|
|
60 function chat.name_html()
|
|
61 return html_encode(chat.name)
|
|
62 end
|
|
63
|
9
|
64 function chat.output_system_prompt()
|
|
65 chat.ai.output_system_prompt(chat.ai_thread)
|
|
66 end
|
|
67
|
5
|
68 function chat.output_messages_html()
|
|
69 chat.ai.output_messages_html(chat.ai_thread)
|
|
70 end
|
|
71
|
|
72 function chat.ask(input)
|
13
|
73 local old_thread = chat.ai_thread
|
|
74 local ai_thread = chat.ai.ask(old_thread,input)
|
|
75 run_in_transaction( function()
|
|
76 chat = chat.reload()
|
|
77 chat.ai_thread = ai_thread
|
|
78 chat.save()
|
|
79 end )
|
|
80 return `chat.ai.output_messages_html(ai_thread,old_thread)`
|
5
|
81 end
|
|
82
|
4
|
83 return chat
|
|
84 end
|
|
85
|
|
86 function Chat.search(query,sort,rows)
|
|
87 rows = rows or 1000000
|
|
88 local chats = {}
|
|
89 local docs = Db.search(query,1,rows,{sort=sort})
|
|
90 for _, doc in ipairs(docs) do
|
|
91 chats[#chats+1] = from_doc(doc)
|
|
92 end
|
|
93 return chats
|
|
94 end
|
|
95
|
|
96 function Chat.get_by_id(id)
|
|
97 local doc = Db.get_document("id:"..id)
|
|
98 return doc and doc.type=="chat" and from_doc(doc) or nil
|
|
99 end
|
|
100
|
|
101 return Chat
|