Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 390b9d71b6 | |||
| b3ae0a9c50 | |||
| 1f3526b996 | |||
| 471da0c5ec | |||
| c355748e6f | |||
| f6895984d6 | |||
| 4ac5b97d53 | |||
| 6db50b6a52 | |||
| 096baad09d | |||
| c1120d811a | |||
| 7789748f25 | |||
| 9193260539 | |||
| 5f284883b3 | |||
| d2592ab6d6 | |||
| da21790263 | |||
| c59f6bfa61 | |||
| 3c91222462 | |||
| f62b8f14e7 | |||
| 7ffb720f86 |
+128
-96
@@ -1,8 +1,20 @@
|
||||
# This file is machine-generated - editing it directly is not advised
|
||||
|
||||
julia_version = "1.12.6"
|
||||
julia_version = "1.12.7"
|
||||
manifest_format = "2.0"
|
||||
project_hash = "aa163e2bf572632825162936e107be18384fd40f"
|
||||
project_hash = "43252cf86e6030e836ede74c563b58ab2f0f0548"
|
||||
|
||||
[[deps.AWS]]
|
||||
deps = ["Base64", "Compat", "Dates", "Downloads", "GitHub", "HTTP", "IniFile", "JSON", "MD5", "Mocking", "OrderedCollections", "Random", "SHA", "ScopedValues", "Sockets", "URIs", "UUIDs", "XMLDict"]
|
||||
git-tree-sha1 = "842075b12a7f763c5f815a04037a99b6ac346df9"
|
||||
uuid = "fbe9abb3-538b-5e4e-ba9e-bc94f4f92ebc"
|
||||
version = "1.99.0"
|
||||
|
||||
[[deps.AWSS3]]
|
||||
deps = ["AWS", "ArrowTypes", "Base64", "Compat", "Dates", "EzXML", "FilePathsBase", "HTTP", "MbedTLS", "Mocking", "OrderedCollections", "Retry", "SymDict", "URIs", "UUIDs", "XMLDict"]
|
||||
git-tree-sha1 = "af99cea71364c8c4483405a6b03697d197ab4d3b"
|
||||
uuid = "1c724243-ef5b-51ab-93f4-b0a88ac62a95"
|
||||
version = "0.11.6"
|
||||
|
||||
[[deps.Accessors]]
|
||||
deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"]
|
||||
@@ -86,9 +98,9 @@ version = "1.11.0"
|
||||
|
||||
[[deps.CSV]]
|
||||
deps = ["CodecZlib", "Dates", "FilePathsBase", "InlineStrings", "Mmap", "Parsers", "PooledArrays", "PrecompileTools", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings", "WorkerUtilities"]
|
||||
git-tree-sha1 = "8d8e0b0f350b8e1c91420b5e64e5de774c2f0f4d"
|
||||
git-tree-sha1 = "abed1e735dd4152f48c90cf0767e1790e25f332f"
|
||||
uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
|
||||
version = "0.10.16"
|
||||
version = "0.10.17"
|
||||
|
||||
[[deps.CodeTracking]]
|
||||
deps = ["InteractiveUtils", "REPL", "UUIDs"]
|
||||
@@ -110,9 +122,9 @@ version = "0.4.6"
|
||||
|
||||
[[deps.CodecZlib]]
|
||||
deps = ["TranscodingStreams", "Zlib_jll"]
|
||||
git-tree-sha1 = "962834c22b66e32aa10f7611c08c8ca4e20749a9"
|
||||
git-tree-sha1 = "970758a3d591a2a5c2a907c53f2e2f8c1b1d3537"
|
||||
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
|
||||
version = "0.7.8"
|
||||
version = "0.7.9"
|
||||
|
||||
[[deps.CodecZstd]]
|
||||
deps = ["TranscodingStreams", "Zstd_jll"]
|
||||
@@ -121,9 +133,10 @@ uuid = "6b39b394-51ab-5f42-8807-6242bab2b4c2"
|
||||
version = "0.8.7"
|
||||
|
||||
[[deps.CommonSolve]]
|
||||
git-tree-sha1 = "cf963add2340ad9960e5eb22844e61ad8f931fe1"
|
||||
deps = ["PrecompileTools"]
|
||||
git-tree-sha1 = "6c389fa857f6ca5a95474b52a52023fd77f24cb7"
|
||||
uuid = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2"
|
||||
version = "0.2.13"
|
||||
version = "0.2.14"
|
||||
|
||||
[[deps.Compat]]
|
||||
deps = ["TOML", "UUIDs"]
|
||||
@@ -143,7 +156,7 @@ version = "0.1.1"
|
||||
[[deps.CompilerSupportLibraries_jll]]
|
||||
deps = ["Artifacts", "Libdl"]
|
||||
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
|
||||
version = "1.3.0+1"
|
||||
version = "1.3.1+2"
|
||||
|
||||
[[deps.CompositionsBase]]
|
||||
git-tree-sha1 = "802bb88cd69dfd1509f6670416bd4434015693ad"
|
||||
@@ -181,9 +194,9 @@ uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
|
||||
version = "4.2.0"
|
||||
|
||||
[[deps.DBInterface]]
|
||||
git-tree-sha1 = "a444404b3f94deaa43ca2a58e18153a82695282b"
|
||||
git-tree-sha1 = "265d7f87f329c063cbde41920f9d00713a43cedd"
|
||||
uuid = "a10d1c49-ce27-4219-8d33-6db1a4562965"
|
||||
version = "2.6.1"
|
||||
version = "2.7.0"
|
||||
|
||||
[[deps.DataAPI]]
|
||||
git-tree-sha1 = "abe83f3a2f1b857aac70ef8b269080af17764bbe"
|
||||
@@ -238,9 +251,9 @@ version = "1.11.0"
|
||||
|
||||
[[deps.Distributions]]
|
||||
deps = ["AliasTables", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "Roots", "SpecialFunctions", "Statistics", "StatsAPI", "StatsBase", "StatsFuns"]
|
||||
git-tree-sha1 = "d2facc77c08c1c2bfb1a77c148edd05b3db5410b"
|
||||
git-tree-sha1 = "a958ab3a40c755563f5e1405c0846cb0446bf19d"
|
||||
uuid = "31c24e10-a181-5473-b8eb-7969acd0382f"
|
||||
version = "0.25.130"
|
||||
version = "0.25.131"
|
||||
|
||||
[deps.Distributions.extensions]
|
||||
DistributionsChainRulesCoreExt = "ChainRulesCore"
|
||||
@@ -274,15 +287,11 @@ git-tree-sha1 = "d2e49e7efd29719d6f28b891b0e0e159daa9d2b4"
|
||||
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
|
||||
version = "0.1.11"
|
||||
|
||||
[[deps.FileIO]]
|
||||
deps = ["Pkg", "Requires", "UUIDs"]
|
||||
git-tree-sha1 = "6621fef488e496356c9c9625d0562c12a6070819"
|
||||
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
|
||||
version = "1.20.0"
|
||||
weakdeps = ["HTTP"]
|
||||
|
||||
[deps.FileIO.extensions]
|
||||
HTTPExt = "HTTP"
|
||||
[[deps.EzXML]]
|
||||
deps = ["Printf", "XML2_jll"]
|
||||
git-tree-sha1 = "7ea1aa5869e2626ccae84480e4f37185bc6f41d3"
|
||||
uuid = "8f5d6c58-4d21-5cfd-889c-e3ad7ee6a615"
|
||||
version = "1.2.3"
|
||||
|
||||
[[deps.FilePathsBase]]
|
||||
deps = ["Compat", "Dates"]
|
||||
@@ -318,17 +327,24 @@ uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
|
||||
version = "1.11.0"
|
||||
|
||||
[[deps.Gamma]]
|
||||
git-tree-sha1 = "86f86b6168a016ed88e4ae4e64577b98c3b59e8e"
|
||||
deps = ["LogExpFunctions"]
|
||||
git-tree-sha1 = "becc397f7cfb06e343496ae6ffb04818a851da51"
|
||||
uuid = "a0844989-3bd2-4988-8bea-c9407ab0941b"
|
||||
version = "1.1.0"
|
||||
version = "1.2.0"
|
||||
|
||||
[[deps.GeneralUtils]]
|
||||
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "Distributions", "Graphs", "HTTP", "JSON", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "SHA", "StringDistances", "UUIDs"]
|
||||
git-tree-sha1 = "129b8fa1bf3bf6d8c0a080f39db09b9b986ef8de"
|
||||
deps = ["AWS", "AWSS3", "CSV", "DataFrames", "DataStructures", "Dates", "Distributions", "Graphs", "HTTP", "JSON", "LibPQ", "NATS", "OrderedCollections", "PrettyPrinting", "Random", "Revise", "SHA", "StringDistances", "URIs", "UUIDs"]
|
||||
git-tree-sha1 = "4d7ff3b02a9cbd6d4f65fea43551b0bca6a83a22"
|
||||
repo-rev = "main"
|
||||
repo-url = "https://git.yiem.cc/ton/GeneralUtils"
|
||||
uuid = "c6c72f09-b708-4ac8-ac7c-2084d70108fe"
|
||||
version = "0.5.11"
|
||||
version = "0.6.9"
|
||||
|
||||
[[deps.GitHub]]
|
||||
deps = ["Base64", "Dates", "HTTP", "JSON", "MbedTLS", "Sockets", "SodiumSeal", "URIs"]
|
||||
git-tree-sha1 = "33de1bc5665494f0a9669fd6027e28180709d874"
|
||||
uuid = "bc5e4493-9b4d-5f90-b8aa-2b2bcaad7a26"
|
||||
version = "5.13.0"
|
||||
|
||||
[[deps.Graphs]]
|
||||
deps = ["ArnoldiMethod", "DataStructures", "Inflate", "LinearAlgebra", "Random", "SimpleTraits", "SparseArrays", "Statistics"]
|
||||
@@ -345,9 +361,9 @@ version = "1.14.0"
|
||||
|
||||
[[deps.HTTP]]
|
||||
deps = ["Base64", "CodecZlib", "Dates", "EnumX", "PrecompileTools", "Random", "Reseau", "SHA", "URIs", "UUIDs", "Zlib_jll"]
|
||||
git-tree-sha1 = "0a58fbbdee93d132a2fb1159b7f5e1b5c2465e71"
|
||||
git-tree-sha1 = "49a90cd540681d5b79bf5c8ca13c92677e37005e"
|
||||
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
|
||||
version = "2.6.4"
|
||||
version = "2.6.6"
|
||||
|
||||
[[deps.HashArrayMappedTries]]
|
||||
git-tree-sha1 = "2eaa69a7cab70a52b9687c8bf950a5a93ec895ae"
|
||||
@@ -377,6 +393,11 @@ git-tree-sha1 = "d1b1b796e47d94588b3757fe84fbf65a5ec4a80d"
|
||||
uuid = "d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9"
|
||||
version = "0.1.5"
|
||||
|
||||
[[deps.IniFile]]
|
||||
git-tree-sha1 = "f550e6e32074c939295eb5ea6de31849ac2c9625"
|
||||
uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f"
|
||||
version = "0.5.1"
|
||||
|
||||
[[deps.InlineStrings]]
|
||||
git-tree-sha1 = "8f3d257792a522b4601c24a577954b0a8cd7334d"
|
||||
uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48"
|
||||
@@ -436,9 +457,9 @@ version = "1.8.0"
|
||||
|
||||
[[deps.JSON]]
|
||||
deps = ["Dates", "Logging", "Parsers", "PrecompileTools", "StructUtils", "UUIDs", "Unicode"]
|
||||
git-tree-sha1 = "65979512c25a0727f050e6e4be40f0fd9ec893f7"
|
||||
git-tree-sha1 = "c7345ab1a7ca4dc8a02c9f6510da0d9857bbe513"
|
||||
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
|
||||
version = "1.7.0"
|
||||
version = "1.7.1"
|
||||
weakdeps = ["ArrowTypes"]
|
||||
|
||||
[deps.JSON.extensions]
|
||||
@@ -471,18 +492,10 @@ git-tree-sha1 = "0f2899fdadaab4b8f57db558ba21bdb4fb52f1f0"
|
||||
uuid = "b39eb1a6-c29a-53d7-8c32-632cd16f18da"
|
||||
version = "1.21.3+0"
|
||||
|
||||
[[deps.LLMMCTS]]
|
||||
deps = ["GeneralUtils", "JSON", "PrettyPrinting"]
|
||||
git-tree-sha1 = "3dff98131dfa79be8c9bd84fc51cb0ba1832c472"
|
||||
repo-rev = "main"
|
||||
repo-url = "https://git.yiem.cc/ton/LLMMCTS"
|
||||
uuid = "d76c5a4d-449e-4835-8cc4-dd86ec44f241"
|
||||
version = "0.1.5"
|
||||
|
||||
[[deps.LaTeXStrings]]
|
||||
git-tree-sha1 = "dda21b8cbd6a6c40d9d02a73230f9d70fed6918c"
|
||||
git-tree-sha1 = "f88f3ccef05a6a72a0cf0ed417c8fd68530f4ab2"
|
||||
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
|
||||
version = "1.4.0"
|
||||
version = "1.4.1"
|
||||
|
||||
[[deps.LayerDicts]]
|
||||
git-tree-sha1 = "6087ad3521d6278ebe5c27ae55e7bbb15ca312cb"
|
||||
@@ -530,6 +543,12 @@ version = "1.11.3+1"
|
||||
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
|
||||
version = "1.11.0"
|
||||
|
||||
[[deps.Libiconv_jll]]
|
||||
deps = ["Artifacts", "JLLWrappers", "Libdl"]
|
||||
git-tree-sha1 = "be484f5c92fad0bd8acfef35fe017900b0b73809"
|
||||
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
|
||||
version = "1.18.0+0"
|
||||
|
||||
[[deps.LinearAlgebra]]
|
||||
deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"]
|
||||
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
|
||||
@@ -567,6 +586,12 @@ git-tree-sha1 = "191686b1ac1ea9c89fc52e996ad15d1d241d1e33"
|
||||
uuid = "5ced341a-0733-55b8-9ab6-a4889d929147"
|
||||
version = "1.10.1+0"
|
||||
|
||||
[[deps.MD5]]
|
||||
deps = ["Random", "SHA"]
|
||||
git-tree-sha1 = "1576f756617d31eb397a4a517b68562fd28dc2b4"
|
||||
uuid = "6ac74813-4b46-53a4-afec-0b5dc9d7885c"
|
||||
version = "0.2.3"
|
||||
|
||||
[[deps.MacroTools]]
|
||||
git-tree-sha1 = "1e0228a030642014fe5cfe68c2c0a818f9e3f522"
|
||||
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
|
||||
@@ -655,7 +680,7 @@ version = "0.8.7+0"
|
||||
[[deps.OpenSSL_jll]]
|
||||
deps = ["Artifacts", "Libdl"]
|
||||
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
|
||||
version = "3.5.4+0"
|
||||
version = "3.5.6+0"
|
||||
|
||||
[[deps.OpenSpecFun_jll]]
|
||||
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl"]
|
||||
@@ -684,15 +709,6 @@ git-tree-sha1 = "3de8f5e6e90ebfa8d6d1f86997d6cdcd6a912ff3"
|
||||
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
|
||||
version = "2.8.7"
|
||||
|
||||
[[deps.Pkg]]
|
||||
deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "Random", "SHA", "TOML", "Tar", "UUIDs", "p7zip_jll"]
|
||||
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
|
||||
version = "1.12.1"
|
||||
weakdeps = ["REPL"]
|
||||
|
||||
[deps.Pkg.extensions]
|
||||
REPLExt = "REPL"
|
||||
|
||||
[[deps.PooledArrays]]
|
||||
deps = ["DataAPI", "Future"]
|
||||
git-tree-sha1 = "36d8b4b899628fb92c2749eb488d884a926614d3"
|
||||
@@ -718,9 +734,9 @@ version = "0.4.3"
|
||||
|
||||
[[deps.PrettyTables]]
|
||||
deps = ["Crayons", "LaTeXStrings", "Markdown", "PrecompileTools", "Printf", "REPL", "Reexport", "StringManipulation", "Tables"]
|
||||
git-tree-sha1 = "4ac881f5432bd93463a41767a814a45245be22b6"
|
||||
git-tree-sha1 = "1b8aa19f229b1cea7fc93874a52e49db6a854450"
|
||||
uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d"
|
||||
version = "3.4.6"
|
||||
version = "3.4.8"
|
||||
|
||||
[deps.PrettyTables.extensions]
|
||||
PrettyTablesExcelExt = "XLSX"
|
||||
@@ -781,15 +797,20 @@ version = "1.3.1"
|
||||
|
||||
[[deps.Reseau]]
|
||||
deps = ["NetworkOptions", "OpenSSL_jll", "PrecompileTools", "Random", "SHA"]
|
||||
git-tree-sha1 = "701ef63506992668c0069a4d1ac1540b77258e6c"
|
||||
git-tree-sha1 = "aaee74fab545e9af4b21d10c2203c93c636c4ae0"
|
||||
uuid = "802f3686-a58f-41ce-bb0c-3c43c75bba36"
|
||||
version = "1.3.6"
|
||||
version = "1.4.1"
|
||||
|
||||
[[deps.Retry]]
|
||||
git-tree-sha1 = "41ac127cd281bb33e42aba46a9d3b25cd35fc6d5"
|
||||
uuid = "20febd7b-183b-5ae2-ac4a-720e7ce64774"
|
||||
version = "0.4.1"
|
||||
|
||||
[[deps.Revise]]
|
||||
deps = ["CRC32c", "CodeTracking", "FileWatching", "JuliaInterpreter", "LibGit2", "LoweredCodeUtils", "OrderedCollections", "Preferences", "REPL", "UUIDs"]
|
||||
git-tree-sha1 = "ec46aed6a3a8cc6b67839ca361e7b4aa32eaeee1"
|
||||
git-tree-sha1 = "ab0f5630e37968bc49b8c4cedd3279a7d30b9486"
|
||||
uuid = "295af30f-e4ad-537b-8983-00126c2a3abe"
|
||||
version = "3.16.3"
|
||||
version = "3.17.0"
|
||||
weakdeps = ["Distributed"]
|
||||
|
||||
[deps.Revise.extensions]
|
||||
@@ -809,9 +830,9 @@ version = "0.5.2+0"
|
||||
|
||||
[[deps.Roots]]
|
||||
deps = ["Accessors", "CommonSolve", "Printf"]
|
||||
git-tree-sha1 = "7fb25a964849d90a0446366cdefca822e0e84900"
|
||||
git-tree-sha1 = "13a9e0164267bb9ebc55c1c5d72fceea8f09555b"
|
||||
uuid = "f2b01f46-fcfa-551c-844a-d8ac1e96c665"
|
||||
version = "3.0.6"
|
||||
version = "3.0.7"
|
||||
|
||||
[deps.Roots.extensions]
|
||||
RootsChainRulesCoreExt = "ChainRulesCore"
|
||||
@@ -833,14 +854,6 @@ version = "3.0.6"
|
||||
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
|
||||
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 = "bae2fd2e2b087753fbb3415896be41df1ae0eb90"
|
||||
repo-rev = "main"
|
||||
repo-url = "https://git.yiem.cc/ton/SQLLLM"
|
||||
uuid = "2ebc79c7-cc10-4a3a-9665-d2e1d61e63d3"
|
||||
version = "0.2.8"
|
||||
|
||||
[[deps.SQLStrings]]
|
||||
git-tree-sha1 = "55de0530689832b1d3d43491ee6b67bd54d3323c"
|
||||
uuid = "af517c2e-c243-48fa-aab8-efac3db270f5"
|
||||
@@ -884,6 +897,12 @@ git-tree-sha1 = "907703e0d50846f300650d7225bdcab145b7bca9"
|
||||
uuid = "4f5b5e99-b0ad-42cd-b47a-334e172ec8bd"
|
||||
version = "1.1.2"
|
||||
|
||||
[[deps.SodiumSeal]]
|
||||
deps = ["Base64", "Libdl", "libsodium_jll"]
|
||||
git-tree-sha1 = "80cef67d2953e33935b41c6ab0a178b9987b1c99"
|
||||
uuid = "2133526b-2bfb-4018-ac12-889fb3908a75"
|
||||
version = "0.1.1"
|
||||
|
||||
[[deps.SortingAlgorithms]]
|
||||
deps = ["DataStructures"]
|
||||
git-tree-sha1 = "13cd91cc9be159e3f4d95b857fa2aa383b53772a"
|
||||
@@ -897,9 +916,9 @@ version = "1.12.0"
|
||||
|
||||
[[deps.SpecialFunctions]]
|
||||
deps = ["IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
|
||||
git-tree-sha1 = "c3ac026e735264e9bdc6a9bcbd1b1e781b36e3bc"
|
||||
git-tree-sha1 = "429071b23f4c9a13fb6582f807cc2ef454082408"
|
||||
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
|
||||
version = "2.8.3"
|
||||
version = "2.9.0"
|
||||
|
||||
[deps.SpecialFunctions.extensions]
|
||||
SpecialFunctionsChainRulesCoreExt = "ChainRulesCore"
|
||||
@@ -909,9 +928,9 @@ version = "2.8.3"
|
||||
|
||||
[[deps.StaticArrays]]
|
||||
deps = ["LinearAlgebra", "PrecompileTools", "Random", "StaticArraysCore"]
|
||||
git-tree-sha1 = "246a8bb2e6667f832eea063c3a56aef96429a3db"
|
||||
git-tree-sha1 = "fac51faf3bb96e8bc0bf6f9f39ca4955652776bb"
|
||||
uuid = "90137ffa-7385-5640-81b9-e52037218182"
|
||||
version = "1.9.18"
|
||||
version = "1.9.19"
|
||||
|
||||
[deps.StaticArrays.extensions]
|
||||
StaticArraysChainRulesCoreExt = "ChainRulesCore"
|
||||
@@ -928,9 +947,9 @@ version = "1.4.4"
|
||||
|
||||
[[deps.Statistics]]
|
||||
deps = ["LinearAlgebra"]
|
||||
git-tree-sha1 = "ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0"
|
||||
git-tree-sha1 = "389592b8592e5fb48f498ff60dc6acb4a0e62953"
|
||||
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
|
||||
version = "1.11.1"
|
||||
version = "1.11.4"
|
||||
weakdeps = ["SparseArrays"]
|
||||
|
||||
[deps.Statistics.extensions]
|
||||
@@ -944,9 +963,9 @@ version = "1.8.0"
|
||||
|
||||
[[deps.StatsBase]]
|
||||
deps = ["AliasTables", "DataAPI", "DataStructures", "IrrationalConstants", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
|
||||
git-tree-sha1 = "e4d7a1a0edc20af42689ea6f4f3587a2175d50ee"
|
||||
git-tree-sha1 = "adb9da019510162e67a4493fc235c23203d8b09e"
|
||||
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
|
||||
version = "0.34.12"
|
||||
version = "0.34.13"
|
||||
|
||||
[[deps.StatsFuns]]
|
||||
deps = ["HypergeometricFunctions", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"]
|
||||
@@ -964,15 +983,15 @@ version = "2.2.1"
|
||||
|
||||
[[deps.StringDistances]]
|
||||
deps = ["Distances", "StatsAPI"]
|
||||
git-tree-sha1 = "cd83a04baf746e3b43b83c61b7de77ab0409b80a"
|
||||
git-tree-sha1 = "456f343c7a6c8f52d8b501c0da2a05538ab1b907"
|
||||
uuid = "88034a9c-02f8-509d-84a9-84ec65e18404"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
|
||||
[[deps.StringManipulation]]
|
||||
deps = ["PrecompileTools"]
|
||||
git-tree-sha1 = "8a90c1d77c3277a5d43b83927b3cbe2c70a37484"
|
||||
git-tree-sha1 = "773065c6e0e903924a9d838259be74338422aef2"
|
||||
uuid = "892a3eda-7b42-436c-8928-eab12a02cf0e"
|
||||
version = "0.4.7"
|
||||
version = "0.5.0"
|
||||
|
||||
[[deps.StringViews]]
|
||||
git-tree-sha1 = "f2dcb92855b31ad92fe8f079d4f75ac57c93e4b8"
|
||||
@@ -987,9 +1006,9 @@ version = "1.11.0"
|
||||
|
||||
[[deps.StructUtils]]
|
||||
deps = ["Dates", "UUIDs"]
|
||||
git-tree-sha1 = "c65ae4aa47e543c278aea0a3468786d33021a3ff"
|
||||
git-tree-sha1 = "2d0fc55c61321ba245c47be599570d11bac50303"
|
||||
uuid = "ec057cc2-7a8d-4b58-b3b3-92acb9f63b42"
|
||||
version = "2.8.4"
|
||||
version = "2.8.5"
|
||||
|
||||
[deps.StructUtils.extensions]
|
||||
StructUtilsMeasurementsExt = ["Measurements"]
|
||||
@@ -1014,6 +1033,12 @@ deps = ["Artifacts", "Libdl", "libblastrampoline_jll"]
|
||||
uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c"
|
||||
version = "7.8.3+2"
|
||||
|
||||
[[deps.SymDict]]
|
||||
deps = ["Test"]
|
||||
git-tree-sha1 = "0108ccdaea3ef69d9680eeafc8d5ad198b896ec8"
|
||||
uuid = "2da68c74-98d7-5633-99d6-8493888d7b1e"
|
||||
version = "0.3.0"
|
||||
|
||||
[[deps.TOML]]
|
||||
deps = ["Dates"]
|
||||
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
|
||||
@@ -1021,9 +1046,9 @@ version = "1.0.3"
|
||||
|
||||
[[deps.TZJData]]
|
||||
deps = ["Artifacts"]
|
||||
git-tree-sha1 = "72df96b3a595b7aab1e101eb07d2a435963a97e2"
|
||||
git-tree-sha1 = "d3b30a9f29a898e21fb4bdf280101b7a12e1f39c"
|
||||
uuid = "dc5dba14-91b3-4cab-a142-028a31da12f7"
|
||||
version = "1.5.0+2025b"
|
||||
version = "1.5.1+2025b"
|
||||
|
||||
[[deps.TableTraits]]
|
||||
deps = ["IteratorInterfaceExtensions"]
|
||||
@@ -1033,14 +1058,9 @@ version = "1.0.1"
|
||||
|
||||
[[deps.Tables]]
|
||||
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "OrderedCollections", "TableTraits"]
|
||||
git-tree-sha1 = "0f38a06c83f0007bbab3cf911262841c9a0f07e0"
|
||||
git-tree-sha1 = "a94d9bdda1b7bed0046cea645639ab3f62196fac"
|
||||
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
|
||||
version = "1.13.0"
|
||||
|
||||
[[deps.Tar]]
|
||||
deps = ["ArgTools", "SHA"]
|
||||
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
|
||||
version = "1.10.0"
|
||||
version = "1.14.0"
|
||||
|
||||
[[deps.Test]]
|
||||
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
|
||||
@@ -1063,9 +1083,9 @@ uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
|
||||
version = "0.11.3"
|
||||
|
||||
[[deps.URIs]]
|
||||
git-tree-sha1 = "3b0738bd7c5645641845da25cbd99800b8718689"
|
||||
git-tree-sha1 = "908fec9df6c5de98548ead82a468c95ccf6cd263"
|
||||
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
|
||||
version = "1.6.2"
|
||||
version = "1.7.0"
|
||||
|
||||
[[deps.UTCDateTimes]]
|
||||
deps = ["Dates", "TimeZones"]
|
||||
@@ -1093,8 +1113,20 @@ git-tree-sha1 = "cd1659ba0d57b71a464a29e64dbc67cfe83d54e7"
|
||||
uuid = "76eceee3-57b5-4d4a-8e66-0e911cebbf60"
|
||||
version = "1.6.1"
|
||||
|
||||
[[deps.XML2_jll]]
|
||||
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Zlib_jll"]
|
||||
git-tree-sha1 = "3f3315d89fc954a28f5b471bce698ed6e27481be"
|
||||
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
|
||||
version = "2.15.3+0"
|
||||
|
||||
[[deps.XMLDict]]
|
||||
deps = ["EzXML", "IterTools", "OrderedCollections"]
|
||||
git-tree-sha1 = "8e8cdc9c93e1f442eba471b56db6f86ffeb1a33a"
|
||||
uuid = "228000da-037f-5747-90a9-8195ccbf91a5"
|
||||
version = "0.4.2"
|
||||
|
||||
[[deps.YiemAgent]]
|
||||
deps = ["Base64", "CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "SQLLLM", "Serialization", "URIs", "UUIDs"]
|
||||
deps = ["Base64", "CSV", "DataFrames", "DataStructures", "Dates", "HTTP", "JSON", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "Serialization", "URIs", "UUIDs", "msghandler"]
|
||||
path = "."
|
||||
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
|
||||
version = "0.8.0"
|
||||
@@ -1122,12 +1154,12 @@ uuid = "a9144af2-ca23-56d9-984f-0d03f7b5ccf8"
|
||||
version = "1.0.21+0"
|
||||
|
||||
[[deps.msghandler]]
|
||||
deps = ["Arrow", "Base64", "DataFrames", "Dates", "GeneralUtils", "HTTP", "JSON", "NATS", "PrettyPrinting", "Revise", "UUIDs"]
|
||||
git-tree-sha1 = "e82a79cf6602541ea25409aded57b2ace4a7c29f"
|
||||
deps = ["Arrow", "Base64", "DataFrames", "Dates", "GeneralUtils", "HTTP", "JSON", "NATS", "PrettyPrinting", "UUIDs"]
|
||||
git-tree-sha1 = "e7889a120327db84cdf1b1acf4a2c7caba6e8ef7"
|
||||
repo-rev = "main"
|
||||
repo-url = "https://git.yiem.cc/ton/msghandler"
|
||||
uuid = "f2724d33-f338-4a57-b9f8-1be882570d10"
|
||||
version = "1.2.1"
|
||||
version = "1.4.0"
|
||||
|
||||
[[deps.nghttp2_jll]]
|
||||
deps = ["Artifacts", "Libdl"]
|
||||
|
||||
+2
-6
@@ -12,13 +12,11 @@ Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
|
||||
GeneralUtils = "c6c72f09-b708-4ac8-ac7c-2084d70108fe"
|
||||
HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3"
|
||||
JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
|
||||
LLMMCTS = "d76c5a4d-449e-4835-8cc4-dd86ec44f241"
|
||||
LibPQ = "194296ae-ab2e-5f79-8cd4-7183a0a5a0d1"
|
||||
NATS = "55e73f9c-eeeb-467f-b4cc-a633fde63d2a"
|
||||
PrettyPrinting = "54e16d92-306c-5ea0-a30b-337be88ac337"
|
||||
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
|
||||
Revise = "295af30f-e4ad-537b-8983-00126c2a3abe"
|
||||
SQLLLM = "2ebc79c7-cc10-4a3a-9665-d2e1d61e63d3"
|
||||
Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
|
||||
URIs = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
|
||||
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
|
||||
@@ -28,10 +26,8 @@ msghandler = "f2724d33-f338-4a57-b9f8-1be882570d10"
|
||||
Base64 = "1.11.0"
|
||||
CSV = "0.10.15"
|
||||
DataFrames = "1.7.0"
|
||||
GeneralUtils = "0.5.10"
|
||||
GeneralUtils = "0.6.9"
|
||||
HTTP = "2.4.0"
|
||||
JSON = "1.6.1"
|
||||
LLMMCTS = "0.1.5"
|
||||
NATS = "0.1.0"
|
||||
SQLLLM = "0.2.8"
|
||||
msghandler = "1.2.1"
|
||||
msghandler = "1.4.0"
|
||||
|
||||
@@ -1,34 +1,311 @@
|
||||
# YiemAgent
|
||||
|
||||
Julia framework for building agents with tool use.
|
||||
Julia framework for building agents with tool use and MCP (Model Context Protocol) support.
|
||||
|
||||
## Getting Started
|
||||
## Quick Start
|
||||
|
||||
1. Install dependencies: `]add JSON, DataStructures, UUIDs, Dates, ...`
|
||||
2. Create a `yiemAgent` with `loadTools("src/tools")`
|
||||
3. Call `runAgent(agent, "message")` then `takeResponse(agent)`
|
||||
```julia
|
||||
using YiemAgent
|
||||
|
||||
# 1. Create an LLM callable (see "Custom LLM Callable" below)
|
||||
llmCall = ...
|
||||
|
||||
# 2. Create a callable MCP server (see "MCP Server Integration" below)
|
||||
mcpServer = ...
|
||||
|
||||
# 3. Create the agent
|
||||
agent = yiemAgent(llmCall; mcpServer=mcpServer, eventSink=println)
|
||||
|
||||
# 4. Interact
|
||||
promptAgent(agent, "What tools do you have?")
|
||||
response = takeResponse(agent)
|
||||
|
||||
# 5. Stop when done
|
||||
stopAgent(agent)
|
||||
```
|
||||
|
||||
## Agent API
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `promptAgent(agent, text)` | Send plain text to the agent's input channel |
|
||||
| `promptAgent(agent, msg)` | Send a structured message (OpenAI format dict) to the input channel |
|
||||
| `takeResponse(agent)` | Block and take the agent's response from output channel |
|
||||
| `followUp(agent, text)` | Send plain text follow-up while agent is still processing |
|
||||
| `followUp(agent, msg)` | Send a structured follow-up (OpenAI format dict) while agent is processing |
|
||||
| `stopAgent(agent)` | Gracefully stop the agent and close channels |
|
||||
|
||||
## Creating a yiemAgent
|
||||
|
||||
```julia
|
||||
yiemAgent(llmCall;
|
||||
systemPrompt::String = "You are a helpful assistant.",
|
||||
model = nothing,
|
||||
messages::Vector{agentMessage} = agentMessage[],
|
||||
prepareContext::Function = prepareContext,
|
||||
formatMsgForLLM::Function = formatMsgForLLM,
|
||||
beforeToolCall::Function = beforeToolCall,
|
||||
afterToolCall::Function = afterToolCall,
|
||||
sessionId::Union{String, Nothing} = nothing,
|
||||
maxRetryDelayMs::Union{Int64, Nothing} = nothing,
|
||||
parallelToolExecute::Bool = false,
|
||||
eventSink::Function = eventSink,
|
||||
mcpServer = nothing
|
||||
)
|
||||
```
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `llmCall` | **(required)** Function that receives formatted messages and returns an LLM response |
|
||||
| `systemPrompt` | System prompt for the agent |
|
||||
| `model` | LLM model configuration (`llmModel` struct) |
|
||||
| `messages` | Initial conversation messages |
|
||||
| `prepareContext` | Hook to transform messages/context before each LLM call |
|
||||
| `formatMsgForLLM` | Hook to convert agent context to LLM API format |
|
||||
| `beforeToolCall` | Hook to block/allow tool execution |
|
||||
| `afterToolCall` | Hook to post-process tool results |
|
||||
| `sessionId` | Optional session identifier for MCP server |
|
||||
| `maxRetryDelayMs` | Maximum retry delay in milliseconds |
|
||||
| `parallelToolExecute` | Run multiple tool calls in parallel |
|
||||
| `eventSink` | Callback for agent events/debug messages |
|
||||
| `mcpServer` | Callable struct for MCP server communication |
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Text Messages
|
||||
|
||||
```julia
|
||||
# Send plain text
|
||||
promptAgent(agent, "What tools do you have?")
|
||||
response = takeResponse(agent)
|
||||
|
||||
# Follow-up while agent is processing
|
||||
promptAgent(agent, "Tell me about wine")
|
||||
followUp(agent, "Also include prices")
|
||||
response = takeResponse(agent)
|
||||
```
|
||||
|
||||
### Structured Messages (OpenAI Format)
|
||||
|
||||
```julia
|
||||
promptAgent(agent, Dict("role" => "user", "content" => "Hello"))
|
||||
response = takeResponse(agent)
|
||||
```
|
||||
|
||||
### Output Format
|
||||
|
||||
`takeResponse()` returns a `Dict{String, Any}` in OpenAI message format:
|
||||
|
||||
```julia
|
||||
Dict(
|
||||
"role" => "assistant",
|
||||
"content" => [
|
||||
Dict("type" => "text", "text" => "The weather in Tokyo is Sunny, 22°C."),
|
||||
# ... more content blocks
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
Content block types:
|
||||
|
||||
| Block Type | Fields | Description |
|
||||
|------------|--------|-------------|
|
||||
| `text` | `"type" => "text"`, `"text" => "..."` | Plain text response from the LLM |
|
||||
| `image_url` | `"type" => "image_url"`, `"image_url" => Dict("url" => "...")` | Image content (rare, used by multimodal models) |
|
||||
|
||||
Example — extracting the text response:
|
||||
|
||||
```julia
|
||||
response = takeResponse(agent)
|
||||
text_response = first(c["text"] for c in response["content"] if c["type"] == "text")
|
||||
```
|
||||
|
||||
### Multimodal Messages (Text + Image)
|
||||
|
||||
```julia
|
||||
# Encode images to data URIs
|
||||
image_path = "test/image.png"
|
||||
image_bytes = read(image_path)
|
||||
base64_string = base64encode(image_bytes)
|
||||
data_uri = "data:image/png;base64,$(base64_string)"
|
||||
|
||||
# Build message with text and image content blocks
|
||||
message = Dict(
|
||||
"role" => "user",
|
||||
"content" => [
|
||||
Dict("type" => "text", "text" => "Do you have Brunello di Montalcino?"),
|
||||
Dict("type" => "image_url", "image_url" => Dict("url" => data_uri))
|
||||
]
|
||||
)
|
||||
promptAgent(agent, message)
|
||||
response = takeResponse(agent)
|
||||
```
|
||||
|
||||
### Custom Hooks
|
||||
|
||||
```julia
|
||||
# beforeToolCall — request user approval for destructive tools
|
||||
function my_before_tool_call(context::beforeToolCallContext, signal::abortSignal)::beforeToolCallResult
|
||||
if context.toolCall.name == "deleteFile"
|
||||
return beforeToolCallResult(true, "User must approve file deletion")
|
||||
end
|
||||
return beforeToolCallResult(false, "N/A")
|
||||
end
|
||||
|
||||
# afterToolCall — mask sensitive data from results
|
||||
function my_after_tool_call(context::afterToolCallContext, signal::abortSignal)::Union{agentToolResult, Nothing}
|
||||
if context.isError
|
||||
return agentToolResult(
|
||||
[textContent("The tool encountered an error. Please try again.")],
|
||||
context.result.details, context.result.usage, context.result.terminate
|
||||
)
|
||||
end
|
||||
return nothing
|
||||
end
|
||||
|
||||
agent = yiemAgent(llmCall;
|
||||
mcpServer=mcpServer,
|
||||
beforeToolCall=my_before_tool_call,
|
||||
afterToolCall=my_after_tool_call,
|
||||
eventSink=println
|
||||
)
|
||||
```
|
||||
|
||||
### Custom LLM Callable
|
||||
|
||||
```julia
|
||||
function my_llm_call(messages_dict::Dict{String, Any})
|
||||
# messages_dict contains "messages" key with OpenAI-format message array,
|
||||
# plus optional "tools", "temperature", etc.
|
||||
|
||||
# Call your LLM provider (OpenAI, Anthropic, local model, etc.)
|
||||
raw_response = call_my_llm_provider(messages_dict)
|
||||
|
||||
# Return a dict with these fields:
|
||||
return Dict(
|
||||
"message" => Dict("role" => "assistant", "content" => raw_response["content"]),
|
||||
"finish_reason" => raw_response["finish_reason"],
|
||||
"api" => "my_provider",
|
||||
"provider" => "my_provider",
|
||||
"model" => "my-model-name",
|
||||
"usage" => llmUsage(100, 50)
|
||||
)
|
||||
end
|
||||
```
|
||||
|
||||
### Custom Context Preparation
|
||||
|
||||
```julia
|
||||
function my_prepare_context(state::agentState, eventSink)::agentContext
|
||||
sysPrompt = state.systemPrompt * "\nCurrent time: $(now())"
|
||||
msgs = deepcopy(state.messages)
|
||||
|
||||
# Prune old messages to fit context window
|
||||
max_messages = 20
|
||||
if length(msgs) > max_messages
|
||||
msgs = msgs[end-max_messages+1:end]
|
||||
end
|
||||
|
||||
return agentContext(sysPrompt, msgs, state.tools)
|
||||
end
|
||||
|
||||
agent = yiemAgent(llmCall; prepareContext=my_prepare_context, ...)
|
||||
```
|
||||
|
||||
## MCP Server Integration
|
||||
|
||||
YiemAgent uses JSON-RPC 2.0 for MCP communication. The `mcpServer` callable struct must implement `tools/list` and `tools/call` methods.
|
||||
|
||||
### Protocol
|
||||
|
||||
```julia
|
||||
# tools/list — returns tool definitions
|
||||
mcpServer("tools/list")
|
||||
# → Dict("jsonrpc"=>"2.0", "id"=>1, "result"=>Dict("tools"=>[...], "nextCursor"=>...))
|
||||
|
||||
# tools/call — executes a tool
|
||||
mcpServer("tools/call", toolName, arguments)
|
||||
# → Dict("jsonrpc"=>"2.0", "id"=>2, "result"=>Dict("content"=>[...], "isError"=>...))
|
||||
|
||||
# Protocol error responses include "error" instead of "result":
|
||||
Dict("jsonrpc"=>"2.0", "id"=>2, "error"=>Dict("code"=>-32602, "message"=>"..."))
|
||||
```
|
||||
|
||||
### Example: NATS-based MCP Server Client
|
||||
|
||||
```julia
|
||||
struct mcpServer
|
||||
natsConn::NATS.Connection
|
||||
topic::String
|
||||
senderID::String
|
||||
fileserver_url::String
|
||||
end
|
||||
|
||||
# tools/list implementation
|
||||
function (c::mcpServer)(method::String)
|
||||
payload = Dict("jsonrpc" => "2.0", "id" => 1, "method" => method, "params" => Dict{String, Any}())
|
||||
payloads = [("payload", payload, "dictionary")]
|
||||
_, msg_envelope = msghandler.smartpack(c.topic, payloads;
|
||||
sender_id=c.senderID, msg_purpose="mcp_tools_list", fileserver_url=c.fileserver_url)
|
||||
reply = NATS.request(c.natsConn, c.topic, msg_envelope, timeout=180)
|
||||
incoming = msghandler.smartunpack(String(reply.payload))
|
||||
return incoming["payloads"][1][2]
|
||||
end
|
||||
|
||||
# tools/call implementation
|
||||
function (c::mcpServer)(method::String, toolName::String, arguments::Dict{String, Any})
|
||||
payload = Dict("jsonrpc" => "2.0", "id" => 2, "method" => method,
|
||||
"params" => Dict("name" => toolName, "arguments" => arguments))
|
||||
payloads = [("payload", payload, "dictionary")]
|
||||
_, msg_envelope = msghandler.smartpack(c.topic, payloads;
|
||||
sender_id=c.senderID, msg_purpose="mcp_tool_call", fileserver_url=c.fileserver_url)
|
||||
reply = NATS.request(c.natsConn, c.topic, msg_envelope, timeout=180)
|
||||
incoming = msghandler.smartunpack(String(reply.payload))
|
||||
return incoming["payloads"][1][2]
|
||||
end
|
||||
```
|
||||
|
||||
## Tool Discovery
|
||||
|
||||
Tools are discovered dynamically via the MCP server:
|
||||
|
||||
1. `listTools` is the only pre-registered tool at agent creation
|
||||
2. When the LLM calls `listTools()`, tools are discovered from the MCP server and registered at runtime
|
||||
3. Supports pagination via `nextCursor` for large tool sets
|
||||
4. New tools become immediately available without restarting the agent
|
||||
|
||||
## Hooks
|
||||
|
||||
Hooks allow customization of the agent's behavior at key points in the execution pipeline.
|
||||
|
||||
| Hook | Signature | Purpose |
|
||||
|------|-----------|---------|
|
||||
| `prepareContext` | `(state::agentState, eventSink) -> agentContext` | Transform messages/context before LLM call (filter tools, inject context, prune messages) |
|
||||
| `formatMsgForLLM` | `(ctx::agentContext, eventSink) -> Dict` | Convert agent context to LLM API message format |
|
||||
| `beforeToolCall` | `(context::beforeToolCallContext, signal::abortSignal) -> beforeToolCallResult` | Block/allow tool execution; request user approval |
|
||||
| `afterToolCall` | `(context::afterToolCallContext, signal::abortSignal) -> Union{agentToolResult, Nothing}` | Post-process tool results; mask sensitive data; set `terminate` flag |
|
||||
| `eventSink` | `(msg) -> nothing` | Callback for agent events/debug messages throughout the pipeline |
|
||||
|
||||
## Agent Lifecycle
|
||||
|
||||
1. **Creation** — `yiemAgent()` spawns a background task (`_agentLoop`) listening on `inputChannel` and `followUpChannel`
|
||||
2. **Input** — User messages enter via `promptAgent()` (immediate) or `followUp()` (queued while agent is busy)
|
||||
3. **Processing** — `_processMessage()` handles LLM calls, tool execution, and conversation history in a loop
|
||||
4. **Tool Execution Pipeline** — each tool call follows three phases:
|
||||
- `prepareToolCall` — resolve tool, validate arguments, run `beforeToolCall` hook
|
||||
- `executePreparedToolCall` — invoke `tool.execute()`
|
||||
- `finalizeExecutedToolCall` — run `afterToolCall` hook, construct `toolResultMessage`
|
||||
5. **Termination** — tool `execute` functions can set `terminate=true` to stop the agent loop
|
||||
6. **Shutdown** — `stopAgent()` sends a `:shutdown` signal, drains channels, and closes the agent
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
src/
|
||||
├── YiemAgent.jl # Module entry point
|
||||
├── type.jl # Core types (messages, tools, agent state)
|
||||
├── utils.jl # Message formatting, validation
|
||||
├── agentCore.jl # Agent loop, tool execution pipeline
|
||||
├── api.jl # Public API (runAgent, takeResponse, etc.)
|
||||
└── tools/
|
||||
├── registry.jl # Tool registry (loadTools, registerTool, listTools)
|
||||
├── getWeather.jl # Weather lookup tool
|
||||
├── getTime.jl # Time lookup tool
|
||||
├── writeTool.jl # Create new tool files (self-modifying)
|
||||
└── README.md # Tool development guide
|
||||
├── type.jl # Core types (messages, tools, agent state, events)
|
||||
├── utils.jl # Message formatting, context preparation, validation
|
||||
├── toolRegistry.jl # Tool store, MCP discovery, listTools registration
|
||||
├── agentCore.jl # Agent loop, tool execution pipeline, yiemAgent struct
|
||||
└── api.jl # Public API (promptAgent, takeResponse, followUp, stopAgent)
|
||||
```
|
||||
|
||||
## Tool Development
|
||||
|
||||
See `src/tools/README.md` for:
|
||||
- Tool anatomy (schema, execute, getTool)
|
||||
- Validation hooks
|
||||
- Agent loop lifecycle
|
||||
- Self-modifying tools (`writeTool`)
|
||||
|
||||
-1599
File diff suppressed because it is too large
Load Diff
@@ -1,54 +0,0 @@
|
||||
{
|
||||
"nats_server_info": {
|
||||
"description": "nats server",
|
||||
"url": "nats.yiem.cc"
|
||||
},
|
||||
"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"
|
||||
],
|
||||
"nats": [
|
||||
"sommpanion.backend.agentbackend.v1.inbox"
|
||||
]
|
||||
},
|
||||
"agentRole": "sommelier",
|
||||
"organization": "yiem_hq",
|
||||
"externalservice": {
|
||||
"servicesloadbalancer": {
|
||||
"nats": "sommpanion.backend.servicesloadbalancer.v1.inbox"
|
||||
},
|
||||
"textembedding": {
|
||||
"url": "textembedding.api.v1"
|
||||
},
|
||||
"textimage_to_text_llm": {
|
||||
"url": "https://llmcoder.yiem.cc/v1/chat/completions",
|
||||
"modelname": "Qwen3.6-35B-A3B-UD-Q4_K_M"
|
||||
},
|
||||
"virtualWineCustomer_1": {
|
||||
"serviceSubject": "",
|
||||
"modelName": "qwen3:8b"
|
||||
},
|
||||
"sommpanion_db" : {
|
||||
"description": "A database connection info for LibPQ client",
|
||||
"url": "192.168.88.106:5432",
|
||||
"dbname": "winedb",
|
||||
"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": "admin",
|
||||
"password": "admin@Sommpanion_0.0"
|
||||
},
|
||||
"fileserver": {
|
||||
"description": "temporary file server",
|
||||
"url": "https://fileserver.yiem.cc"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
check my understand:
|
||||
1) if LLM didn't use tool calls, assistantMessage get pushed into agent._state.messages and
|
||||
it will be the latest message in agent._state.messages. then _agentLoop() can pick it as
|
||||
the output to outputChannel
|
||||
2) if LLM use tool calls but toolResultBatch.terminate is false, assistantMessageToolCall
|
||||
@@ -6,3 +6,6 @@ check my understanding
|
||||
Is my understanding correct?
|
||||
|
||||
|
||||
the user can provide NATS connection to MCP server by adding agent.mcpserver (a callable struct) for communication with MCP server just like agent.llmCall (also a callable struct). I think communicating with MCP server is just send/receive JSON text right?
|
||||
Moreover, for simplicity I want to all tools into an MCP server so an agent can be instantiated with only listTools() in tool store then populate tools from MCP server later.
|
||||
what do you think?
|
||||
@@ -0,0 +1,94 @@
|
||||
can you make sure yiemAgent use correct format when contacting MCP server. you can check MCP server doc at /home/ton/docker-apps/sommpanion/mcp/docs/specification.md?
|
||||
|
||||
smartpack() and smartunpack() doc is at /home/ton/docker-apps/sommpanion/msghandler/README.md
|
||||
|
||||
user code that use yiemAgent is here /home/ton/docker-apps/sommpanion/agent-backend/test/runtest.jl
|
||||
|
||||
this is log folder that logs when I ran yiemAgent. you can check /home/ton/docker-apps/sommpanion/agent-backend/log/
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+30
-66
@@ -1,66 +1,30 @@
|
||||
module YiemAgent
|
||||
|
||||
export register_all_tools
|
||||
|
||||
""" Order by dependencies of each file. The 1st included file must not depend on any other
|
||||
files and each file can only depend on the file included before it.
|
||||
"""
|
||||
|
||||
include("type.jl")
|
||||
using .type
|
||||
|
||||
include("utils.jl")
|
||||
using .utils
|
||||
|
||||
include("tools/getWeather.jl")
|
||||
include("tools/getTime.jl")
|
||||
include("tools/searchWine.jl")
|
||||
include("tools/writeTool.jl")
|
||||
|
||||
include("toolRegistry.jl")
|
||||
using .toolRegistry
|
||||
|
||||
function register_all_tools(store::toolRegistry.toolStore)
|
||||
registerTool(store, getWeatherTool())
|
||||
registerTool(store, getTimeTool())
|
||||
registerTool(store, searchWineTool())
|
||||
registerTool(store, writeToolTool())
|
||||
registerTool(store, listTool(store))
|
||||
return store.tools
|
||||
end
|
||||
|
||||
# include("llmfunction.jl")
|
||||
# using .llmfunction
|
||||
|
||||
include("agentCore.jl")
|
||||
using .agentCore
|
||||
|
||||
include("api.jl")
|
||||
using .api
|
||||
|
||||
|
||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
end # module YiemAgent_v1
|
||||
module YiemAgent
|
||||
|
||||
"""Order by dependencies of each file. The 1st included file must not depend on any other
|
||||
files and each file can only depend on the file included before it."""
|
||||
|
||||
include("type.jl")
|
||||
using .type
|
||||
|
||||
include("utils.jl")
|
||||
using .utils
|
||||
|
||||
include("toolRegistry.jl")
|
||||
using .toolRegistry
|
||||
|
||||
include("agentCore.jl")
|
||||
using .agentCore
|
||||
|
||||
include("api.jl")
|
||||
using .api
|
||||
|
||||
export promptAgent, takeResponse, followUp, stopAgent
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
||||
|
||||
|
||||
|
||||
|
||||
end # end module
|
||||
|
||||
+275
-204
@@ -9,11 +9,6 @@ using JSON, DataStructures, Dates, UUIDs, HTTP, Random, PrettyPrinting, Serializ
|
||||
using GeneralUtils
|
||||
using ..type, ..utils, ..toolRegistry
|
||||
|
||||
function register_all_tools(store::toolRegistry.toolStore)
|
||||
# Call parent module's version which has access to tool functions
|
||||
parentmodule(@__MODULE__).register_all_tools(store)
|
||||
end
|
||||
|
||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
||||
|
||||
"""
|
||||
@@ -24,14 +19,46 @@ mutable struct yiemAgent <: agent # High-level agent wrapper
|
||||
|
||||
# user sends prompt message to agent. if agent is idle, it process user message right away.
|
||||
# if agent is running, it process user message after the current tool call finished.
|
||||
# Expect each message in OpenAI chat format:
|
||||
# image1_path = "test/large_image.png"
|
||||
# image1_bytes = read(image1_path)
|
||||
# image1_base64_string = base64encode(image1_bytes)
|
||||
# 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
|
||||
# message = Dict(
|
||||
# "role" => "user",
|
||||
# "content" => [
|
||||
# Dict("type" => "text", "text" =>
|
||||
# "
|
||||
# Do you have Brunello di Montalcino from Tenuta CastelGiocon?
|
||||
# "),
|
||||
# Dict(
|
||||
# "type" => "image_url",
|
||||
# "image_url" => Dict("url" => data1_uri)
|
||||
# )
|
||||
# ]
|
||||
# )
|
||||
inputChannel::Channel
|
||||
|
||||
# Buffers messages the user sends while the agent is busy. Processed after all inputChannel
|
||||
# messages are handled and the agent is idle (not using a tool call).
|
||||
# Buffers follow-up messages the user sends while the agent is busy. Uses the same
|
||||
# OpenAI chat format as inputChannel. Processed after all inputChannel messages are
|
||||
# handled and the agent is idle (not in the middle of a tool call).
|
||||
followUpChannel::Channel
|
||||
|
||||
# agent sends response message to user after processing all user messages in inputChannel
|
||||
# and all followUp messages.
|
||||
# agent sends response message to user after processing all user messages in inputChannel
|
||||
# and all followUp messages. Response is in OpenAI message format:
|
||||
# Dict("role" => "assistant", "content" => [
|
||||
# Dict("type" => "text", "text" => "Response text here")
|
||||
# ])
|
||||
outputChannel::Channel
|
||||
|
||||
_agentLoop::Union{Task, Nothing} # agent loop running in the background
|
||||
@@ -49,7 +76,10 @@ mutable struct yiemAgent <: agent # High-level agent wrapper
|
||||
# Each block has a type — "text", "thinking", or "toolCall".
|
||||
# The code filters for type === "toolCall" blocks, then passes them to executeToolCalls().
|
||||
llmCall
|
||||
|
||||
|
||||
# check input and output format at MCP server doc
|
||||
mcpServer
|
||||
|
||||
# Callback invoked before executing a tool call (ask for user permission/confirmation/abort, etc..)
|
||||
beforeToolCall::Union{Function, Nothing}
|
||||
|
||||
@@ -61,7 +91,7 @@ mutable struct yiemAgent <: agent # High-level agent wrapper
|
||||
sessionId::Union{String, Nothing} # Optional session identifier
|
||||
maxRetryDelayMs::Union{Int64, Nothing} # Maximum delay between retries (ms)
|
||||
parallelToolExecute::Bool # Default: false
|
||||
agentEventSink # agent emits its status via this function
|
||||
eventSink # agent emits its status via this function
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -85,7 +115,10 @@ on `inputChannel` and `followUpChannel` channels concurrently.
|
||||
- `sessionId::Union{String, Nothing}`: Optional session identifier (default: `nothing`)
|
||||
- `maxRetryDelayMs::Union{Int64, Nothing}`: Maximum delay between retries in milliseconds (default: `nothing`)
|
||||
- `parallelToolExecute::Bool`: Run tool calls in parallel (default: `false`)
|
||||
- `agentEventSink::Function`: Callback to receive agent events
|
||||
- `eventSink::Function`: Callback to receive agent events
|
||||
- `mcpServer`: Callable struct for MCP server communication. Called as
|
||||
`mcpServer("tools/list")` to discover tools, or `mcpServer("tools/call", args)`
|
||||
to execute a tool. Returns parsed JSON dicts. (default: `nothing`)
|
||||
|
||||
# Returns
|
||||
- A new `yiemAgent` instance with an active background task
|
||||
@@ -102,23 +135,45 @@ function yiemAgent(
|
||||
afterToolCall::Function=afterToolCall,
|
||||
# prepareNextTurn::Union{Function, Nothing}=nothing,
|
||||
# prepareNextTurnWithContext::Union{Function, Nothing}=nothing,
|
||||
sessionId::Union{String, Nothing}=nothing,
|
||||
sessionId::Union{String, Nothing}="",
|
||||
maxRetryDelayMs::Union{Int64, Nothing}=nothing,
|
||||
parallelToolExecute::Bool=false,
|
||||
agentEventSink=agentEventSink,
|
||||
eventSink=eventSink,
|
||||
mcpServer=nothing,
|
||||
)
|
||||
# Create channels: input (user -> agent), followUp (async queue), output (agent -> user)
|
||||
inputChannel = Channel(16)
|
||||
followUp = Channel(32)
|
||||
outputChannel = Channel(16)
|
||||
|
||||
# load tools (statically registered at module init)
|
||||
toolStore1 = toolStore(name="myagent")
|
||||
register_all_tools(toolStore1)
|
||||
if mcpServer === nothing
|
||||
error(""" please implement the following MCP server interface
|
||||
struct mcpServer
|
||||
natsConn::NATS.Connection
|
||||
topic::String
|
||||
senderID::String
|
||||
end
|
||||
|
||||
# MCP protocol: tools/list — returns tool definitions (JSON-RPC 2.0)
|
||||
# check input and output format from MCP server doc
|
||||
function (mcp::mcpServer)(method::String, sessionId::String; eventSink=nothing)::AbstractDict{String, <:Any}
|
||||
error("please implement MCP server tools/list interface")
|
||||
end
|
||||
|
||||
# MCP protocol: tools/call — executes a tool (JSON-RPC 2.0)
|
||||
function (mcp::mcpServer)(method::String, toolName::String, arguments::Dict{String, Any},
|
||||
sessionId::String; eventSink=nothing)::AbstractDict{String, <:Any}
|
||||
error("please implement MCP server interface")
|
||||
end
|
||||
""")
|
||||
end
|
||||
|
||||
tools = OrderedDict{String, agentTool}()
|
||||
registerAllTools(tools, mcpServer; eventSink=eventSink, sessionId=sessionId)
|
||||
|
||||
# Create struct with a placeholder task, then spawn and replace it
|
||||
agent = yiemAgent(
|
||||
agentState(systemPrompt, model, getTools(toolStore1), messages),
|
||||
agentState(systemPrompt, model, tools, messages),
|
||||
inputChannel,
|
||||
followUp,
|
||||
outputChannel,
|
||||
@@ -126,6 +181,7 @@ function yiemAgent(
|
||||
prepareContext,
|
||||
formatMsgForLLM,
|
||||
llmCall,
|
||||
mcpServer,
|
||||
beforeToolCall,
|
||||
afterToolCall,
|
||||
# prepareNextTurn,
|
||||
@@ -133,7 +189,7 @@ function yiemAgent(
|
||||
sessionId,
|
||||
maxRetryDelayMs,
|
||||
parallelToolExecute,
|
||||
agentEventSink,
|
||||
eventSink,
|
||||
)
|
||||
|
||||
# Spawn the background loop and attach it
|
||||
@@ -208,18 +264,18 @@ function _agentLoop(agent::yiemAgent)
|
||||
while true
|
||||
while newUserMsg === nothing
|
||||
if isready(agent.inputChannel)
|
||||
agent.agentEventSink("_agentLoop 1 agent._state.messages length $(length(agent._state.messages))")
|
||||
agent.eventSink("_agentLoop 1 agent._state.messages length $(length(agent._state.messages))"; publish=false, log=true)
|
||||
# agent process new user msg immediately after the current tool call finished.
|
||||
newUserMsg = take!(agent.inputChannel)
|
||||
agent.agentEventSink("new user msg")
|
||||
# agent.eventSink("new user msg\n$newUserMsg"; publish=false, log=true)
|
||||
else
|
||||
# check followUp message after _processMessage() is done
|
||||
if typeof(processingTask) == Task && istaskdone(processingTask) == true
|
||||
agent.agentEventSink("_agentLoop 2 agent._state.messages length $(length(agent._state.messages))")
|
||||
agent.eventSink("_agentLoop 2 agent._state.messages length $(length(agent._state.messages))"; publish=false, log=true)
|
||||
# if agent runs is done but followUpChannel has messages,
|
||||
# put new message in inputChannel instead
|
||||
if isready(agent.followUpChannel)
|
||||
agent.agentEventSink("_agentLoop 3 agent._state.messages length $(length(agent._state.messages))")
|
||||
agent.eventSink("_agentLoop 3 agent._state.messages length $(length(agent._state.messages))"; publish=false, log=true)
|
||||
while isready(agent.followUpChannel)
|
||||
followUpMsg = take!(agent.followUpChannel)
|
||||
put!(agent.inputChannel, followUpMsg)
|
||||
@@ -227,24 +283,24 @@ function _agentLoop(agent::yiemAgent)
|
||||
processingTask = nothing # reset
|
||||
result = nothing # reset
|
||||
else # _processMessage() done and no followUp message.
|
||||
agent.agentEventSink("_agentLoop 4 agent._state.messages length $(length(agent._state.messages))")
|
||||
agent.eventSink("_agentLoop 4 agent._state.messages length $(length(agent._state.messages))"; publish=false, log=true)
|
||||
result = deepcopy(agent._state.messages[end])
|
||||
|
||||
agent.eventSink("_agentLoop 4-1 "; publish=false, log=true)
|
||||
# filter out reasoningContent in-place
|
||||
filter!(c -> !(c isa reasoningContent), result.content)
|
||||
|
||||
agent.eventSink("_agentLoop 5 "; publish=false, log=true)
|
||||
# format output
|
||||
respondToUI = _assistantMessageToOpenAI(result)
|
||||
|
||||
agent.eventSink("_agentLoop 6 "; publish=false, log=true)
|
||||
put!(agent.outputChannel, respondToUI)
|
||||
if !isempty(result.content) && result.content[1] isa textContent
|
||||
agent.agentEventSink(result.content[1].text)
|
||||
agent.eventSink(result.content[1].text; publish=false, log=true)
|
||||
end
|
||||
processingTask = nothing # reset
|
||||
result = nothing # reset
|
||||
end
|
||||
end
|
||||
yield()
|
||||
sleep(0.1)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -269,7 +325,7 @@ function _agentLoop(agent::yiemAgent)
|
||||
else
|
||||
# spawn new _processMessage() if it is not already running.
|
||||
if processingTask === nothing
|
||||
agent.agentEventSink("_agentLoop 5 agent._state.messages length $(length(agent._state.messages))")
|
||||
agent.eventSink("_agentLoop 5 agent._state.messages length $(length(agent._state.messages))"; publish=false, log=true)
|
||||
# discard all messages in followUpChannel
|
||||
while isready(agent.followUpChannel)
|
||||
_ = take!(agent.followUpChannel)
|
||||
@@ -278,7 +334,7 @@ function _agentLoop(agent::yiemAgent)
|
||||
# Dispatch message through the processing pipeline
|
||||
processingTask = @spawn _processMessage(
|
||||
processMessageInputCh,
|
||||
agent.agentEventSink,
|
||||
agent.eventSink,
|
||||
agent._state.messages,
|
||||
agent._state.systemPrompt,
|
||||
agent._state.tools,
|
||||
@@ -295,6 +351,13 @@ function _agentLoop(agent::yiemAgent)
|
||||
end
|
||||
end
|
||||
catch e
|
||||
bt = catch_backtrace()
|
||||
errMsg = sprint() do io
|
||||
showerror(io, e, bt)
|
||||
println(io)
|
||||
end
|
||||
eventSink(errMsg; publish=false, log=true)
|
||||
|
||||
# On any error, send error response and exit the loop
|
||||
@error "Agent loop failed" error=e
|
||||
end
|
||||
@@ -330,7 +393,7 @@ julia> # Currently returns a placeholder echo response
|
||||
"""
|
||||
function _processMessage(
|
||||
inputChannel::Channel,
|
||||
agentEventSink,
|
||||
eventSink,
|
||||
agentMsgHistory::Vector{agentMessage},
|
||||
systemPrompt::String,
|
||||
tools::OrderedDict{String, agentTool},
|
||||
@@ -341,7 +404,7 @@ function _processMessage(
|
||||
afterToolCall::Union{Function, Nothing},
|
||||
parallelToolExecute::Bool,
|
||||
)::Nothing
|
||||
agentEventSink("_processMessage 1 _state.messages length $(length(agentMsgHistory))")
|
||||
eventSink("_processMessage 1 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
# loop until llmCall() response didn't use tool calls
|
||||
final_response = nothing
|
||||
|
||||
@@ -359,113 +422,124 @@ function _processMessage(
|
||||
"""
|
||||
|
||||
while true
|
||||
# Drain inputChannel and convert OpenAI-format messages to userMessage type
|
||||
while isready(inputChannel)
|
||||
agentEventSink("_processMessage 2 _state.messages length $(length(agentMsgHistory))")
|
||||
newUserMsg_openai = take!(inputChannel)
|
||||
agentEventSink("_processMessage 3 _state.messages length $(length(agentMsgHistory))")
|
||||
if newUserMsg_openai === :shutdown
|
||||
agentEventSink("_processMessage 4 _state.messages length $(length(agentMsgHistory))")
|
||||
# Re-emit shutdown signal for the loop to handle
|
||||
put!(inputChannel, :shutdown)
|
||||
break
|
||||
try
|
||||
# Drain inputChannel and convert OpenAI-format messages to userMessage type
|
||||
while isready(inputChannel)
|
||||
eventSink("_processMessage 2 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
newUserMsg_openai = take!(inputChannel)
|
||||
eventSink("_processMessage 3 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
if newUserMsg_openai === :shutdown
|
||||
eventSink("_processMessage 4 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
# Re-emit shutdown signal for the loop to handle
|
||||
put!(inputChannel, :shutdown)
|
||||
break
|
||||
end
|
||||
eventSink("_processMessage 5 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
newUserMsg = OpenAiToUserMessage(newUserMsg_openai)
|
||||
push!(agentMsgHistory, newUserMsg)
|
||||
eventSink("_processMessage 6 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
end
|
||||
agentEventSink("_processMessage 5 _state.messages length $(length(agentMsgHistory))")
|
||||
newUserMsg = OpenAiToUserMessage(newUserMsg_openai)
|
||||
push!(agentMsgHistory, newUserMsg)
|
||||
agentEventSink("_processMessage 6 _state.messages length $(length(agentMsgHistory))")
|
||||
end
|
||||
agentEventSink("_processMessage 7 _state.messages length $(length(agentMsgHistory))")
|
||||
# call prepareContext()
|
||||
state = agentState(systemPrompt, nothing, tools, agentMsgHistory)
|
||||
agentEventSink("_processMessage 8 _state.messages length $(length(agentMsgHistory))")
|
||||
preparedContext = prepareContext(state, agentEventSink, llmCall)
|
||||
agentEventSink("_processMessage 9 _state.messages length $(length(agentMsgHistory))")
|
||||
# Call formatMessagesForLLM() to format for LLM
|
||||
formattedMessages = formatMessagesForLLM(preparedContext, agentEventSink)
|
||||
|
||||
agentEventSink("_processMessage 10 formattedMessages $formattedMessages")
|
||||
eventSink("_processMessage 7 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
# call prepareContext()
|
||||
state = agentState(systemPrompt, nothing, tools, agentMsgHistory)
|
||||
eventSink("_processMessage 8 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
preparedContext = prepareContext(state, eventSink)
|
||||
eventSink("_processMessage 9 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
# Call formatMessagesForLLM() to format for LLM
|
||||
formattedMessages = formatMessagesForLLM(preparedContext, eventSink)
|
||||
|
||||
# eventSink("_processMessage 10 formattedMessages $formattedMessages"; publish=false, log=true)
|
||||
|
||||
""" response example
|
||||
response = JSON.Object{String, Any}("finish_reason" => "tool_calls", "index" => 0, "message" => JSON.Object{String, Any}("role" => "assistant", "content" => "", "reasoning_content" => "Here's a thinking process:\n\n1. **Identify User Request**: The user is asking for the weather in Bangkok.\n2. **Locate Relevant Tool**: I have a `getWeather` function available.\n3. **Check Function Parameters**:\n - `city` (required): City and country, e.g., 'San Francisco, CA' or 'Tokyo, Japan'\n - `units` (optional, default \"celsius\"): Temperature scale (\"celsius\" or \"fahrenheit\")\n4. **Prepare Parameters**:\n - `city`: \"Bangkok, Thailand\" (adding country for clarity, though just \"Bangkok\" might work, following the example format is safer)\n - `units`: Not specified, so I'll use the default (\"celsius\")\n5. **Execute Tool Call**: Call `getWeather` with `city: \"Bangkok, Thailand\"`\n6. **Anticipate Response**: The function will return current weather and forecast data for Bangkok. I'll then format it nicely for the user.\n - *Self-Correction/Verification during thought*: The prompt says \"city: City and country, e.g., 'San Francisco, CA' or 'Tokyo, Japan'\". I'll use \"Bangkok, Thailand\". The `units` parameter is optional, so I'll omit it to use the default.\n - Proceed with tool call.✅\n", "tool_calls" => Any[JSON.Object{String, Any}("type" => "function", "function" => JSON.Object{String, Any}("name" => "getWeather", "arguments" => "{\"city\":\"Bangkok, Thailand\"}"), "id" => "6fOilR5QPcdppbAAHluhkRyUDu3oWMAL")]))
|
||||
"""
|
||||
response = llmCall(formattedMessages)
|
||||
agentEventSink(" llmCall " * string(response))
|
||||
""" response example
|
||||
response = JSON.Object{String, Any}("finish_reason" => "tool_calls", "index" => 0, "message" => JSON.Object{String, Any}("role" => "assistant", "content" => "", "reasoning_content" => "Here's a thinking process:\n\n1. **Identify User Request**: The user is asking for the weather in Bangkok.\n2. **Locate Relevant Tool**: I have a `getWeather` function available.\n3. **Check Function Parameters**:\n - `city` (required): City and country, e.g., 'San Francisco, CA' or 'Tokyo, Japan'\n - `units` (optional, default \"celsius\"): Temperature scale (\"celsius\" or \"fahrenheit\")\n4. **Prepare Parameters**:\n - `city`: \"Bangkok, Thailand\" (adding country for clarity, though just \"Bangkok\" might work, following the example format is safer)\n - `units`: Not specified, so I'll use the default (\"celsius\")\n5. **Execute Tool Call**: Call `getWeather` with `city: \"Bangkok, Thailand\"`\n6. **Anticipate Response**: The function will return current weather and forecast data for Bangkok. I'll then format it nicely for the user.\n - *Self-Correction/Verification during thought*: The prompt says \"city: City and country, e.g., 'San Francisco, CA' or 'Tokyo, Japan'\". I'll use \"Bangkok, Thailand\". The `units` parameter is optional, so I'll omit it to use the default.\n - Proceed with tool call.✅\n", "tool_calls" => Any[JSON.Object{String, Any}("type" => "function", "function" => JSON.Object{String, Any}("name" => "getWeather", "arguments" => "{\"city\":\"Bangkok, Thailand\"}"), "id" => "6fOilR5QPcdppbAAHluhkRyUDu3oWMAL")]))
|
||||
"""
|
||||
response = llmCall(formattedMessages, eventSink=eventSink)
|
||||
# eventSink("LLM response " * string(response); publish=false, log=true)
|
||||
|
||||
agentEventSink("_processMessage 11 _state.messages length $(length(agentMsgHistory))")
|
||||
# Extract tool calls from LLM response content blocks
|
||||
hasToolCalls, toolCallList, assistant_msg = _extractToolCalls(response)
|
||||
agentEventSink("hasToolCalls: $hasToolCalls\ntoolCallList: $toolCallList _state.messages length $(length(agentMsgHistory))")
|
||||
agentEventSink("assistant_msg " * string(assistant_msg))
|
||||
agentEventSink("_processMessage 11-1")
|
||||
eventSink("_processMessage 11 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
# Extract tool calls from LLM response content blocks
|
||||
hasToolCalls, toolCallList, assistant_msg = _extractToolCalls(response)
|
||||
eventSink("hasToolCalls: $hasToolCalls\ntoolCallList: $toolCallList _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
eventSink("assistant_msg " * string(assistant_msg); publish=false, log=true)
|
||||
eventSink("_processMessage 11-1"; publish=false, log=true)
|
||||
|
||||
# Add assistant message (tool calls or text) to history for next LLM turn
|
||||
push!(agentMsgHistory, assistant_msg)
|
||||
# Add assistant message (tool calls or text) to history for next LLM turn
|
||||
push!(agentMsgHistory, assistant_msg)
|
||||
|
||||
if hasToolCalls && length(toolCallList) > 0
|
||||
# Build context and config for executeToolCalls
|
||||
if hasToolCalls && length(toolCallList) > 0
|
||||
# Build context and config for executeToolCalls
|
||||
|
||||
config = agentLoopConfig(
|
||||
beforeToolCall,
|
||||
afterToolCall,
|
||||
parallelToolExecute ? "parallel" : "sequential",
|
||||
llmCall,
|
||||
)
|
||||
config = agentLoopConfig(
|
||||
beforeToolCall,
|
||||
afterToolCall,
|
||||
parallelToolExecute ? "parallel" : "sequential",
|
||||
)
|
||||
|
||||
signal = abortSignal(false)
|
||||
agentEventSink("_processMessage 12 _state.messages length $(length(agentMsgHistory))")
|
||||
signal = abortSignal(false)
|
||||
eventSink("_processMessage 12 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
|
||||
# call executeToolCalls()
|
||||
toolResultBatch = executeToolCalls(preparedContext, assistant_msg, toolCallList, config,
|
||||
signal, agentEventSink)
|
||||
agentEventSink("_processMessage 13 _state.messages length $(length(agentMsgHistory))")
|
||||
# call executeToolCalls()
|
||||
toolResultBatch = executeToolCalls(preparedContext, assistant_msg, toolCallList, config,
|
||||
signal, eventSink)
|
||||
eventSink("_processMessage 13 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
|
||||
# save toolResults to messages
|
||||
for toolResult in toolResultBatch.messages
|
||||
agentEventSink("toolResult " * string(toolResult))
|
||||
push!(agentMsgHistory, toolResult)
|
||||
end
|
||||
agentEventSink("_processMessage 14 _state.messages length $(length(agentMsgHistory))")
|
||||
if toolResultBatch.terminate
|
||||
agentEventSink("_processMessage 15 _state.messages length $(length(agentMsgHistory))")
|
||||
# If toolResultBatch requested termination, build a final response
|
||||
final_content = [textContent("Tool execution completed.")]
|
||||
# save toolResults to messages
|
||||
for toolResult in toolResultBatch.messages
|
||||
for content_block in toolResult.content
|
||||
if content_block isa textContent
|
||||
append!(final_content, [content_block])
|
||||
elseif content_block isa Dict
|
||||
if haskey(content_block, :text)
|
||||
push!(final_content, textContent(content_block[:text]))
|
||||
# eventSink("toolResult " * string(toolResult); publish=false, log=true)
|
||||
push!(agentMsgHistory, toolResult)
|
||||
end
|
||||
eventSink("_processMessage 14 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
if toolResultBatch.terminate
|
||||
eventSink("_processMessage 15 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
# If toolResultBatch requested termination, build a final response
|
||||
final_content = [textContent("Tool execution completed.")]
|
||||
for toolResult in toolResultBatch.messages
|
||||
for content_block in toolResult.content
|
||||
if content_block isa textContent
|
||||
append!(final_content, [content_block])
|
||||
elseif content_block isa Dict
|
||||
if haskey(content_block, :text)
|
||||
push!(final_content, textContent(content_block[:text]))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
eventSink("_processMessage 16 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
final_response = assistantMessage(
|
||||
role="assistant",
|
||||
content=final_content,
|
||||
api=assistant_msg.api,
|
||||
model=assistant_msg.model,
|
||||
usage=assistant_msg.usage,
|
||||
stopReason="tool_use_terminated",
|
||||
errorMessage=if any(x -> x.isError, toolResultBatch.messages)
|
||||
"One or more tool calls failed"
|
||||
else
|
||||
nothing
|
||||
end,
|
||||
timestamp=now(),
|
||||
)
|
||||
push!(agentMsgHistory, final_response)
|
||||
break
|
||||
end
|
||||
agentEventSink("_processMessage 16 _state.messages length $(length(agentMsgHistory))")
|
||||
final_response = assistantMessage(
|
||||
role="assistant",
|
||||
content=final_content,
|
||||
api=assistant_msg.api,
|
||||
model=assistant_msg.model,
|
||||
usage=assistant_msg.usage,
|
||||
stopReason="tool_use_terminated",
|
||||
errorMessage=if any(x -> x.isError, toolResultBatch.messages)
|
||||
"One or more tool calls failed"
|
||||
else
|
||||
nothing
|
||||
end,
|
||||
timestamp=now(),
|
||||
)
|
||||
push!(agentMsgHistory, final_response)
|
||||
else
|
||||
eventSink("_processMessage 17 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
# LLM did not use tool calls —
|
||||
break
|
||||
end
|
||||
else
|
||||
agentEventSink("_processMessage 17 _state.messages length $(length(agentMsgHistory))")
|
||||
# LLM did not use tool calls —
|
||||
break
|
||||
catch e
|
||||
bt = catch_backtrace()
|
||||
err_msg = sprint() do io
|
||||
showerror(io, e, bt)
|
||||
println(io)
|
||||
end
|
||||
|
||||
eventSink(err_msg; publish=false, log=true)
|
||||
end
|
||||
end
|
||||
agentEventSink("_processMessage 18 _state.messages length $(length(agentMsgHistory))")
|
||||
|
||||
|
||||
eventSink("_processMessage 18 _state.messages length $(length(agentMsgHistory))"; publish=false, log=true)
|
||||
return nothing
|
||||
end
|
||||
|
||||
@@ -496,7 +570,7 @@ agentToolResult([textContent("text", "Tool not found")], Dict{Any,Any}())
|
||||
```
|
||||
"""
|
||||
function createErrorToolResult(msg::String)::agentToolResult
|
||||
return agentToolResult([textContent("text", msg)], dict{any,any}())
|
||||
return agentToolResult([textContent("text", msg)], Dict{Any,Any}())
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -788,10 +862,10 @@ stopping the agent when other tools in the batch did not intend to terminate.
|
||||
julia> shouldTerminate(finalizedOutcome[])
|
||||
false
|
||||
|
||||
julia> shouldTerminate([finalizedOutcome(tc, agentToolResult([], dict{any,any}(), dict{any,any}(), false), false) for _ in 1:2])
|
||||
julia> shouldTerminate([finalizedOutcome(tc, agentToolResult([], Dict{Any,Any}(), Dict{Any,Any}(), false), false) for _ in 1:2])
|
||||
false
|
||||
|
||||
julia> shouldTerminate([finalizedOutcome(tc, agentToolResult([], dict{any,any}(), dict{any,any}(), true), false) for _ in 1:2])
|
||||
julia> shouldTerminate([finalizedOutcome(tc, agentToolResult([], Dict{Any,Any}(), Dict{Any,Any}(), true), false) for _ in 1:2])
|
||||
true
|
||||
```
|
||||
"""
|
||||
@@ -903,45 +977,49 @@ function prepareToolCall(
|
||||
toolCall::agentToolCall,
|
||||
config::agentLoopConfig,
|
||||
signal::abortSignal,
|
||||
agentEventSink
|
||||
eventSink
|
||||
)::Union{preparedToolCall,immediateOutcome}
|
||||
agentEventSink("prepareToolCall 1")
|
||||
tool = get(context.tools, toolCall.name, nothing) # pick a called tool from tool store
|
||||
eventSink("prepareToolCall 1"; publish=false, log=true)
|
||||
|
||||
# pick a called tool from tool store
|
||||
tool = get(context.tools, toolCall.name, nothing)
|
||||
|
||||
if tool === nothing
|
||||
agentEventSink("prepareToolCall 2")
|
||||
eventSink("prepareToolCall 2"; publish=false, log=true)
|
||||
return immediateOutcome(createErrorToolResult("Tool $toolCall.name not found"), true)
|
||||
end
|
||||
|
||||
try
|
||||
agentEventSink("prepareToolCall 3")
|
||||
eventSink("prepareToolCall 3"; publish=false, log=true)
|
||||
# 1. prepare arguments (tool-specific transform)
|
||||
prepared = prepareToolCallArguments(tool, toolCall)
|
||||
agentEventSink("prepared " * string(prepared.arguments))
|
||||
agentEventSink("prepareToolCall 4")
|
||||
eventSink("prepared " * string(prepared.arguments); publish=false, log=true)
|
||||
eventSink("prepareToolCall 4"; publish=false, log=true)
|
||||
validatedArgs = validateToolArguments(tool, prepared)
|
||||
agentEventSink("validatedArgs " * string(validatedArgs))
|
||||
agentEventSink("prepareToolCall 5")
|
||||
eventSink("validatedArgs " * string(validatedArgs); publish=false, log=true)
|
||||
eventSink("prepareToolCall 5"; publish=false, log=true)
|
||||
# 2. beforeToolCall hook — can block
|
||||
if config.beforeToolCall !== nothing
|
||||
agentEventSink("prepareToolCall 6")
|
||||
eventSink("prepareToolCall 6"; publish=false, log=true)
|
||||
|
||||
before = config.beforeToolCall(
|
||||
beforeToolCallContext(assistantMsg, toolCall, validatedArgs, context),
|
||||
signal
|
||||
signal,
|
||||
eventSink
|
||||
)
|
||||
agentEventSink("prepareToolCall 7")
|
||||
eventSink("prepareToolCall 7"; publish=false, log=true)
|
||||
if signal.aborted
|
||||
agentEventSink("prepareToolCall 8")
|
||||
eventSink("prepareToolCall 8"; publish=false, log=true)
|
||||
return immediateOutcome(createErrorToolResult("Operation aborted"), true)
|
||||
end
|
||||
|
||||
if before !== nothing && before.block
|
||||
agentEventSink("prepareToolCall 9")
|
||||
eventSink("prepareToolCall 9"; publish=false, log=true)
|
||||
return immediateOutcome(
|
||||
createErrorToolResult(get(before, :reason, "Tool execution was blocked")), true)
|
||||
end
|
||||
end
|
||||
agentEventSink("prepareToolCall 10")
|
||||
eventSink("prepareToolCall 10"; publish=false, log=true)
|
||||
return preparedToolCall(tool, toolCall, validatedArgs)
|
||||
catch e
|
||||
bt = catch_backtrace()
|
||||
@@ -950,7 +1028,7 @@ function prepareToolCall(
|
||||
println(io)
|
||||
end
|
||||
|
||||
agentEventSink(errMsg)
|
||||
eventSink(errMsg; publish=false, log=true)
|
||||
|
||||
return immediateOutcome(createErrorToolResult(sprint(showerror, e)), true)
|
||||
end
|
||||
@@ -989,7 +1067,7 @@ emitted after the result has already been captured.
|
||||
```julia
|
||||
# Successful execution
|
||||
executePreparedToolCall(prep, nothing, emit)
|
||||
# => executedOutcome(agentToolResult([textContent("text", "Found 3 wines")], dict{any,any}(), dict{any,any}()), false)
|
||||
# => executedOutcome(agentToolResult([textContent("text", "Found 3 wines")], Dict{Any,Any}(), Dict{Any,Any}()), false)
|
||||
|
||||
# Execution error
|
||||
executePreparedToolCall(prep, nothing, emit)
|
||||
@@ -1000,17 +1078,18 @@ executePreparedToolCall(prep, nothing, emit)
|
||||
function executePreparedToolCall(
|
||||
prep::preparedToolCall,
|
||||
signal::Union{Nothing,abortSignal},
|
||||
agentEventSink,
|
||||
llmCall::Union{Any,Nothing}=nothing,
|
||||
eventSink,
|
||||
)::executedOutcome
|
||||
agentEventSink("executePreparedToolCall 1")
|
||||
agentEventSink("executePreparedToolCall 2")
|
||||
agentEventSink("executePreparedToolCall 3")
|
||||
eventSink("executePreparedToolCall 1"; publish=false, log=true)
|
||||
|
||||
try
|
||||
result = prep.tool.execute(prep.toolCall.id, prep.args, signal, agentEventSink, llmCall)
|
||||
agentEventSink(result.content[1].text)
|
||||
agentEventSink("executePreparedToolCall 4")
|
||||
|
||||
result = prep.tool.execute(prep.toolCall.id, prep.args, signal, eventSink)
|
||||
|
||||
|
||||
eventSink("executePreparedToolCall 2"; publish=false, log=true)
|
||||
eventSink("tool execute raw result: " * sprint(show, result); publish=false, log=true)
|
||||
eventSink("executePreparedToolCall 3"; publish=false, log=true)
|
||||
return executedOutcome(result, false)
|
||||
catch e
|
||||
bt = catch_backtrace()
|
||||
@@ -1018,10 +1097,11 @@ function executePreparedToolCall(
|
||||
showerror(io, e, bt)
|
||||
println(io)
|
||||
end
|
||||
agentEventSink(errMsg)
|
||||
eventSink(errMsg; publish=false, log=true)
|
||||
|
||||
return executedOutcome(createErrorToolResult(sprint(showerror, e)), true)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
|
||||
@@ -1088,25 +1168,23 @@ function finalizeExecutedToolCall(
|
||||
executed::executedOutcome,
|
||||
config::agentLoopConfig,
|
||||
signal::Union{Nothing,abortSignal},
|
||||
agentEventSink
|
||||
eventSink
|
||||
)::finalizedOutcome
|
||||
agentEventSink("finalizeExecutedToolCall 1")
|
||||
eventSink("finalizeExecutedToolCall 1"; publish=false, log=true)
|
||||
result = executed.result
|
||||
isError = executed.isError
|
||||
agentEventSink("finalizeExecutedToolCall 2")
|
||||
eventSink("finalizeExecutedToolCall result before afterToolCall\n$result"; publish=false, log=true)
|
||||
if config.afterToolCall !== nothing
|
||||
try
|
||||
after = config.afterToolCall(
|
||||
afterToolCallContext(assistantMsg, prep.toolCall, prep.args, result, isError, context),
|
||||
signal
|
||||
signal,
|
||||
eventSink
|
||||
)
|
||||
agentEventSink("finalizeExecutedToolCall 3")
|
||||
eventSink("finalizeExecutedToolCall 3"; publish=false, log=true)
|
||||
if after !== nothing
|
||||
result = merge(result, dict(:content=>get(after,:content,result.content),
|
||||
:details=>get(after,:details,result.details),
|
||||
:usage=>get(after,:usage,result.usage),
|
||||
:terminate=>get(after,:terminate,result.terminate)))
|
||||
isError = get(after, :isError, isError)
|
||||
result = after
|
||||
isError = false
|
||||
end
|
||||
catch e
|
||||
bt = catch_backtrace()
|
||||
@@ -1114,13 +1192,13 @@ function finalizeExecutedToolCall(
|
||||
showerror(io, e, bt)
|
||||
println(io)
|
||||
end
|
||||
agentEventSink(errMsg)
|
||||
eventSink(errMsg; publish=false, log=true)
|
||||
|
||||
result = createErrorToolResult(sprint(showerror, e))
|
||||
isError = true
|
||||
end
|
||||
end
|
||||
agentEventSink("finalizeExecutedToolCall 4")
|
||||
eventSink("finalizeExecutedToolCall 4"; publish=false, log=true)
|
||||
return finalizedOutcome(prep.toolCall, result, isError)
|
||||
end
|
||||
|
||||
@@ -1184,41 +1262,41 @@ function executeToolCallsSequential(
|
||||
toolCalls::Vector{agentToolCall},
|
||||
config::agentLoopConfig,
|
||||
signal::abortSignal,
|
||||
agentEventSink,
|
||||
eventSink,
|
||||
)::agentToolCallBatch
|
||||
llmCall = config.llmCall
|
||||
agentEventSink("executeToolCallsSequential 1")
|
||||
eventSink("executeToolCallsSequential 1"; publish=false, log=true)
|
||||
finalizedCalls = finalizedOutcome[]
|
||||
messages = toolResultMessage[]
|
||||
|
||||
for tc in toolCalls
|
||||
agentEventSink("start tool execute $(tc.id), $(tc.name), $(tc.arguments)")
|
||||
prep = prepareToolCall(context, assistantMsg, tc, config, signal, agentEventSink)
|
||||
agentEventSink("executeToolCallsSequential " * string(prep.args))
|
||||
eventSink("start tool execute $(tc.id), $(tc.name), $(tc.arguments)"; publish=false, log=true)
|
||||
prep = prepareToolCall(context, assistantMsg, tc, config, signal, eventSink)
|
||||
eventSink("executeToolCallsSequential " * string(prep.args); publish=false, log=true)
|
||||
|
||||
if prep isa immediateOutcome
|
||||
agentEventSink("executeToolCallsSequential 2-1")
|
||||
eventSink("executeToolCallsSequential 2-1"; publish=false, log=true)
|
||||
finalized = finalizedOutcome(tc, prep.result, prep.isError)
|
||||
agentEventSink("executeToolCallsSequential 2-2")
|
||||
eventSink("executeToolCallsSequential 2-2"; publish=false, log=true)
|
||||
else
|
||||
agentEventSink("executeToolCallsSequential 3")
|
||||
executed = executePreparedToolCall(prep, signal, agentEventSink, llmCall)
|
||||
agentEventSink("executeToolCallsSequential 3-1")
|
||||
finalized = finalizeExecutedToolCall(context, assistantMsg, prep, executed, config,
|
||||
signal, agentEventSink)
|
||||
agentEventSink("executeToolCallsSequential 3-2")
|
||||
eventSink("executeToolCallsSequential 3"; publish=false, log=true)
|
||||
executed = executePreparedToolCall(prep, signal, eventSink)
|
||||
|
||||
eventSink("executeToolCallsSequential 3-1"; publish=false, log=true)
|
||||
finalized = finalizeExecutedToolCall(context, assistantMsg, prep, executed, config,
|
||||
signal, eventSink)
|
||||
eventSink("executeToolCallsSequential 3-2"; publish=false, log=true)
|
||||
end
|
||||
agentEventSink("executeToolCallsSequential 4")
|
||||
agentEventSink("finalized $(finalized.toolCall.id), $(finalized.toolCall.name),
|
||||
$(finalized.result), $(finalized.isError)")
|
||||
eventSink("executeToolCallsSequential 4"; publish=false, log=true)
|
||||
# eventSink("finalized $(finalized.toolCall.id), $(finalized.toolCall.name),
|
||||
# $(finalized.result), $(finalized.isError)"; publish=false, log=true)
|
||||
push!(messages, createToolResultMessage(finalized))
|
||||
push!(finalizedCalls, finalized)
|
||||
agentEventSink("executeToolCallsSequential 5")
|
||||
eventSink("executeToolCallsSequential 5"; publish=false, log=true)
|
||||
if signal !== nothing && signal.aborted
|
||||
break
|
||||
end
|
||||
end
|
||||
agentEventSink("executeToolCallsSequential 6")
|
||||
eventSink("executeToolCallsSequential 6"; publish=false, log=true)
|
||||
return agentToolCallBatch(messages, shouldTerminate(finalizedCalls))
|
||||
end
|
||||
|
||||
@@ -1285,27 +1363,26 @@ function executeToolCallsParallel(
|
||||
toolCalls::Vector{agentToolCall},
|
||||
config::agentLoopConfig,
|
||||
signal::abortSignal,
|
||||
agentEventSink,
|
||||
eventSink,
|
||||
)::agentToolCallBatch
|
||||
|
||||
entries = Union{finalizedOutcome,Task}[]
|
||||
llmCall = config.llmCall
|
||||
|
||||
for tc in toolCalls
|
||||
agentEventSink(toolExecStartEvent(tc.id, tc.name, tc.arguments))
|
||||
eventSink(toolExecStartEvent(tc.id, tc.name, tc.arguments); publish=false, log=true)
|
||||
|
||||
prep = prepareToolCall(context, assistantMsg, tc, config, signal, agentEventSink)
|
||||
prep = prepareToolCall(context, assistantMsg, tc, config, signal, eventSink)
|
||||
|
||||
if prep isa immediateOutcome
|
||||
finalized = finalizedOutcome(tc, prep.result, prep.isError)
|
||||
agentEventSink(toolExecEndEvent(finalized.toolCall.id, finalized.toolCall.name,
|
||||
eventSink(toolExecEndEvent(finalized.toolCall.id, finalized.toolCall.name,
|
||||
finalized.result, finalized.isError))
|
||||
push!(entries, finalized)
|
||||
else
|
||||
t = Task() do
|
||||
executed = executePreparedToolCall(prep, signal, agentEventSink, llmCall)
|
||||
executed = executePreparedToolCall(prep, signal, eventSink)
|
||||
finalized = finalizeExecutedToolCall(context, assistantMsg, prep, executed, config, signal)
|
||||
agentEventSink(toolExecEndEvent(finalized.toolCall.id, finalized.toolCall.name,
|
||||
eventSink(toolExecEndEvent(finalized.toolCall.id, finalized.toolCall.name,
|
||||
finalized.result, finalized.isError))
|
||||
return finalized
|
||||
end
|
||||
@@ -1388,11 +1465,10 @@ function executeToolCalls(
|
||||
toolCalls::Vector{agentToolCall},
|
||||
config::agentLoopConfig,
|
||||
signal::abortSignal,
|
||||
agentEventSink,
|
||||
eventSink,
|
||||
)::agentToolCallBatch
|
||||
|
||||
llmCall = config.llmCall
|
||||
agentEventSink("_executeToolCalls 1")
|
||||
eventSink("_executeToolCalls 1"; publish=false, log=true)
|
||||
hasSequential = false
|
||||
for tc in toolCalls
|
||||
t = get(context.tools, tc.name, nothing)
|
||||
@@ -1401,15 +1477,15 @@ function executeToolCalls(
|
||||
break
|
||||
end
|
||||
end
|
||||
agentEventSink("_executeToolCalls 2")
|
||||
eventSink("_executeToolCalls 2"; publish=false, log=true)
|
||||
if config.toolExecution == "sequential" || hasSequential
|
||||
agentEventSink("_executeToolCalls 3")
|
||||
eventSink("_executeToolCalls 3"; publish=false, log=true)
|
||||
return executeToolCallsSequential(context, assistantMsg, toolCalls, config, signal,
|
||||
agentEventSink)
|
||||
eventSink)
|
||||
else
|
||||
agentEventSink("_executeToolCalls 4")
|
||||
eventSink("_executeToolCalls 4"; publish=false, log=true)
|
||||
return executeToolCallsParallel(context, assistantMsg, toolCalls, config, signal,
|
||||
agentEventSink)
|
||||
eventSink)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1448,13 +1524,13 @@ OpenAiToUserMessage(msg)
|
||||
# => userMessage("user", [textContent("Hello")], DateTime(...))
|
||||
```
|
||||
"""
|
||||
function OpenAiToUserMessage(msg::Dict)::userMessage
|
||||
function OpenAiToUserMessage(msg::AbstractDict)::userMessage
|
||||
content_blocks = Vector{messageContent}()
|
||||
|
||||
raw_content = get(msg, "content", Any[])
|
||||
if raw_content isa Vector
|
||||
for block in raw_content
|
||||
if block isa Dict
|
||||
if typeof(block) <: AbstractDict
|
||||
block_type = get(block, "type", "")
|
||||
if block_type == "text"
|
||||
text = get(block, "text", "")
|
||||
@@ -1543,11 +1619,6 @@ end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+19
-9
@@ -1,6 +1,6 @@
|
||||
module api
|
||||
|
||||
export prompt
|
||||
export promptAgent, takeResponse, followUp, stopAgent
|
||||
|
||||
using JSON, DataStructures, Dates, UUIDs, HTTP, Random, PrettyPrinting, Serialization,
|
||||
DataFrames
|
||||
@@ -18,7 +18,7 @@ The agent processes messages from `inputChannel` in the background task.
|
||||
|
||||
# Arguments
|
||||
- `agent::yiemAgent`: The agent instance to send a message to
|
||||
- `msg`: The message to send (any type accepted by the agent's processing pipeline)
|
||||
- `msg`: The message to send, in OpenAI message format (e.g. `Dict("role" => "user", "content" => "Hello!")`)
|
||||
|
||||
# Returns
|
||||
- The same `agent` instance for chaining
|
||||
@@ -29,15 +29,20 @@ The agent processes messages from `inputChannel` in the background task.
|
||||
|
||||
# Examples
|
||||
```jldoctest
|
||||
julia> runAgent(agent, "Hello!")
|
||||
julia> promptAgent(agent, Dict("role" => "user", "content" => "Hello!"))
|
||||
yiemAgent(...)
|
||||
```
|
||||
"""
|
||||
function runAgent(agent::yiemAgent, msg)
|
||||
function promptAgent(agent::yiemAgent, msg::AbstractDict{String, Any})
|
||||
put!(agent.inputChannel, msg)
|
||||
return agent
|
||||
end
|
||||
|
||||
function promptAgent(agent::yiemAgent, text::String)
|
||||
put!(agent.inputChannel, Dict("role" => "user", "content" => [Dict("type" => "text", "text" => text)]))
|
||||
return agent
|
||||
end
|
||||
|
||||
"""
|
||||
Take a response from the agent's output channel.
|
||||
|
||||
@@ -50,7 +55,7 @@ Blocks until the agent sends a response.
|
||||
- An `assistantMessage` instance representing the agent's response
|
||||
|
||||
# Notes
|
||||
- Use `runAgent(agent, msg)` to send a message before calling this function.
|
||||
- Use `promptAgent(agent, msg)` to send a message before calling this function.
|
||||
|
||||
# Examples
|
||||
```jldoctest
|
||||
@@ -70,27 +75,32 @@ and before any tool call results are sent.
|
||||
|
||||
# Arguments
|
||||
- `agent::yiemAgent`: The agent instance to send a follow-up message to
|
||||
- `msg`: The follow-up message to send
|
||||
- `msg`: The follow-up message to send, in OpenAI message format (e.g. `Dict("role" => "user", "content" => "Also consider red wines")`)
|
||||
|
||||
# Returns
|
||||
- The same `agent` instance for chaining
|
||||
|
||||
# Notes
|
||||
- Use `runAgent(agent, msg)` for the primary message and `followUp(agent, msg)` for additional
|
||||
- Use `promptAgent(agent, msg)` for the primary message and `followUp(agent, msg)` for additional
|
||||
messages while the agent is processing.
|
||||
- Follow-up messages are buffered in a separate channel (capacity 32 by default).
|
||||
|
||||
# Examples
|
||||
```jldoctest
|
||||
julia> followUp(agent, "Also consider red wines")
|
||||
julia> followUp(agent, Dict("role" => "user", "content" => "Also consider red wines"))
|
||||
yiemAgent(...)
|
||||
```
|
||||
"""
|
||||
function followUp(agent::yiemAgent, msg)
|
||||
function followUp(agent::yiemAgent, msg::AbstractDict{String, Any})
|
||||
put!(agent.followUpChannel, msg)
|
||||
return agent
|
||||
end
|
||||
|
||||
function followUp(agent::yiemAgent, text::String)
|
||||
put!(agent.followUpChannel, Dict("role" => "user", "content" => [Dict("type" => "text", "text" => text)]))
|
||||
return agent
|
||||
end
|
||||
|
||||
"""
|
||||
Gracefully stop the agent.
|
||||
|
||||
|
||||
+245
-133
@@ -1,179 +1,291 @@
|
||||
module toolRegistry
|
||||
|
||||
export toolStore, registerTool, getTools, clearTools, listTool
|
||||
export registerTool, registerAllTools, clearTools, listTool
|
||||
|
||||
using Dates
|
||||
using JSON, DataStructures
|
||||
using ..type
|
||||
|
||||
"""
|
||||
Per-agent isolated tool storage.
|
||||
|
||||
Each agent gets its own `toolStore` so tool registration is independent —
|
||||
`registerTool(store, tool)` only affects that agent's tool set.
|
||||
|
||||
# Fields
|
||||
- `tools::OrderedDict{String, agentTool}` — keyed by name for O(1) lookup + ordered iteration
|
||||
- `name::String` — identifier for debugging/logs
|
||||
# ── MCP helper functions ────────────────────────────────────────────
|
||||
|
||||
"""
|
||||
struct toolStore
|
||||
tools::OrderedDict{String, agentTool}
|
||||
name::String
|
||||
Extract text from MCP tool result content array.
|
||||
|
||||
Handles JSON-RPC 2.0 result content format:
|
||||
{"content": [{"type": "text", "text": "..."}], "isError": false}
|
||||
"""
|
||||
function _extract_text_content(result::AbstractDict)::String
|
||||
content = get(result, "content", Any[])
|
||||
if content isa Vector && !isempty(content)
|
||||
lines = String[]
|
||||
for block in content
|
||||
if block isa Dict && get(block, "type", "") == "text"
|
||||
push!(lines, string(get(block, "text", "")))
|
||||
end
|
||||
end
|
||||
if !isempty(lines)
|
||||
return join(lines, "\n")
|
||||
end
|
||||
end
|
||||
return JSON.json(result)
|
||||
end
|
||||
|
||||
"""
|
||||
toolStore(; name="default") -> toolStore
|
||||
Wrap an MCP tool definition as an `agentTool`.
|
||||
|
||||
Create a new empty tool store.
|
||||
|
||||
# Keyword Arguments
|
||||
- `name::String`: Display name for logging (default: `"default"`)
|
||||
|
||||
# Example
|
||||
```julia
|
||||
julia> store = toolStore(name="agent1")
|
||||
toolStore(OrderedDict{String, agentTool}(), "agent1")
|
||||
```
|
||||
The returned tool's `execute` function calls the MCP server's "tools/call"
|
||||
method with the validated arguments.
|
||||
"""
|
||||
function toolStore(; name::String="default")::toolStore
|
||||
toolStore(OrderedDict{String, agentTool}(), name)
|
||||
function _wrap_mcp_tool(mcpserver, tool_def::AbstractDict{String, Any}; eventSink=nothing, sessionId=nothing)::agentTool
|
||||
name = tool_def["name"]
|
||||
title = get(tool_def, "title", get(tool_def, "label", name))
|
||||
desc = get(tool_def, "description", "")
|
||||
input_schema = get(tool_def, "inputSchema", Dict{String,Any}())
|
||||
|
||||
# Normalize inputSchema to OpenAI function format
|
||||
if haskey(input_schema, "properties") && input_schema["type"] == "object"
|
||||
params = Dict(
|
||||
"type" => "object",
|
||||
"properties" => input_schema["properties"],
|
||||
"required" => get(input_schema, "required", Any[]),
|
||||
)
|
||||
else
|
||||
params = Dict(
|
||||
"type" => "object",
|
||||
"properties" => Dict{String,Any}(),
|
||||
"required" => Any[],
|
||||
)
|
||||
end
|
||||
|
||||
return agentTool(
|
||||
name=name,
|
||||
label=title,
|
||||
description=desc,
|
||||
inputSchema=params,
|
||||
execute=(toolCallId::String, args::AbstractDict{String, Any},
|
||||
signal::Union{Nothing,abortSignal},
|
||||
eventSink) -> begin
|
||||
try
|
||||
response = mcpserver("tools/call", name, args, sessionId; eventSink=eventSink)
|
||||
|
||||
# Parse JSON-RPC 2.0 response envelope
|
||||
if haskey(response, "error")
|
||||
rpc_error = response["error"]
|
||||
err_msg = get(rpc_error, "message", "Unknown MCP error")
|
||||
return agentToolResult(
|
||||
[textContent("MCP error: $err_msg")],
|
||||
Dict{Any,Any}("error" => err_msg),
|
||||
nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
result_data = get(response, "result", response)
|
||||
content_text = _extract_text_content(result_data)
|
||||
is_error = get(result_data, "isError", false)
|
||||
|
||||
return agentToolResult(
|
||||
[textContent(content_text)],
|
||||
Dict{Any,Any}("isError" => is_error),
|
||||
nothing, false
|
||||
)
|
||||
catch e
|
||||
errMsg = sprint(showerror, e)
|
||||
return agentToolResult(
|
||||
[textContent("MCP call error: $errMsg")],
|
||||
Dict{Any,Any}("error" => errMsg),
|
||||
nothing, false
|
||||
)
|
||||
end
|
||||
end,
|
||||
prepareArguments=nothing,
|
||||
validateRequiredArgs=nothing,
|
||||
parallelToolExecute=false,
|
||||
)
|
||||
end
|
||||
|
||||
"""
|
||||
listTool(store::toolStore) -> agentTool
|
||||
Discover and register MCP tools into `store.tools`.
|
||||
|
||||
Return an `agentTool` definition for listing registered tools.
|
||||
Queries the MCP server via `mcpserver("tools/list")` (JSON-RPC 2.0 format),
|
||||
parses the response envelope, and registers each discovered tool.
|
||||
Handles pagination via `nextCursor`. Skips tools already registered.
|
||||
|
||||
Each call produces a **new** tool object that captures (closes over)
|
||||
`store`. `register_all_tools` auto-registers one so the LLM can discover tools
|
||||
at runtime.
|
||||
# Returns
|
||||
- `Int`: number of new tools registered
|
||||
"""
|
||||
function register_mcp_tools(tools::OrderedDict{String, agentTool}, mcpserver; eventSink=nothing, sessionId=nothing)::Int
|
||||
if mcpserver === nothing
|
||||
return 0
|
||||
end
|
||||
new_count = 0
|
||||
try
|
||||
eventSink("register_mcp_tools 1")
|
||||
response = mcpserver("tools/list", sessionId; eventSink=eventSink)
|
||||
eventSink("register_mcp_tools 2")
|
||||
# Parse JSON-RPC 2.0 response envelope
|
||||
if haskey(response, "error")
|
||||
rpc_error = response["error"]
|
||||
err_msg = get(rpc_error, "message", "Unknown MCP error")
|
||||
println("[toolRegistry] MCP tools/list failed: $err_msg")
|
||||
return 0
|
||||
end
|
||||
if haskey(response, "result")
|
||||
response = response["result"]
|
||||
end
|
||||
|
||||
tools_array = response["tools"]
|
||||
cursor = get(response, "nextCursor", nothing)
|
||||
|
||||
for tool_def in tools_array
|
||||
name = tool_def["name"]
|
||||
if haskey(tools, name)
|
||||
continue
|
||||
end
|
||||
|
||||
wrapped = _wrap_mcp_tool(mcpserver, tool_def, eventSink=eventSink, sessionId=sessionId)
|
||||
tools[name] = wrapped
|
||||
new_count += 1
|
||||
end
|
||||
|
||||
# Paginate: fetch remaining tools if nextCursor is present
|
||||
while cursor !== nothing && cursor !== ""
|
||||
response = sessionId !== nothing ? mcpserver("tools/list", sessionId; eventSink=eventSink) : mcpserver("tools/list"; eventSink=eventSink)
|
||||
if haskey(response, "result")
|
||||
response = response["result"]
|
||||
end
|
||||
tools_array = get(response, "tools", Any[])
|
||||
cursor = get(response, "nextCursor", nothing)
|
||||
for tool_def in tools_array
|
||||
name = tool_def["name"]
|
||||
if haskey(tools, name)
|
||||
continue
|
||||
end
|
||||
wrapped = _wrap_mcp_tool(mcpserver, tool_def, eventSink=eventSink, sessionId=sessionId)
|
||||
tools[name] = wrapped
|
||||
new_count += 1
|
||||
end
|
||||
end
|
||||
|
||||
println("[toolRegistry] Discovered $new_count MCP tools. Total: $(length(tools))")
|
||||
catch e
|
||||
bt = catch_backtrace()
|
||||
err_msg = sprint() do io
|
||||
showerror(io, e, bt)
|
||||
println(io)
|
||||
end
|
||||
|
||||
eventSink(err_msg)
|
||||
|
||||
errMsg = sprint(showerror, e)
|
||||
println("[toolRegistry] MCP tools/list failed: $errMsg")
|
||||
end
|
||||
|
||||
return new_count
|
||||
end
|
||||
|
||||
"""
|
||||
registerTool(tools::OrderedDict{String, agentTool}, tool::agentTool) -> OrderedDict{String, agentTool}
|
||||
|
||||
Add `tool` to `tools`, overwriting any existing tool with the same name.
|
||||
|
||||
# Arguments
|
||||
- `store`: The tool store whose tools will be listed when the tool runs
|
||||
- `tools`: Tool dict to modify
|
||||
- `tool`: The `agentTool` to register
|
||||
|
||||
# Example
|
||||
```julia
|
||||
julia> store = toolStore(name="agent1");
|
||||
|
||||
julia> register_all_tools(store) # auto-registers listTools
|
||||
[toolRegistry:agent1] Loaded tool: getWeather (Weather Lookup)
|
||||
[toolRegistry:agent1] Registered tool: listTools
|
||||
|
||||
julia> tools = getTools(store)
|
||||
OrderedDict{String, agentTool} with 4 entries:
|
||||
"getWeather" => agentTool(...)
|
||||
"getTime" => agentTool(...)
|
||||
"writeTool" => agentTool(...)
|
||||
"listTools" => agentTool(...)
|
||||
```
|
||||
# Returns
|
||||
- The same `tools` dict (modified in place)
|
||||
"""
|
||||
function listTool(store::toolStore)::agentTool
|
||||
function registerTool(tools::OrderedDict{String, agentTool}, tool::agentTool; eventSink=nothing
|
||||
)::OrderedDict{String, agentTool}
|
||||
tools[tool.name] = tool
|
||||
println("[toolRegistry] Registered tool: $(tool.name)")
|
||||
return tools
|
||||
end
|
||||
|
||||
"""
|
||||
Remove all tools from the dict.
|
||||
|
||||
# Arguments
|
||||
- `tools`: Tool dict to clear
|
||||
|
||||
# Returns
|
||||
- `nothing`
|
||||
"""
|
||||
function clearTools(tools::OrderedDict{String, agentTool})::Nothing
|
||||
empty!(tools)
|
||||
println("[toolRegistry] Registry cleared")
|
||||
return nothing
|
||||
end
|
||||
|
||||
# ── listTools tool (auto-discover new MCP tools at runtime) ─────────
|
||||
|
||||
"""
|
||||
listTool(tools::OrderedDict{String, agentTool}, mcpserver) -> agentTool
|
||||
|
||||
MCP-aware listTools tool (JSON-RPC 2.0 protocol).
|
||||
|
||||
First call: queries the MCP server via `mcpserver("tools/list")`, registers
|
||||
all discovered tools into `tools` (in-place mutation, with
|
||||
pagination via nextCursor), then returns the full tool list.
|
||||
|
||||
Subsequent calls: returns the current list (tools remain registered).
|
||||
"""
|
||||
function listTool(tools::OrderedDict{String, agentTool}, mcpserver; eventSink=nothing, sessionId=nothing)::agentTool
|
||||
return agentTool(
|
||||
name = "listTools",
|
||||
label = "List Tools",
|
||||
description = "List all available tools with their names, labels, and descriptions. Use this before creating a new tool to check for name collisions.",
|
||||
inputSchema = Dict{String,Any}(
|
||||
name="listTools",
|
||||
label="List Tools",
|
||||
description="List all available tools. First call discovers and registers all tools from the MCP server. After discovery, new tools become immediately available for use.",
|
||||
inputSchema=Dict{String,Any}(
|
||||
"type" => "object",
|
||||
"properties" => Dict{String,Any}(),
|
||||
"required" => Any[]
|
||||
),
|
||||
execute = (toolCallId, args, signal, onPartialResult) -> begin
|
||||
tools = getTools(store)
|
||||
if isempty(tools)
|
||||
result_text = "No tools registered."
|
||||
else
|
||||
lines = String["- $(t.name): $(t.label) — $(t.description)" for (k, t) in tools]
|
||||
result_text = "Available tools:\n" * join(lines, "\n")
|
||||
end
|
||||
execute=(toolCallId::String, args::AbstractDict{String, Any},
|
||||
signal::Union{Nothing,abortSignal},
|
||||
eventSink) -> begin
|
||||
# Discover and register MCP tools (idempotent — skips already registered)
|
||||
new_count = register_mcp_tools(tools, mcpserver; eventSink=eventSink, sessionId=sessionId)
|
||||
eventSink("tools dump: " * sprint(show, tools))
|
||||
|
||||
# Always include listTools itself in the count
|
||||
total = length(tools)
|
||||
|
||||
lines = String[
|
||||
"- $(t.name): $(t.label) — $(t.description)"
|
||||
for (k, t) in tools
|
||||
]
|
||||
result_text = "Available tools ($total):\n" * join(lines, "\n")
|
||||
|
||||
return agentToolResult(
|
||||
[textContent(result_text)],
|
||||
Dict{Any,Any}("count" => length(tools)),
|
||||
Dict{Any,Any}("count" => total),
|
||||
nothing, false
|
||||
)
|
||||
end,
|
||||
prepareArguments = nothing,
|
||||
validateRequiredArgs = nothing,
|
||||
parallelToolExecute = false
|
||||
prepareArguments=nothing,
|
||||
validateRequiredArgs=nothing,
|
||||
parallelToolExecute=false,
|
||||
)
|
||||
end
|
||||
|
||||
# Note: register_all_tools is defined in YiemAgent.jl where tool functions are in scope
|
||||
# ── High-level API ──────────────────────────────────────────────────
|
||||
|
||||
"""
|
||||
registerTool(store::toolStore, tool::agentTool) -> OrderedDict{String, agentTool}
|
||||
registerAllTools(tools::OrderedDict{String, agentTool}, mcpserver)
|
||||
|
||||
Add `tool` to `store`, overwriting any existing tool with the same name.
|
||||
Register all tools for an agent:
|
||||
1. Auto-discover existing tools from the MCP server
|
||||
2. Register the `listTools` tool so the agent can discover new tools at runtime
|
||||
|
||||
# Arguments
|
||||
- `store`: Tool store to modify
|
||||
- `tool`: The `agentTool` to register
|
||||
|
||||
# Returns
|
||||
- The same `store.tools` dict (modified in place)
|
||||
|
||||
# Example
|
||||
```julia
|
||||
julia> store = toolStore(name="agent1");
|
||||
|
||||
julia> registerTool(store, listTool(store))
|
||||
[toolRegistry:agent1] Registered tool: listTools
|
||||
OrderedDict{String, agentTool} with 1 entry:
|
||||
"listTools" => agentTool(...)
|
||||
```
|
||||
- `tools`: The tool dict to populate
|
||||
- `mcpserver`: A callable struct that communicates with the MCP server
|
||||
"""
|
||||
function registerTool(store::toolStore, tool::agentTool)::OrderedDict{String, agentTool}
|
||||
store.tools[tool.name] = tool
|
||||
println("[$(store.name)] Registered tool: $(tool.name)")
|
||||
return store.tools
|
||||
end
|
||||
|
||||
"""
|
||||
Return the tools registered in `store`.
|
||||
|
||||
The returned dict is the **same object** stored inside `store` — mutations
|
||||
to it (e.g. via `registerTool`) are visible through subsequent calls.
|
||||
|
||||
# Arguments
|
||||
- `store`: Tool store to query
|
||||
|
||||
# Returns
|
||||
- `OrderedDict{String, agentTool}`: Tools keyed by name, in registration order
|
||||
|
||||
# Example
|
||||
```julia
|
||||
julia> tools = getTools(store)
|
||||
OrderedDict{String, agentTool} with 2 entries:
|
||||
"getWeather" => agentTool(...)
|
||||
"getTime" => agentTool(...)
|
||||
```
|
||||
"""
|
||||
function getTools(store::toolStore)::OrderedDict{String, agentTool}
|
||||
return store.tools
|
||||
end
|
||||
|
||||
"""
|
||||
Remove all tools from `store`.
|
||||
|
||||
# Arguments
|
||||
- `store`: Tool store to clear
|
||||
|
||||
# Returns
|
||||
- `nothing`
|
||||
|
||||
# Example
|
||||
```julia
|
||||
julia> clearTools(store)
|
||||
[toolRegistry:agent1] Registry cleared
|
||||
nothing
|
||||
|
||||
julia> getTools(store)
|
||||
OrderedDict{String, agentTool} with 0 entries
|
||||
```
|
||||
"""
|
||||
function clearTools(store::toolStore)::Nothing
|
||||
empty!(store.tools)
|
||||
println("[$(store.name)] Registry cleared")
|
||||
return nothing
|
||||
function registerAllTools(tools::OrderedDict{String, agentTool}, mcpserver=nothing; eventSink=nothing, sessionId=nothing)
|
||||
list_t = listTool(tools, mcpserver; eventSink=eventSink, sessionId=sessionId)
|
||||
registerTool(tools, list_t; eventSink=eventSink)
|
||||
end
|
||||
|
||||
end # module
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
using .type
|
||||
using Dates
|
||||
|
||||
"""
|
||||
Validate required arguments for the getTime tool.
|
||||
|
||||
Demonstrates custom validation beyond simple required-field checking:
|
||||
- Ensures at least one time source (timezone or city) is provided
|
||||
- Validates timezone is in IANA format if specified
|
||||
- Validates city name is not empty if specified
|
||||
|
||||
# Arguments
|
||||
- `args::Dict{String,Any}`: Arguments from the LLM
|
||||
|
||||
# Returns
|
||||
- `nothing` if validation passes
|
||||
- `String` error message if validation fails
|
||||
"""
|
||||
function getTimeValidateRequiredArgs(args::Dict{String,Any})::Union{Nothing,String}
|
||||
tz = get(args, "timezone", nothing)
|
||||
city = get(args, "city", "")
|
||||
|
||||
hasTz = tz !== nothing && !isempty(tz)
|
||||
hasCity = !isempty(city)
|
||||
|
||||
# At least one of timezone or city is required
|
||||
if !hasTz && !hasCity
|
||||
return "Missing required argument: provide at least one of 'timezone' or 'city'"
|
||||
end
|
||||
|
||||
# Validate timezone format (IANA tz database: "Continent/City" or "Continent/City/SubCity")
|
||||
if hasTz
|
||||
tz_str = string(tz)
|
||||
if !occursin(r"^[A-Za-z]+\/[A-Za-z]+(/[A-Za-z]+)*$", tz_str)
|
||||
return "Invalid timezone format: '$tz_str'. Use IANA format, e.g. 'America/New_York' or 'Asia/Tokyo'"
|
||||
end
|
||||
end
|
||||
|
||||
return nothing
|
||||
end
|
||||
|
||||
"""
|
||||
Execute the getTime tool.
|
||||
|
||||
Returns mock time data for the given timezone or city.
|
||||
"""
|
||||
function getTimeExecute(toolCallId::String, args::Dict{String,Any}, signal::Union{Nothing,abortSignal},
|
||||
onPartialResult, llmCall=nothing)
|
||||
tz = get(args, "timezone", nothing)
|
||||
city = get(args, "city", "")
|
||||
if tz !== nothing
|
||||
result = "Current time in $(tz): $(now())"
|
||||
else
|
||||
result = "Current time in $(city): $(now())"
|
||||
end
|
||||
return agentToolResult(
|
||||
[textContent(result)],
|
||||
Dict{Any,Any}(), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
"""
|
||||
Define and return the getTime agentTool.
|
||||
"""
|
||||
function getTimeTool()::agentTool
|
||||
return agentTool(
|
||||
name = "getTime",
|
||||
label = "Time Lookup",
|
||||
description = "Get current local time for a timezone or city.",
|
||||
inputSchema = Dict{String,Any}(
|
||||
"type" => "object",
|
||||
"properties" => Dict(
|
||||
"timezone" => Dict("type" => "string", "description" => "IANA timezone, e.g. 'America/New_York'"),
|
||||
"city" => Dict("type" => "string", "description" => "City name as fallback")
|
||||
),
|
||||
"required" => []
|
||||
),
|
||||
execute = getTimeExecute,
|
||||
prepareArguments = nothing,
|
||||
validateRequiredArgs = getTimeValidateRequiredArgs,
|
||||
parallelToolExecute = false
|
||||
)
|
||||
end
|
||||
@@ -1,48 +0,0 @@
|
||||
using msghandler
|
||||
using .type
|
||||
|
||||
"""
|
||||
Execute the getWeather tool.
|
||||
|
||||
Returns mock weather data for the given city and temperature units.
|
||||
"""
|
||||
function getWeatherExecute(toolCallId::String, args::Dict{String,Any}, signal::Union{Nothing,abortSignal},
|
||||
agentEventSink, llmCall=nothing)
|
||||
|
||||
agentEventSink("Getting weather...")
|
||||
|
||||
city = get(args, "city", "")
|
||||
units = get(args, "units", "celsius")
|
||||
temp = units == "fahrenheit" ? "72" : "22"
|
||||
unit_symbol = units == "celsius" ? "°C" : "°F"
|
||||
|
||||
return agentToolResult(
|
||||
[textContent("Weather in $(city): Sunny, $(temp)$(unit_symbol)")],
|
||||
Dict{Any,Any}(),
|
||||
nothing,
|
||||
false
|
||||
)
|
||||
end
|
||||
|
||||
"""
|
||||
Define and return the getWeather agentTool.
|
||||
"""
|
||||
function getWeatherTool()::agentTool
|
||||
return agentTool(
|
||||
name = "getWeather",
|
||||
label = "Weather Lookup",
|
||||
description = "Fetch current weather and forecast for a given city.",
|
||||
inputSchema = Dict{String,Any}(
|
||||
"type" => "object",
|
||||
"properties" => Dict(
|
||||
"city" => Dict("type" => "string", "description" => "City and country, e.g., 'San Francisco, CA' or 'Tokyo, Japan'"),
|
||||
"units" => Dict("type" => "string", "enum" => ["celsius", "fahrenheit"], "default" => "celsius", "description" => "Temperature scale")
|
||||
),
|
||||
"required" => ["city"]
|
||||
),
|
||||
execute = getWeatherExecute,
|
||||
prepareArguments = nothing,
|
||||
validateRequiredArgs = nothing,
|
||||
parallelToolExecute = false
|
||||
)
|
||||
end
|
||||
@@ -1,397 +0,0 @@
|
||||
using .type
|
||||
using LibPQ, DataFrames, JSON, DataStructures
|
||||
using Dates, Random, HTTP
|
||||
using GeneralUtils
|
||||
|
||||
# ── Database config — update for your environment ───────────────────────
|
||||
const DB_CONFIG = Dict{String,Any}(
|
||||
"host" => "localhost",
|
||||
"port" => 5432,
|
||||
"dbname" => "winedb",
|
||||
"user" => "postgres",
|
||||
"password" => "",
|
||||
)
|
||||
|
||||
"""
|
||||
Execute the search_wine_database! tool.
|
||||
|
||||
Uses the agent's LLM to generate SQL from the free-form text query,
|
||||
then executes it against the wine database and returns formatted results.
|
||||
"""
|
||||
function searchWineExecute(
|
||||
toolCallId::String,
|
||||
args::Dict{String,Any},
|
||||
signal::Union{Nothing,abortSignal},
|
||||
agentEventSink,
|
||||
llmCall,
|
||||
)::agentToolResult
|
||||
#WORKING
|
||||
search_query = get(args, "searchQuery", "")::String
|
||||
|
||||
if isempty(search_query)
|
||||
return agentToolResult(
|
||||
[textContent("Please provide a search query for the wine database.")],
|
||||
Dict{Any,Any}(), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
agentEventSink("searchWineExecute: query=$search_query")
|
||||
|
||||
# ── SQL generation prompt ───────────────────────────────────────────
|
||||
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.
|
||||
- Text information in the database is usually stored in lower case.
|
||||
If your search returns empty, try using lower case to search.
|
||||
- Overly strict conditions usually yield empty results.
|
||||
- Use ILIKE for case-insensitive text matching.
|
||||
- Only output the SQL query — do not wrap it in backticks or add comments.
|
||||
|
||||
# situation
|
||||
You are a wine store database assistant. You will be given a user's
|
||||
natural language search query and the database table schema.
|
||||
|
||||
# objective
|
||||
Generate a single SQL query to find wines matching the user's request.
|
||||
|
||||
# your responsibility includes
|
||||
Fulfill the objective.
|
||||
|
||||
# you should respond with ONLY the SQL query string, ending with ';'
|
||||
"""
|
||||
|
||||
table_schema = """
|
||||
CREATE TABLE wine (
|
||||
wine_id uuid primary key default gen_random_uuid (),
|
||||
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 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 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
|
||||
);
|
||||
"""
|
||||
|
||||
context = "<internal_context_for_assistant>\n<database_table_schema>\n$table_schema\n</database_table_schema>\n</internal_context_for_assistant>\n\n"
|
||||
input = context * "User query: $search_query\n\nGenerate the SQL query:"
|
||||
|
||||
# ── Call LLM for SQL generation ────────────────────────────────────
|
||||
max_attempts = 5
|
||||
generated_sql = nothing
|
||||
|
||||
for attempt in 1:max_attempts
|
||||
msg = Dict(
|
||||
"messages" => [
|
||||
Dict(
|
||||
"role" => "system",
|
||||
"content" => [Dict("type" => "text", "text" => systemmsg)],
|
||||
),
|
||||
Dict(
|
||||
"role" => "user",
|
||||
"content" => [Dict("type" => "text", "text" => input)],
|
||||
),
|
||||
],
|
||||
"temperature" => 0.7,
|
||||
)
|
||||
|
||||
llm_response = llmCall(msg)
|
||||
|
||||
# Clean the response — extract SQL from potential markdown/code blocks
|
||||
sql_text = _clean_sql_response(llm_response)
|
||||
|
||||
# Validate it looks like SQL
|
||||
if _is_valid_sql(sql_text)
|
||||
generated_sql = sql_text
|
||||
agentEventSink("searchWine: generated SQL (attempt $attempt)\n$sql_text")
|
||||
break
|
||||
else
|
||||
agentEventSink("searchWine: invalid SQL attempt $attempt: $sql_text")
|
||||
end
|
||||
end
|
||||
|
||||
if generated_sql === nothing
|
||||
return agentToolResult(
|
||||
[textContent("Failed to generate a valid SQL query for your search. Please try rephrasing.")],
|
||||
Dict{Any,Any}("error" => "sql_generation_failed"), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
# ── Execute SQL ────────────────────────────────────────────────────
|
||||
try
|
||||
conn = LibPQ.Connection(DB_CONFIG)
|
||||
|
||||
# Ensure LIMIT to prevent large result sets
|
||||
sanitized_sql = _ensure_limit(generated_sql)
|
||||
agentEventSink("searchWine: executing\n$sanitized_sql")
|
||||
|
||||
result = LibPQ.execute(conn, sanitized_sql)
|
||||
close(conn)
|
||||
|
||||
if !LibPQ.hasdata(result)
|
||||
return agentToolResult(
|
||||
[textContent("No wines found matching your search. Try loosening your criteria.")],
|
||||
Dict{Any,Any}("count" => 0), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
df = DataFrame(result)
|
||||
num_rows, num_cols = size(df)
|
||||
|
||||
if num_cols > 30
|
||||
return agentToolResult(
|
||||
[textContent("The result has more than 30 columns. Please be more specific in your search.")],
|
||||
Dict{Any,Any}("error" => "too_many_columns"), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
# Randomly sample up to 2 rows for display if more than 2 results
|
||||
display_df = df
|
||||
if num_rows > 2
|
||||
idx = sample(1:num_rows, min(2, num_rows), replace=false)
|
||||
display_df = df[idx, :]
|
||||
end
|
||||
|
||||
# Convert to vector of dicts
|
||||
result_vec = GeneralUtils.dfToVectorDict(display_df)
|
||||
|
||||
# Fetch bottle images if available
|
||||
for d in result_vec
|
||||
image_url_json_str = get(d, "image_url", nothing)
|
||||
if image_url_json_str !== nothing && !isempty(string(image_url_json_str))
|
||||
try
|
||||
image_url_json_obj = JSON.parse(string(image_url_json_str))
|
||||
base_url = "http://192.168.88.106:8080/"
|
||||
if haskey(image_url_json_obj, "bottle")
|
||||
url = base_url * string(image_url_json_obj["bottle"])
|
||||
image_data = HTTP.get(url)
|
||||
image_base64_string = base64encode(image_data.body)
|
||||
d["image"] = image_base64_string
|
||||
end
|
||||
catch
|
||||
# Skip image fetch on error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Format results as readable text
|
||||
result_str = _format_wine_results(display_df)
|
||||
|
||||
return agentToolResult(
|
||||
[textContent(result_str)],
|
||||
Dict{Any,Any}(
|
||||
"count" => num_rows,
|
||||
"displayed" => size(display_df, 1),
|
||||
),
|
||||
nothing, false
|
||||
)
|
||||
|
||||
catch e
|
||||
errMsg = sprint(showerror, e)
|
||||
return agentToolResult(
|
||||
[textContent("Database error: $errMsg")],
|
||||
Dict{Any,Any}("error" => errMsg), nothing, false
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
"""
|
||||
Extract a SQL query string from the LLM response, handling potential
|
||||
markdown code blocks, extra text, or JSON wrapping.
|
||||
"""
|
||||
function _clean_sql_response(response)::String
|
||||
text = string(response)
|
||||
|
||||
# Try to extract from code block
|
||||
if occursin("```", text)
|
||||
extracted = GeneralUtils.extract_triple_backtick_text(text)
|
||||
if !isempty(extracted)
|
||||
text = extracted[1]
|
||||
# Remove "sql\n" prefix if present
|
||||
if startswith(text, "sql\n") || startswith(text, "SQL\n")
|
||||
text = text[5:end]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Remove JSON wrapping if present
|
||||
text = strip(text)
|
||||
if startswith(text, "{") && occursin("action_input", text)
|
||||
# Parse as JSON and extract action_input
|
||||
try
|
||||
parsed = JSON.parse(text)
|
||||
if parsed isa Dict
|
||||
text = get(parsed, "action_input", text)
|
||||
end
|
||||
catch
|
||||
# Keep original
|
||||
end
|
||||
end
|
||||
|
||||
# Extract SQL keywords to find the actual query
|
||||
lines = split(strip(text), '\n')
|
||||
sql_lines = String[]
|
||||
for line in lines
|
||||
stripped = strip(line)
|
||||
if occursin(r"(?i)(SELECT|FROM|WHERE|JOIN|ORDER|LIMIT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH)", stripped)
|
||||
# Take everything from this line to the end
|
||||
push!(sql_lines, line)
|
||||
elseif !isempty(sql_lines)
|
||||
# Continue collecting if we already found SQL
|
||||
push!(sql_lines, line)
|
||||
end
|
||||
end
|
||||
|
||||
result = join(sql_lines, "\n")
|
||||
|
||||
# Ensure it ends with semicolon
|
||||
result = strip(result)
|
||||
if !endswith(result, ";")
|
||||
result *= ";"
|
||||
end
|
||||
|
||||
return result
|
||||
end
|
||||
|
||||
"""
|
||||
Check if a string looks like a valid SQL query.
|
||||
"""
|
||||
function _is_valid_sql(sql::String)::Bool
|
||||
sql = strip(sql)
|
||||
# Must start with a SQL keyword
|
||||
has_sql_keyword = occursin(r"(?i)(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH)\s", sql) ||
|
||||
occursin(r"(?i)(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH)\s*;", sql)
|
||||
# Must end with semicolon
|
||||
has_semicolon = endswith(sql, ";")
|
||||
# Must not be too short (reject single words)
|
||||
reasonable_length = length(sql) > 10
|
||||
return has_sql_keyword && has_semicolon && reasonable_length
|
||||
end
|
||||
|
||||
"""
|
||||
Ensure the SQL query has a LIMIT clause to prevent loading excessive data.
|
||||
"""
|
||||
function _ensure_limit(sql::String)::String
|
||||
sql = strip(sql)
|
||||
if !occursin(r"(?i)LIMIT", sql)
|
||||
# Remove existing semicolon, add LIMIT, re-add semicolon
|
||||
if endswith(sql, ";")
|
||||
sql = sql[1:end-1]
|
||||
end
|
||||
sql *= " ORDER BY RANDOM() LIMIT 2;"
|
||||
end
|
||||
return sql
|
||||
end
|
||||
|
||||
"""
|
||||
Format wine database results as human-readable text.
|
||||
"""
|
||||
function _format_wine_results(df::DataFrame)::String
|
||||
lines = String[]
|
||||
num_rows = size(df, 1)
|
||||
|
||||
for i in 1:num_rows
|
||||
row = df[i, :]
|
||||
push!(lines, "$(i). $(get(row, :wine_name, "Unknown")) $(get(row, :vintage, ""))")
|
||||
|
||||
winery = get(row, :winery, "Unknown")
|
||||
region = get(row, :region, "Unknown")
|
||||
country = get(row, :country, "Unknown")
|
||||
push!(lines, " Winery: $winery")
|
||||
push!(lines, " Region: $region, $country")
|
||||
|
||||
grape = get(row, :grape, "Unknown")
|
||||
wtype = get(row, :wine_type, "Unknown")
|
||||
push!(lines, " Grape: $grape")
|
||||
push!(lines, " Type: $wtype")
|
||||
|
||||
sweetness = get(row, :sweetness, "N/A")
|
||||
intensity = get(row, :intensity, "N/A")
|
||||
tannin_val = get(row, :tannin, "N/A")
|
||||
acidity = get(row, :acidity, "N/A")
|
||||
push!(lines, " Profile: Sweetness: $sweetness, Intensity: $intensity, Tannin: $tannin_val, Acidity: $acidity")
|
||||
|
||||
tasting = get(row, :tasting_notes, nothing)
|
||||
if tasting !== nothing && !isempty(string(tasting))
|
||||
tn = string(tasting)
|
||||
limit = min(200, length(tn))
|
||||
push!(lines, " Notes: $(tn[1:limit])$(length(tn) > limit ? "..." : "")")
|
||||
end
|
||||
|
||||
price = get(row, :price, "N/A")
|
||||
currency = get(row, :currency, "")
|
||||
retailer = get(row, :retailer_name, "N/A")
|
||||
push!(lines, " Price: $price $currency at $retailer")
|
||||
push!(lines, "")
|
||||
end
|
||||
|
||||
return join(lines, "\n")
|
||||
end
|
||||
|
||||
"""
|
||||
Define and return the searchWine agentTool.
|
||||
"""
|
||||
function searchWineTool()::agentTool
|
||||
return agentTool(
|
||||
name = "searchWine",
|
||||
label = "Search Wine Database",
|
||||
description = "Search the wine database for wines matching a free-text query. Uses the LLM to generate SQL and execute it against the database. Returns wine details including name, winery, vintage, tasting notes, and price.",
|
||||
inputSchema = Dict{String,Any}(
|
||||
"type" => "object",
|
||||
"properties" => Dict(
|
||||
"searchQuery" => Dict(
|
||||
"type" => "string",
|
||||
"description" => "Free-text description of the wine you're looking for, e.g., 'a light-bodied red wine from France under 50 dollars'",
|
||||
),
|
||||
),
|
||||
"required" => ["searchQuery"],
|
||||
),
|
||||
execute = searchWineExecute,
|
||||
prepareArguments = nothing,
|
||||
validateRequiredArgs = nothing,
|
||||
parallelToolExecute = false,
|
||||
)
|
||||
end
|
||||
@@ -1,276 +0,0 @@
|
||||
using .type
|
||||
using JSON
|
||||
|
||||
"""
|
||||
Tool that writes new Julia tool module files to disk.
|
||||
|
||||
The agent can use this tool when it encounters a task that no existing tool
|
||||
can handle. Provide the tool's name, label, description, inputSchema, and
|
||||
execute logic as Julia code. The tool is written to `src/tools/<name>.jl`.
|
||||
|
||||
After calling this tool, add the new file to `YiemAgent.jl` with an `include()`
|
||||
statement (after `include("toolRegistry.jl")`), then restart the agent.
|
||||
The new tool must be registered in `register_all_tools()` in `toolRegistry.jl`.
|
||||
|
||||
# Example
|
||||
|
||||
1. Agent calls writeTool with a spec for a "searchWine" tool
|
||||
2. writeTool generates src/tools/searchWine.jl
|
||||
3. Developer adds `include("tools/searchWine.jl")` to YiemAgent.jl
|
||||
4. Developer adds `registerTool(store, searchWineTool())` to register_all_tools()
|
||||
5. Restart agent — new tool is available
|
||||
|
||||
# How It Works
|
||||
|
||||
writeTool is a **file writer**, not a code generator. The LLM provides the
|
||||
tool logic as `executeCode`, and writeTool wraps it in Julia boilerplate:
|
||||
- Converts `inputSchema` Dict into Julia `Dict{String,Any}(...)` string
|
||||
- Indents `executeCode` with 4 spaces
|
||||
- Wraps it inside `function executeTool(...)::agentToolResult ... end`
|
||||
- Appends `writeToolTool()` returning an `agentTool` struct
|
||||
- Writes the combined string to `src/tools/<name>.jl`
|
||||
|
||||
# Important Notes
|
||||
|
||||
- The `executeCode` string is embedded literally into the generated tool.
|
||||
Use `args["param_name"]` to access input parameters.
|
||||
- The code string should be the function body (NOT wrapped in a function).
|
||||
Lines will be indented with 4 spaces inside the execute function.
|
||||
- Tool names must be valid Julia identifiers (lowercase letters, digits, underscores,
|
||||
no leading digits or special characters).
|
||||
"""
|
||||
|
||||
"""
|
||||
Validate that a tool name is a valid Julia identifier.
|
||||
"""
|
||||
function validateToolName(name::String)::Union{Nothing,String}
|
||||
if !occursin(r"^[a-zA-Z_][a-zA-Z0-9_!]*$", name)
|
||||
return "Invalid tool name: '$name'. Tool names must be valid Julia identifiers (letters, digits, underscores, starting with a letter or underscore)."
|
||||
end
|
||||
return nothing
|
||||
end
|
||||
|
||||
"""
|
||||
Indent a multi-line code string by the specified number of spaces.
|
||||
"""
|
||||
function indent_code(code::String, n::Int)::String
|
||||
prefix = " "^n
|
||||
lines = split(code, '\n')
|
||||
result_lines = String[prefix * line for line in lines]
|
||||
return join(result_lines, "\n")
|
||||
end
|
||||
|
||||
"""
|
||||
Convert a Julia Dict to a valid Julia Dict{String,Any}(...) literal string.
|
||||
"""
|
||||
function dict_to_julia_literal(d)::String
|
||||
if d isa Dict
|
||||
items = String[]
|
||||
for (k, v) in d
|
||||
key_str = json_string(k)
|
||||
val_str = value_to_julia(v)
|
||||
push!(items, "$key_str => $val_str")
|
||||
end
|
||||
return "Dict{String,Any}(" * join(items, ", ") * ")"
|
||||
else
|
||||
return value_to_julia(d)
|
||||
end
|
||||
end
|
||||
|
||||
function value_to_julia(v)::String
|
||||
if v isa Dict
|
||||
return dict_to_julia_literal(v)
|
||||
elseif v isa Vector
|
||||
items = [value_to_julia(x) for x in v]
|
||||
return "[" * join(items, ", ") * "]"
|
||||
elseif v isa String
|
||||
escaped = replace(v, "\\" => "\\\\")
|
||||
escaped = replace(escaped, "\"" => "\\\"")
|
||||
return "\"$escaped\""
|
||||
elseif v isa Number
|
||||
return string(v)
|
||||
elseif v isa Bool
|
||||
return string(v)
|
||||
elseif v === nothing
|
||||
return "nothing"
|
||||
else
|
||||
return "\"$(v)\""
|
||||
end
|
||||
end
|
||||
|
||||
"""
|
||||
Convert any Julia value to a JSON string.
|
||||
"""
|
||||
function json_string(v)::String
|
||||
return JSON.json(v)
|
||||
end
|
||||
|
||||
"""
|
||||
Define and return the writeTool agentTool.
|
||||
"""
|
||||
function writeToolTool()::agentTool
|
||||
return agentTool(
|
||||
name = "writeTool",
|
||||
label = "Create Tool",
|
||||
description = "Write a new Julia tool module file to src/tools/<name>.jl. The LLM provides the tool logic as executeCode; writeTool wraps it in Julia boilerplate and writes the file. Restart the agent to load the new tool.",
|
||||
inputSchema = Dict{String,Any}(
|
||||
"type" => "object",
|
||||
"properties" => Dict(
|
||||
"name" => Dict("type" => "string", "description" => "Unique tool name (valid Julia identifier, no spaces or special chars)"),
|
||||
"label" => Dict("type" => "string", "description" => "Human-readable tool name shown in tool descriptions"),
|
||||
"description" => Dict("type" => "string", "description" => "What the tool does (shown to LLM for tool selection decisions)"),
|
||||
"inputSchema" => Dict(
|
||||
"type" => "object",
|
||||
"description" => "JSON Schema describing tool parameters in MCP format"
|
||||
),
|
||||
"executeCode" => Dict("type" => "string", "description" => "Julia code for the execute function body. Use args[\"key\"] to access parameters. Do NOT wrap in a function definition."),
|
||||
"validateCode" => Dict("type" => "string", "optional" => true, "description" => "Optional custom validation Julia code (runs before execute). Use args[\"key\"] to access parameters. Return nothing to pass, or a string error message to fail."),
|
||||
"prepareCode" => Dict("type" => "string", "optional" => true, "description" => "Optional argument preparation code (runs before validation). Return modified args dict."),
|
||||
"parallel" => Dict("type" => "boolean", "default" => false, "description" => "Whether this tool can run in parallel with other tools")
|
||||
),
|
||||
"required" => ["name", "label", "description", "inputSchema", "executeCode"]
|
||||
),
|
||||
execute = (toolCallId::String, args::Dict{String,Any}, signal::Union{Nothing,abortSignal}, onPartialResult, llmCall=nothing) -> begin
|
||||
tool_name = get(args, "name", "")::String
|
||||
tool_label = get(args, "label", tool_name)::String
|
||||
tool_description = get(args, "description", "")::String
|
||||
tool_schema = get(args, "inputSchema", Dict{String,Any}())::Dict{String,Any}
|
||||
execute_code = get(args, "executeCode", "")::String
|
||||
validate_code = get(args, "validateCode", nothing)::Union{String,Nothing}
|
||||
prepare_code = get(args, "prepareCode", nothing)::Union{String,Nothing}
|
||||
parallel = get(args, "parallel", false)::Bool
|
||||
|
||||
# Validate tool name
|
||||
name_err = validateToolName(tool_name)
|
||||
if name_err !== nothing
|
||||
return agentToolResult(
|
||||
[textContent(name_err)],
|
||||
Dict{Any,Any}(), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
# Validate required fields
|
||||
if isempty(tool_name)
|
||||
return agentToolResult(
|
||||
[textContent("Missing required field: 'name'")],
|
||||
Dict{Any,Any}(), nothing, false
|
||||
)
|
||||
end
|
||||
if isempty(tool_description)
|
||||
return agentToolResult(
|
||||
[textContent("Missing required field: 'description'")],
|
||||
Dict{Any,Any}(), nothing, false
|
||||
)
|
||||
end
|
||||
if isempty(execute_code)
|
||||
return agentToolResult(
|
||||
[textContent("Missing required field: 'executeCode'")],
|
||||
Dict{Any,Any}(), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
onPartialResult(Dict("status" => "Generating tool: $tool_name"))
|
||||
|
||||
# Build the tool file path
|
||||
script_dir = dirname(@__FILE__)
|
||||
tools_dir = dirname(script_dir)
|
||||
filepath = joinpath(tools_dir, "$(tool_name).jl")
|
||||
|
||||
# Check for naming conflicts
|
||||
if isfile(filepath)
|
||||
return agentToolResult(
|
||||
[textContent("Tool file already exists: $filepath. Rename the tool or delete the existing file first.")],
|
||||
Dict{Any,Any}(), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
onPartialResult(Dict("status" => "Writing file: $(basename(filepath))"))
|
||||
|
||||
# Convert schema Dict to a Julia Dict literal string
|
||||
schema_literal = dict_to_julia_literal(tool_schema)
|
||||
|
||||
# Build optional validation function
|
||||
validate_section = if validate_code !== nothing && !isempty(validate_code)
|
||||
indented = indent_code(validate_code, 4)
|
||||
"function validateRequiredArgs(args::Dict{String,Any})::Union{Nothing,String}\n$indented\n return nothing\nend\n"
|
||||
else
|
||||
""
|
||||
end
|
||||
|
||||
# Build optional prepare function
|
||||
prepare_section = if prepare_code !== nothing && !isempty(prepare_code)
|
||||
indented = indent_code(prepare_code, 4)
|
||||
"function prepareArguments(args::Dict{String,Any})::Dict{String,Any}\n$indented\n return args\nend\n"
|
||||
else
|
||||
""
|
||||
end
|
||||
|
||||
# Indent user's execute code for embedding inside execute function body
|
||||
indented_exec = indent_code(execute_code, 4)
|
||||
|
||||
# Escape description for Julia string literal
|
||||
escaped_desc = replace(tool_description, "\\" => "\\\\")
|
||||
escaped_desc = replace(escaped_desc, "\"" => "\\\"")
|
||||
|
||||
# Build the complete tool file content
|
||||
parts = String[]
|
||||
push!(parts, "# Auto-generated tool: $tool_name\n")
|
||||
push!(parts, "# Generated by writeTool at $(now())\n\n")
|
||||
if !isempty(validate_section)
|
||||
push!(parts, validate_section)
|
||||
push!(parts, "\n")
|
||||
end
|
||||
if !isempty(prepare_section)
|
||||
push!(parts, prepare_section)
|
||||
push!(parts, "\n")
|
||||
end
|
||||
push!(parts, "\n")
|
||||
push!(parts, "# Execute function\n")
|
||||
push!(parts, "function executeTool(toolCallId::String, args::Dict{String,Any}, signal::Union{Nothing,abortSignal}, onPartialResult::Function)::agentToolResult\n")
|
||||
push!(parts, "$indented_exec\n")
|
||||
push!(parts, "end\n\n")
|
||||
push!(parts, "# Tool definition\n")
|
||||
push!(parts, "function getTool()::agentTool\n")
|
||||
push!(parts, " return agentTool(\n")
|
||||
push!(parts, " name = \"$(tool_name)\",\n")
|
||||
push!(parts, " label = \"$(tool_label)\",\n")
|
||||
push!(parts, " description = \"$(escaped_desc)\",\n")
|
||||
push!(parts, " inputSchema = $schema_literal,\n")
|
||||
push!(parts, " execute = executeTool,\n")
|
||||
if validate_code !== nothing && !isempty(validate_code)
|
||||
push!(parts, " validateRequiredArgs = validateRequiredArgs,\n")
|
||||
else
|
||||
push!(parts, " validateRequiredArgs = nothing,\n")
|
||||
end
|
||||
if prepare_code !== nothing && !isempty(prepare_code)
|
||||
push!(parts, " prepareArguments = prepareArguments,\n")
|
||||
else
|
||||
push!(parts, " prepareArguments = nothing,\n")
|
||||
end
|
||||
push!(parts, " parallelToolExecute = $parallel\n")
|
||||
push!(parts, " )\n")
|
||||
push!(parts, "end\n")
|
||||
|
||||
tool_code = join(parts)
|
||||
|
||||
# Write the file — tool must be included in YiemAgent.jl and registered in register_all_tools()
|
||||
write(filepath, tool_code)
|
||||
|
||||
onPartialResult(Dict("status" => "Done"))
|
||||
|
||||
return agentToolResult(
|
||||
[textContent("Tool '$(tool_name)' written to $filepath. Add include(\"tools/$(tool_name).jl\") to YiemAgent.jl and registerTool(store, $(tool_name)Tool()) to register_all_tools(), then restart the agent.")],
|
||||
Dict{Any,Any}(
|
||||
"file" => filepath,
|
||||
"name" => tool_name,
|
||||
"label" => tool_label,
|
||||
"description" => tool_description,
|
||||
),
|
||||
nothing, false
|
||||
)
|
||||
end,
|
||||
prepareArguments = nothing,
|
||||
validateRequiredArgs = nothing,
|
||||
parallelToolExecute = false
|
||||
)
|
||||
end
|
||||
+11
-13
@@ -23,7 +23,7 @@
|
||||
preparedToolCall, immediateOutcome, executedOutcome, finalizedOutcome,
|
||||
agentToolCallBatch,
|
||||
# Functions (defined elsewhere)
|
||||
runAgent, takeResponse, followUp, stopAgent
|
||||
promptAgent, takeResponse, followUp, stopAgent
|
||||
|
||||
|
||||
using Dates, UUIDs, DataStructures, JSON, NATS, Base.Threads
|
||||
@@ -358,7 +358,6 @@ struct agentContext # Snapshot of the agent's conversa
|
||||
systemPrompt::String # System prompt for the agent
|
||||
messages::Vector{agentMessage} # Conversation messages
|
||||
tools::Union{OrderedDict{String, agentTool}, Nothing} # Available tools keyed by name
|
||||
llmCall::Union{Any, Nothing} # LLM call function (for tools that need it)
|
||||
end
|
||||
|
||||
|
||||
@@ -408,7 +407,7 @@ function agentState(
|
||||
agentState(
|
||||
systemPrompt,
|
||||
model,
|
||||
deepcopy(tools),
|
||||
tools,
|
||||
deepcopy(messages),
|
||||
Vector{String}(),
|
||||
nothing,
|
||||
@@ -443,7 +442,7 @@ end
|
||||
"""
|
||||
Configuration for the agent tool execution loop.
|
||||
|
||||
# Arguments
|
||||
# Fields
|
||||
- `beforeToolCall::Union{Function, Nothing}`: Callback before tool execution
|
||||
- `afterToolCall::Union{Function, Nothing}`: Callback after tool execution
|
||||
- `toolExecution::String`: Execution mode — "sequential" or "parallel"
|
||||
@@ -452,7 +451,6 @@ struct agentLoopConfig
|
||||
beforeToolCall::Union{Function, Nothing}
|
||||
afterToolCall::Union{Function, Nothing}
|
||||
toolExecution::String
|
||||
llmCall::Union{Any, Nothing} # LLM call function (for tools like searchWine)
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -487,13 +485,13 @@ Context passed to the `beforeToolCall` hook.
|
||||
# Arguments
|
||||
- `message::assistantMessageToolCall`: The assistant message containing the tool call
|
||||
- `toolCall::agentToolCall`: The tool call being prepared
|
||||
- `args::Dict{String,Any}`: Validated tool arguments
|
||||
- `args::AbstractDict{String, Any}`: Validated tool arguments
|
||||
- `context::agentContext`: Current conversation context
|
||||
"""
|
||||
struct beforeToolCallContext
|
||||
message::assistantMessageToolCall
|
||||
toolCall::agentToolCall
|
||||
args::Dict{String,Any}
|
||||
args::AbstractDict{String, Any}
|
||||
context::agentContext
|
||||
end
|
||||
|
||||
@@ -508,7 +506,7 @@ Context passed to the `afterToolCall` hook.
|
||||
# Arguments
|
||||
- `message::assistantMessageToolCall`: The assistant message containing the tool call
|
||||
- `toolCall::agentToolCall`: The tool call that was executed
|
||||
- `args::Dict{String,Any}`: Tool arguments
|
||||
- `args::AbstractDict{String, Any}`: Tool arguments
|
||||
- `result::agentToolResult`: The raw tool result
|
||||
- `isError::Bool`: Whether execution resulted in an error
|
||||
- `context::agentContext`: Current conversation context
|
||||
@@ -516,7 +514,7 @@ Context passed to the `afterToolCall` hook.
|
||||
struct afterToolCallContext
|
||||
message::assistantMessageToolCall
|
||||
toolCall::agentToolCall
|
||||
args::Dict{String,Any}
|
||||
args::AbstractDict{String, Any}
|
||||
result::agentToolResult
|
||||
isError::Bool
|
||||
context::agentContext
|
||||
@@ -528,12 +526,12 @@ Event emitted when a tool call execution starts.
|
||||
# Arguments
|
||||
- `toolCallId::String`: ID of the tool call
|
||||
- `toolName::String`: Name of the tool
|
||||
- `arguments::Dict{String,Any}`: Tool arguments
|
||||
- `arguments::AbstractDict{String, Any}`: Tool arguments
|
||||
"""
|
||||
struct toolExecStartEvent
|
||||
toolCallId::String
|
||||
toolName::String
|
||||
arguments::Dict{String,Any}
|
||||
arguments::AbstractDict{String, Any}
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -542,13 +540,13 @@ Event emitted with partial results during tool execution.
|
||||
# Arguments
|
||||
- `toolCallId::String`: ID of the tool call
|
||||
- `toolName::String`: Name of the tool
|
||||
- `arguments::Dict{String,Any}`: Tool arguments
|
||||
- `arguments::AbstractDict{String, Any}`: Tool arguments
|
||||
- `partialResult::Any`: The partial result data
|
||||
"""
|
||||
struct toolExecUpdateEvent
|
||||
toolCallId::String
|
||||
toolName::String
|
||||
arguments::Dict{String,Any}
|
||||
arguments::AbstractDict{String, Any}
|
||||
partialResult::Any
|
||||
end
|
||||
|
||||
|
||||
+33
-44
@@ -2,8 +2,8 @@ module utils
|
||||
|
||||
export clearhistory, availableWineToText, prepareContext, formatMsgForLLM, validateRequiredArgs,
|
||||
validateToolArguments, _userMessageToOpenAI,
|
||||
_assistantMessageToOpenAI, _toolResultMessageToOpenAI, _messageContentToBlocks, _toolsToOpenAI,
|
||||
beforeToolCall, afterToolCall, agentEventSink
|
||||
_assistantMessageToOpenAI, _toolResultMessageToOpenAI, _messageContentToBlocks,
|
||||
_toolsToOpenAI, beforeToolCall, afterToolCall
|
||||
|
||||
using UUIDs, Dates, DataStructures, HTTP, JSON, NATS
|
||||
using GeneralUtils
|
||||
@@ -96,7 +96,7 @@ or pruning and reordering messages before formatting and calling the LLM.
|
||||
messages, and tools to be sent to the LLM
|
||||
|
||||
# Examples
|
||||
```julia
|
||||
```jldoctest
|
||||
# Default: returns an agentContext with deep copies of system prompt, messages, and tools
|
||||
prepareContext(state).messages == deepcopy(state.messages)
|
||||
|
||||
@@ -109,18 +109,18 @@ prepareContext(state).messages == deepcopy(state.messages)
|
||||
# end
|
||||
```
|
||||
"""
|
||||
function prepareContext(state::agentState, agentEventSink, llmCall=nothing)::agentContext
|
||||
|
||||
function prepareContext(state::agentState, eventSink)::agentContext
|
||||
|
||||
#TODO filter tools from state.tools based on user intend in user message and tool description
|
||||
filteredTools = state.tools
|
||||
|
||||
#TODO add filtered tools to the current system prompt / modify systemPrompt here
|
||||
preparedSystemPrompt = state.systemPrompt
|
||||
|
||||
|
||||
#TODO add system prompt, adjust/modify and inject additional context into messages
|
||||
preparedMessages = deepcopy(state.messages) # messages that will be send to LLM
|
||||
|
||||
agentCtx = agentContext(preparedSystemPrompt, preparedMessages, filteredTools, llmCall)
|
||||
agentCtx = agentContext(preparedSystemPrompt, preparedMessages, filteredTools)
|
||||
|
||||
return agentCtx
|
||||
end
|
||||
@@ -146,7 +146,7 @@ LLM message formats for different APIs/providers.
|
||||
an array of OpenAI-format message dicts
|
||||
|
||||
# Examples
|
||||
```julia
|
||||
```jldoctest
|
||||
# Default output:
|
||||
formatMsgForLLm(ctx) == Dict("messages" => [
|
||||
Dict("role" => "system", "content" => [...]),
|
||||
@@ -156,7 +156,7 @@ formatMsgForLLm(ctx) == Dict("messages" => [
|
||||
])
|
||||
```
|
||||
"""
|
||||
function formatMsgForLLM(ctx::agentContext, agentEventSink)::Dict{String, Any}
|
||||
function formatMsgForLLM(ctx::agentContext, eventSink)::Dict{String, Any}
|
||||
|
||||
""" openai message format example
|
||||
msg = Dict(
|
||||
@@ -208,7 +208,7 @@ function formatMsgForLLM(ctx::agentContext, agentEventSink)::Dict{String, Any}
|
||||
openaiReadyMsg = Dict{String, Any}()
|
||||
# openaiReadyMsg["model"] = "gemma-4-E4B-it-UD-Q4_K_XL"
|
||||
messages = Vector{Dict{String, Any}}()
|
||||
agentEventSink("formatMsgForLLM 1")
|
||||
eventSink("formatMsgForLLM 1")
|
||||
# System prompt as system message
|
||||
if !isempty(ctx.systemPrompt)
|
||||
push!(messages, Dict(
|
||||
@@ -216,7 +216,7 @@ function formatMsgForLLM(ctx::agentContext, agentEventSink)::Dict{String, Any}
|
||||
"content" => [Dict("type" => "text", "text" => ctx.systemPrompt)]
|
||||
))
|
||||
end
|
||||
agentEventSink("formatMsgForLLM 2")
|
||||
eventSink("formatMsgForLLM 2")
|
||||
# Conversation messages
|
||||
for msg in ctx.messages
|
||||
if msg isa userMessage
|
||||
@@ -229,10 +229,10 @@ function formatMsgForLLM(ctx::agentContext, agentEventSink)::Dict{String, Any}
|
||||
push!(messages, _toolResultMessageToOpenAI(msg))
|
||||
end
|
||||
end
|
||||
agentEventSink("formatMsgForLLM 3")
|
||||
eventSink("formatMsgForLLM 3")
|
||||
# Convert ctx.tools into OpenAI tools format
|
||||
tools_array = _toolsToOpenAI(ctx.tools, agentEventSink)
|
||||
agentEventSink("formatMsgForLLM 4")
|
||||
tools_array = _toolsToOpenAI(ctx.tools, eventSink)
|
||||
eventSink("formatMsgForLLM 4")
|
||||
openaiReadyMsg["messages"] = messages
|
||||
openaiReadyMsg["temperature"] = 0.7
|
||||
|
||||
@@ -265,7 +265,7 @@ Common use cases:
|
||||
- `nothing` is treated as allow (equivalent to `beforeToolCallResult(false, "N/A")`).
|
||||
|
||||
# Example
|
||||
```julia
|
||||
```jldoctest
|
||||
function beforeToolCall(context::beforeToolCallContext, signal::abortSignal)
|
||||
if context.toolCall.name == "deleteFile"
|
||||
# Block file deletion unless explicitly approved
|
||||
@@ -275,14 +275,10 @@ function beforeToolCall(context::beforeToolCallContext, signal::abortSignal)
|
||||
end
|
||||
```
|
||||
"""
|
||||
function beforeToolCall(context::beforeToolCallContext, signal::abortSignal
|
||||
function beforeToolCall(context::beforeToolCallContext, signal::abortSignal, eventSink
|
||||
)::beforeToolCallResult
|
||||
|
||||
# final context check
|
||||
|
||||
# seek user approval via UI
|
||||
|
||||
# other check
|
||||
eventSink("beforeToolCall: $(context.toolCall.name) args=$(context.args)")
|
||||
|
||||
return beforeToolCallResult(false, "N/A")
|
||||
end
|
||||
@@ -310,22 +306,15 @@ Common use cases:
|
||||
- `agentToolResult(...)` to return a modified result (content, details, usage,
|
||||
terminate flag can all be overridden).
|
||||
|
||||
"""
|
||||
function afterToolCall(context::afterToolCallContext, signal::abortSignal
|
||||
""" #WORKING arrange result from searchWine tool
|
||||
function afterToolCall(context::afterToolCallContext, signal::abortSignal, eventSink
|
||||
)::Union{agentToolResult, Nothing}
|
||||
|
||||
# modify context.result if needed and return agentToolResult
|
||||
eventSink("afterToolCall: $(context.toolCall.name) result=$(context.result) error=$(context.isError)")
|
||||
|
||||
return nothing
|
||||
end
|
||||
|
||||
|
||||
#TODO
|
||||
function agentEventSink(x)
|
||||
|
||||
end
|
||||
|
||||
|
||||
"""
|
||||
Convert a userMessage to OpenAI message format.
|
||||
"""
|
||||
@@ -375,7 +364,7 @@ function _assistantMessageToolCallToOpenAI(msg::assistantMessageToolCall)::Dict{
|
||||
)
|
||||
end
|
||||
|
||||
"""
|
||||
"""
|
||||
Convert an assistantMessage to OpenAI message format.
|
||||
"""
|
||||
function _assistantMessageToOpenAI(msg::assistantMessage)::Dict{String, Any}
|
||||
@@ -432,15 +421,15 @@ Convert an OrderedDict of agentTool definitions into OpenAI function tool format
|
||||
Returns an empty vector when `tools` is `nothing` or empty.
|
||||
|
||||
# Examples
|
||||
```julia
|
||||
```jldoctest
|
||||
_toolsToOpenAI(nothing) # => Dict{String, Any}[]
|
||||
_toolsToOpenAI(tools) # => [Dict("type" => "function", "function" => Dict("name" => "getWeather", ...))]
|
||||
```
|
||||
"""
|
||||
function _toolsToOpenAI(tools::Union{OrderedDict{String, agentTool}, Nothing}, agentEventSink)::Vector{Dict{String, Any}}
|
||||
function _toolsToOpenAI(tools::Union{OrderedDict{String, agentTool}, Nothing}, eventSink)::Vector{Dict{String, Any}}
|
||||
tools_array = Vector{Dict{String, Any}}()
|
||||
agentEventSink("_toolsToOpenAI 1")
|
||||
agentEventSink(string(typeof(tools)))
|
||||
eventSink("_toolsToOpenAI 1")
|
||||
eventSink(string(typeof(tools)))
|
||||
if tools !== nothing
|
||||
for (_, tool) in tools
|
||||
push!(tools_array, Dict(
|
||||
@@ -453,13 +442,13 @@ function _toolsToOpenAI(tools::Union{OrderedDict{String, agentTool}, Nothing}, a
|
||||
))
|
||||
end
|
||||
end
|
||||
agentEventSink("_toolsToOpenAI 2")
|
||||
eventSink("_toolsToOpenAI 2")
|
||||
return tools_array
|
||||
end
|
||||
|
||||
|
||||
"""
|
||||
validateRequiredArgs(args::Dict{String,Any}, inputSchema::Dict{String,Any}) -> Union{Nothing,String}
|
||||
validateRequiredArgs(args::AbstractDict{String, Any}, inputSchema::AbstractDict{String, Any}) -> Union{Nothing,String}
|
||||
|
||||
Validates that all required fields listed in the tool's JSON Schema are present
|
||||
in `args`. Returns `nothing` if validation passes, or a descriptive error string
|
||||
@@ -470,15 +459,15 @@ with a custom validation function that performs additional checks (e.g. type
|
||||
coercion, format validation, cross-field constraints).
|
||||
|
||||
# Arguments
|
||||
- `args::Dict{String,Any}`: The arguments provided by the LLM
|
||||
- `inputSchema::Dict{String,Any}`: The tool's `inputSchema` (JSON Schema format)
|
||||
- `args::AbstractDict{String, Any}`: The arguments provided by the LLM
|
||||
- `inputSchema::AbstractDict{String, Any}`: The tool's `inputSchema` (JSON Schema format)
|
||||
|
||||
# Returns
|
||||
- `nothing` if all required args are present
|
||||
- `String` error message listing missing fields otherwise
|
||||
|
||||
# Examples
|
||||
```julia
|
||||
```jldoctest
|
||||
schema = Dict("required" => ["city"])
|
||||
args = Dict{String,Any}()
|
||||
validateRequiredArgs(args, schema) # => "Missing required arguments: city"
|
||||
@@ -487,7 +476,7 @@ args2 = Dict("city" => "Tokyo")
|
||||
validateRequiredArgs(args2, schema) # => nothing
|
||||
```
|
||||
"""
|
||||
function validateRequiredArgs(args::Dict{String,Any}, inputSchema::Dict{String,Any})::Union{Nothing,String}
|
||||
function validateRequiredArgs(args::AbstractDict{String, Any}, inputSchema::AbstractDict{String, Any})::Union{Nothing,String}
|
||||
required = get(inputSchema, "required", Any[])
|
||||
if isempty(required)
|
||||
return nothing
|
||||
@@ -533,7 +522,7 @@ false `toolExecutionStart` events.
|
||||
and converted to an `immediateOutcome`
|
||||
|
||||
# Examples
|
||||
```julia
|
||||
```jldoctest
|
||||
# With validateRequiredArgs hook set on the tool
|
||||
validateToolArguments(toolWithHook, tc) # => validated args or throws
|
||||
|
||||
@@ -541,7 +530,7 @@ validateToolArguments(toolWithHook, tc) # => validated args or throws
|
||||
validateToolArguments(toolDefault, tc) # => args or throws
|
||||
```
|
||||
"""
|
||||
function validateToolArguments(tool::agentTool, prepared::agentToolCall)::Dict{String,Any}
|
||||
function validateToolArguments(tool::agentTool, prepared::agentToolCall)::AbstractDict{String, Any}
|
||||
# Use default (2-arg: args + schema) or tool-specific hook (1-arg: args only)
|
||||
if isnothing(tool.validateRequiredArgs)
|
||||
result = validateRequiredArgs(prepared.arguments, tool.inputSchema)
|
||||
|
||||
@@ -1,367 +0,0 @@
|
||||
using Test
|
||||
using Dates
|
||||
using YiemAgent
|
||||
using YiemAgent.toolRegistry
|
||||
using YiemAgent.type
|
||||
using YiemAgent.agentCore
|
||||
|
||||
@testset "register_all_tools with toolStore" begin
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# 1. register_all_tools registers all static tools + listTools #
|
||||
# ------------------------------------------------------------------ #
|
||||
store = toolStore(name="test1")
|
||||
loaded = register_all_tools(store)
|
||||
@test !isempty(loaded)
|
||||
@test length(loaded) == 4 # getWeather + getTime + writeTool + listTools
|
||||
|
||||
names = [k for k in keys(loaded)]
|
||||
@test "getTime" in names
|
||||
@test "getWeather" in names
|
||||
@test "writeTool" in names
|
||||
@test "listTools" in names
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# 2. register_all_tools returns tools in registration order #
|
||||
# ------------------------------------------------------------------ #
|
||||
@test collect(keys(loaded))[1] == "getWeather"
|
||||
@test collect(keys(loaded))[2] == "getTime"
|
||||
@test collect(keys(loaded))[3] == "writeTool"
|
||||
@test collect(keys(loaded))[4] == "listTools"
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# 3. Verify loaded tool fields are correct #
|
||||
# ------------------------------------------------------------------ #
|
||||
# getTime
|
||||
time_tool = loaded["getTime"]
|
||||
@test time_tool.name == "getTime"
|
||||
@test time_tool.label == "Time Lookup"
|
||||
@test time_tool.validateRequiredArgs !== nothing
|
||||
@test time_tool.parallelToolExecute == false
|
||||
@test time_tool.inputSchema["required"] == Any[]
|
||||
|
||||
# getWeather
|
||||
weather = loaded["getWeather"]
|
||||
@test weather.name == "getWeather"
|
||||
@test weather.label == "Weather Lookup"
|
||||
@test weather.execute !== nothing
|
||||
@test weather.parallelToolExecute == false
|
||||
@test weather.inputSchema["required"] == ["city"]
|
||||
|
||||
# writeTool
|
||||
wt = loaded["writeTool"]
|
||||
@test wt.name == "writeTool"
|
||||
@test wt.label == "Create Tool"
|
||||
@test wt.execute !== nothing
|
||||
@test "name" in wt.inputSchema["required"]
|
||||
@test "executeCode" in wt.inputSchema["required"]
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# 4. Tool execution returns valid results #
|
||||
# ------------------------------------------------------------------ #
|
||||
sig = nothing
|
||||
op = x -> x # no-op partial result callback
|
||||
|
||||
# execute getTime
|
||||
result_t = time_tool.execute("call-1", Dict{String,Any}("city" => "Tokyo"), sig, op)
|
||||
@test result_t isa agentToolResult
|
||||
@test result_t.content[1] isa textContent
|
||||
@test occursin("Tokyo", result_t.content[1].text)
|
||||
|
||||
# execute getTime with timezone
|
||||
result_tz = time_tool.execute("call-2", Dict{String,Any}("timezone" => "America/New_York"), sig, op)
|
||||
@test result_tz isa agentToolResult
|
||||
@test occursin("America/New_York", result_tz.content[1].text)
|
||||
|
||||
# execute getWeather
|
||||
result_w = weather.execute("call-3", Dict{String,Any}("city" => "Bangkok"), sig, op)
|
||||
@test result_w isa agentToolResult
|
||||
@test result_w.content[1] isa textContent
|
||||
@test occursin("Bangkok", result_w.content[1].text)
|
||||
|
||||
# execute getWeather with units
|
||||
result_w2 = weather.execute("call-4", Dict{String,Any}("city" => "London", "units" => "fahrenheit"), sig, op)
|
||||
@test occursin("72\u00b0F", result_w2.content[1].text)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# 5. getTools / registerTool / clearTools (per-store isolation) #
|
||||
# ------------------------------------------------------------------ #
|
||||
store3 = toolStore(name="test3")
|
||||
registry_tools = getTools(store3)
|
||||
@test isempty(registry_tools)
|
||||
|
||||
# Register tools manually
|
||||
registerTool(store3, loaded["getTime"])
|
||||
registerTool(store3, loaded["getWeather"])
|
||||
registerTool(store3, loaded["writeTool"])
|
||||
|
||||
reg = getTools(store3)
|
||||
@test !isempty(reg)
|
||||
@test "getTime" in keys(reg)
|
||||
@test "getWeather" in keys(reg)
|
||||
@test "writeTool" in keys(reg)
|
||||
@test collect(keys(reg))[1] == "getTime"
|
||||
@test collect(keys(reg))[2] == "getWeather"
|
||||
@test collect(keys(reg))[3] == "writeTool"
|
||||
|
||||
clearTools(store3)
|
||||
@test isempty(getTools(store3))
|
||||
|
||||
test_tool = agentTool(
|
||||
name = "manualTool",
|
||||
label = "Manual Tool",
|
||||
description = "Registered manually",
|
||||
inputSchema = Dict{String,Any}("type" => "object", "properties" => Dict{String,Any}(), "required" => Any[]),
|
||||
execute = (toolCallId, args, signal, onPartialResult) ->
|
||||
agentToolResult([textContent("manual")], Dict{Any,Any}(), nothing, false),
|
||||
prepareArguments = nothing,
|
||||
validateRequiredArgs = nothing,
|
||||
parallelToolExecute = true
|
||||
)
|
||||
registerTool(store3, test_tool)
|
||||
reg = getTools(store3)
|
||||
@test haskey(reg, "manualTool")
|
||||
@test length(reg) == 1
|
||||
@test reg["manualTool"].parallelToolExecute == true
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# 6. getTools returns direct reference (mutations affect registry) #
|
||||
# ------------------------------------------------------------------ #
|
||||
copy1 = getTools(store3)
|
||||
copy2 = getTools(store3)
|
||||
@test copy1 === copy2 # same reference, not a deep copy
|
||||
empty!(copy1)
|
||||
@test isempty(getTools(store3)) # mutation propagates
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# 7. Per-store isolation — two stores don't share tools #
|
||||
# ------------------------------------------------------------------ #
|
||||
storeA = toolStore(name="isolationA")
|
||||
storeB = toolStore(name="isolationB")
|
||||
|
||||
registerTool(storeA, loaded["getTime"])
|
||||
registerTool(storeB, loaded["getWeather"])
|
||||
|
||||
regA = getTools(storeA)
|
||||
regB = getTools(storeB)
|
||||
|
||||
@test "getTime" in keys(regA)
|
||||
@test "getWeather" ∉ keys(regA)
|
||||
@test "getWeather" in keys(regB)
|
||||
@test "getTime" ∉ keys(regB)
|
||||
|
||||
clearTools(storeA)
|
||||
@test isempty(getTools(storeA))
|
||||
@test !isempty(getTools(storeB)) # storeB unaffected
|
||||
end
|
||||
|
||||
@testset "listTool" begin
|
||||
store = toolStore(name="test_list")
|
||||
register_all_tools(store) # auto-registers getWeather, getTime, writeTool + listTools
|
||||
|
||||
# register_all_tools auto-registers listTool
|
||||
@test "listTools" in keys(store.tools)
|
||||
|
||||
# listTool returns an agentTool, not a string or array
|
||||
list_t = listTool(store)
|
||||
@test list_t isa agentTool
|
||||
@test list_t.name == "listTools"
|
||||
@test list_t.label == "List Tools"
|
||||
@test isempty(list_t.inputSchema["required"])
|
||||
|
||||
# Verify all tools appear (3 loaded + listTools = 4)
|
||||
result = list_t.execute("call-1", Dict{String,Any}(), nothing, x -> x)
|
||||
@test result isa agentToolResult
|
||||
@test result.content[1] isa textContent
|
||||
@test occursin("listTools", result.content[1].text)
|
||||
@test occursin("getWeather", result.content[1].text)
|
||||
@test occursin("getTime", result.content[1].text)
|
||||
@test occursin("writeTool", result.content[1].text)
|
||||
@test result.details["count"] == 4
|
||||
|
||||
# Each listTool call creates an independent closure
|
||||
storeB = toolStore(name="test_listB")
|
||||
registerTool(storeB, store.tools["getWeather"])
|
||||
list_tB = listTool(storeB)
|
||||
|
||||
resultA = list_t.execute("call-3", Dict{String,Any}(), nothing, x -> x)
|
||||
resultB = list_tB.execute("call-4", Dict{String,Any}(), nothing, x -> x)
|
||||
|
||||
@test occursin("getWeather", resultA.content[1].text)
|
||||
@test occursin("getWeather", resultB.content[1].text)
|
||||
@test occursin("getTime", resultA.content[1].text)
|
||||
@test occursin("getTime", resultB.content[1].text) == false # storeB only has getWeather
|
||||
end
|
||||
|
||||
@testset "executePreparedToolCall with static tools" begin
|
||||
# Tests executePreparedToolCall with statically loaded tools.
|
||||
# The world-age issue is resolved because tool.execute comes from
|
||||
# a statically included module, not a dynamically created one.
|
||||
|
||||
store = toolStore(name="test_static")
|
||||
register_all_tools(store)
|
||||
|
||||
weather_tool = store.tools["getWeather"]
|
||||
|
||||
# Create a preparedToolCall that mimics what prepareToolCall() returns
|
||||
tool_call = agentToolCall(
|
||||
"function", "call-static-1", "getWeather",
|
||||
Dict{String,Any}("city" => "San Francisco")
|
||||
)
|
||||
prep = preparedToolCall(
|
||||
weather_tool, tool_call, Dict{String,Any}("city" => "San Francisco")
|
||||
)
|
||||
sig = abortSignal(false)
|
||||
|
||||
# This call goes through: executePreparedToolCall -> prep.tool.execute(...)
|
||||
result = executePreparedToolCall(
|
||||
prep, sig, x -> nothing
|
||||
)
|
||||
|
||||
@test result isa executedOutcome
|
||||
@test result.isError == false
|
||||
@test result.result.content[1] isa textContent
|
||||
@test occursin("San Francisco", result.result.content[1].text)
|
||||
end
|
||||
|
||||
@testset "executePreparedToolCall with validation (static tools)" begin
|
||||
# Tests executePreparedToolCall with a tool that has custom validation hooks.
|
||||
# This exercises the full tool execution path including validation.
|
||||
|
||||
store = toolStore(name="test_static_validate")
|
||||
register_all_tools(store)
|
||||
|
||||
time_tool = store.tools["getTime"]
|
||||
|
||||
tool_call = agentToolCall(
|
||||
"function", "call-static-2", "getTime",
|
||||
Dict{String,Any}("timezone" => "America/New_York")
|
||||
)
|
||||
prep = preparedToolCall(
|
||||
time_tool, tool_call, Dict{String,Any}("timezone" => "America/New_York")
|
||||
)
|
||||
sig = abortSignal(false)
|
||||
|
||||
result = executePreparedToolCall(
|
||||
prep, sig, x -> nothing
|
||||
)
|
||||
|
||||
@test result isa executedOutcome
|
||||
@test result.isError == false
|
||||
@test result.result.content[1] isa textContent
|
||||
@test occursin("America/New_York", result.result.content[1].text)
|
||||
end
|
||||
|
||||
@testset "executeToolCallsSequential with static tools (full pipeline)" begin
|
||||
# Tests the full tool execution pipeline: executeToolCallsSequential
|
||||
# which calls prepareToolCall -> executePreparedToolCall -> finalizeExecutedToolCall
|
||||
# with statically loaded tools.
|
||||
|
||||
store = toolStore(name="test_full_pipeline")
|
||||
register_all_tools(store)
|
||||
|
||||
# Build agentContext from the store's tools
|
||||
tools = getTools(store)
|
||||
ctx = agentContext(
|
||||
"test system prompt",
|
||||
agentMessage[],
|
||||
tools
|
||||
)
|
||||
|
||||
# Create an assistant message containing tool calls
|
||||
assistant_msg = assistantMessage(
|
||||
role="assistant",
|
||||
content=Vector{messageContent}(),
|
||||
api="openai",
|
||||
provider="test",
|
||||
model="test-model",
|
||||
usage=llmUsage(0, 0),
|
||||
stopReason="tool_calls",
|
||||
errorMessage=nothing,
|
||||
timestamp=now()
|
||||
)
|
||||
|
||||
# Create tool calls for multiple statically loaded tools
|
||||
tool_calls = [
|
||||
agentToolCall(
|
||||
"function", "call-seq-1", "getWeather",
|
||||
Dict{String,Any}("city" => "Tokyo")
|
||||
),
|
||||
agentToolCall(
|
||||
"function", "call-seq-2", "getTime",
|
||||
Dict{String,Any}("timezone" => "Europe/London")
|
||||
),
|
||||
]
|
||||
|
||||
config = agentLoopConfig(
|
||||
nothing, nothing, "sequential"
|
||||
)
|
||||
sig = abortSignal(false)
|
||||
|
||||
# Execute the full pipeline
|
||||
batch = executeToolCallsSequential(
|
||||
ctx, assistant_msg, tool_calls, config, sig, x -> nothing
|
||||
)
|
||||
|
||||
@test batch.messages isa Vector{toolResultMessage}
|
||||
@test length(batch.messages) == 2
|
||||
@test batch.messages[1].toolName == "getWeather"
|
||||
@test batch.messages[1].isError == false
|
||||
@test occursin("Tokyo", batch.messages[1].content[1].text)
|
||||
@test batch.messages[2].toolName == "getTime"
|
||||
@test batch.messages[2].isError == false
|
||||
@test occursin("Europe/London", batch.messages[2].content[1].text)
|
||||
end
|
||||
|
||||
@testset "executeToolCallsParallel with static tools (full pipeline)" begin
|
||||
# Same as above but tests parallel execution path.
|
||||
|
||||
store = toolStore(name="test_parallel")
|
||||
register_all_tools(store)
|
||||
|
||||
tools = getTools(store)
|
||||
ctx = agentContext(
|
||||
"test system prompt",
|
||||
agentMessage[],
|
||||
tools
|
||||
)
|
||||
|
||||
assistant_msg = assistantMessage(
|
||||
role="assistant",
|
||||
content=Vector{messageContent}(),
|
||||
api="openai",
|
||||
provider="test",
|
||||
model="test-model",
|
||||
usage=llmUsage(0, 0),
|
||||
stopReason="tool_calls",
|
||||
errorMessage=nothing,
|
||||
timestamp=now()
|
||||
)
|
||||
|
||||
tool_calls = [
|
||||
agentToolCall(
|
||||
"function", "call-par-1", "getWeather",
|
||||
Dict{String,Any}("city" => "Paris")
|
||||
),
|
||||
agentToolCall(
|
||||
"function", "call-par-2", "getTime",
|
||||
Dict{String,Any}("city" => "Sydney")
|
||||
),
|
||||
]
|
||||
|
||||
config = agentLoopConfig(
|
||||
nothing, nothing, "parallel"
|
||||
)
|
||||
sig = abortSignal(false)
|
||||
|
||||
batch = executeToolCallsParallel(
|
||||
ctx, assistant_msg, tool_calls, config, sig, x -> nothing
|
||||
)
|
||||
|
||||
@test batch.messages isa Vector{toolResultMessage}
|
||||
@test length(batch.messages) == 2
|
||||
@test batch.messages[1].toolName == "getWeather"
|
||||
@test batch.messages[1].isError == false
|
||||
@test batch.messages[2].toolName == "getTime"
|
||||
@test batch.messages[2].isError == false
|
||||
end
|
||||
+5
-5
@@ -32,7 +32,7 @@ catch e
|
||||
println(io)
|
||||
end
|
||||
|
||||
agentEventSink(err_msg)
|
||||
eventSink(err_msg)
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -66,13 +66,13 @@ end
|
||||
|
||||
|
||||
|
||||
struct agentEventSink
|
||||
struct eventSink
|
||||
natsConn::NATS.Connection
|
||||
topic::String
|
||||
senderID::String
|
||||
end
|
||||
|
||||
function (aes::agentEventSink)(msg::String)
|
||||
function (aes::eventSink)(msg::String)
|
||||
NATS.publish(aes.natsConn, aes.topic, msg)
|
||||
end
|
||||
|
||||
@@ -88,11 +88,11 @@ text2text_llm = text2textInstructLLM(agent_conn,
|
||||
"sender",
|
||||
config["externalservice"]["fileserver"]["url"])
|
||||
|
||||
debugNats = agentEventSink(agent_conn, "sommanion.debug", "sender")
|
||||
debugNats = eventSink(agent_conn, "sommanion.debug", "sender")
|
||||
|
||||
agent = YiemAgent.yiemAgent(
|
||||
text2text_llm;
|
||||
agentEventSink=debugNats
|
||||
eventSink=debugNats
|
||||
)
|
||||
|
||||
msg = Dict(
|
||||
|
||||
Reference in New Issue
Block a user