Compare commits

..

58 Commits

Author SHA1 Message Date
ton c29dccf597 up version 2026-07-09 08:01:08 +07:00
ton 70cf04b0db Merge pull request 'v0.4.1-fix_agent_not_respond' (#3) from v0.4.1-fix_agent_not_respond into v0.4.1
Reviewed-on: #3
2026-07-09 00:58:33 +00:00
ton 4d57f0146b update 2026-07-09 07:56:33 +07:00
ton d33aa14dc8 use md system prompt 2026-07-07 07:54:24 +07:00
ton 0ed3edd48a update 2026-07-06 06:10:12 +07:00
ton fb91b51573 update 2026-07-05 20:48:24 +07:00
ton 0bbd227920 update 2026-07-04 17:37:43 +07:00
ton 3487770f77 update 2026-07-04 15:42:00 +07:00
ton 7d27f9e567 update 2026-07-04 13:43:44 +07:00
ton 511b4d682d update 2026-07-04 13:42:33 +07:00
ton 5ba91d8acc update compat 2026-07-04 13:41:00 +07:00
ton 709f7e7115 Merge pull request 'v0.4.0' (#2) from v0.4.0 into main
Reviewed-on: #2
2026-07-04 06:34:08 +00:00
ton 3529384cdb Merge pull request 'v0.4.0-fix_appcontext' (#1) from v0.4.0-fix_appcontext into v0.4.0
Reviewed-on: #1
2026-07-04 06:33:31 +00:00
ton d1921fa403 update 2026-07-04 13:23:46 +07:00
ton b4f2a6185b update 2026-06-30 21:18:59 +07:00
ton d076d5f912 update 2026-06-28 22:03:58 +07:00
ton e63dd7d898 update 2026-06-27 08:00:41 +07:00
ton 299a485e4e update docstring 2026-06-25 08:19:25 +07:00
ton 57dd6df942 add context 2026-06-24 21:02:56 +07:00
ton 9c22cf2e31 use Dict string key 2026-06-24 20:46:24 +07:00
ton de20764610 update 2026-06-24 19:50:43 +07:00
ton 906afc6422 update 2026-06-24 08:47:36 +07:00
ton f6eaf4751b update 2026-06-21 09:48:17 +07:00
ton 99b2fda461 use JSON instead 2026-06-21 08:51:39 +07:00
ton b5a00bc694 update 2025-07-30 18:08:57 +07:00
ton 4eb55537f7 update 2025-07-23 18:28:38 +07:00
narawat lamaiin 0a1032c545 update 2025-07-18 07:54:59 +07:00
narawat lamaiin 68a20b5080 update 2025-07-17 11:48:23 +07:00
narawat lamaiin 8a9c9606c7 update 2025-07-14 19:33:12 +07:00
narawat lamaiin bad2ca35ed update 2025-07-14 08:54:51 +07:00
narawat lamaiin f2b56640cc update 2025-06-17 12:53:32 +07:00
narawat lamaiin 5d552d96c4 add example 2025-06-17 12:52:00 +07:00
narawat lamaiin e0dc7d29b2 update 2025-06-15 08:02:59 +07:00
narawat lamaiin 932611a439 update 2025-06-09 06:33:48 +07:00
narawat lamaiin a5c6360b4e update 2025-06-03 10:08:54 +07:00
narawat lamaiin 03f50379c9 mark new version 2025-05-26 07:14:19 +07:00
ton a7da0b8123 Merge pull request 'v0.3.0' (#5) from v0.3.0 into main
Reviewed-on: #5
2025-05-26 00:07:21 +00:00
narawat lamaiin e524813021 update 2025-05-26 07:05:14 +07:00
narawat lamaiin 3444f00062 update 2025-05-19 21:10:04 +07:00
narawat lamaiin 919d8ec85e update 2025-05-18 17:21:51 +07:00
narawat lamaiin 3a88e0e7d4 update 2025-05-17 21:36:29 +07:00
narawat lamaiin 68c2c2f12b update 2025-05-17 12:18:25 +07:00
narawat lamaiin 3e79c0bfed update 2025-05-16 10:26:50 +07:00
narawat lamaiin d0c26e52e8 update 2025-05-14 21:21:35 +07:00
narawat lamaiin a0152a3c29 update 2025-05-04 20:56:17 +07:00
narawat lamaiin 1fc5dfe820 mark new version 2025-05-02 15:27:29 +07:00
ton 4b2575f4a4 Merge pull request 'v0.2.0' (#4) from v0.2.0 into main
Reviewed-on: #4
2025-05-02 08:21:05 +00:00
narawat lamaiin a01a91e7b9 update 2025-05-01 12:05:59 +07:00
narawat lamaiin aa8436c0ed update 2025-05-01 08:04:01 +07:00
narawat lamaiin cccad676db update 2025-05-01 07:59:37 +07:00
narawat lamaiin 03de659c9b update companion 2025-04-30 12:58:32 +07:00
narawat lamaiin affb96f0cf update 2025-04-29 18:45:52 +07:00
narawat lamaiin f19f302bd9 update 2025-04-29 11:01:36 +07:00
narawat lamaiin 7ca4f5276d update 2025-04-26 06:20:09 +07:00
narawat lamaiin 44804041a3 update 2025-04-25 21:12:27 +07:00
narawat lamaiin 48a3704f6d update 2025-04-13 21:46:54 +07:00
tonaerospace 8321a13afc update 2025-04-04 15:23:34 +07:00
tonaerospace b26ae31d4c mark new version 2025-04-04 15:23:11 +07:00
22 changed files with 4302 additions and 2381 deletions
+386 -214
View File
File diff suppressed because it is too large Load Diff
+11 -5
View File
@@ -1,17 +1,19 @@
name = "YiemAgent" name = "YiemAgent"
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2" uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
version = "0.4.1"
authors = ["narawat lamaiin <narawat@outlook.com>"] authors = ["narawat lamaiin <narawat@outlook.com>"]
version = "0.1.4"
[deps] [deps]
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
GeneralUtils = "c6c72f09-b708-4ac8-ac7c-2084d70108fe" GeneralUtils = "c6c72f09-b708-4ac8-ac7c-2084d70108fe"
HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3"
JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
LLMMCTS = "d76c5a4d-449e-4835-8cc4-dd86ec44f241" LLMMCTS = "d76c5a4d-449e-4835-8cc4-dd86ec44f241"
LibPQ = "194296ae-ab2e-5f79-8cd4-7183a0a5a0d1" LibPQ = "194296ae-ab2e-5f79-8cd4-7183a0a5a0d1"
NATS = "55e73f9c-eeeb-467f-b4cc-a633fde63d2a"
PrettyPrinting = "54e16d92-306c-5ea0-a30b-337be88ac337" PrettyPrinting = "54e16d92-306c-5ea0-a30b-337be88ac337"
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
Revise = "295af30f-e4ad-537b-8983-00126c2a3abe" Revise = "295af30f-e4ad-537b-8983-00126c2a3abe"
@@ -21,7 +23,11 @@ URIs = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[compat] [compat]
CSV = "0.10.15"
DataFrames = "1.7.0" DataFrames = "1.7.0"
GeneralUtils = "0.1, 0.2" GeneralUtils = "0.4.9"
LLMMCTS = "0.1.2" HTTP = "2.4.0"
SQLLLM = "0.2.0" JSON = "1.6.1"
LLMMCTS = "0.1.5"
NATS = "0.1.0"
SQLLLM = "0.2.5"
+82
View File
@@ -0,0 +1,82 @@
# Store Policy
- Generally speaking, the store inventory has some wines from France, the United States, Australia, Spain, and Italy, but you won't know exactly until you check your inventory.
- If you found wines in the store's database, they are in stock.
- You can only recommend wines that are currently in our inventory
- Before searching the database for wine, ensure you have at least the following information: 1) budget, 2) wine type, and 3) occasion. Additional details are always helpful. If the user is unsure, provide relevant information and gather insights to make reasonable inferences.
- Ask the user one question at a time.
- Do not ask the user about wine's flavor e.g. floral, citrusy, nutty or some thing similar as these terms cannot be used to search the database.
- Once the user has selected their wine, if you haven't already, ask the user whether they need any further assistance. Do not offer any additional services.
- Only end the conversation when the user explicitly intends to do so. When ending, ensure a polite farewell and an invitation to return in the future.
- Spicy foods should be paired only with light red wines.
- We do not sell organic, sustainable, gluten-free, and sulfite-free wine. Inform the user imediately if they are looking for these types of wines. Do not sell our wines as such.
- Gift box, gift card, and custom messages are available. Inform the user to contact our sales team.
# Store Guidelines
- Greeting the customer warmly by ask them how could you help. Do not ask any other questions during this greeting.
- Customer may provide images for you to look up.
- Encourage the customer to explore different options and try new things.
- If you are unable to locate the desired item in the database after 2 attempts, it may not be available in your inventory. In such cases, inform the user that the item is unavailable and suggest an alternative instead.
- Your store carries only wine.
- Vintage 0 means non-vintage.
- Start searching the database as broadly as possible within the given information boundary to maximize the chances of finding. Avoid unnecessary parameters unless specified by the user. Refine the search subsequently.
# Prompt
Search the database as broad as possible under the informantion you have will increase the chance to find wine. Avoid uneccessary parameter such as region, country, tasting notes unless the user specify
# Situation
Your customer is coming into the store
# Role
Your name is $(newAgent.name). You are a helpful sommelier for website-based $(newAgent.retailername)'s wine store. You are working under your mentor supervision.
# Objective
1. Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences.
2. Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences.
# Responsibility Includes
1. According to the store's policy and guidelines, make an informed decision about what you need to do to achieve the objective
2. Keep the conversation with the customer going smoothly
3. Obey your mentor's suggestions.
# Responsibility Does NOT Include
1. Requesting the user to place an order, make a purchase, or confirm the order. These are the job of our sales team at the store.
2. Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store.
3. Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store.
# Available Actions
- **CHAT_BOX** which you can use to talk with the user.
- **CHECK_WINE** allows you to check information about wines you want in your inventory's database. The input is text that specify supported search criteria includeing: retailer_name, wine price, winery, name, vintage, region, country, type, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity.
- Example query 1: "Dry, full-bodied red wine from 1) region: Burgundy, country: France or 2) region: Tuscany, country: Italy. Grape varietal: Merlot or Syrah. price 100 to 1000 USD."
- Example query 2: "Red or white wine, medium tannin, price under 700 USD"
- Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
- **PRESENT_WINE_GUIDELINE** which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
- **END_CONVER_GUIDELINE** which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
# Response Format
You should respond to the user with interleaving plan, action_name, action_input:
1. **plan**: Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
2. **action_name**: (Typically corresponds to the execution of the first step in your plan) Can be one of the available_actions name
3. **action_input**: The input to the action you are about to perform according to your plan.
After the action is executed you gets "action_result". It is the output from the action you selected.
Assistant should only respond in JSON format as described below:
```json
{
"plan": "...",
"action_name": "...",
"action_input": "..."
}
```
+53
View File
@@ -0,0 +1,53 @@
{
"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_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": "yiemtechnologies@gmail.com",
"password": "yiemtechnologies@Postgres_0.0"
},
"sommpanion_vectordb" : {
"description": "A wine database connection info for LibPQ client",
"url": "192.168.88.106:5433",
"dbname": "vectordb",
"user": "yiemtechnologies@gmail.com",
"password": "yiemtechnologies@Postgres_0.0"
},
"fileserver": {
"description": "temporary file server",
"url": "https://fileserver.yiem.cc"
}
}
}
+13
View File
@@ -0,0 +1,13 @@
d = Dict(
"hello"=> 555,
"world"=> Dict(
"name"=> "ton"
)
)
x = 55
@info "YiemAgent think() 1 " d x @__LINE__
+585
View File
@@ -0,0 +1,585 @@
using Revise
using JSON, JSON, Dates, UUIDs, PrettyPrinting, LibPQ, Base64, DataFrames, DataStructures
using YiemAgent, GeneralUtils
using Base.Threads
# ---------------------------------------------- 100 --------------------------------------------- #
# load config
config = JSON.parsefile("/appfolder/app/dev/YiemAgent/test/config.json")
# config = copy(JSON.parsefile("../mountvolume/config.json"))
function executeSQL(sql::T) where {T<:AbstractString}
host = config[:externalservice][:wineDB][:host]
port = config[:externalservice][:wineDB][:port]
dbname = config[:externalservice][:wineDB][:dbname]
user = config[:externalservice][:wineDB][:user]
password = config[:externalservice][:wineDB][:password]
DBconnection = LibPQ.Connection("host=$host port=$port dbname=$dbname user=$user password=$password")
result = LibPQ.execute(DBconnection, sql)
close(DBconnection)
return result
end
function executeSQLVectorDB(sql)
host = config[:externalservice][:SQLVectorDB][:host]
port = config[:externalservice][:SQLVectorDB][:port]
dbname = config[:externalservice][:SQLVectorDB][:dbname]
user = config[:externalservice][:SQLVectorDB][:user]
password = config[:externalservice][:SQLVectorDB][:password]
DBconnection = LibPQ.Connection("host=$host port=$port dbname=$dbname user=$user password=$password")
result = LibPQ.execute(DBconnection, sql)
close(DBconnection)
return result
end
function text2textInstructLLM(prompt::String; maxattempt::Integer=10, modelsize::String="medium",
senderId=GeneralUtils.uuid4snakecase(), timeout=90,
llmkwargs=Dict(
:num_ctx => 32768,
:temperature => 0.5,
)
)
msgMeta = GeneralUtils.generate_msgMeta(
config[:externalservice][:loadbalancer][:mqtttopic];
msgPurpose="inference",
senderName="yiemagent",
senderId=senderId,
receiverName="text2textinstruct_$modelsize",
mqttBrokerAddress=config[:mqttServerInfo][:broker],
mqttBrokerPort=config[:mqttServerInfo][:port],
)
outgoingMsg = Dict(
:msgMeta => msgMeta,
:payload => Dict(
:text => prompt,
:kwargs => llmkwargs
)
)
response = nothing
for attempts in 1:maxattempt
_response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; responsetimeout=timeout, responsemaxattempt=maxattempt)
payload = _response[:response]
if _response[:success] && payload[:text] !== nothing
response = _response[:response][:text]
break
else
println("\n<text2textInstructLLM()> attempt $attempts/$maxattempt failed ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
pprintln(outgoingMsg)
println("</text2textInstructLLM()> attempt $attempts/$maxattempt failed ", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
sleep(3)
end
end
return response
end
# get text embedding from a LLM service
function getEmbedding(text::T) where {T<:AbstractString}
msgMeta = GeneralUtils.generate_msgMeta(
config[:externalservice][:loadbalancer][:mqtttopic];
msgPurpose="embedding",
senderName="yiemagent",
senderId=sessionId,
receiverName="textembedding",
mqttBrokerAddress=config[:mqttServerInfo][:broker],
mqttBrokerPort=config[:mqttServerInfo][:port],
)
outgoingMsg = Dict(
:msgMeta => msgMeta,
:payload => Dict(
:text => [text] # must be a vector of string
)
)
response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; responsetimeout=120, responsemaxattempt=3)
embedding = response[:response][:embeddings]
return embedding
end
function findSimilarTextFromVectorDB(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 = getEmbedding(text)[1]
# 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 similarSQLVectorDB(query; maxdistance::Integer=100)
tablename = "sqlllm_decision_repository"
# get embedding of the query
df = findSimilarTextFromVectorDB(query, tablename,
"function_input_embedding", executeSQLVectorDB)
# 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
function insertSQLVectorDB(query::T1, SQL::T2; maxdistance::Integer=3) where {T1<:AbstractString, T2<:AbstractString}
tablename = "sqlllm_decision_repository"
# get embedding of the query
# query = state[:thoughtHistory][:question]
df = findSimilarTextFromVectorDB(query, tablename,
"function_input_embedding", executeSQLVectorDB)
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 = getEmbedding(query)[1]
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)
_ = executeSQLVectorDB(sql)
end
end
function similarSommelierDecision(recentevents::T1; maxdistance::Integer=3
)::Union{AbstractDict, Nothing} where {T1<:AbstractString}
tablename = "sommelier_decision_repository"
# find similar
println("\n~~~ search vectorDB for this: $recentevents ", @__FILE__, " ", @__LINE__)
df = findSimilarTextFromVectorDB(recentevents, tablename,
"function_input_embedding", executeSQLVectorDB)
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.parsefile(_output_str))
return output
else
println("\n~~~ similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__)
return nothing
end
end
function insertSommelierDecision(recentevents::T1, decision::T2; maxdistance::Integer=5
) where {T1<:AbstractString, T2<:AbstractDict}
tablename = "sommelier_decision_repository"
# find similar
df = findSimilarTextFromVectorDB(recentevents, tablename,
"function_input_embedding", executeSQLVectorDB)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
recentevents_embedding = getEmbedding(recentevents)[1]
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)
_ = executeSQLVectorDB(sql)
else
println("~~~ similar decision previously cached, distance $distance ", @__FILE__, " ", @__LINE__)
end
end
sessionId = GeneralUtils.uuid4snakecase()
externalFunction = (
getEmbedding=getEmbedding,
text2textInstructLLM=text2textInstructLLM,
executeSQL=executeSQL,
similarSQLVectorDB=similarSQLVectorDB,
insertSQLVectorDB=insertSQLVectorDB,
similarSommelierDecision=similarSommelierDecision,
insertSommelierDecision=insertSommelierDecision,
)
# s = "full-bodied red wine, budget 1500 USD"
# r = YiemAgent.extractWineAttributes_1(agent, s)
# println(r)
# --------------------------- generating scenario and customer profile --------------------------- #
function rolegenerator()
rolegenerator_systemmsg =
"""
Your role:
- You are a helpful assistant
Your mission:
- Create one random role of a potential customer of an internet wine store.
You must follow the following guidelines:
- the user only need the role, do not add your own words.
- the role should be detailed and realistic.
You should then respond to the user with:
Name: a name of the potential customer
Situation: a situation that the potential customer may be facing
Mission: a mission of the potential customer
Profile: a profile of the potential customer, including their age, gender, occupation, and other relevant information
You should only respond in format as described below:
Name: ...
Situation: ...
Mission: ...
Profile: ...
Additional_information: ...
Here are some examples:
Name: Jimmy
Situation:
- Your relationship with your boss is not that good. You need to improve your relationship with your boss.
- Your boss's wedding anniversary is coming up.
- You are at a wine store and start talking with the store's sommelier.
Mission:
- Ask the sommelier to provide multiple wine options, and subsequently choose one option from the presented list.
Profile:
- You are a young professional in a big company.
- You are avid party goer
- You like beer.
- You know nothing about wine.
- You have a budget of 1500usd.
Additional_information:
- your boss like spicy food.
- your boss is a middle-aged man.
- your boss likes Australian wine.
Name: Kate
Situation:
- Your husband asked you to get him a bottle of wine. He will gift the wine to his business client while dining at a German restaurant.
- Your husband is a business client and he will gift the wine to his business
- You are at a wine store and start talking with the store's sommelier.
Mission:
- Ask the sommelier to provide multiple wine options, and subsequently choose one option from the presented list.
Profile:
- You are a CEO in a startup company.
- You are a nerd
- You don't like alcohol.
- You have a budget of 150usd.
- You don't care about organic, sulfite, gluten-free, or sustainability certified wines
Additional_information:
- your husband like spicy food.
- your husband is a middle-aged man.
Name: John
Situation:
- A local newspaper club wants to have a scoop about wine with local food in the U.S.
- You are at a wine store and start talking with the store's sommelier.
Mission:
- Ask the sommelier to provide multiple wine options, and subsequently choose one option from the presented list.
Profile:
- I'm a young guy.
- I prefer to express my ideas in a succinct and clear manner.
Additional_information:
- N/A
Name: Jane
Situation:
- You have catering a dinner party with French cuisine.
- You want to serve wine with your guests.
- You are at a wine store and start talking with the store's sommelier.
Mission:
- Ask the sommelier to provide multiple wine options, and subsequently choose one option from the presented list.
Profile:
- You are a young French restaurant owner.
- You like dry, full-bodied red wine with high tannin
- You don't care about organic, sulfite, gluten-free, or sustainability certified wines.
- You have a budget of 200 usd.
Additional_information:
- N/A
Let's begin!
"""
header = ["Name:", "Situation:", "Mission:", "Profile:", "Additional_information:"]
dictkey = ["name", "situation", "mission", "profile", "additional_information"]
errornote = "N/A"
for attempt in 1:10
_prompt =
[
Dict(:name => "system", :text => rolegenerator_systemmsg),
]
prompt = GeneralUtils.formatLLMtext(_prompt, "qwen3")
response = text2textInstructLLM(prompt) # generated role
response = GeneralUtils.deFormatLLMtext(response, "qwen3")
think, response = GeneralUtils.extractthink(response)
# check whether response has all header
detected_kw = GeneralUtils.detect_keyword(header, response)
kwvalue = [i for i in values(detected_kw)]
zeroind = findall(x -> x == 0, kwvalue)
missingkeys = [header[i] for i in zeroind]
if 0 values(detected_kw)
errornote = "$missingkeys are missing from your previous response"
println("\nERROR YiemAgent rolegenerator() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
elseif sum(values(detected_kw)) > length(header)
errornote = "\nYour previous attempt has duplicated points according to the required response format"
println("\nERROR YiemAgent rolegenerator() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
end
responsedict = GeneralUtils.textToDict(response, header;
dictKey=dictkey, symbolkey=true)
responsedict[:id] = GeneralUtils.uuid4snakecase()
responsedict[:systemmsg] =
"""
You are role playing as a CUSTOMER of a wine store and you are currently talking with a sommelier of a wine store.
Your profile is as follows:
Situation: $(responsedict[:situation])
Mission: $(responsedict[:mission])
Profile: $(responsedict[:profile])
Additional_information: $(responsedict[:additional_information])
You should follow the following guidelines:
- Focus on the lastest conversation
- Your like to be short and concise
- If you don't know an answer to sommelier's question, you should say: I don't know.
- If you think the store can't provide what you seek, you can leave.
You should then respond to the user with:
Dialogue: what you want to say to the user
Role: Verify that the dialogue is intended for the customer of a wine store. Can be "yes" or "no"
You should only respond in format as described below:
Dialogue: ...
Role: ...
Let's begin!
"""
println("\nrolegenerator() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
println(responsedict)
return responsedict
end
error("ERROR rolegenerator() failed to generate customer role: ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
end
# Define the external functions for the customer agent in named tuple format
customer_externalFunction = (
text2textInstructLLM=text2textInstructLLM,
)
function main()
agent = YiemAgent.sommelier(
externalFunction;
name="Jane",
id=sessionId, # agent instance id
retailername="Yiem",
llmFormatName="qwen3"
)
customerDict = rolegenerator()
customer = YiemAgent.virtualcustomer(
customer_externalFunction;
systemmsg=customerDict[:systemmsg],
name=customerDict[:name],
id=sessionId, # agent instance id
llmFormatName="qwen3"
)
# customer_chat = "hello"
# YiemAgent.addNewMessage(customer, "assistant", customer_chat)
# # add user activity to events memory
# push!(customer.memory[:events],
# YiemAgent.eventdict(;
# event_description="the assistant talks to the user.",
# timestamp=Dates.now(),
# subject="assistant",
# action_name="CHAT_BOX",
# action_input=customer_chat,
# )
# )
# println("\ncustomer respond:\n $customer_chat")
agent_response = YiemAgent.conversation(agent; maximumMsg=50)
println("\nagent respond:\n $agent_response")
while true
customer_chat = nothing
while customer_chat === nothing
customer_response = YiemAgent.conversation(customer, Dict(:text=> agent_response);
converPartnerName=agent.name,
maximumMsg=50)
customer_response = GeneralUtils.deFormatLLMtext(customer_response, customer.llmFormatName)
customer_chat = customer_response
#[WORKING] check whether customer response the same before
end
println("\ncustomer respond:\n $customer_chat")
agent_response = YiemAgent.conversation(agent;
userinput=Dict(:text=> customer_chat),
maximumMsg=50)
println("\nagent respond:\n $agent_response")
if haskey(agent.memory[:events][end], :thought)
lastAssistantAction = agent.memory[:events][end][:thought][:action_name]
if lastAssistantAction == "END_CONVER_GUIDELINE" # store thoughtDict
# save a.memory[:shortmem][:decisionlog] to disk using JSON
println("\nsaving agent.memory[:shortmem][:decisionlog] to disk")
date = "$(Dates.now())"
date = replace(date, ':'=>'.')
filename = "agent_decision_log_$(date)_$(agent.id).json"
filepath = "/appfolder/mountvolume/appdata/log/$filename"
open(filepath, "w") do io
JSON.pretty(io, agent.memory[:shortmem][:decisionlog])
end
# check how many file in /appfolder/mountvolume/appdata/log/ folder now
logfilesnumber = length(readdir("/appfolder/mountvolume/appdata/log/"))
println("\nCaching conversation process done. Total $logfilesnumber files in /appfolder/mountvolume/appdata/log/ folder now.\n")
break
end
end
end
end
for i in 1:100
main()
println("\n Round $i/100 done.")
end
println("done")
# prompt =
# """
# <|im_start|>system
# You are a role playing agent acting as:
# Name: Emily
# Situation: - Emily is planning her upcoming birthday party and wants to make it extra special. She has invited close friends and family, and she's looking for a unique wine that will impress them.
# Mission: - Emily needs to find a rare and high-quality wine that matches the theme of her party, which is a mix of classic and modern flavors. She also wants to ensure that the wine is not too expensive so that it won't break her budget.
# Profile: - Emily is in her late 20s, works as a marketing executive for a tech company, and has a passion for trying new things. She's organized and detail-oriented but can be spontaneous when it comes to planning events.
# Additional_information: - Emily loves experimenting with different types of food and wine pairings.
# Your are currently talking with a sommelier.
# You should follow the following guidelines:
# - Focus on the lastest conversation
# - If you satisfy with the sommelier's recommendation for bottle of wine(s), you should say: Thanks for you help. I will buy the wine you recommended.
# - If you don't satisfy with the sommelier's questions or can't get a good wine recommendation, you can continue the conversation.
# Let's begin!
# <|im_end|>
# <|im_start|>Jane
# Hello! Welcome to Yiem's Wine Store. I'm Jane, your friendly sommelier. How can I assist you today? What type of wine are you in the mood for, and is there a special occasion or event on your mind?
# <|im_end|>
# <|im_start|>Emily
# Hi Jane! Thank you so much for welcoming me. For my birthday party, I'm looking for something that combines classic and modern flavors. It's a mix of guests who enjoy both traditional tastes and more contemporary ones. Also, I want to make sure it won't break the bank. Any suggestions?
# <|im_end|>
# <|im_start|>Jane
# Thank you for sharing your preferences, Jane! To better assist you, could you please let me know if there are any specific characteristics of wine you're looking for, such as tannin, sweetness, intensity, or acidity? Additionally, do you have any food items in mind that this wine should pair well with?
# <|im_end|>
# <|im_start|>Emily
# """
# llmkwargs=Dict(
# :num_ctx => 32768,
# :temperature => 0.3,
# )
# r = text2textInstructLLM(prompt, llmkwargs=llmkwargs)
# println(r)
# println(555)
# response = YiemAgent.conversation(agent, Dict(:text=> "I want to get a French red wine under 100."))
# while true
# println("your respond: ")
# user_answer = readline()
# response = YiemAgent.conversation(agent, Dict(:text=> user_answer))
# println("\n$response")
# end
# """
# Hello
# I would like to get a bottle of wine for my boss but I don't know much about wine. Can you help me?
# well actually, my boss is going to offer the wine to his client as a gift in a business meeting. All I know is his client like spicy food and French wine. I have a budget about 1000.
# """
# input = "French wine, bordeaux, under USD100, pairs with spicy food"
# r = YiemAgent.extractWineAttributes_1(a, input)
# inventory_order = "French Syrah, Viognier, full bodied, under 100"
# r = YiemAgent.extractWineAttributes_2(a, inventory_order)
# pprintln(r)
# cron job
# @reboot sleep 50 && nvidia-smi -pm 1
# @reboot sleep 51 && nvidia-smi -i 0 -pl 150
# @reboot sleep 52 && nvidia-smi -i 1 -pl 150
# @reboot sleep 53 && nvidia-smi -i 2 -pl 150
# @reboot sleep 54 && nvidia-smi -i 3 -pl 150
# @reboot sleep 55 && julia -t 2 /home/ton/work/restartContainer/main.jl
# using GeneralUtils
# msgMeta = GeneralUtils.generate_msgMeta(
# "/tonpc_containerServices",
# senderName= "somename",
# senderId= "1230",
# mqttBrokerAddress= "mqtt.yiem.cc",
# mqttBrokerPort= 1883,
# )
# outgoingMsg = Dict(
# :msgMeta=> msgMeta,
# :payload=> "docker container restart playground-app",
# )
# GeneralUtils.sendMqttMsg(outgoingMsg)
+706
View File
@@ -0,0 +1,706 @@
using JSON, JSON, Dates, UUIDs, PrettyPrinting, LibPQ, Base64, DataFrames, DataStructures
using YiemAgent, GeneralUtils
using Base.Threads
# ---------------------------------------------- 100 --------------------------------------------- #
""" Expected incomming MQTT message format for this service:
{
"msgMeta": {
"msgPurpose": "updateStatus",
"requestresponse": "request",
"timestamp": "2024-03-29T05:8:48.362",
"replyToMsgId": null,
"receiverId": null,
"getpost": "get",
"msgId": "e5c09bd8-7100-4e4e-bb43-05bee589a22c",
"acknowledgestatus": null,
"sendTopic": "/agent/wine/backend/chat/api/v1/prompt",
"receiverName": "agent-wine-backend",
"replyTopic": "/agent/wine/frontend/chat/api/v1/txt/receive",
"senderName": "agent-wine-frontend-chat",
"senderId": "0938a757-e0ee-40a9-8355-5e24906a87cd"
},
"payload" : {
"text": "hello"
}
}
"""
# load config
config = copy(JSON.parsefile("../mountvolume/config/config.json"))
""" Instantiate an agent. One need to specify startmessage and one of gpu location info,
Mqtt or Rest. start message must be comply with GeneralUtils's message format
Arguments\n
-----
channel::Channel
communication channel
sessionId::String
sesstion ID of the agent
agentName::String
Name of the agent
mqttBroker::String
mqtt broker e.g. "tcp://127.0.0.1:1883"
agentConfigTopic::String
main communication topic for an agent to ask for config
timeout::Int64
inactivity timeout in minutes. If timeout is reached, an agent will be terminated.
Return\n
-----
a task represent an agent
Example\n
-----
```jldoctest
julia> using YiemAgent, GeneralUtils
julia> msg = GeneralUtils.generate_msgMeta("/agent")
julia> incoming_msg = msg # assuming 1st msg was sent from other app
julia> agentConfigTopic = "/agent/wine/backend/config"
julia> task = runAgentInstance(incoming_msg, mqttBroker, agentConfigTopic, 60)
```
TODO\n
-----
[] update docstringLAMA_CONTEXT_LENGTH=40960 since the default size is 2048 as you can see in your debug log:
[] change how to get result of YiemAgent from let YiemAgent send msg directly to frontend,
to
response = YiemAgent.conversation()
then send response to frontend
Signature\n
-----
"""
function runAgentInstance(
receiveUserMsgChannel::Channel,
outputchannel::Channel,
sessionId::String,
config::Dict,
timeout::Int64,
)
function executeSQL(sql::T) where {T<:AbstractString}
host = config[:externalservice][:wineDB][:host]
port = config[:externalservice][:wineDB][:port]
dbname = config[:externalservice][:wineDB][:dbname]
user = config[:externalservice][:wineDB][:user]
password = config[:externalservice][:wineDB][:password]
DBconnection = LibPQ.Connection("host=$host port=$port dbname=$dbname user=$user password=$password")
result = LibPQ.execute(DBconnection, sql)
close(DBconnection)
return result
end
function executeSQLVectorDB(sql)
host = config[:externalservice][:SQLVectorDB][:host]
port = config[:externalservice][:SQLVectorDB][:port]
dbname = config[:externalservice][:SQLVectorDB][:dbname]
user = config[:externalservice][:SQLVectorDB][:user]
password = config[:externalservice][:SQLVectorDB][:password]
DBconnection = LibPQ.Connection("host=$host port=$port dbname=$dbname user=$user password=$password")
result = LibPQ.execute(DBconnection, sql)
close(DBconnection)
return result
end
function text2textInstructLLM(prompt::String; maxattempt::Integer=3, modelsize::String="medium",
senderId=GeneralUtils.uuid4snakecase(), timeout=180,
llmkwargs=Dict(
:num_ctx => 32768,
:temperature => 0.5,
))
msgMeta = GeneralUtils.generate_msgMeta(
config[:externalservice][:loadbalancer][:mqtttopic];
msgPurpose="inference",
senderName="yiemagent",
senderId=senderId,
receiverName="text2textinstruct_$modelsize",
mqttBrokerAddress=config[:mqttServerInfo][:broker],
mqttBrokerPort=config[:mqttServerInfo][:port],
)
outgoingMsg = Dict(
:msgMeta => msgMeta,
:payload => Dict(
:text => prompt,
:kwargs => llmkwargs
)
)
response = nothing
for attempts in 1:maxattempt
_response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=timeout, maxattempt=maxattempt)
payload = _response[:response]
if _response[:success] && payload[:text] !== nothing
response = _response[:response][:text]
break
else
println("\n<text2textInstructLLM()> attempt $attempts/$maxattempt failed ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
pprintln(outgoingMsg)
println("</text2textInstructLLM()> attempt $attempts/$maxattempt failed ", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
sleep(3)
end
end
return response
end
# get text embedding from a LLM service
function getEmbedding(text::T) where {T<:AbstractString}
msgMeta = GeneralUtils.generate_msgMeta(
config[:externalservice][:loadbalancer][:mqtttopic];
msgPurpose="embedding",
senderName="yiemagent",
senderId=sessionId,
receiverName="textembedding",
mqttBrokerAddress=config[:mqttServerInfo][:broker],
mqttBrokerPort=config[:mqttServerInfo][:port],
)
outgoingMsg = Dict(
:msgMeta => msgMeta,
:payload => Dict(
:text => [text] # must be a vector of string
)
)
response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=120, maxattempt=3)
embedding = response[:response][:embeddings]
return embedding
end
function findSimilarTextFromVectorDB(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 = getEmbedding(text)[1]
# 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 similarSQLVectorDB(query; maxdistance::Integer=100)
tablename = "sqlllm_decision_repository"
# get embedding of the query
df = findSimilarTextFromVectorDB(query, tablename,
"function_input_embedding", executeSQLVectorDB)
# 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
function insertSQLVectorDB(query::T1, SQL::T2; maxdistance::Integer=3) where {T1<:AbstractString, T2<:AbstractString}
tablename = "sqlllm_decision_repository"
# get embedding of the query
# query = state[:thoughtHistory][:question]
df = findSimilarTextFromVectorDB(query, tablename,
"function_input_embedding", executeSQLVectorDB)
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 = getEmbedding(query)[1]
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)
_ = executeSQLVectorDB(sql)
end
end
function similarSommelierDecision(recentevents::T1; maxdistance::Integer=3
)::Union{AbstractDict, Nothing} where {T1<:AbstractString}
tablename = "sommelier_decision_repository"
# find similar
println("\n~~~ search vectorDB for this: $recentevents ", @__FILE__, " ", @__LINE__)
df = findSimilarTextFromVectorDB(recentevents, tablename,
"function_input_embedding", executeSQLVectorDB)
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.parsefile(_output_str))
return output
else
println("\n~~~ similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__)
return nothing
end
end
function insertSommelierDecision(recentevents::T1, decision::T2; maxdistance::Integer=5
) where {T1<:AbstractString, T2<:AbstractDict}
tablename = "sommelier_decision_repository"
# find similar
df = findSimilarTextFromVectorDB(recentevents, tablename,
"function_input_embedding", executeSQLVectorDB)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
recentevents_embedding = getEmbedding(recentevents)[1]
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)
_ = executeSQLVectorDB(sql)
else
println("~~~ similar decision previously cached, distance $distance ", @__FILE__, " ", @__LINE__)
end
end
# keepaliveChannel_2::Channel{Dict} = Channel{Dict}(8)
latestUserMsgTimeStamp::DateTime = Dates.now()
externalFunction = (
getEmbedding=getEmbedding,
text2textInstructLLM=text2textInstructLLM,
executeSQL=executeSQL,
similarSQLVectorDB=similarSQLVectorDB,
insertSQLVectorDB=insertSQLVectorDB,
similarSommelierDecision=similarSommelierDecision,
insertSommelierDecision=insertSommelierDecision,
)
agent = YiemAgent.sommelier(
externalFunction;
name="Jane",
id=sessionId, # agent instance id
retailername="Yiem",
llmFormatName="qwen3"
)
# user chat loop
while true
# check for new user message
if isready(receiveUserMsgChannel)
incomingMsg = take!(receiveUserMsgChannel)
incoming_msgMeta = incomingMsg[:msgMeta]
incomingPayload = incomingMsg[:payload]
latestUserMsgTimeStamp = Dates.now()
# make sure the message has :text key because YiemAgent use this key for incoming user msg
if haskey(incomingPayload, :text)
# skip, msg already has correct key name
elseif haskey(incomingPayload, :txt)
# change key name to text
incomingPayload[:text] = incomingPayload[:txt]
else
error("\n no :txt or :text key in the message.")
end
# reset agent
if occursin("newtopic", incomingPayload[:text]) ||
occursin("Newtopic", incomingPayload[:text]) ||
occursin("New topic", incomingPayload[:text]) ||
occursin("new topic", incomingPayload[:text])
# YiemAgent.clearhistory(agent)
agent = YiemAgent.sommelier(
externalFunction;
name="Janie",
id=sessionId, # agent instance id
retailername="Yiem",
)
# sending msg back to sender i.e. LINE
msgMeta = GeneralUtils.generate_msgMeta(
incomingMsg[:msgMeta][:replyTopic];
senderName="wine_assistant_backend",
senderId=sessionId,
replyToMsgId=incomingMsg[:msgMeta][:msgId],
mqttBrokerAddress=config[:mqttServerInfo][:broker],
mqttBrokerPort=config[:mqttServerInfo][:port],
)
outgoingMsg = Dict(
:msgMeta => msgMeta,
:payload => Dict(
:alias => agent.name, # will be shown in frontend as agent name
:text => "Okay. What shall we talk about?"
)
)
_ = GeneralUtils.sendMqttMsg(outgoingMsg)
println("--> outgoingMsg ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
pprintln(outgoingMsg)
else
usermsg = incomingPayload
if incoming_msgMeta[:msgPurpose] == "initialize"
println("\n-- Initializing... ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
end
# send prompt
result = YiemAgent.conversation(agent;
userinput=usermsg,
maximumMsg=50)
# Ken's bot use [br] for newline character '\n'
# result = replace(result, '\n'=>"[br]")
if incoming_msgMeta[:msgPurpose] == "initialize"
println("\n-- Initialized. Ready! waiting for request at:\n$(config[:servicetopic][:mqtttopic]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
end
msgMeta = GeneralUtils.generate_msgMeta(
incomingMsg[:msgMeta][:replyTopic];
senderName="wine_assistant_backend",
senderId=string(uuid4()),
replyToMsgId=incomingMsg[:msgMeta][:msgId],
mqttBrokerAddress=config[:mqttServerInfo][:broker],
mqttBrokerPort=config[:mqttServerInfo][:port],
)
outgoingMsg = Dict(
:msgMeta => msgMeta,
:payload => Dict(
:alias => agent.name, # will be shown in frontend as agent name
:text => result
)
)
_ = GeneralUtils.sendMqttMsg(outgoingMsg)
println("\n--> outgoingMsg ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
pprintln(outgoingMsg)
# jpg_as_juliaStr = nothing
# prompt = nothing
# if haskey(payload, "img")
# url_or_base64 = payload["img"]
# if startswith(url_or_base64, "http")
# # img in http
# julia_rgb_img, cv2_bgr_img = ImageUtils.url_to_cv2_image(url_or_base64)
# _, buffer = cv2.imencode(".jpg", cv2_bgr_img)
# jpg_as_pyStr = base64.b64encode(buffer).decode("utf-8")
# jpg_as_juliaStr = pyconvert(String, jpg_as_pyStr)
# else
# # img in base64
# cv2_bgr_img = payload["img"]
# jpg_as_juliaStr = pyconvert(String, jpg_as_pyStr)
# end
# end
end
else
# println("\n no msg")
end
if haskey(agent.memory[:events][end], :thought)
lastAssistantAction = agent.memory[:events][end][:thought][:action_name]
if lastAssistantAction == "END_CONVER_GUIDELINE" # store thoughtDict
# save a.memory[:shortmem][:decisionlog] to disk using JSON
println("\nsaving agent.memory[:shortmem][:decisionlog] to disk")
filename = "agent_decision_log_$(Dates.now())_$(agent.id).json"
filepath = "/appfolder/app/log/$filename"
open(filepath, "w") do io
JSON.pretty(io, agent.memory[:shortmem][:decisionlog])
end
# for (i, event) in enumerate(agent.memory[:events])
# if event[:subject] == "assistant"
# # create timeline of the last 3 conversation except the last one.
# # The former will be used as caching key and the latter will be the caching target
# # in vector database
# all_recapkeys = keys(agent.memory[:recap]) #[TESTING] recap as caching
# all_recapkeys_vec = [r for r in all_recapkeys] # convert to a vector
# # select from 1 to 2nd-to-lase event (i.e. excluding the latest which is assistant's response)
# _recapkeys_vec = all_recapkeys_vec[1:i-1]
# # select only previous 3 recaps
# recapkeys_vec =
# if length(_recapkeys_vec) <= 3 # 1st message is a user's hello msg
# _recapkeys_vec # choose all
# else
# _recapkeys_vec[end-2:end]
# end
# #[PENDING] if there is specific data such as number, donot store in database
# tempmem = DataStructures.OrderedDict()
# for k in recapkeys_vec
# tempmem[k] = agent.memory[:recap][k]
# end
# recap = GeneralUtils.dictToString_noKey(tempmem)
# thoughtDict = agent.memory[:events][i][:thought] # latest assistant thoughtDict
# insertSommelierDecision(recap, thoughtDict)
# else
# # skip
# end
# end
println("\nCaching conversation process done")
break
end
end
# self terminate if too long inactivity
timediff = GeneralUtils.timedifference(latestUserMsgTimeStamp, Dates.now(), "minutes")
if timediff > timeout
result = Dict(:exitreason => "timeout", :timestamp => Dates.now())
put!(outputchannel, result)
println("Agent ID $(agent.id) timeout has been reached $timediff/$timeout minutes Send delete session msg ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# send "delete session" message to inform the main loop that this session can be deleted
sendto =
if typeof(config[:servicetopic][:mqtttopic]) <: Array
config[:servicetopic][:mqtttopic][1]
else
config[:servicetopic][:mqtttopic]
end
msgMeta = GeneralUtils.generate_msgMeta(
sendto;
senderName="session",
senderId=sessionId,
msgPurpose="delete session",
mqttBrokerAddress=config[:mqttServerInfo][:broker],
mqttBrokerPort=config[:mqttServerInfo][:port],
)
outgoingMsg = Dict(
:msgMeta => msgMeta,
:payload => nothing
)
_ = GeneralUtils.sendMqttMsg(outgoingMsg)
try disconnect(agent.mqttClient) catch end
break
end
sleep(1) # allowing on_msg_2, asyncmove above and other process to run
end
end
sessionDict = Dict{String,Any}()
incomingMsgChannel = (ch1=Channel(8),) # store msg that coming into servicetopic
# incommingInternalMsg = [] # st ore msg that coming into servicetopic internal management
keepaliveChannel::Channel{Dict} = Channel{Dict}(8)
# Define the callback for receiving messages.
function onMsgCallback_1(topic, payload)
jobj = JSON.parsefile(String(payload))
incomingMqttMsg = copy(jobj) # convert json object into julia dictionary recursively
if occursin("keepalive", topic)
put!(keepaliveChannel, incomingMqttMsg)
else
put!(incomingMsgChannel[:ch1], incomingMqttMsg)
end
end
mqttInstance = GeneralUtils.mqttClientInstance_v2(
config[:mqttServerInfo][:broker],
config[:servicetopic][:mqtttopic],
incomingMsgChannel,
keepaliveChannel,
onMsgCallback_1
)
# ------------------------------------------------------------------------------------------------ #
# this service main loop #
# ------------------------------------------------------------------------------------------------ #
function main()
sessiontimeout = 1 * 1 * 60 # timeout in minute for each instance (day * hour * minute)
initializing = false
while true
# check if mqtt connection is still up
_ = GeneralUtils.checkMqttConnection!(mqttInstance; keepaliveCheckInterval=30)
# initialize session 0
if initializing == false # send init msg
sendto =
if typeof(config[:servicetopic][:mqtttopic]) <: Array
config[:servicetopic][:mqtttopic][1]
else
config[:servicetopic][:mqtttopic]
end
msgMeta = GeneralUtils.generate_msgMeta(
sendto;
msgPurpose="initialize",
senderName="initializer",
senderId="0",
msgId= "initMsg",
replyTopic=sendto,
mqttBrokerAddress=config[:mqttServerInfo][:broker],
mqttBrokerPort=config[:mqttServerInfo][:port],
)
outgoingMsg = Dict(
:msgMeta => msgMeta,
:payload => Dict( # will be shown in frontend as agent name
:text => "Do you have full-bodied red wines under 100 USD. I don't have any other preferences."
)
)
_ = GeneralUtils.sendMqttMsg(outgoingMsg)
initializing = true
println("\n--> Initializing msg sent ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
end
# check for new message
if !isempty(incomingMsgChannel[:ch1])
msg = popfirst!(incomingMsgChannel[:ch1])
println("\n<-- incomingMsg ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
pprintln(msg)
# @spawn new runAgentInstance and store it in sessionDict
# use agent's frontend id because 1 backend agent per 1 frontend session
sessionId = msg[:msgMeta][:senderId]
sessionId = replace(sessionId, "-" => "_") # julia can't use "-" in a dict key
# check for delete session msg
if msg[:msgMeta][:msgPurpose] == "delete session"
delete!(sessionDict, sessionId)
println("sessionId $(sessionId) has been terminated ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# no session yet, create new session
elseif sessionId keys(sessionDict)
inputch = Channel{Dict}(8)
outputch = Channel{Dict}(8)
process = @spawn runAgentInstance(inputch, outputch, sessionId, config, sessiontimeout)
# process = runAgentInstance(inputch, outputch, sessionId, config, sessiontimeout) #XXX use spawn version
println("\ninstantiate agent success ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# call runAgentInstance() and store it in sessionDict to be able to check on it later
sessionDict[sessionId] = Dict(
:inputchannel => inputch,
:outputchannel => outputch,
:process => process,
)
put!(sessionDict[sessionId][:inputchannel], msg)
# ongoing session
else
println("sessionId $(sessionId) existing session ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
put!(sessionDict[sessionId][:inputchannel], msg)
end
end
# sleep is needed because MQTTClient use async. "while true" loop leave no
# chance for control to switch to on_msg()
sleep(1)
end
end
main()
+72
View File
@@ -0,0 +1,72 @@
To make **LLM-driven inference** fast while maintaining its dynamic capabilities, there are a few practices or approaches to avoid, as they could lead to performance bottlenecks or inefficiencies. Here's what *not* to do:
---
### **1. Avoid Using Overly Large Models for Every Query**
While larger LLMs like GPT-4 provide high accuracy and nuanced responses, they may slow down real-time processing due to their computational complexity. Instead:
- Use distilled or smaller models (e.g., GPT-3.5 Turbo or fine-tuned versions) for faster inference without compromising much on quality.
---
### **2. Avoid Excessive Entity Preprocessing**
Dont rely on overly complicated preprocessing steps (like advanced NER models or regex-heavy pipelines) to extract entities from the query before invoking the LLM. This could add latency. Instead:
- Design efficient prompts that allow the LLM to extract entities and generate responses simultaneously.
---
### **3. Avoid Asking the LLM Multiple Separate Questions**
Running the LLM for multiple subtasks—for example, entity extraction first and response generation second—can significantly slow down the pipeline. Instead:
- Create prompts that combine tasks into one pass, e.g., *"Identify the city name and generate a weather response for this query: 'What's the weather in London?'"*.
---
### **4. Dont Overload the LLM with Context History**
Excessively lengthy conversation history or irrelevant context in your prompts can slow down inference times. Instead:
- Provide only the relevant context for each query, trimming unnecessary parts of the conversation.
---
### **5. Avoid Real-Time Dependence on External APIs**
Using external APIs to fetch supplementary data (e.g., weather details or location info) during every query can introduce latency. Instead:
- Pre-fetch API data asynchronously and use the LLM to integrate it dynamically into responses.
---
### **6. Avoid Running LLM on Underpowered Hardware**
Running inference on CPUs or low-spec GPUs will result in slower response times. Instead:
- Deploy the LLM on optimized infrastructure (e.g., high-performance GPUs like NVIDIA A100 or cloud platforms like Azure AI) to reduce latency.
---
### **7. Skip Lengthy Generative Prompts**
Avoid prompts that encourage the LLM to produce overly detailed or verbose responses, as these take longer to process. Instead:
- Use concise prompts that focus on generating actionable or succinct answers.
---
### **8. Dont Ignore Optimization Techniques**
Failing to optimize your LLM setup can drastically impact performance. For example:
- Avoid skipping techniques like model quantization (reducing numerical precision to speed up inference) or distillation (training smaller models).
---
### **9. Dont Neglect Response Caching**
While you may not want a full caching system to avoid sunk costs, dismissing lightweight caching entirely can impact speed. Instead:
- Use temporary session-based caching for very frequent queries, without committing to a full-fledged cache infrastructure.
---
### **10. Avoid One-Size-Fits-All Solutions**
Applying the same LLM inference method to all queries—whether simple or complex—will waste processing resources. Instead:
- Route basic queries to faster, specialized models and use the LLM for nuanced or multi-step queries only.
---
### Summary: Focus on Efficient Design
By avoiding these pitfalls, you can ensure that LLM-driven inference remains fast and responsive:
- Optimize prompts.
- Use smaller models for simpler queries.
- Run the LLM on high-performance hardware.
- Trim unnecessary preprocessing or contextual steps.
Would you like me to help refine a prompt or suggest specific tools to complement your implementation? Let me know!
+1
View File
@@ -0,0 +1 @@
iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAtGVYSWZJSSoACAAAAAYAEgEDAAEAAAABAAAAGgEFAAEAAABWAAAAGwEFAAEAAABeAAAAKAEDAAEAAAACAAAAEwIDAAEAAAABAAAAaYcEAAEAAABmAAAAAAAAAEgAAAABAAAASAAAAAEAAAAGAACQBwAEAAAAMDIxMAGRBwAEAAAAAQIDAACgBwAEAAAAMDEwMAGgAwABAAAA//8AAAKgBAABAAAAgAAAAAOgBAABAAAAgAAAAAAAAABKviP0AAANMElEQVR4nO2de3BU1R3Hv7+zu9nNO9mQTQIJzxAeQkKI5MFjAgJJrEiSVmZqq2L/UdvOVO34Xx9WWzvTTutjHMdHrVbb6UyLDqC0jQ9s66ABLaIiCAgmQEhIYh6bBLLPezpnIZDdvQs3mMfde+5n5s5kz97du9nzu79zft/z+50FTExMTExMTExMTExMTExMTExMTEwMTeWWLYnigMRYITODvrsv/vU4JIUgKdXVWx0eh/s4gVv8tuC8/bt2nYeEMEiKN7H/HiLMAFGuLWC5C5JCUt/9hBmhBs7PyuoFmNR3/wgSewHpPEDU3T+CpF5AOg/gcbgfiOp8AVGu1W/9MSRDGg9QWbt5A8B+BULFlc/knxDYI81N218RD2BwDG8A2jteTkMwrAFce8fLZQgWGJCqmvqVYOxFEJZ8/XejXADXF8xd8GHbiaOnYTAMOQlsfnPn+/5u1wKQshXgX1zr+3DOT3KO+zLgWSTeEwbEsEPACGVld9lsrrO3gtNPAZqvteMBeiyTPM80NTV5YWAMbwBhhpDdeQdADwIoiHHaaYA/5O/OeXn//uf8kABpDGD0/IAzek/tOWJKdfM/X3sXEmHIOcCVEGM559gd2c45dsvW+VIagIBx/vOoNovyMCRESgOI9AJc0rtfWgOI9AJM0rtfeipqG94WByRG6pxADv4QJEdqAwDxHFLIcPr+WJBOBxihvK4ujbjjMBFndjsW/3fnzn5IiLSTQIL9kQuJIZTn8ZC0k0ApPUBVXeMKhSvNRHRhNZRzhYFWv//GjmZIhnQeoLq62qpw/uylzhcQMQV4RqwXQDKkM4DhxIz7iFAa9QSh2JrV+SNIhlRDwKoNm2YGrJZDBEpRPYHjvKIEl3zw1ustkASpPEDQan0yZucLCEmMsacgEdIYQHnd5lsAbL7qiUQ3VtTUfwuSQHLF/Cr1AKrwDlm0ASZXzB9O7uz+0KHyCmm0ASZDzA+O70e2W6wKSta3YtmGFlhtStTrCPyHK2sbqmBwmHQx/0UWVbUhOd2DpDQvFlSciX6xJNoAkzHmT5t2HoXLz156XHR9O9KzVWpCJdAGmJFjfgJEBnAYBI7lG1pEEggutTGO5Ru/DD0XdT7Rw+Ubb54Dg8Jki/nnlHTBOX0w6vzM3CHMLumSThtgMsX8jmQfrlt9Kubrlqw5BUeKTyptgBkz5mequ34VrzsJmz0Y87W2hCCWVqsbCDE8WV1fnwGDwWSJ+V2z3cgv6rnq6wsWfIXcuX3SaANMlpi/dL329Z1lN7RKow0wmWJ+rSRJpA0w2WJ+rRRJog0w2WJ+rZAk2gCTMebXSqYE2gCTNebXyhKDawNM1phfKzaDawNMtpg/rc+G6a1JsA9r/9eNrA2QYXL7R8X8G7Z+qhr2LdvjxJIPnKHN3nx2Bf9pbEfXDG3h4fkBO95+qQQBf4ThxHlNAZMl5hd3/kjnCxK8DCveyR6TNrCwss1w2gCTJeZP6bdFbfOY7B5bbez8sg7DaQNMlpi/J9cTcvuj6Zg1DNm1ASZLzO9NvDDm97m88NmDOLlgCB9s6L4mbUBcyyjaAMVbzM/AtqnF/Bvv/GRcwj4t+H0WvP2nZRgeih72ucJv2ffmzlcRJzBDxPxrxyfmH5M2sLbVENoAi/eYP2dOP/IXXH2df7zJL+oxhDbA4n2dX6zdTxXLDJA3wGRa5x9vkgygDVjjIeZniI75iYCe9lTs23V5A/CsGUMoLO0Y8zUK04PIT1Yw4Gc42GOB/wqrx8cP5KHnzOUgRAmy0GfhPKY28HvoGIrrev5RMAvH+ts/RapzbLH98uwgKlyXNwbvGmbY3pIAJcbeYYN9Duz+czGUgAbnGQf7DbC4rucfhXDFY+18wVJn+K7wrkQldMQiNdODBeUq6WJqxIE2wOK+nv+iBFy0on3SHOPCcpEudk7jW+k7b4DFW8wfiZBlS4UEzK5tv8eDveHzNDEEdA3TVSXh0o0tII17TOpZG9DlJJAhYT0n/v7I10ucCMTrAYqaVc8p7USWigTMSLhzHpqcdXso5pj+UbcFAz5CQUoQbi/hYJ815rmjcYYk4U58+bH4TalIuB+cdnK6PDX0evk6ANuhM3Q9CRyhorb+TiJ6MbJdpGpt3BotAdsswOZZvktjeecw4bVWOwJjzw3VIAmXYHgoQe3pO/c27XgJOkeXQ8BoyjZtmgbgt2rPiWIPNQm42BkIm8jlJHIsdQYnRBJetkF9gs/BH63a2OiCztG9AVgD1ieIKCpzY0ZRL/LmqUmxQFpCtA9PTxjn2/8ieXP7MH1+LyIhkFNhyqPQObo2gMqaxjoCvqN25xWvjR1atw1F/x7m6SE2oZKwTcUTEdF3q2oaNkHH6PaXQ8s2bUqyKLQLRJmRz5Wsa0V2Qey1/17vhZSNTDsPqXoffWXD4b6J+1etCUEk2IM425KpNhSsKswvfv7kycMqueVTjy6jAIEtYPkliOZGtjvzBjG7+OqJHPu7raHjWln8YSYWHkgPpZEdLXXjULn6cDOCKCA5dWQaes6khrUT0Sxvov8XAB6ADtGlByivaSwB4Y8UMUSJWH/lN4/AkTSxv+k461gKKt9yweZjoSPvVBLcWT64p/muGE5NmzGIls9c4Ep4cMU5r8ift+gfZ04cGftChWxzALH6R0x5gVS8k6jYTcsau9w7VvJaE6PaRC3B1UgRMrGKIilWMonwgh5XB3VnAF5H5v0EWq71y50IhtIC0W0Z2rxOTCMlFFuyO++FztCVAVTU1s8GqWT8ElBWcwLMOjGhXCRHy9zozbn8m9G9Li+OlLqhBTFMLa9RzxxmnB5aWdcwDzpCV5NAAp4V6fpqs+zjB3JDx2gdQMuWL6PhfhvOHShDwJ0Ox+wWOOYfUz3Pb1PQdGsbsjscocfdeR4oltj6cNuxLJw55gz/zHYFfm/EFIuQpAB/ALA+FCDoAN1IweW19bczope1nHtNWcAKw1d/vQ2+jumXmtLW/hspK/bh6+L3WkNlY2pZwmpw4PZ9TTv+Ah2giyFgxfqGLCL8Tuv5QgcYaxawr316WOcLzu1fgfHAZg+geJ32nA8Cf3x13RbtdWlGNwCLDY8RSJNuLjJxhfsfF1+nYNyYMb8X0wv7tH6YLD/3azZ4QxtAec1msUx6m5ZzhQQs1v6vBVtuB2yuzrC25OUfYTwpibE4pQYR7iiva6iB7EJQQeGiezhxIZAcvnBQGwGFaueW3CAk4IGodpuHwdV+IXb3OZSYSRxJiz4HWQOwpA0gtWIfkkvHbgABdwb8XTlgdg/IGrEMLSRhRwBnv4yWhAUceAPgB0b+V8Ypo+3EkSn97WLdTAJHqKirf5pA90S2T8sfwJoth0Mh4WhcZxxYu2M6EjwsNK3+ZFUPPqvU6orHxmDzKgzuWR362pjDA2fjK0jID08LFykge15dhO5T6dFvwPnTe9/Y+QPoiCkfAkYjiimI4y61jF/h+iM7X1C+OzvU+QLxdMl7WUgVpeDjTKAv81LnCxSPA+7d0R5cfMbS9a2hohUV7i6vrV8DHaEbA6irqxPF28+Logq1ApBYGb+huv9RiO5Jdo+/AQQHREofRRmF6mfKHMaiSvWNJhnwfHX11gsCgw7QjQH0c/vPQFgc2S42ZBAbM8Ti7MxwwxB7APTmjn+1kC2nA8xxWR0U2GfFLkubf307MlwqmcNERd7E/p9AJ0z5JFBQeWP9UgAvA+HlX2LiVtVwFEmpsVfhOgs8SO+zIXnQBrfTh+ZvdGEgItd/PCBrALa8dgQ6c8H9djjmnkBGTRMoQf1aYihw5p3DyUPZ4DxidRC0cmZh0a6240fHvoWp4SaBDz7IKvZ9vIdAUcWUItdf7NMXzxx8dya++F+4ACXgnH84My2hatu2bZNX167HIaCi+eP71To/OT1G4WWcsXhlG5IzoockIlpxasB/r9RDQGj1j+HvBEqIdJ/lN32BVOfUVf6OF2J1MH3aeZz+PFr5JWDNzPkL/3b6+JGJiVv17gHE6p9a7d+s67rgmqVt+TUeyC4YwMzF6vsKXVwdJOkMoKJm8/dAVKO20re0+iSMRvHaU0hMUZ0wrquord+KKYKmqtjD5rd+DoIo+ojK/NFceBlnuLuTMdQXLQFw8F74lMX73nk9fLHCqAkh1oDlKbXOF4gvSO1LMjIEcsJmeQLAtyf/2pNMeW3jTYz4rsm+bjxAxBub/7Vzx6Rec7LLvhm3HwJR/mReN37gk/6z9ZM6CSTYf2N2/pWgPK8Hv4YRPUDFDTfnkM3yBCc+4UZHHFWRhpZoZciwa5vy9HsDGI6sJee8jRMmfEt44qRwf/DeyZoQTr0UPAFU1jW8AiBsW5b81ARU5mrabgh7zw6hbTBq/eHVvU07xLY1hmLKpWCTqcU0AMkxDUByTAOQHF2Vhk0kZwZ92D6kbdFNidr31bhIYwCiS4MSdaxWzCFAckwDkBzTACTHkHMArtCzYPzNcX1ThXS75buJiYmJiYmJiYmJiYmJiYmJiYmJCa7I/wEjf8WA9CzV0gAAAABJRU5ErkJggg==
+1033 -1358
View File
File diff suppressed because it is too large Load Diff
+342 -376
View File
@@ -1,10 +1,10 @@
module llmfunction module llmfunction
export virtualWineUserChatbox, jsoncorrection, checkinventory, # recommendbox, export virtualWineUserChatbox, jsoncorrection, checkwine!, # recommendbox,
virtualWineUserRecommendbox, userChatbox, userRecommendbox, extractWineAttributes_1, virtualWineUserRecommendbox, userChatbox, userRecommendbox, extractWineAttributes_1,
extractWineAttributes_2, paraphrase extractWineAttributes_2, paraphrase
using HTTP, JSON3, URIs, Random, PrettyPrinting, UUIDs, Dates using HTTP, JSON, URIs, Random, PrettyPrinting, UUIDs, Dates, DataFrames, DataStructures
using GeneralUtils, SQLLLM using GeneralUtils, SQLLLM
using ..type, ..util using ..type, ..util
@@ -37,10 +37,10 @@ function virtualWineUserRecommendbox(a::T1, input
)::Union{Tuple{String, Number, Number, Bool}, Tuple{String, Nothing, Number, Bool}} where {T1<:agent} )::Union{Tuple{String, Number, Number, Bool}, Tuple{String, Nothing, Number, Bool}} where {T1<:agent}
# put in model format # put in model format
virtualWineCustomer = a.config[:externalservice][:virtualWineCustomer_1] virtualWineCustomer = a.config["externalservice"]["virtualWineCustomer_1"]
llminfo = virtualWineCustomer[:llminfo] llminfo = virtualWineCustomer["llminfo"]
prompt = prompt =
if llminfo[:name] == "llama3instruct" if llminfo["name"] == "llama3instruct"
formatLLMtext_llama3instruct("assistant", input) formatLLMtext_llama3instruct("assistant", input)
else else
error("llm model name is not defied yet $(@__LINE__)") error("llm model name is not defied yet $(@__LINE__)")
@@ -48,26 +48,26 @@ function virtualWineUserRecommendbox(a::T1, input
# send formatted input to user using GeneralUtils.sendReceiveMqttMsg # send formatted input to user using GeneralUtils.sendReceiveMqttMsg
msgMeta = GeneralUtils.generate_msgMeta( msgMeta = GeneralUtils.generate_msgMeta(
virtualWineCustomer[:mqtttopic], virtualWineCustomer["mqtttopic"],
senderName= "virtualWineUserRecommendbox", senderName= "virtualWineUserRecommendbox",
senderId= a.id, senderId= a.id,
receiverName= "virtualWineCustomer", receiverName= "virtualWineCustomer",
mqttBroker= a.config[:mqttServerInfo][:broker], mqttBroker= a.config["mqttServerInfo"]["broker"],
mqttBrokerPort= a.config[:mqttServerInfo][:port], mqttBrokerPort= a.config["mqttServerInfo"]["port"],
msgId = "dummyid" #CHANGE remove after testing finished msgId = "dummyid" #CHANGE remove after testing finished
) )
outgoingMsg = Dict( outgoingMsg = Dict(
:msgMeta=> msgMeta, "msgMeta"=> msgMeta,
:payload=> Dict( "payload"=> Dict(
:text=> prompt, "text"=> prompt,
) )
) )
result = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=120) result = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=120)
response = result[:response] response = result["response"]
return (response[:text], response[:select], response[:reward], response[:isterminal]) return (response["text"], response["select"], response["reward"], response["isterminal"])
end end
@@ -171,26 +171,26 @@ function virtualWineUserChatbox(config::T1, input::T2, virtualCustomerChatHistor
Let's begin! Let's begin!
""" """
pushfirst!(virtualCustomerChatHistory, Dict(:name=> "system", :text=> systemmsg)) pushfirst!(virtualCustomerChatHistory, Dict("name"=> "system", "text"=> systemmsg))
# replace the :user key in chathistory to allow the virtual wine customer AI roleplay # replace the :user key in chathistory to allow the virtual wine customer AI roleplay
chathistory::Vector{Dict{Symbol, Any}} = Vector{Dict{Symbol, Any}}() chathistory::Vector{Dict{String, Any}} = Vector{Dict{String, Any}}()
for i in virtualCustomerChatHistory for i in virtualCustomerChatHistory
newdict = Dict() newdict = Dict()
newdict[:name] = newdict["name"] =
if i[:name] == "user" if i["name"] == "user"
"you" "you"
elseif i[:name] == "assistant" elseif i["name"] == "assistant"
"sommelier" "sommelier"
else else
i[:name] i["name"]
end end
newdict[:text] = i[:text] newdict["text"] = i["text"]
push!(chathistory, newdict) push!(chathistory, newdict)
end end
push!(chathistory, Dict(:name=> "assistant", :text=> input)) push!(chathistory, Dict("name"=> "assistant", "text"=> input))
# put in model format # put in model format
prompt = formatLLMtext(chathistory, "llama3instruct") prompt = formatLLMtext(chathistory, "llama3instruct")
@@ -201,23 +201,23 @@ function virtualWineUserChatbox(config::T1, input::T2, virtualCustomerChatHistor
""" """
pprint(prompt) pprint(prompt)
externalService = config[:externalservice][:text2textinstruct] externalService = config["externalservice"]["text2textinstruct"]
# send formatted input to user using GeneralUtils.sendReceiveMqttMsg # send formatted input to user using GeneralUtils.sendReceiveMqttMsg
msgMeta = GeneralUtils.generate_msgMeta( msgMeta = GeneralUtils.generate_msgMeta(
externalService[:mqtttopic], externalService["mqtttopic"],
senderName= "virtualWineUserChatbox", senderName= "virtualWineUserChatbox",
senderId= string(uuid4()), senderId= string(uuid4()),
receiverName= "text2textinstruct", receiverName= "text2textinstruct",
mqttBroker= config[:mqttServerInfo][:broker], mqttBroker= config["mqttServerInfo"]["broker"],
mqttBrokerPort= config[:mqttServerInfo][:port], mqttBrokerPort= config["mqttServerInfo"]["port"],
msgId = string(uuid4()) #CHANGE remove after testing finished msgId = string(uuid4()) #CHANGE remove after testing finished
) )
outgoingMsg = Dict( outgoingMsg = Dict(
:msgMeta=> msgMeta, "msgMeta"=> msgMeta,
:payload=> Dict( "payload"=> Dict(
:text=> prompt, "text"=> prompt,
) )
) )
@@ -225,7 +225,7 @@ function virtualWineUserChatbox(config::T1, input::T2, virtualCustomerChatHistor
for attempt in 1:5 for attempt in 1:5
try try
response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=120) response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=120)
_responseJsonStr = response[:response][:text] _responseJsonStr = response["response"]["text"]
expectedJsonExample = expectedJsonExample =
""" """
Here is an expected JSON format: Here is an expected JSON format:
@@ -237,12 +237,12 @@ function virtualWineUserChatbox(config::T1, input::T2, virtualCustomerChatHistor
} }
""" """
responseJsonStr = jsoncorrection(config, _responseJsonStr, expectedJsonExample) responseJsonStr = jsoncorrection(config, _responseJsonStr, expectedJsonExample)
responseDict = copy(JSON3.read(responseJsonStr)) responseDict = copy(JSON.parsefile(responseJsonStr))
text::AbstractString = responseDict[:text] text::AbstractString = responseDict["text"]
select::Union{Nothing, Number} = responseDict[:select] == "null" ? nothing : responseDict[:select] select::Union{Nothing, Number} = responseDict["select"] == "null" ? nothing : responseDict["select"]
reward::Number = responseDict[:reward] reward::Number = responseDict["reward"]
isterminal::Bool = responseDict[:isterminal] isterminal::Bool = responseDict["isterminal"]
if text != "" if text != ""
# pass test # pass test
@@ -269,7 +269,7 @@ end
# Arguments # Arguments
- `a::T1` - `a::T1`
one of ChatAgent's agent. one of ChatAgent's agent.
- `input::T2` - `thoughtdict::AbstractDict`
# Return # Return
A JSON string of available wine A JSON string of available wine
@@ -281,36 +281,31 @@ julia> input = "{\"food\": \"pizza\", \"occasion\": \"anniversary\"}"
julia> result = checkinventory(agent, input) 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\"}, }"
``` ```
# TODO
- [] update docs
- [x] implement the function
# Signature
""" """
function checkinventory(a::T1, input::T2 function checkwine!(a::T, thoughtdict::AbstractDict
) where {T1<:agent, T2<:AbstractString} )::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
println("\ncheckinventory order: $input ", @__FILE__, ":", @__LINE__, " $(Dates.now())") println("\ncheckinventory order: $(thoughtdict["action_input"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
wineattributes_1 = extractWineAttributes_1(a, input) wineattributes_1 = extractWineAttributes_1(a, thoughtdict["action_input"])
wineattributes_2 = extractWineAttributes_2(a, input) wineattributes_2 = extractWineAttributes_2(a, thoughtdict["action_input"])
_inventoryquery = "retailer name: $(a.retailername), $wineattributes_1, $wineattributes_2" retrieve_attributes = ["winery", "wine_name", "wine_id", "vintage", "region", "country", "wine_type", "grape", "serving_temperature", "sweetness", "intensity", "tannin", "acidity", "tasting_notes", "price", "currency"]
inventoryquery = "Retrieves winery, wine_name, vintage, region, country, wine_type, grape, serving_temperature, sweetness, intensity, tannin, acidity, tasting_notes, price and currency of wines that match the following criteria - {$_inventoryquery}" _inventoryquery = "$wineattributes_1, $wineattributes_2"
inventoryquery = "Retrieves $retrieve_attributes of wines that match the following criteria - {$_inventoryquery}"
println("\ncheckinventory input: $inventoryquery ", @__FILE__, ":", @__LINE__, " $(Dates.now())") println("\ncheckinventory input: $inventoryquery ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# add suppport for similarSQLVectorDB # add suppport for similarSQLVectorDB
textresult, rawresponse = SQLLLM.query(inventoryquery, a.func[:executeSQL], textresult, result_raw = SQLLLM.query(
a.func[:text2textInstructLLM], inventoryquery,
insertSQLVectorDB=a.func[:insertSQLVectorDB], a.context.executeSQL,
similarSQLVectorDB=a.func[:similarSQLVectorDB]) a.context.text2textInstructLLM;
insertSQLVectorDB=a.context.insertSQLVectorDB,
similarSQLVectorDB=a.context.similarSQLVectorDB,
llmFormatName="qwen3")
thoughtdict["action_result"] = textresult
println("\ncheckinventory result ", @__FILE__, ":", @__LINE__, " $(Dates.now())") return (thoughtdict=thoughtdict, result_raw=result_raw)
println(textresult)
return (result=textresult, rawresponse=rawresponse, success=true, errormsg=nothing)
end end
""" """
# Arguments # Arguments
@@ -323,213 +318,173 @@ end
```jldoctest ```jldoctest
julia> julia>
``` ```
# TODO
- [] update docstring
- implement the function
# Signature
""" """
function extractWineAttributes_1(a::T1, input::T2)::String where {T1<:agent, T2<:AbstractString} function extractWineAttributes_1(a::T1, input::T2; maxattempt=10
)::String where {T1<:agent, T2<:AbstractString}
systemmsg = systemmsg =
""" """
As a helpful sommelier, your task is to extract the user information from the user's query as much as possible to fill out user's preference form. <situation>
At each round of conversation, the user provides the following:
At each round of conversation, the user will give you the following: - The query: the query provided by the user.
User's query: ... </situation>
<objective>
You must follow the following guidelines: Extract information from the user's query as much as possible according to wine attributes extraction guidelines to fill out user's preference form.
- If specific information required in the preference form is not available in the query or there isn't any, mark with "NA" to indicate this. </objective>
<your responsibility includes>
Fulfill the objective.
</your responsibility includes>
<wine attributes extraction guidelines>
- If specific information required in the preference form is not available in the query or there isn't any, mark with "N/A" to indicate this.
Additionally, words like 'any' or 'unlimited' mean no information is available. Additionally, words like 'any' or 'unlimited' mean no information is available.
- Do not generate other comments. - Do not generate other comments.
</wine attributes extraction guidelines>
You should then respond to the user with: <you should then respond to the user with>
Thought: state your understanding of the current situation wine_name: name of the wine
Wine_name: name of the wine winery: name of the winery
Winery: name of the winery vintage: the year of the wine
Vintage: the year of the wine region: a region, such as Burgundy, Bordeaux, Champagne, Napa Valley, Tuscany, California, Oregon, etc. Use "or" if there are multiple regions.
Region: a region (NOT a country) where the wine is produced, such as Burgundy, Napa Valley, etc country: a country where wine is produced. Can be "Austria", "Australia", "France", "Germany", "Italy", "Portugal", "Spain", "United States". Use "or" if there are multiple countries.
Country: a country where the wine is produced. Can be "Austria", "Australia", "France", "Germany", "Italy", "Portugal", "Spain", "United States" wine_type: can be one of: "red", "white", "sparkling", "rose", "dessert" or "fortified"
Wine_type: can be one of: "red", "white", "sparkling", "rose", "dessert" or "fortified" grape_varietal: the name of the primary grape used to make the wine
Grape_varietal: the name of the primary grape used to make the wine tasting_notes: a word describe the wine's flavor, such as "butter", "oak", "fruity", "raspberry", "earthy", "floral", etc
Tasting_notes: a brief description of the wine's taste, such as "butter", "oak", "fruity", etc wine_price_min: minimum price range of wine. Example: For wine price 20, wine_price_min will be 0. For wine price 10 to 100, wine_price_min will be 10.
Wine_price: price range of wine. wine_price_max: maximum price range of wine. Example: For wine price 20, wine_price_max will be 20. For wine price 10 to 100, wine_price_max will be 100.
Occasion: the occasion the user is having the wine for occasion: the occasion the user is having the wine for
Food_to_be_paired_with_wine: food that the user will be served with the wine such as poultry, fish, steak, etc food_to_be_paired_with_wine: food that the user will be served with the wine such as poultry, fish, steak, etc
</you should then respond to the user with>
You should only respond in format as described below: <you should only respond in JSON format as described below>
Thought: ... "wine_name": "...",
Wine_name: ... "winery": "...",
Winery: ... "vintage": "...",
Vintage: ... "region": "...",
Region: ... "country": "...",
Country: ... "wine_type": "...",
Wine_type: "grape_varietal": "...",
Grape_varietal: ... "tasting_notes": "...",
Tasting_notes: ... "wine_price_min": "...",
Wine_price: ... "wine_price_max": "...",
Occasion: ... "occasion": "...",
Food_to_be_paired_with_wine: ... "food_to_be_paired_with_wine": "..."
</you should only respond in JSON format as described below>
Here are some example: <here are some examples>
User's query: red, Chenin Blanc, Riesling, 20 USD User's query: red, Chenin Blanc, Riesling, 20 USD from Tuscany, Italy or Napa Valley, USA
{"reasoning": ..., "winery": "NA", "wine_name": "NA", "vintage": "NA", "region": "NA", "country": "NA", "wine_type": "red, white", "grape_varietal": "Chenin Blanc, Riesling", "tasting_notes": "NA", "wine_price": "0-20", "occasion": "NA", "food_to_be_paired_with_wine": "NA"} "wine_name": "N/A",
"winery": "N/A",
User's query: Domaine du Collier Saumur Blanc 2019, France, white, Merlot "vintage": "N/A",
{"reasoning": ..., "winery": "Domaine du Collier", "wine_name": "Saumur Blanc", "vintage": "2019", "region": "Saumur", "country": "France", "wine_type": "white", "grape_varietal": "Merlot", "tasting_notes": "NA", "wine_price": "NA", "occasion": "NA", "food_to_be_paired_with_wine": "NA"} "region": "Tuscany or Napa Valley",
"country": "Italy or United States",
Let's begin! "wine_type": "red or white",
"grape_varietal": "Chenin Blanc or Riesling",
"tasting_notes": "citrus",
"wine_price_min": "0",
"wine_price_max": "20",
"occasion": "N/A",
"food_to_be_paired_with_wine": "N/A"
User's query: Domaine du Collier Saumur Blanc 2019, France, white, Merlot
"wine_name": "Saumur Blanc",
"winery": "Domaine du Collier",
"vintage": "2019",
"region": "Saumur",
"country": "France",
"wine_type": "white",
"grape_varietal": "Merlot",
"tasting_notes": "plum",
"wine_price_min": "N/A",
"wine_price_max": "N/A",
"occasion": "N/A",
"food_to_be_paired_with_wine": "N/A"
</here are some examples>
"""
requiredKeys = ["wine_name", "winery", "vintage", "region", "country", "wine_type", "grape_varietal", "tasting_notes", "wine_price_min", "wine_price_max", "occasion", "food_to_be_paired_with_wine"]
errornote = ""
context =
"""
<internal_context_for_assistant>
$errornote
</internal_context_for_assistant>
""" """
header = ["Thought:", "Wine_name:", "Winery:", "Vintage:", "Region:", "Country:", "Wine_type:", "Grape_varietal:", "Tasting_notes:", "Wine_price:", "Occasion:", "Food_to_be_paired_with_wine:"] input = context * input
dictkey = ["thought", "wine_name", "winery", "vintage", "region", "country", "wine_type", "grape_varietal", "tasting_notes", "wine_price", "occasion", "food_to_be_paired_with_wine"]
errornote = ""
for attempt in 1:10
#[WORKING] I should add generatequestion()
if attempt > 1 msg = Dict(
println("\nYiemAgent extractWineAttributes_1() attempt $attempt/10 ", @__FILE__, ":", @__LINE__, " $(Dates.now())") "model" => "gemma-4-E4B-it-UD-Q4_K_XL",
end "messages" => [
Dict(
"role" => "system",
"content" => [
Dict("type" => "text", "text" => systemmsg),
]
),
Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => input),
]
),
],
"temperature" => 0.7
)
usermsg = for attempt in 1:maxattempt
""" response = a.context.text2textInstructLLM(a.id, msg)
User's query: $input response = GeneralUtils.clean_json_response(response)
$errornote println("\n--- extractWineAttributes_1-1()")
""" println(response)
println("--- \n")
_prompt =
[
Dict(:name=> "system", :text=> systemmsg),
Dict(:name=> "user", :text=> usermsg)
]
# put in model format
prompt = GeneralUtils.formatLLMtext(_prompt; formatname="qwen")
response = a.func[:text2textInstructLLM](prompt)
response = GeneralUtils.remove_french_accents(response) response = GeneralUtils.remove_french_accents(response)
think, response = GeneralUtils.extractthink(response)
# check wheter all attributes are in the response responsedict = nothing
checkFlag = false try
for word in header _responsedict = JSON.parse(response)
if !occursin(word, response) responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
errornote = "$word attribute is missing in previous attempts" catch
println("Attempt $attempt $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())") println("\nERROR YiemAgent extractWineAttributes_1() failed to parse response: $response", @__FILE__, ":", @__LINE__, " $(Dates.now())")
checkFlag = true
break
end
end
checkFlag == true ? continue : nothing
# check whether response has all header
detected_kw = GeneralUtils.detect_keyword(header, response)
if 0 values(detected_kw)
errornote = "\nYiemAgent extractWineAttributes_1() response does not have all header"
continue
elseif sum(values(detected_kw)) > length(header)
errornote = "\nYiemAgent extractWineAttributes_1() response has duplicated header"
continue continue
end end
responsedict = GeneralUtils.textToDict(response, header; # check whether all answer's key points are in responsedict
dictKey=dictkey, symbolkey=true) ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
if !ispass
delete!(responsedict, :thought) errornote = errormsg
delete!(responsedict, :tasting_notes) println("\nERROR YiemAgent extractWineAttributes_1() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
delete!(responsedict, :occasion) continue
delete!(responsedict, :food_to_be_paired_with_wine) end
removekeys = ["thought", "tasting_notes", "occasion", "food_to_be_paired_with_wine", "vintage"]
println(@__FILE__, " ", @__LINE__) for i in removekeys
pprintln(responsedict) delete!(responsedict, i)
# check if winery, wine_name, region, country, wine_type, grape_varietal's value are in the query because sometime AI halucinates
checkFlag = false
for i in dictkey
j = Symbol(i)
if j [:thought, :tasting_notes, :occasion, :food_to_be_paired_with_wine]
# in case j is wine_price it needs to be checked differently because its value is ranged
if j == :wine_price
if responsedict[:wine_price] != "NA"
# check whether wine_price is in ranged number
if !occursin('-', responsedict[:wine_price])
errornote = "wine_price must be a range number"
println("ERROR YiemAgent extractWineAttributes_1() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
checkFlag = true
break
end
# check whether max wine_price is in the input
pricerange = split(responsedict[:wine_price], '-')
minprice = pricerange[1]
maxprice = pricerange[end]
if !occursin(maxprice, input)
responsedict[:wine_price] = "NA"
end
# price range like 100-100 is not good
if minprice == maxprice
errornote = "wine_price with minimum equals to maximum is not valid"
println("ERROR YiemAgent extractWineAttributes_1() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
checkFlag = true
break
end
end
else
content = responsedict[j]
if typeof(content) <: AbstractVector
content = strip.(content)
elseif occursin(',', content)
content = split(content, ",") # sometime AI generates multiple values e.g. "Chenin Blanc, Riesling"
content = strip.(content)
else
content = [content]
end
# for x in content #check whether price are mentioned in the input
# if !occursin("NA", responsedict[j]) && !occursin(x, input)
# errornote = "$x is not mentioned in the user query, you must only use the info from the query."
# println("ERROR YiemAgent extractWineAttributes_1() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
# checkFlag == true
# break
# end
# end
end
end
end end
checkFlag == true ? continue : nothing # skip the rest code if true
# remove (some text) # remove (some text)
for (k, v) in responsedict for (k, v) in responsedict
_v = replace(v, r"\(.*?\)" => "") _v = replace(v, r"\(.*?\)" => "")
responsedict[k] = _v responsedict[k] = _v
end end
result = "" result = ""
for (k, v) in responsedict for (k, v) in responsedict
# some time LLM generate text with "(some comment)". this line removes it # some time LLM generate text with "(some comment)". this line removes it
if !occursin("NA", v) && v != "" && !occursin("none", v) && !occursin("None", v) if !occursin("N/A", v) && v != "" && !occursin("none", v) && !occursin("None", v)
result *= "$k: $v, " result *= "$k: $v, "
end end
end end
#[PENDING] remove halucination. "highend dry white wine" --> "wine_type: white, occasion: special occasion, food_to_be_paired_with_wine: seafood, fish, country: France, Italy, USA, grape_varietal: Chardonnay, Sauvignon Blanc, Pinot Grigio\nwine_notes: citrus, green apple, floral"
result = result[1:end-2] # remove the ending ", " result = result[1:end-2] # remove the ending ", "
println("\n--- extractWineAttributes_1-2()")
println(result)
println("--- \n")
return result return result
end end
error("wineattributes_wordToNumber() failed to get a response") error("extractWineAttributes_1() failed to get a response")
end end
""" """
# TODO - TODO "French dry white wines with medium bod" the LLM does not recognize sweetness. use LLM self questioning to solve.
- [PENDING] "French dry white wines with medium bod" the LLM does not recognize sweetness. use LLM self questioning to solve. - TODO French Syrah, Viognier, under 100. LLM extract intensiry of 3-5. why?
- [PENDING] French Syrah, Viognier, under 100. LLM extract intensiry of 3-5. why?
""" """
function extractWineAttributes_2(a::T1, input::T2)::String where {T1<:agent, T2<:AbstractString} function extractWineAttributes_2(a::T1, input::T2)::String where {T1<:agent, T2<:AbstractString}
conversiontable = conversiontable =
""" """
<Conversion Table> <conversion_table>
Intensity level: Intensity level:
1 to 2: May correspond to "light-bodied" or a similar description. 1 to 2: May correspond to "light-bodied" or a similar description.
2 to 3: May correspond to "med light bodied", "medium light" or a similar description. 2 to 3: May correspond to "med light bodied", "medium light" or a similar description.
@@ -554,157 +509,166 @@ function extractWineAttributes_2(a::T1, input::T2)::String where {T1<:agent, T2<
3 to 4: May correspond to "medium acidity" or a similar description. 3 to 4: May correspond to "medium acidity" or a similar description.
4 to 5: May correspond to "semi high acidity" or a similar description. 4 to 5: May correspond to "semi high acidity" or a similar description.
4 to 5: May correspond to "high acidity" or a similar description. 4 to 5: May correspond to "high acidity" or a similar description.
</Conversion Table> </conversion_table>
""" """
systemmsg = systemmsg =
""" """
As an helpful sommelier, your task is to fill out the user's preference form based on the corresponding words from the user's query. <situation>
At each round of conversation, you will be given the following information:
At each round of conversation, the user will give you the current situation: conversion_table: a conversion table that maps descriptive words to their corresponding integer levels
Conversion Table: ... query: the words from the user's query that describe their preferences
User's query: ... </situation>
<objective>
The preference form requires the following information: Fill out the user's preference form based on the corresponding words from the user's query according to the guidelines.
sweetness, acidity, tannin, intensity </objective>
<your responsibility includes>
<You must follow the following guidelines> Fulfill the objective
1) If specific information required in the preference form is not available in the query or there isn't any, mark with 'NA' to indicate this. </your responsibility includes>
<guidelines>
- The preference form requires sweetness, acidity, tannin, intensity infomation
- If specific information required in the preference form is not available in the query or there isn't any, mark with 'N/A' to indicate this.
Additionally, words like 'any' or 'unlimited' mean no information is available. Additionally, words like 'any' or 'unlimited' mean no information is available.
2) Use the conversion table to convert the descriptive word level of sweetness, intensity, tannin, and acidity into a corresponding integer. - Use the conversion table to convert the descriptive word level of sweetness, intensity, tannin, and acidity into a corresponding integer.
3) Do not generate other comments. - Do not generate other comments.
</You must follow the following guidelines> </guidelines>
<you should then respond to the user with>
<You should then respond to the user with> sweetness_keyword: The exact keywords in the user's query describing the sweetness level of the wine.
Sweetness_keyword: The exact keywords in the user's query describing the sweetness level of the wine. sweetness: ( S ), where ( S ) represents integers indicating the range of sweetness levels. Example: 1-2
Sweetness: ( S ), where ( S ) represents integers indicating the range of sweetness levels. Example: 1-2 acidity_keyword: The exact keywords in the user's query describing the acidity level of the wine.
Acidity_keyword: The exact keywords in the user's query describing the acidity level of the wine. acidity: ( A ), where ( A ) represents integers indicating the range of acidity level. Example: 3-5
Acidity: ( A ), where ( A ) represents integers indicating the range of acidity level. Example: 3-5 tannin_keyword: The exact keywords in the user's query describing the tannin level of the wine.
Tannin_keyword: The exact keywords in the user's query describing the tannin level of the wine. tannin: ( T ), where ( T ) represents integers indicating the range of tannin level. Example: 1-3
Tannin: ( T ), where ( T ) represents integers indicating the range of tannin level. Example: 1-3 intensity_keyword: The exact keywords in the user's query describing the intensity level of the wine.
Intensity_keyword: The exact keywords in the user's query describing the intensity level of the wine. intensity: ( I ), where ( I ) represents integers indicating the range of intensity level. Example: 2-4
Intensity: ( I ), where ( I ) represents integers indicating the range of intensity level. Example: 2-4 </you should then respond to the user with>
</You should then respond to the user with> <you should only respond in JSON format as described below>
"sweetness_keyword": "...",
<You should only respond in format as described below> "sweetness_min": "...",
Sweetness_keyword: ... "sweetness_max": "...",
Sweetness: ... "acidity_keyword": "...",
Acidity_keyword: ... "acidity_min": "...",
Acidity: ... "acidity_max": "...",
Tannin_keyword: ... "tannin_keyword": "...",
Tannin: ... "tannin_min": "...",
Intensity_keyword: ... "tannin_max": "...",
Intensity: ... "intensity_keyword": "...",
</You should only respond in format as described below> "intensity_min": "...",
"intensity_max": "..."
<Here are some examples> </you should only respond in JSON format as described below>
<here are some examples>
User's query: I want a wine with a medium-bodied, low acidity, medium tannin. User's query: I want a wine with a medium-bodied, low acidity, medium tannin.
Sweetness_keyword: NA "sweetness_keyword": "N/A",
Sweetness: NA "sweetness_min": "N/A",
Acidity_keyword: low acidity "sweetness_max": "N/A",
Acidity: 1-2 "acidity_keyword": "low acidity",
Tannin_keyword: medium tannin "acidity_min": 1,
Tannin: 3-4 "acidity_max": 2,
Intensity_keyword: medium-bodied "tannin_keyword": "medium tannin",
Intensity: 3-4 "tannin_min": 3,
"tannin_max": 4,
"intensity_keyword": "medium-bodied",
"intensity_min": 3,
"intensity_max": 4
User's query: German red wine, under 100, pairs with spicy food User's query: German red wine, under 100, pairs with spicy food.
Sweetness_keyword: NA "sweetness_keyword": "N/A",
Sweetness: NA "sweetness_min": "N/A",
Acidity_keyword: NA "sweetness_max": "N/A",
Acidity: NA "acidity_keyword": "N/A",
Tannin_keyword: NA "acidity_min": "N/A",
Tannin: NA "acidity_max": "N/A",
Intensity_keyword: NA "tannin_keyword": "N/A",
Intensity: NA "tannin_min": "N/A",
</Here are some examples> "tannin_max": "N/A",
"intensity_keyword": "N/A",
Let's begin! "intensity_min": "N/A",
"intensity_max": "N/A"
<here are some examples>
""" """
header = ["Sweetness_keyword:", "Sweetness:", "Acidity_keyword:", "Acidity:", "Tannin_keyword:", "Tannin:", "Intensity_keyword:", "Intensity:"] requiredKeys = ["sweetness_keyword", "sweetness_min", "sweetness_max",
dictkey = ["sweetness_keyword", "sweetness", "acidity_keyword", "acidity", "tannin_keyword", "tannin", "intensity_keyword", "intensity"] "acidity_keyword", "acidity_min", "acidity_max",
"tannin_keyword", "tannin_min", "tannin_max",
"intensity_keyword", "intensity_min", "intensity_max"]
errornote = "" errornote = ""
context =
"""
<internal_context_for_assistant>
$conversiontable
$errornote
</internal_context_for_assistant>
"""
input = context * input
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:10 for attempt in 1:10
usermsg = response = a.context.text2textInstructLLM(a.id, msg)
""" response = GeneralUtils.clean_json_response(response)
$conversiontable println("\n--- extractWineAttributes_2-1()")
User's query: $input println(response)
$errornote println("--- \n")
"""
_prompt = response = GeneralUtils.remove_french_accents(response)
[ think, response = GeneralUtils.extractthink(response)
Dict(:name=> "system", :text=> systemmsg), responsedict = nothing
Dict(:name=> "user", :text=> usermsg) try
] _responsedict = JSON.parse(response)
responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
# put in model format catch
prompt = GeneralUtils.formatLLMtext(_prompt; formatname="qwen") println("\nERROR YiemAgent extractWineAttributes_2() failed to parse response: $response", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
response = a.func[:text2textInstructLLM](prompt) end
# check whether response has all header # check whether all answer's key points are in responsedict
detected_kw = GeneralUtils.detect_keyword(header, response) ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
if 0 values(detected_kw) if !ispass
errornote = "\nYiemAgent extractWineAttributes_2() response does not have all header" errornote = errormsg
continue println("\nERROR YiemAgent extractWineAttributes_2() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
elseif sum(values(detected_kw)) > length(header)
errornote = "\nYiemAgent extractWineAttributes_2() response has duplicated header"
continue continue
end end
responsedict = GeneralUtils.textToDict(response, header; # delete some key words from responsedict
dictKey=dictkey, symbolkey=true)
# check whether each describing keyword is in the input to prevent halucination
for i in ["sweetness", "acidity", "tannin", "intensity"]
keyword = Symbol(i * "_keyword") # e.g. sweetness_keyword
value = responsedict[keyword]
if value != "NA" && !occursin(value, input)
errornote = "WARNING. Keyword $keyword: $value does not appear in the input. You must use information from the input only"
println("Attempt $attempt $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
end
# if value == "NA" then responsedict[i] = "NA"
# e.g. if sweetness_keyword == "NA" then sweetness = "NA"
if value == "NA"
responsedict[Symbol(i)] = "NA"
end
end
# some time LLM not put integer range
for (k, v) in responsedict for (k, v) in responsedict
if !occursin("keyword", string(k)) if k ["sweetness_keyword", "acidity_keyword", "tannin_keyword", "intensity_keyword"]
if v !== "NA" && (!occursin('-', v) || length(v) > 5) delete!(responsedict, k)
errornote = "WARNING: The non-range value {$k: $v} is not allowed. It should be specified in a range format, i.e. min-max."
println("Attempt $attempt $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
continue
end
end
end
# some time LLM says NA-2. Need to convert NA to 1
for (k, v) in responsedict
if occursin("NA", v) && occursin("-", v)
new_v = replace(v, "NA"=>"1")
responsedict[k] = new_v
end end
end end
# get result in String. Reject "N/A" value
result = "" result = ""
for (k, v) in responsedict for (k, v) in responsedict
# some time LLM generate text with "(some comment)". this line removes it if typeof(v) <: Number
if !occursin("NA", v) result *= "$k: $v, "
elseif typeof(v) == String && !occursin("N/A", v)
result *= "$k: $v, " result *= "$k: $v, "
end end
end end
result = result[1:end-2] # remove the ending ", " result = result[1:end-2] # remove the ending ", "
println("\n--- extractWineAttributes_2-2()")
println(result)
println("--- \n")
return result return result
end end
error("wineattributes_wordToNumber() failed to get a response") error("extractWineAttributes_2() failed to get a response")
end end
@@ -744,31 +708,33 @@ function paraphrase(text2textInstructLLM::Function, text::String)
Let's begin! Let's begin!
""" """
#[PENDING] use JSON the same as extractWineAttributes_1 is better. change this function to use the same format use decisionMaker
header = ["Paraphrase:"] header = ["Paraphrase:"]
dictkey = ["paraphrase"] dictkey = ["paraphrase"]
errornote = "" errornote = "N/A"
response = nothing # placeholder for show when error msg show up response = nothing # placeholder for show when error msg show up
for attempt in 1:10 for attempt in 1:10
usermsg = """ usermsg = """
Text: $text Text: $text
$errornote P.S. $errornote
""" """
_prompt = _prompt =
[ [
Dict(:name => "system", :text => systemmsg), Dict("name" => "system", "text" => systemmsg),
Dict(:name => "user", :text => usermsg) Dict("name" => "user", "text" => usermsg)
] ]
# put in model format # put in model format
prompt = GeneralUtils.formatLLMtext(_prompt; formatname="qwen") prompt = GeneralUtils.formatLLMtext(_prompt, a.llmFormatName)
try try
response = text2textInstructLLM(prompt) response = text2textInstructLLM(prompt)
response = GeneralUtils.deFormatLLMtext(response, a.llmFormatName)
think, response = GeneralUtils.extractthink(response)
# sometime the model response like this "here's how I would respond: ..." # sometime the model response like this "here's how I would respond: ..."
if occursin("respond:", response) if occursin("respond:", response)
errornote = "You don't need to intro your response" errornote = "You don't need to intro your response"
@@ -780,13 +746,13 @@ function paraphrase(text2textInstructLLM::Function, text::String)
response = replace(response, '`' => "") response = replace(response, '`' => "")
response = GeneralUtils.remove_french_accents(response) response = GeneralUtils.remove_french_accents(response)
# check whether response has all header # check whether response has all answer's key points
detected_kw = GeneralUtils.detect_keyword(header, response) detected_kw = GeneralUtils.detect_keyword(header, response)
if 0 values(detected_kw) if 0 values(detected_kw)
errornote = "\nYiemAgent paraphrase() response does not have all header" errornote = "\nYiemAgent paraphrase() response does not have all answer's key points"
continue continue
elseif sum(values(detected_kw)) > length(header) elseif sum(values(detected_kw)) > length(header)
errornote = "\nnYiemAgent paraphrase() response has duplicated header" errornote = "\nnYiemAgent paraphrase() response has duplicated answer's key points"
continue continue
end end
@@ -794,7 +760,7 @@ function paraphrase(text2textInstructLLM::Function, text::String)
dictKey=dictkey, symbolkey=true) dictKey=dictkey, symbolkey=true)
for i [:paraphrase] for i [:paraphrase]
if length(JSON3.write(responsedict[i])) == 0 if length(JSON.json(responsedict[i])) == 0
error("$i is empty ", @__FILE__, ":", @__LINE__, " $(Dates.now())") error("$i is empty ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
end end
end end
@@ -810,7 +776,7 @@ function paraphrase(text2textInstructLLM::Function, text::String)
println("\nparaphrase() ", @__FILE__, ":", @__LINE__, " $(Dates.now())") println("\nparaphrase() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
pprintln(Dict(responsedict)) pprintln(Dict(responsedict))
result = responsedict[:paraphrase] result = responsedict["paraphrase"]
return result return result
catch e catch e
@@ -854,7 +820,7 @@ function jsoncorrection(config::T1, input::T2, correctJsonExample::T3;
for attempt in 1:maxattempt for attempt in 1:maxattempt
try try
d = copy(JSON3.read(incorrectjson)) d = copy(JSON.parsefile(incorrectjson))
correctjson = incorrectjson correctjson = incorrectjson
return correctjson return correctjson
catch e catch e
@@ -879,10 +845,10 @@ function jsoncorrection(config::T1, input::T2, correctJsonExample::T3;
""" """
# apply LLM specific instruct format # apply LLM specific instruct format
externalService = config[:externalservice][:text2textinstruct] externalService = config["externalservice"]["text2textinstruct"]
llminfo = externalService[:llminfo] llminfo = externalService["llminfo"]
prompt = prompt =
if llminfo[:name] == "llama3instruct" if llminfo["name"] == "llama3instruct"
formatLLMtext_llama3instruct("system", _prompt) formatLLMtext_llama3instruct("system", _prompt)
else else
error("llm model name is not defied yet $(@__LINE__)") error("llm model name is not defied yet $(@__LINE__)")
@@ -890,21 +856,21 @@ function jsoncorrection(config::T1, input::T2, correctJsonExample::T3;
# send formatted input to user using GeneralUtils.sendReceiveMqttMsg # send formatted input to user using GeneralUtils.sendReceiveMqttMsg
msgMeta = GeneralUtils.generate_msgMeta( msgMeta = GeneralUtils.generate_msgMeta(
externalService[:mqtttopic], externalService["mqtttopic"],
senderName= "jsoncorrection", senderName= "jsoncorrection",
senderId= string(uuid4()), senderId= string(uuid4()),
receiverName= "text2textinstruct", receiverName= "text2textinstruct",
mqttBroker= config[:mqttServerInfo][:broker], mqttBroker= config["mqttServerInfo"]["broker"],
mqttBrokerPort= config[:mqttServerInfo][:port], mqttBrokerPort= config["mqttServerInfo"]["port"],
) )
outgoingMsg = Dict( outgoingMsg = Dict(
:msgMeta=> msgMeta, "msgMeta"=> msgMeta,
:payload=> Dict( "payload"=> Dict(
:text=> prompt, "text"=> prompt,
:kwargs=> Dict( "kwargs"=> Dict(
:max_tokens=> 512, "max_tokens"=> 512,
:stop=> ["<|eot_id|>"], "stop"=> ["<|eot_id|>"],
) )
) )
) )
@@ -927,7 +893,7 @@ end
# "thought" is step-by-step reasoning about the current situation. # "thought" is step-by-step reasoning about the current situation.
# "plan" is what to do to complete the task from the current situation. # "plan" is what to do to complete the task from the current situation.
# “action_name” is the name of the action taken, which can be one of the following functions: # “action_name” is the name of the action taken, which can be one of the following functions:
# 1) CHATBOX[text], which you can use to talk with the user. "text" is in verbal English. # 1) CHAT_BOX[text], which you can use to talk with the user. "text" is in verbal English.
# 2) WINESTOCK[query], which you can use to find info about wine in your inventory. "query" is a search term in verbal English. The best query must includes "budget", "type of wine", "characteristics of wine" and "food pairing". # 2) WINESTOCK[query], which you can use to find info about wine in your inventory. "query" is a search term in verbal English. The best query must includes "budget", "type of wine", "characteristics of wine" and "food pairing".
# "action_input" is the input to the action # "action_input" is the input to the action
# "observation" is result of the preceding immediate action. # "observation" is result of the preceding immediate action.
@@ -984,7 +950,7 @@ end
# ] # ]
# # put in model format # # put in model format
# prompt = GeneralUtils.formatLLMtext(_prompt; formatname="qwen") # prompt = GeneralUtils.formatLLMtext(_prompt, "granite3")
# prompt *= # prompt *=
# """ # """
# <|start_header_id|>assistant<|end_header_id|> # <|start_header_id|>assistant<|end_header_id|>
+325 -141
View File
@@ -1,193 +1,215 @@
module type module type
export agent, sommelier, companion export agent, sommelier, companion, virtualcustomer, agentcontext
using Dates, UUIDs, DataStructures, JSON3 using Dates, UUIDs, DataStructures, JSON, NATS
using GeneralUtils using GeneralUtils
# ---------------------------------------------- 100 --------------------------------------------- # # ---------------------------------------------- 100 --------------------------------------------- #
mutable struct agentcontext
text2textInstructLLM::Function
getTextEmbedding::Function
executeSQL::Function
similarSQLVectorDB::Function
insertSQLVectorDB::Function
similarSommelierDecision::Function
insertSommelierDecision::Function
end
abstract type agent end abstract type agent end
mutable struct companion <: agent mutable struct companion <: agent
name::String # agent name
id::String # agent id id::String # agent id
systemmsg::Union{String, Nothing} systemmsg::String # system message
tools::Dict # tools
maxHistoryMsg::Integer # e.g. 21th and earlier messages will get summarized maxHistoryMsg::Integer # e.g. 21th and earlier messages will get summarized
chathistory::Vector{Dict{String, Any}}
memory::Dict{String, Any}
context::NamedTuple # NamedTuple of functions
llmFormatName::String
end
function companion(
context::agentcontext # NamedTuple of functions
;
name::String= "Assistant",
id::String= GeneralUtils.uuid4snakecase(),
maxHistoryMsg::Integer= 20,
chathistory::Vector{Dict{String, String}} = Vector{Dict{String, String}}(),
llmFormatName::String= "granite3",
systemmsg::String=
"""
Your name: $name
Your sex: Female
Your role: You are a helpful assistant.
You should follow the following guidelines:
- Focus on the latest conversation.
- Your like to be short and concise.
Let's begin!
""",
)
tools = Dict( # update input format
"CHAT_BOX"=> Dict(
"description" => "- CHAT_BOX which you can use to talk with the user. The input is your intentions for the dialogue. Be specific.",
),
)
""" Memory """ Memory
Ref: Chat prompt format https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/discussions/3 Ref: Chat prompt format https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/discussions/3
NO "system" message in chathistory because I want to add it at the inference time NO "system" message in chathistory because I want to add it at the inference time
chathistory= [ chathistory= [
Dict(:name=>"user", :text=> "Wassup!", :timestamp=> Dates.now()), Dict("name"=>"user", "text"=> "Wassup!", "timestamp"=> Dates.now()),
Dict(:name=>"assistant", :text=> "Hi I'm your assistant.", :timestamp=> Dates.now()), Dict("name"=>"assistant", "text"=> "Hi I'm your assistant.", "timestamp"=> Dates.now()),
] ]
""" """
chathistory::Vector{Dict{Symbol, Any}} memory = Dict{String, Any}(
memory::Dict{Symbol, Any} "events"=> Vector{Dict{String, Any}}(),
"state"=> Dict{String, Any}(), # state of the agent
# communication function "recap"=> OrderedDict{String, Any}(), # recap summary of the conversation
text2textInstructLLM::Function )
end
function companion(
text2textInstructLLM::Function
;
id::String= string(uuid4()),
systemmsg::Union{String, Nothing}= nothing,
maxHistoryMsg::Integer= 20,
chathistory::Vector{Dict{Symbol, String}} = Vector{Dict{Symbol, String}}(),
)
memory = Dict{Symbol, Any}(
:chatbox=> "",
:shortmem=> OrderedDict{Symbol, Any}(),
:events=> Vector{Dict{Symbol, Any}}(),
:state=> Dict{Symbol, Any}(),
)
newAgent = companion( newAgent = companion(
id, name,
systemmsg, id,
maxHistoryMsg, systemmsg,
chathistory, tools,
memory, maxHistoryMsg,
text2textInstructLLM chathistory,
) memory,
context,
llmFormatName
)
return newAgent return newAgent
end end
""" A sommelier agent.
# Arguments
- `mqttClient::Client`
MQTTClient's client
- `msgMeta::Dict{Symbol, Any}`
A dict contain info about a message.
- `config::Dict{Symbol, Any}`
Config info for an agent. Contain mqtt topic for internal use and other info.
# Keyword Arguments
- `name::String`
Agent's name
- `id::String`
Agent's ID
- `tools::Dict{Symbol, Any}`
Agent's tools
- `maxHistoryMsg::Integer`
max history message
# Return
- `nothing`
# Example
```jldoctest
julia> using YiemAgent, MQTTClient, GeneralUtils
julia> msgMeta = GeneralUtils.generate_msgMeta(
"N/A",
replyTopic = "/testtopic/prompt"
)
julia> tools= Dict(
:chatbox=>Dict(
:name => "chatbox",
:description => "Useful only for when you need to ask the user for more info or context. Do not ask the user their own question.",
:input => "Input should be a text.",
:output => "" ,
:func => nothing,
),
)
julia> agentConfig = Dict(
:receiveprompt=>Dict(
:mqtttopic=> "/testtopic/prompt", # topic to receive prompt i.e. frontend send msg to this topic
),
:receiveinternal=>Dict(
:mqtttopic=> "/testtopic/internal", # receive topic for model's internal
),
:text2text=>Dict(
:mqtttopic=> "/text2text/receive",
),
)
julia> client, connection = MakeConnection("test.mosquitto.org", 1883)
julia> agent = YiemAgent.bsommelier(
client,
msgMeta,
agentConfig,
name= "assistant",
id= "555", # agent instance id
tools=tools,
)
```
# TODO
- [] update docstring
- [x] implement the function
# Signature
"""
mutable struct sommelier <: agent mutable struct sommelier <: agent
name::String # agent name name::String # agent name
id::String # agent id id::String # agent id
retailername::String retailername::String
tools::Dict tools::Dict
maxHistoryMsg::Integer # e.g. 21th and earlier messages will get summarized maxHistoryMsg::Integer # e.g. 21th and earlier messages will get summarized
chathistory::Vector{Dict{String, Any}}
""" Memory memory::Dict{String, Any}
Ref: Chat prompt format https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/discussions/3 context::agentcontext
NO "system" message in chathistory because I want to add it at the inference time llmFormatName::String
chathistory= [
Dict(:name=>"user", :text=> "Wassup!", :timestamp=> Dates.now()),
Dict(:name=>"assistant", :text=> "Hi I'm your assistant.", :timestamp=> Dates.now()),
]
"""
chathistory::Vector{Dict{Symbol, Any}}
memory::Dict{Symbol, Any}
func # NamedTuple of functions
end end
""" A sommelier agent.
# Arguments
- `context::agentcontext`
Application context containing shared functions for LLM, SQL, and vector database operations.
# Keyword Arguments
- `name::String`
Agent's name. Default: `"Assistant"`
- `id::String`
Agent's ID. Default: generated UUID string.
- `retailername::String`
Retailer name associated with the sommelier. Default: `"retailer_name"`
- `maxHistoryMsg::Integer`
Maximum history messages. Default: `20`
- `chathistory::Vector{Dict{String, String}}`
Chat history. Default: empty vector.
- `llmFormatName::String`
LLM format name. Default: `"granite3"`
# Return
- `sommelier`: An instantiated sommelier agent.
# Example
```julia
julia> using YiemAgent
julia> context = agentcontext(
text2textInstructLLM,
getTextEmbedding,
executeSQL,
similarSQLVectorDB,
insertSQLVectorDB,
similarSommelierDecision,
insertSommelierDecision
)
julia> agent = sommelier(context, name="WineExpert", id="123", retailername="MyWineShop")
```
"""
function sommelier( function sommelier(
func, # NamedTuple of functions context::agentcontext, # app context
; ;
name::String= "Assistant", name::String= "Assistant",
id::String= string(uuid4()), id::String= string(uuid4()),
retailername::String= "retailer_name", retailername::String= "retailer_name",
maxHistoryMsg::Integer= 20, maxHistoryMsg::Integer= 20,
chathistory::Vector{Dict{Symbol, String}} = Vector{Dict{Symbol, String}}(), chathistory::Vector{Dict{String, Any}} = Vector{Dict{String, Any}}(),
llmFormatName::String= "granite3"
) )
tools = Dict( # update input format tools = Dict( # update input format
"chatbox"=> Dict( "chatbox"=> Dict(
:description => "<askbox tool description>Useful for when you need to ask the user for more context. Do not ask the user their own question.</askbox tool description>", "description" => "<askbox tool description>Useful for when you need to ask the user for more context. Do not ask the user their own question.</askbox tool description>",
:input => """<input>Input is a text in JSON format.</input><input example>{\"Q1\": \"How are you doing?\", \"Q2\": \"How may I help you?\"}</input example>""", "input" => """<input>Input is a text in JSON format.</input><input example>{\"Q1\": \"How are you doing?\", \"Q2\": \"How may I help you?\"}</input example>""",
:output => "" , "output" => "" ,
), ),
"winestock"=> Dict( "winestock"=> Dict(
:description => "<winestock tool description>A handy tool for searching wine in your inventory that match the user preferences.</winestock tool description>", "description" => "<winestock tool description>A handy tool for searching wine in your inventory that match the user preferences.</winestock tool description>",
:input => """<input>Input is a JSON-formatted string that contains a detailed and precise search query.</input><input example>{\"wine type\": \"rose\", \"price\": \"max 35\", \"sweetness level\": \"sweet\", \"intensity level\": \"light bodied\", \"Tannin level\": \"low\", \"Acidity level\": \"low\"}</input example>""", "input" => """<input>Input is a JSON-formatted string that contains a detailed and precise search query.</input><input example>{\"wine type\": \"rose\", \"price\": \"max 35\", \"sweetness level\": \"sweet\", \"intensity level\": \"light bodied\", \"Tannin level\": \"low\", \"Acidity level\": \"low\"}</input example>""",
:output => """<output>Output are wines that match the search query in JSON format.""", "output" => """<output>Output are wines that match the search query in JSON format.""",
), ),
# "finalanswer"=> Dict(
# :description => "<tool description>Useful for when you are ready to recommend wines to the user.</tool description>",
# :input => """<input format>{\"finalanswer\": \"some text\"}.</input format><input example>{\"finalanswer\": \"I recommend Zena Crown Vista\"}</input example>""",
# :output => "" ,
# :func => nothing,
# ),
) )
memory = Dict{Symbol, Any}( """ Memory
:chatbox=> "",
:shortmem=> OrderedDict{Symbol, Any}( Chat history use openai format as follow:
:available_wine=> [],
:found_wine=> [], # used by decisionMaker(). This is to prevent decisionMaker() keep presenting the same wines image1_path = "test/large_image.png" ---
image1_bytes = read(image1_path) | this part must be done
image1_base64_string = base64encode(image1_bytes) | in frontend
mime_type = "image/png" | not in agent code
data1_uri = "data:<mime_type>;base64,<image1_base64_string>" ---
chathistory= [
Dict(
"role" => "system",
"content" => [
Dict("type" => "text", "text" => "You are a helpful assistant"),
]
),
Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => "<internal_context_for_assistant>
LLM context here...
</internal_context_for_assistant>
Do you know this wine? Just give me brief intro."
),
Dict(
"type" => "image_url",
"image_url" => Dict("url" => data1_uri)
),
]
),
]
shortmem = Dict(
"1"=> Dict("plan"=> "...", "action_name"=> "...", "action_input"=> "...", "action_result"=> "..."),
"2"=> Dict("plan"=> "...", "action_name"=> "...", "action_input"=> "...", "action_result"=> "..."),
...
)
"""
memory = Dict{String, Any}(
"shortmem"=> OrderedDict{String, Any}(),
"scratchpad"=> "",
"events"=> Vector{Dict{String, Any}}(),
"state"=> Dict{String, Any}(
), ),
:events=> Vector{Dict{Symbol, Any}}(), "recap"=> OrderedDict{String, Any}(),
:state=> Dict{Symbol, Any}(
),
:recap=> OrderedDict{Symbol, Any}(),
) )
newAgent = sommelier( newAgent = sommelier(
@@ -198,7 +220,169 @@ function sommelier(
maxHistoryMsg, maxHistoryMsg,
chathistory, chathistory,
memory, memory,
func context,
llmFormatName
)
systemmsg =
"""
# store_policy
- Generally speaking, the store inventory has some wines from France, the United States, Australia, Spain, and Italy, but you won't know exactly until you check your inventory.
- If you found wines in the store's database, they are in stock.
- You can only recommend wines that are currently in our inventory
- Before searching the database for wine, ensure you have at least the following information: 1) budget, 2) wine type, and 3) occasion. Additional details are always helpful. If the user is unsure, provide relevant information and gather insights to make reasonable inferences.
- Ask the user one question at a time.
- Do not ask the user about wine's flavor e.g. floral, citrusy, nutty or some thing similar as these terms cannot be used to search the database.
- Once the user has selected their wine, if you haven't already, ask the user whether they need any further assistance. Do not offer any additional services.
- Only end the conversation when the user explicitly intends to do so. When ending, ensure a polite farewell and an invitation to return in the future.
- Spicy foods should be paired only with light red wines.
- We do not sell organic, sustainable, gluten-free, and sulfite-free wine. Inform the user imediately if they are looking for these types of wines. Do not sell our wines as such.
- Gift box, gift card, and custom messages are available. Inform the user to contact our sales team.
# store_guidelines
- Greeting the customer warmly by ask them how could you help. Do not ask any other questions during this greeting.
- Customer may provide images for you to look up.
- Encourage the customer to explore different options and try new things.
- If you are unable to locate the desired item in the database after 2 attempts, it may not be available in your inventory. In such cases, inform the user that the item is unavailable and suggest an alternative instead.
- Your store carries only wine.
- Vintage 0 means non-vintage.
- Start searching the database as broadly as possible within the given information boundary to maximize the chances of finding. Avoid unnecessary parameters unless specified by the user. Refine the search subsequently.
# situation
You are having conversation with a customer.
# your role
Your name is $(newAgent.name). You are a helpful sommelier for website-based $(newAgent.retailername)'s wine store.
# objective
- Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences.
- Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences.
# your responsibility includes
- According to the store's policy and guidelines, and make an informed decision about what available_actions you need to use to achieve the objective.
- Keep the conversation with the customer going smoothly
# your responsibility does NOT includes
- Requesting the user to place an order, make a purchase, or confirm the order. These are the job of our sales team at the store.
- Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store.
- Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store.
# you should then respond to the user with interleaving plan, action_name, action_input
1) **plan**, Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
2) **action_name**, (Typically corresponds to the execution of the first step in your plan) Can be one of the available_actions name
3) **action_input**, The input to the action you are about to perform according to your plan.
After the action is executed you gets "action_result". It is the output from the action you selected.
# you should only respond in JSON format as described below
"plan": "...",
"action_name": "...",
"action_input": "..."
# available actions
**CHAT_BOX**, which you can use to talk with the user. The input is dialogue you want to chat with the user according to your plan.
**CHECK_WINE**, allows you to check information about wines you want in your inventory's database. The input is text that specify supported search criteria includeing: retailer_name, wine price, winery, name, vintage, region, country, type, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity.
Example query 1: "Dry, full-bodied red wine from 1) region: Burgundy, country: France or 2) region: Tuscany, country: Italy. Grape varietal: Merlot or Syrah. price 100 to 1000 USD."
Example query 2: "Red or white wine, medium tannin, price under 700 USD"
Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
**WINE_PRESENTATION_GUIDELINE**, which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
**END_CONVER_GUIDELINE**, which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
"""
system_msg = Dict(
"role" => "system",
"content" => [
Dict("type" => "text", "text" => systemmsg),
]
)
push!(newAgent.chathistory, system_msg)
return newAgent
end
mutable struct virtualcustomer <: agent
name::String # agent name
id::String # agent id
systemmsg::String # system message
tools::Dict
maxHistoryMsg::Integer # e.g. 21th and earlier messages will get summarized
chathistory::Vector{Dict{String, Any}}
memory::Dict{String, Any}
context # NamedTuple of functions
llmFormatName::String
end
function virtualcustomer(
context, # NamedTuple of functions
;
name::String= "Assistant",
id::String= string(uuid4()),
maxHistoryMsg::Integer= 20,
chathistory::Vector{Dict{String, String}} = Vector{Dict{String, String}}(),
llmFormatName::String= "granite3",
systemmsg::String=
"""
Your name: $name
Your sex: Female
Your role: You are a helpful assistant.
You should follow the following guidelines:
- Focus on the latest conversation.
- Your like to be short and concise.
Let's begin!
""",
)
tools = Dict( # update input format
"chatbox"=> Dict(
"description" => "<askbox tool description>Useful for when you need to ask the user for more context. Do not ask the user their own question.</askbox tool description>",
"input" => """<input>Input is a text in JSON format.</input><input example>{\"Q1\": \"How are you doing?\", \"Q2\": \"How may I help you?\"}</input example>""",
"output" => "" ,
),
)
""" Memory
Ref: Chat prompt format is openai
chathistory = [
Dict(
"role" => "system",
"content" => [
Dict("type" => "text", "text" => system_msg),
]
),
Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => "Do you know this wine? Just give me brief intro."),
Dict(
"type" => "image_url",
"image_url" => Dict("url" => data1_uri)
)
]
)
]
"""
memory = Dict{String, Any}(
"shortmem"=> OrderedDict{String, Any}(
),
"scratchpad"=> "",
"events"=> Vector{Dict{String, Any}}(),
"state"=> Dict{String, Any}(
),
"recap"=> OrderedDict{String, Any}(),
)
newAgent = virtualcustomer(
name,
id,
systemmsg,
tools,
maxHistoryMsg,
chathistory,
memory,
context,
llmFormatName
) )
return newAgent return newAgent
+160 -272
View File
@@ -1,9 +1,10 @@
module util module util
export clearhistory, addNewMessage, chatHistoryToText, eventdict, noises, createTimeline, export clearhistory, addNewMessage, chatHistoryToText, eventdict, noises, createTimeline,
availableWineToText availableWineToText, createEventsLog, createChatLog, checkAgentResponse_JSON,
checkAgentResponse_text
using UUIDs, Dates, DataStructures, HTTP, JSON3 using UUIDs, Dates, DataStructures, HTTP, JSON
using GeneralUtils using GeneralUtils
using ..type using ..type
@@ -25,16 +26,16 @@ julia> client, connection = MakeConnection("test.mosquitto.org", 1883)
julia> connect(client, connection) julia> connect(client, connection)
julia> msgMeta = GeneralUtils.generate_msgMeta("testtopic") julia> msgMeta = GeneralUtils.generate_msgMeta("testtopic")
julia> agentConfig = Dict( julia> agentConfig = Dict(
:receiveprompt=>Dict( "receiveprompt"=>Dict(
:mqtttopic=> "testtopic/receive", "mqtttopic"=> "testtopic/receive",
), ),
:receiveinternal=>Dict( "receiveinternal"=>Dict(
:mqtttopic=> "testtopic/internal", "mqtttopic"=> "testtopic/internal",
), ),
:text2text=>Dict( "text2text"=>Dict(
:mqtttopic=> "testtopic/text2text", "mqtttopic"=> "testtopic/text2text",
), ),
) )
julia> a = YiemAgent.sommelier( julia> a = YiemAgent.sommelier(
client, client,
msgMeta, msgMeta,
@@ -51,14 +52,25 @@ julia> YiemAgent.clearhistory(a)
""" """
function clearhistory(a::T) where {T<:agent} function clearhistory(a::T) where {T<:agent}
empty!(a.chathistory) empty!(a.chathistory)
empty!(a.memory[:shortmem]) empty!(a.memory["shortmem"])
empty!(a.memory[:events]) empty!(a.memory["events"])
a.memory[:chatbox] = "" a.memory["chatbox"] = ""
end end
""" Add new message to agent. """ Add new message to agent.
messages => Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => "Describe this image for me"),
Dict(
"type" => "image_url",
"image_url" => Dict("url" => data_uri)
)
]
)
Arguments\n Arguments\n
----- -----
a::agent a::agent
@@ -75,44 +87,24 @@ end
Example\n Example\n
----- -----
```jldoctest ```jldoctest
julia> using YiemAgent, MQTTClient, GeneralUtils
julia> client, connection = MakeConnection("test.mosquitto.org", 1883)
julia> connect(client, connection)
julia> msgMeta = GeneralUtils.generate_msgMeta("testtopic")
julia> agentConfig = Dict(
:receiveprompt=>Dict(
:mqtttopic=> "testtopic/receive",
),
:receiveinternal=>Dict(
:mqtttopic=> "testtopic/internal",
),
:text2text=>Dict(
:mqtttopic=> "testtopic/text2text",
),
)
julia> a = YiemAgent.sommelier(
client,
msgMeta,
agentConfig,
)
julia> YiemAgent.addNewMessage(a, "user", "hello")
``` ```
Signature\n Signature\n
----- -----
""" """
function addNewMessage(a::T1, name::String, text::T2; function addNewMessage(a::T1, name::String, userinput::T2;
maximumMsg::Integer=20) where {T1<:agent, T2<:AbstractString} 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
#[PENDING] 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
d = Dict(:name=> name, :text=> text, :timestamp=> Dates.now()) userinput["timestamp"] = Dates.now()
push!(a.chathistory, d) push!(a.chathistory, userinput)
end end
end end
@@ -137,7 +129,7 @@ This function takes in a vector of dictionaries and outputs a single string wher
julia> using Revise julia> using Revise
julia> using GeneralUtils julia> using GeneralUtils
julia> vecd = [Dict(:name => "John", :text => "Hello"), Dict(:name => "Jane", :text => "Goodbye")] julia> vecd = [Dict("name" => "John", "text" => "Hello"), Dict("name" => "Jane", "text" => "Goodbye")]
julia> GeneralUtils.vectorOfDictToText(vecd, withkey=true) julia> GeneralUtils.vectorOfDictToText(vecd, withkey=true)
"John> Hello\nJane> Goodbye\n" "John> Hello\nJane> Goodbye\n"
``` ```
@@ -154,11 +146,11 @@ function chatHistoryToText(vecd::Vector; withkey=true, range=nothing)::String
# Loop through each dictionary in the input vector # Loop through each dictionary in the input vector
for d in elements for d in elements
# Extract the 'name' and 'text' keys from the dictionary # Extract the 'name' and 'text' keys from the dictionary
name = d[:name] name = titlecase(d[:name])
_text = d[:text] _text = d[:text]
# Append the formatted string to the text variable # Append the formatted string to the text variable
text *= "$name:> $_text \n" text *= "$name> $_text \n"
end end
else else
# Loop through each dictionary in the input vector # Loop through each dictionary in the input vector
@@ -208,9 +200,9 @@ end
The subject or entity associated with the event The subject or entity associated with the event
- `thought::Union{AbstractDict, Nothing}` - `thought::Union{AbstractDict, Nothing}`
Any associated thoughts or metadata Any associated thoughts or metadata
- `actionname::Union{String, Nothing}` - `action_name::Union{String, Nothing}`
The name of the action performed (e.g., "CHAT", "CHECKINVENTORY") The name of the action performed (e.g., "CHAT", "CHECKINVENTORY")
- `actioninput::Union{String, Nothing}` - `action_input::Union{String, Nothing}`
Input or parameters for the action Input or parameters for the action
- `location::Union{String, Nothing}` - `location::Union{String, Nothing}`
Where the event took place Where the event took place
@@ -231,27 +223,30 @@ function eventdict(;
timestamp::Union{DateTime, Nothing}=nothing, timestamp::Union{DateTime, Nothing}=nothing,
subject::Union{String, Nothing}=nothing, subject::Union{String, Nothing}=nothing,
thought::Union{AbstractDict, Nothing}=nothing, thought::Union{AbstractDict, Nothing}=nothing,
actionname::Union{String, Nothing}=nothing, # "CHAT", "CHECKINVENTORY", "PRESENTBOX", etc action_name::Union{String, Nothing}=nothing, # "CHAT", "CHECKINVENTORY", "PRESENT_WINE_GUIDELINE", etc
actioninput::Union{String, Nothing}=nothing, action_input::Union{String, Nothing}=nothing,
location::Union{String, Nothing}=nothing, location::Union{String, Nothing}=nothing,
equipment_used::Union{String, Nothing}=nothing, equipment_used::Union{String, Nothing}=nothing,
material_used::Union{String, Nothing}=nothing, material_used::Union{String, Nothing}=nothing,
outcome::Union{String, Nothing}=nothing, observation::Union{String, Nothing}=nothing,
note::Union{String, Nothing}=nothing, note::Union{String, Nothing}=nothing,
) )
return Dict{Symbol, Any}(
:event_description=> event_description, d = Dict{String, Any}(
:timestamp=> timestamp, "event_description"=> event_description,
:subject=> subject, "timestamp"=> timestamp,
:thought=> thought, "subject"=> subject,
:actionname=> actionname, "thought"=> thought,
:actioninput=> actioninput, "action_name"=> action_name,
:location=> location, "action_input"=> action_input,
:equipment_used=> equipment_used, "location"=> location,
:material_used=> material_used, "equipment_used"=> equipment_used,
:outcome=> outcome, "material_used"=> material_used,
:note=> note, "observation"=> observation,
) "note"=> note,
)
return d
end end
@@ -259,22 +254,22 @@ end
# Arguments # Arguments
- `events::T1` - `events::T1`
Vector of event dictionaries containing subject, actioninput and optional outcome fields Vector of event dictionaries containing subject, action_input and optional outcome fields
Each event dictionary should have the following keys: Each event dictionary should have the following keys:
- :subject - The subject or entity performing the action - :subject - The subject or entity performing the action
- :actioninput - The action or input performed by the subject - :action_input - The action or input performed by the subject
- :outcome - (Optional) The result or outcome of the action - :observation - (Optional) The result or outcome of the action
# Returns # Returns
- `timeline::String` - `timeline::String`
A formatted string representing the events with their subjects, actions, and optional outcomes A formatted string representing the events with their subjects, actions, and optional outcomes
Format: "{index}) {subject}> {actioninput} {outcome}\n" for each event Format: "{index}) {subject}> {action_input} {outcome}\n" for each event
# Example # Example
events = [ events = [
Dict(:subject => "User", :actioninput => "Hello", :outcome => nothing), Dict("subject" => "User", "action_input" => "Hello", "observation" => nothing),
Dict(:subject => "Assistant", :actioninput => "Hi there!", :outcome => "with a smile") Dict("subject" => "Assistant", "action_input" => "Hi there!", "observation" => "with a smile")
] ]
timeline = createTimeline(events) timeline = createTimeline(events)
# 1) User> Hello # 1) User> Hello
@@ -295,13 +290,17 @@ function createTimeline(events::T1; eventindex::Union{UnitRange, Nothing}=nothin
end end
# Iterate through events and format each one # Iterate through events and format each one
for (i, event) in zip(ind, events) for i in ind
event = events[i]
# If no outcome exists, format without outcome # If no outcome exists, format without outcome
if event[:outcome] === nothing # if event["action_name"] == "CHAT_BOX"
timeline *= "Event_$i $(event[:subject])> $(event[:actioninput])\n" # timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"])\n"
# If outcome exists, include it in formatting # elseif event["action_name"] == "CHECKINVENTORY" && event["observation"] === nothing
# timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"]), observation: Not done yet.\n"
if event["action_name"] == "CHECK_WINE"
timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"]), observation: $(event["observation"])\\n"
else else
timeline *= "Event_$i $(event[:subject])> $(event[:actioninput]) $(event[:outcome])\n" timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"])\\n"
end end
end end
@@ -309,223 +308,112 @@ function createTimeline(events::T1; eventindex::Union{UnitRange, Nothing}=nothin
return timeline return timeline
end end
function createEventsLog(events::T1; index::Union{UnitRange, Nothing}=nothing
) where {T1<:AbstractVector}
# Initialize empty log array
log = Dict{String, String}[]
# Determine which indices to use - either provided range or full length
ind =
if index !== nothing
[index...]
else
1:length(events)
end
# Iterate through events and format each one
for i in ind
event = events[i]
# If no outcome exists, format without outcome
if event["observation"] === nothing
subject = event["subject"]
action_name = event["action_name"]
action_input = event["action_input"]
str = "action_name: $action_name, action_input: $action_input"
d = Dict{String, String}("name"=>subject, "text"=>str)
push!(log, d)
else
subject = event["subject"]
action_name = event["action_name"]
action_input = event["action_input"]
observation = event["observation"]
str = "action_name: $action_name, action_input: $action_input, observation: $observation"
d = Dict{String, String}("name"=>subject, "text"=>str)
push!(log, d)
end
end
return log
end
function createChatLog(chatdict::T1; index::Union{UnitRange, Nothing}=nothing
) where {T1<:AbstractVector}
# Initialize empty log array
log = Dict{String, String}[]
# Determine which indices to use - either provided range or full length
ind =
if index !== nothing
[index...]
else
1:length(chatdict)
end
# Iterate through events and format each one
for i in ind
event = chatdict[i]
subject = event["name"]
text = event["text"]
d = Dict{String, String}("name"=>subject, "text"=>text)
push!(log, d)
end
return log
end
function checkAgentResponse_text(response::String, requiredHeader::T
)::Tuple where {T<:Array{String}}
detected_kw = GeneralUtils.detectKeywordVariation(requiredHeader, response)
missingkeys = [k for (k, v) in detected_kw if v === nothing]
ispass = false
errormsg = nothing
if !isempty(missingkeys)
errormsg = "$missingkeys are missing from your previous response"
ispass = false
elseif sum([length(i) for i in values(detected_kw)]) > length(requiredHeader)
errormsg = "Your previous attempt has duplicated points according to the required response format"
ispass = false
else
ispass = true
end
return (ispass, errormsg)
end
# """ Convert a single chat dictionary into LLM model instruct format.
# # Llama 3 instruct format example
# <|system|>
# You are a helpful AI assistant.<|end|>
# <|user|>
# I am going to Paris, what should I see?<|end|>
# <|assistant|>
# Paris, the capital of France, is known for its stunning architecture, art museums."<|end|>
# <|user|>
# What is so great about #1?<|end|>
# <|assistant|>
# # Arguments
# - `name::T`
# message owner name e.f. "system", "user" or "assistant"
# - `text::T`
# # Return
# - `formattedtext::String`
# text formatted to model format
# # Example
# ```jldoctest
# julia> using Revise
# julia> using YiemAgent
# julia> d = Dict(:name=> "system",:text=> "You are a helpful, respectful and honest assistant.",)
# julia> formattedtext = YiemAgent.formatLLMtext_phi3instruct(d[:name], d[:text])
# ```
# Signature
# """
# function formatLLMtext_phi3instruct(name::T, text::T) where {T<:AbstractString}
# formattedtext =
# """
# <|$name|>
# $text<|end|>\n
# """
# return formattedtext
# end
# """ Convert a single chat dictionary into LLM model instruct format.
# # Llama 3 instruct format example
# <|begin_of_text|>
# <|start_header_id|>system<|end_header_id|>
# You are a helpful assistant.
# <|eot_id|>
# <|start_header_id|>user<|end_header_id|>
# Get me an icecream.
# <|eot_id|>
# <|start_header_id|>assistant<|end_header_id|>
# Go buy it yourself at 7-11.
# <|eot_id|>
# # Arguments
# - `name::T`
# message owner name e.f. "system", "user" or "assistant"
# - `text::T`
# # Return
# - `formattedtext::String`
# text formatted to model format
# # Example
# ```jldoctest
# julia> using Revise
# julia> using YiemAgent
# julia> d = Dict(:name=> "system",:text=> "You are a helpful, respectful and honest assistant.",)
# julia> formattedtext = YiemAgent.formatLLMtext_llama3instruct(d[:name], d[:text])
# "<|begin_of_text|>\n <|start_header_id|>system<|end_header_id|>\n You are a helpful, respectful and honest assistant.\n <|eot_id|>\n"
# ```
# Signature
# """
# function formatLLMtext_llama3instruct(name::T, text::T) where {T<:AbstractString}
# formattedtext =
# if name == "system"
# """
# <|begin_of_text|>
# <|start_header_id|>$name<|end_header_id|>
# $text
# <|eot_id|>
# """
# else
# """
# <|start_header_id|>$name<|end_header_id|>
# $text
# <|eot_id|>
# """
# end
# return formattedtext
# end
# """ Convert a chat messages in vector of dictionary into LLM model instruct format.
# # Arguments
# - `messages::Vector{Dict{Symbol, T}}`
# message owner name e.f. "system", "user" or "assistant"
# - `formatname::T`
# format name to be used
# # Return
# - `formattedtext::String`
# text formatted to model format
# # Example
# ```jldoctest
# julia> using Revise
# julia> using YiemAgent
# julia> chatmessage = [
# Dict(:name=> "system",:text=> "You are a helpful, respectful and honest assistant.",),
# Dict(:name=> "user",:text=> "list me all planets in our solar system.",),
# Dict(:name=> "assistant",:text=> "I'm sorry. I don't know. You tell me.",),
# ]
# julia> formattedtext = YiemAgent.formatLLMtext(chatmessage, "llama3instruct")
# "<|begin_of_text|>\n <|start_header_id|>system<|end_header_id|>\n You are a helpful, respectful and honest assistant.\n <|eot_id|>\n <|start_header_id|>user<|end_header_id|>\n list me all planets in our solar system.\n <|eot_id|>\n <|start_header_id|>assistant<|end_header_id|>\n I'm sorry. I don't know. You tell me.\n <|eot_id|>\n"
# ```
# # Signature
# """
# function formatLLMtext(messages::Vector{Dict{Symbol, T}},
# formatname::String="llama3instruct") where {T<:Any}
# f = if formatname == "llama3instruct"
# formatLLMtext_llama3instruct
# elseif formatname == "mistral"
# # not define yet
# elseif formatname == "phi3instruct"
# formatLLMtext_phi3instruct
# else
# error("$formatname template not define yet")
# end
# str = ""
# for t in messages
# str *= f(t[:name], t[:text])
# end
# # add <|assistant|> so that the model don't generate it and I don't need to clean it up later
# if formatname == "phi3instruct"
# str *= "<|assistant|>\n"
# end
# return str
# end
# """
# Arguments\n
# -----
# Return\n
# -----
# Example\n
# -----
# ```jldoctest
# julia>
# ```
# TODO\n
# -----
# [] update docstring
# [PENDING] implement the function
# Signature\n
# -----
# """
# function iterativeprompting(a::T, prompt::String, verification::Function) where {T<:agent}
# msgMeta = GeneralUtils.generate_msgMeta(
# a.config[:externalService][:text2textinstruct],
# senderName= "iterativeprompting",
# senderId= a.id,
# receiverName= "text2textinstruct",
# )
# outgoingMsg = Dict(
# :msgMeta=> msgMeta,
# :payload=> Dict(
# :text=> prompt,
# )
# )
# success = nothing
# result = nothing
# critique = ""
# # iteration loop
# while true
# # send prompt to LLM
# response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg)
# error("--> iterativeprompting")
# # check for correctness and get feedback
# success, _critique = verification(response)
# if success
# result = response
# break
# else
# # add critique to prompt
# critique *= _critique * "\n"
# replace!(prompt, "Critique: ..." => "Critique: $critique")
# end
# end
# return (success=success, result=result)
# end
+15 -11
View File
@@ -8,8 +8,8 @@ using Base.Threads
# load config # load config
config = JSON3.read("/appfolder/app/dev/YiemAgent/test/config.json") config = JSON.parsefile("/appfolder/app/dev/YiemAgent/test/config.json")
# config = copy(JSON3.read("../mountvolume/config.json")) # config = copy(JSON.parsefile("../mountvolume/config.json"))
function executeSQL(sql::T) where {T<:AbstractString} function executeSQL(sql::T) where {T<:AbstractString}
@@ -36,7 +36,12 @@ function executeSQLVectorDB(sql)
return result return result
end end
function text2textInstructLLM(prompt::String; maxattempt::Integer=2, modelsize::String="medium") function text2textInstructLLM(prompt::String; maxattempt::Integer=3, modelsize::String="medium",
llmkwargs=Dict(
:num_ctx => 32768,
:temperature => 0.1,
)
)
msgMeta = GeneralUtils.generate_msgMeta( msgMeta = GeneralUtils.generate_msgMeta(
config[:externalservice][:loadbalancer][:mqtttopic]; config[:externalservice][:loadbalancer][:mqtttopic];
msgPurpose="inference", msgPurpose="inference",
@@ -51,10 +56,7 @@ function text2textInstructLLM(prompt::String; maxattempt::Integer=2, modelsize::
:msgMeta => msgMeta, :msgMeta => msgMeta,
:payload => Dict( :payload => Dict(
:text => prompt, :text => prompt,
:kwargs => Dict( :kwargs => llmkwargs
:num_ctx => 16384,
:temperature => 0.2,
)
) )
) )
@@ -177,7 +179,7 @@ function similarSommelierDecision(recentevents::T1; maxdistance::Integer=3
println("\n~~~ found similar decision. row id $rowid, distance $distance ", @__FILE__, " ", @__LINE__) println("\n~~~ found similar decision. row id $rowid, distance $distance ", @__FILE__, " ", @__LINE__)
output_b64 = df[1, :function_output_base64] # pick the closest match output_b64 = df[1, :function_output_base64] # pick the closest match
_output_str = String(base64decode(output_b64)) _output_str = String(base64decode(output_b64))
output = copy(JSON3.read(_output_str)) output = copy(JSON.parsefile(_output_str))
return output return output
else else
println("\n~~~ similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__) println("\n~~~ similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__)
@@ -195,9 +197,9 @@ function insertSommelierDecision(recentevents::T1, decision::T2; maxdistance::In
row, col = size(df) row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance] distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database if row == 0 || distance > maxdistance # no close enough SQL stored in the database
recentevents_embedding = a.func[:getEmbedding](recentevents)[1] recentevents_embedding = getEmbedding(recentevents)[1]
recentevents = replace(recentevents, "'" => "") recentevents = replace(recentevents, "'" => "")
decision_json = JSON3.write(decision) decision_json = JSON.json(decision)
decision_base64 = base64encode(decision_json) decision_base64 = base64encode(decision_json)
decision = replace(decision_json, "'" => "") decision = replace(decision_json, "'" => "")
@@ -237,7 +239,9 @@ a = YiemAgent.sommelier(
while true while true
print("\nyour respond: ") print("\nyour respond: ")
user_answer = readline() user_answer = readline()
response = YiemAgent.conversation(a, Dict(:text=> user_answer)) response = YiemAgent.conversation(agent;
userinput=Dict(:text=> user_answer),
maximumMsg=50)
println("\n$response") println("\n$response")
end end
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

+2 -2
View File
@@ -46,7 +46,7 @@ thoughtDict = OrderedDict(
:Observation_6=> "I don't like it. Do you have another option?", :Observation_6=> "I don't like it. Do you have another option?",
) )
_thoughtJsonStr = JSON3.write(thoughtDict) _thoughtJsonStr = JSON.json(thoughtDict)
thoughtJsonStr = _thoughtJsonStr[1:end-1] # remove } at the end thoughtJsonStr = _thoughtJsonStr[1:end-1] # remove } at the end
# @show thoughtJsonStr # @show thoughtJsonStr
@@ -100,7 +100,7 @@ Here are some examples:
Let's begin! Let's begin!
$(JSON3.write(thoughtDict)) $(JSON.json(thoughtDict))
{Thought_$nextThoughtIndice {Thought_$nextThoughtIndice
""" """
+2 -2
View File
@@ -4,7 +4,7 @@ using Base.Threads
# ---------------------------------------------- 100 --------------------------------------------- # # ---------------------------------------------- 100 --------------------------------------------- #
config = copy(JSON3.read("config.json")) config = copy(JSON.parsefile("config.json"))
instanceInternalTopic = config[:serviceInternalTopic][:mqtttopic] * "/1" instanceInternalTopic = config[:serviceInternalTopic][:mqtttopic] * "/1"
@@ -66,7 +66,7 @@ tools=Dict( # update input format
input = input =
OrderedDict{Symbol, Any}(:question => "Hello, I would like a get a bottle of wine", :thought_1 => "It's great that the user is looking for a bottle of wine. To give them a personalized recommendation, I need to know more about their preferences.", :action_1 => Dict{Symbol, Any}(:name => "chatbox", :input => "What occasion are you planning to use this wine for?"), :observation_1 => "We are holding a wedding party", :thought_2 => "A wedding party is a great occasion for a special bottle of wine. I need to know what type of food will be served, and how much the user is willing to spend.", :action_2 => Dict{Symbol, Any}(:name => "chatbox", :input => "What type of food will you be serving at the wedding?"), :observation_2 => "It will be Thai dishes.", :thought_3 => "The type of wine that pairs well with Thai dishes is usually a crisp and refreshing white wine, but I also need to consider the budget and personal preferences.", :action_3 => Dict{Symbol, Any}(:name => "chatbox", :input => "How much are you willing to spend on this bottle of wine?"), :observation_3 => "I would spend up to 50 bucks.", :thought_4 => "I have a good idea of the occasion, food, and budget. Now I need to know what type of wine the user is looking for.", :action_4 => Dict{Symbol, Any}(:name => "chatbox", :input => "What type of wine are you usually looking for? Red, White, Sparkling, Rose, Dessert or Fortified?"), :observation_4 => "I like full-bodied Red wine with low tannin.", :thought_5 => "Now that I have all the necessary information, I can start searching for a suitable wine in our inventory.", :action_5 => Dict{Symbol, Any}(:name => "winestock", :input => "red wine with low tannins"), :observation_5 => "I found the following wines in our stock: \n{\n 1: El Enemigo Cabernet Franc 2019\n2: Tantara Chardonnay 2017\n\n}\n", :thought_6 => "Now that I have the information about the wine, it's time to make a recommendation.", :action_6 => Dict{Symbol, Any}(:name => "recommendbox", :input => "El Enemigo Cabernet Franc 2019"), :observation_6 => "I don't like the one you recommend. I want dry wine.") OrderedDict{String, Any}(:question => "Hello, I would like a get a bottle of wine", :thought_1 => "It's great that the user is looking for a bottle of wine. To give them a personalized recommendation, I need to know more about their preferences.", :action_1 => Dict{String, Any}(:name => "chatbox", :input => "What occasion are you planning to use this wine for?"), :observation_1 => "We are holding a wedding party", :thought_2 => "A wedding party is a great occasion for a special bottle of wine. I need to know what type of food will be served, and how much the user is willing to spend.", :action_2 => Dict{String, Any}(:name => "chatbox", :input => "What type of food will you be serving at the wedding?"), :observation_2 => "It will be Thai dishes.", :thought_3 => "The type of wine that pairs well with Thai dishes is usually a crisp and refreshing white wine, but I also need to consider the budget and personal preferences.", :action_3 => Dict{String, Any}(:name => "chatbox", :input => "How much are you willing to spend on this bottle of wine?"), :observation_3 => "I would spend up to 50 bucks.", :thought_4 => "I have a good idea of the occasion, food, and budget. Now I need to know what type of wine the user is looking for.", :action_4 => Dict{String, Any}(:name => "chatbox", :input => "What type of wine are you usually looking for? Red, White, Sparkling, Rose, Dessert or Fortified?"), :observation_4 => "I like full-bodied Red wine with low tannin.", :thought_5 => "Now that I have all the necessary information, I can start searching for a suitable wine in our inventory.", :action_5 => Dict{String, Any}(:name => "winestock", :input => "red wine with low tannins"), :observation_5 => "I found the following wines in our stock: \n{\n 1: El Enemigo Cabernet Franc 2019\n2: Tantara Chardonnay 2017\n\n}\n", :thought_6 => "Now that I have the information about the wine, it's time to make a recommendation.", :action_6 => Dict{String, Any}(:name => "recommendbox", :input => "El Enemigo Cabernet Franc 2019"), :observation_6 => "I don't like the one you recommend. I want dry wine.")
result = YiemAgent.jsoncorrection(a, input) result = YiemAgent.jsoncorrection(a, input)
+223
View File
@@ -0,0 +1,223 @@
using JSON, Dates, UUIDs, PrettyPrinting, Base64, NATS, HTTP
using GeneralUtils, msghandler
config = JSON.parsefile("./appconfig.json")
agent_conn = NATS.connect(config["nats_server_info"]["url"])
function text2text_instruct_llm(sender_id::String, openai_msg::Dict{String, Any})
payloads = [("msg", openai_msg, "dictionary")] # List of tuples
_, msg_envelope_json_str = msghandler.smartpack(
config["externalservice"]["servicesloadbalancer"]["nats"],
payloads;
sender_id=sender_id,
msg_purpose="text2text",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalservice"]["fileserver"]["url"])
reply = NATS.request(agent_conn,
config["externalservice"]["servicesloadbalancer"]["nats"],
msg_envelope_json_str, timeout=120)
incoming_env_json_str = String(reply.payload)
incoming_env = msghandler.smartunpack(incoming_env_json_str)
_llm_response = incoming_env["payloads"][1][2]
llm_response = _llm_response["choices"][1]["message"]["content"]
return llm_response
end
# 1. Read local file and encode to base64 string
image1_path = "test/large_image.png"
image1_bytes = read(image1_path)
image1_base64_string = base64encode(image1_bytes)
# 2. Match the MIME type according to your file extension (e.g., png, jpeg)
mime_type = "image/png"
data1_uri = "data:$(mime_type);base64,$(image1_base64_string)"
# 3. Construct payload with the Data URI
openai_msg = Dict(
"model" => "gemma-4-E4B-it-UD-Q4_K_XL",
"messages" => [
Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => "Do you know this wine? Just give me brief intro."),
Dict(
"type" => "image_url",
"image_url" => Dict("url" => data1_uri)
)
]
)
],
"temperature" => 0.7
)
llm_response = text2text_instruct_llm(openai_msg)
# 1. Read local file and encode to base64 string
image2_path = "test/large_image.png"
image2_bytes = read(image2_path)
image2_base64_string = base64encode(image2_bytes)
# 2. Match the MIME type according to your file extension (e.g., png, jpeg)
mime_type = "image/png"
data2_uri = "data:$(mime_type);base64,$(image2_base64_string)"
systemmsg =
"""
# Store Policy
- Generally speaking, the store inventory has some wines from France, the United States, Australia, Spain, and Italy, but you won't know exactly until you check your inventory.
- If you found wines in the store's database, they are in stock.
- You can only recommend wines that are currently in our inventory
- Before searching the database for wine, ensure you have at least the following information: 1) budget, 2) wine type, and 3) occasion. Additional details are always helpful. If the user is unsure, provide relevant information and gather insights to make reasonable inferences.
- Ask the user one question at a time.
- Do not ask the user about wine's flavor e.g. floral, citrusy, nutty or some thing similar as these terms cannot be used to search the database.
- Once the user has selected their wine, if you haven't already, ask the user whether they need any further assistance. Do not offer any additional services.
- Only end the conversation when the user explicitly intends to do so. When ending, ensure a polite farewell and an invitation to return in the future.
- Spicy foods should be paired only with light red wines.
- We do not sell organic, sustainable, gluten-free, and sulfite-free wine. Inform the user imediately if they are looking for these types of wines. Do not sell our wines as such.
- Gift box, gift card, and custom messages are available. Inform the user to contact our sales team.
# Store Guidelines
- Greeting the customer warmly by ask them how could you help. Do not ask any other questions during this greeting.
- Customer may provide images for you to look up.
- Encourage the customer to explore different options and try new things.
- If you are unable to locate the desired item in the database after 2 attempts, it may not be available in your inventory. In such cases, inform the user that the item is unavailable and suggest an alternative instead.
- Your store carries only wine.
- Vintage 0 means non-vintage.
- Start searching the database as broadly as possible within the given information boundary to maximize the chances of finding. Avoid unnecessary parameters unless specified by the user. Refine the search subsequently.
# Situation
Your customer is coming into the store
# Role
Your name is Janie. You are a helpful sommelier for website-based Yiem Wine's wine store. You are working under your mentor supervision.
# Objective
1. Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences.
2. Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences.
# Responsibility Includes
1. According to the store's policy and guidelines, make an informed decision about what you need to do to achieve the objective
2. Keep the conversation with the customer going smoothly
3. Obey your mentor's suggestions.
# Responsibility Does NOT Include
1. Requesting the user to place an order, make a purchase, or confirm the order. These are the job of our sales team at the store.
2. Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store.
3. Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store.
# You should then respond to the user with interleaving plan, action_name, action_input
1) plan: Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
2) action_name: (Typically corresponds to the execution of the first step in your plan) Can be one of the available_actions name
3) action_input: The input to the action you are about to perform according to your plan.
After the action is executed you gets "action_result". It is the output from the action you selected.
# You should only respond in JSON format as described below
"plan": "...",
"action_name": "...",
"action_input": "..."
# Available Actions
- **CHAT_BOX** which you can use to talk with the user.
- **CHECK_WINE** allows you to check information about wines you want in your inventory's database. The input is text that specify supported search criteria includeing: retailer_name, wine price, winery, name, vintage, region, country, type, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity.
- Example query 1: "Dry, full-bodied red wine from 1) region: Burgundy, country: France or 2) region: Tuscany, country: Italy. Grape varietal: Merlot or Syrah. price 100 to 1000 USD."
- Example query 2: "Red or white wine, medium tannin, price under 700 USD"
- Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
- **PRESENT_WINE_GUIDELINE** which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
- **END_CONVER_GUIDELINE** which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
"""
openai_msg = Dict(
"model" => "gemma-4-E4B-it-UD-Q4_K_XL",
"messages" => [
Dict(
"role" => "system",
"content" => [
Dict("type" => "text", "text" => systemmsg),
]
),
Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => "Do you know this wine? Just give me brief intro."),
]
),
Dict(
"role" => "assistant",
"content" => [
Dict("type" => "text", "text" =>
"""
" <plan>I will greet the customer warmly as Janie, acknowledge their request to find a similar wine for their wedding party based on the image, identify the wine type and country (Italian Sparkling Wine), and then use the CHECK_WINE action to search the inventory for suitable options.</plan>\n <action_name>CHAT_BOX</action_name>\n <action_input>Hello! I'm Janie, and I'd be delighted to help you find the perfect wine for your wedding party. That beautiful wine in the image appears to be an Italian sparkling wine, which is wonderful for a celebration like a wedding! Since you have an unlimited budget, I can certainly look for some truly exceptional options. To start, I will check our inventory for similar Italian sparkling wines that are perfect for a wedding celebration.</action_input><action_result> User response in the next message </action_result>"
"""
),
]
),
Dict(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => "ok"),
]
),
],
"temperature" => 0.7
)
llm_response = text2text_instruct_llm(openai_msg)
# ---------------------------------------------- 100 --------------------------------------------- #
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+291
View File
@@ -0,0 +1,291 @@
using JSON, Dates, UUIDs, PrettyPrinting, LibPQ, Base64, DataFrames, DataStructures, HTTP, Base64,
NATS, Base.Threads
using YiemAgent, GeneralUtils, msghandler
function text2text_instruct_llm(sender_id::String, openai_msg::Dict{String, Any})
payloads = [("msg", openai_msg, "dictionary")] # List of tuples
_, msg_envelope_json_str = msghandler.smartpack(
config["externalService"]["servicesloadbalancer"]["nats"],
payloads;
sender_id=sender_id,
msg_purpose="text2text",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalService"]["fileserver"]["url"])
reply = NATS.request(agent_conn,
config["externalService"]["servicesloadbalancer"]["nats"],
msg_envelope_json_str, timeout=120)
incoming_env_json_str = String(reply.payload)
incoming_env = msghandler.smartunpack(incoming_env_json_str)
_llm_response = incoming_env["payloads"][1][2]
llm_response = _llm_response["choices"][1]["message"]["content"]
return llm_response
end
#TESTING get text embedding from a LLM service
function get_embedding(text::AbstractArray{String})
documents_dict = Dict("documents" => text)
payloads = [("documents", documents_dict, "dictionary")]
_, msg_envelope_json_str = msghandler.smartpack(
config["externalService"]["servicesloadbalancer"]["nats"],
payloads;
msg_purpose="embedding",
broker_url=config["nats_server_info"]["url"],
fileserver_url=config["externalService"]["fileserver"]["url"])
reply = NATS.request(agent_conn,
config["externalService"]["servicesloadbalancer"]["nats"],
msg_envelope_json_str, timeout=120)
incoming_env_json_str = String(reply.payload)
incoming_env = msghandler.smartunpack(incoming_env_json_str)
embedding_response = incoming_env["payloads"][1][2]
return embedding_response
end
#TESTING
function execute_sql_winedb(config::JSON.Object, sql::T) where {T<:AbstractString}
host_url, _port = split(config["externalservice"]["sommpanion_db"]["url"], ':')
port = parse(Int, _port)
dbname = "winedb"
user = config["externalservice"]["sommpanion_db"]["user"]
password = config["externalservice"]["sommpanion_db"]["password"]
db_connection = LibPQ.Connection("host=$host_url port=$port dbname=$dbname user=$user password=$password")
result = LibPQ.execute(db_connection, sql)
LibPQ.close(db_connection)
return result
end
#TESTING
function similar_sql_vectordb(query; maxdistance::Integer=100)
tablename = "sqlllm_decision_repository"
# get embedding of the query
df = find_similar_text_from_vectordb(query, tablename,
"function_input_embedding", execute_sql_vectordb)
# println(df[1, [:id, :function_output]])
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
# distance = 100 # CHANGE this is for testing only
if row != 0 && distance < maxdistance
# if there is usable SQL, return it.
output_b64 = df[1, :function_output_base64] # pick the closest match
output_str = String(base64decode(output_b64))
rowid = df[1, :id]
println("\n~~~ found similar sql. row id $rowid, distance $distance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
return (dict=output_str, distance=distance)
else
println("\n~~~ similar sql not found, max distance $maxdistance ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
return (dict=nothing, distance=nothing)
end
end
#TESTING
function insert_sql_vectordb(query::T1, SQL::T2; maxdistance::Integer=3) where {T1<:AbstractString, T2<:AbstractString}
tablename = "sqlllm_decision_repository"
# get embedding of the query
# query = state[:thoughtHistory][:question]
df = find_similar_text_from_vectordb(query, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
_query_embedding = get_embedding([query])[1]
query_embedding = _query_embedding["data"][1]["embedding"]
query = replace(query, "'" => "")
sql_base64 = base64encode(SQL)
sql_ = replace(SQL, "'" => "")
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
#TESTING
function execute_sql_vectordb(sql::T) where {T<:AbstractString}
host_url, _port = split(config["SQLVectorDB"]["url"], ':')
port = parse(Int, _port)
dbname = config[:externalservice][:SQLVectorDB][:dbname]
user = config[:externalservice][:SQLVectorDB][:user]
password = config[:externalservice][:SQLVectorDB][:password]
DBconnection = LibPQ.Connection("host=$host_url port=$port dbname=$dbname user=$user password=$password")
result = LibPQ.execute(DBconnection, sql)
close(DBconnection)
return result
end
function similar_sommelier_decision(recentevents::T1; maxdistance::Integer=3
)::Union{AbstractDict, Nothing} where {T1<:AbstractString}
tablename = "sommelier_decision_repository"
# find similar
println("\n~~~ search vectorDB for this: $recentevents ", @__FILE__, " ", @__LINE__)
df = find_similar_text_from_vectordb(recentevents, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row != 0 && distance < maxdistance
# if there is usable decision, return it.
rowid = df[1, :id]
println("\n~~~ found similar decision. row id $rowid, distance $distance ", @__FILE__, " ", @__LINE__)
output_b64 = df[1, :function_output_base64] # pick the closest match
_output_str = String(base64decode(output_b64))
output = copy(JSON.read(_output_str))
return output
else
println("\n~~~ similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__)
return nothing
end
end
#TESTING
function find_similar_text_from_vectordb(text::T1, tablename::T2, embeddingColumnName::T3,
vectorDB::Function; limit::Integer=1
)::DataFrame where {T1<:AbstractString, T2<:AbstractString, T3<:AbstractString}
# get embedding from LLM service
_embedding = get_embedding([text])[1]
embedding = _embedding["data"][1]["embedding"]
# check whether there is close enough vector already store in vectorDB. if no, add, else skip
sql = """
SELECT *, $embeddingColumnName <-> '$embedding' as distance
FROM $tablename
ORDER BY distance LIMIT $limit;
"""
response = vectorDB(sql)
df = DataFrame(response)
return df
end
function insert_sommelier_decision(recentevents::T1, decision::T2; maxdistance::Integer=5
) where {T1<:AbstractString, T2<:AbstractDict}
tablename = "sommelier_decision_repository"
# find similar
df = find_similar_text_from_vectordb(recentevents, tablename,
"function_input_embedding", execute_sql_vectordb)
row, col = size(df)
distance = row == 0 ? Inf : df[1, :distance]
if row == 0 || distance > maxdistance # no close enough SQL stored in the database
_embedding = get_embedding([recentevents])[1]
recentevents_embedding = _embedding["data"][1]["embedding"]
recentevents = replace(recentevents, "'" => "")
decision_json = JSON.json(decision)
decision_base64 = base64encode(decision_json)
decision = replace(decision_json, "'" => "")
sql =
"""
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
sessionId = "0"
backend_session_topic = "sommpanion.backend.agentbackend.v1.inbox.$sessionId"
config = JSON.parsefile("./dummy_config.json")
agent_ch = Channel(8)
agent_conn = NATS.connect(config["nats_server_info"]["url"])
sub2 = NATS.subscribe(agent_conn, backend_session_topic) do msg
put!(agent_ch, msg)
end
agent_context = YiemAgent.agentcontext(
text2text_instruct_llm,
get_embedding,
execute_sql_winedb,
similar_sql_vectordb,
insert_sql_vectordb,
similar_sommelier_decision,
insert_sommelier_decision
)
# can't instantiate
agent = YiemAgent.sommelier(
agent_context;
name="Janie",
id=sessionId, # agent instance id
retailername="Yiem",
llmFormatName=""
)
# 1. Read local file and encode to base64 string
image1_path = "test/large_image.png"
image1_bytes = read(image1_path)
image1_base64_string = base64encode(image1_bytes)
# 2. Match the MIME type according to your file extension (e.g., png, jpeg)
mime_type = "image/png"
data1_uri = "data:$(mime_type);base64,$(image1_base64_string)"
# 3. Construct payload with the Data URI
usermsg = Dict{String, Any}(
"role" => "user",
"content" => [
Dict("type" => "text", "text" => "รู้จักไวน์ที่อยู่ในรูปมั้ย"),
Dict(
"type" => "image_url",
"image_url" => Dict("url" => data1_uri)
)
]
)
result = YiemAgent.conversation(agent; userinput=usermsg)
println(result)
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB