diff --git a/Manifest.toml b/Manifest.toml
index c190222..3469f0b 100644
--- a/Manifest.toml
+++ b/Manifest.toml
@@ -406,7 +406,7 @@ version = "1.21.3+0"
[[deps.LLMMCTS]]
deps = ["GeneralUtils", "JSON", "PrettyPrinting"]
-git-tree-sha1 = "6b4f123b03c0fcce5b21c0dbcb947e8dd23f333a"
+git-tree-sha1 = "3dff98131dfa79be8c9bd84fc51cb0ba1832c472"
repo-rev = "main"
repo-url = "https://git.yiem.cc/ton/LLMMCTS"
uuid = "d76c5a4d-449e-4835-8cc4-dd86ec44f241"
@@ -760,7 +760,7 @@ 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 = "c18ef75ef5d43b256be9624d6e9c1b10a91d5b64"
+git-tree-sha1 = "93cc1ae6202279a2eb4e1dbfff706c5bc158609d"
repo-rev = "main"
repo-url = "https://git.yiem.cc/ton/SQLLLM"
uuid = "2ebc79c7-cc10-4a3a-9665-d2e1d61e63d3"
@@ -983,7 +983,7 @@ uuid = "76eceee3-57b5-4d4a-8e66-0e911cebbf60"
version = "1.6.1"
[[deps.YiemAgent]]
-deps = ["CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "Serialization", "URIs", "UUIDs"]
+deps = ["CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "SQLLLM", "Serialization", "URIs", "UUIDs"]
path = "."
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
version = "0.4.0"
diff --git a/etc.jl b/etc.jl
index 13b0321..c904b6d 100644
--- a/etc.jl
+++ b/etc.jl
@@ -1,93 +1,13 @@
-using DataStructures
-
-function dictify2(x; keytype::Type=Any, sort_order::Union{Nothing, Vector}=nothing)
- # Dict-like objects
- if x isa AbstractDict
- out = OrderedDict{keytype, Any}()
-
- # 1. Process and normalize all keys from the input dictionary
- processed_dict = OrderedDict{keytype, Any}()
- for (k, v) in x
- if keytype === String
- newk = string(k)
- elseif keytype === Symbol
- newk = Symbol(string(k))
- else
- newk = k
- end
- processed_dict[newk] = dictify(v; keytype=keytype, sort_order=sort_order)
- end
-
- # 2. If a sort order is specified, apply it
- if !isnothing(sort_order)
- # Normalize the sort_order elements to match the requested keytype
- normalized_order = map(sort_order) do tk
- if keytype === String
- return string(tk)
- elseif keytype === Symbol
- return Symbol(string(tk))
- else
- return tk
- end
- end
-
- # First, insert keys that match the requested order
- for target_key in normalized_order
- if haskey(processed_dict, target_key)
- out[target_key] = processed_dict[target_key]
- end
- end
-
- # Then, append any remaining keys that weren't in the sort_order
- for (k, v) in processed_dict
- if !haskey(out, k)
- out[k] = v
- end
- end
- else
- # If no sort order is given, just use the processed dict
- out = processed_dict
- end
-
- return out
-
- # Arrays / vectors: map elements recursively
- elseif x isa AbstractArray
- return [dictify(element; keytype=keytype, sort_order=sort_order) for element in x]
-
- # Everything else: return as-is
- else
- return x
- end
-end
-
-
-
-
-function dict_to_string_html2(d::AbstractDict; indent_level=1, indent_str=" ")
- lines = String[]
- padding = indent_str ^ indent_level
-
- # Sort keys for predictable, clean output
- for k in keys(d)
- v = d[k]
-
- if v isa AbstractDict
- # Open tag, recurse for children, then close tag
- push!(lines, "$padding<$k>")
- ind_level = indent_level + 1
- push!(lines, dict_to_string_html(v; indent_level=ind_level, indent_str=indent_str))
- push!(lines, "$padding$k>")
- else
- # Leaf node: put key and value on a single line
- push!(lines, "$padding<$k>$v$k>")
- end
- end
- return join(lines, "\n")
-end
-
+d = Dict(
+ "hello"=> 555,
+ "world"=> Dict(
+ "name"=> "ton"
+ )
+)
+x = 55
+@info "YiemAgent think() 1 " d x @__LINE__
\ No newline at end of file
diff --git a/src/interface.jl b/src/interface.jl
index 984e253..cc00f16 100644
--- a/src/interface.jl
+++ b/src/interface.jl
@@ -60,40 +60,18 @@ end
# Keyword Arguments
# Return
- - `thoughtDict::Dict`
+ - `thoughtdict::Dict`
# Example
```jldoctest
-julia> config = Dict(
- "mqttServerInfo" => Dict(
- "description" => "mqtt server info",
- "port" => 1883,
- "broker" => "mqtt.yiem.cc"
- ),
- "externalservice" => Dict(
- "text2textinstruct" => Dict(
- "mqtttopic" => "/loadbalancer/requestingservice",
- "description" => "text to text service with instruct LLM",
- "llminfo" => Dict(
- "name" => "llama3instruct"
- )
- ),
- )
- )
+julia> result = decisionMaker(agent)
-julia> output_thoughtDict = Dict(
- "thought_1" => "The customer wants to buy a bottle of wine. This is a good start!",
- "action_1" => Dict{String, Any}(
- "action"=>"CHAT_BOX",
- "input"=>"What occasion are you buying the wine for?"
- ),
- "observation_1" => ""
- )
+OrderedDict{String, Any} with 4 entries:
+ "plan" => "The user provided an image of a sparkling white wine (Asolo Prosecco Bella Principessa from Italy) and requested a search for similar wines in the inventory. According to store guidelines, I must st…
+ "action_name" => "CHECK_WINE"
+ "action_input" => "Sparkling white wine from Italy"
+ "action_result" => "1) winery: Terrazze dell Etna, wine_name: Rose Brut.
```
- - [] update docstring
- - [] use customerinfo
- - [] user storeinfo
-
"""
function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
) where {T<:agent}
@@ -160,11 +138,11 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
response = a.context.text2textInstructLLM(a.id, msg)
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)
+
responsedict = nothing
if occursin(requiredKeys[2], response)
try
@@ -192,11 +170,11 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
continue
end
- if responsedict["action_name"] ∉ ["CHAT_BOX", "CHECK_WINE", "PRESENT_WINE_GUIDELINE", "END_CONVER_GUIDELINE"]
- errornote = "Your previous attempt didn't use the given functions"
- println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)--> $(responsedict["action_name"])", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- continue
- end
+ # if responsedict["action_name"] ∉ ["CHAT_BOX", "CHECK_WINE", "PRESENT_WINE_GUIDELINE", "END_CONVER_GUIDELINE"]
+ # errornote = "Your previous attempt didn't use the given functions"
+ # println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)--> $(responsedict["action_name"])", @__FILE__, ":", @__LINE__, " $(Dates.now())")
+ # continue
+ # end
# println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# pprintln(responsedict)
@@ -370,6 +348,148 @@ function evaluator(a::T1, timeline, decisiondict, evaluateecontext
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.
@@ -396,92 +516,95 @@ message => Dict(
]
)
-# ---------------------------------------------- 100 --------------------------------------------- #
"""
function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Object{String, Any}},
- maximumMsg=50)
+ maximumMsg=50, max_think_loop::Integer=3)
+
+ @info "YiemAgent conversation() 1" @__LINE__
userinput = GeneralUtils.dictify(userinput; keytype=String, sort_order=["text"])
# find text in usermsg
usertext = nothing
- text_position = nothing
for (i, d) in enumerate(userinput["content"])
if d["type"] == "text"
+ d["text"] = GeneralUtils.remove_french_accents(d["text"])
usertext = d["text"]
- text_position = i
end
end
-
- # place holder
- action_name = nothing
- result = nothing
- chatresponse = nothing
if usertext == "newtopic"
clearhistory(a)
return "Okay. What shall we talk about?"
else
- userinput["content"][text_position]["text"] = GeneralUtils.remove_french_accents(usertext)
+ @info "YiemAgent conversation() 2" @__LINE__
# add usermsg to a.chathistory but how do I handle images?
addNewMessage(a, "user", userinput; maximumMsg=maximumMsg)
# thinking loop until AI wants to communicate with the user
- chatresponse = nothing
- while chatresponse === nothing
- action_name, result = think(a)
- if action_name ∈ ["CHAT_BOX"]
- chatresponse = result
+ loopcount = 0
+ while true
+ @info "YiemAgent conversation() 2-0 count $loopcount" @__LINE__
+ loopcount += 1
+ thoughtdict, _ = think(a)
+ if thoughtdict["action_name"] ∈ ["CHAT_BOX"]
+ @info "YiemAgent conversation() 2-1" @__LINE__
+ assistant_response = Dict{String, Any}(
+ "role" => "assistant",
+ "content" => [Dict("type" => "text", "text" => thoughtdict["action_input"]),]
+ )
+ addNewMessage(a, "assistant", assistant_response; maximumMsg=maximumMsg)
+ return thoughtdict["action_input"]
+ end
+
+ if loopcount > max_think_loop
+ @info "YiemAgent conversation() 2-2" @__LINE__
+ r = generatechat(a)
+ @info "YiemAgent conversation() 2-3" @__LINE__
+ return r
end
end
- assistant_response = Dict{String, Any}(
- "role" => "assistant",
- "content" => [Dict("type" => "text", "text" => chatresponse),]
- )
- addNewMessage(a, "assistant", assistant_response; maximumMsg=maximumMsg)
-
- return chatresponse
end
end
-function conversation(a::Union{companion, virtualcustomer}, userinput::Dict;
- converPartnerName::Union{String, Nothing}=nothing,
- maximumMsg=50)
+# function conversation(a::Union{companion, virtualcustomer}, userinput::Dict;
+# converPartnerName::Union{String, Nothing}=nothing,
+# maximumMsg=50)
- chatresponse = nothing
+# 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)
+# 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)
+# # 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)
+# 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
+# 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
@@ -494,42 +617,59 @@ julia>
```
"""
-function think(a::T) where {T<:agent}
+function think(a::T)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
# a.memory[:recap] = generateSituationReport(a, a.context["text"2textInstructLLM]; skiprecent=0)
- thoughtDict = decisionMaker(a)
+ thoughtdict = decisionMaker(a)
+ @info "YiemAgent think() 1" @__LINE__
+ # pprintln(thoughtdict)
- println("\n--- YiemAgent think() 1 ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- pprintln(thoughtDict)
- println("---")
-
- # # map action and input() to llm function
- # response =
- # if thoughtDict["action_name"] == "CHAT_BOX" || thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
- # (result=thoughtDict["plan"], errormsg=nothing, success=true)
- # elseif thoughtDict["action_name"] == "CHECK_WINE"
- # checkwine(a, thoughtDict["action_input"])
- # elseif thoughtDict["action_name"] == "PRESENT_WINE_GUIDELINE"
- # (result=thoughtDict["action_input"], errormsg=nothing, success=true)
- # else
- # error("undefined LLM function. Requesting $(thoughtDict["action_name"])")
- # end
-
- # # this section allow LLM functions above to have different return values.
- # result = haskey(response, "result") ? response["result"] : nothing
- # rawresponse = haskey(response, "rawresponse") ? response["rawresponse"] : nothing
- # select = haskey(response, "select") ? response["select"] : nothing
- # reward::Integer = haskey(response, "reward") ? response["reward"] : 0
- # isterminal::Bool = haskey(response, "isterminal") ? response["isterminal"] : false
- # errormsg::Union{AbstractString,Nothing} = haskey(response, "errormsg") ? response["errormsg"] : nothing
- # success::Bool = haskey(response, "success") ? response["success"] : false
-
- result = nothing
- if thoughtDict["action_name"] ∈ ["CHAT_BOX"]
- result = thoughtDict["action_input"]
- elseif thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
+ result_raw = nothing
+ if thoughtdict["action_name"] ∈ ["CHAT_BOX"]
+ @info "YiemAgent think() 2" @__LINE__
+ thoughtdict, result_raw = chatbox!(a, thoughtdict)
- # add guideline in to context
- guideline =
+ elseif thoughtdict["action_name"] == "END_CONVER_GUIDELINE"
+ @info "YiemAgent think() 3" @__LINE__
+ thoughtdict, result_raw = end_conversation_guideline!(a, thoughtdict)
+
+ elseif thoughtdict["action_name"] ∈ ["WINE_PRESENTATION_GUIDELINE"]
+ @info "YiemAgent think() 4" @__LINE__
+ thoughtdict, result_raw = wine_presentation_guideline!(a, thoughtdict)
+
+
+ elseif thoughtdict["action_name"] == "CHECK_WINE"
+ @info "YiemAgent think() 5" @__LINE__
+ thoughtdict, result_raw = checkwine!(a, thoughtdict)
+
+ else
+ @info "YiemAgent think() 6" @__LINE__
+ error("condition is not defined ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
+ end
+
+ max_ind =
+ if length(a.memory["shortmem"]) == 0
+ 0
+ else
+ k = keys(a.memory["shortmem"])
+ maximum(parse.(Int, k))
+ end
+ a.memory["shortmem"]["$(max_ind + 1)"] = thoughtdict
+
+ @info "YiemAgent think() 7" @__LINE__
+ pprintln(thoughtdict)
+ return (thoughtdict=thoughtdict, result_raw=result_raw)
+end
+
+function chatbox!(a::T, thoughtdict::AbstractDict
+ )::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
+ thoughtdict["action_result"] = "Action result is the next user dialogue."
+ return (thoughtdict=thoughtdict, result_raw=nothing)
+end
+
+function end_conversation_guideline!(a::T, thoughtdict::AbstractDict
+ )::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
+
+ guideline =
"""
- Provide customer with store contact info and business hours
@@ -540,20 +680,15 @@ function think(a::T) where {T<:agent}
"""
- thoughtDict["action_result"] = guideline
- max_ind =
- if length(a.memory["shortmem"]) == 0
- 0
- else
- k = keys(a.memory["shortmem"])
- maximum(parse.(Int, k))
- end
- a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
+ thoughtdict["action_result"] = guideline
- elseif thoughtDict["action_name"] ∈ ["PRESENT_WINE_GUIDELINE"] #WORKING
-
- # add guideline in to context
- guideline =
+ return (thoughtdict=thoughtdict, result_raw=nothing)
+end
+
+function wine_presentation_guideline!(a::T, thoughtdict::AbstractDict
+ )::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
+
+ guideline =
"""
- Provide detailed introductions of the wines you've found to the user.
@@ -589,295 +724,366 @@ function think(a::T) where {T<:agent}
"""
- thoughtDict["action_result"] = guideline
- max_ind =
- if length(a.memory["shortmem"]) == 0
- 0
- else
- k = keys(a.memory["shortmem"])
- maximum(parse.(Int, k))
- end
- a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
+ thoughtdict["action_result"] = guideline
- elseif thoughtDict["action_name"] == "CHECK_WINE"
- result = checkwine(a, thoughtDict["action_input"])
-
- thoughtDict["action_result"] = result[:result_str]
- max_ind =
- if length(a.memory["shortmem"]) == 0
- 0
- else
- k = keys(a.memory["shortmem"])
- maximum(parse.(Int, k))
- end
- a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
- else
- error("condition is not defined ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- end
-
- println("\n--- YiemAgent think() 2 ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- pprintln(thoughtDict)
- println("---")
- return (action_name=thoughtDict["action_name"], result=result)
+ return (thoughtdict=thoughtdict, result_raw=nothing)
end
-function presentbox(a::sommelier, thoughtDict; maxtattempt::Integer=10, recentevents::Integer=10)
- recentchat_ind = GeneralUtils.recentElementsIndex(length(a.chathistory), recentevents;
- includelatest=true)
+#PENDING
+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 =
- """
-
- You have checked the inventory and found wines that may match what the user wants.
-
-
- Your name is $(a.name). You are a helpful English-speaking assistant, acting as a polite, website-based sommelier for $(a.retailername)'s wine store.
-
-
- Present the wines to the user in a way that keep the conversation smooth and engaging.
-
+ """
+ # store_policy
+ - 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.
+ # store_guidelines
+ - 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.
+ # situation
+ You are continuing the conversation with the user.
+ # your role
+ 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.
+ # objective
+ - Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences.
+ - Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences.
+ # your responsibility includes
+ - According to the store's policy and guidelines, continuing conversation with the customer using CHAT_BOX action.
+ - Keep the conversation with the customer going smoothly
+
+ # your responsibility does NOT includes
+ - 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.
+ - Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store.
+ - 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.
+
+ # you should then respond to the user with interleaving plan, action_name, action_input
+ 1) **plan**, Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
+ 2) **action_name**, (Typically corresponds to the execution of the first step in your plan). Must be "CHAT_BOX
+ 3) **action_input**, Dialogue you want to chat with the user according to your plan.
+ After the action is executed you gets "action_result". It is the output from the action you selected.
+
+ # you should only respond in JSON format as described below
+ "plan": "...",
+ "action_name": "...",
+ "action_input": "..."
+ """
-
+ system_msg = Dict(
+ "role" => "system",
+ "content" => [
+ Dict("type" => "text", "text" => systemmsg),
+ ]
+ )
-
- Name of the wines that needs to be introduced: name of wines you are going to introduce to the user
- Database search result: the result of a database search using SQL commands you have found so far
-
-
-
-
-
- dialogue: Your presentation to the user
-
-
- {
- "dialogue": "..."
- }
-
+ chathistory = deepcopy(a.chathistory[2:end])
+ pushfirst!(chathistory, system_msg)
- Let's begin!
- """
- requiredKeys = [:dialogue]
- database_search_result =
- if length(a.memory["shortmem"][:db_search_result]) != 0
- availableWineToText(a.memory["shortmem"][:db_search_result])
- else
- "N/A"
- end
+ requiredKeys = ["plan", "action_name", "action_input"]
+ context =
+ """
+
+
+ $(GeneralUtils.dict_to_string_html(a.memory["shortmem"]))
+
+
+ """
- # chathistory = chatHistoryToText(a.chathistory)
+ # 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
-
-
- # yourthought = "$(thoughtDict[:thought]) $(thoughtDict["plan"])"
- # yourthought1 = nothing
-
- for attempt in 1:maxtattempt
-
- context =
- """
-
- Name of the wines that needs to be introduced: $(thoughtDict["action_input"])
- $(a.memory["shortmem"]["scratchpad"])
- P.S. $errornote
-
- """
-
- unformatPrompt =
- [
- Dict("name" => "system", "text" => systemmsg),
- ]
-
- unformatPrompt = vcat(unformatPrompt, recentchat)
- # 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)
-
- response = replace(response, '*'=>"")
- response = replace(response, '$' => "USD")
- response = replace(response, '`' => "")
- response = replace(response, "<|eot_id|>"=>"")
+ 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" => a.chathistory,
+ "temperature" => 0.7
+ )
+
+ response = a.context.text2textInstructLLM(a.id, msg)
+ 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
- try
- responsedict = copy(JSON.parsefile(response))
- catch
- println("\nERROR YiemAgent presentbox() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- continue
+ if occursin(requiredKeys[2], response)
+ try
+ _responsedict = JSON.parse(response)
+ responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
+ catch
+ 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
+ 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
+ )
end
# check whether all answer's key points are in responsedict
- ispass, errormsg = checkAgentResponse_JSON(responsedict, requiredKeys)
+ ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
if !ispass
errornote = errormsg
- println("\nERROR YiemAgent presentbox() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
+ println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
continue
end
- # check if Context: is in dialogue
- if occursin("Context:", responsedict["dialogue"])
- errornote = "Your previous response contains 'Context:' which is not allowed"
- println("\nERROR YiemAgent presentbox() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- continue
- end
+ # if responsedict["action_name"] ∉ ["CHAT_BOX", "CHECK_WINE", "PRESENT_WINE_GUIDELINE", "END_CONVER_GUIDELINE"]
+ # errornote = "Your previous attempt didn't use the given functions"
+ # println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)--> $(responsedict["action_name"])", @__FILE__, ":", @__LINE__, " $(Dates.now())")
+ # continue
+ # end
- println("\nYiemAgent presentbox() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- pprintln(Dict(responsedict))
+ # println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
+ # pprintln(responsedict)
- # check whether an agent recommend wines before checking inventory or recommend wines
- # outside its inventory
- # ask LLM whether there are any winery mentioned in the response
- mentioned_winery = detectWineryName(a, responsedict["dialogue"])
- if mentioned_winery != "None"
- mentioned_winery = String.(strip.(split(mentioned_winery, ",")))
-
- # check whether the wine is in event
- isWineInEvent = false
- for winename in mentioned_winery
- for event in a.memory["events"]
- if event["observation"] !== nothing && occursin(winename, event["observation"])
- isWineInEvent = true
- break
- end
- end
- end
-
- # if wine is mentioned but not in timeline or shortmem,
- # then the agent is not supposed to recommend the wine
- if isWineInEvent == false
- errornote = "Your previous response recommended wines that is not in your inventory which is not allowed"
- println("\nERROR YiemAgent presentbox() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- s = """
- Perfect choice! The Colgin Tychson Hill Vineyard Cabernet Sauvignon (2014) is an excellent match for your criteria. Here's why:
-
- Boldness & Flavor: This wine delivers intense blackberry, black cherry, and dark fruit notes, layered with vanilla, oak, and earthy undertones. Its high intensity (rated 5/5) ensures a rich, full-bodied experience that's both powerful and balanced.
-
- Family-Owned Legacy: Produced by Colgin Cellars, a renowned Napa Valley family winery, this vintage reflects their commitment to quality and tradition. While not a limited-edition release, it's a highly regarded, consistently excellent Cabernet Sauvignon.
-
- Gift-Ready & Affordable: Priced at USD144 (well under your USD250 budget), it comes in a sleek, gift-ready box—perfect for impressing friends or loved ones.
-
- Why I Recommend It: It perfectly balances your desire for bold fruit, oak, and a presentable format without sacrificing quality. If you're curious about alternatives, the 2017 Hunter Glenn Cabernet (also USD159) shares similar intensity but lacks specific tasting notes. However, the 2014 Tychson Hill is a more complete match for your criteria. Enjoy your selection!"""
-
- continue
- end
- end
-
- result = responsedict["dialogue"]
- return result
+ return responsedict["action_input"]
end
- error("presentbox() failed to generate a response")
+ error("YiemAgent generatechat() failed to generate a thought ", response)
end
+# function generatechat(a::T; recentevents::Integer=20, maxattempt=10
+# )::String where {T<:agent}
-# function endconversation(a::sommelier, thoughtDict; maxattempt::Integer=10)
-# text =
-# """
-# ---
+# # 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": "..."
+#
+# """
-# """
-# requiredKeys = ["dialogue"]
-
# system_msg = Dict(
-# "role" => "system",
-# "content" => [
-# Dict("type" => "text", "text" => systemmsg),
-# ]
-# )
+# "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
-
-# 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)
+# if attempt > 1
+# println("\nYiemAgent generatechat() attempt $attempt/$maxattempt ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
+# end
-# responsedict = nothing
-# try
-# responsedict = copy(JSON.parsefile(response))
-# catch
-# println("\nERROR YiemAgent generatechat() failed to parse response: $response", @__FILE__, ":", @__LINE__, " $(Dates.now())")
-# continue
-# 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)
-# # check whether all answer's key points are in responsedict
-# ispass, errormsg = checkAgentResponse_JSON(responsedict, requiredKeys)
-# if !ispass
-# errornote = errormsg
-# println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
-# continue
-# end
-
-# # sometime the model response like this "here's how I would respond: ..."
-# if occursin("respond:", response)
-# errornote = "Your previous response contains 'response:' which is not allowed"
-# println("\nERROR YiemAgent generatechat() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
-# continue
-# elseif occursin("Your thoughts:", response) || occursin("your thoughts:", response)
-# errornote = "You don't need to put 'Your thoughts:' in your response"
-# println("\nERROR YiemAgent generatechat() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
-# continue
-# end
# response = GeneralUtils.remove_french_accents(response)
-# response = replace(response, '*'=>"")
-# response = replace(response, '$' => "USD")
-# response = replace(response, '`' => "")
-# response = replace(response, "<|eot_id|>"=>"")
-
-# # check whether an agent recommend wines before checking inventory or recommend wines
-# # outside its inventory
-# # ask LLM whether there are any winery mentioned in the response
-# mentioned_winery = detectWineryName(a, response)
-# if mentioned_winery != "None"
-# mentioned_winery = String.(strip.(split(mentioned_winery, ",")))
-
-# # check whether the wine is in event
-# isWineInEvent = false
-# for winename in mentioned_winery
-# for event in a.memory["events"]
-# if event["observation"] !== nothing && occursin(winename, event["observation"])
-# isWineInEvent = true
-# break
-# end
-# end
-# end
-
-# # then the agent is not supposed to recommend the wine
-# if isWineInEvent == false
-# errornote = "You recommended wines that are not in your inventory before. Please only recommend wines that you have previously found in your inventory."
-# println("\nERROR YiemAgent generatechat() $errornote $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
+# 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
-# result = responsedict["dialogue"]
-# return result
+# 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
-# error("generatechat failed to generate a response")
+# @info "YiemAgent generatechat() 2-13 attempt $attempt " @__LINE__
+# error("YiemAgent generatechat() failed to generate a thought ", response)
# end
diff --git a/src/llmfunction.jl b/src/llmfunction.jl
index 20be98f..fa98057 100644
--- a/src/llmfunction.jl
+++ b/src/llmfunction.jl
@@ -1,10 +1,10 @@
module llmfunction
-export virtualWineUserChatbox, jsoncorrection, checkwine, # recommendbox,
+export virtualWineUserChatbox, jsoncorrection, checkwine!, # recommendbox,
virtualWineUserRecommendbox, userChatbox, userRecommendbox, extractWineAttributes_1,
extractWineAttributes_2, paraphrase
-using HTTP, JSON, URIs, Random, PrettyPrinting, UUIDs, Dates, DataFrames
+using HTTP, JSON, URIs, Random, PrettyPrinting, UUIDs, Dates, DataFrames, DataStructures
using GeneralUtils, SQLLLM
using ..type, ..util
@@ -269,7 +269,7 @@ end
# Arguments
- `a::T1`
one of ChatAgent's agent.
- - `input::T2`
+ - `thoughtdict::AbstractDict`
# Return
A JSON string of available wine
@@ -281,53 +281,14 @@ julia> input = "{\"food\": \"pizza\", \"occasion\": \"anniversary\"}"
julia> result = checkinventory(agent, input)
"{"wine 1": {\"Winery\": \"Pichon Baron\", \"wine name\": \"Pauillac (Grand Cru Classé)\", \"grape variety\": \"Cabernet Sauvignon\", \"year\": 2010, \"price\": \"125 USD\", \"stock ID\": \"ar-17\"}, }"
```
-"""
-function checkwine(a::T1, input::T2; maxattempt::Int=3
- ) where {T1<:agent, T2<:AbstractString}
+"""
+function checkwine!(a::T, thoughtdict::AbstractDict
+ )::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
- println("\ncheckinventory order: $input ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- wineattributes_1 = extractWineAttributes_1(a, input)
- wineattributes_2 = extractWineAttributes_2(a, input)
+ println("\ncheckinventory order: $(thoughtdict["action_input"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
+ wineattributes_1 = extractWineAttributes_1(a, thoughtdict["action_input"])
+ wineattributes_2 = extractWineAttributes_2(a, thoughtdict["action_input"])
- # placeholder
- # textresult = nothing
- # rawresponse = nothing
-
- # for i in 1:maxattempt
-
- # #CHANGE if you want to add retailer name
- # # _inventoryquery = "retailer name: $(a.retailername), $wineattributes_1, $wineattributes_2"
- # _inventoryquery = "$wineattributes_1, $wineattributes_2"
-
- # retrieve_attributes = ["winery", "wine_name", "wine_id", "vintage", "region", "country", "wine_type", "grape", "serving_temperature", "sweetness", "intensity", "tannin", "acidity", "tasting_notes", "price", "currency"]
- # inventoryquery = "Retrieves $retrieve_attributes of wines that match the following criteria - {$_inventoryquery}"
- # println("\ncheckinventory input: $inventoryquery ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- # # add suppport for similarSQLVectorDB
- # textresult, result_raw = SQLLLM.query(
- # inventoryquery,
- # a.context.executeSQL,
- # a.context.text2textInstructLLM;
- # insertSQLVectorDB=a.context.insertSQLVectorDB,
- # similarSQLVectorDB=a.context.similarSQLVectorDB,
- # llmFormatName="qwen3")
-
- # # check if all of retrieve_attributes appears in textresult
- # isin = [occursin(x, textresult) for x in retrieve_attributes]
- # # check if rawresponse type is DataFrame so that I can check for column
- # if typeof(result_raw) == DataFrame &&
- # !occursin("The resulting table has 0 row", textresult) &&
- # !all(isin)
-
- # errornote = "Not all of $retrieve_attributes appear in search result"
- # println("\nERROR YiemAgent checkwine() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- # continue
- # else
- # break
- # end
- # end
-
- #CHANGE if you want to add retailer name
- # _inventoryquery = "retailer name: $(a.retailername), $wineattributes_1, $wineattributes_2"
retrieve_attributes = ["winery", "wine_name", "wine_id", "vintage", "region", "country", "wine_type", "grape", "serving_temperature", "sweetness", "intensity", "tannin", "acidity", "tasting_notes", "price", "currency"]
_inventoryquery = "$wineattributes_1, $wineattributes_2"
inventoryquery = "Retrieves $retrieve_attributes of wines that match the following criteria - {$_inventoryquery}"
@@ -340,15 +301,11 @@ function checkwine(a::T1, input::T2; maxattempt::Int=3
insertSQLVectorDB=a.context.insertSQLVectorDB,
similarSQLVectorDB=a.context.similarSQLVectorDB,
llmFormatName="qwen3")
- # println("\n--- YiemAgent checkwine() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
- # println(textresult)
- # println(result_raw)
- # println("---")
+ thoughtdict["action_result"] = textresult
- return (result_str=textresult, result_raw=result_raw, success=true, errormsg=nothing)
+ return (thoughtdict=thoughtdict, result_raw=result_raw)
end
-
"""
# Arguments
diff --git a/src/type.jl b/src/type.jl
index b40b64b..a11af7d 100644
--- a/src/type.jl
+++ b/src/type.jl
@@ -223,10 +223,9 @@ function sommelier(
context,
llmFormatName
)
-
systemmsg =
"""
-
+ # store_policy
- 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
@@ -238,8 +237,8 @@ function sommelier(
- 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 imediately 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.
-
-
+
+ # store_guidelines
- 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.
@@ -247,47 +246,46 @@ function sommelier(
- 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.
-
-
- Your customer is coming into the store
-
-
- Your name is $(newAgent.name). You are a helpful sommelier for website-based $(newAgent.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
- 2) Obey your mentor's suggestions.
-
-
- 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.
-
-
- 1) plan: Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
- 2) action_name: (Typically corresponds to the execution of the first step in your plan) Can be one of the available_actions name
- 3) action_input: The input to the action you are about to perform according to your plan.
+
+ # situation
+ You are having conversation with a customer.
+
+ # your role
+ Your name is $(newAgent.name). You are a helpful sommelier for website-based $(newAgent.retailername)'s wine store.
+
+ # objective
+ - Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences.
+ - Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences.
+
+ # your responsibility includes
+ - According to the store's policy and guidelines, and make an informed decision about what available_actions you need to use to achieve the objective.
+ - Keep the conversation with the customer going smoothly
+
+ # your responsibility does NOT includes
+ - 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.
+ - Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store.
+ - 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.
+
+ # you should then respond to the user with interleaving plan, action_name, action_input
+ 1) **plan**, Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
+ 2) **action_name**, (Typically corresponds to the execution of the first step in your plan) Can be one of the available_actions name
+ 3) **action_input**, The input to the action you are about to perform according to your plan.
After the action is executed you gets "action_result". It is the output from the action you selected.
-
-
+
+ # you should only respond in JSON format as described below
"plan": "...",
"action_name": "...",
"action_input": "..."
-
-
- - CHAT_BOX which you can use to talk with the user.
- - CHECK_WINE allows you to check information about wines you want in your inventory's database. The input is text that specify supported search criteria includeing: retailer_name, wine price, winery, name, vintage, region, country, type, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity.
- Example query 1: "Dry, full-bodied red wine from 1) region: Burgundy, country: France or 2) region: Tuscany, country: Italy. Grape varietal: Merlot or Syrah. price 100 to 1000 USD."
- Example query 2: "Red or white wine, medium tannin, price under 700 USD"
- Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
- - PRESENT_WINE_GUIDELINE which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
- - END_CONVER_GUIDELINE which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
-
+
+ # available actions
+ **CHAT_BOX**, which you can use to talk with the user. The input is dialogue you want to chat with the user according to your plan.
+ **CHECK_WINE**, allows you to check information about wines you want in your inventory's database. The input is text that specify supported search criteria includeing: retailer_name, wine price, winery, name, vintage, region, country, type, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity.
+ Example query 1: "Dry, full-bodied red wine from 1) region: Burgundy, country: France or 2) region: Tuscany, country: Italy. Grape varietal: Merlot or Syrah. price 100 to 1000 USD."
+ Example query 2: "Red or white wine, medium tannin, price under 700 USD"
+ Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
+ **WINE_PRESENTATION_GUIDELINE**, which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
+ **END_CONVER_GUIDELINE**, which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
+
"""
system_msg = Dict(