Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cd6f6ef961 | |||
| fdec34832d | |||
| 3c72373b85 | |||
| 688a8c4df2 | |||
| 8bd4986be2 | |||
| 6e5809fc9b | |||
| 2b7c0041e5 | |||
| 9ff0b48eec | |||
| afeb4c7aef | |||
| 2942a89730 | |||
| 6a66f58e63 | |||
| 1d0353d793 | |||
| 0f6aa7c79f | |||
| 0320fd321f | |||
| c29dccf597 | |||
| 70cf04b0db | |||
| 4d57f0146b | |||
| d33aa14dc8 | |||
| 0ed3edd48a | |||
| fb91b51573 | |||
| 0bbd227920 | |||
| 3487770f77 | |||
| 7d27f9e567 | |||
| 511b4d682d | |||
| 5ba91d8acc | |||
| 709f7e7115 |
+8
-55
@@ -2,7 +2,7 @@
|
||||
|
||||
julia_version = "1.12.6"
|
||||
manifest_format = "2.0"
|
||||
project_hash = "5b5e1c071ff66b72aeed7d8a4316829e2407ae1a"
|
||||
project_hash = "a2c996ffe370e277cbff80af974d2701698f1b6c"
|
||||
|
||||
[[deps.Accessors]]
|
||||
deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"]
|
||||
@@ -38,12 +38,6 @@ version = "1.1.3"
|
||||
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
|
||||
version = "1.1.2"
|
||||
|
||||
[[deps.Arrow]]
|
||||
deps = ["ArrowTypes", "BitIntegers", "CodecLz4", "CodecZstd", "ConcurrentUtilities", "DataAPI", "Dates", "EnumX", "Mmap", "PooledArrays", "SentinelArrays", "StringViews", "Tables", "TimeZones", "TranscodingStreams", "UUIDs"]
|
||||
git-tree-sha1 = "4a69a3eadc1f7da78d950d1ef270c3a62c1f7e01"
|
||||
uuid = "69666777-d1a9-59fb-9406-91d4454c9d45"
|
||||
version = "2.8.1"
|
||||
|
||||
[[deps.ArrowTypes]]
|
||||
deps = ["Sockets", "UUIDs"]
|
||||
git-tree-sha1 = "404265cd8128a2515a81d5eae16de90fdef05101"
|
||||
@@ -58,12 +52,6 @@ version = "1.11.0"
|
||||
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
|
||||
version = "1.11.0"
|
||||
|
||||
[[deps.BitIntegers]]
|
||||
deps = ["Random"]
|
||||
git-tree-sha1 = "091d591a060e43df1dd35faab3ca284925c48e46"
|
||||
uuid = "c3b6d118-76ef-56ca-8cc7-ebb389d030a1"
|
||||
version = "0.3.7"
|
||||
|
||||
[[deps.BufferedStreams]]
|
||||
git-tree-sha1 = "6863c5b7fc997eadcabdbaf6c5f201dc30032643"
|
||||
uuid = "e1450e63-4bb3-523b-b2a4-4ffa8c0fd77d"
|
||||
@@ -96,24 +84,12 @@ git-tree-sha1 = "40956acdbef3d8c7cc38cba42b56034af8f8581a"
|
||||
uuid = "6c391c72-fb7b-5838-ba82-7cfb1bcfecbf"
|
||||
version = "0.3.4"
|
||||
|
||||
[[deps.CodecLz4]]
|
||||
deps = ["Lz4_jll", "TranscodingStreams"]
|
||||
git-tree-sha1 = "d58afcd2833601636b48ee8cbeb2edcb086522c2"
|
||||
uuid = "5ba52731-8f18-5e0d-9241-30f10d1ec561"
|
||||
version = "0.4.6"
|
||||
|
||||
[[deps.CodecZlib]]
|
||||
deps = ["TranscodingStreams", "Zlib_jll"]
|
||||
git-tree-sha1 = "962834c22b66e32aa10f7611c08c8ca4e20749a9"
|
||||
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
|
||||
version = "0.7.8"
|
||||
|
||||
[[deps.CodecZstd]]
|
||||
deps = ["TranscodingStreams", "Zstd_jll"]
|
||||
git-tree-sha1 = "da54a6cd93c54950c15adf1d336cfd7d71f51a56"
|
||||
uuid = "6b39b394-51ab-5f42-8807-6242bab2b4c2"
|
||||
version = "0.8.7"
|
||||
|
||||
[[deps.CommonSolve]]
|
||||
git-tree-sha1 = "99ee296f88c12485402e37c2fd025f95ae097637"
|
||||
uuid = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2"
|
||||
@@ -148,12 +124,6 @@ weakdeps = ["InverseFunctions"]
|
||||
[deps.CompositionsBase.extensions]
|
||||
CompositionsBaseInverseFunctionsExt = "InverseFunctions"
|
||||
|
||||
[[deps.ConcurrentUtilities]]
|
||||
deps = ["Serialization", "Sockets"]
|
||||
git-tree-sha1 = "21d088c496ea22914fe80906eb5bce65755e5ec8"
|
||||
uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb"
|
||||
version = "2.5.1"
|
||||
|
||||
[[deps.ConstructionBase]]
|
||||
git-tree-sha1 = "b4b092499347b18a015186eae3042f72267106cb"
|
||||
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
|
||||
@@ -436,7 +406,9 @@ version = "1.21.3+0"
|
||||
|
||||
[[deps.LLMMCTS]]
|
||||
deps = ["GeneralUtils", "JSON", "PrettyPrinting"]
|
||||
path = "../LLMMCTS"
|
||||
git-tree-sha1 = "3dff98131dfa79be8c9bd84fc51cb0ba1832c472"
|
||||
repo-rev = "main"
|
||||
repo-url = "https://git.yiem.cc/ton/LLMMCTS"
|
||||
uuid = "d76c5a4d-449e-4835-8cc4-dd86ec44f241"
|
||||
version = "0.1.5"
|
||||
|
||||
@@ -522,12 +494,6 @@ git-tree-sha1 = "3733419e9a71156b389f3e331672d2e95436783f"
|
||||
uuid = "6f1432cf-f94c-5a45-995e-cdbf5db27b0b"
|
||||
version = "3.6.2"
|
||||
|
||||
[[deps.Lz4_jll]]
|
||||
deps = ["Artifacts", "JLLWrappers", "Libdl"]
|
||||
git-tree-sha1 = "191686b1ac1ea9c89fc52e996ad15d1d241d1e33"
|
||||
uuid = "5ced341a-0733-55b8-9ab6-a4889d929147"
|
||||
version = "1.10.1+0"
|
||||
|
||||
[[deps.MacroTools]]
|
||||
git-tree-sha1 = "1e0228a030642014fe5cfe68c2c0a818f9e3f522"
|
||||
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
|
||||
@@ -794,11 +760,11 @@ version = "0.7.0"
|
||||
|
||||
[[deps.SQLLLM]]
|
||||
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "FileIO", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "PrettyPrinting", "Random", "Revise", "StatsBase", "Tables", "URIs", "UUIDs"]
|
||||
git-tree-sha1 = "997602ed56a285ac29d74c91bb57bc5faeadfad6"
|
||||
git-tree-sha1 = "2807a768907f59308d8d71ece599037b0a66b0a5"
|
||||
repo-rev = "main"
|
||||
repo-url = "https://git.yiem.cc/ton/SQLLLM"
|
||||
uuid = "2ebc79c7-cc10-4a3a-9665-d2e1d61e63d3"
|
||||
version = "0.2.5"
|
||||
version = "0.2.7"
|
||||
|
||||
[[deps.SQLStrings]]
|
||||
git-tree-sha1 = "55de0530689832b1d3d43491ee6b67bd54d3323c"
|
||||
@@ -902,11 +868,6 @@ git-tree-sha1 = "d05693d339e37d6ab134c5ab53c29fce5ee5d7d5"
|
||||
uuid = "892a3eda-7b42-436c-8928-eab12a02cf0e"
|
||||
version = "0.4.4"
|
||||
|
||||
[[deps.StringViews]]
|
||||
git-tree-sha1 = "f2dcb92855b31ad92fe8f079d4f75ac57c93e4b8"
|
||||
uuid = "354b36f9-a18e-4713-926e-db85100087ba"
|
||||
version = "1.3.7"
|
||||
|
||||
[[deps.StructTypes]]
|
||||
deps = ["Dates", "UUIDs"]
|
||||
git-tree-sha1 = "159331b30e94d7b11379037feeb9b690950cace8"
|
||||
@@ -1022,10 +983,10 @@ 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", "SQLLLM", "Serialization", "URIs", "UUIDs", "msghandler"]
|
||||
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "Serialization", "URIs", "UUIDs"]
|
||||
path = "."
|
||||
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
|
||||
[[deps.Zlib_jll]]
|
||||
deps = ["Libdl"]
|
||||
@@ -1049,14 +1010,6 @@ git-tree-sha1 = "011b0a7331b41c25524b64dc42afc9683ee89026"
|
||||
uuid = "a9144af2-ca23-56d9-984f-0d03f7b5ccf8"
|
||||
version = "1.0.21+0"
|
||||
|
||||
[[deps.msghandler]]
|
||||
deps = ["Arrow", "Base64", "DataFrames", "Dates", "GeneralUtils", "HTTP", "JSON", "NATS", "PrettyPrinting", "Revise", "UUIDs"]
|
||||
git-tree-sha1 = "db16f76f72bd4fa2a87e34ef47bb787204e1f888"
|
||||
repo-rev = "main"
|
||||
repo-url = "https://git.yiem.cc/ton/msghandler"
|
||||
uuid = "f2724d33-f338-4a57-b9f8-1be882570d10"
|
||||
version = "0.5.7"
|
||||
|
||||
[[deps.nghttp2_jll]]
|
||||
deps = ["Artifacts", "Libdl"]
|
||||
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
|
||||
|
||||
+3
-4
@@ -1,6 +1,6 @@
|
||||
name = "YiemAgent"
|
||||
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
authors = ["narawat lamaiin <narawat@outlook.com>"]
|
||||
|
||||
[deps]
|
||||
@@ -21,7 +21,6 @@ SQLLLM = "2ebc79c7-cc10-4a3a-9665-d2e1d61e63d3"
|
||||
Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
|
||||
URIs = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
|
||||
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
|
||||
msghandler = "f2724d33-f338-4a57-b9f8-1be882570d10"
|
||||
|
||||
[compat]
|
||||
CSV = "0.10.15"
|
||||
@@ -29,6 +28,6 @@ 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"
|
||||
msghandler = "0.5.6"
|
||||
SQLLLM = "0.2.7"
|
||||
|
||||
@@ -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__
|
||||
+241
-575
@@ -60,212 +60,22 @@ end
|
||||
# Keyword Arguments
|
||||
|
||||
# Return
|
||||
- `thoughtDict::Dict`
|
||||
- `thoughtdict::Dict`
|
||||
|
||||
# Example
|
||||
```jldoctest
|
||||
julia> config = Dict(
|
||||
"mqttServerInfo" => Dict(
|
||||
"description" => "mqtt server info",
|
||||
"port" => 1883,
|
||||
"broker" => "mqtt.yiem.cc"
|
||||
),
|
||||
"externalservice" => Dict(
|
||||
"text2textinstruct" => Dict(
|
||||
"mqtttopic" => "/loadbalancer/requestingservice",
|
||||
"description" => "text to text service with instruct LLM",
|
||||
"llminfo" => Dict(
|
||||
"name" => "llama3instruct"
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
julia> result = decisionMaker(agent)
|
||||
|
||||
julia> output_thoughtDict = Dict(
|
||||
"thought_1" => "The customer wants to buy a bottle of wine. This is a good start!",
|
||||
"action_1" => Dict{String, Any}(
|
||||
"action"=>"CHAT_BOX",
|
||||
"input"=>"What occasion are you buying the wine for?"
|
||||
),
|
||||
"observation_1" => ""
|
||||
)
|
||||
OrderedDict{String, Any} with 4 entries:
|
||||
"plan" => "The user provided an image of a sparkling white wine (Asolo Prosecco Bella Principessa from Italy) and requested a search for similar wines in the inventory. According to store guidelines, I must st…
|
||||
"action_name" => "CHECK_WINE"
|
||||
"action_input" => "Sparkling white wine from Italy"
|
||||
"action_result" => "1) winery: Terrazze dell Etna, wine_name: Rose Brut.
|
||||
```
|
||||
- [] update docstring
|
||||
- [] use customerinfo
|
||||
- [] user storeinfo
|
||||
|
||||
"""
|
||||
# function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
|
||||
# ) where {T<:agent}
|
||||
# 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()")
|
||||
|
||||
# lessonDict = copy(JSON.parsefile("lesson.json"))
|
||||
|
||||
# lesson =
|
||||
@@ -298,9 +108,6 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
|
||||
context =
|
||||
"""
|
||||
<internal_context_for_assistant>
|
||||
<thought_history>
|
||||
$(GeneralUtils.dict_to_string_html(a.memory["shortmem"]))
|
||||
</thought_history>
|
||||
</internal_context_for_assistant>
|
||||
"""
|
||||
|
||||
@@ -328,11 +135,16 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
|
||||
|
||||
response = a.context.text2textInstructLLM(a.id, msg)
|
||||
response = GeneralUtils.clean_json_response(response)
|
||||
|
||||
response = GeneralUtils.remove_french_accents(response)
|
||||
think, response = GeneralUtils.extractthink(response)
|
||||
response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to
|
||||
response = strip(response)
|
||||
|
||||
# dollar sign in Julia means string interpolation
|
||||
while occursin('$', response)
|
||||
response = replace(response, '$' => "USD")
|
||||
end
|
||||
|
||||
responsedict = nothing
|
||||
if occursin(requiredKeys[2], response)
|
||||
try
|
||||
@@ -345,26 +157,31 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
|
||||
|
||||
# fall back to normal text because LLM default to natural chat when it didn't use action_call
|
||||
else
|
||||
try
|
||||
responsedict = OrderedDict(
|
||||
"plan"=> "I will talk to the user",
|
||||
"action_name"=> "CHAT_BOX",
|
||||
"action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response
|
||||
)
|
||||
catch e
|
||||
println("\nERROR YiemAgent decisionMaker(). $e --(not qualify response)-> $response", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
continue
|
||||
end
|
||||
end
|
||||
|
||||
# check whether all answer's key points are in responsedict
|
||||
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
if !ispass
|
||||
errornote = errormsg
|
||||
println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)-> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
continue
|
||||
end
|
||||
|
||||
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)
|
||||
@@ -459,9 +276,9 @@ function evaluator(a::T1, timeline, decisiondict, evaluateecontext
|
||||
context =
|
||||
"""
|
||||
<context>
|
||||
<trajectory>
|
||||
<assistant_trajectories>
|
||||
$timeline
|
||||
</trajectory>
|
||||
</assistant_trajectories>
|
||||
<evaluatee_context>
|
||||
$evaluateecontext
|
||||
</evaluatee_context>
|
||||
@@ -510,36 +327,11 @@ function evaluator(a::T1, timeline, decisiondict, evaluateecontext
|
||||
|
||||
println("\nEvaluator() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(Dict(responsedict))
|
||||
|
||||
# # read sessionId
|
||||
# sessionid = a.id
|
||||
# # save to filename ./log/decisionlog.txt
|
||||
# println("saving SQLLLM evaluator() to disk")
|
||||
# filename = "agent_evaluator_log_$(sessionid[:id]).json"
|
||||
# filepath = "/appfolder/app/log/$filename"
|
||||
# # check whether there is a file path exists before writing to it
|
||||
# if !isfile(filepath)
|
||||
# decisionlist = [responsedict]
|
||||
# println("Creating file $filepath")
|
||||
# open(filepath, "w") do io
|
||||
# JSON.pretty(io, decisionlist)
|
||||
# end
|
||||
# else
|
||||
# # read the file and append new data
|
||||
# decisionlist = copy(JSON.parsefile(filepath))
|
||||
# push!(decisionlist, responsedict)
|
||||
# println("Appending new data to file $filepath")
|
||||
# open(filepath, "w") do io
|
||||
# JSON.pretty(io, decisionlist)
|
||||
# end
|
||||
# end
|
||||
|
||||
return responsedict
|
||||
end
|
||||
error("Evaluator failed to generate an evaluation, Response: \n$response\n<|End of error|>")
|
||||
end
|
||||
|
||||
|
||||
""" Chat with llm.
|
||||
|
||||
# Example userinput
|
||||
@@ -564,92 +356,72 @@ message => Dict(
|
||||
]
|
||||
)
|
||||
|
||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
||||
"""
|
||||
function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Object{String, Any}},
|
||||
maximumMsg=50)
|
||||
maximumMsg=50, max_think_loop::Integer=3)
|
||||
|
||||
@info "YiemAgent conversation() 1 " @__LINE__
|
||||
userinput = GeneralUtils.dictify(userinput; keytype=String, sort_order=["text"])
|
||||
|
||||
# find text in usermsg
|
||||
usertext = nothing
|
||||
text_position = nothing
|
||||
for (i, d) in enumerate(userinput["content"])
|
||||
if d["type"] == "text"
|
||||
d["text"] = GeneralUtils.remove_french_accents(d["text"])
|
||||
usertext = d["text"]
|
||||
text_position = i
|
||||
end
|
||||
end
|
||||
|
||||
# place holder
|
||||
action_name = nothing
|
||||
result = nothing
|
||||
chatresponse = nothing
|
||||
|
||||
if usertext == "newtopic"
|
||||
clearhistory(a)
|
||||
return "Okay. What shall we talk about?"
|
||||
else
|
||||
userinput["content"][text_position]["text"] = GeneralUtils.remove_french_accents(usertext)
|
||||
@info "YiemAgent conversation() 2 " @__LINE__
|
||||
# add usermsg to a.chathistory but how do I handle images?
|
||||
addNewMessage(a, "user", userinput; maximumMsg=maximumMsg)
|
||||
|
||||
# thinking loop until AI wants to communicate with the user
|
||||
chatresponse = nothing
|
||||
while chatresponse === nothing
|
||||
action_name, result = think(a)
|
||||
if action_name ∈ ["CHAT_BOX"]
|
||||
chatresponse = result
|
||||
end
|
||||
loopcount = 0
|
||||
while true
|
||||
loopcount += 1
|
||||
if loopcount > max_think_loop
|
||||
@info "YiemAgent conversation() 2-1 think count $loopcount " @__LINE__
|
||||
r = generatechat!(a)
|
||||
@info "YiemAgent conversation() 2-2 think count $loopcount " @__LINE__
|
||||
return r
|
||||
end
|
||||
|
||||
@info "YiemAgent conversation() 2-3 think count $loopcount " @__LINE__
|
||||
thoughtdict, _ = think(a)
|
||||
if thoughtdict["action_name"] ∈ ["CHAT_BOX"]
|
||||
@info "YiemAgent conversation() 2-4 think count $loopcount " @__LINE__
|
||||
assistant_response = Dict{String, Any}(
|
||||
"role" => "assistant",
|
||||
"content" => [Dict("type" => "text", "text" => chatresponse),]
|
||||
"content" => [Dict("type" => "text", "text" => thoughtdict["action_input"]),]
|
||||
)
|
||||
addNewMessage(a, "assistant", assistant_response; maximumMsg=maximumMsg)
|
||||
return thoughtdict["action_input"]
|
||||
|
||||
return chatresponse
|
||||
end
|
||||
end
|
||||
|
||||
function conversation(a::Union{companion, virtualcustomer}, userinput::Dict;
|
||||
converPartnerName::Union{String, Nothing}=nothing,
|
||||
maximumMsg=50)
|
||||
|
||||
chatresponse = nothing
|
||||
|
||||
if userinput["text"] == "newtopic"
|
||||
clearhistory(a)
|
||||
return "Okay. What shall we talk about?"
|
||||
else
|
||||
# add usermsg to a.chathistory
|
||||
addNewMessage(a, "user", userinput["text"]; maximumMsg=maximumMsg)
|
||||
action_name = thoughtdict["action_name"]
|
||||
action_input = thoughtdict["action_input"]
|
||||
action_call = Dict{String, Any}(
|
||||
"role" => "action_call",
|
||||
"content" => [Dict("type" => "text", "text" => "{action_name: $action_name, action_input: $action_input}"),]
|
||||
)
|
||||
addNewMessage(a, "action_call", action_call; maximumMsg=maximumMsg)
|
||||
|
||||
# add user activity to events memory
|
||||
push!(a.memory["events"],
|
||||
eventdict(;
|
||||
event_description="the user talks to the assistant.",
|
||||
timestamp=Dates.now(),
|
||||
subject="user",
|
||||
action_name="CHAT_BOX",
|
||||
action_input=userinput["text"],
|
||||
action_result = thoughtdict["action_result"]
|
||||
actionresult = Dict{String, Any}(
|
||||
"role" => "action_result",
|
||||
"content" => [Dict("type" => "text", "text" => "$action_result"),]
|
||||
)
|
||||
)
|
||||
chatresponse = generatechat(a; converPartnerName=converPartnerName, recentEventNum=20)
|
||||
|
||||
addNewMessage(a, "assistant", chatresponse; maximumMsg=maximumMsg)
|
||||
|
||||
push!(a.memory["events"],
|
||||
eventdict(;
|
||||
event_description="the assistant talks to the user.",
|
||||
timestamp=Dates.now(),
|
||||
subject="assistant",
|
||||
action_name="CHAT_BOX",
|
||||
action_input=chatresponse,
|
||||
)
|
||||
)
|
||||
return chatresponse
|
||||
addNewMessage(a, "actionresult", actionresult; maximumMsg=maximumMsg)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
"""
|
||||
# Arguments
|
||||
@@ -662,41 +434,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)
|
||||
thoughtDict = decisionMaker(a)
|
||||
thoughtdict = decisionMaker(a)
|
||||
@info "YiemAgent think() 1 " @__LINE__
|
||||
# pprintln(thoughtdict)
|
||||
|
||||
println("\n--- YiemAgent think() 1 ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(thoughtDict)
|
||||
println("---")
|
||||
result_raw = nothing
|
||||
if thoughtdict["action_name"] ∈ ["CHAT_BOX"]
|
||||
@info "YiemAgent think() 2 " @__LINE__
|
||||
thoughtdict, result_raw = generatechat!(a)
|
||||
|
||||
# # map action and input() to llm function
|
||||
# response =
|
||||
# if thoughtDict["action_name"] == "CHAT_BOX" || thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
|
||||
# (result=thoughtDict["plan"], errormsg=nothing, success=true)
|
||||
# elseif thoughtDict["action_name"] == "CHECK_WINE"
|
||||
# checkwine(a, thoughtDict["action_input"])
|
||||
# elseif thoughtDict["action_name"] == "PRESENT_WINE_GUIDELINE"
|
||||
# (result=thoughtDict["action_input"], errormsg=nothing, success=true)
|
||||
elseif thoughtdict["action_name"] == "END_CONVER_GUIDELINE"
|
||||
@info "YiemAgent think() 3 " @__LINE__
|
||||
thoughtdict, result_raw = end_conversation_guideline!(a, thoughtdict)
|
||||
|
||||
elseif thoughtdict["action_name"] ∈ ["WINE_PRESENTATION_GUIDELINE"]
|
||||
@info "YiemAgent think() 4 " @__LINE__
|
||||
thoughtdict, result_raw = wine_presentation_guideline!(a, thoughtdict)
|
||||
|
||||
|
||||
elseif thoughtdict["action_name"] == "CHECK_WINE"
|
||||
@info "YiemAgent think() 5 " @__LINE__
|
||||
thoughtdict, result_raw = checkwine!(a, thoughtdict; useSQLLLM=false)
|
||||
|
||||
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
|
||||
# error("undefined LLM function. Requesting $(thoughtDict["action_name"])")
|
||||
# k = keys(a.memory["shortmem"])
|
||||
# maximum(parse.(Int, k))
|
||||
# end
|
||||
# a.memory["shortmem"]["$(max_ind + 1)"] = thoughtdict
|
||||
|
||||
# # 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
|
||||
pprintln(thoughtdict)
|
||||
@info "YiemAgent think() 7 " @__LINE__
|
||||
return (thoughtdict=thoughtdict, result_raw=result_raw)
|
||||
end
|
||||
|
||||
result = nothing
|
||||
if thoughtDict["action_name"] ∈ ["CHAT_BOX"]
|
||||
result = thoughtDict["action_input"]
|
||||
elseif thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
|
||||
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}
|
||||
|
||||
# add guideline in to context
|
||||
guideline =
|
||||
"""
|
||||
<end_conversation_guideline>
|
||||
@@ -708,19 +497,14 @@ function think(a::T) where {T<:agent}
|
||||
</store_info>
|
||||
</end_conversation_guideline>
|
||||
"""
|
||||
thoughtDict["action_result"] = guideline
|
||||
max_ind =
|
||||
if length(a.memory["shortmem"]) == 0
|
||||
0
|
||||
else
|
||||
k = keys(a.memory["shortmem"])
|
||||
maximum(parse.(Int, k))
|
||||
thoughtdict["action_result"] = guideline
|
||||
|
||||
return (thoughtdict=thoughtdict, result_raw=nothing)
|
||||
end
|
||||
a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
|
||||
|
||||
elseif thoughtDict["action_name"] ∈ ["PRESENT_WINE_GUIDELINE"] #WORKING
|
||||
function wine_presentation_guideline!(a::T, thoughtdict::AbstractDict
|
||||
)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
|
||||
|
||||
# add guideline in to context
|
||||
guideline =
|
||||
"""
|
||||
<wine_presentation_guideline>
|
||||
@@ -757,296 +541,178 @@ function think(a::T) where {T<:agent}
|
||||
</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
|
||||
thoughtdict["action_result"] = guideline
|
||||
|
||||
elseif thoughtDict["action_name"] == "CHECK_WINE"
|
||||
result = checkwine(a, thoughtDict["action_input"])
|
||||
|
||||
thoughtDict["action_result"] = result[:result_str]
|
||||
max_ind =
|
||||
if length(a.memory["shortmem"]) == 0
|
||||
0
|
||||
else
|
||||
k = keys(a.memory["shortmem"])
|
||||
maximum(parse.(Int, k))
|
||||
end
|
||||
a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
|
||||
else
|
||||
error("condition is not defined ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
end
|
||||
|
||||
println("\n--- YiemAgent think() 2 ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(thoughtDict)
|
||||
println("---")
|
||||
return (action_name=thoughtDict["action_name"], result=result)
|
||||
return (thoughtdict=thoughtdict, result_raw=nothing)
|
||||
end
|
||||
|
||||
|
||||
function presentbox(a::sommelier, thoughtDict; maxtattempt::Integer=10, recentevents::Integer=10)
|
||||
recentchat_ind = GeneralUtils.recentElementsIndex(length(a.chathistory), recentevents;
|
||||
includelatest=true)
|
||||
#PENDING
|
||||
function generatechat!(a::T; maxattempt::Integer=10
|
||||
)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} 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 =
|
||||
"""
|
||||
<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>
|
||||
# store_policy
|
||||
- Generally speaking, the store inventory has some wines from France, the United States, Australia, Spain, and Italy, but you won't know exactly until you check your inventory.
|
||||
- If you found wines in the store's database, they are in stock.
|
||||
- You can only recommend wines that are currently in our inventory
|
||||
- Before searching the database for wine, ensure you have at least the following information: 1) budget, 2) wine type, and 3) occasion. Additional details are always helpful. If the user is unsure, provide relevant information and gather insights to make reasonable inferences.
|
||||
- Ask the user one question at a time.
|
||||
- Do not ask the user about wine's flavor e.g. floral, citrusy, nutty or some thing similar as these terms cannot be used to search the database.
|
||||
- Once the user has selected their wine, if you haven't already, ask the user whether they need any further assistance. Do not offer any additional services.
|
||||
- Only end the conversation when the user explicitly intends to do so. When ending, ensure a polite farewell and an invitation to return in the future.
|
||||
- Spicy foods should be paired only with light red wines.
|
||||
- We do not sell organic, sustainable, gluten-free, and sulfite-free wine. Inform the user immediately if they are looking for these types of wines. Do not sell our wines as such.
|
||||
- Gift box, gift card, and custom messages are available. Inform the user to contact our sales team.
|
||||
|
||||
# store_guidelines
|
||||
- Greeting the customer warmly by ask them how could you help. Do not ask any other questions during this greeting.
|
||||
- Customer may provide images for you to look up.
|
||||
- Encourage the customer to explore different options and try new things.
|
||||
- If you are unable to locate the desired item in the database after 2 attempts, it may not be available in your inventory. In such cases, inform the user that the item is unavailable and suggest an alternative instead.
|
||||
- Your store carries only wine.
|
||||
- Vintage 0 means non-vintage.
|
||||
- Start searching the database as broadly as possible within the given information boundary to maximize the chances of finding. Avoid unnecessary parameters unless specified by the user. Refine the search subsequently.
|
||||
|
||||
# situation
|
||||
You are continuing the conversation with the user.
|
||||
|
||||
# your role
|
||||
Your name is $(a.name). You are a helpful sommelier for website-based $(a.retailername)'s wine store. You are working under your mentor supervision.
|
||||
|
||||
# objective
|
||||
- Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences.
|
||||
- Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences.
|
||||
|
||||
# your responsibility includes
|
||||
- According to the store's policy and guidelines, continuing conversation with the customer using CHAT_BOX action.
|
||||
- Keep the conversation with the customer going smoothly
|
||||
|
||||
# your responsibility does NOT includes
|
||||
- Requesting the user to place an order, make a purchase, or confirm the order. These are the job of our sales team at the store.
|
||||
- Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store.
|
||||
- Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store.
|
||||
|
||||
# you should then respond to the user with interleaving plan, action_name, action_input
|
||||
1) "plan", Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
|
||||
2) "action_name", Must be "CHAT_BOX
|
||||
3) "action_input", Dialogue you want to chat with the user according to your plan.
|
||||
After the action is executed you gets "action_result". It is the output from the action you selected.
|
||||
|
||||
<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!
|
||||
# you should only respond in JSON format as described below
|
||||
"plan": "...",
|
||||
"action_name": "...",
|
||||
"action_input": "..."
|
||||
"""
|
||||
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)
|
||||
system_msg = Dict(
|
||||
"role" => "system",
|
||||
"content" => [
|
||||
Dict("type" => "text", "text" => systemmsg),
|
||||
]
|
||||
)
|
||||
|
||||
chathistory = deepcopy(a.chathistory[2:end]) # use deep copy because I want to replace system msg
|
||||
pushfirst!(chathistory, system_msg)
|
||||
|
||||
requiredKeys = ["plan", "action_name", "action_input"]
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
# 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 = a.context.text2textInstructLLM(a.id, msg)
|
||||
response = GeneralUtils.clean_json_response(response)
|
||||
response = GeneralUtils.remove_french_accents(response)
|
||||
# response = replace(response, '$'=>"USD")
|
||||
think, response = GeneralUtils.extractthink(response)
|
||||
response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to
|
||||
|
||||
response = replace(response, '*'=>"")
|
||||
response = replace(response, '$' => "USD")
|
||||
response = replace(response, '`' => "")
|
||||
response = replace(response, "<|eot_id|>"=>"")
|
||||
response = strip(response)
|
||||
|
||||
responsedict = nothing
|
||||
if occursin(requiredKeys[2], response)
|
||||
try
|
||||
responsedict = copy(JSON.parsefile(response))
|
||||
_responsedict = JSON.parse(response)
|
||||
responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
|
||||
catch
|
||||
println("\nERROR YiemAgent presentbox() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
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
|
||||
try
|
||||
responsedict = OrderedDict(
|
||||
"plan"=> "I will talk to the user",
|
||||
"action_name"=> "CHAT_BOX",
|
||||
"action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response
|
||||
)
|
||||
catch e
|
||||
println("\nERROR YiemAgent decisionMaker(). $e --(not qualify response)-> $response", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
continue
|
||||
end
|
||||
end
|
||||
|
||||
# check whether all answer's key points are in responsedict
|
||||
ispass, errormsg = checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
if !ispass
|
||||
errornote = errormsg
|
||||
println("\nERROR YiemAgent presentbox() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
continue
|
||||
end
|
||||
|
||||
# check if Context: is in dialogue
|
||||
if occursin("Context:", responsedict["dialogue"])
|
||||
errornote = "Your previous response contains 'Context:' which is not allowed"
|
||||
println("\nERROR YiemAgent presentbox() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
end
|
||||
|
||||
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())")
|
||||
# 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
|
||||
|
||||
# # 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
|
||||
# println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# pprintln(responsedict)
|
||||
|
||||
# # 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
|
||||
return (thoughtdict=responsedict, result_raw=responsedict["action_input"])
|
||||
end
|
||||
error("YiemAgent generatechat() failed to generate a thought ", response)
|
||||
end
|
||||
|
||||
|
||||
function generatequestion(a, text2textInstructLLM::Function, timeline)::String
|
||||
|
||||
+334
-171
@@ -1,10 +1,10 @@
|
||||
module llmfunction
|
||||
|
||||
export virtualWineUserChatbox, jsoncorrection, checkwine, # recommendbox,
|
||||
export virtualWineUserChatbox, jsoncorrection, checkwine!, # recommendbox,
|
||||
virtualWineUserRecommendbox, userChatbox, userRecommendbox, extractWineAttributes_1,
|
||||
extractWineAttributes_2, paraphrase
|
||||
|
||||
using HTTP, JSON, URIs, Random, PrettyPrinting, UUIDs, Dates, DataFrames
|
||||
using HTTP, JSON, URIs, Random, PrettyPrinting, UUIDs, Dates, DataFrames, DataStructures
|
||||
using GeneralUtils, SQLLLM
|
||||
using ..type, ..util
|
||||
|
||||
@@ -269,7 +269,7 @@ end
|
||||
# Arguments
|
||||
- `a::T1`
|
||||
one of ChatAgent's agent.
|
||||
- `input::T2`
|
||||
- `thoughtdict::AbstractDict`
|
||||
# Return
|
||||
A JSON string of available wine
|
||||
|
||||
@@ -282,56 +282,19 @@ julia> result = checkinventory(agent, input)
|
||||
"{"wine 1": {\"Winery\": \"Pichon Baron\", \"wine name\": \"Pauillac (Grand Cru Classé)\", \"grape variety\": \"Cabernet Sauvignon\", \"year\": 2010, \"price\": \"125 USD\", \"stock ID\": \"ar-17\"}, }"
|
||||
```
|
||||
"""
|
||||
function checkwine(a::T1, input::T2; maxattempt::Int=3
|
||||
) where {T1<:agent, T2<:AbstractString}
|
||||
function checkwine!(a::T, thoughtdict::AbstractDict; useSQLLLM::Bool=false
|
||||
)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
|
||||
|
||||
println("\ncheckinventory order: $input ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
wineattributes_1 = extractWineAttributes_1(a, input)
|
||||
wineattributes_2 = extractWineAttributes_2(a, input)
|
||||
println("\ncheckinventory order: $(thoughtdict["action_input"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
wineattributes_1 = extractWineAttributes_1(a, thoughtdict["action_input"])
|
||||
wineattributes_2 = extractWineAttributes_2(a, thoughtdict["action_input"])
|
||||
|
||||
# placeholder
|
||||
# textresult = nothing
|
||||
# rawresponse = nothing
|
||||
|
||||
# for i in 1:maxattempt
|
||||
|
||||
# #CHANGE if you want to add retailer name
|
||||
# # _inventoryquery = "retailer name: $(a.retailername), $wineattributes_1, $wineattributes_2"
|
||||
# _inventoryquery = "$wineattributes_1, $wineattributes_2"
|
||||
|
||||
# retrieve_attributes = ["winery", "wine_name", "wine_id", "vintage", "region", "country", "wine_type", "grape", "serving_temperature", "sweetness", "intensity", "tannin", "acidity", "tasting_notes", "price", "currency"]
|
||||
# inventoryquery = "Retrieves $retrieve_attributes of wines that match the following criteria - {$_inventoryquery}"
|
||||
# println("\ncheckinventory input: $inventoryquery ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# # add suppport for similarSQLVectorDB
|
||||
# textresult, result_raw = SQLLLM.query(
|
||||
# inventoryquery,
|
||||
# a.context.executeSQL,
|
||||
# a.context.text2textInstructLLM;
|
||||
# insertSQLVectorDB=a.context.insertSQLVectorDB,
|
||||
# similarSQLVectorDB=a.context.similarSQLVectorDB,
|
||||
# llmFormatName="qwen3")
|
||||
|
||||
# # check if all of retrieve_attributes appears in textresult
|
||||
# isin = [occursin(x, textresult) for x in retrieve_attributes]
|
||||
# # check if rawresponse type is DataFrame so that I can check for column
|
||||
# if typeof(result_raw) == DataFrame &&
|
||||
# !occursin("The resulting table has 0 row", textresult) &&
|
||||
# !all(isin)
|
||||
|
||||
# errornote = "Not all of $retrieve_attributes appear in search result"
|
||||
# println("\nERROR YiemAgent checkwine() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# continue
|
||||
# else
|
||||
# break
|
||||
# end
|
||||
# end
|
||||
|
||||
#CHANGE if you want to add retailer name
|
||||
# _inventoryquery = "retailer name: $(a.retailername), $wineattributes_1, $wineattributes_2"
|
||||
retrieve_attributes = ["winery", "wine_name", "wine_id", "vintage", "region", "country", "wine_type", "grape", "serving_temperature", "sweetness", "intensity", "tannin", "acidity", "tasting_notes", "price", "currency"]
|
||||
_inventoryquery = "$wineattributes_1, $wineattributes_2"
|
||||
inventoryquery = "Retrieves $retrieve_attributes of wines that match the following criteria - {$_inventoryquery}"
|
||||
println("\ncheckinventory input: $inventoryquery ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
|
||||
if useSQLLLM
|
||||
# add suppport for similarSQLVectorDB
|
||||
textresult, result_raw = SQLLLM.query(
|
||||
inventoryquery,
|
||||
@@ -340,12 +303,332 @@ function checkwine(a::T1, input::T2; maxattempt::Int=3
|
||||
insertSQLVectorDB=a.context.insertSQLVectorDB,
|
||||
similarSQLVectorDB=a.context.similarSQLVectorDB,
|
||||
llmFormatName="qwen3")
|
||||
# println("\n--- YiemAgent checkwine() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# println(textresult)
|
||||
# println(result_raw)
|
||||
thoughtdict["action_result"] = textresult
|
||||
else
|
||||
|
||||
# direct query with possible sql instead of SQLLLM.
|
||||
sql = generatesql(a, inventoryquery)
|
||||
textresult, result_raw, _, _ = SQLexecution(a.context.executeSQL, sql)
|
||||
thoughtdict["action_result"] = textresult
|
||||
end
|
||||
|
||||
return (thoughtdict=thoughtdict, result_raw=result_raw)
|
||||
end
|
||||
|
||||
|
||||
function generatesql(a::T, searchterm::String,
|
||||
; maxattempt=10
|
||||
)::String where {T<:agent}
|
||||
|
||||
systemmsg =
|
||||
"""
|
||||
# database_search_guidelines
|
||||
- Keep SQL queries focused only on the provided information.
|
||||
- Do not create any table in the database
|
||||
- A junction table can be used to link tables together. Another use case is for filtering data.
|
||||
- If you can't find a single table that can be used to answer the user's search term, try joining multiple tables to see if you can obtain the answer.
|
||||
- Text information in the database usually stored in lower case. If your search returns empty, try using lower case to search.
|
||||
- If there is no search result from the database, remove the restrictive criteria until a search result is available, and proceed from there.
|
||||
|
||||
# situation
|
||||
At each round of conversation, you will be given the following:
|
||||
- user search term
|
||||
|
||||
# objective
|
||||
Consult the database_search_guidelines. Then find the data from a database to satisfy the user's search term.
|
||||
|
||||
# your responsibility includes
|
||||
Fulfill the objective.
|
||||
|
||||
# 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, Must be "RUNSQL"
|
||||
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
|
||||
"RUNSQL", which you can use to execute SQL against the database.
|
||||
The input must be a single SQL query to be executed against the database.
|
||||
For more effective text search, it's necessary to use case-insensitivity and the ILIKE operator.
|
||||
Do not wrap the SQL as it will be executed against the database directly and SQL must be ended with ';'.
|
||||
"""
|
||||
|
||||
table_schema =
|
||||
"""
|
||||
create table customer (
|
||||
customer_id uuid primary key default gen_random_uuid (),
|
||||
customer_firstname varchar(128),
|
||||
customer_lastname varchar(128),
|
||||
customer_displayname varchar(128) not null,
|
||||
customer_username varchar(128),
|
||||
customer_password varchar(128),
|
||||
customer_gender varchar(128),
|
||||
country varchar(128),
|
||||
telephone varchar(128),
|
||||
email varchar(128) not null,
|
||||
customer_birthdate varchar(128),
|
||||
note text,
|
||||
|
||||
other_attributes jsonb,
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp,
|
||||
description text
|
||||
);
|
||||
|
||||
create table retailer (
|
||||
retailer_id uuid primary key default gen_random_uuid (),
|
||||
retailer_name varchar(128) not null,
|
||||
retailer_username varchar(128) not null,
|
||||
retailer_password varchar(128) not null,
|
||||
retailer_address text not null,
|
||||
country varchar(128) not null,
|
||||
contact_person varchar(128) not null,
|
||||
telephone varchar(128) not null,
|
||||
email varchar(128) not null,
|
||||
note text,
|
||||
|
||||
other_attributes jsonb,
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp,
|
||||
description text
|
||||
);
|
||||
|
||||
create table food (
|
||||
food_id uuid primary key default gen_random_uuid (),
|
||||
food_name varchar(128) not null,
|
||||
country varchar(128),
|
||||
spiciness integer,
|
||||
sweetness integer,
|
||||
sourness integer,
|
||||
savoriness integer,
|
||||
bitterness integer,
|
||||
serving_temperature integer,
|
||||
image_url jsonb,
|
||||
note text,
|
||||
other_attributes jsonb,
|
||||
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp,
|
||||
description text
|
||||
);
|
||||
|
||||
create table wine (
|
||||
wine_id uuid primary key default gen_random_uuid (),
|
||||
seo_name varchar(128) not null,
|
||||
wine_name varchar(128) not null,
|
||||
winery varchar(128) not null,
|
||||
vintage integer not null,
|
||||
region varchar(128) not null,
|
||||
country varchar(128) not null,
|
||||
wine_type varchar(128) not null,
|
||||
grape varchar(128) not null,
|
||||
serving_temperature varchar(128) not null,
|
||||
intensity integer,
|
||||
sweetness integer,
|
||||
tannin integer,
|
||||
acidity integer,
|
||||
fizziness integer,
|
||||
tasting_notes text,
|
||||
image_url jsonb,
|
||||
manufacturer_sku text,
|
||||
note text,
|
||||
other_attributes jsonb,
|
||||
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp,
|
||||
description text
|
||||
);
|
||||
|
||||
create table wine_food (
|
||||
wine_id uuid references wine(wine_id),
|
||||
food_id uuid references food(food_id),
|
||||
constraint wine_food_id primary key (wine_id, food_id),
|
||||
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp
|
||||
);
|
||||
|
||||
CREATE TABLE retailer_wine (
|
||||
retailer_id uuid references retailer(retailer_id),
|
||||
wine_id uuid references wine(wine_id),
|
||||
constraint retailer_wine_id primary key (retailer_id, wine_id),
|
||||
price NUMERIC(10, 2),
|
||||
currency varchar(3) not null,
|
||||
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp
|
||||
);
|
||||
|
||||
CREATE TABLE retailer_food (
|
||||
retailer_id uuid references retailer(retailer_id),
|
||||
food_id uuid references food(food_id),
|
||||
constraint retailer_food_id primary key (retailer_id, food_id),
|
||||
price NUMERIC(10, 2),
|
||||
currency varchar(3) not null,
|
||||
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp
|
||||
);
|
||||
"""
|
||||
|
||||
requiredKeys = ["plan", "action_name", "action_input"]
|
||||
errornote = ""
|
||||
# provide similar sql only for the first attempt
|
||||
sql, distance = a.context.similarSQLVectorDB(searchterm)
|
||||
|
||||
similarSQL_ = sql !== nothing ? sql : "None"
|
||||
# if sql is really close, just use it
|
||||
if similarSQL_ != "None" && distance <= 0.1
|
||||
return similarSQL_
|
||||
end
|
||||
|
||||
context =
|
||||
"""
|
||||
<internal_context_for_assistant>
|
||||
<database_table_schema>
|
||||
$table_schema
|
||||
</database_table_schema>
|
||||
<possible SQL for user's search term>
|
||||
$similarSQL_
|
||||
</possible SQL for user's search term>
|
||||
<error_note>
|
||||
$errornote
|
||||
<error_note>
|
||||
</internal_context_for_assistant>
|
||||
"""
|
||||
input = context * searchterm
|
||||
|
||||
msg = Dict(
|
||||
"model" => "gemma-4-E4B-it-UD-Q4_K_XL",
|
||||
"messages" => [
|
||||
Dict(
|
||||
"role" => "system",
|
||||
"content" => [
|
||||
Dict("type" => "text", "text" => systemmsg),
|
||||
]
|
||||
),
|
||||
Dict(
|
||||
"role" => "user",
|
||||
"content" => [
|
||||
Dict("type" => "text", "text" => input),
|
||||
]
|
||||
),
|
||||
],
|
||||
"temperature" => 0.7
|
||||
)
|
||||
|
||||
for attempt in 1:maxattempt
|
||||
response = a.context.text2textInstructLLM("random_id", msg)
|
||||
|
||||
response = GeneralUtils.clean_json_response(response)
|
||||
|
||||
think, response = GeneralUtils.extractthink(response)
|
||||
responsedict = nothing
|
||||
try
|
||||
_responsedict = JSON.parse(response)
|
||||
responsedict = GeneralUtils.dictify(_responsedict, keytype=String, sort_order=requiredKeys)
|
||||
catch
|
||||
println("\nERROR 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
|
||||
|
||||
# remove backticks Error occurred: MethodError: no method matching occursin(::String, ::Vector{String})
|
||||
if occursin("```", responsedict["action_input"])
|
||||
sql = GeneralUtils.extract_triple_backtick_text(responsedict["action_input"])[1]
|
||||
if sql[1:4] == "sql\n"
|
||||
sql = sql[5:end]
|
||||
end
|
||||
sql = split(sql, ';') # some time there are comments in the sql
|
||||
sql = sql[1] * ';'
|
||||
|
||||
responsedict["action_input"] = sql
|
||||
end
|
||||
|
||||
toollist = ["RUNSQL"]
|
||||
if responsedict["action_name"] ∉ toollist
|
||||
errornote = "Your previous attempt has action_name that is not in the tool list"
|
||||
println("\nERROR SQLLLM decisionMaker(). Attempt $attempt/$maxattempt. $errornote --(not qualify response)--> $(responsedict["action_name"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
end
|
||||
|
||||
for i in toollist
|
||||
if occursin(i, responsedict["action_input"])
|
||||
errornote = "Your previous attempt has action_name in action_input which is not allowed"
|
||||
println("\nERROR SQLLLM decisionMaker(). Attempt $attempt/$maxattempt. $errornote --(not qualify response)--> $(responsedict["action_input"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
end
|
||||
end
|
||||
|
||||
# println("\nSQLLLM decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# pprintln(responsedict)
|
||||
# println("---")
|
||||
|
||||
return (result_str=textresult, result_raw=result_raw, success=true, errormsg=nothing)
|
||||
return responsedict["action_input"]
|
||||
end
|
||||
error("SQLLLM DecisionMaker() failed to generate a thought \n", response)
|
||||
end
|
||||
|
||||
function SQLexecution(executeSQL::Function, sql::T
|
||||
)::NamedTuple where {T<:AbstractString}
|
||||
|
||||
try
|
||||
# add LIMIT to the SQL to prevent loading large data
|
||||
sql = strip(sql)
|
||||
|
||||
# remove DISTINCT keyword because it is incompatible with RANDOM()
|
||||
sql = replace(sql, "DISTINCT" => "")
|
||||
|
||||
if sql[end] == ';'
|
||||
if !occursin("LIMIT", sql)
|
||||
sql = sql[1:end-1] * " ORDER BY RANDOM() LIMIT 2;"
|
||||
end
|
||||
else
|
||||
sql = sql * ";"
|
||||
end
|
||||
result = executeSQL(sql)
|
||||
df = DataFrame(result)
|
||||
tablesize = size(df)
|
||||
row, column = tablesize
|
||||
if row == 0
|
||||
return (result_str="No records found.", result_raw=df, success=true, errormsg=nothing)
|
||||
elseif column > 30
|
||||
return (result_str="There are more than 30 columns. Please be more specific.", result_raw=df, success=true, errormsg=nothing)
|
||||
else
|
||||
df1 =
|
||||
if row > 2
|
||||
# ramdom row to pick
|
||||
df[sample(1:nrow(df), 2, replace=false), :] # random select 2 rows from df
|
||||
else
|
||||
df
|
||||
end
|
||||
result = GeneralUtils.dfToString(df1)
|
||||
# println("\n~~~ SQLexecution() result: ", @__FILE__, " ", @__LINE__)
|
||||
# println(sql)
|
||||
# println(df1)
|
||||
# println("\n")
|
||||
return (result_str=result, result_raw=df1, success=true, errormsg=nothing)
|
||||
end
|
||||
catch e
|
||||
io = IOBuffer()
|
||||
showerror(io, e)
|
||||
errorMsg = String(take!(io))
|
||||
st = sprint((io, v) -> show(io, "text/plain", v), stacktrace(catch_backtrace()))
|
||||
println(errorMsg)
|
||||
return (result_str=nothing, result_raw=nothing, success=false, errormsg=errorMsg)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -924,126 +1207,6 @@ externalService = config["externalservice"]["text2textinstruct"]
|
||||
end
|
||||
|
||||
|
||||
# function isrecommend(state::T1, text2textInstructLLM::Function
|
||||
# ) where {T1<:AbstractDict}
|
||||
|
||||
# systemmsg =
|
||||
# """
|
||||
# You are a helpful assistant that analyzes agent's trajectories to find solutions and observations (i.e., the results of actions) to answer the user's questions.
|
||||
|
||||
# Definitions:
|
||||
# "question" is the user's question.
|
||||
# "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) 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.
|
||||
|
||||
# At each round of conversation, the user will give you:
|
||||
# Context: ...
|
||||
# Trajectories: ...
|
||||
|
||||
# You should then respond to the user with:
|
||||
# 1) trajectory_evaluation:
|
||||
# - Analyze the trajectories of a solution to answer the user's original question.
|
||||
# Then given a question and a trajectory, evaluate its correctness and provide your reasoning and
|
||||
# analysis in detail. Focus on the latest thought, action, and observation.
|
||||
# Incomplete trajectories can be correct if the thoughts and actions so far are correct,
|
||||
# even if the answer is not found yet. Do not generate additional thoughts or actions.
|
||||
# 2) answer_evaluation: Focus only on the matter mentioned in the question and analyze how the latest observation addresses the question.
|
||||
# 3) accepted_as_answer: Decide whether the latest observation's content answers the question. The possible responses are either 'Yes' or 'No.'
|
||||
# Bad example (The observation didn't answers the question):
|
||||
# question: Find cars with 4 wheels.
|
||||
# observation: There are 2 cars in the table.
|
||||
# Good example (The observation answers the question):
|
||||
# question: Find cars with a stereo.
|
||||
# observation: There are 1 cars in the table. 1) brand: Toyota, model: yaris, color: black.
|
||||
# 4) score: Correctness score s where s is a single integer between 0 to 9.
|
||||
# - 0 means the trajectories are incorrect.
|
||||
# - 9 means the trajectories are correct, and the observation's content directly answers the question.
|
||||
# 5) suggestion: if accepted_as_answer is "No", provide suggestion.
|
||||
|
||||
# You should only respond in format as described below:
|
||||
# trajectory_evaluation: ...
|
||||
# answer_evaluation: ...
|
||||
# accepted_as_answer: ...
|
||||
# score: ...
|
||||
# suggestion: ...
|
||||
|
||||
# Let's begin!
|
||||
# """
|
||||
|
||||
# thoughthistory = ""
|
||||
# for (k, v) in state[:thoughtHistory]
|
||||
# thoughthistory *= "$k: $v\n"
|
||||
# end
|
||||
|
||||
# usermsg =
|
||||
# """
|
||||
# Context: None
|
||||
# Trajectories: $thoughthistory
|
||||
# """
|
||||
|
||||
# _prompt =
|
||||
# [
|
||||
# Dict(:name=> "system", :text=> systemmsg),
|
||||
# Dict(:name=> "user", :text=> usermsg)
|
||||
# ]
|
||||
|
||||
# # put in model format
|
||||
# prompt = GeneralUtils.formatLLMtext(_prompt, "granite3")
|
||||
# prompt *=
|
||||
# """
|
||||
# <|start_header_id|>assistant<|end_header_id|>
|
||||
# """
|
||||
|
||||
# for attempt in 1:5
|
||||
# try
|
||||
# response = text2textInstructLLM(prompt)
|
||||
# responsedict = GeneralUtils.textToDict(response,
|
||||
# ["trajectory_evaluation", "answer_evaluation", "accepted_as_answer", "score", "suggestion"],
|
||||
# rightmarker=":", symbolkey=true)
|
||||
|
||||
# # check if dict has all required value
|
||||
# trajectoryevaluation_text::AbstractString = responsedict[:trajectory_evaluation]
|
||||
# answerevaluation_text::AbstractString = responsedict[:answer_evaluation]
|
||||
# responsedict[:score] = parse(Int, responsedict[:score]) # convert string "5" into integer 5
|
||||
# score::Integer = responsedict[:score]
|
||||
# accepted_as_answer::AbstractString = responsedict[:accepted_as_answer]
|
||||
# suggestion::AbstractString = responsedict[:suggestion]
|
||||
|
||||
# # add to state here instead to in transition() because the latter causes julia extension crash (a bug in julia extension)
|
||||
# state[:evaluation] = "$(responsedict[:trajectory_evaluation]) $(responsedict[:answer_evaluation])"
|
||||
# state[:evaluationscore] = responsedict[:score]
|
||||
# state[:accepted_as_answer] = responsedict[:accepted_as_answer]
|
||||
# state[:suggestion] = responsedict[:suggestion]
|
||||
|
||||
# # mark as terminal state when the answer is achieved
|
||||
# if accepted_as_answer == "Yes"
|
||||
# state[:isterminal] = true
|
||||
# state[:reward] = 1
|
||||
# end
|
||||
# println("--> 5 Evaluator ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# pprintln(Dict(responsedict))
|
||||
# return responsedict[:score]
|
||||
# catch e
|
||||
# io = IOBuffer()
|
||||
# showerror(io, e)
|
||||
# errorMsg = String(take!(io))
|
||||
# st = sprint((io, v) -> show(io, "text/plain", v), stacktrace(catch_backtrace()))
|
||||
# println("")
|
||||
# println("Attempt $attempt. Error occurred: $errorMsg\n$st")
|
||||
# println("")
|
||||
# end
|
||||
# end
|
||||
# error("evaluator failed to generate an evaluation")
|
||||
# end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+35
-38
@@ -223,10 +223,9 @@ function sommelier(
|
||||
context,
|
||||
llmFormatName
|
||||
)
|
||||
|
||||
systemmsg =
|
||||
"""
|
||||
<store_policy>
|
||||
# store_policy
|
||||
- Generally speaking, the store inventory has some wines from France, the United States, Australia, Spain, and Italy, but you won't know exactly until you check your inventory.
|
||||
- If you found wines in the store's database, they are in stock.
|
||||
- You can only recommend wines that are currently in our inventory
|
||||
@@ -238,8 +237,8 @@ function sommelier(
|
||||
- Spicy foods should be paired only with light red wines.
|
||||
- We do not sell organic, sustainable, gluten-free, and sulfite-free wine. Inform the user imediately if they are looking for these types of wines. Do not sell our wines as such.
|
||||
- Gift box, gift card, and custom messages are available. Inform the user to contact our sales team.
|
||||
</store_policy>
|
||||
<store_guidelines>
|
||||
|
||||
# store_guidelines
|
||||
- Greeting the customer warmly by ask them how could you help. Do not ask any other questions during this greeting.
|
||||
- Customer may provide images for you to look up.
|
||||
- Encourage the customer to explore different options and try new things.
|
||||
@@ -247,47 +246,45 @@ 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>
|
||||
<situation>
|
||||
Your customer is coming into the store
|
||||
</situation>
|
||||
<your 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.
|
||||
</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.
|
||||
|
||||
# situation
|
||||
You are having conversation with a customer.
|
||||
|
||||
# your role
|
||||
Your name is $(newAgent.name). You are a helpful sommelier for website-based $(newAgent.retailername)'s wine store.
|
||||
|
||||
# objective
|
||||
- Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences.
|
||||
- Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences.
|
||||
|
||||
# your responsibility includes
|
||||
- According to the store's policy and guidelines, and make an informed decision about what available_actions you need to use to achieve the objective.
|
||||
- Keep the conversation with the customer going smoothly
|
||||
|
||||
# your responsibility does NOT includes
|
||||
- Requesting the user to place an order, make a purchase, or confirm the order. These are the job of our sales team at the store.
|
||||
- Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store.
|
||||
- Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store.
|
||||
|
||||
# you should then respond to the user with interleaving plan, action_name, action_input
|
||||
1) "plan", Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
|
||||
2) "action_name", (Typically corresponds to the execution of the first step in your plan) Can be one of the available_actions name
|
||||
3) "action_input", The input to the action you are about to perform according to your plan.
|
||||
After the action is executed you gets "action_result". It is the output from the action you selected.
|
||||
</you should then respond to the user with interleaving plan, action_name, action_input>
|
||||
<you should only respond in JSON format as described below>
|
||||
|
||||
# you should only respond in JSON format as described below (not Markdown format)
|
||||
"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.
|
||||
- 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.
|
||||
|
||||
# available actions
|
||||
"CHAT_BOX", which you can use to talk with the user. The input is dialogue you want to chat with the user according to your plan.
|
||||
"CHECK_WINE", allows you to check information about wines you want in your inventory's database. The input is text that specify supported search criteria includeing: retailer_name, wine price, winery, name, vintage, region, country, type, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity.
|
||||
Example query 1: "Dry, full-bodied red wine from 1) region: Burgundy, country: France or 2) region: Tuscany, country: Italy. Grape varietal: Merlot or Syrah. price 100 to 1000 USD."
|
||||
Example query 2: "Red or white wine, medium tannin, price under 700 USD"
|
||||
Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
|
||||
- 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>
|
||||
"WINE_PRESENTATION_GUIDELINE", which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
|
||||
"END_CONVER_GUIDELINE", which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
|
||||
"""
|
||||
|
||||
system_msg = Dict(
|
||||
|
||||
+4
-4
@@ -95,15 +95,15 @@ end
|
||||
"""
|
||||
function addNewMessage(a::T1, name::String, userinput::T2;
|
||||
maximumMsg::Integer=30) where {T1<:agent, T2<:AbstractDict}
|
||||
if name ∉ ["system", "user", "assistant"] # guard against typo
|
||||
error("name is not in agent.availableRole $(@__LINE__)")
|
||||
end
|
||||
# if name ∉ ["system", "user", "assistant"] # guard against typo
|
||||
# error("name is not in agent.availableRole $(@__LINE__)")
|
||||
# end
|
||||
|
||||
#TODO summarize the oldest 10 message
|
||||
if length(a.chathistory) > maximumMsg
|
||||
summarize(a.chathistory)
|
||||
else
|
||||
userinput["timestamp"] = Dates.now()
|
||||
# userinput["timestamp"] = Dates.now()
|
||||
push!(a.chathistory, userinput)
|
||||
end
|
||||
end
|
||||
|
||||
+161
-51
@@ -2,19 +2,18 @@ using JSON, Dates, UUIDs, PrettyPrinting, LibPQ, Base64, DataFrames, DataStructu
|
||||
NATS, Base.Threads
|
||||
using YiemAgent, GeneralUtils, msghandler
|
||||
|
||||
|
||||
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)
|
||||
@@ -24,19 +23,23 @@ function text2text_instruct_llm(sender_id::String, openai_msg::Dict{String, Any}
|
||||
return llm_response
|
||||
end
|
||||
|
||||
#TESTING get text embedding from a LLM service
|
||||
""" get a single text embedding from a LLM service
|
||||
Example
|
||||
text = ["hello"]
|
||||
embedding = get_embedding(text)
|
||||
"""
|
||||
function get_embedding(text::AbstractArray{String})
|
||||
documents_dict = Dict("documents" => text)
|
||||
payloads = [("documents", documents_dict, "dictionary")]
|
||||
_, msg_envelope_json_str = msghandler.smartpack(
|
||||
config["externalService"]["servicesloadbalancer"]["nats"],
|
||||
config["externalservice"]["servicesloadbalancer"]["nats"],
|
||||
payloads;
|
||||
msg_purpose="embedding",
|
||||
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)
|
||||
incoming_env = msghandler.smartunpack(incoming_env_json_str)
|
||||
@@ -45,44 +48,61 @@ function get_embedding(text::AbstractArray{String})
|
||||
return embedding_response
|
||||
end
|
||||
|
||||
#TESTING
|
||||
function execute_sql_winedb(config::JSON.Object, sql::T) where {T<:AbstractString}
|
||||
""" sql = "SELECT * FROM wine;"
|
||||
result = execute_sql_winedb(sql)
|
||||
"""
|
||||
function execute_sql_winedb(sql::T) where {T<:AbstractString}
|
||||
host_url, _port = split(config["externalservice"]["sommpanion_db"]["url"], ':')
|
||||
port = parse(Int, _port)
|
||||
dbname = "winedb"
|
||||
user = config["externalservice"]["sommpanion_db"]["user"]
|
||||
password = config["externalservice"]["sommpanion_db"]["password"]
|
||||
db_connection = LibPQ.Connection("host=$host_url port=$port dbname=$dbname user=$user password=$password")
|
||||
result = nothing
|
||||
try
|
||||
result = LibPQ.execute(db_connection, sql)
|
||||
catch e
|
||||
LibPQ.close(db_connection)
|
||||
end
|
||||
|
||||
LibPQ.close(db_connection)
|
||||
return result
|
||||
end
|
||||
|
||||
#TESTING
|
||||
function similar_sql_vectordb(query; maxdistance::Integer=100)
|
||||
""" find similar sql from vector database
|
||||
sql = "SELECT * FROM wine;"
|
||||
result, distance = similar_sql_vectordb(sql)
|
||||
"""
|
||||
function similar_sql_vectordb(sql::T; maxdistance::Number=0.2) where {T<:AbstractString}
|
||||
tablename = "sqlllm_decision_repository"
|
||||
# get embedding of the query
|
||||
df = find_similar_text_from_vectordb(query, tablename,
|
||||
df = find_similar_text_from_vectordb(sql, tablename,
|
||||
"function_input_embedding", execute_sql_vectordb)
|
||||
# println(df[1, [:id, :function_output]])
|
||||
row, col = size(df)
|
||||
distance = row == 0 ? Inf : df[1, :distance]
|
||||
# distance = 100 # CHANGE this is for testing only
|
||||
if row != 0 && distance < maxdistance
|
||||
# if there is usable SQL, return it.
|
||||
output_b64 = df[1, :function_output_base64] # pick the closest match
|
||||
output_str = String(base64decode(output_b64))
|
||||
rowid = df[1, :id]
|
||||
println("\n~~~ found similar sql. row id $rowid, distance $distance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
return (dict=output_str, distance=distance)
|
||||
println("\n--| similar sql found. row id $rowid, distance $distance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(output_str)
|
||||
return (result=output_str, distance=distance)
|
||||
else
|
||||
println("\n~~~ similar sql not found, max distance $maxdistance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
return (dict=nothing, distance=nothing)
|
||||
println("\n--| similar sql not found, max distance $maxdistance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
return (result=nothing, distance=nothing)
|
||||
end
|
||||
end
|
||||
|
||||
#TESTING
|
||||
function insert_sql_vectordb(query::T1, SQL::T2; maxdistance::Integer=3) where {T1<:AbstractString, T2<:AbstractString}
|
||||
""" insert query and sql into vector database
|
||||
query = "get all wines from wine table"
|
||||
sql = "SELECT * FROM wine;"
|
||||
insert_sql_vectordb(query, sql)
|
||||
"""
|
||||
function insert_sql_vectordb(query::T1, SQL::T2; maxdistance::Number=3
|
||||
) where {T1<:AbstractString, T2<:AbstractString}
|
||||
|
||||
tablename = "sqlllm_decision_repository"
|
||||
# get embedding of the query
|
||||
# query = state[:thoughtHistory][:question]
|
||||
@@ -91,40 +111,49 @@ function insert_sql_vectordb(query::T1, SQL::T2; maxdistance::Integer=3) where {
|
||||
row, col = size(df)
|
||||
distance = row == 0 ? Inf : df[1, :distance]
|
||||
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
|
||||
_query_embedding = get_embedding([query])[1]
|
||||
_query_embedding = get_embedding([query])
|
||||
_query_embedding = GeneralUtils.dictify(_query_embedding)
|
||||
# println("\n--- _query_embedding() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# println(_query_embedding)
|
||||
# println("---\n")
|
||||
query_embedding = _query_embedding["data"][1]["embedding"]
|
||||
query = replace(query, "'" => "")
|
||||
sql_base64 = base64encode(SQL)
|
||||
sql_ = replace(SQL, "'" => "")
|
||||
|
||||
sql = """
|
||||
sql =
|
||||
"""
|
||||
INSERT INTO $tablename (function_input, function_output, function_output_base64, function_input_embedding) VALUES ('$query', '$sql_', '$sql_base64', '$query_embedding');
|
||||
"""
|
||||
# println("\n~~~ added new decision to vectorDB ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# println("\n--| added new decision to vectorDB ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# println(sql)
|
||||
_ = execute_sql_vectordb(sql)
|
||||
end
|
||||
end
|
||||
|
||||
#TESTING
|
||||
""" execute sql against vectordb
|
||||
sql = "SELECT * FROM wine;"
|
||||
result = execute_sql_vectordb(sql)
|
||||
"""
|
||||
function execute_sql_vectordb(sql::T) where {T<:AbstractString}
|
||||
host_url, _port = split(config["SQLVectorDB"]["url"], ':')
|
||||
host_url, _port = split(config["externalservice"]["sommpanion_vectordb"]["url"], ':')
|
||||
port = parse(Int, _port)
|
||||
dbname = config[:externalservice][:SQLVectorDB][:dbname]
|
||||
user = config[:externalservice][:SQLVectorDB][:user]
|
||||
password = config[:externalservice][:SQLVectorDB][:password]
|
||||
dbname = config["externalservice"]["sommpanion_vectordb"]["dbname"]
|
||||
user = config["externalservice"]["sommpanion_vectordb"]["user"]
|
||||
password = config["externalservice"]["sommpanion_vectordb"]["password"]
|
||||
DBconnection = LibPQ.Connection("host=$host_url port=$port dbname=$dbname user=$user password=$password")
|
||||
result = LibPQ.execute(DBconnection, sql)
|
||||
close(DBconnection)
|
||||
return result
|
||||
end
|
||||
|
||||
|
||||
""" search similar decision llm made from vectordb
|
||||
"""
|
||||
function similar_sommelier_decision(recentevents::T1; maxdistance::Integer=3
|
||||
)::Union{AbstractDict, Nothing} where {T1<:AbstractString}
|
||||
|
||||
tablename = "sommelier_decision_repository"
|
||||
# find similar
|
||||
println("\n~~~ search vectorDB for this: $recentevents ", @__FILE__, " ", @__LINE__)
|
||||
df = find_similar_text_from_vectordb(recentevents, tablename,
|
||||
"function_input_embedding", execute_sql_vectordb)
|
||||
row, col = size(df)
|
||||
@@ -132,24 +161,29 @@ function similar_sommelier_decision(recentevents::T1; maxdistance::Integer=3
|
||||
if row != 0 && distance < maxdistance
|
||||
# if there is usable decision, return it.
|
||||
rowid = df[1, :id]
|
||||
println("\n~~~ found similar decision. row id $rowid, distance $distance ", @__FILE__, " ", @__LINE__)
|
||||
println("\n--| found similar decision. row id $rowid, distance $distance ", @__FILE__, " ", @__LINE__)
|
||||
output_b64 = df[1, :function_output_base64] # pick the closest match
|
||||
_output_str = String(base64decode(output_b64))
|
||||
output = copy(JSON.read(_output_str))
|
||||
return output
|
||||
else
|
||||
println("\n~~~ similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__)
|
||||
println("\n--| similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__)
|
||||
return nothing
|
||||
end
|
||||
end
|
||||
|
||||
#TESTING
|
||||
""" search similar text from vectordb
|
||||
"""
|
||||
function find_similar_text_from_vectordb(text::T1, tablename::T2, embeddingColumnName::T3,
|
||||
vectorDB::Function; limit::Integer=1
|
||||
)::DataFrame where {T1<:AbstractString, T2<:AbstractString, T3<:AbstractString}
|
||||
# get embedding from LLM service
|
||||
_embedding = get_embedding([text])[1]
|
||||
embedding = _embedding["data"][1]["embedding"]
|
||||
_embedding = get_embedding([text])
|
||||
_embedding = _embedding["data"][1]["embedding"]
|
||||
_embedding = "$_embedding"
|
||||
|
||||
embedding = _embedding[4:end]
|
||||
|
||||
# check whether there is close enough vector already store in vectorDB. if no, add, else skip
|
||||
sql = """
|
||||
SELECT *, $embeddingColumnName <-> '$embedding' as distance
|
||||
@@ -158,10 +192,12 @@ function find_similar_text_from_vectordb(text::T1, tablename::T2, embeddingColum
|
||||
"""
|
||||
response = vectorDB(sql)
|
||||
df = DataFrame(response)
|
||||
|
||||
return df
|
||||
end
|
||||
|
||||
|
||||
""" insert decision llm made to vectordb
|
||||
"""
|
||||
function insert_sommelier_decision(recentevents::T1, decision::T2; maxdistance::Integer=5
|
||||
) where {T1<:AbstractString, T2<:AbstractDict}
|
||||
tablename = "sommelier_decision_repository"
|
||||
@@ -182,20 +218,20 @@ function insert_sommelier_decision(recentevents::T1, decision::T2; maxdistance::
|
||||
"""
|
||||
INSERT INTO $tablename (function_input, function_output, function_output_base64, function_input_embedding) VALUES ('$recentevents', '$decision', '$decision_base64', '$recentevents_embedding');
|
||||
"""
|
||||
println("\n~~~ added new decision to vectorDB ", @__FILE__, " ", @__LINE__)
|
||||
println("\n--| added new decision to vectorDB ", @__FILE__, " ", @__LINE__)
|
||||
println(sql)
|
||||
_ = execute_sql_vectordb(sql)
|
||||
else
|
||||
println("~~~ similar decision previously cached, distance $distance ", @__FILE__, " ", @__LINE__)
|
||||
println("--| similar decision previously cached, distance $distance ", @__FILE__, " ", @__LINE__)
|
||||
end
|
||||
end
|
||||
|
||||
config = JSON.parsefile("./appconfig.json")
|
||||
sessionId = "0"
|
||||
backend_session_topic = "sommpanion.backend.agentbackend.v1.inbox.$sessionId"
|
||||
|
||||
config = JSON.parsefile("./dummy_config.json")
|
||||
backend_session_topic = "sommpanion.testsubject"
|
||||
agent_ch = Channel(8)
|
||||
agent_conn = NATS.connect(config["nats_server_info"]["url"])
|
||||
|
||||
sub2 = NATS.subscribe(agent_conn, backend_session_topic) do msg
|
||||
put!(agent_ch, msg)
|
||||
end
|
||||
@@ -215,27 +251,29 @@ agent = YiemAgent.sommelier(
|
||||
agent_context;
|
||||
name="Janie",
|
||||
id=sessionId, # agent instance id
|
||||
retailername="Yiem",
|
||||
retailername="Yiem Wine Ltd.",
|
||||
llmFormatName=""
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
# 1. Read local file and encode to base64 string
|
||||
image1_path = "test/large_image.png"
|
||||
image1_bytes = read(image1_path)
|
||||
image1_base64_string = base64encode(image1_bytes)
|
||||
|
||||
# 2. Match the MIME type according to your file extension (e.g., png, jpeg)
|
||||
mime_type = "image/png"
|
||||
data1_uri = "data:$(mime_type);base64,$(image1_base64_string)"
|
||||
|
||||
# 1. Read local file and encode to base64 string
|
||||
image2_path = "test/small_image.png"
|
||||
image2_bytes = read(image2_path)
|
||||
image2_base64_string = base64encode(image2_bytes)
|
||||
mime_type = "image/png"
|
||||
data2_uri = "data:$(mime_type);base64,$(image2_base64_string)"
|
||||
|
||||
# 3. Construct payload with the Data URI
|
||||
usermsg = Dict{String, Any}(
|
||||
message = Dict(
|
||||
"role" => "user",
|
||||
"content" => [
|
||||
Dict("type" => "text", "text" => "รู้จักไวน์ที่อยู่ในรูปมั้ย"),
|
||||
Dict("type" => "text", "text" => "Do you know type of wine in the image?"),
|
||||
Dict(
|
||||
"type" => "image_url",
|
||||
"image_url" => Dict("url" => data1_uri)
|
||||
@@ -243,8 +281,80 @@ usermsg = Dict{String, Any}(
|
||||
]
|
||||
)
|
||||
|
||||
result = YiemAgent.conversation(agent; userinput=usermsg)
|
||||
println(result)
|
||||
result = YiemAgent.conversation(agent; userinput=message)
|
||||
println("\n$result")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# message = Dict(
|
||||
# "role" => "user",
|
||||
# "content" => [
|
||||
# Dict("type" => "text", "text" =>
|
||||
# "
|
||||
# เป็นงานเลี้ยงทั่วไป
|
||||
# "),
|
||||
# ]
|
||||
# )
|
||||
|
||||
# result = YiemAgent.conversation(agent; userinput=message)
|
||||
# println("\n$result")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# message = Dict(
|
||||
# "role" => "user",
|
||||
# "content" => [
|
||||
# Dict("type" => "text", "text" => "no thanks. that's all"),
|
||||
# ]
|
||||
# )
|
||||
|
||||
# result = YiemAgent.conversation(agent; userinput=message)
|
||||
# println("\n$result")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# message = Dict(
|
||||
# "role" => "user",
|
||||
# "content" => [
|
||||
# Dict("type" => "text", "text" => "What about this wine?"),
|
||||
# Dict(
|
||||
# "type" => "image_url",
|
||||
# "image_url" => Dict("url" => data2_uri)
|
||||
# )
|
||||
# ]
|
||||
# )
|
||||
|
||||
# result = YiemAgent.conversation(agent; userinput=message)
|
||||
# println("\n$result")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user