This commit is contained in:
2026-07-11 21:45:49 +07:00
parent 8bd4986be2
commit 688a8c4df2
8 changed files with 682 additions and 254 deletions
+1 -1
View File
@@ -986,7 +986,7 @@ version = "1.6.1"
deps = ["CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "Serialization", "URIs", "UUIDs"] deps = ["CSV", "DataFrames", "DataStructures", "Dates", "GeneralUtils", "HTTP", "JSON", "LLMMCTS", "LibPQ", "NATS", "PrettyPrinting", "Random", "Revise", "Serialization", "URIs", "UUIDs"]
path = "." path = "."
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2" uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
version = "0.4.2" version = "0.5.0"
[[deps.Zlib_jll]] [[deps.Zlib_jll]]
deps = ["Libdl"] deps = ["Libdl"]
+1 -1
View File
@@ -1,6 +1,6 @@
name = "YiemAgent" name = "YiemAgent"
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2" uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
version = "0.4.3" version = "0.5.0"
authors = ["narawat lamaiin <narawat@outlook.com>"] authors = ["narawat lamaiin <narawat@outlook.com>"]
[deps] [deps]
+35 -39
View File
@@ -108,9 +108,6 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
context = context =
""" """
<internal_context_for_assistant> <internal_context_for_assistant>
<assistant_action_history>
$(GeneralUtils.dict_to_string_html(a.memory["shortmem"]))
</assistant_action_history>
</internal_context_for_assistant> </internal_context_for_assistant>
""" """
@@ -384,7 +381,7 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj
loopcount += 1 loopcount += 1
if loopcount > max_think_loop if loopcount > max_think_loop
@info "YiemAgent conversation() 2-1 think count $loopcount " @__LINE__ @info "YiemAgent conversation() 2-1 think count $loopcount " @__LINE__
r = generatechat(a) r = generatechat!(a)
@info "YiemAgent conversation() 2-2 think count $loopcount " @__LINE__ @info "YiemAgent conversation() 2-2 think count $loopcount " @__LINE__
return r return r
end end
@@ -399,6 +396,22 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj
) )
addNewMessage(a, "assistant", assistant_response; maximumMsg=maximumMsg) addNewMessage(a, "assistant", assistant_response; maximumMsg=maximumMsg)
return thoughtdict["action_input"] return thoughtdict["action_input"]
else
action_name = thoughtdict["action_name"]
action_input = thoughtdict["action_input"]
action_call = Dict{String, Any}(
"role" => "action_call",
"content" => [Dict("type" => "text", "text" => "{action_name: $action_name, action_input: $action_input}"),]
)
addNewMessage(a, "action_call", action_call; maximumMsg=maximumMsg)
action_result = thoughtdict["action_result"]
actionresult = Dict{String, Any}(
"role" => "action_result",
"content" => [Dict("type" => "text", "text" => "$action_result"),]
)
addNewMessage(a, "actionresult", actionresult; maximumMsg=maximumMsg)
end end
end end
end end
@@ -425,7 +438,7 @@ function think(a::T)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict,
result_raw = nothing result_raw = nothing
if thoughtdict["action_name"] ["CHAT_BOX"] if thoughtdict["action_name"] ["CHAT_BOX"]
@info "YiemAgent think() 2 " @__LINE__ @info "YiemAgent think() 2 " @__LINE__
thoughtdict, result_raw = chatbox!(a, thoughtdict) thoughtdict, result_raw = generatechat!(a)
elseif thoughtdict["action_name"] == "END_CONVER_GUIDELINE" elseif thoughtdict["action_name"] == "END_CONVER_GUIDELINE"
@info "YiemAgent think() 3 " @__LINE__ @info "YiemAgent think() 3 " @__LINE__
@@ -438,21 +451,21 @@ function think(a::T)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict,
elseif thoughtdict["action_name"] == "CHECK_WINE" elseif thoughtdict["action_name"] == "CHECK_WINE"
@info "YiemAgent think() 5 " @__LINE__ @info "YiemAgent think() 5 " @__LINE__
thoughtdict, result_raw = checkwine!(a, thoughtdict) thoughtdict, result_raw = checkwine!(a, thoughtdict; useSQLLLM=false)
else else
@info "YiemAgent think() 6 " @__LINE__ @info "YiemAgent think() 6 " @__LINE__
error("condition is not defined ", @__FILE__, ":", @__LINE__, " $(Dates.now())") error("condition is not defined ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
end end
max_ind = # max_ind =
if length(a.memory["shortmem"]) == 0 # if length(a.memory["shortmem"]) == 0
0 # 0
else # else
k = keys(a.memory["shortmem"]) # k = keys(a.memory["shortmem"])
maximum(parse.(Int, k)) # maximum(parse.(Int, k))
end # end
a.memory["shortmem"]["$(max_ind + 1)"] = thoughtdict # a.memory["shortmem"]["$(max_ind + 1)"] = thoughtdict
@info "YiemAgent think() 7 " @__LINE__ @info "YiemAgent think() 7 " @__LINE__
pprintln(thoughtdict) pprintln(thoughtdict)
@@ -530,8 +543,8 @@ end
#PENDING #PENDING
function generatechat(a::T; recentevents::Integer=20, maxattempt=10 function generatechat!(a::T; maxattempt::Integer=10
)::String where {T<:agent} )::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
# lessonDict = copy(JSON.parsefile("lesson.json")) # lessonDict = copy(JSON.parsefile("lesson.json"))
@@ -605,9 +618,9 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
- Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store. - Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store.
# you should then respond to the user with interleaving plan, action_name, action_input # you should then respond to the user with interleaving plan, action_name, action_input
1) **plan**, Based on the current situation, state a complete action plan to complete the task and rationale. Be specific. 1) "plan", Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
2) **action_name**, (Typically corresponds to the execution of the first step in your plan). Must be "CHAT_BOX 2) "action_name", Must be "CHAT_BOX
3) **action_input**, Dialogue you want to chat with the user according to your plan. 3) "action_input", Dialogue you want to chat with the user according to your plan.
After the action is executed you gets "action_result". It is the output from the action you selected. After the action is executed you gets "action_result". It is the output from the action you selected.
# you should only respond in JSON format as described below # you should only respond in JSON format as described below
@@ -623,27 +636,11 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
] ]
) )
chathistory = deepcopy(a.chathistory[2:end]) chathistory = deepcopy(a.chathistory[2:end]) # use deep copy because I want to replace system msg
pushfirst!(chathistory, system_msg) pushfirst!(chathistory, system_msg)
requiredKeys = ["plan", "action_name", "action_input"] requiredKeys = ["plan", "action_name", "action_input"]
context =
"""
<internal_context_for_assistant>
<assistant_action_history>
$(GeneralUtils.dict_to_string_html(a.memory["shortmem"]))
</assistant_action_history>
</internal_context_for_assistant>
"""
# add context to text of the latest message (in the front).
# use for loop because in openai format, each msg may contain both text and image.
for d in chathistory[end]["content"]
if d["type"] == "text"
d["text"] = context * d["text"]
break
end
end
errornote = "N/A" errornote = "N/A"
response = nothing # placeholder for show when error msg show up response = nothing # placeholder for show when error msg show up
@@ -654,7 +651,7 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
msg = Dict( msg = Dict(
"model" => "gemma-4-E4B-it-UD-Q4_K_XL", "model" => "gemma-4-E4B-it-UD-Q4_K_XL",
"messages" => a.chathistory, "messages" => chathistory,
"temperature" => 0.7 "temperature" => 0.7
) )
@@ -665,7 +662,6 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to
response = strip(response) response = strip(response)
@show response
responsedict = nothing responsedict = nothing
if occursin(requiredKeys[2], response) if occursin(requiredKeys[2], response)
@@ -708,7 +704,7 @@ function generatechat(a::T; recentevents::Integer=20, maxattempt=10
# println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())") # println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# pprintln(responsedict) # pprintln(responsedict)
return responsedict["action_input"] return (thoughtdict=responsedict, result_raw=responsedict["action_input"])
end end
error("YiemAgent generatechat() failed to generate a thought ", response) error("YiemAgent generatechat() failed to generate a thought ", response)
end end
+333 -10
View File
@@ -282,7 +282,7 @@ julia> result = checkinventory(agent, input)
"{"wine 1": {\"Winery\": \"Pichon Baron\", \"wine name\": \"Pauillac (Grand Cru Classé)\", \"grape variety\": \"Cabernet Sauvignon\", \"year\": 2010, \"price\": \"125 USD\", \"stock ID\": \"ar-17\"}, }" "{"wine 1": {\"Winery\": \"Pichon Baron\", \"wine name\": \"Pauillac (Grand Cru Classé)\", \"grape variety\": \"Cabernet Sauvignon\", \"year\": 2010, \"price\": \"125 USD\", \"stock ID\": \"ar-17\"}, }"
``` ```
""" """
function checkwine!(a::T, thoughtdict::AbstractDict function checkwine!(a::T, thoughtdict::AbstractDict; useSQLLLM::Bool=false
)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent} )::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
println("\ncheckinventory order: $(thoughtdict["action_input"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())") println("\ncheckinventory order: $(thoughtdict["action_input"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
@@ -293,19 +293,342 @@ function checkwine!(a::T, thoughtdict::AbstractDict
_inventoryquery = "$wineattributes_1, $wineattributes_2" _inventoryquery = "$wineattributes_1, $wineattributes_2"
inventoryquery = "Retrieves $retrieve_attributes of wines that match the following criteria - {$_inventoryquery}" inventoryquery = "Retrieves $retrieve_attributes of wines that match the following criteria - {$_inventoryquery}"
println("\ncheckinventory input: $inventoryquery ", @__FILE__, ":", @__LINE__, " $(Dates.now())") println("\ncheckinventory input: $inventoryquery ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# add suppport for similarSQLVectorDB
textresult, result_raw = SQLLLM.query( if useSQLLLM
inventoryquery, # add suppport for similarSQLVectorDB
a.context.executeSQL, textresult, result_raw = SQLLLM.query(
a.context.text2textInstructLLM; inventoryquery,
insertSQLVectorDB=a.context.insertSQLVectorDB, a.context.executeSQL,
similarSQLVectorDB=a.context.similarSQLVectorDB, a.context.text2textInstructLLM;
llmFormatName="qwen3") insertSQLVectorDB=a.context.insertSQLVectorDB,
thoughtdict["action_result"] = textresult similarSQLVectorDB=a.context.similarSQLVectorDB,
llmFormatName="qwen3")
thoughtdict["action_result"] = textresult
else
# direct query with possible sql instead of SQLLLM.
sql = generatesql(a, inventoryquery)
textresult, result_raw, _, _ = SQLexecution(a.context.executeSQL, sql)
thoughtdict["action_result"] = textresult
end
return (thoughtdict=thoughtdict, result_raw=result_raw) return (thoughtdict=thoughtdict, result_raw=result_raw)
end end
function generatesql(a::T, searchterm::String,
; maxattempt=10
)::String where {T<:agent}
systemmsg =
"""
# database_search_guidelines
- Keep SQL queries focused only on the provided information.
- Do not create any table in the database
- A junction table can be used to link tables together. Another use case is for filtering data.
- If you can't find a single table that can be used to answer the user's search term, try joining multiple tables to see if you can obtain the answer.
- Text information in the database usually stored in lower case. If your search returns empty, try using lower case to search.
- If there is no search result from the database, remove the restrictive criteria until a search result is available, and proceed from there.
# situation
At each round of conversation, you will be given the following:
- user search term
# objective
Consult the database_search_guidelines. Then find the data from a database to satisfy the user's search term.
# your responsibility includes
Fulfill the objective.
# you should then respond to the user with interleaving plan, action_name, action_input
1) "plan, Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
2) "action_name, Must be "RUNSQL"
3) "action_input, The input to the action you are about to perform according to your plan.
After the action is executed you gets "action_result". It is the output from the action you selected.
# you should only respond in JSON format as described below
"plan": "...",
"action_name": "...",
"action_input": "..."
# available_actions
"RUNSQL", which you can use to execute SQL against the database.
The input must be a single SQL query to be executed against the database.
For more effective text search, it's necessary to use case-insensitivity and the ILIKE operator.
Do not wrap the SQL as it will be executed against the database directly and SQL must be ended with ';'.
"""
table_schema =
"""
create table customer (
customer_id uuid primary key default gen_random_uuid (),
customer_firstname varchar(128),
customer_lastname varchar(128),
customer_displayname varchar(128) not null,
customer_username varchar(128),
customer_password varchar(128),
customer_gender varchar(128),
country varchar(128),
telephone varchar(128),
email varchar(128) not null,
customer_birthdate varchar(128),
note text,
other_attributes jsonb,
created_time timestamptz default current_timestamp,
updated_time timestamptz default current_timestamp,
description text
);
create table retailer (
retailer_id uuid primary key default gen_random_uuid (),
retailer_name varchar(128) not null,
retailer_username varchar(128) not null,
retailer_password varchar(128) not null,
retailer_address text not null,
country varchar(128) not null,
contact_person varchar(128) not null,
telephone varchar(128) not null,
email varchar(128) not null,
note text,
other_attributes jsonb,
created_time timestamptz default current_timestamp,
updated_time timestamptz default current_timestamp,
description text
);
create table food (
food_id uuid primary key default gen_random_uuid (),
food_name varchar(128) not null,
country varchar(128),
spiciness integer,
sweetness integer,
sourness integer,
savoriness integer,
bitterness integer,
serving_temperature integer,
image_url jsonb,
note text,
other_attributes jsonb,
created_time timestamptz default current_timestamp,
updated_time timestamptz default current_timestamp,
description text
);
create table wine (
wine_id uuid primary key default gen_random_uuid (),
seo_name varchar(128) not null,
wine_name varchar(128) not null,
winery varchar(128) not null,
vintage integer not null,
region varchar(128) not null,
country varchar(128) not null,
wine_type varchar(128) not null,
grape varchar(128) not null,
serving_temperature varchar(128) not null,
intensity integer,
sweetness integer,
tannin integer,
acidity integer,
fizziness integer,
tasting_notes text,
image_url jsonb,
manufacturer_sku text,
note text,
other_attributes jsonb,
created_time timestamptz default current_timestamp,
updated_time timestamptz default current_timestamp,
description text
);
create table wine_food (
wine_id uuid references wine(wine_id),
food_id uuid references food(food_id),
constraint wine_food_id primary key (wine_id, food_id),
created_time timestamptz default current_timestamp,
updated_time timestamptz default current_timestamp
);
CREATE TABLE retailer_wine (
retailer_id uuid references retailer(retailer_id),
wine_id uuid references wine(wine_id),
constraint retailer_wine_id primary key (retailer_id, wine_id),
price NUMERIC(10, 2),
currency varchar(3) not null,
created_time timestamptz default current_timestamp,
updated_time timestamptz default current_timestamp
);
CREATE TABLE retailer_food (
retailer_id uuid references retailer(retailer_id),
food_id uuid references food(food_id),
constraint retailer_food_id primary key (retailer_id, food_id),
price NUMERIC(10, 2),
currency varchar(3) not null,
created_time timestamptz default current_timestamp,
updated_time timestamptz default current_timestamp
);
"""
requiredKeys = ["plan", "action_name", "action_input"]
errornote = ""
# provide similar sql only for the first attempt
sql, _ = a.context.similarSQLVectorDB(searchterm)
similarSQL_ = sql !== nothing ? sql : "None"
context =
"""
<internal_context_for_assistant>
<database_table_schema>
$table_schema
</database_table_schema>
<possible SQL for user's search term>
$similarSQL_
</possible SQL for user's search term>
<error_note>
$errornote
<error_note>
</internal_context_for_assistant>
"""
input = context * searchterm
msg = Dict(
"model" => "gemma-4-E4B-it-UD-Q4_K_XL",
"messages" => [
Dict(
"role" => "system",
"content" => [
Dict("type" => "text", "text" => systemmsg),
]
),
Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => input),
]
),
],
"temperature" => 0.7
)
for attempt in 1:maxattempt
response = a.context.text2textInstructLLM("random_id", msg)
response = GeneralUtils.clean_json_response(response)
think, response = GeneralUtils.extractthink(response)
responsedict = nothing
try
_responsedict = JSON.parse(response)
responsedict = GeneralUtils.dictify(_responsedict, keytype=String, sort_order=requiredKeys)
catch
println("\nERROR decisionMaker() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
end
# check whether all answer's key points are in responsedict
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
if !ispass
errornote = errormsg
println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)> $responsedict ", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
continue
end
# remove backticks Error occurred: MethodError: no method matching occursin(::String, ::Vector{String})
if occursin("```", responsedict["action_input"])
sql = GeneralUtils.extract_triple_backtick_text(responsedict["action_input"])[1]
if sql[1:4] == "sql\n"
sql = sql[5:end]
end
sql = split(sql, ';') # some time there are comments in the sql
sql = sql[1] * ';'
responsedict["action_input"] = sql
end
toollist = ["RUNSQL"]
if responsedict["action_name"] toollist
errornote = "Your previous attempt has action_name that is not in the tool list"
println("\nERROR SQLLLM decisionMaker(). Attempt $attempt/$maxattempt. $errornote --(not qualify response)--> $(responsedict["action_name"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
end
for i in toollist
if occursin(i, responsedict["action_input"])
errornote = "Your previous attempt has action_name in action_input which is not allowed"
println("\nERROR SQLLLM decisionMaker(). Attempt $attempt/$maxattempt. $errornote --(not qualify response)--> $(responsedict["action_input"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
end
end
# println("\nSQLLLM decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# pprintln(responsedict)
# println("---")
return responsedict["action_input"]
end
error("SQLLLM DecisionMaker() failed to generate a thought \n", response)
end
function SQLexecution(executeSQL::Function, sql::T
)::NamedTuple where {T<:AbstractString}
try
# add LIMIT to the SQL to prevent loading large data
sql = strip(sql)
# remove DISTINCT keyword because it is incompatible with RANDOM()
sql = replace(sql, "DISTINCT" => "")
if sql[end] == ';'
if !occursin("LIMIT", sql)
sql = sql[1:end-1] * " ORDER BY RANDOM() LIMIT 2;"
end
else
sql = sql * ";"
end
result = executeSQL(sql)
df = DataFrame(result)
tablesize = size(df)
row, column = tablesize
if row == 0
return (result_str="No records found.", result_raw=df, success=true, errormsg=nothing)
elseif column > 30
return (result_str="There are more than 30 columns. Please be more specific.", result_raw=df, success=true, errormsg=nothing)
else
df1 =
if row > 2
# ramdom row to pick
df[sample(1:nrow(df), 2, replace=false), :] # random select 2 rows from df
else
df
end
result = GeneralUtils.dfToString(df1)
# println("\n~~~ SQLexecution() result: ", @__FILE__, " ", @__LINE__)
# println(sql)
# println(df1)
# println("\n")
return (result_str=result, result_raw=df1, success=true, errormsg=nothing)
end
catch e
io = IOBuffer()
showerror(io, e)
errorMsg = String(take!(io))
st = sprint((io, v) -> show(io, "text/plain", v), stacktrace(catch_backtrace()))
println(errorMsg)
return (result_str=nothing, result_raw=nothing, success=false, errormsg=errorMsg)
end
end
""" """
# Arguments # Arguments
-1
View File
@@ -285,7 +285,6 @@ function sommelier(
Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
"WINE_PRESENTATION_GUIDELINE", which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow. "WINE_PRESENTATION_GUIDELINE", which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
"END_CONVER_GUIDELINE", which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow. "END_CONVER_GUIDELINE", which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
""" """
system_msg = Dict( system_msg = Dict(
+4 -4
View File
@@ -95,15 +95,15 @@ end
""" """
function addNewMessage(a::T1, name::String, userinput::T2; function addNewMessage(a::T1, name::String, userinput::T2;
maximumMsg::Integer=30) where {T1<:agent, T2<:AbstractDict} maximumMsg::Integer=30) where {T1<:agent, T2<:AbstractDict}
if name ["system", "user", "assistant"] # guard against typo # if name ∉ ["system", "user", "assistant"] # guard against typo
error("name is not in agent.availableRole $(@__LINE__)") # error("name is not in agent.availableRole $(@__LINE__)")
end # end
#TODO summarize the oldest 10 message #TODO summarize the oldest 10 message
if length(a.chathistory) > maximumMsg if length(a.chathistory) > maximumMsg
summarize(a.chathistory) summarize(a.chathistory)
else else
userinput["timestamp"] = Dates.now() # userinput["timestamp"] = Dates.now()
push!(a.chathistory, userinput) push!(a.chathistory, userinput)
end end
end end
+308 -198
View File
@@ -2,200 +2,236 @@ using JSON, Dates, UUIDs, PrettyPrinting, LibPQ, Base64, DataFrames, DataStructu
NATS, Base.Threads NATS, Base.Threads
using YiemAgent, GeneralUtils, msghandler using YiemAgent, GeneralUtils, msghandler
function text2text_instruct_llm(sender_id::String, openai_msg::Dict{String, Any})
payloads = [("msg", openai_msg, "dictionary")] # List of tuples
_, msg_envelope_json_str = msghandler.smartpack(
config["externalservice"]["servicesloadbalancer"]["nats"],
payloads;
sender_id=sender_id,
msg_purpose="text2text",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalservice"]["fileserver"]["url"])
function text2text_instruct_llm(sender_id::String, openai_msg::Dict{String, Any}) reply = NATS.request(agent_conn,
payloads = [("msg", openai_msg, "dictionary")] # List of tuples config["externalservice"]["servicesloadbalancer"]["nats"],
_, msg_envelope_json_str = msghandler.smartpack( msg_envelope_json_str, timeout=120)
config["externalService"]["servicesloadbalancer"]["nats"],
payloads;
sender_id=sender_id,
msg_purpose="text2text",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalService"]["fileserver"]["url"])
reply = NATS.request(agent_conn, incoming_env_json_str = String(reply.payload)
config["externalService"]["servicesloadbalancer"]["nats"], incoming_env = msghandler.smartunpack(incoming_env_json_str)
msg_envelope_json_str, timeout=120) _llm_response = incoming_env["payloads"][1][2]
llm_response = _llm_response["choices"][1]["message"]["content"]
incoming_env_json_str = String(reply.payload) return llm_response
incoming_env = msghandler.smartunpack(incoming_env_json_str)
_llm_response = incoming_env["payloads"][1][2]
llm_response = _llm_response["choices"][1]["message"]["content"]
return llm_response
end
#TESTING get text embedding from a LLM service
function get_embedding(text::AbstractArray{String})
documents_dict = Dict("documents" => text)
payloads = [("documents", documents_dict, "dictionary")]
_, msg_envelope_json_str = msghandler.smartpack(
config["externalService"]["servicesloadbalancer"]["nats"],
payloads;
msg_purpose="embedding",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalService"]["fileserver"]["url"])
reply = NATS.request(agent_conn,
config["externalService"]["servicesloadbalancer"]["nats"],
msg_envelope_json_str, timeout=120)
incoming_env_json_str = String(reply.payload)
incoming_env = msghandler.smartunpack(incoming_env_json_str)
embedding_response = incoming_env["payloads"][1][2]
return embedding_response
end
#TESTING
function execute_sql_winedb(config::JSON.Object, sql::T) where {T<:AbstractString}
host_url, _port = split(config["externalservice"]["sommpanion_db"]["url"], ':')
port = parse(Int, _port)
dbname = "winedb"
user = config["externalservice"]["sommpanion_db"]["user"]
password = config["externalservice"]["sommpanion_db"]["password"]
db_connection = LibPQ.Connection("host=$host_url port=$port dbname=$dbname user=$user password=$password")
result = LibPQ.execute(db_connection, sql)
LibPQ.close(db_connection)
return result
end
#TESTING
function similar_sql_vectordb(query; maxdistance::Integer=100)
tablename = "sqlllm_decision_repository"
# get embedding of the query
df = find_similar_text_from_vectordb(query, tablename,
"function_input_embedding", execute_sql_vectordb)
# println(df[1, [:id, :function_output]])
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
# distance = 100 # CHANGE this is for testing only
if row != 0 && distance < maxdistance
# if there is usable SQL, return it.
output_b64 = df[1, :function_output_base64] # pick the closest match
output_str = String(base64decode(output_b64))
rowid = df[1, :id]
println("\n~~~ found similar sql. row id $rowid, distance $distance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
return (dict=output_str, distance=distance)
else
println("\n~~~ similar sql not found, max distance $maxdistance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
return (dict=nothing, distance=nothing)
end end
end
#TESTING """ get a single text embedding from a LLM service
function insert_sql_vectordb(query::T1, SQL::T2; maxdistance::Integer=3) where {T1<:AbstractString, T2<:AbstractString} Example
tablename = "sqlllm_decision_repository" text = ["hello"]
# get embedding of the query embedding = get_embedding(text)
# query = state[:thoughtHistory][:question] """
df = find_similar_text_from_vectordb(query, tablename, function get_embedding(text::AbstractArray{String})
"function_input_embedding", execute_sql_vectordb) documents_dict = Dict("documents" => text)
row, col = size(df) payloads = [("documents", documents_dict, "dictionary")]
distance = row == 0 ? Inf : df[1, :distance] _, msg_envelope_json_str = msghandler.smartpack(
if row == 0 || distance > maxdistance # no close enough SQL stored in the database config["externalservice"]["servicesloadbalancer"]["nats"],
_query_embedding = get_embedding([query])[1] payloads;
query_embedding = _query_embedding["data"][1]["embedding"] msg_purpose="embedding",
query = replace(query, "'" => "") broker_url=config["nats_server_info"]["url"],
sql_base64 = base64encode(SQL) fileserver_url=config["externalservice"]["fileserver"]["url"])
sql_ = replace(SQL, "'" => "")
sql = """ reply = NATS.request(agent_conn,
INSERT INTO $tablename (function_input, function_output, function_output_base64, function_input_embedding) VALUES ('$query', '$sql_', '$sql_base64', '$query_embedding'); config["externalservice"]["servicesloadbalancer"]["nats"],
""" msg_envelope_json_str, timeout=120)
# println("\n~~~ added new decision to vectorDB ", @__FILE__, ":", @__LINE__, " $(Dates.now())") incoming_env_json_str = String(reply.payload)
# println(sql) incoming_env = msghandler.smartunpack(incoming_env_json_str)
_ = execute_sql_vectordb(sql) embedding_response = incoming_env["payloads"][1][2]
return embedding_response
end end
end
#TESTING """ sql = "SELECT * FROM wine;"
function execute_sql_vectordb(sql::T) where {T<:AbstractString} result = execute_sql_winedb(sql)
host_url, _port = split(config["SQLVectorDB"]["url"], ':') """
port = parse(Int, _port) function execute_sql_winedb(sql::T) where {T<:AbstractString}
dbname = config[:externalservice][:SQLVectorDB][:dbname] host_url, _port = split(config["externalservice"]["sommpanion_db"]["url"], ':')
user = config[:externalservice][:SQLVectorDB][:user] port = parse(Int, _port)
password = config[:externalservice][:SQLVectorDB][:password] dbname = "winedb"
DBconnection = LibPQ.Connection("host=$host_url port=$port dbname=$dbname user=$user password=$password") user = config["externalservice"]["sommpanion_db"]["user"]
result = LibPQ.execute(DBconnection, sql) password = config["externalservice"]["sommpanion_db"]["password"]
close(DBconnection) db_connection = LibPQ.Connection("host=$host_url port=$port dbname=$dbname user=$user password=$password")
return result result = nothing
end try
result = LibPQ.execute(db_connection, sql)
catch e
function similar_sommelier_decision(recentevents::T1; maxdistance::Integer=3 LibPQ.close(db_connection)
)::Union{AbstractDict, Nothing} where {T1<:AbstractString} end
tablename = "sommelier_decision_repository"
# find similar
println("\n~~~ search vectorDB for this: $recentevents ", @__FILE__, " ", @__LINE__)
df = find_similar_text_from_vectordb(recentevents, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row != 0 && distance < maxdistance
# if there is usable decision, return it.
rowid = df[1, :id]
println("\n~~~ found similar decision. row id $rowid, distance $distance ", @__FILE__, " ", @__LINE__)
output_b64 = df[1, :function_output_base64] # pick the closest match
_output_str = String(base64decode(output_b64))
output = copy(JSON.read(_output_str))
return output
else
println("\n~~~ similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__)
return nothing
end
end
#TESTING
function find_similar_text_from_vectordb(text::T1, tablename::T2, embeddingColumnName::T3,
vectorDB::Function; limit::Integer=1
)::DataFrame where {T1<:AbstractString, T2<:AbstractString, T3<:AbstractString}
# get embedding from LLM service
_embedding = get_embedding([text])[1]
embedding = _embedding["data"][1]["embedding"]
# check whether there is close enough vector already store in vectorDB. if no, add, else skip
sql = """
SELECT *, $embeddingColumnName <-> '$embedding' as distance
FROM $tablename
ORDER BY distance LIMIT $limit;
"""
response = vectorDB(sql)
df = DataFrame(response)
return df
end
function insert_sommelier_decision(recentevents::T1, decision::T2; maxdistance::Integer=5
) where {T1<:AbstractString, T2<:AbstractDict}
tablename = "sommelier_decision_repository"
# find similar
df = find_similar_text_from_vectordb(recentevents, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
_embedding = get_embedding([recentevents])[1]
recentevents_embedding = _embedding["data"][1]["embedding"]
recentevents = replace(recentevents, "'" => "")
decision_json = JSON.json(decision)
decision_base64 = base64encode(decision_json)
decision = replace(decision_json, "'" => "")
sql = LibPQ.close(db_connection)
""" return result
INSERT INTO $tablename (function_input, function_output, function_output_base64, function_input_embedding) VALUES ('$recentevents', '$decision', '$decision_base64', '$recentevents_embedding');
"""
println("\n~~~ added new decision to vectorDB ", @__FILE__, " ", @__LINE__)
println(sql)
_ = execute_sql_vectordb(sql)
else
println("~~~ similar decision previously cached, distance $distance ", @__FILE__, " ", @__LINE__)
end end
end
""" find similar sql from vector database
sql = "SELECT * FROM wine;"
result, distance = similar_sql_vectordb(sql)
"""
function similar_sql_vectordb(sql::T; maxdistance::Number=0.2) where {T<:AbstractString}
tablename = "sqlllm_decision_repository"
# get embedding of the query
df = find_similar_text_from_vectordb(sql, tablename,
"function_input_embedding", execute_sql_vectordb)
# println(df[1, [:id, :function_output]])
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row != 0 && distance < maxdistance
# if there is usable SQL, return it.
output_b64 = df[1, :function_output_base64] # pick the closest match
output_str = String(base64decode(output_b64))
rowid = df[1, :id]
println("\n--| similar sql found. row id $rowid, distance $distance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
pprintln(output_str)
return (result=output_str, distance=distance)
else
println("\n--| similar sql not found, max distance $maxdistance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
return (result=nothing, distance=nothing)
end
end
""" insert query and sql into vector database
query = "get all wines from wine table"
sql = "SELECT * FROM wine;"
insert_sql_vectordb(query, sql)
"""
function insert_sql_vectordb(query::T1, SQL::T2; maxdistance::Number=3
) where {T1<:AbstractString, T2<:AbstractString}
tablename = "sqlllm_decision_repository"
# get embedding of the query
# query = state[:thoughtHistory][:question]
df = find_similar_text_from_vectordb(query, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
_query_embedding = get_embedding([query])
_query_embedding = GeneralUtils.dictify(_query_embedding)
# println("\n--- _query_embedding() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# println(_query_embedding)
# println("---\n")
query_embedding = _query_embedding["data"][1]["embedding"]
query = replace(query, "'" => "")
sql_base64 = base64encode(SQL)
sql_ = replace(SQL, "'" => "")
sql =
"""
INSERT INTO $tablename (function_input, function_output, function_output_base64, function_input_embedding) VALUES ('$query', '$sql_', '$sql_base64', '$query_embedding');
"""
# println("\n--| added new decision to vectorDB ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# println(sql)
_ = execute_sql_vectordb(sql)
end
end
""" execute sql against vectordb
sql = "SELECT * FROM wine;"
result = execute_sql_vectordb(sql)
"""
function execute_sql_vectordb(sql::T) where {T<:AbstractString}
host_url, _port = split(config["externalservice"]["sommpanion_vectordb"]["url"], ':')
port = parse(Int, _port)
dbname = config["externalservice"]["sommpanion_vectordb"]["dbname"]
user = config["externalservice"]["sommpanion_vectordb"]["user"]
password = config["externalservice"]["sommpanion_vectordb"]["password"]
DBconnection = LibPQ.Connection("host=$host_url port=$port dbname=$dbname user=$user password=$password")
result = LibPQ.execute(DBconnection, sql)
close(DBconnection)
return result
end
""" search similar decision llm made from vectordb
"""
function similar_sommelier_decision(recentevents::T1; maxdistance::Integer=3
)::Union{AbstractDict, Nothing} where {T1<:AbstractString}
tablename = "sommelier_decision_repository"
# find similar
df = find_similar_text_from_vectordb(recentevents, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row != 0 && distance < maxdistance
# if there is usable decision, return it.
rowid = df[1, :id]
println("\n--| found similar decision. row id $rowid, distance $distance ", @__FILE__, " ", @__LINE__)
output_b64 = df[1, :function_output_base64] # pick the closest match
_output_str = String(base64decode(output_b64))
output = copy(JSON.read(_output_str))
return output
else
println("\n--| similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__)
return nothing
end
end
""" search similar text from vectordb
"""
function find_similar_text_from_vectordb(text::T1, tablename::T2, embeddingColumnName::T3,
vectorDB::Function; limit::Integer=1
)::DataFrame where {T1<:AbstractString, T2<:AbstractString, T3<:AbstractString}
# get embedding from LLM service
_embedding = get_embedding([text])
_embedding = _embedding["data"][1]["embedding"]
_embedding = "$_embedding"
embedding = _embedding[4:end]
# check whether there is close enough vector already store in vectorDB. if no, add, else skip
sql = """
SELECT *, $embeddingColumnName <-> '$embedding' as distance
FROM $tablename
ORDER BY distance LIMIT $limit;
"""
response = vectorDB(sql)
df = DataFrame(response)
return df
end
""" insert decision llm made to vectordb
"""
function insert_sommelier_decision(recentevents::T1, decision::T2; maxdistance::Integer=5
) where {T1<:AbstractString, T2<:AbstractDict}
tablename = "sommelier_decision_repository"
# find similar
df = find_similar_text_from_vectordb(recentevents, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
_embedding = get_embedding([recentevents])[1]
recentevents_embedding = _embedding["data"][1]["embedding"]
recentevents = replace(recentevents, "'" => "")
decision_json = JSON.json(decision)
decision_base64 = base64encode(decision_json)
decision = replace(decision_json, "'" => "")
sql =
"""
INSERT INTO $tablename (function_input, function_output, function_output_base64, function_input_embedding) VALUES ('$recentevents', '$decision', '$decision_base64', '$recentevents_embedding');
"""
println("\n--| added new decision to vectorDB ", @__FILE__, " ", @__LINE__)
println(sql)
_ = execute_sql_vectordb(sql)
else
println("--| similar decision previously cached, distance $distance ", @__FILE__, " ", @__LINE__)
end
end
config = JSON.parsefile("./appconfig.json")
sessionId = "0" sessionId = "0"
backend_session_topic = "sommpanion.backend.agentbackend.v1.inbox.$sessionId" backend_session_topic = "sommpanion.testsubject"
config = JSON.parsefile("./dummy_config.json")
agent_ch = Channel(8) agent_ch = Channel(8)
agent_conn = NATS.connect(config["nats_server_info"]["url"]) agent_conn = NATS.connect(config["nats_server_info"]["url"])
sub2 = NATS.subscribe(agent_conn, backend_session_topic) do msg sub2 = NATS.subscribe(agent_conn, backend_session_topic) do msg
put!(agent_ch, msg) put!(agent_ch, msg)
end end
@@ -210,32 +246,34 @@ agent_context = YiemAgent.agentcontext(
insert_sommelier_decision insert_sommelier_decision
) )
# can't instantiate # can't instantiate
agent = YiemAgent.sommelier( agent = YiemAgent.sommelier(
agent_context; agent_context;
name="Janie", name="Janie",
id=sessionId, # agent instance id id=sessionId, # agent instance id
retailername="Yiem", retailername="Yiem Wine Ltd.",
llmFormatName="" llmFormatName=""
) )
# 1. Read local file and encode to base64 string
image1_path = "test/large_image.png" image1_path = "test/large_image.png"
image1_bytes = read(image1_path) image1_bytes = read(image1_path)
image1_base64_string = base64encode(image1_bytes) image1_base64_string = base64encode(image1_bytes)
# 2. Match the MIME type according to your file extension (e.g., png, jpeg)
mime_type = "image/png" mime_type = "image/png"
data1_uri = "data:$(mime_type);base64,$(image1_base64_string)" 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 # 3. Construct payload with the Data URI
usermsg = Dict{String, Any}( message = Dict(
"role" => "user", "role" => "user",
"content" => [ "content" => [
Dict("type" => "text", "text" => "รู้จักไวน์ที่อยู่ในรูปมั้ย"), Dict("type" => "text", "text" => "Do you know type of wine in the image?"),
Dict( Dict(
"type" => "image_url", "type" => "image_url",
"image_url" => Dict("url" => data1_uri) "image_url" => Dict("url" => data1_uri)
@@ -243,8 +281,80 @@ usermsg = Dict{String, Any}(
] ]
) )
result = YiemAgent.conversation(agent; userinput=usermsg) result = YiemAgent.conversation(agent; userinput=message)
println(result) println("\n$result")
# message = Dict(
# "role" => "user",
# "content" => [
# Dict("type" => "text", "text" =>
# "
# เป็นงานเลี้ยงทั่วไป
# "),
# ]
# )
# result = YiemAgent.conversation(agent; userinput=message)
# println("\n$result")
# message = Dict(
# "role" => "user",
# "content" => [
# Dict("type" => "text", "text" => "no thanks. that's all"),
# ]
# )
# result = YiemAgent.conversation(agent; userinput=message)
# println("\n$result")
# message = Dict(
# "role" => "user",
# "content" => [
# Dict("type" => "text", "text" => "What about this wine?"),
# Dict(
# "type" => "image_url",
# "image_url" => Dict("url" => data2_uri)
# )
# ]
# )
# result = YiemAgent.conversation(agent; userinput=message)
# println("\n$result")