update
This commit is contained in:
+123
-399
@@ -60,7 +60,7 @@ end
|
|||||||
# Keyword Arguments
|
# Keyword Arguments
|
||||||
|
|
||||||
# Return
|
# Return
|
||||||
- `thoughtDict::Dict`
|
- `thoughtdict::Dict`
|
||||||
|
|
||||||
# Example
|
# Example
|
||||||
```jldoctest
|
```jldoctest
|
||||||
@@ -396,12 +396,12 @@ message => Dict(
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
|
||||||
"""
|
"""
|
||||||
function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Object{String, Any}},
|
function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Object{String, Any}},
|
||||||
maximumMsg=50; max_think_loop::Integer=5)
|
maximumMsg=50, max_think_loop::Integer=3)
|
||||||
userinput = GeneralUtils.dictify(userinput; keytype=String, sort_order=["text"])
|
|
||||||
@info "YiemAgent conversation() 1" @__LINE__
|
@info "YiemAgent conversation() 1" @__LINE__
|
||||||
|
userinput = GeneralUtils.dictify(userinput; keytype=String, sort_order=["text"])
|
||||||
|
|
||||||
# find text in usermsg
|
# find text in usermsg
|
||||||
usertext = nothing
|
usertext = nothing
|
||||||
@@ -412,11 +412,6 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj
|
|||||||
text_position = i
|
text_position = i
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
# place holder
|
|
||||||
action_name = nothing
|
|
||||||
result = nothing
|
|
||||||
chatresponse = nothing
|
|
||||||
|
|
||||||
if usertext == "newtopic"
|
if usertext == "newtopic"
|
||||||
clearhistory(a)
|
clearhistory(a)
|
||||||
@@ -428,69 +423,67 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj
|
|||||||
addNewMessage(a, "user", userinput; maximumMsg=maximumMsg)
|
addNewMessage(a, "user", userinput; maximumMsg=maximumMsg)
|
||||||
|
|
||||||
# thinking loop until AI wants to communicate with the user
|
# thinking loop until AI wants to communicate with the user
|
||||||
chatresponse = nothing
|
loopcount = 0
|
||||||
loop_count = 0
|
while true
|
||||||
while chatresponse === nothing
|
loopcount += 1
|
||||||
loop_count += 1
|
thoughtdict, _ = think(a)
|
||||||
action_name, result = think(a)
|
if thoughtdict["action_name"] ∈ ["CHAT_BOX"]
|
||||||
if action_name ∈ ["CHAT_BOX"]
|
@info "YiemAgent conversation() 2-1" @__LINE__
|
||||||
chatresponse = result
|
assistant_response = Dict{String, Any}(
|
||||||
elseif loop_count > max_think_loop
|
"role" => "assistant",
|
||||||
thoughtDict = generatechat(a) #WORKING
|
"content" => [Dict("type" => "text", "text" => thoughtdict["action_input"]),]
|
||||||
chatresponse = thoughtDict["action_input"]
|
)
|
||||||
break
|
addNewMessage(a, "assistant", assistant_response; maximumMsg=maximumMsg)
|
||||||
|
return thoughtdict["action_input"]
|
||||||
|
end
|
||||||
|
|
||||||
|
if loopcount > max_think_loop
|
||||||
|
@info "YiemAgent conversation() 2-2" @__LINE__
|
||||||
|
return generatechat(a)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@info "YiemAgent conversation() 3" @__LINE__
|
|
||||||
assistant_response = Dict{String, Any}(
|
|
||||||
"role" => "assistant",
|
|
||||||
"content" => [Dict("type" => "text", "text" => chatresponse),]
|
|
||||||
)
|
|
||||||
addNewMessage(a, "assistant", assistant_response; maximumMsg=maximumMsg)
|
|
||||||
@info "YiemAgent conversation() 4" @__LINE__
|
|
||||||
return chatresponse
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
function conversation(a::Union{companion, virtualcustomer}, userinput::Dict;
|
# function conversation(a::Union{companion, virtualcustomer}, userinput::Dict;
|
||||||
converPartnerName::Union{String, Nothing}=nothing,
|
# converPartnerName::Union{String, Nothing}=nothing,
|
||||||
maximumMsg=50)
|
# maximumMsg=50)
|
||||||
|
|
||||||
chatresponse = nothing
|
# chatresponse = nothing
|
||||||
|
|
||||||
if userinput["text"] == "newtopic"
|
# if userinput["text"] == "newtopic"
|
||||||
clearhistory(a)
|
# clearhistory(a)
|
||||||
return "Okay. What shall we talk about?"
|
# return "Okay. What shall we talk about?"
|
||||||
else
|
# else
|
||||||
# add usermsg to a.chathistory
|
# # add usermsg to a.chathistory
|
||||||
addNewMessage(a, "user", userinput["text"]; maximumMsg=maximumMsg)
|
# addNewMessage(a, "user", userinput["text"]; maximumMsg=maximumMsg)
|
||||||
|
|
||||||
# add user activity to events memory
|
# # add user activity to events memory
|
||||||
push!(a.memory["events"],
|
# push!(a.memory["events"],
|
||||||
eventdict(;
|
# eventdict(;
|
||||||
event_description="the user talks to the assistant.",
|
# event_description="the user talks to the assistant.",
|
||||||
timestamp=Dates.now(),
|
# timestamp=Dates.now(),
|
||||||
subject="user",
|
# subject="user",
|
||||||
action_name="CHAT_BOX",
|
# action_name="CHAT_BOX",
|
||||||
action_input=userinput["text"],
|
# action_input=userinput["text"],
|
||||||
)
|
# )
|
||||||
)
|
# )
|
||||||
chatresponse = generatechat(a; converPartnerName=converPartnerName, recentEventNum=20)
|
# chatresponse = generatechat(a; converPartnerName=converPartnerName, recentEventNum=20)
|
||||||
|
|
||||||
addNewMessage(a, "assistant", chatresponse; maximumMsg=maximumMsg)
|
# addNewMessage(a, "assistant", chatresponse; maximumMsg=maximumMsg)
|
||||||
|
|
||||||
push!(a.memory["events"],
|
# push!(a.memory["events"],
|
||||||
eventdict(;
|
# eventdict(;
|
||||||
event_description="the assistant talks to the user.",
|
# event_description="the assistant talks to the user.",
|
||||||
timestamp=Dates.now(),
|
# timestamp=Dates.now(),
|
||||||
subject="assistant",
|
# subject="assistant",
|
||||||
action_name="CHAT_BOX",
|
# action_name="CHAT_BOX",
|
||||||
action_input=chatresponse,
|
# action_input=chatresponse,
|
||||||
)
|
# )
|
||||||
)
|
# )
|
||||||
return chatresponse
|
# return chatresponse
|
||||||
end
|
# end
|
||||||
end
|
# end
|
||||||
|
|
||||||
"""
|
"""
|
||||||
# Arguments
|
# Arguments
|
||||||
@@ -503,41 +496,58 @@ 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)
|
# a.memory[:recap] = generateSituationReport(a, a.context["text"2textInstructLLM]; skiprecent=0)
|
||||||
thoughtDict = decisionMaker(a)
|
thoughtdict = decisionMaker(a)
|
||||||
@info "YiemAgent think() 1" @__LINE__
|
@info "YiemAgent think() 1" @__LINE__
|
||||||
@show thoughtDict
|
pprintln(thoughtdict)
|
||||||
|
|
||||||
# # map action and input() to llm function
|
result_raw = nothing
|
||||||
# response =
|
if thoughtdict["action_name"] ∈ ["CHAT_BOX"]
|
||||||
# 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"]
|
|
||||||
@info "YiemAgent think() 2" @__LINE__
|
@info "YiemAgent think() 2" @__LINE__
|
||||||
result = thoughtDict["action_input"]
|
thoughtdict, result_raw = chatbox!(a, thoughtdict)
|
||||||
elseif thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
|
|
||||||
|
elseif thoughtdict["action_name"] == "END_CONVER_GUIDELINE"
|
||||||
@info "YiemAgent think() 3" @__LINE__
|
@info "YiemAgent think() 3" @__LINE__
|
||||||
# add guideline in to context
|
thoughtdict, result_raw = end_conversation_guideline!(a, thoughtdict)
|
||||||
guideline =
|
|
||||||
|
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__
|
||||||
|
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 =
|
||||||
"""
|
"""
|
||||||
<end_conversation_guideline>
|
<end_conversation_guideline>
|
||||||
- Provide customer with store contact info and business hours
|
- Provide customer with store contact info and business hours
|
||||||
@@ -548,20 +558,15 @@ function think(a::T) where {T<:agent}
|
|||||||
</store_info>
|
</store_info>
|
||||||
</end_conversation_guideline>
|
</end_conversation_guideline>
|
||||||
"""
|
"""
|
||||||
thoughtDict["action_result"] = guideline
|
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
|
|
||||||
|
|
||||||
elseif thoughtDict["action_name"] ∈ ["PRESENT_WINE_GUIDELINE"] #PENDING
|
return (thoughtdict=thoughtdict, result_raw=nothing)
|
||||||
@info "YiemAgent think() 4" @__LINE__
|
end
|
||||||
# add guideline in to context
|
|
||||||
guideline =
|
function wine_presentation_guideline!(a::T, thoughtdict::AbstractDict
|
||||||
|
)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
|
||||||
|
|
||||||
|
guideline =
|
||||||
"""
|
"""
|
||||||
<wine_presentation_guideline>
|
<wine_presentation_guideline>
|
||||||
- Provide detailed introductions of the wines you've found to the user.
|
- Provide detailed introductions of the wines you've found to the user.
|
||||||
@@ -597,40 +602,15 @@ function think(a::T) where {T<:agent}
|
|||||||
</conversion_table>
|
</conversion_table>
|
||||||
</wine_presentation_guideline>
|
</wine_presentation_guideline>
|
||||||
"""
|
"""
|
||||||
thoughtDict["action_result"] = guideline
|
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
|
|
||||||
|
|
||||||
elseif thoughtDict["action_name"] == "CHECK_WINE"
|
return (thoughtdict=thoughtdict, result_raw=nothing)
|
||||||
@info "YiemAgent think() 5" @__LINE__
|
|
||||||
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
|
|
||||||
|
|
||||||
@info "YiemAgent think() 6" @__LINE__
|
|
||||||
return (action_name=thoughtDict["action_name"], result=result)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
#WORKING
|
|
||||||
|
#PENDING
|
||||||
function generatechat(a::T; recentevents::Integer=20, maxattempt=10
|
function generatechat(a::T; recentevents::Integer=20, maxattempt=10
|
||||||
) where {T<:agent}
|
)::String where {T<:agent}
|
||||||
|
|
||||||
# lessonDict = copy(JSON.parsefile("lesson.json"))
|
# lessonDict = copy(JSON.parsefile("lesson.json"))
|
||||||
|
|
||||||
@@ -730,7 +710,7 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
|
|||||||
chathistory = deepcopy(a.chathistory[2:end])
|
chathistory = deepcopy(a.chathistory[2:end])
|
||||||
pushfirst!(chathistory, system_msg)
|
pushfirst!(chathistory, system_msg)
|
||||||
|
|
||||||
requiredKeys = ["chat", "action_name", "action_input"]
|
requiredKeys = ["plan", "action_name", "action_input"]
|
||||||
context =
|
context =
|
||||||
"""
|
"""
|
||||||
<internal_context_for_assistant>
|
<internal_context_for_assistant>
|
||||||
@@ -784,7 +764,7 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
|
|||||||
responsedict = OrderedDict(
|
responsedict = OrderedDict(
|
||||||
"plan"=> "I will talk to the user",
|
"plan"=> "I will talk to the user",
|
||||||
"action_name"=> "CHAT_BOX",
|
"action_name"=> "CHAT_BOX",
|
||||||
"action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response
|
"action_input"=> string(response[2:end-1]) # remove { } at the front and back that added by clean_json_response
|
||||||
)
|
)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -792,279 +772,23 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
|
|||||||
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
|
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||||
if !ispass
|
if !ispass
|
||||||
errornote = errormsg
|
errornote = errormsg
|
||||||
println("\nERROR YiemAgent generatechat() $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
|
||||||
|
|
||||||
|
if responsedict["action_name"] != "CHAT_BOX" # make sure llm use correct tool
|
||||||
continue
|
continue
|
||||||
end
|
end
|
||||||
|
|
||||||
# println("\nYiemAgent generatechat() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
# println("\nYiemAgent generatechat() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||||
# pprintln(responsedict)
|
# pprintln(responsedict)
|
||||||
|
|
||||||
return responsedict
|
return responsedict["action_input"]
|
||||||
end
|
end
|
||||||
error("YiemAgent generatechat() failed to generate a thought ", response)
|
error("YiemAgent generatechat() failed to generate a thought ", response)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
function presentbox(a::sommelier, thoughtDict; maxtattempt::Integer=10, recentevents::Integer=10)
|
|
||||||
recentchat_ind = GeneralUtils.recentElementsIndex(length(a.chathistory), recentevents;
|
|
||||||
includelatest=true)
|
|
||||||
|
|
||||||
systemmsg =
|
|
||||||
"""
|
|
||||||
<situation>
|
|
||||||
You have checked the inventory and found wines that may match what the user wants.
|
|
||||||
</situation>
|
|
||||||
<Your role>
|
|
||||||
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.
|
|
||||||
</Your role>
|
|
||||||
<objective>
|
|
||||||
Present the wines to the user in a way that keep the conversation smooth and engaging.
|
|
||||||
</objective>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<At each round of conversation, you will be given the following information>
|
|
||||||
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
|
|
||||||
</At each round of conversation, you will be given the following information>
|
|
||||||
<You should follow the following guidelines>
|
|
||||||
|
|
||||||
</You should follow the following guidelines>
|
|
||||||
<You should then respond to the user with>
|
|
||||||
dialogue: Your presentation to the user
|
|
||||||
</You should then respond to the user with>
|
|
||||||
<You should only respond in format as described below>
|
|
||||||
{
|
|
||||||
"dialogue": "..."
|
|
||||||
}
|
|
||||||
</You should only respond in format as described below>
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
# chathistory = chatHistoryToText(a.chathistory)
|
|
||||||
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 =
|
|
||||||
"""
|
|
||||||
<context>
|
|
||||||
Name of the wines that needs to be introduced: $(thoughtDict["action_input"])
|
|
||||||
$(a.memory["shortmem"]["scratchpad"])
|
|
||||||
P.S. $errornote
|
|
||||||
</context>
|
|
||||||
"""
|
|
||||||
|
|
||||||
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|>"=>"")
|
|
||||||
|
|
||||||
responsedict = nothing
|
|
||||||
try
|
|
||||||
responsedict = copy(JSON.parsefile(response))
|
|
||||||
catch
|
|
||||||
println("\nERROR YiemAgent presentbox() 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 presentbox() $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
|
|
||||||
|
|
||||||
println("\nYiemAgent presentbox() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
|
||||||
pprintln(Dict(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
|
|
||||||
end
|
|
||||||
error("presentbox() failed to generate a response")
|
|
||||||
end
|
|
||||||
|
|
||||||
# function endconversation(a::sommelier, thoughtDict; maxattempt::Integer=10)
|
|
||||||
# text =
|
|
||||||
# """
|
|
||||||
# ---
|
|
||||||
|
|
||||||
# """
|
|
||||||
# requiredKeys = ["dialogue"]
|
|
||||||
|
|
||||||
# system_msg = Dict(
|
|
||||||
# "role" => "system",
|
|
||||||
# "content" => [
|
|
||||||
# Dict("type" => "text", "text" => systemmsg),
|
|
||||||
# ]
|
|
||||||
# )
|
|
||||||
|
|
||||||
# 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)
|
|
||||||
|
|
||||||
# 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 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())")
|
|
||||||
# continue
|
|
||||||
# end
|
|
||||||
# end
|
|
||||||
# result = responsedict["dialogue"]
|
|
||||||
|
|
||||||
# return result
|
|
||||||
# end
|
|
||||||
# error("generatechat failed to generate a response")
|
|
||||||
# end
|
|
||||||
|
|
||||||
|
|
||||||
function generatequestion(a, text2textInstructLLM::Function, timeline)::String
|
function generatequestion(a, text2textInstructLLM::Function, timeline)::String
|
||||||
systemmsg =
|
systemmsg =
|
||||||
"""
|
"""
|
||||||
|
|||||||
+10
-53
@@ -1,10 +1,10 @@
|
|||||||
module llmfunction
|
module llmfunction
|
||||||
|
|
||||||
export virtualWineUserChatbox, jsoncorrection, checkwine, # recommendbox,
|
export virtualWineUserChatbox, jsoncorrection, checkwine!, # recommendbox,
|
||||||
virtualWineUserRecommendbox, userChatbox, userRecommendbox, extractWineAttributes_1,
|
virtualWineUserRecommendbox, userChatbox, userRecommendbox, extractWineAttributes_1,
|
||||||
extractWineAttributes_2, paraphrase
|
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 GeneralUtils, SQLLLM
|
||||||
using ..type, ..util
|
using ..type, ..util
|
||||||
|
|
||||||
@@ -281,53 +281,14 @@ julia> input = "{\"food\": \"pizza\", \"occasion\": \"anniversary\"}"
|
|||||||
julia> result = checkinventory(agent, input)
|
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\"}, }"
|
"{"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
|
function checkwine!(a::T, thoughtdict::AbstractDict
|
||||||
) where {T1<:agent, T2<:AbstractString}
|
)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
|
||||||
|
|
||||||
println("\ncheckinventory order: $input ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
println("\ncheckinventory order: $(thoughtdict["action_input"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||||
wineattributes_1 = extractWineAttributes_1(a, input)
|
wineattributes_1 = extractWineAttributes_1(a, thoughtdict["action_input"])
|
||||||
wineattributes_2 = extractWineAttributes_2(a, 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"]
|
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 = "$wineattributes_1, $wineattributes_2"
|
||||||
inventoryquery = "Retrieves $retrieve_attributes of wines that match the following criteria - {$_inventoryquery}"
|
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,
|
insertSQLVectorDB=a.context.insertSQLVectorDB,
|
||||||
similarSQLVectorDB=a.context.similarSQLVectorDB,
|
similarSQLVectorDB=a.context.similarSQLVectorDB,
|
||||||
llmFormatName="qwen3")
|
llmFormatName="qwen3")
|
||||||
# println("\n--- YiemAgent checkwine() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
thoughtdict["action_result"] = textresult
|
||||||
# println(textresult)
|
|
||||||
# println(result_raw)
|
|
||||||
# println("---")
|
|
||||||
|
|
||||||
return (result_str=textresult, result_raw=result_raw, success=true, errormsg=nothing)
|
return (thoughtdict=thoughtdict, result_raw=result_raw)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Arguments
|
# Arguments
|
||||||
|
|||||||
+1
-1
@@ -285,7 +285,7 @@ function sommelier(
|
|||||||
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 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 2: "Red or white wine, medium tannin, price under 700 USD"
|
||||||
Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
|
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.
|
- 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.
|
- 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>
|
</available_actions>
|
||||||
"""
|
"""
|
||||||
|
|||||||
Reference in New Issue
Block a user