v0.4.1 #4
+3
-5
@@ -2,7 +2,7 @@
|
||||
|
||||
julia_version = "1.12.6"
|
||||
manifest_format = "2.0"
|
||||
project_hash = "09bd5c43d6ad954d8be233d27fc343ea1149c0b0"
|
||||
project_hash = "3268ef1072eadefb752ce9f6d8f677881aada3b8"
|
||||
|
||||
[[deps.Accessors]]
|
||||
deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"]
|
||||
@@ -406,9 +406,7 @@ version = "1.21.3+0"
|
||||
|
||||
[[deps.LLMMCTS]]
|
||||
deps = ["GeneralUtils", "JSON", "PrettyPrinting"]
|
||||
git-tree-sha1 = "6b4f123b03c0fcce5b21c0dbcb947e8dd23f333a"
|
||||
repo-rev = "main"
|
||||
repo-url = "https://git.yiem.cc/ton/LLMMCTS"
|
||||
path = "../LLMMCTS"
|
||||
uuid = "d76c5a4d-449e-4835-8cc4-dd86ec44f241"
|
||||
version = "0.1.5"
|
||||
|
||||
@@ -983,7 +981,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"
|
||||
|
||||
@@ -28,6 +28,5 @@ DataFrames = "1.7.0"
|
||||
GeneralUtils = "0.4.9"
|
||||
HTTP = "2.4.0"
|
||||
JSON = "1.6.1"
|
||||
LLMMCTS = "0.1.5"
|
||||
NATS = "0.1.0"
|
||||
SQLLLM = "0.2.5"
|
||||
|
||||
@@ -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__
|
||||
+201
-17
@@ -192,11 +192,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)
|
||||
@@ -399,8 +399,9 @@ message => Dict(
|
||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
||||
"""
|
||||
function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Object{String, Any}},
|
||||
maximumMsg=50)
|
||||
maximumMsg=50; max_think_loop::Integer=5)
|
||||
userinput = GeneralUtils.dictify(userinput; keytype=String, sort_order=["text"])
|
||||
@info "YiemAgent conversation() 1" @__LINE__
|
||||
|
||||
# find text in usermsg
|
||||
usertext = nothing
|
||||
@@ -421,24 +422,32 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj
|
||||
clearhistory(a)
|
||||
return "Okay. What shall we talk about?"
|
||||
else
|
||||
@info "YiemAgent conversation() 2" @__LINE__
|
||||
userinput["content"][text_position]["text"] = GeneralUtils.remove_french_accents(usertext)
|
||||
# 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
|
||||
loop_count = 0
|
||||
while chatresponse === nothing
|
||||
loop_count += 1
|
||||
action_name, result = think(a)
|
||||
if action_name ∈ ["CHAT_BOX"]
|
||||
chatresponse = result
|
||||
elseif loop_count > max_think_loop
|
||||
thoughtDict = generatechat(a) #WORKING
|
||||
chatresponse = thoughtDict["action_input"]
|
||||
break
|
||||
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
|
||||
@@ -497,10 +506,8 @@ julia>
|
||||
function think(a::T) where {T<:agent}
|
||||
# a.memory[:recap] = generateSituationReport(a, a.context["text"2textInstructLLM]; skiprecent=0)
|
||||
thoughtDict = decisionMaker(a)
|
||||
|
||||
println("\n--- YiemAgent think() 1 ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(thoughtDict)
|
||||
println("---")
|
||||
@info "YiemAgent think() 1" @__LINE__
|
||||
@show thoughtDict
|
||||
|
||||
# # map action and input() to llm function
|
||||
# response =
|
||||
@@ -525,9 +532,10 @@ function think(a::T) where {T<:agent}
|
||||
|
||||
result = nothing
|
||||
if thoughtDict["action_name"] ∈ ["CHAT_BOX"]
|
||||
@info "YiemAgent think() 2" @__LINE__
|
||||
result = thoughtDict["action_input"]
|
||||
elseif thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
|
||||
|
||||
@info "YiemAgent think() 3" @__LINE__
|
||||
# add guideline in to context
|
||||
guideline =
|
||||
"""
|
||||
@@ -550,8 +558,8 @@ function think(a::T) where {T<:agent}
|
||||
end
|
||||
a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
|
||||
|
||||
elseif thoughtDict["action_name"] ∈ ["PRESENT_WINE_GUIDELINE"] #WORKING
|
||||
|
||||
elseif thoughtDict["action_name"] ∈ ["PRESENT_WINE_GUIDELINE"] #PENDING
|
||||
@info "YiemAgent think() 4" @__LINE__
|
||||
# add guideline in to context
|
||||
guideline =
|
||||
"""
|
||||
@@ -600,6 +608,7 @@ function think(a::T) where {T<:agent}
|
||||
a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
|
||||
|
||||
elseif thoughtDict["action_name"] == "CHECK_WINE"
|
||||
@info "YiemAgent think() 5" @__LINE__
|
||||
result = checkwine(a, thoughtDict["action_input"])
|
||||
|
||||
thoughtDict["action_result"] = result[:result_str]
|
||||
@@ -615,12 +624,187 @@ function think(a::T) where {T<:agent}
|
||||
error("condition is not defined ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
end
|
||||
|
||||
println("\n--- YiemAgent think() 2 ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(thoughtDict)
|
||||
println("---")
|
||||
@info "YiemAgent think() 6" @__LINE__
|
||||
return (action_name=thoughtDict["action_name"], result=result)
|
||||
end
|
||||
|
||||
#WORKING
|
||||
function generatechat(a::T; recentevents::Integer=20, maxattempt=10
|
||||
) 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 =
|
||||
"""
|
||||
<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 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_policy>
|
||||
<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.
|
||||
</store_guidelines>
|
||||
<situation>
|
||||
Your customer is coming into the store
|
||||
</situation>
|
||||
<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.
|
||||
</your role>
|
||||
<objective>
|
||||
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.
|
||||
</objective>
|
||||
<your responsibility includes>
|
||||
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.
|
||||
</your responsibility includes>
|
||||
<your responsibility does NOT includes>
|
||||
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.
|
||||
</your responsibility does NOT includes>
|
||||
<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 then respond to the user with interleaving plan, action_name, action_input>
|
||||
<you should only respond in JSON format as described below>
|
||||
"plan": "...",
|
||||
"action_name": "...",
|
||||
"action_input": "..."
|
||||
</you should only respond in JSON format as described below>
|
||||
<available_actions>
|
||||
- CHAT_BOX which you can use to talk with the user.
|
||||
</available_actions>
|
||||
"""
|
||||
|
||||
system_msg = Dict(
|
||||
"role" => "system",
|
||||
"content" => [
|
||||
Dict("type" => "text", "text" => systemmsg),
|
||||
]
|
||||
)
|
||||
|
||||
chathistory = deepcopy(a.chathistory[2:end])
|
||||
pushfirst!(chathistory, system_msg)
|
||||
|
||||
requiredKeys = ["chat", "action_name", "action_input"]
|
||||
context =
|
||||
"""
|
||||
<internal_context_for_assistant>
|
||||
<thought_history>
|
||||
$(GeneralUtils.dict_to_string_html(a.memory["shortmem"]))
|
||||
</thought_history>
|
||||
</internal_context_for_assistant>
|
||||
"""
|
||||
|
||||
# add context to text of the latest message (in the front).
|
||||
# use for loop because in openai format, each msg may contain both text and image.
|
||||
for d in chathistory[end]["content"]
|
||||
if d["type"] == "text"
|
||||
d["text"] = context * d["text"]
|
||||
break
|
||||
end
|
||||
end
|
||||
errornote = "N/A"
|
||||
response = nothing # placeholder for show when error msg show up
|
||||
|
||||
for attempt in 1:maxattempt
|
||||
if attempt > 1
|
||||
println("\nYiemAgent generatechat() attempt $attempt/$maxattempt ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
end
|
||||
|
||||
msg = Dict(
|
||||
"model" => "gemma-4-E4B-it-UD-Q4_K_XL",
|
||||
"messages" => chathistory,
|
||||
"temperature" => 0.7
|
||||
)
|
||||
|
||||
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
|
||||
_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 = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
if !ispass
|
||||
errornote = errormsg
|
||||
println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
continue
|
||||
end
|
||||
|
||||
# println("\nYiemAgent generatechat() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# pprintln(responsedict)
|
||||
|
||||
return responsedict
|
||||
end
|
||||
error("YiemAgent generatechat() failed to generate a thought ", response)
|
||||
end
|
||||
|
||||
|
||||
|
||||
function presentbox(a::sommelier, thoughtDict; maxtattempt::Integer=10, recentevents::Integer=10)
|
||||
recentchat_ind = GeneralUtils.recentElementsIndex(length(a.chathistory), recentevents;
|
||||
|
||||
Reference in New Issue
Block a user