Compare commits

..

56 Commits

Author SHA1 Message Date
ton ddbb135b6b update 2026-07-17 12:22:56 +07:00
ton afda364484 update 2026-07-17 12:03:36 +07:00
ton af73d955eb Merge pull request 'v0.7.1' (#27) from v0.7.1 into main
Reviewed-on: #27
2026-07-17 03:28:17 +00:00
ton 39cf9a72a1 Merge pull request 'v0.7.1-fix_single_items_info_frontend' (#26) from v0.7.1-fix_single_items_info_frontend into v0.7.1
Reviewed-on: #26
2026-07-17 03:28:06 +00:00
ton 1c829ad854 update 2026-07-17 10:14:13 +07:00
ton da98baddb6 update 2026-07-17 10:06:32 +07:00
ton c5fbaabf42 Merge pull request 'v0.7.0' (#25) from v0.7.0 into main
Reviewed-on: #25
2026-07-17 00:03:01 +00:00
ton 8080905bad Merge pull request 'v0.7.0-output_openai_msg' (#24) from v0.7.0-output_openai_msg into v0.7.0
Reviewed-on: #24
2026-07-17 00:02:47 +00:00
ton b349c3a8b6 update 2026-07-17 07:01:55 +07:00
ton 0148e03d6a update 2026-07-16 23:31:36 +07:00
ton e718cc4a5c update 2026-07-16 23:13:18 +07:00
ton 87bc6a46a1 update 2026-07-16 22:31:40 +07:00
ton 44bb8baf7c Merge pull request 'update' (#23) from v0.6.0-output_text_image into main
Reviewed-on: #23
2026-07-15 11:51:43 +00:00
ton 18b2d54ba7 update 2026-07-15 18:51:21 +07:00
ton b3c3bb9b75 Merge pull request 'update' (#22) from v0.6.0-output_text_image into main
Reviewed-on: #22
2026-07-15 11:50:09 +00:00
ton d004193b19 update 2026-07-15 18:49:51 +07:00
ton 8898226825 Merge pull request 'v0.6.0-output_text_image' (#21) from v0.6.0-output_text_image into main
Reviewed-on: #21
2026-07-15 11:48:20 +00:00
ton 686b9b2e92 update 2026-07-15 18:47:18 +07:00
ton 3acf46964b update 2026-07-15 14:25:04 +07:00
ton 5c7caf0b49 Merge pull request 'update' (#20) from v0.6.0-output_text_image into main
Reviewed-on: #20
2026-07-15 07:01:48 +00:00
ton ad917ea8d0 update 2026-07-15 14:01:32 +07:00
ton edeef4ed2a Merge pull request 'v0.6.0-output_text_image' (#19) from v0.6.0-output_text_image into main
Reviewed-on: #19
2026-07-15 06:59:56 +00:00
ton 31daa805f3 update 2026-07-15 13:59:28 +07:00
ton c9937ab5d7 update 2026-07-15 13:59:01 +07:00
ton 4610137f04 Merge pull request 'update' (#18) from v0.6.0-output_text_image into main
Reviewed-on: #18
2026-07-15 05:20:58 +00:00
ton 9d7eed7cde update 2026-07-15 12:20:44 +07:00
ton aedc53bf86 Merge pull request 'update' (#17) from v0.6.0-output_text_image into main
Reviewed-on: #17
2026-07-15 05:17:56 +00:00
ton 286da3cf2c update 2026-07-15 12:16:59 +07:00
ton 7fa988313d Merge pull request 'update' (#16) from v0.6.0-output_text_image into main
Reviewed-on: #16
2026-07-15 05:15:31 +00:00
ton e5b19dd268 update 2026-07-15 12:14:32 +07:00
ton 0df4159261 Merge pull request 'update' (#15) from v0.6.0-output_text_image into main
Reviewed-on: #15
2026-07-15 05:11:05 +00:00
ton 45e8ded111 update 2026-07-15 12:10:36 +07:00
ton 9167ece0c0 Merge pull request 'v0.6.0' (#14) from v0.6.0 into main
Reviewed-on: #14
2026-07-15 04:57:47 +00:00
ton a6a9395ecc Merge pull request 'update' (#13) from v0.6.0-output_text_image into v0.6.0
Reviewed-on: #13
2026-07-15 04:57:11 +00:00
ton a503d4d759 update 2026-07-15 11:56:44 +07:00
ton f45a036971 Merge pull request 'v0.6.0' (#12) from v0.6.0 into main
Reviewed-on: #12
2026-07-15 04:38:48 +00:00
ton 24b85be58b Merge pull request 'updatet' (#11) from v0.6.0-output_text_image into v0.6.0
Reviewed-on: #11
2026-07-15 04:38:18 +00:00
ton a798cd119e updatet 2026-07-14 18:08:36 +07:00
ton fa338dd0f8 Merge pull request 'v0.5.0' (#10) from v0.5.0 into main
Reviewed-on: #10
2026-07-12 08:03:41 +00:00
ton 8d4bf5f01f Merge pull request 'v0.5.0-tool_role' (#9) from v0.5.0-tool_role into v0.5.0
Reviewed-on: #9
2026-07-12 08:03:26 +00:00
ton cd6f6ef961 update 2026-07-12 11:14:30 +07:00
ton fdec34832d update 2026-07-12 10:54:15 +07:00
ton 3c72373b85 update 2026-07-12 05:54:47 +07:00
ton 688a8c4df2 update 2026-07-11 21:45:49 +07:00
ton 8bd4986be2 Merge pull request 'v0.4.3' (#8) from v0.4.3 into main
Reviewed-on: #8
2026-07-10 10:47:34 +00:00
ton 6e5809fc9b Merge pull request 'v0.4.3-fix_markdown_response' (#7) from v0.4.3-fix_markdown_response into v0.4.3
Reviewed-on: #7
2026-07-10 10:47:18 +00:00
ton 2b7c0041e5 up version 2026-07-10 17:46:55 +07:00
ton 9ff0b48eec update 2026-07-10 17:45:58 +07:00
ton afeb4c7aef Merge pull request 'v0.4.2' (#6) from v0.4.2 into main
Reviewed-on: #6
2026-07-09 13:20:36 +00:00
ton 2942a89730 Merge pull request 'v0.4.2-limit_consecutive_same_tool_use' (#5) from v0.4.2-limit_consecutive_same_tool_use into v0.4.2
Reviewed-on: #5
2026-07-09 13:20:21 +00:00
ton 6a66f58e63 update 2026-07-09 20:19:41 +07:00
ton 1d0353d793 update 2026-07-09 20:14:04 +07:00
ton 0f6aa7c79f update 2026-07-09 19:45:04 +07:00
ton 0320fd321f Merge pull request 'v0.4.1' (#4) from v0.4.1 into main
Reviewed-on: #4
2026-07-09 01:01:53 +00:00
ton c29dccf597 up version 2026-07-09 08:01:08 +07:00
ton 70cf04b0db Merge pull request 'v0.4.1-fix_agent_not_respond' (#3) from v0.4.1-fix_agent_not_respond into v0.4.1
Reviewed-on: #3
2026-07-09 00:58:33 +00:00
12 changed files with 1165 additions and 905 deletions
+94 -24
View File
@@ -2,7 +2,7 @@
julia_version = "1.12.6"
manifest_format = "2.0"
project_hash = "09bd5c43d6ad954d8be233d27fc343ea1149c0b0"
project_hash = "1e317787f914f6d857feb7c23bb910d1185caed9"
[[deps.Accessors]]
deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"]
@@ -38,6 +38,12 @@ version = "1.1.3"
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.2"
[[deps.ArnoldiMethod]]
deps = ["LinearAlgebra", "Random", "StaticArrays"]
git-tree-sha1 = "d57bd3762d308bded22c3b82d033bff85f6195c6"
uuid = "ec485272-7323-5ecc-a04f-4719b315124d"
version = "0.4.0"
[[deps.ArrowTypes]]
deps = ["Sockets", "UUIDs"]
git-tree-sha1 = "404265cd8128a2515a81d5eae16de90fdef05101"
@@ -91,9 +97,9 @@ uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.8"
[[deps.CommonSolve]]
git-tree-sha1 = "99ee296f88c12485402e37c2fd025f95ae097637"
git-tree-sha1 = "eeaad7cef88554c2fa56b5a3f71cfd5cb708c662"
uuid = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2"
version = "0.2.9"
version = "0.2.11"
[[deps.Compat]]
deps = ["TOML", "UUIDs"]
@@ -181,6 +187,20 @@ git-tree-sha1 = "e98abef36d02a0ec385d68cd7dadbce9b28cbd88"
uuid = "abce61dc-4473-55a0-ba07-351d65e31d42"
version = "0.4.1"
[[deps.Distances]]
deps = ["LinearAlgebra", "Statistics", "StatsAPI"]
git-tree-sha1 = "c7e3a542b999843086e2f29dac96a618c105be1d"
uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7"
version = "0.10.12"
[deps.Distances.extensions]
DistancesChainRulesCoreExt = "ChainRulesCore"
DistancesSparseArraysExt = "SparseArrays"
[deps.Distances.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
@@ -226,9 +246,13 @@ version = "0.1.10"
[[deps.FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "91e0e5c68d02bcdaae76d3c8ceb4361e8f28d2e9"
git-tree-sha1 = "6621fef488e496356c9c9625d0562c12a6070819"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.16.5"
version = "1.20.0"
weakdeps = ["HTTP"]
[deps.FileIO.extensions]
HTTPExt = "HTTP"
[[deps.FilePathsBase]]
deps = ["Compat", "Dates"]
@@ -250,6 +274,7 @@ deps = ["LinearAlgebra"]
git-tree-sha1 = "2f979084d1e13948a3352cf64a25df6bd3b4dca3"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "1.16.0"
weakdeps = ["PDMats", "SparseArrays", "StaticArrays", "Statistics"]
[deps.FillArrays.extensions]
FillArraysPDMatsExt = "PDMats"
@@ -257,12 +282,6 @@ version = "1.16.0"
FillArraysStaticArraysExt = "StaticArrays"
FillArraysStatisticsExt = "Statistics"
[deps.FillArrays.weakdeps]
PDMats = "90014a1f-27ba-587c-ab20-58faa44d9150"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[deps.Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
@@ -274,18 +293,31 @@ uuid = "a0844989-3bd2-4988-8bea-c9407ab0941b"
version = "1.1.0"
[[deps.GeneralUtils]]
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "Distributions", "HTTP", "JSON", "NATS", "PrettyPrinting", "Random", "Revise", "SHA", "UUIDs"]
git-tree-sha1 = "7c0600c166a5deb2c607018a491c04eb25969c2e"
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "Distributions", "Graphs", "HTTP", "JSON", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "SHA", "StringDistances", "UUIDs"]
git-tree-sha1 = "a75a088ee8e5faf10f554ca00748e0e6ca58d1ca"
repo-rev = "main"
repo-url = "https://git.yiem.cc/ton/GeneralUtils"
uuid = "c6c72f09-b708-4ac8-ac7c-2084d70108fe"
version = "0.4.9"
version = "0.5.1"
[[deps.Graphs]]
deps = ["ArnoldiMethod", "DataStructures", "Inflate", "LinearAlgebra", "Random", "SimpleTraits", "SparseArrays", "Statistics"]
git-tree-sha1 = "7eb45fe833a5b7c51cf6d89c5a841d5967e44be3"
uuid = "86223c79-3864-5bf0-83f7-82e725a168b6"
version = "1.14.0"
[deps.Graphs.extensions]
GraphsSharedArraysExt = "SharedArrays"
[deps.Graphs.weakdeps]
Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b"
SharedArrays = "1a1011a3-84de-559e-8e89-a11a2f7dc383"
[[deps.HTTP]]
deps = ["Base64", "CodecZlib", "Dates", "EnumX", "PrecompileTools", "Random", "Reseau", "SHA", "URIs", "UUIDs", "Zlib_jll"]
git-tree-sha1 = "eda1d37cb55d90a17d0957c75841138c88b361a1"
git-tree-sha1 = "c2c808326222b6dc4bec295a83b55f79aeec98e0"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "2.5.4"
version = "2.5.5"
[[deps.HashArrayMappedTries]]
git-tree-sha1 = "2eaa69a7cab70a52b9687c8bf950a5a93ec895ae"
@@ -310,6 +342,11 @@ git-tree-sha1 = "cf8234411cbeb98676c173f930951ea29dca3b23"
uuid = "a303e19e-6eb4-11e9-3b09-cd9505f79100"
version = "0.2.4"
[[deps.Inflate]]
git-tree-sha1 = "d1b1b796e47d94588b3757fe84fbf65a5ec4a80d"
uuid = "d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9"
version = "0.1.5"
[[deps.InlineStrings]]
git-tree-sha1 = "8f3d257792a522b4601c24a577954b0a8cd7334d"
uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48"
@@ -645,15 +682,17 @@ version = "0.4.2"
[[deps.PrettyTables]]
deps = ["Crayons", "LaTeXStrings", "Markdown", "PrecompileTools", "Printf", "REPL", "Reexport", "StringManipulation", "Tables"]
git-tree-sha1 = "624de6279ab7d94fc9f672f0068107eb6619732c"
git-tree-sha1 = "ebf455bb866ee6737030e3d3816bb6a0683c4325"
uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d"
version = "3.3.2"
version = "3.4.0"
[deps.PrettyTables.extensions]
PrettyTablesExcelExt = "XLSX"
PrettyTablesTypstryExt = "Typstry"
[deps.PrettyTables.weakdeps]
Typstry = "f0ed7684-a786-439e-b1e3-3b82803b501e"
XLSX = "fdbf4ff8-1666-58a4-91e7-1b58723a45e0"
[[deps.Printf]]
deps = ["Unicode"]
@@ -734,9 +773,9 @@ version = "0.5.1+0"
[[deps.Roots]]
deps = ["Accessors", "CommonSolve", "Printf"]
git-tree-sha1 = "ed45bcc7cf3c8887595b973f2b1efbe91dcc50ec"
git-tree-sha1 = "a7caaf7ba8cf307112ca443784d1b56b4a591455"
uuid = "f2b01f46-fcfa-551c-844a-d8ac1e96c665"
version = "3.0.1"
version = "3.0.5"
[deps.Roots.extensions]
RootsChainRulesCoreExt = "ChainRulesCore"
@@ -760,11 +799,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 = "93cc1ae6202279a2eb4e1dbfff706c5bc158609d"
git-tree-sha1 = "bae2fd2e2b087753fbb3415896be41df1ae0eb90"
repo-rev = "main"
repo-url = "https://git.yiem.cc/ton/SQLLLM"
uuid = "2ebc79c7-cc10-4a3a-9665-d2e1d61e63d3"
version = "0.2.5"
version = "0.2.8"
[[deps.SQLStrings]]
git-tree-sha1 = "55de0530689832b1d3d43491ee6b67bd54d3323c"
@@ -793,6 +832,12 @@ version = "1.4.10"
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
version = "1.11.0"
[[deps.SimpleTraits]]
deps = ["InteractiveUtils", "MacroTools"]
git-tree-sha1 = "7ddb0b49c109481b046972c0e4ab02b2127d6a75"
uuid = "699a6c99-e7fa-54fc-8d76-47d257e15c1d"
version = "0.9.6"
[[deps.Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
version = "1.11.0"
@@ -826,6 +871,25 @@ version = "2.8.0"
[deps.SpecialFunctions.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
[[deps.StaticArrays]]
deps = ["LinearAlgebra", "PrecompileTools", "Random", "StaticArraysCore"]
git-tree-sha1 = "246a8bb2e6667f832eea063c3a56aef96429a3db"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.9.18"
[deps.StaticArrays.extensions]
StaticArraysChainRulesCoreExt = "ChainRulesCore"
StaticArraysStatisticsExt = "Statistics"
[deps.StaticArrays.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[deps.StaticArraysCore]]
git-tree-sha1 = "6ab403037779dae8c514bad259f32a447262455a"
uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
version = "1.4.4"
[[deps.Statistics]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0"
@@ -862,6 +926,12 @@ version = "2.2.0"
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112"
[[deps.StringDistances]]
deps = ["Distances", "StatsAPI"]
git-tree-sha1 = "cd83a04baf746e3b43b83c61b7de77ab0409b80a"
uuid = "88034a9c-02f8-509d-84a9-84ec65e18404"
version = "1.0.0"
[[deps.StringManipulation]]
deps = ["PrecompileTools"]
git-tree-sha1 = "d05693d339e37d6ab134c5ab53c29fce5ee5d7d5"
@@ -983,10 +1053,10 @@ uuid = "76eceee3-57b5-4d4a-8e66-0e911cebbf60"
version = "1.6.1"
[[deps.YiemAgent]]
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "SQLLLM", "Serialization", "URIs", "UUIDs"]
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "SQLLLM", "Serialization", "URIs", "UUIDs"]
path = "."
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
version = "0.4.0"
version = "0.6.5"
[[deps.Zlib_jll]]
deps = ["Libdl"]
+5 -3
View File
@@ -1,9 +1,10 @@
name = "YiemAgent"
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
version = "0.4.0"
version = "0.7.2"
authors = ["narawat lamaiin <narawat@outlook.com>"]
[deps]
Base64 = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
@@ -23,11 +24,12 @@ URIs = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[compat]
Base64 = "1.11.0"
CSV = "0.10.15"
DataFrames = "1.7.0"
GeneralUtils = "0.4.9"
GeneralUtils = "0.5.1"
HTTP = "2.4.0"
JSON = "1.6.1"
LLMMCTS = "0.1.5"
NATS = "0.1.0"
SQLLLM = "0.2.5"
SQLLLM = "0.2.8"
+1 -1
View File
@@ -54,7 +54,7 @@ Your name is $(newAgent.name). You are a helpful sommelier for website-based $(n
# 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.
- **SEARCH_WINE_DATABASE** 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
+6 -5
View File
@@ -6,6 +6,7 @@
"testingOrProduction": "testing",
"agentId": "2b74b87a-5413-4fe2-a4d3-405891051680",
"agentCentralConfigSubject": "/yiem/hq/agent/sommelier/backend/config/api/v1.1",
"this_service_name": "agent_backend",
"this_service_input_channel": {
"mqtt": [
"/yiem/hq/agent/sommpanion/backend/db/api_v1"
@@ -16,7 +17,7 @@
},
"agentRole": "sommelier",
"organization": "yiem_hq",
"externalService": {
"externalservice": {
"servicesloadbalancer": {
"nats": "sommpanion.backend.servicesloadbalancer.v1.inbox"
},
@@ -35,15 +36,15 @@
"description": "A database connection info for LibPQ client",
"url": "192.168.88.106:5432",
"dbname": "winedb",
"user": "yiemtechnologies@gmail.com",
"password": "yiemtechnologies@Postgres_0.0"
"user": "admin",
"password": "admin@Sommpanion_0.0"
},
"sommpanion_vectordb" : {
"description": "A wine database connection info for LibPQ client",
"url": "192.168.88.106:5433",
"dbname": "vectordb",
"user": "yiemtechnologies@gmail.com",
"password": "yiemtechnologies@Postgres_0.0"
"user": "admin",
"password": "admin@Sommpanion_0.0"
},
"fileserver": {
"description": "temporary file server",
+106 -8
View File
@@ -1,13 +1,111 @@
using HTTP, JSON, URIs, Random, PrettyPrinting, UUIDs, Dates, DataFrames, DataStructures
using GeneralUtils, SQLLLM, YiemAgent
config = JSON.parsefile("./appconfig.json")
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"]
pg_conn_str = "host=$host_url port=$port dbname=$dbname user=$user password=$password"
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
sql =
"""
SELECT T1.winery, T1.wine_name, T1.wine_id, T1.vintage, T1.region, T1.country, T1.wine_type, T1.grape, T1.serving_temperature, T1.sweetness, T1.intensity, T1.tannin, T1.acidity, T1.tasting_notes, T2.price, T2.currency, T1.image_url, T3.retailer_name, T3.retailer_id FROM "wine" AS T1 JOIN "retailer_wine" AS T2 ON T1.wine_id = T2.wine_id JOIN "retailer" AS T3 ON T2.retailer_id = T3.retailer_id WHERE T1.wine_name = 'Montrachet Grand Cru' AND T1.winery = 'Domaine Jacques Prieur' AND T3.retailer_name = 'Yiem Wines Ltd' AND T3.retailer_id = 'f54eab6b-7650-4448-b009-c53f3efbcc3b';
"""
textresult, sql_result_raw, _, _ = YiemAgent.SQLexecution(execute_sql_winedb, sql)
result_vec = GeneralUtils.dfToVectorDict(sql_result_raw)
for d in result_vec
wine_name = d["wine_name"]
image_url_json_str = d["image_url"]
image_url_json_obj = JSON.parse(image_url_json)
base_url = "http://192.168.88.106:8080/"
image_base64 =
if haskey(image_url_json_obj, "bottle")
url = base_url * image_url_json_obj["bottle"]
image_data = HTTP.get(url) # vector{int} data
image_base64_string = base64encode(image_data)
else
nothing
end
d["image"] = image_base64
end
using LibPQ
using Tables
"""
update_car_regions_one_by_one(conn::LibPQ.Connection, target_word::String)
Iterates through all rows in the 'car' table where the region is "German",
and updates them one-by-one to the `target_word`.
"""
function update_car_regions_one_by_one(pg_conn_str::String, replace_word::String , target_word::String)
conn = LibPQ.Connection(pg_conn_str)
# 1. Fetch the target rows. Assumes 'id' is the primary key.
# We select the ID to target rows individually during the update step.
select_query = "SELECT id FROM car WHERE region = '$replace_word';"
result = execute(conn, select_query)
rows = Tables.rows(result)
# 2. Prepare the update statement for execution reuse
# Using explicit types for parameter placeholders ($1, $2)
update_query = "UPDATE car SET region = \$1 WHERE id = \$2;"
println("Starting one-by-one update...")
updated_count = 0
# 3. Iterate through rows one-by-one
for row in rows
# LibPQ row values are accessed via properties or column names
row_id = row.id
# Execute the parameterized statement safely
execute(conn, update_query, [target_word, row_id])
updated_count += 1
end
println("Successfully updated \$updated_count rows.")
return updated_count
end
d = Dict(
"hello"=> 555,
"world"=> Dict(
"name"=> "ton"
)
)
x = 55
@info "YiemAgent think() 1 " d x @__LINE__
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

+218 -490
View File
@@ -68,14 +68,14 @@ julia> result = decisionMaker(agent)
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_name" => "SEARCH_WINE_DATABASE"
"action_input" => "Sparkling white wine from Italy"
"action_result" => "1) winery: Terrazze dell Etna, wine_name: Rose Brut.
```
"""
function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
function decisionMaker(a::T; recentevents::Integer=20, maxattempt=3
) where {T<:agent}
println("\nExecuting YiemAgent decisionMaker()")
@info "YiemAgent decisionMaker() start " @__LINE__
# lessonDict = copy(JSON.parsefile("lesson.json"))
# lesson =
@@ -108,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>
"""
@@ -126,9 +123,7 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
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",
@@ -137,12 +132,18 @@ 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
@@ -152,25 +153,30 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
println("\nERROR YiemAgent decisionMaker() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
end
# fall back to normal text because LLM default to natural chat when it didn't use action_call
else
responsedict = OrderedDict(
"plan"=> "I will talk to the user",
"action_name"=> "CHAT_BOX",
"action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response
)
end
# check whether all answer's key points are in responsedict
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
if !ispass
errornote = errormsg
println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
else
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"]
# check whether all answer's key points are in responsedict
println("\n---")
println(responsedict)
println("---\n")
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_input"] == "CHAT_BOX" &&
occursin("similar", responsedict["action_input"])
continue
end
# if responsedict["action_name"] ∉ ["CHAT_BOX", "SEARCH_WINE_DATABASE", "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
@@ -178,10 +184,17 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
# println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# pprintln(responsedict)
@info "YiemAgent decisionMaker() end " @__LINE__
return responsedict
end
error("DecisionMaker failed to generate a thought ", response)
# in case decisionMaker failed, force to use generatechat!()
responsedict = OrderedDict(
"plan"=> "N/A",
"action_name"=> "CHAT_BOX",
"action_input"=> "N/A"
)
return responsedict
end
@@ -269,9 +282,9 @@ function evaluator(a::T1, timeline, decisiondict, evaluateecontext
context =
"""
<context>
<trajectory>
<assistant_trajectories>
$timeline
</trajectory>
</assistant_trajectories>
<evaluatee_context>
$evaluateecontext
</evaluatee_context>
@@ -310,7 +323,7 @@ function evaluator(a::T1, timeline, decisiondict, evaluateecontext
ispass, errormsg = checkAgentResponse_JSON(responsedict, requiredKeys)
if !ispass
errornote = errormsg
println("\nERROR YiemAgent evaluator() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
println("\nERROR YiemAgent evaluator() $errornote --(not qualify response)> $responsedict ", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
continue
end
@@ -320,177 +333,10 @@ 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
return responsedict
end
error("Evaluator failed to generate an evaluation, Response: \n$response\n<|End of error|>")
end
# function evaluator(a::T1, timeline, decisiondict, evaluateecontext
# ) where {T1<:agent}
# systemmsg =
# """
# <Your role>
# - You are a master sommelier of an online wine store.
# </Your role>
# <Situation>
# - Under your supervision, a trainee sommelier is engaging with a store customer. Each time the customer speaks, the trainee will assess the situation, determine the next course of action, and pause to await your guidance before proceeding.
# </Situation>
# <Your mission>
# - Improve a trainee sommelier decision based on the store policy and guidelines while ensuring seamless interactions between the trainee and customers.
# </Your mission>
# <At each round of conversation, you will be given the following information>
# - trajectory: A conversation between your trainee and the customer that have occurred up until now
# - evaluatee_context: The context that evaluatee use to make a decision
# - evaluatee_decision: The decision made by the evaluatee, consists of the following elements:
# "plan" is the trainee's plan
# "action_name" is the name of the action taken, which can be one of the available tool name.
# "action_input" is the input to the action.
# </At each round of conversation, you will be given the following information>
# <You must follow the following policy>
# - Use only infomation provided by the store policy and guidelines as a bedrocks for your response.
# </You must follow the following policy>
# <You should follow the following guidelines>
# - The trainee's plan, action_name, and action_input must be logically consistent
# - The trainee's action_input should be in a proper format as specified by the tools.
# - The trainee's action name and action input should make sense. For example, if the trainee isn't finished talking, he shouldn't use the END_CONVER_GUIDELINE tool.
# </You should follow the following guidelines>
# <You should then respond to the user with>
# 1) trajectory_evaluation: Analyze the trajectory of a solution to answer the user's original question.
# - Evaluate the correctness of each section and the overall trajectory based on the given question.
# - Provide detailed reasoning and analysis, focusing on the latest thought, action, and observation.
# - Incomplete trajectory are acceptable if the thoughts and actions up to that point are correct, even if the final answer isn't reached.
# - Do not generate additional thoughts or actions.
# 2) decision_evaluation:
# - Examine how the trainee's decisions align with the store's policies and guidelines before proceeding.
# 3) suggestion: Based store policy and guidelines, provide a suggestion for the immediate decision step only.
# 4) approval: Can be "yes" or "no". "no" if the suggestion contradict the trainee's decision; otherwise, it is "yes".
# </You should then respond to the user with>
# <You should only respond in JSON format as described below>
# {
# "trajectory_evaluation": "...",
# "decision_evaluation": "...",
# "suggestion": "...",
# "approval": "...",
# }
# </You should only respond in format as described below>
# Let's begin!
# """
# requiredKeys = [:trajectory_evaluation, :decision_evaluation, :approval, :suggestion]
# errornote = "N/A"
# for attempt in 1:10
# evaluateecontext = replace(evaluateecontext, "<context>" => "")
# evaluateecontext = replace(evaluateecontext, "</context>" => "")
# context =
# """
# <context>
# <trajectory>
# $timeline
# </trajectory>
# <evaluatee_context>
# $evaluateecontext
# </evaluatee_context>
# <evaluatee_decision>
# {plan: $(decisiondict["plan"]), action_name: $(decisiondict["action_name"]), action_input: $(decisiondict["action_input"])}
# </evaluatee_decision>
# P.S. $errornote
# </context>
# """
# unformatPrompt =
# [
# Dict("name" => "system", "text" => systemmsg),
# ]
# # put in model format
# prompt = GeneralUtils.formatLLMtext(unformatPrompt, a.llmFormatName)
# # add info
# prompt = prompt * context
# response = a.context.text2textInstructLLM(prompt; senderId=a.id)
# response = GeneralUtils.deFormatLLMtext(response, a.llmFormatName)
# response = GeneralUtils.remove_french_accents(response)
# # response = replace(response, '$'=>"USD")
# think, response = GeneralUtils.extractthink(response)
# responsedict = nothing
# try
# responsedict = copy(JSON.parsefile(response))
# catch
# println("\nERROR YiemAgent generatechat() failed to parse response: $response", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# continue
# end
# # check whether all answer's key points are in responsedict
# ispass, errormsg = checkAgentResponse_JSON(responsedict, requiredKeys)
# if !ispass
# errornote = errormsg
# println("\nERROR YiemAgent evaluator() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
# continue
# end
# # if accepted_as_answer ∉ ["yes", "no"] # [PENDING] add errornote into the prompt
# # error("generated accepted_as_answer has wrong format")
# # end
# println("\nEvaluator() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# pprintln(Dict(responsedict))
# # # read sessionId
# # sessionid = a.id
# # # save to filename ./log/decisionlog.txt
# # println("saving SQLLLM evaluator() to disk")
# # filename = "agent_evaluator_log_$(sessionid[:id]).json"
# # filepath = "/appfolder/app/log/$filename"
# # # check whether there is a file path exists before writing to it
# # if !isfile(filepath)
# # decisionlist = [responsedict]
# # println("Creating file $filepath")
# # open(filepath, "w") do io
# # JSON.pretty(io, decisionlist)
# # end
# # else
# # # read the file and append new data
# # decisionlist = copy(JSON.parsefile(filepath))
# # push!(decisionlist, responsedict)
# # println("Appending new data to file $filepath")
# # open(filepath, "w") do io
# # JSON.pretty(io, decisionlist)
# # end
# # end
# return responsedict
# end
# error("Evaluator failed to generate an evaluation, Response: \n$response\n<|End of error|>")
# end
""" Chat with llm.
@@ -520,7 +366,7 @@ message => Dict(
function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Object{String, Any}},
maximumMsg=50, max_think_loop::Integer=3)
@info "YiemAgent conversation() 1" @__LINE__
@info "YiemAgent conversation() start " @__LINE__
userinput = GeneralUtils.dictify(userinput; keytype=String, sort_order=["text"])
# find text in usermsg
@@ -536,75 +382,147 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj
clearhistory(a)
return "Okay. What shall we talk about?"
else
@info "YiemAgent conversation() 2" @__LINE__
# 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
loopcount = 0
while true
@info "YiemAgent conversation() 2-0 count $loopcount" @__LINE__
loopcount += 1
thoughtdict, _ = think(a)
if thoughtdict["action_name"] ["CHAT_BOX"]
@info "YiemAgent conversation() 2-1" @__LINE__
if loopcount > max_think_loop
thoughtdict, result_raw = generatechat!(a)
assistant_response = Dict{String, Any}(
"role" => "assistant",
"content" => [Dict("type" => "text", "text" => thoughtdict["action_input"]),]
)
addNewMessage(a, "assistant", assistant_response; maximumMsg=maximumMsg)
return thoughtdict["action_input"]
items_info = []
send_item_ind = [] # index of the item being send to frontend
if haskey(a.memory["shortmem"], "items_info")
for (i, item) in enumerate(a.memory["shortmem"]["items_info"])
if haskey(item, "wine_name") && occursin(item["wine_name"], thoughtdict["action_input"])
push!(items_info, deepcopy(item))
push!(send_item_ind, i)
end
end
# remove sent items
deleteat!(a.memory["shortmem"]["items_info"], send_item_ind)
end
response_to_frontend = Dict{String, Any}(
"role" => "assistant",
"content" => [
Dict("type" => "text", "text" => thoughtdict["action_input"]),
Dict(
"type" => "items_info",
"items_info" => items_info
),
]
)
return response_to_frontend
end
if loopcount > max_think_loop
@info "YiemAgent conversation() 2-2" @__LINE__
r = generatechat(a)
@info "YiemAgent conversation() 2-3" @__LINE__
return r
thoughtdict, result_raw = think(a)
if thoughtdict["action_name"] ["CHAT_BOX"]
assistant_response = Dict{String, Any}(
"role" => "assistant",
"content" => [Dict("type" => "text", "text" => thoughtdict["action_input"]),]
)
addNewMessage(a, "assistant", assistant_response; maximumMsg=maximumMsg)
items_info = []
send_item_ind = [] # index of the item being send to frontend
if haskey(a.memory["shortmem"], "items_info")
for (i, item) in enumerate(a.memory["shortmem"]["items_info"])
if haskey(item, "wine_name") && occursin(item["wine_name"], thoughtdict["action_input"])
push!(items_info, deepcopy(item))
push!(send_item_ind, i)
end
end
# remove sent items
deleteat!(a.memory["shortmem"]["items_info"], send_item_ind)
end
response_to_frontend = Dict{String, Any}(
"role" => "assistant",
"content" => [
Dict("type" => "text", "text" => thoughtdict["action_input"]),
Dict(
"type" => "items_info",
"items_info" => items_info
),
]
)
""" intended message to send to frontend should have the following format.
response_to_frontend = Dict{String, Any}(
"role" => "assistant",
"content" => [
Dict("type" => "text", "text" => "assistant_text_response"),
Dict(
"type" => "items_info",
"items_info" => [
Dict(
"wine_name"=> "wine name 1",
"wine_id"=> "...",
"image"=> base64 encoded image,
...
),
Dict(
"wine_name"=> "wine name 2",
"wine_id"=> "...",
"image"=> base64 encoded image,
...
),
]
),
]
)
"""
return response_to_frontend
else # still in action
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)
action_result = thoughtdict["action_result"]
actionresult = Dict{String, Any}(
"role" => "action_result",
"content" => [Dict("type" => "text", "text" => "$action_result"),]
)
addNewMessage(a, "actionresult", actionresult; maximumMsg=maximumMsg)
@info "YiemAgent conversation() end think count $loopcount " @__LINE__
end
end
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)
# # add user activity to events memory
# push!(a.memory["events"],
# eventdict(;
# event_description="the user talks to the assistant.",
# timestamp=Dates.now(),
# subject="user",
# action_name="CHAT_BOX",
# action_input=userinput["text"],
# )
# )
# chatresponse = generatechat(a; converPartnerName=converPartnerName, recentEventNum=20)
# addNewMessage(a, "assistant", chatresponse; maximumMsg=maximumMsg)
# push!(a.memory["events"],
# eventdict(;
# event_description="the assistant talks to the user.",
# timestamp=Dates.now(),
# subject="assistant",
# action_name="CHAT_BOX",
# action_input=chatresponse,
# )
# )
# return chatresponse
# end
# end
"""
# Arguments
@@ -619,44 +537,51 @@ julia>
"""
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)
@info "YiemAgent think() start " @__LINE__
thoughtdict = decisionMaker(a)
@info "YiemAgent think() 1" @__LINE__
# pprintln(thoughtdict)
@info "YiemAgent think() 1 " @__LINE__
@show thoughtdict
println("---\n")
result_raw = nothing
if thoughtdict["action_name"] ["CHAT_BOX"]
@info "YiemAgent think() 2" @__LINE__
thoughtdict, result_raw = chatbox!(a, thoughtdict)
# sometime CHAT_BOX input is too short.
# if thoughtdict["action_input] < 20 character, use generatechat!()
if length(thoughtdict["action_input"]) < 20
thoughtdict, result_raw = generatechat!(a)
else
thoughtdict["action_result"] = "Action result is the next user dialogue."
result_raw = thoughtdict["action_input"]
end
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"] == "SEARCH_WINE_DATABASE"
thoughtdict, result_raw = search_wine_database!(a, thoughtdict; useSQLLLM=false)
if result_raw !== nothing && result_raw isa Vector
if haskey(a.memory["shortmem"], "items_info")
append!(a.memory["shortmem"]["items_info"], result_raw)
else
a.memory["shortmem"]["items_info"] = result_raw
end
end
elseif thoughtdict["action_name"] == "CHECK_WINE"
@info "YiemAgent think() 5" @__LINE__
thoughtdict, result_raw = checkwine!(a, thoughtdict)
else
@info "YiemAgent think() 6" @__LINE__
error("condition is not defined ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
end
max_ind =
if length(a.memory["shortmem"]) == 0
0
else
k = keys(a.memory["shortmem"])
maximum(parse.(Int, k))
end
a.memory["shortmem"]["$(max_ind + 1)"] = thoughtdict
@info "YiemAgent think() 7" @__LINE__
pprintln(thoughtdict)
@info "YiemAgent think() end " @__LINE__
@show thoughtdict
println("---\n")
return (thoughtdict=thoughtdict, result_raw=result_raw)
end
@@ -731,9 +656,9 @@ end
#PENDING
function generatechat(a::T; recentevents::Integer=20, maxattempt=10
)::String where {T<:agent}
function generatechat!(a::T; maxattempt::Integer=10
)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
@info "YiemAgent generatechat!() start " @__LINE__
# lessonDict = copy(JSON.parsefile("lesson.json"))
# lesson =
@@ -806,9 +731,9 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
- Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store.
# you should then respond to the user with interleaving plan, action_name, action_input
1) **plan**, Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
2) **action_name**, (Typically corresponds to the execution of the first step in your plan). Must be "CHAT_BOX
3) **action_input**, Dialogue you want to chat with the user according to your plan.
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.
# you should only respond in JSON format as described below
@@ -816,7 +741,7 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
"action_name": "...",
"action_input": "..."
"""
system_msg = Dict(
"role" => "system",
"content" => [
@@ -824,27 +749,11 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
]
)
chathistory = deepcopy(a.chathistory[2:end])
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"]
context =
"""
<internal_context_for_assistant>
<thought_history>
$(GeneralUtils.dict_to_string_html(a.memory["shortmem"]))
</thought_history>
</internal_context_for_assistant>
"""
# add context to text of the latest message (in the front).
# use for loop because in openai format, each msg may contain both text and image.
for d in chathistory[end]["content"]
if d["type"] == "text"
d["text"] = context * d["text"]
break
end
end
errornote = "N/A"
response = nothing # placeholder for show when error msg show up
@@ -855,7 +764,7 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
msg = Dict(
"model" => "gemma-4-E4B-it-UD-Q4_K_XL",
"messages" => a.chathistory,
"messages" => chathistory,
"temperature" => 0.7
)
@@ -863,10 +772,8 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
response = GeneralUtils.clean_json_response(response)
response = GeneralUtils.remove_french_accents(response)
think, response = GeneralUtils.extractthink(response)
response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to
response = strip(response)
@show response
responsedict = nothing
if occursin(requiredKeys[2], response)
@@ -877,25 +784,21 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
println("\nERROR YiemAgent generatechat() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
end
# fall back to normal text because LLM default to natural chat when it didn't use action_call
else
responsedict = OrderedDict(
"plan"=> "I will talk to the user",
"action_name"=> "CHAT_BOX",
"action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response
)
else
println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict ", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
continue
end
# check whether all answer's key points are in responsedict
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
if !ispass
errornote = errormsg
println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict ", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
continue
end
# if responsedict["action_name"] ∉ ["CHAT_BOX", "CHECK_WINE", "PRESENT_WINE_GUIDELINE", "END_CONVER_GUIDELINE"]
# if responsedict["action_name"] ∉ ["CHAT_BOX", "SEARCH_WINE_DATABASE", "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
@@ -903,188 +806,13 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
# println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# pprintln(responsedict)
return responsedict["action_input"]
responsedict["action_result"] = "Action result is the next user dialogue."
@info "YiemAgent generatechat!() end " @__LINE__
return (thoughtdict=responsedict, result_raw=responsedict["action_input"])
end
@info "YiemAgent generatechat() failed to generate a thought " @__LINE__
error("YiemAgent generatechat() failed to generate a thought ", response)
end
# function generatechat(a::T; recentevents::Integer=20, maxattempt=10
# )::String where {T<:agent}
# # lessonDict = copy(JSON.parsefile("lesson.json"))
# # lesson =
# # if isempty(lessonDict)
# # ""
# # else
# # lessons = Dict{String, Any}()
# # for (k, v) in lessonDict
# # lessons[k] = lessonDict[k][:lesson]
# # end
# # """
# # You have attempted to help the user before and failed, either because your reasoning for the
# # recommendation was incorrect or your response did not exactly match the user expectation.
# # The following lesson(s) give a plan to avoid failing to help the user in the same way you
# # did previously. Use them to improve your strategy to help the user.
# # Here are some lessons in JSON format:
# # $(JSON.json(lessons))
# # When providing the thought and action for the current trial, that into account these failed
# # trajectories and make sure not to repeat the same mistakes and incorrect answers.
# # """
# # end
# # recentevents_ind = GeneralUtils.recentElementsIndex(
# # length(a.memory["events"]), recentevents; includelatest=true)
# systemmsg =
# """
# <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_policy>
# <store_guidelines>
# - Greeting the customer warmly by ask them how could you help. Do not ask any other questions during this greeting.
# - Customer may provide images for you to look up.
# - Encourage the customer to explore different options and try new things.
# - If you are unable to locate the desired item in the database after 2 attempts, it may not be available in your inventory. In such cases, inform the user that the item is unavailable and suggest an alternative instead.
# - Your store carries only wine.
# - Vintage 0 means non-vintage.
# - Start searching the database as broadly as possible within the given information boundary to maximize the chances of finding. Avoid unnecessary parameters unless specified by the user. Refine the search subsequently.
# </store_guidelines>
# <situation>
# You are continuing the conversation with the user.
# </situation>
# <your role>
# Your name is $(a.name). You are a helpful sommelier for website-based $(a.retailername)'s wine store. You are working under your mentor supervision.
# </your role>
# <objective>
# 1) Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences.
# 2) Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences.
# </objective>
# <your responsibility includes>
# 1) According to the store's policy and guidelines, make an informed decision about what you need to do to achieve the objective
# 2) Keep the conversation with the customer going smoothly
# </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>
# Dialogue you want to chat with the user
# </you should then respond to the user with interleaving plan, action_name, action_input>
# <you should only respond in JSON format as described below>
# "CHAT_BOX": "..."
# </you should only respond in JSON format as described below>
# """
# system_msg = Dict(
# "role" => "system",
# "content" => [
# Dict("type" => "text", "text" => systemmsg),
# ]
# )
# chathistory = deepcopy(a.chathistory[2:end])
# pushfirst!(chathistory, system_msg)
# requiredKeys = ["CHAT_BOX"]
# context =
# """
# <internal_context_for_assistant>
# <thought_history>
# $(GeneralUtils.dict_to_string_html(a.memory["shortmem"]))
# </thought_history>
# </internal_context_for_assistant>
# """
# # add context to text of the latest message (in the front).
# # use for loop because in openai format, each msg may contain both text and image.
# for d in chathistory[end]["content"]
# if d["type"] == "text"
# d["text"] = context * d["text"]
# break
# end
# end
# errornote = "N/A"
# response = nothing # placeholder for show when error msg show up
# for attempt in 1:maxattempt
# if attempt > 1
# println("\nYiemAgent generatechat() attempt $attempt/$maxattempt ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# end
# msg = Dict(
# "model" => "gemma-4-E4B-it-UD-Q4_K_XL",
# "messages" => chathistory,
# "temperature" => 0.7
# )
# @info "YiemAgent generatechat() 2-2 attempt $attempt " @__LINE__
# response = a.context.text2textInstructLLM(a.id, msg)
# @info "YiemAgent generatechat() 2-3 attempt $attempt " @__LINE__
# response = GeneralUtils.clean_json_response(response)
# response = GeneralUtils.remove_french_accents(response)
# think, response = GeneralUtils.extractthink(response)
# response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to
# response = strip(response)
# @show response
# responsedict = nothing
# if occursin("CHAT_BOX", response)
# @info "YiemAgent generatechat() 2-4 attempt $attempt " @__LINE__
# try
# @info "YiemAgent generatechat() 2-5 attempt $attempt " @__LINE__
# _responsedict = JSON.parse(response)
# responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
# catch
# @info "YiemAgent generatechat() 2-6 attempt $attempt " @__LINE__
# println("\nERROR YiemAgent generatechat() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# continue
# end
# # fall back to normal text because LLM default to natural chat when it didn't use action_call
# else
# @info "YiemAgent generatechat() 2-7 attempt $attempt " @__LINE__
# responsedict = OrderedDict(
# "CHAT_BOX"=> response
# )
# end
# if length(keys(responsedict)) > length(requiredKeys)
# @info "YiemAgent generatechat() 2-7-1 attempt $attempt " @__LINE__
# continue
# end
# @info "YiemAgent generatechat() 2-8 attempt $attempt " @__LINE__
# # check whether all answer's key points are in responsedict
# ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
# if !ispass
# @info "YiemAgent generatechat() 2-9 attempt $attempt " @__LINE__
# errornote = errormsg
# println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict ", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
# continue
# end
# @info "YiemAgent generatechat() 2-12 attempt $attempt " @__LINE__
# # println("\nYiemAgent generatechat() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# # pprintln(responsedict)
# return responsedict["CHAT_BOX"]
# end
# @info "YiemAgent generatechat() 2-13 attempt $attempt " @__LINE__
# error("YiemAgent generatechat() failed to generate a thought ", response)
# end
function generatequestion(a, text2textInstructLLM::Function, timeline)::String
+401 -156
View File
@@ -1,10 +1,11 @@
module llmfunction
export virtualWineUserChatbox, jsoncorrection, checkwine!, # recommendbox,
export virtualWineUserChatbox, jsoncorrection, search_wine_database!, # recommendbox,
virtualWineUserRecommendbox, userChatbox, userRecommendbox, extractWineAttributes_1,
extractWineAttributes_2, paraphrase
extractWineAttributes_2, paraphrase, SQLexecution
using HTTP, JSON, URIs, Random, PrettyPrinting, UUIDs, Dates, DataFrames, DataStructures
using HTTP, JSON, URIs, Random, PrettyPrinting, UUIDs, Dates, DataFrames, DataStructures,
Base64
using GeneralUtils, SQLLLM
using ..type, ..util
@@ -211,7 +212,7 @@ pushfirst!(virtualCustomerChatHistory, Dict("name"=> "system", "text"=> systemms
receiverName= "text2textinstruct",
mqttBroker= config["mqttServerInfo"]["broker"],
mqttBrokerPort= config["mqttServerInfo"]["port"],
msgId = string(uuid4()) #CHANGE remove after testing finished
msgId = string(uuid4()) # remove after testing finished
)
outgoingMsg = Dict(
@@ -282,30 +283,384 @@ 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::T, thoughtdict::AbstractDict
function search_wine_database!(a::T, thoughtdict::AbstractDict; useSQLLLM::Bool=false
)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
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"])
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"
retrieve_attributes = ["winery", "wine_name", "wine_id", "vintage", "region", "country", "wine_type", "grape", "serving_temperature", "sweetness", "intensity", "tannin", "acidity", "tasting_notes", "price", "currency", "image_url", "retailer_name", "retailer_id"]
_inventoryquery = "$(thoughtdict["action_input"]), $wineattributes_1, $wineattributes_2, retailer_name: $(a.retailername), retailerid: $(a.retailerid)"
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")
thoughtdict["action_result"] = textresult
return (thoughtdict=thoughtdict, result_raw=result_raw)
if useSQLLLM
# 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")
thoughtdict["action_result"] = textresult
else
# direct query with possible sql instead of SQLLLM.
sql = generatesql(a, inventoryquery)
println("\nSQL: $sql ", @__FILE__, ":", @__LINE__, " $(Dates.now()) \n")
textresult, sql_result_df, success, _ = SQLexecution(a.context.executeSQL, sql)
items = nothing
if sql_result_df !== nothing
result_vec = GeneralUtils.dfToVectorDict(sql_result_df)
# get image
for d in result_vec
image_url_json_str = d["image_url"]
image_url_json_obj = JSON.parse(image_url_json_str)
base_url = "http://192.168.88.106:8080/"
if haskey(image_url_json_obj, "bottle")
url = base_url * image_url_json_obj["bottle"]
image_data = HTTP.get(url) # vector{int} data
image_base64_string = base64encode(image_data.body)
d["image"] = image_base64_string
else
d["image"] = nothing
end
end
items = result_vec # image is added to each item
end
thoughtdict["action_result"] = textresult
end
return (thoughtdict=thoughtdict, result_raw=items)
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.
- Use wildcard character (%) to search more effectively.
- 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.
- Overly strict condition usually yields empth result
# 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
#CHANGE use find_related_tables_for_user_question and inject only related table schema instead
# of hard code table schema. CPU embedding is too slow. use embedding service on GPU.
related_tables = a.context.find_related_tables_for_user_question(searchterm)
table_schema = ""
for table in related_tables
_table_schema_str = GeneralUtils.get_db_table_schema_simple(a.context.pg_conn_str, table)
table_schema_str = sprint(show, _table_schema_str) * "\n"
table_schema = table_schema * table_schema_str
end
context =
"""
<internal_context_for_assistant>
<database_table_schema>
$table_schema
</database_table_schema>
</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 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. Try loosening your search criteria.", result_raw=nothing, 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
"""
# Arguments
@@ -343,7 +698,6 @@ function extractWineAttributes_1(a::T1, input::T2; maxattempt=10
wine_name: name of the wine
winery: name of the winery
vintage: the year of the wine
region: a region, such as Burgundy, Bordeaux, Champagne, Napa Valley, Tuscany, California, Oregon, etc. Use "or" if there are multiple regions.
country: a country where wine is produced. Can be "Austria", "Australia", "France", "Germany", "Italy", "Portugal", "Spain", "United States". Use "or" if there are multiple countries.
wine_type: can be one of: "red", "white", "sparkling", "rose", "dessert" or "fortified"
grape_varietal: the name of the primary grape used to make the wine
@@ -352,12 +706,12 @@ function extractWineAttributes_1(a::T1, input::T2; maxattempt=10
wine_price_max: maximum price range of wine. Example: For wine price 20, wine_price_max will be 20. For wine price 10 to 100, wine_price_max will be 100.
occasion: the occasion the user is having the wine for
food_to_be_paired_with_wine: food that the user will be served with the wine such as poultry, fish, steak, etc
_keyword suffice is the related keyword that appears in user's query.
</you should then respond to the user with>
<you should only respond in JSON format as described below>
"wine_name": "...",
"winery": "...",
"vintage": "...",
"region": "...",
"country": "...",
"wine_type": "...",
"grape_varietal": "...",
@@ -372,7 +726,6 @@ function extractWineAttributes_1(a::T1, input::T2; maxattempt=10
"wine_name": "N/A",
"winery": "N/A",
"vintage": "N/A",
"region": "Tuscany or Napa Valley",
"country": "Italy or United States",
"wine_type": "red or white",
"grape_varietal": "Chenin Blanc or Riesling",
@@ -386,18 +739,17 @@ function extractWineAttributes_1(a::T1, input::T2; maxattempt=10
"wine_name": "Saumur Blanc",
"winery": "Domaine du Collier",
"vintage": "2019",
"region": "Saumur",
"country": "France",
"wine_type": "white",
"grape_varietal": "Merlot",
"tasting_notes": "plum",
"tasting_notes": "N/A",
"wine_price_min": "N/A",
"wine_price_max": "N/A",
"occasion": "N/A",
"food_to_be_paired_with_wine": "N/A"
</here are some examples>
"""
requiredKeys = ["wine_name", "winery", "vintage", "region", "country", "wine_type", "grape_varietal", "tasting_notes", "wine_price_min", "wine_price_max", "occasion", "food_to_be_paired_with_wine"]
requiredKeys = ["wine_name", "winery", "vintage", "country", "wine_type", "grape_varietal", "tasting_notes", "wine_price_min", "wine_price_max", "occasion", "food_to_be_paired_with_wine"]
errornote = ""
context =
"""
@@ -430,9 +782,6 @@ function extractWineAttributes_1(a::T1, input::T2; maxattempt=10
for attempt in 1:maxattempt
response = a.context.text2textInstructLLM(a.id, msg)
response = GeneralUtils.clean_json_response(response)
println("\n--- extractWineAttributes_1-1()")
println(response)
println("--- \n")
response = GeneralUtils.remove_french_accents(response)
think, response = GeneralUtils.extractthink(response)
@@ -460,6 +809,20 @@ function extractWineAttributes_1(a::T1, input::T2; maxattempt=10
_v = replace(v, r"\(.*?\)" => "")
responsedict[k] = _v
end
@info "YiemAgent extractWineAttributes_1() " @__LINE__
@show responsedict
@info "---\n" @__LINE__
# check each attributes against each column in a database table with BM25
for (k, v) in responsedict
if k ["wine_price_min", "wine_price_max"]
words_catalog = GeneralUtils.harvest_entity_catalog(a.context.pg_conn_str, "wine", k)
resolved_word = GeneralUtils.resolve_entity(v, words_catalog; threshold=0.9)
responsedict[k] = resolved_word
end
end
result = ""
for (k, v) in responsedict
# some time LLM generate text with "(some comment)". this line removes it
@@ -467,10 +830,13 @@ function extractWineAttributes_1(a::T1, input::T2; maxattempt=10
result *= "$k: $v, "
end
end
result = result[1:end-2] # remove the ending ", "
println("\n--- extractWineAttributes_1-2()")
println(result)
println("--- \n")
@info "YiemAgent extractWineAttributes_1() " @__LINE__
@show result
@info "---\n" @__LINE__
return result
end
error("extractWineAttributes_1() failed to get a response")
@@ -623,9 +989,6 @@ function extractWineAttributes_2(a::T1, input::T2)::String where {T1<:agent, T2<
for attempt in 1:10
response = a.context.text2textInstructLLM(a.id, msg)
response = GeneralUtils.clean_json_response(response)
println("\n--- extractWineAttributes_2-1()")
println(response)
println("--- \n")
response = GeneralUtils.remove_french_accents(response)
think, response = GeneralUtils.extractthink(response)
@@ -663,9 +1026,11 @@ function extractWineAttributes_2(a::T1, input::T2)::String where {T1<:agent, T2<
end
end
result = result[1:end-2] # remove the ending ", "
println("\n--- extractWineAttributes_2-2()")
println(result)
println("--- \n")
@info "YiemAgent extractWineAttributes_2() " @__LINE__
@show result
@info "---\n" @__LINE__
return result
end
error("extractWineAttributes_2() failed to get a response")
@@ -845,7 +1210,7 @@ function jsoncorrection(config::T1, input::T2, correctJsonExample::T3;
"""
# apply LLM specific instruct format
externalService = config["externalservice"]["text2textinstruct"]
externalService = config["externalservice"]["text2textinstruct"]
llminfo = externalService["llminfo"]
prompt =
if llminfo["name"] == "llama3instruct"
@@ -881,126 +1246,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
+19 -13
View File
@@ -16,6 +16,9 @@ mutable struct agentcontext
insertSQLVectorDB::Function
similarSommelierDecision::Function
insertSommelierDecision::Function
find_related_tables_for_user_question::Function
pg_conn_str::String
agentconfig::AbstractDict
end
abstract type agent end
@@ -93,6 +96,7 @@ mutable struct sommelier <: agent
name::String # agent name
id::String # agent id
retailername::String
retailerid::String
tools::Dict
maxHistoryMsg::Integer # e.g. 21th and earlier messages will get summarized
chathistory::Vector{Dict{String, Any}}
@@ -140,11 +144,12 @@ julia> agent = sommelier(context, name="WineExpert", id="123", retailername="MyW
```
"""
function sommelier(
context::agentcontext, # app context
context::agentcontext, # agent functions, db connect and other context
;
name::String= "Assistant",
id::String= string(uuid4()),
retailername::String= "retailer_name",
retailername::String= "not specified",
retailerid::String= "not specified",
maxHistoryMsg::Integer= 20,
chathistory::Vector{Dict{String, Any}} = Vector{Dict{String, Any}}(),
llmFormatName::String= "granite3"
@@ -216,6 +221,7 @@ function sommelier(
name,
id,
retailername,
retailerid,
tools,
maxHistoryMsg,
chathistory,
@@ -246,6 +252,7 @@ function sommelier(
- Your store carries only wine.
- Vintage 0 means non-vintage.
- Start searching the database as broadly as possible within the given information boundary to maximize the chances of finding. Avoid unnecessary parameters unless specified by the user. Refine the search subsequently.
- User usually ask for something similar. This means you should use the search term based on the profile they like.
# situation
You are having conversation with a customer.
@@ -267,25 +274,24 @@ function sommelier(
- 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.
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
# you should only respond in JSON format as described below (not Markdown format)
"plan": "...",
"action_name": "...",
"action_input": "..."
# 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."
"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.
"SEARCH_WINE_DATABASE", allows you to search information about wines you want in your inventory's database. The input is strictly supported search term including: retailer_name, wine price, winery, name, vintage, region, country, type of wine, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity.
Example query 1: "Dry, full-bodied red wine from Burgundy, France. Grape varietal could be Merlot or Syrah. price 100 to 1000 USD."
Example query 2: "Red or white wine, medium tannin, price under 700 USD"
Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
**WINE_PRESENTATION_GUIDELINE**, which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
**END_CONVER_GUIDELINE**, which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
Example query 3: "white wine from Tuscany, Italy or Bordeaux, France
"WINE_PRESENTATION_GUIDELINE", which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
"END_CONVER_GUIDELINE", which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
"""
system_msg = Dict(
+5 -5
View File
@@ -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
@@ -297,7 +297,7 @@ function createTimeline(events::T1; eventindex::Union{UnitRange, Nothing}=nothin
# timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"])\n"
# elseif event["action_name"] == "CHECKINVENTORY" && event["observation"] === nothing
# timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"]), observation: Not done yet.\n"
if event["action_name"] == "CHECK_WINE"
if event["action_name"] == "SEARCH_WINE_DATABASE"
timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"]), observation: $(event["observation"])\\n"
else
timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"])\\n"
+2 -2
View File
@@ -128,7 +128,7 @@ systemmsg =
# 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.
- **SEARCH_WINE_DATABASE** 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
@@ -157,7 +157,7 @@ openai_msg = Dict(
"content" => [
Dict("type" => "text", "text" =>
"""
" <plan>I will greet the customer warmly as Janie, acknowledge their request to find a similar wine for their wedding party based on the image, identify the wine type and country (Italian Sparkling Wine), and then use the CHECK_WINE action to search the inventory for suitable options.</plan>\n <action_name>CHAT_BOX</action_name>\n <action_input>Hello! I'm Janie, and I'd be delighted to help you find the perfect wine for your wedding party. That beautiful wine in the image appears to be an Italian sparkling wine, which is wonderful for a celebration like a wedding! Since you have an unlimited budget, I can certainly look for some truly exceptional options. To start, I will check our inventory for similar Italian sparkling wines that are perfect for a wedding celebration.</action_input><action_result> User response in the next message </action_result>"
" <plan>I will greet the customer warmly as Janie, acknowledge their request to find a similar wine for their wedding party based on the image, identify the wine type and country (Italian Sparkling Wine), and then use the SEARCH_WINE_DATABASE action to search the inventory for suitable options.</plan>\n <action_name>CHAT_BOX</action_name>\n <action_input>Hello! I'm Janie, and I'd be delighted to help you find the perfect wine for your wedding party. That beautiful wine in the image appears to be an Italian sparkling wine, which is wonderful for a celebration like a wedding! Since you have an unlimited budget, I can certainly look for some truly exceptional options. To start, I will check our inventory for similar Italian sparkling wines that are perfect for a wedding celebration.</action_input><action_result> User response in the next message </action_result>"
"""
),
]
+308 -198
View File
@@ -2,200 +2,236 @@ 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"],
payloads;
sender_id=sender_id,
msg_purpose="text2text",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalservice"]["fileserver"]["url"])
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"],
payloads;
sender_id=sender_id,
msg_purpose="text2text",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalService"]["fileserver"]["url"])
reply = NATS.request(agent_conn,
config["externalservice"]["servicesloadbalancer"]["nats"],
msg_envelope_json_str, timeout=120)
reply = NATS.request(agent_conn,
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)
_llm_response = incoming_env["payloads"][1][2]
llm_response = _llm_response["choices"][1]["message"]["content"]
return llm_response
end
#TESTING get text embedding from a LLM service
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"],
payloads;
msg_purpose="embedding",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalService"]["fileserver"]["url"])
reply = NATS.request(agent_conn,
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)
embedding_response = incoming_env["payloads"][1][2]
return embedding_response
end
#TESTING
function execute_sql_winedb(config::JSON.Object, 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 = LibPQ.execute(db_connection, sql)
LibPQ.close(db_connection)
return result
end
#TESTING
function similar_sql_vectordb(query; maxdistance::Integer=100)
tablename = "sqlllm_decision_repository"
# get embedding of the query
df = find_similar_text_from_vectordb(query, 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)
else
println("\n~~~ similar sql not found, max distance $maxdistance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
return (dict=nothing, distance=nothing)
incoming_env_json_str = String(reply.payload)
incoming_env = msghandler.smartunpack(incoming_env_json_str)
_llm_response = incoming_env["payloads"][1][2]
llm_response = _llm_response["choices"][1]["message"]["content"]
return llm_response
end
end
#TESTING
function insert_sql_vectordb(query::T1, SQL::T2; maxdistance::Integer=3) where {T1<:AbstractString, T2<:AbstractString}
tablename = "sqlllm_decision_repository"
# get embedding of the query
# query = state[:thoughtHistory][:question]
df = find_similar_text_from_vectordb(query, tablename,
"function_input_embedding", execute_sql_vectordb)
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 = _query_embedding["data"][1]["embedding"]
query = replace(query, "'" => "")
sql_base64 = base64encode(SQL)
sql_ = replace(SQL, "'" => "")
""" 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"],
payloads;
msg_purpose="embedding",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalservice"]["fileserver"]["url"])
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(sql)
_ = execute_sql_vectordb(sql)
reply = NATS.request(agent_conn,
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)
embedding_response = incoming_env["payloads"][1][2]
return embedding_response
end
end
#TESTING
function execute_sql_vectordb(sql::T) where {T<:AbstractString}
host_url, _port = split(config["SQLVectorDB"]["url"], ':')
port = parse(Int, _port)
dbname = config[:externalservice][:SQLVectorDB][:dbname]
user = config[:externalservice][:SQLVectorDB][:user]
password = config[:externalservice][:SQLVectorDB][: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
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)
distance = row == 0 ? Inf : df[1, :distance]
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__)
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__)
return nothing
end
end
#TESTING
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"]
# check whether there is close enough vector already store in vectorDB. if no, add, else skip
sql = """
SELECT *, $embeddingColumnName <-> '$embedding' as distance
FROM $tablename
ORDER BY distance LIMIT $limit;
"""
response = vectorDB(sql)
df = DataFrame(response)
return df
end
function insert_sommelier_decision(recentevents::T1, decision::T2; maxdistance::Integer=5
) where {T1<:AbstractString, T2<:AbstractDict}
tablename = "sommelier_decision_repository"
# find similar
df = find_similar_text_from_vectordb(recentevents, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
_embedding = get_embedding([recentevents])[1]
recentevents_embedding = _embedding["data"][1]["embedding"]
recentevents = replace(recentevents, "'" => "")
decision_json = JSON.json(decision)
decision_base64 = base64encode(decision_json)
decision = replace(decision_json, "'" => "")
""" 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
sql =
"""
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(sql)
_ = execute_sql_vectordb(sql)
else
println("~~~ similar decision previously cached, distance $distance ", @__FILE__, " ", @__LINE__)
LibPQ.close(db_connection)
return result
end
end
""" 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(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]
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--| 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 (result=nothing, distance=nothing)
end
end
""" 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]
df = find_similar_text_from_vectordb(query, tablename,
"function_input_embedding", execute_sql_vectordb)
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])
_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 =
"""
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(sql)
_ = execute_sql_vectordb(sql)
end
end
""" 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["externalservice"]["sommpanion_vectordb"]["url"], ':')
port = parse(Int, _port)
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
df = find_similar_text_from_vectordb(recentevents, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
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__)
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__)
return nothing
end
end
""" 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])
_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
FROM $tablename
ORDER BY distance LIMIT $limit;
"""
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"
# find similar
df = find_similar_text_from_vectordb(recentevents, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
_embedding = get_embedding([recentevents])[1]
recentevents_embedding = _embedding["data"][1]["embedding"]
recentevents = replace(recentevents, "'" => "")
decision_json = JSON.json(decision)
decision_base64 = base64encode(decision_json)
decision = replace(decision_json, "'" => "")
sql =
"""
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(sql)
_ = execute_sql_vectordb(sql)
else
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
@@ -210,32 +246,34 @@ agent_context = YiemAgent.agentcontext(
insert_sommelier_decision
)
# can't instantiate
agent = YiemAgent.sommelier(
agent_context;
name="Janie",
id=sessionId, # agent instance id
retailername="Yiem",
llmFormatName=""
)
# can't instantiate
agent = YiemAgent.sommelier(
agent_context;
name="Janie",
id=sessionId, # agent instance id
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")