Mercurial Hosting > lang
changeset 38:238a91f224b1
add get_thread
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sat, 09 Aug 2025 09:31:28 +0900 |
parents | d72b1dff01c9 |
children | df72d5d5d9dc |
files | src/lib/ai/claude/Ai_chat.luan |
diffstat | 1 files changed, 58 insertions(+), 3 deletions(-) [+] |
line wrap: on
line diff
diff -r d72b1dff01c9 -r 238a91f224b1 src/lib/ai/claude/Ai_chat.luan --- a/src/lib/ai/claude/Ai_chat.luan Sat Aug 09 05:57:34 2025 +0900 +++ b/src/lib/ai/claude/Ai_chat.luan Sat Aug 09 09:31:28 2025 +0900 @@ -1,6 +1,7 @@ local Luan = require "luan:Luan.luan" local error = Luan.error local ipairs = Luan.ipairs or error() +local pairs = Luan.pairs or error() local type = Luan.type or error() local String = require "luan:String.luan" local starts_with = String.starts_with or error() @@ -76,10 +77,40 @@ end_for end +local functions = { + get_thread = { + tool = { + cname = "get_thread" + description = "Get the contents of a thread/chat with Claude on this website. The contents will be JSON in the format of the Claude API." + input_schema = { + type = "object" + properties = { + thread_id = { + description = "The ID of the thread" + type = "string" + } + } + } + } + fn = function(input) + local Chat = require "site:/lib/Chat.luan" + local thread_id = input.thread_id or error() + local chat = Chat.get_by_id(thread_id) or error + return chat.ai_thread or error() + end + } +} +local tools = {nil} +for name, f in pairs(functions) do + f.name = name + f.tool.name = name + tools[#tools+1] = f.tool +end function Ai_chat.init(system_prompt) local thread = { system = system_prompt + tools = tools messages = {nil} } return json_string(thread) @@ -90,12 +121,11 @@ return #thread.messages > 0 end -function Ai_chat.ask(thread,input) - thread = json_parse(thread) +local function ask(thread,content) local messages = thread.messages or error messages[#messages+1] = { role = "user" - content = input + content = content } --[=[ messages[#messages+1] = { @@ -120,6 +150,31 @@ role = "assistant" content = content } + local stop_reason = result.stop_reason or error() + if stop_reason == "end_turn" then + -- ok + elseif stop_reason == "tool_use" then + local response = {nil} + for _, part in ipairs(content) do + if part.type == "tool_use" then + local f = functions[part.name] or error() + local input = part.input or error() + response[#response+1] = { + type = "tool_result" + tool_use_id = part.id or error() + content = f.fn(input) + } + end + end + ask(thread,response) + else + error(stop_reason) + end +end + +function Ai_chat.ask(thread,input) + thread = json_parse(thread) + ask(thread,input) return json_string(thread) end