This commit is contained in:
2026-07-04 13:23:46 +07:00
parent b4f2a6185b
commit d1921fa403
14 changed files with 759 additions and 336 deletions
+21 -14
View File
@@ -2,7 +2,7 @@
julia_version = "1.12.6"
manifest_format = "2.0"
project_hash = "f897ee3fe396a565f9279db1f39a2f86d2c466c2"
project_hash = "5b5e1c071ff66b72aeed7d8a4316829e2407ae1a"
[[deps.Accessors]]
deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"]
@@ -298,19 +298,24 @@ deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
version = "1.11.0"
[[deps.Gamma]]
git-tree-sha1 = "86f86b6168a016ed88e4ae4e64577b98c3b59e8e"
uuid = "a0844989-3bd2-4988-8bea-c9407ab0941b"
version = "1.1.0"
[[deps.GeneralUtils]]
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "Distributions", "JSON", "NATS", "PrettyPrinting", "Random", "Revise", "SHA", "UUIDs"]
git-tree-sha1 = "aafde7b6e54a06840127f8379abe19ac17db6fea"
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "Distributions", "HTTP", "JSON", "NATS", "PrettyPrinting", "Random", "Revise", "SHA", "UUIDs"]
git-tree-sha1 = "7c0600c166a5deb2c607018a491c04eb25969c2e"
repo-rev = "main"
repo-url = "https://git.yiem.cc/ton/GeneralUtils"
uuid = "c6c72f09-b708-4ac8-ac7c-2084d70108fe"
version = "0.4.3"
version = "0.4.9"
[[deps.HTTP]]
deps = ["Base64", "CodecZlib", "Dates", "EnumX", "PrecompileTools", "Random", "Reseau", "SHA", "URIs", "UUIDs", "Zlib_jll"]
git-tree-sha1 = "e718a35dd7386ccd6bed64a1d84d661972404b99"
git-tree-sha1 = "eda1d37cb55d90a17d0957c75841138c88b361a1"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "2.5.1"
version = "2.5.4"
[[deps.HashArrayMappedTries]]
git-tree-sha1 = "2eaa69a7cab70a52b9687c8bf950a5a93ec895ae"
@@ -318,10 +323,10 @@ uuid = "076d061b-32b6-4027-95e0-9a2c6f6d7e74"
version = "0.2.0"
[[deps.HypergeometricFunctions]]
deps = ["LinearAlgebra", "OpenLibm_jll", "SpecialFunctions"]
git-tree-sha1 = "68c173f4f449de5b438ee67ed0c9c748dc31a2ec"
deps = ["Gamma", "LinearAlgebra"]
git-tree-sha1 = "18d7deab5fb0440dc6a7b6993c5c27b25420de10"
uuid = "34004b35-14d8-5ef3-9330-4cdb6864b03a"
version = "0.3.28"
version = "0.3.29"
[[deps.ICU_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
@@ -433,7 +438,7 @@ version = "1.21.3+0"
deps = ["GeneralUtils", "JSON", "PrettyPrinting"]
path = "../LLMMCTS"
uuid = "d76c5a4d-449e-4835-8cc4-dd86ec44f241"
version = "0.1.4"
version = "0.1.5"
[[deps.LaTeXStrings]]
git-tree-sha1 = "dda21b8cbd6a6c40d9d02a73230f9d70fed6918c"
@@ -763,9 +768,9 @@ version = "0.5.1+0"
[[deps.Roots]]
deps = ["Accessors", "CommonSolve", "Printf"]
git-tree-sha1 = "91cfb1cb4f6e27557cc2df798a31eff6089a41eb"
git-tree-sha1 = "ed45bcc7cf3c8887595b973f2b1efbe91dcc50ec"
uuid = "f2b01f46-fcfa-551c-844a-d8ac1e96c665"
version = "3.0.0"
version = "3.0.1"
[deps.Roots.extensions]
RootsChainRulesCoreExt = "ChainRulesCore"
@@ -789,9 +794,11 @@ version = "0.7.0"
[[deps.SQLLLM]]
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "FileIO", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "PrettyPrinting", "Random", "Revise", "StatsBase", "Tables", "URIs", "UUIDs"]
path = "../SQLLLM"
git-tree-sha1 = "997602ed56a285ac29d74c91bb57bc5faeadfad6"
repo-rev = "main"
repo-url = "https://git.yiem.cc/ton/SQLLLM"
uuid = "2ebc79c7-cc10-4a3a-9665-d2e1d61e63d3"
version = "0.2.4"
version = "0.2.5"
[[deps.SQLStrings]]
git-tree-sha1 = "55de0530689832b1d3d43491ee6b67bd54d3323c"
+2 -1
View File
@@ -26,8 +26,9 @@ msghandler = "f2724d33-f338-4a57-b9f8-1be882570d10"
[compat]
CSV = "0.10.15"
DataFrames = "1.7.0"
GeneralUtils = "0.4.3"
GeneralUtils = "0.4.9"
HTTP = "2.4.0"
JSON = "1.6.1"
NATS = "0.1.0"
SQLLLM = "0.2.5"
msghandler = "0.5.6"
+82
View File
@@ -0,0 +1,82 @@
# 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 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.
# Prompt
Search the database as broad as possible under the informantion you have will increase the chance to find wine. Avoid uneccessary parameter such as region, country, tasting notes unless the user specify
# Situation
Your customer is coming into the store
# Role
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.
# 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.
# 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
3. Obey your mentor's suggestions.
# Responsibility Does NOT Include
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.
# Available Actions
- **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.
# Response Format
You should 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.
Assistant should only respond in JSON format as described below:
```json
{
"plan": "...",
"action_name": "...",
"action_input": "..."
}
```
+93
View File
@@ -0,0 +1,93 @@
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
+2 -2
View File
@@ -426,7 +426,7 @@ function main()
# event_description="the assistant talks to the user.",
# timestamp=Dates.now(),
# subject="assistant",
# action_name="CHATBOX",
# action_name="CHAT_BOX",
# action_input=customer_chat,
# )
# )
@@ -454,7 +454,7 @@ function main()
if haskey(agent.memory[:events][end], :thought)
lastAssistantAction = agent.memory[:events][end][:thought][:action_name]
if lastAssistantAction == "ENDCONVERGUIDELINE" # store thoughtDict
if lastAssistantAction == "END_CONVER_GUIDELINE" # store thoughtDict
# save a.memory[:shortmem][:decisionlog] to disk using JSON
println("\nsaving agent.memory[:shortmem][:decisionlog] to disk")
+1 -1
View File
@@ -429,7 +429,7 @@ function runAgentInstance(
if haskey(agent.memory[:events][end], :thought)
lastAssistantAction = agent.memory[:events][end][:thought][:action_name]
if lastAssistantAction == "ENDCONVERGUIDELINE" # store thoughtDict
if lastAssistantAction == "END_CONVER_GUIDELINE" # store thoughtDict
# save a.memory[:shortmem][:decisionlog] to disk using JSON
println("\nsaving agent.memory[:shortmem][:decisionlog] to disk")
+1
View File
@@ -0,0 +1 @@
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
-88
View File
@@ -1,88 +0,0 @@
""" Recursively convert dictionary-like variable (e.g. JSON.Object) into a dictionary.
The function walks any nested structure composed of `AbstractDict` (e.g., `JSON.Object`,
`Dict`, `OrderedDict`) and `AbstractArray` and produces a new tree where
every dictionary-like node is a plain `Dict` and every array-like node is a
`Vector{Any}`. Scalar values (numbers, strings, booleans, `nothing`, etc.)
are returned unchanged.
Does **not** mutate the input; it always allocates new containers.
# Arguments
- `x`
Any Julia value. If `x` is an `AbstractDict` it will be converted to a `Dict`;
if it is an `AbstractArray` its elements will be processed recursively.
# Keyword Arguments
- `keytype::Type=Any`
The key type for the output Dict. Use `String` for `Dict{String,Any}`, `Symbol` for `Dict{Symbol,Any}`, or `Any` to preserve original key types.
- `stringkey::Bool=false`
If `true`, every dictionary key is converted to `String` via `string(k)`. This parameter is ignored when `keytype` is explicitly set.
# Return
- A newly allocated nested structure composed of `Dict{keytype,Any}` and
`Vector{Any}` that mirrors the input shape but uses plain Julia containers.
# Notes
- The function treats any `AbstractDict` as a mapping source, so it works with
`JSON.Object`, `Dict`, `OrderedDict`, etc.
- Arrays are returned as `Vector{Any}` with their elements processed
recursively.
# Examples
```jldoctest
julia> using JSON
julia> d = Dict(
"a" => 4,
"b" => 6,
"c" => Dict(
"d"=>7,
:e=>Dict(
"f"=>"hey",
"g"=>Dict(
"world"=>[1, "2", 3, Dict(:dd=>4.7)]
)
)
)
)
julia jsonstring = JSON.json(d)
julia> A1 = JSON.parse(jsonstring) # A1 type is JSON.Object
julia> A2 = dictify(A1; keytype=String)
Dict{String,Any} with 3 entries:
"a" => 4
"b" => 6
"c" => Dict("d"=>7, "e"=>Dict("f"=>"hey", "g"=>Dict("world"=>[1, "2", 3, 4.7])))
julia> A3 = dictify(A1; keytype=Symbol)
Dict{Symbol,Any} with 3 entries:
:a => 4
:b => 6
:c => Dict(:d=>7, :e=>Dict("f"=>"hey", "g"=>Dict("world"=>[1, "2", 3, 4.7])))
julia> B1 = dictify(d; keytype=String)
Dict{String, Any} with 3 entries:
"""
function dictify(x; keytype::Type=Any)
# Dict-like objects
if x isa AbstractDict
# choose output key type container
out = Dict{keytype,Any}()
for (k,v) in x
if keytype === String
newk = string(k)
elseif keytype === Symbol
newk = Symbol(string(k))
else
newk = k
end
out[newk] = dictify(v; keytype=keytype)
end
return out
# Arrays / vectors: map elements recursively and return a Vector{Any}
elseif x isa AbstractArray
return [dictify(element; keytype=keytype) for element in x]
# everything else: return as-is (primitives, numbers, strings, etc.)
else
return x
end
end
+366 -130
View File
@@ -84,7 +84,7 @@ julia> config = Dict(
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"=>"CHATBOX",
"action"=>"CHAT_BOX",
"input"=>"What occasion are you buying the wine for?"
),
"observation_1" => ""
@@ -95,6 +95,174 @@ julia> output_thoughtDict = Dict(
- [] user storeinfo
"""
# function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
# ) where {T<:agent}
# println("\nExecuting YiemAgent decisionMaker()")
# # 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 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
# Your customer is coming into the store
# # Role
# 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.
# # 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.
# # 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
# 3. Obey your mentor's suggestions.
# # Responsibility Does NOT Include
# 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.
# # 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": "..."
# # Available Actions
# - **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.
# """
# requiredKeys = ["plan", "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 a.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 decisionMaker() 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)
# responsedict = nothing
# try
# _responsedict = JSON.parse(response)
# responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
# catch
# println("\nERROR YiemAgent decisionMaker() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# continue
# end
# # check whether all answer's key points are in responsedict
# ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
# if !ispass
# errornote = errormsg
# println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
# 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)
# return responsedict
# end
# error("DecisionMaker failed to generate a thought ", response)
# end
function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
) where {T<:agent}
println("\nExecuting YiemAgent decisionMaker()")
@@ -166,30 +334,40 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to
response = strip(response)
responsedict = nothing
try
_responsedict = JSON.parse(response)
responsedict = GeneralUtils.dictify(_responsedict, keytype=String)
catch
println("\nERROR YiemAgent decisionMaker() 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 decisionMaker() 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 decisionMaker() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
continue
end
if responsedict["action_name"] ["CHATBOX", "CHECKWINE", "PRESENTBOX", "ENDCONVERGUIDELINE"]
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(Dict(responsedict))
# println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# pprintln(responsedict)
return responsedict
end
@@ -246,7 +424,7 @@ function evaluator(a::T1, timeline, decisiondict, evaluateecontext
<You should follow the following guidelines>
- 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 ENDCONVERGUIDELINE tool.
- 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.
</You should follow the following guidelines>
<You should then respond to the user with>
1) trajectory_evaluation: Analyze the trajectory of a solution to answer the user's original question.
@@ -390,7 +568,7 @@ message => Dict(
"""
function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Object{String, Any}},
maximumMsg=50)
userinput = GeneralUtils.dictify(userinput; keytype=String)
userinput = GeneralUtils.dictify(userinput; keytype=String, sort_order=["text"])
# find text in usermsg
usertext = nothing
@@ -419,7 +597,7 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj
chatresponse = nothing
while chatresponse === nothing
action_name, result = think(a)
if action_name ["CHATBOX"]
if action_name ["CHAT_BOX"]
chatresponse = result
end
end
@@ -452,7 +630,7 @@ function conversation(a::Union{companion, virtualcustomer}, userinput::Dict;
event_description="the user talks to the assistant.",
timestamp=Dates.now(),
subject="user",
action_name="CHATBOX",
action_name="CHAT_BOX",
action_input=userinput["text"],
)
)
@@ -465,7 +643,7 @@ function conversation(a::Union{companion, virtualcustomer}, userinput::Dict;
event_description="the assistant talks to the user.",
timestamp=Dates.now(),
subject="assistant",
action_name="CHATBOX",
action_name="CHAT_BOX",
action_input=chatresponse,
)
)
@@ -484,17 +662,21 @@ julia>
```
"""
function think(a::T)::Union{NamedTuple{(:action_name, :result), Tuple{String, String}}, NamedTuple{(:action_name, :result), Tuple{String, Nothing}}} where {T<:agent}
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("---")
# # map action and input() to llm function
# response =
# if thoughtDict["action_name"] == "CHATBOX" || thoughtDict["action_name"] == "ENDCONVERGUIDELINE"
# if thoughtDict["action_name"] == "CHAT_BOX" || thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
# (result=thoughtDict["plan"], errormsg=nothing, success=true)
# elseif thoughtDict["action_name"] == "CHECKWINE"
# elseif thoughtDict["action_name"] == "CHECK_WINE"
# checkwine(a, thoughtDict["action_input"])
# elseif thoughtDict["action_name"] == "PRESENTBOX"
# elseif thoughtDict["action_name"] == "PRESENT_WINE_GUIDELINE"
# (result=thoughtDict["action_input"], errormsg=nothing, success=true)
# else
# error("undefined LLM function. Requesting $(thoughtDict["action_name"])")
@@ -510,23 +692,23 @@ function think(a::T)::Union{NamedTuple{(:action_name, :result), Tuple{String, St
# success::Bool = haskey(response, "success") ? response["success"] : false
result = nothing
if thoughtDict["action_name"] ["CHATBOX"]
if thoughtDict["action_name"] ["CHAT_BOX"]
result = thoughtDict["action_input"]
elseif thoughtDict["action_name"] == "ENDCONVERGUIDELINE"
elseif thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
# add ENDCONVERGUIDELINE guideline in to scratchpad
endconversation_guideline =
# add guideline in to context
guideline =
"""
<end_conversation_guideline>
- Provide customer with store contact info and business hours
- Invite customer to comeback
- Provide customer with store contact info and business hours
- Invite customer to comeback
<store_info>
Business Hours: everyday 9.00-20.00
Tel. 0863055790
</store_info>
</end_conversation_guideline>
<store_info>
Business Hours: everyday 9.00-20.00
Tel. 0863055790
</store_info>
"""
thoughtDict["action_result"] = endconversation_guideline
thoughtDict["action_result"] = guideline
max_ind =
if length(a.memory["shortmem"]) == 0
0
@@ -536,13 +718,59 @@ function think(a::T)::Union{NamedTuple{(:action_name, :result), Tuple{String, St
end
a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
elseif thoughtDict["action_name"] ["PRESENTBOX"] #PENDING
chatresponse = presentbox(a, thoughtDict)
result = chatresponse
elseif thoughtDict["action_name"] ["PRESENT_WINE_GUIDELINE"] #WORKING
elseif thoughtDict["action_name"] == "CHECKWINE"
df = checkwine(a, thoughtDict["action_input"])
thoughtDict["action_result"] = GeneralUtils.dfToString(df)
# add guideline in to context
guideline =
"""
<wine_presentation_guideline>
- Provide detailed introductions of the wines you've found to the user.
- Explain how the wine could match the user's intention and what its effects might mean for the user's experience.
- If multiple wines are available, highlight their differences and provide a comprehensive comparison of how each option aligns with the user's intention and what the potential effects of each option could mean for the user's experience.
- Provide your personal recommendation and provide a brief explanation of why you recommend it.
- People don't describe wine quality level in numbers so use convertion_table if neccessary
<conversion_table>
Intensity level:
1 to 2: May correspond to "light-bodied" or a similar description.
2 to 3: May correspond to "med light bodied", "medium light" or a similar description.
3 to 4: May correspond to "medium bodied" or a similar description.
4 to 5: May correspond to "med full bodied", "medium full" or a similar description.
4 to 5: May correspond to "full bodied" or a similar description.
Sweetness level:
1 to 2: May correspond to "dry", "no sweet" or a similar description.
2 to 3: May correspond to "off dry", "less sweet" or a similar description.
3 to 4: May correspond to "semi sweet" or a similar description.
4 to 5: May correspond to "sweet" or a similar description.
4 to 5: May correspond to "very sweet" or a similar description.
Tannin level:
1 to 2: May correspond to "low tannin" or a similar description.
2 to 3: May correspond to "semi low tannin" or a similar description.
3 to 4: May correspond to "medium tannin" or a similar description.
4 to 5: May correspond to "semi high tannin" or a similar description.
4 to 5: May correspond to "high tannin" or a similar description.
Acidity level:
1 to 2: May correspond to "low acidity" or a similar description.
2 to 3: May correspond to "semi low acidity" or a similar description.
3 to 4: May correspond to "medium acidity" or a similar description.
4 to 5: May correspond to "semi high acidity" or a similar description.
4 to 5: May correspond to "high acidity" or a similar description.
</conversion_table>
</wine_presentation_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"
result = checkwine(a, thoughtDict["action_input"])
thoughtDict["action_result"] = result[:result_str]
max_ind =
if length(a.memory["shortmem"]) == 0
0
@@ -555,6 +783,9 @@ function think(a::T)::Union{NamedTuple{(:action_name, :result), Tuple{String, St
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)
end
@@ -562,27 +793,32 @@ end
function presentbox(a::sommelier, thoughtDict; maxtattempt::Integer=10, recentevents::Integer=10)
recentchat_ind = GeneralUtils.recentElementsIndex(length(a.chathistory), recentevents;
includelatest=true)
recentchat = createChatLog(a.chathistory; index=recentchat_ind)
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>
<Situation>
You have checked the inventory and found wines that may match what the user wants
</Situation>
<Your mission>
<objective>
Present the wines to the user in a way that keep the conversation smooth and engaging.
</Your mission>
</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>
- Provide detailed introductions of the wines you've found to the user.
- Explain how the wine could match the user's intention and what its effects might mean for the user's experience.
- If multiple wines are available, highlight their differences and provide a comprehensive comparison of how each option aligns with the user's intention and what the potential effects of each option could mean for the user's experience.
- Provide your personal recommendation and provide a brief explanation of why you recommend it.
</You should follow the following guidelines>
<You should then respond to the user with>
dialogue: Your presentation to the user
@@ -715,102 +951,102 @@ function presentbox(a::sommelier, thoughtDict; maxtattempt::Integer=10, recentev
error("presentbox() failed to generate a response")
end
function endconversation(a::sommelier, thoughtDict; maxattempt::Integer=10)
text =
"""
---
# function endconversation(a::sommelier, thoughtDict; maxattempt::Integer=10)
# text =
# """
# ---
"""
requiredKeys = ["dialogue"]
# """
# requiredKeys = ["dialogue"]
system_msg = Dict(
"role" => "system",
"content" => [
Dict("type" => "text", "text" => systemmsg),
]
)
# system_msg = Dict(
# "role" => "system",
# "content" => [
# Dict("type" => "text", "text" => systemmsg),
# ]
# )
for attempt in 1:maxattempt
# for attempt in 1:maxattempt
unformatPrompt =
[
Dict("name" => "system", "text" => systemmsg),
]
# unformatPrompt =
# [
# Dict("name" => "system", "text" => systemmsg),
# ]
# put in model format
prompt = GeneralUtils.formatLLMtext(unformatPrompt, a.llmFormatName)
# add info
prompt = prompt * context
# # 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 = 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
# 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
# # 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|>"=>"")
# # 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 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
# # 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"]
# # 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
# return result
# end
# error("generatechat failed to generate a response")
# end
function generatequestion(a, text2textInstructLLM::Function, timeline)::String
+58 -41
View File
@@ -290,46 +290,62 @@ function checkwine(a::T1, input::T2; maxattempt::Int=3
wineattributes_2 = extractWineAttributes_2(a, input)
# placeholder
textresult = nothing
rawresponse = nothing
# textresult = nothing
# rawresponse = nothing
for i in 1:maxattempt
# for i in 1:maxattempt
#CHANGE if you want to add retailer name
# #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"
_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 = "$wineattributes_1, $wineattributes_2"
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")
# println("\n--- YiemAgent checkwine() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# println(textresult)
# println(result_raw)
# println("---")
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
#WORKING
textresult, rawresponse = SQLLLM.query(
inventoryquery,
a.context.executeSQL,
a.context.text2textInstructLLM;
insertSQLVectorDB=a.context.insertSQLVectorDB,
similarSQLVectorDB=a.context.similarSQLVectorDB,
llmFormatName="qwen3")
error(5555)
# 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(rawresponse) == 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
println("\ncheckinventory result ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
println(textresult)
return (result=textresult, rawresponse=rawresponse, success=true, errormsg=nothing)
return (result_str=textresult, result_raw=result_raw, success=true, errormsg=nothing)
end
@@ -466,13 +482,13 @@ function extractWineAttributes_1(a::T1, input::T2; maxattempt=10
responsedict = nothing
try
_responsedict = JSON.parse(response)
responsedict = GeneralUtils.dictify(_responsedict, keytype=String)
responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
catch
println("\nERROR YiemAgent extractWineAttributes_1() 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)
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
if !ispass
errornote = errormsg
println("\nERROR YiemAgent extractWineAttributes_1() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
@@ -659,13 +675,14 @@ function extractWineAttributes_2(a::T1, input::T2)::String where {T1<:agent, T2<
responsedict = nothing
try
_responsedict = JSON.parse(response)
responsedict = GeneralUtils.dictify(_responsedict, keytype=String)
responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
catch
println("\nERROR YiemAgent extractWineAttributes_2() 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)
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
if !ispass
errornote = errormsg
println("\nERROR YiemAgent extractWineAttributes_2() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
@@ -919,7 +936,7 @@ end
# "thought" is step-by-step reasoning about the current situation.
# "plan" is what to do to complete the task from the current situation.
# “action_name” is the name of the action taken, which can be one of the following functions:
# 1) CHATBOX[text], which you can use to talk with the user. "text" is in verbal English.
# 1) CHAT_BOX[text], which you can use to talk with the user. "text" is in verbal English.
# 2) WINESTOCK[query], which you can use to find info about wine in your inventory. "query" is a search term in verbal English. The best query must includes "budget", "type of wine", "characteristics of wine" and "food pairing".
# "action_input" is the input to the action
# "observation" is result of the preceding immediate action.
+13 -13
View File
@@ -54,8 +54,8 @@ function companion(
)
tools = Dict( # update input format
"CHATBOX"=> Dict(
"description" => "- CHATBOX which you can use to talk with the user. The input is your intentions for the dialogue. Be specific.",
"CHAT_BOX"=> Dict(
"description" => "- CHAT_BOX which you can use to talk with the user. The input is your intentions for the dialogue. Be specific.",
),
)
@@ -247,16 +247,7 @@ 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.
</store_guidelines>Search the database as broad as possible under the informantion you have will increase the chance to find wine. Avoid uneccessary parameter such as region, country, tasting notes unless the user specify
<available_actions>
- CHATBOX which you can use to talk with the user. Be specific.
- CHECKWINE allows you to check information about wines you want in your inventory's database. The input must be supported search criteria includeing: 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
- PRESENTBOX which you can use to to generate proper dialogue to present wines you have found in your inventory to the user. The input are wine names that you want to present. The output is presentation of the wines.
- ENDCONVERGUIDELINE 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>
</store_guidelines>
<situation>
Your customer is coming into the store
</situation>
@@ -278,7 +269,7 @@ function sommelier(
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. Be specific.
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.
@@ -288,6 +279,15 @@ function sommelier(
"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.
- 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>
"""
system_msg = Dict(
+38 -23
View File
@@ -223,7 +223,7 @@ function eventdict(;
timestamp::Union{DateTime, Nothing}=nothing,
subject::Union{String, Nothing}=nothing,
thought::Union{AbstractDict, Nothing}=nothing,
action_name::Union{String, Nothing}=nothing, # "CHAT", "CHECKINVENTORY", "PRESENTBOX", etc
action_name::Union{String, Nothing}=nothing, # "CHAT", "CHECKINVENTORY", "PRESENT_WINE_GUIDELINE", etc
action_input::Union{String, Nothing}=nothing,
location::Union{String, Nothing}=nothing,
equipment_used::Union{String, Nothing}=nothing,
@@ -293,11 +293,11 @@ function createTimeline(events::T1; eventindex::Union{UnitRange, Nothing}=nothin
for i in ind
event = events[i]
# If no outcome exists, format without outcome
# if event["action_name"] == "CHATBOX"
# if event["action_name"] == "CHAT_BOX"
# timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"])\n"
# elseif event["action_name"] == "CHECKINVENTORY" && event["observation"] === nothing
# timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"]), observation: Not done yet.\n"
if event["action_name"] == "CHECKWINE"
if event["action_name"] == "CHECK_WINE"
timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"]), observation: $(event["observation"])\\n"
else
timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"])\\n"
@@ -392,26 +392,41 @@ function checkAgentResponse_text(response::String, requiredHeader::T
end
function checkAgentResponse_JSON(responsedict::Dict, requiredKeys::T
)::Tuple where {T<:Array{String}}
_responsedictKey = keys(responsedict)
responsedictKey = [i for i in _responsedictKey] # convert into a list
is_requiredKeys_in_responsedictKey = [i responsedictKey for i in requiredKeys]
ispass = false
errormsg = nothing
if length(is_requiredKeys_in_responsedictKey) > length(requiredKeys)
errormsg = "Your previous attempt has duplicated points according to the required response format"
ispass = false
elseif !all(is_requiredKeys_in_responsedictKey)
zeroind = findall(x -> x == 0, is_requiredKeys_in_responsedictKey)
missingkeys = [requiredKeys[i] for i in zeroind]
errormsg = "$missingkeys are missing from your previous response"
ispass = false
else
ispass = true
end
return (ispass, errormsg)
end
+80 -21
View File
@@ -6,17 +6,18 @@ config = JSON.parsefile("./appconfig.json")
agent_conn = NATS.connect(config["nats_server_info"]["url"])
function text2text_instruct_llm(openai_msg::AbstractDict)
function text2text_instruct_llm(sender_id::String, openai_msg::Dict{String, Any})
payloads = [("msg", openai_msg, "dictionary")] # List of tuples
_, msg_envelope_json_str = msghandler.smartpack(
config["externalService"]["servicesloadbalancer"]["nats"],
config["externalservice"]["servicesloadbalancer"]["nats"],
payloads;
sender_id=sender_id,
msg_purpose="text2text",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalService"]["fileserver"]["url"])
fileserver_url=config["externalservice"]["fileserver"]["url"])
reply = NATS.request(agent_conn,
config["externalService"]["servicesloadbalancer"]["nats"],
config["externalservice"]["servicesloadbalancer"]["nats"],
msg_envelope_json_str, timeout=120)
incoming_env_json_str = String(reply.payload)
@@ -61,7 +62,7 @@ llm_response = text2text_instruct_llm(openai_msg)
# 1. Read local file and encode to base64 string
image2_path = "test/small_image.png"
image2_path = "test/large_image.png"
image2_bytes = read(image2_path)
image2_base64_string = base64encode(image2_bytes)
@@ -69,44 +70,102 @@ image2_base64_string = base64encode(image2_bytes)
mime_type = "image/png"
data2_uri = "data:$(mime_type);base64,$(image2_base64_string)"
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 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
Your customer is coming into the store
# Role
Your name is Janie. You are a helpful sommelier for website-based Yiem Wine's wine store. You are working under your mentor supervision.
# 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.
# 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
3. Obey your mentor's suggestions.
# Responsibility Does NOT Include
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.
# 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": "..."
# Available Actions
- **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.
"""
openai_msg = Dict(
"model" => "gemma-4-E4B-it-UD-Q4_K_XL",
"messages" => [
Dict(
"role" => "user",
"role" => "system",
"content" => [
Dict("type" => "text", "text" => "Do you know this wine? Just give me brief intro."),
Dict(
"type" => "image_url",
"image_url" => Dict("url" => data1_uri)
)
Dict("type" => "text", "text" => systemmsg),
]
),
Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => "Do you know this wine? Just give me brief intro."),
Dict(
"type" => "image_url",
"image_url" => Dict("url" => data1_uri)
)
]
),
Dict(
"role" => "assistant",
"content" => [
Dict("type" => "text", "text" => "Yes, I do!\n\nThis is **Asolo Bella Principessa**, a high-quality Italian sparkling wine made from the Prosecco region.\n\n### 🥂 Brief Intro\n\n* **What it is:** A Prosecco Superiore D.O.C.G., meaning it meets strict quality standards for a premium sparkling wine.\n* **Style:** It is a **Sparkling White Wine** and is designated as **Extra Dry**. This means it is crisp, refreshing, and has a dry finish (not overly sweet).\n* **Flavor Profile:** Expect bright, lively bubbles, often with notes of green apple, pear, and citrus.\n* **Best For:** It's a versatile wine, perfect for celebratory toasts, enjoying with appetizers (like seafood or charcuterie), or simply as a refreshing aperitivo."),
Dict("type" => "text", "text" =>
"""
" <plan>I will greet the customer warmly as Janie, acknowledge their request to find a similar wine for their wedding party based on the image, identify the wine type and country (Italian Sparkling Wine), and then use the CHECK_WINE action to search the inventory for suitable options.</plan>\n <action_name>CHAT_BOX</action_name>\n <action_input>Hello! I'm Janie, and I'd be delighted to help you find the perfect wine for your wedding party. That beautiful wine in the image appears to be an Italian sparkling wine, which is wonderful for a celebration like a wedding! Since you have an unlimited budget, I can certainly look for some truly exceptional options. To start, I will check our inventory for similar Italian sparkling wines that are perfect for a wedding celebration.</action_input><action_result> User response in the next message </action_result>"
"""
),
]
),
Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => "How does this wine differ from earlier wine?"),
Dict(
"type" => "image_url",
"image_url" => Dict("url" => data2_uri)
)
Dict("type" => "text", "text" => "ok"),
]
),
],
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB