diff --git a/Manifest.toml b/Manifest.toml index 3469f0b..e3545fd 100644 --- a/Manifest.toml +++ b/Manifest.toml @@ -2,7 +2,7 @@ julia_version = "1.12.6" manifest_format = "2.0" -project_hash = "09bd5c43d6ad954d8be233d27fc343ea1149c0b0" +project_hash = "95dc0193a18325ca5b1e37deab8108d1b35915db" [[deps.Accessors]] deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"] @@ -760,11 +760,11 @@ version = "0.7.0" [[deps.SQLLLM]] deps = ["CSV", "DataFrames", "DataStructures", "Dates", "FileIO", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "PrettyPrinting", "Random", "Revise", "StatsBase", "Tables", "URIs", "UUIDs"] -git-tree-sha1 = "93cc1ae6202279a2eb4e1dbfff706c5bc158609d" +git-tree-sha1 = "8f264038c55c5bea069cccbdc057c56e27899c42" repo-rev = "main" repo-url = "https://git.yiem.cc/ton/SQLLLM" uuid = "2ebc79c7-cc10-4a3a-9665-d2e1d61e63d3" -version = "0.2.5" +version = "0.2.6" [[deps.SQLStrings]] git-tree-sha1 = "55de0530689832b1d3d43491ee6b67bd54d3323c" @@ -983,10 +983,10 @@ uuid = "76eceee3-57b5-4d4a-8e66-0e911cebbf60" version = "1.6.1" [[deps.YiemAgent]] -deps = ["CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "SQLLLM", "Serialization", "URIs", "UUIDs"] +deps = ["CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "Serialization", "URIs", "UUIDs"] path = "." uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2" -version = "0.4.0" +version = "0.4.1" [[deps.Zlib_jll]] deps = ["Libdl"] diff --git a/Project.toml b/Project.toml index 11bd808..396faff 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "YiemAgent" uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2" -version = "0.4.1" +version = "0.4.2" authors = ["narawat lamaiin "] [deps] @@ -30,4 +30,4 @@ HTTP = "2.4.0" JSON = "1.6.1" LLMMCTS = "0.1.5" NATS = "0.1.0" -SQLLLM = "0.2.5" +SQLLLM = "0.2.6" diff --git a/src/interface.jl b/src/interface.jl index cc00f16..24f35d7 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -75,7 +75,7 @@ OrderedDict{String, Any} with 4 entries: """ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10 ) where {T<:agent} - println("\nExecuting YiemAgent decisionMaker()") + # lessonDict = copy(JSON.parsefile("lesson.json")) # lesson = @@ -108,9 +108,9 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10 context = """ - + $(GeneralUtils.dict_to_string_html(a.memory["shortmem"])) - + """ @@ -155,18 +155,23 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10 # fall back to normal text because LLM default to natural chat when it didn't use action_call else - responsedict = OrderedDict( - "plan"=> "I will talk to the user", - "action_name"=> "CHAT_BOX", - "action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response - ) + try + responsedict = OrderedDict( + "plan"=> "I will talk to the user", + "action_name"=> "CHAT_BOX", + "action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response + ) + catch e + println("\nERROR YiemAgent decisionMaker(). $e --(not qualify response)-> $response", @__FILE__, ":", @__LINE__, " $(Dates.now())\n") + continue + end end # check whether all answer's key points are in responsedict ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys) if !ispass errornote = errormsg - println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n") + println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)-> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n") continue end @@ -269,9 +274,9 @@ function evaluator(a::T1, timeline, decisiondict, evaluateecontext context = """ - + $timeline - + $evaluateecontext @@ -320,177 +325,10 @@ function evaluator(a::T1, timeline, decisiondict, evaluateecontext println("\nEvaluator() ", @__FILE__, ":", @__LINE__, " $(Dates.now())") pprintln(Dict(responsedict)) - - # # read sessionId - # sessionid = a.id - # # save to filename ./log/decisionlog.txt - # println("saving SQLLLM evaluator() to disk") - # filename = "agent_evaluator_log_$(sessionid[:id]).json" - # filepath = "/appfolder/app/log/$filename" - # # check whether there is a file path exists before writing to it - # if !isfile(filepath) - # decisionlist = [responsedict] - # println("Creating file $filepath") - # open(filepath, "w") do io - # JSON.pretty(io, decisionlist) - # end - # else - # # read the file and append new data - # decisionlist = copy(JSON.parsefile(filepath)) - # push!(decisionlist, responsedict) - # println("Appending new data to file $filepath") - # open(filepath, "w") do io - # JSON.pretty(io, decisionlist) - # end - # end - - return responsedict + return responsedict end error("Evaluator failed to generate an evaluation, Response: \n$response\n<|End of error|>") end -# function evaluator(a::T1, timeline, decisiondict, evaluateecontext -# ) where {T1<:agent} - -# systemmsg = -# """ -# -# - You are a master sommelier of an online wine store. -# -# -# - Under your supervision, a trainee sommelier is engaging with a store customer. Each time the customer speaks, the trainee will assess the situation, determine the next course of action, and pause to await your guidance before proceeding. -# -# -# - Improve a trainee sommelier decision based on the store policy and guidelines while ensuring seamless interactions between the trainee and customers. -# -# -# - trajectory: A conversation between your trainee and the customer that have occurred up until now -# - evaluatee_context: The context that evaluatee use to make a decision -# - evaluatee_decision: The decision made by the evaluatee, consists of the following elements: -# "plan" is the trainee's plan -# "action_name" is the name of the action taken, which can be one of the available tool name. -# "action_input" is the input to the action. -# -# -# - Use only infomation provided by the store policy and guidelines as a bedrocks for your response. -# -# -# - The trainee's plan, action_name, and action_input must be logically consistent -# - The trainee's action_input should be in a proper format as specified by the tools. -# - The trainee's action name and action input should make sense. For example, if the trainee isn't finished talking, he shouldn't use the END_CONVER_GUIDELINE tool. -# -# -# 1) trajectory_evaluation: Analyze the trajectory of a solution to answer the user's original question. -# - Evaluate the correctness of each section and the overall trajectory based on the given question. -# - Provide detailed reasoning and analysis, focusing on the latest thought, action, and observation. -# - Incomplete trajectory are acceptable if the thoughts and actions up to that point are correct, even if the final answer isn't reached. -# - Do not generate additional thoughts or actions. -# 2) decision_evaluation: -# - Examine how the trainee's decisions align with the store's policies and guidelines before proceeding. -# 3) suggestion: Based store policy and guidelines, provide a suggestion for the immediate decision step only. -# 4) approval: Can be "yes" or "no". "no" if the suggestion contradict the trainee's decision; otherwise, it is "yes". - -# -# -# { -# "trajectory_evaluation": "...", -# "decision_evaluation": "...", -# "suggestion": "...", -# "approval": "...", -# } -# - -# Let's begin! -# """ -# requiredKeys = [:trajectory_evaluation, :decision_evaluation, :approval, :suggestion] -# errornote = "N/A" - -# for attempt in 1:10 -# evaluateecontext = replace(evaluateecontext, "" => "") -# evaluateecontext = replace(evaluateecontext, "" => "") - -# context = -# """ -# -# -# $timeline -# -# -# $evaluateecontext -# -# -# {plan: $(decisiondict["plan"]), action_name: $(decisiondict["action_name"]), action_input: $(decisiondict["action_input"])} -# -# P.S. $errornote -# -# """ - -# unformatPrompt = -# [ -# Dict("name" => "system", "text" => systemmsg), -# ] - -# # put in model format -# prompt = GeneralUtils.formatLLMtext(unformatPrompt, a.llmFormatName) -# # add info -# prompt = prompt * context - -# response = a.context.text2textInstructLLM(prompt; senderId=a.id) -# response = GeneralUtils.deFormatLLMtext(response, a.llmFormatName) -# response = GeneralUtils.remove_french_accents(response) -# # response = replace(response, '$'=>"USD") -# think, response = GeneralUtils.extractthink(response) - -# responsedict = nothing -# try -# responsedict = copy(JSON.parsefile(response)) -# catch -# println("\nERROR YiemAgent generatechat() failed to parse response: $response", @__FILE__, ":", @__LINE__, " $(Dates.now())") -# continue -# end - -# # check whether all answer's key points are in responsedict -# ispass, errormsg = checkAgentResponse_JSON(responsedict, requiredKeys) -# if !ispass -# errornote = errormsg -# println("\nERROR YiemAgent evaluator() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n") -# continue -# end - -# # if accepted_as_answer ∉ ["yes", "no"] # [PENDING] add errornote into the prompt -# # error("generated accepted_as_answer has wrong format") -# # end - -# println("\nEvaluator() ", @__FILE__, ":", @__LINE__, " $(Dates.now())") -# pprintln(Dict(responsedict)) - -# # # read sessionId -# # sessionid = a.id -# # # save to filename ./log/decisionlog.txt -# # println("saving SQLLLM evaluator() to disk") -# # filename = "agent_evaluator_log_$(sessionid[:id]).json" -# # filepath = "/appfolder/app/log/$filename" -# # # check whether there is a file path exists before writing to it -# # if !isfile(filepath) -# # decisionlist = [responsedict] -# # println("Creating file $filepath") -# # open(filepath, "w") do io -# # JSON.pretty(io, decisionlist) -# # end -# # else -# # # read the file and append new data -# # decisionlist = copy(JSON.parsefile(filepath)) -# # push!(decisionlist, responsedict) -# # println("Appending new data to file $filepath") -# # open(filepath, "w") do io -# # JSON.pretty(io, decisionlist) -# # end -# # end - -# return responsedict -# end -# error("Evaluator failed to generate an evaluation, Response: \n$response\n<|End of error|>") -# end - """ Chat with llm. @@ -543,8 +381,8 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj # thinking loop until AI wants to communicate with the user loopcount = 0 while true - @info "YiemAgent conversation() 2-0 count $loopcount" @__LINE__ loopcount += 1 + @info "YiemAgent conversation() 2-0 count $loopcount" @__LINE__ thoughtdict, _ = think(a) if thoughtdict["action_name"] ∈ ["CHAT_BOX"] @info "YiemAgent conversation() 2-1" @__LINE__ @@ -566,45 +404,6 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj end end -# function conversation(a::Union{companion, virtualcustomer}, userinput::Dict; -# converPartnerName::Union{String, Nothing}=nothing, -# maximumMsg=50) - -# chatresponse = nothing - -# if userinput["text"] == "newtopic" -# clearhistory(a) -# return "Okay. What shall we talk about?" -# else -# # add usermsg to a.chathistory -# addNewMessage(a, "user", userinput["text"]; maximumMsg=maximumMsg) - -# # add user activity to events memory -# push!(a.memory["events"], -# eventdict(; -# event_description="the user talks to the assistant.", -# timestamp=Dates.now(), -# subject="user", -# action_name="CHAT_BOX", -# action_input=userinput["text"], -# ) -# ) -# chatresponse = generatechat(a; converPartnerName=converPartnerName, recentEventNum=20) - -# addNewMessage(a, "assistant", chatresponse; maximumMsg=maximumMsg) - -# push!(a.memory["events"], -# eventdict(; -# event_description="the assistant talks to the user.", -# timestamp=Dates.now(), -# subject="assistant", -# action_name="CHAT_BOX", -# action_input=chatresponse, -# ) -# ) -# return chatresponse -# end -# end """ # Arguments @@ -831,9 +630,9 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10 context = """ - + $(GeneralUtils.dict_to_string_html(a.memory["shortmem"])) - + """ @@ -880,11 +679,16 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10 # fall back to normal text because LLM default to natural chat when it didn't use action_call else - responsedict = OrderedDict( - "plan"=> "I will talk to the user", - "action_name"=> "CHAT_BOX", - "action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response - ) + try + responsedict = OrderedDict( + "plan"=> "I will talk to the user", + "action_name"=> "CHAT_BOX", + "action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response + ) + catch e + println("\nERROR YiemAgent decisionMaker(). $e --(not qualify response)-> $response", @__FILE__, ":", @__LINE__, " $(Dates.now())\n") + continue + end end # check whether all answer's key points are in responsedict @@ -908,183 +712,6 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10 end error("YiemAgent generatechat() failed to generate a thought ", response) end -# function generatechat(a::T; recentevents::Integer=20, maxattempt=10 -# )::String where {T<:agent} - -# # lessonDict = copy(JSON.parsefile("lesson.json")) - -# # lesson = -# # if isempty(lessonDict) -# # "" -# # else -# # lessons = Dict{String, Any}() -# # for (k, v) in lessonDict -# # lessons[k] = lessonDict[k][:lesson] -# # end - -# # """ -# # You have attempted to help the user before and failed, either because your reasoning for the -# # recommendation was incorrect or your response did not exactly match the user expectation. -# # The following lesson(s) give a plan to avoid failing to help the user in the same way you -# # did previously. Use them to improve your strategy to help the user. - -# # Here are some lessons in JSON format: -# # $(JSON.json(lessons)) - -# # When providing the thought and action for the current trial, that into account these failed -# # trajectories and make sure not to repeat the same mistakes and incorrect answers. -# # """ -# # end - -# # recentevents_ind = GeneralUtils.recentElementsIndex( -# # length(a.memory["events"]), recentevents; includelatest=true) - -# systemmsg = -# """ -# -# - Generally speaking, the store inventory has some wines from France, the United States, Australia, Spain, and Italy, but you won't know exactly until you check your inventory. -# - If you found wines in the store's database, they are in stock. -# - You can only recommend wines that are currently in our inventory -# - Before searching the database for wine, ensure you have at least the following information: 1) budget, 2) wine type, and 3) occasion. Additional details are always helpful. If the user is unsure, provide relevant information and gather insights to make reasonable inferences. -# - Ask the user one question at a time. -# - Do not ask the user about wine's flavor e.g. floral, citrusy, nutty or some thing similar as these terms cannot be used to search the database. -# - Once the user has selected their wine, if you haven't already, ask the user whether they need any further assistance. Do not offer any additional services. -# - Only end the conversation when the user explicitly intends to do so. When ending, ensure a polite farewell and an invitation to return in the future. -# - Spicy foods should be paired only with light red wines. -# - We do not sell organic, sustainable, gluten-free, and sulfite-free wine. Inform the user immediately if they are looking for these types of wines. Do not sell our wines as such. -# - Gift box, gift card, and custom messages are available. Inform the user to contact our sales team. -# -# -# - Greeting the customer warmly by ask them how could you help. Do not ask any other questions during this greeting. -# - Customer may provide images for you to look up. -# - Encourage the customer to explore different options and try new things. -# - If you are unable to locate the desired item in the database after 2 attempts, it may not be available in your inventory. In such cases, inform the user that the item is unavailable and suggest an alternative instead. -# - Your store carries only wine. -# - Vintage 0 means non-vintage. -# - Start searching the database as broadly as possible within the given information boundary to maximize the chances of finding. Avoid unnecessary parameters unless specified by the user. Refine the search subsequently. -# -# -# You are continuing the conversation with the user. -# -# -# Your name is $(a.name). You are a helpful sommelier for website-based $(a.retailername)'s wine store. You are working under your mentor supervision. -# -# -# 1) Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences. -# 2) Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences. -# -# -# 1) According to the store's policy and guidelines, make an informed decision about what you need to do to achieve the objective -# 2) Keep the conversation with the customer going smoothly -# -# -# 1) Requesting the user to place an order, make a purchase, or confirm the order. These are the job of our sales team at the store. -# 2) Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store. -# 3) Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store. -# -# -# Dialogue you want to chat with the user -# -# -# "CHAT_BOX": "..." -# -# """ - -# system_msg = Dict( -# "role" => "system", -# "content" => [ -# Dict("type" => "text", "text" => systemmsg), -# ] -# ) - -# chathistory = deepcopy(a.chathistory[2:end]) -# pushfirst!(chathistory, system_msg) - -# requiredKeys = ["CHAT_BOX"] -# context = -# """ -# -# -# $(GeneralUtils.dict_to_string_html(a.memory["shortmem"])) -# -# -# """ - -# # add context to text of the latest message (in the front). -# # use for loop because in openai format, each msg may contain both text and image. -# for d in chathistory[end]["content"] -# if d["type"] == "text" -# d["text"] = context * d["text"] -# break -# end -# end -# errornote = "N/A" -# response = nothing # placeholder for show when error msg show up - -# for attempt in 1:maxattempt -# if attempt > 1 -# println("\nYiemAgent generatechat() attempt $attempt/$maxattempt ", @__FILE__, ":", @__LINE__, " $(Dates.now())") -# end - -# msg = Dict( -# "model" => "gemma-4-E4B-it-UD-Q4_K_XL", -# "messages" => chathistory, -# "temperature" => 0.7 -# ) -# @info "YiemAgent generatechat() 2-2 attempt $attempt " @__LINE__ -# response = a.context.text2textInstructLLM(a.id, msg) -# @info "YiemAgent generatechat() 2-3 attempt $attempt " @__LINE__ -# response = GeneralUtils.clean_json_response(response) - -# response = GeneralUtils.remove_french_accents(response) -# think, response = GeneralUtils.extractthink(response) -# response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to -# response = strip(response) -# @show response -# responsedict = nothing -# if occursin("CHAT_BOX", response) -# @info "YiemAgent generatechat() 2-4 attempt $attempt " @__LINE__ -# try -# @info "YiemAgent generatechat() 2-5 attempt $attempt " @__LINE__ -# _responsedict = JSON.parse(response) -# responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys) -# catch -# @info "YiemAgent generatechat() 2-6 attempt $attempt " @__LINE__ -# println("\nERROR YiemAgent generatechat() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())") -# continue -# end -# # fall back to normal text because LLM default to natural chat when it didn't use action_call -# else -# @info "YiemAgent generatechat() 2-7 attempt $attempt " @__LINE__ -# responsedict = OrderedDict( -# "CHAT_BOX"=> response -# ) -# end - -# if length(keys(responsedict)) > length(requiredKeys) -# @info "YiemAgent generatechat() 2-7-1 attempt $attempt " @__LINE__ -# continue -# end - -# @info "YiemAgent generatechat() 2-8 attempt $attempt " @__LINE__ -# # check whether all answer's key points are in responsedict -# ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys) -# if !ispass -# @info "YiemAgent generatechat() 2-9 attempt $attempt " @__LINE__ -# errornote = errormsg -# println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict ", @__FILE__, ":", @__LINE__, " $(Dates.now())\n") -# continue -# end - -# @info "YiemAgent generatechat() 2-12 attempt $attempt " @__LINE__ -# # println("\nYiemAgent generatechat() ", @__FILE__, ":", @__LINE__, " $(Dates.now())") -# # pprintln(responsedict) - -# return responsedict["CHAT_BOX"] -# end -# @info "YiemAgent generatechat() 2-13 attempt $attempt " @__LINE__ -# error("YiemAgent generatechat() failed to generate a thought ", response) -# end function generatequestion(a, text2textInstructLLM::Function, timeline)::String