Compare commits
79 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2b7c0041e5 | |||
| 9ff0b48eec | |||
| afeb4c7aef | |||
| 2942a89730 | |||
| 6a66f58e63 | |||
| 1d0353d793 | |||
| 0f6aa7c79f | |||
| 0320fd321f | |||
| c29dccf597 | |||
| 70cf04b0db | |||
| 4d57f0146b | |||
| d33aa14dc8 | |||
| 0ed3edd48a | |||
| fb91b51573 | |||
| 0bbd227920 | |||
| 3487770f77 | |||
| 7d27f9e567 | |||
| 511b4d682d | |||
| 5ba91d8acc | |||
| 709f7e7115 | |||
| 3529384cdb | |||
| d1921fa403 | |||
| b4f2a6185b | |||
| d076d5f912 | |||
| e63dd7d898 | |||
| 299a485e4e | |||
| 57dd6df942 | |||
| 9c22cf2e31 | |||
| de20764610 | |||
| 906afc6422 | |||
| f6eaf4751b | |||
| 99b2fda461 | |||
| b5a00bc694 | |||
| 4eb55537f7 | |||
| 0a1032c545 | |||
| 68a20b5080 | |||
| 8a9c9606c7 | |||
| bad2ca35ed | |||
| f2b56640cc | |||
| 5d552d96c4 | |||
| e0dc7d29b2 | |||
| 932611a439 | |||
| a5c6360b4e | |||
| 03f50379c9 | |||
| a7da0b8123 | |||
| e524813021 | |||
| 3444f00062 | |||
| 919d8ec85e | |||
| 3a88e0e7d4 | |||
| 68c2c2f12b | |||
| 3e79c0bfed | |||
| d0c26e52e8 | |||
| a0152a3c29 | |||
| 1fc5dfe820 | |||
| 4b2575f4a4 | |||
| a01a91e7b9 | |||
| aa8436c0ed | |||
| cccad676db | |||
| 03de659c9b | |||
| affb96f0cf | |||
| f19f302bd9 | |||
| 7ca4f5276d | |||
| 44804041a3 | |||
| 48a3704f6d | |||
| 8321a13afc | |||
| b26ae31d4c | |||
| b397bf7bdb | |||
| c0edf7dadf | |||
| c21f943b12 | |||
| b8fd772a28 | |||
| 883f581b2a | |||
| 5a890860a6 | |||
| 7d5bc14a09 | |||
| 37ba3a9d31 | |||
| bfadd53033 | |||
| 8fc3afe348 | |||
| c60037226a | |||
| db6c9c5f2b | |||
| 6504099959 |
+386
-214
File diff suppressed because it is too large
Load Diff
+11
-5
@@ -1,17 +1,19 @@
|
||||
name = "YiemAgent"
|
||||
uuid = "e012c34b-7f78-48e0-971c-7abb83b6f0a2"
|
||||
version = "0.4.3"
|
||||
authors = ["narawat lamaiin <narawat@outlook.com>"]
|
||||
version = "0.1.2"
|
||||
|
||||
[deps]
|
||||
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
|
||||
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
|
||||
DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
|
||||
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
|
||||
GeneralUtils = "c6c72f09-b708-4ac8-ac7c-2084d70108fe"
|
||||
HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3"
|
||||
JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1"
|
||||
JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
|
||||
LLMMCTS = "d76c5a4d-449e-4835-8cc4-dd86ec44f241"
|
||||
LibPQ = "194296ae-ab2e-5f79-8cd4-7183a0a5a0d1"
|
||||
NATS = "55e73f9c-eeeb-467f-b4cc-a633fde63d2a"
|
||||
PrettyPrinting = "54e16d92-306c-5ea0-a30b-337be88ac337"
|
||||
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
|
||||
Revise = "295af30f-e4ad-537b-8983-00126c2a3abe"
|
||||
@@ -21,7 +23,11 @@ URIs = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
|
||||
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
|
||||
|
||||
[compat]
|
||||
CSV = "0.10.15"
|
||||
DataFrames = "1.7.0"
|
||||
GeneralUtils = "0.1, 0.2"
|
||||
LLMMCTS = "0.1.2"
|
||||
SQLLLM = "0.2.0"
|
||||
GeneralUtils = "0.4.9"
|
||||
HTTP = "2.4.0"
|
||||
JSON = "1.6.1"
|
||||
LLMMCTS = "0.1.5"
|
||||
NATS = "0.1.0"
|
||||
SQLLLM = "0.2.7"
|
||||
|
||||
@@ -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": "..."
|
||||
}
|
||||
```
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
|
||||
|
||||
|
||||
d = Dict(
|
||||
"hello"=> 555,
|
||||
"world"=> Dict(
|
||||
"name"=> "ton"
|
||||
)
|
||||
)
|
||||
|
||||
x = 55
|
||||
|
||||
@info "YiemAgent think() 1 " d x @__LINE__
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"mqttServerInfo": {
|
||||
"description": "mqtt server info",
|
||||
"port": 1883,
|
||||
"broker": "mqtt.yiem.cc"
|
||||
},
|
||||
"testingOrProduction": {
|
||||
"value": "testing",
|
||||
"description": "agent status, couldbe testing or production"
|
||||
},
|
||||
"agentid": {
|
||||
"value": "2b74b87a-5413-4fe2-a4d3-405891051680",
|
||||
"description": "a unique id for this agent"
|
||||
},
|
||||
"agentCentralConfigTopic": {
|
||||
"mqtttopic": "/yiem_branch_1/agent/sommelier/backend/config/api/v1.1",
|
||||
"description": "a central agent server's topic to get this agent config"
|
||||
},
|
||||
"servicetopic": {
|
||||
"mqtttopic": [
|
||||
"/yiem/hq/agent/sommelier/backend/prompt/api_v1/testing"
|
||||
],
|
||||
"description": "a topic this agent are waiting for service request"
|
||||
},
|
||||
"role": {
|
||||
"value": "sommelier",
|
||||
"description": "agent role"
|
||||
},
|
||||
"organization": {
|
||||
"value": "yiem_branch_1",
|
||||
"description": "organization name"
|
||||
},
|
||||
"externalservice": {
|
||||
"loadbalancer": {
|
||||
"mqtttopic": "/loadbalancer/requestingservice",
|
||||
"description": "text to text service with instruct LLM"
|
||||
},
|
||||
"text2textinstruct": {
|
||||
"mqtttopic": "/loadbalancer/requestingservice",
|
||||
"description": "text to text service with instruct LLM",
|
||||
"llminfo": {
|
||||
"name": "llama3instruct"
|
||||
}
|
||||
},
|
||||
"virtualWineCustomer_1": {
|
||||
"mqtttopic": "/virtualenvironment/winecustomer",
|
||||
"description": "text to text service with instruct LLM that act as wine customer",
|
||||
"llminfo": {
|
||||
"name": "llama3instruct"
|
||||
}
|
||||
},
|
||||
"text2textchat": {
|
||||
"mqtttopic": "/loadbalancer/requestingservice",
|
||||
"description": "text to text service with instruct LLM",
|
||||
"llminfo": {
|
||||
"name": "llama3instruct"
|
||||
}
|
||||
},
|
||||
"wineDB" : {
|
||||
"description": "A wine database connection info for LibPQ client",
|
||||
"host": "192.168.88.12",
|
||||
"port": 10201,
|
||||
"dbname": "wineDB",
|
||||
"user": "yiemtechnologies",
|
||||
"password": "yiemtechnologies@Postgres_0.0"
|
||||
},
|
||||
"SQLVectorDB" : {
|
||||
"description": "A wine database connection info for LibPQ client",
|
||||
"host": "192.168.88.12",
|
||||
"port": 10203,
|
||||
"dbname": "SQLVectorDB",
|
||||
"user": "yiemtechnologies",
|
||||
"password": "yiemtechnologies@Postgres_0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
+706
@@ -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()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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**
|
||||
Don’t 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. Don’t 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. Don’t 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. Don’t 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!
|
||||
@@ -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==
|
||||
+771
-1107
File diff suppressed because it is too large
Load Diff
+348
-345
@@ -1,10 +1,10 @@
|
||||
module llmfunction
|
||||
|
||||
export virtualWineUserChatbox, jsoncorrection, checkinventory, # recommendbox,
|
||||
export virtualWineUserChatbox, jsoncorrection, checkwine!, # recommendbox,
|
||||
virtualWineUserRecommendbox, userChatbox, userRecommendbox, extractWineAttributes_1,
|
||||
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 ..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}
|
||||
|
||||
# put in model format
|
||||
virtualWineCustomer = a.config[:externalservice][:virtualWineCustomer_1]
|
||||
llminfo = virtualWineCustomer[:llminfo]
|
||||
virtualWineCustomer = a.config["externalservice"]["virtualWineCustomer_1"]
|
||||
llminfo = virtualWineCustomer["llminfo"]
|
||||
prompt =
|
||||
if llminfo[:name] == "llama3instruct"
|
||||
if llminfo["name"] == "llama3instruct"
|
||||
formatLLMtext_llama3instruct("assistant", input)
|
||||
else
|
||||
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
|
||||
msgMeta = GeneralUtils.generate_msgMeta(
|
||||
virtualWineCustomer[:mqtttopic],
|
||||
virtualWineCustomer["mqtttopic"],
|
||||
senderName= "virtualWineUserRecommendbox",
|
||||
senderId= a.id,
|
||||
receiverName= "virtualWineCustomer",
|
||||
mqttBroker= a.config[:mqttServerInfo][:broker],
|
||||
mqttBrokerPort= a.config[:mqttServerInfo][:port],
|
||||
mqttBroker= a.config["mqttServerInfo"]["broker"],
|
||||
mqttBrokerPort= a.config["mqttServerInfo"]["port"],
|
||||
msgId = "dummyid" #CHANGE remove after testing finished
|
||||
)
|
||||
|
||||
outgoingMsg = Dict(
|
||||
:msgMeta=> msgMeta,
|
||||
:payload=> Dict(
|
||||
:text=> prompt,
|
||||
"msgMeta"=> msgMeta,
|
||||
"payload"=> Dict(
|
||||
"text"=> prompt,
|
||||
)
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -171,26 +171,26 @@ function virtualWineUserChatbox(config::T1, input::T2, virtualCustomerChatHistor
|
||||
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
|
||||
chathistory::Vector{Dict{Symbol, Any}} = Vector{Dict{Symbol, Any}}()
|
||||
chathistory::Vector{Dict{String, Any}} = Vector{Dict{String, Any}}()
|
||||
for i in virtualCustomerChatHistory
|
||||
newdict = Dict()
|
||||
newdict[:name] =
|
||||
if i[:name] == "user"
|
||||
newdict["name"] =
|
||||
if i["name"] == "user"
|
||||
"you"
|
||||
elseif i[:name] == "assistant"
|
||||
elseif i["name"] == "assistant"
|
||||
"sommelier"
|
||||
else
|
||||
i[:name]
|
||||
i["name"]
|
||||
end
|
||||
|
||||
newdict[:text] = i[:text]
|
||||
newdict["text"] = i["text"]
|
||||
push!(chathistory, newdict)
|
||||
end
|
||||
|
||||
push!(chathistory, Dict(:name=> "assistant", :text=> input))
|
||||
push!(chathistory, Dict("name"=> "assistant", "text"=> input))
|
||||
|
||||
# put in model format
|
||||
prompt = formatLLMtext(chathistory, "llama3instruct")
|
||||
@@ -201,23 +201,23 @@ function virtualWineUserChatbox(config::T1, input::T2, virtualCustomerChatHistor
|
||||
"""
|
||||
|
||||
pprint(prompt)
|
||||
externalService = config[:externalservice][:text2textinstruct]
|
||||
externalService = config["externalservice"]["text2textinstruct"]
|
||||
|
||||
# send formatted input to user using GeneralUtils.sendReceiveMqttMsg
|
||||
msgMeta = GeneralUtils.generate_msgMeta(
|
||||
externalService[:mqtttopic],
|
||||
externalService["mqtttopic"],
|
||||
senderName= "virtualWineUserChatbox",
|
||||
senderId= string(uuid4()),
|
||||
receiverName= "text2textinstruct",
|
||||
mqttBroker= config[:mqttServerInfo][:broker],
|
||||
mqttBrokerPort= config[:mqttServerInfo][:port],
|
||||
mqttBroker= config["mqttServerInfo"]["broker"],
|
||||
mqttBrokerPort= config["mqttServerInfo"]["port"],
|
||||
msgId = string(uuid4()) #CHANGE remove after testing finished
|
||||
)
|
||||
|
||||
outgoingMsg = Dict(
|
||||
:msgMeta=> msgMeta,
|
||||
:payload=> Dict(
|
||||
:text=> prompt,
|
||||
"msgMeta"=> msgMeta,
|
||||
"payload"=> Dict(
|
||||
"text"=> prompt,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -225,7 +225,7 @@ function virtualWineUserChatbox(config::T1, input::T2, virtualCustomerChatHistor
|
||||
for attempt in 1:5
|
||||
try
|
||||
response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=120)
|
||||
_responseJsonStr = response[:response][:text]
|
||||
_responseJsonStr = response["response"]["text"]
|
||||
expectedJsonExample =
|
||||
"""
|
||||
Here is an expected JSON format:
|
||||
@@ -237,12 +237,12 @@ function virtualWineUserChatbox(config::T1, input::T2, virtualCustomerChatHistor
|
||||
}
|
||||
"""
|
||||
responseJsonStr = jsoncorrection(config, _responseJsonStr, expectedJsonExample)
|
||||
responseDict = copy(JSON3.read(responseJsonStr))
|
||||
responseDict = copy(JSON.parsefile(responseJsonStr))
|
||||
|
||||
text::AbstractString = responseDict[:text]
|
||||
select::Union{Nothing, Number} = responseDict[:select] == "null" ? nothing : responseDict[:select]
|
||||
reward::Number = responseDict[:reward]
|
||||
isterminal::Bool = responseDict[:isterminal]
|
||||
text::AbstractString = responseDict["text"]
|
||||
select::Union{Nothing, Number} = responseDict["select"] == "null" ? nothing : responseDict["select"]
|
||||
reward::Number = responseDict["reward"]
|
||||
isterminal::Bool = responseDict["isterminal"]
|
||||
|
||||
if text != ""
|
||||
# pass test
|
||||
@@ -269,7 +269,7 @@ end
|
||||
# Arguments
|
||||
- `a::T1`
|
||||
one of ChatAgent's agent.
|
||||
- `input::T2`
|
||||
- `thoughtdict::AbstractDict`
|
||||
# Return
|
||||
A JSON string of available wine
|
||||
|
||||
@@ -281,36 +281,31 @@ julia> input = "{\"food\": \"pizza\", \"occasion\": \"anniversary\"}"
|
||||
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\"}, }"
|
||||
```
|
||||
|
||||
# TODO
|
||||
- [] update docs
|
||||
- [x] implement the function
|
||||
|
||||
# Signature
|
||||
"""
|
||||
function checkinventory(a::T1, input::T2
|
||||
) where {T1<:agent, T2<:AbstractString}
|
||||
function checkwine!(a::T, thoughtdict::AbstractDict
|
||||
)::NamedTuple{(:thoughtdict, :result_raw), Tuple{OrderedDict, Any}} where {T<:agent}
|
||||
|
||||
println("\n~~~ checkinventory order: $input ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
wineattributes_1 = extractWineAttributes_1(a, input)
|
||||
wineattributes_2 = extractWineAttributes_2(a, input)
|
||||
println("\ncheckinventory order: $(thoughtdict["action_input"]) ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
wineattributes_1 = extractWineAttributes_1(a, thoughtdict["action_input"])
|
||||
wineattributes_2 = extractWineAttributes_2(a, thoughtdict["action_input"])
|
||||
|
||||
_inventoryquery = "retailer name: $(a.retailername), $wineattributes_1, $wineattributes_2"
|
||||
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}"
|
||||
println("~~~ checkinventory input: $inventoryquery ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
retrieve_attributes = ["winery", "wine_name", "wine_id", "vintage", "region", "country", "wine_type", "grape", "serving_temperature", "sweetness", "intensity", "tannin", "acidity", "tasting_notes", "price", "currency"]
|
||||
_inventoryquery = "$wineattributes_1, $wineattributes_2"
|
||||
inventoryquery = "Retrieves $retrieve_attributes of wines that match the following criteria - {$_inventoryquery}"
|
||||
println("\ncheckinventory input: $inventoryquery ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# add suppport for similarSQLVectorDB
|
||||
textresult, rawresponse = SQLLLM.query(inventoryquery, a.func[:executeSQL],
|
||||
a.func[:text2textInstructLLM],
|
||||
insertSQLVectorDB=a.func[:insertSQLVectorDB],
|
||||
similarSQLVectorDB=a.func[:similarSQLVectorDB])
|
||||
textresult, result_raw = SQLLLM.query(
|
||||
inventoryquery,
|
||||
a.context.executeSQL,
|
||||
a.context.text2textInstructLLM;
|
||||
insertSQLVectorDB=a.context.insertSQLVectorDB,
|
||||
similarSQLVectorDB=a.context.similarSQLVectorDB,
|
||||
llmFormatName="qwen3")
|
||||
thoughtdict["action_result"] = textresult
|
||||
|
||||
println("\n~~~ checkinventory result ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
println(textresult)
|
||||
|
||||
return (result=textresult, rawresponse=rawresponse, success=true, errormsg=nothing)
|
||||
return (thoughtdict=thoughtdict, result_raw=result_raw)
|
||||
end
|
||||
|
||||
|
||||
"""
|
||||
|
||||
# Arguments
|
||||
@@ -323,193 +318,173 @@ end
|
||||
```jldoctest
|
||||
julia>
|
||||
```
|
||||
|
||||
# TODO
|
||||
- [] update docstring
|
||||
- [x] 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 =
|
||||
"""
|
||||
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.
|
||||
|
||||
At each round of conversation, the user will give you the current situation:
|
||||
User's query: ...
|
||||
|
||||
You must follow the following guidelines:
|
||||
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.
|
||||
<situation>
|
||||
At each round of conversation, the user provides the following:
|
||||
- The query: the query provided by the user.
|
||||
</situation>
|
||||
<objective>
|
||||
Extract information from the user's query as much as possible according to wine attributes extraction guidelines to fill out user's preference form.
|
||||
</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.
|
||||
2) Do not generate other comments.
|
||||
- Do not generate other comments.
|
||||
</wine attributes extraction guidelines>
|
||||
<you should then respond to the user with>
|
||||
wine_name: name of the wine
|
||||
winery: name of the winery
|
||||
vintage: the year of the wine
|
||||
region: a region, such as Burgundy, Bordeaux, Champagne, Napa Valley, Tuscany, California, Oregon, etc. Use "or" if there are multiple regions.
|
||||
country: a country where wine is produced. Can be "Austria", "Australia", "France", "Germany", "Italy", "Portugal", "Spain", "United States". Use "or" if there are multiple countries.
|
||||
wine_type: can be one of: "red", "white", "sparkling", "rose", "dessert" or "fortified"
|
||||
grape_varietal: the name of the primary grape used to make the wine
|
||||
tasting_notes: a word describe the wine's flavor, such as "butter", "oak", "fruity", "raspberry", "earthy", "floral", 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_max: maximum price range of wine. Example: For wine price 20, wine_price_max will be 20. For wine price 10 to 100, wine_price_max will be 100.
|
||||
occasion: the occasion the user is having the wine for
|
||||
food_to_be_paired_with_wine: food that the user will be served with the wine such as poultry, fish, steak, etc
|
||||
</you should then respond to the user with>
|
||||
<you should only respond in JSON format as described below>
|
||||
"wine_name": "...",
|
||||
"winery": "...",
|
||||
"vintage": "...",
|
||||
"region": "...",
|
||||
"country": "...",
|
||||
"wine_type": "...",
|
||||
"grape_varietal": "...",
|
||||
"tasting_notes": "...",
|
||||
"wine_price_min": "...",
|
||||
"wine_price_max": "...",
|
||||
"occasion": "...",
|
||||
"food_to_be_paired_with_wine": "..."
|
||||
</you should only respond in JSON format as described below>
|
||||
<here are some examples>
|
||||
User's query: red, Chenin Blanc, Riesling, 20 USD from Tuscany, Italy or Napa Valley, USA
|
||||
"wine_name": "N/A",
|
||||
"winery": "N/A",
|
||||
"vintage": "N/A",
|
||||
"region": "Tuscany or Napa Valley",
|
||||
"country": "Italy or United States",
|
||||
"wine_type": "red or white",
|
||||
"grape_varietal": "Chenin Blanc or Riesling",
|
||||
"tasting_notes": "citrus",
|
||||
"wine_price_min": "0",
|
||||
"wine_price_max": "20",
|
||||
"occasion": "N/A",
|
||||
"food_to_be_paired_with_wine": "N/A"
|
||||
|
||||
You should then respond to the user with the following points:
|
||||
- reasoning: state your understanding of the current situation
|
||||
- wine_name: name of the wine
|
||||
- winery: name of the winery
|
||||
- vintage: the year of the wine
|
||||
- region: a region (NOT a country) where the wine is produced, such as Burgundy, Napa Valley, etc
|
||||
- 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"
|
||||
- grape_varietal: the name of the primary grape used to make the wine
|
||||
- tasting_notes: a brief description of the wine's taste, such as "butter", "oak", "fruity", etc
|
||||
- wine_price: price range of wine.
|
||||
- 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
|
||||
|
||||
|
||||
You should only respond in the user's preference form (JSON) as described below:
|
||||
{"reasoning": ..., "winery": ..., "wine_name": ..., "vintage": ..., "region": ..., "country": ..., "wine_type": ..., "grape_varietal": ..., "tasting_notes": ..., "wine_price": ..., "occasion": ..., "food_to_be_paired_with_wine": ...}
|
||||
|
||||
Here are some example:
|
||||
User's query: red, Chenin Blanc, Riesling, 20 USD
|
||||
{"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"}
|
||||
|
||||
User's query: Domaine du Collier Saumur Blanc 2019, France, white, Chenin Blanc
|
||||
{"reasoning": ..., "winery": "Domaine du Collier", "wine_name": "Saumur Blanc", "vintage": "2019", "region": "Saumur", "country": "France", "wine_type": "white", "grape_varietal": "Chenin Blanc", "tasting_notes": "NA", "wine_price": "NA", "occasion": "NA", "food_to_be_paired_with_wine": "NA"}
|
||||
|
||||
Let's begin!
|
||||
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>
|
||||
"""
|
||||
|
||||
attributes = ["reasoning", "winery", "wine_name", "vintage", "region", "country", "wine_type", "grape_varietal", "tasting_notes", "wine_price", "occasion", "food_to_be_paired_with_wine"]
|
||||
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 = ""
|
||||
|
||||
for attempt in 1:5
|
||||
usermsg =
|
||||
context =
|
||||
"""
|
||||
User's query: $input
|
||||
<internal_context_for_assistant>
|
||||
$errornote
|
||||
</internal_context_for_assistant>
|
||||
"""
|
||||
|
||||
_prompt =
|
||||
[
|
||||
Dict(:name=> "system", :text=> systemmsg),
|
||||
Dict(:name=> "user", :text=> usermsg)
|
||||
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
|
||||
)
|
||||
|
||||
# put in model format
|
||||
prompt = GeneralUtils.formatLLMtext(_prompt; formatname="llama3instruct")
|
||||
prompt *=
|
||||
"""
|
||||
<|start_header_id|>assistant<|end_header_id|>
|
||||
"""
|
||||
for attempt in 1:maxattempt
|
||||
response = a.context.text2textInstructLLM(a.id, msg)
|
||||
response = GeneralUtils.clean_json_response(response)
|
||||
println("\n--- extractWineAttributes_1-1()")
|
||||
println(response)
|
||||
println("--- \n")
|
||||
|
||||
response = a.func[:text2textInstructLLM](prompt)
|
||||
response = GeneralUtils.remove_french_accents(response)
|
||||
|
||||
# check wheter all attributes are in the response
|
||||
checkFlag = false
|
||||
for word in attributes
|
||||
if !occursin(word, response)
|
||||
errornote = "$word attribute is missing in previous attempts"
|
||||
println("Attempt $attempt $errornote ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
checkFlag = true
|
||||
break
|
||||
think, response = GeneralUtils.extractthink(response)
|
||||
responsedict = nothing
|
||||
try
|
||||
_responsedict = JSON.parse(response)
|
||||
responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
|
||||
catch
|
||||
println("\nERROR YiemAgent extractWineAttributes_1() failed to parse response: $response", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
end
|
||||
# check whether all answer's key points are in responsedict
|
||||
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
if !ispass
|
||||
errornote = errormsg
|
||||
println("\nERROR YiemAgent extractWineAttributes_1() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
continue
|
||||
end
|
||||
checkFlag == true ? continue : nothing
|
||||
|
||||
responsedict = copy(JSON3.read(response))
|
||||
|
||||
# convert
|
||||
|
||||
delete!(responsedict, :reasoning)
|
||||
delete!(responsedict, :tasting_notes)
|
||||
delete!(responsedict, :occasion)
|
||||
delete!(responsedict, :food_to_be_paired_with_wine)
|
||||
|
||||
println(@__FILE__, " ", @__LINE__)
|
||||
pprintln(responsedict)
|
||||
|
||||
# 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 attributes
|
||||
j = Symbol(i)
|
||||
if j ∉ [:reasoning, :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("Attempt $attempt $errornote ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
checkFlag = true
|
||||
break
|
||||
removekeys = ["thought", "tasting_notes", "occasion", "food_to_be_paired_with_wine", "vintage"]
|
||||
for i in removekeys
|
||||
delete!(responsedict, i)
|
||||
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("Attempt $attempt $errornote ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
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("Attempt $attempt $errornote ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
checkFlag == true
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
checkFlag == true ? continue : nothing # skip the rest code if true
|
||||
|
||||
# remove (some text)
|
||||
for (k, v) in responsedict
|
||||
_v = replace(v, r"\(.*?\)" => "")
|
||||
responsedict[k] = _v
|
||||
end
|
||||
|
||||
result = ""
|
||||
for (k, v) in responsedict
|
||||
# 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, "
|
||||
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 ", "
|
||||
|
||||
println("\n--- extractWineAttributes_1-2()")
|
||||
println(result)
|
||||
println("--- \n")
|
||||
return result
|
||||
end
|
||||
error("wineattributes_wordToNumber() failed to get a response")
|
||||
error("extractWineAttributes_1() failed to get a response")
|
||||
end
|
||||
|
||||
"""
|
||||
# TODO
|
||||
- [PENDING] "French dry white wines with medium bod" the LLM does not recognize sweetness. use LLM self questioning to solve.
|
||||
- [PENDING] French Syrah, Viognier, under 100. LLM extract intensiry of 3-5. why?
|
||||
- TODO "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?
|
||||
"""
|
||||
function extractWineAttributes_2(a::T1, input::T2)::String where {T1<:agent, T2<:AbstractString}
|
||||
|
||||
conversiontable =
|
||||
"""
|
||||
Conversion Table:
|
||||
<conversion_table>
|
||||
Intensity level:
|
||||
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.
|
||||
@@ -534,151 +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.
|
||||
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.
|
||||
</conversion_table>
|
||||
"""
|
||||
|
||||
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.
|
||||
|
||||
At each round of conversation, the user will give you the current situation:
|
||||
Conversion Table: ...
|
||||
User's query: ...
|
||||
|
||||
The preference form requires the following information:
|
||||
sweetness, acidity, tannin, intensity
|
||||
|
||||
You must follow the following guidelines:
|
||||
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.
|
||||
<situation>
|
||||
At each round of conversation, you will be given the following information:
|
||||
conversion_table: a conversion table that maps descriptive words to their corresponding integer levels
|
||||
query: the words from the user's query that describe their preferences
|
||||
</situation>
|
||||
<objective>
|
||||
Fill out the user's preference form based on the corresponding words from the user's query according to the guidelines.
|
||||
</objective>
|
||||
<your responsibility includes>
|
||||
Fulfill the objective
|
||||
</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.
|
||||
2) 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.
|
||||
|
||||
You should then respond to the user with the following points:
|
||||
- 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
|
||||
- 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
|
||||
- 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
|
||||
- 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
|
||||
|
||||
You should only respond in the form (JSON) as described below:
|
||||
{
|
||||
"sweetness_keyword": ...,
|
||||
"sweetness": ...,
|
||||
"acidity_keyword": ...,
|
||||
"acidity": ...,
|
||||
"tannin_keyword": ...,
|
||||
"tannin": ...,
|
||||
"intensity_keyword": ...,
|
||||
"intensity": ...
|
||||
}
|
||||
|
||||
Here are some examples:
|
||||
- Use the conversion table to convert the descriptive word level of sweetness, intensity, tannin, and acidity into a corresponding integer.
|
||||
- Do not generate other comments.
|
||||
</guidelines>
|
||||
<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: ( 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: ( 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: ( 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: ( I ), where ( I ) represents integers indicating the range of intensity level. Example: 2-4
|
||||
</you should then respond to the user with>
|
||||
<you should only respond in JSON format as described below>
|
||||
"sweetness_keyword": "...",
|
||||
"sweetness_min": "...",
|
||||
"sweetness_max": "...",
|
||||
"acidity_keyword": "...",
|
||||
"acidity_min": "...",
|
||||
"acidity_max": "...",
|
||||
"tannin_keyword": "...",
|
||||
"tannin_min": "...",
|
||||
"tannin_max": "...",
|
||||
"intensity_keyword": "...",
|
||||
"intensity_min": "...",
|
||||
"intensity_max": "..."
|
||||
</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.
|
||||
{
|
||||
"sweetness_keyword": "NA",
|
||||
"sweetness": "NA",
|
||||
"sweetness_keyword": "N/A",
|
||||
"sweetness_min": "N/A",
|
||||
"sweetness_max": "N/A",
|
||||
"acidity_keyword": "low acidity",
|
||||
"acidity": "1-2",
|
||||
"acidity_min": 1,
|
||||
"acidity_max": 2,
|
||||
"tannin_keyword": "medium tannin",
|
||||
"tannin": "3-4",
|
||||
"tannin_min": 3,
|
||||
"tannin_max": 4,
|
||||
"intensity_keyword": "medium-bodied",
|
||||
"intensity": "3-4"
|
||||
}
|
||||
"intensity_min": 3,
|
||||
"intensity_max": 4
|
||||
|
||||
|
||||
User's query: German red wine, under 100, pairs with spicy food
|
||||
{
|
||||
"sweetness_keyword": "NA",
|
||||
"sweetness": "NA",
|
||||
"acidity_keyword": "NA",
|
||||
"acidity": "NA",
|
||||
"tannin_keyword": "NA",
|
||||
"tannin": "NA",
|
||||
"intensity_keyword": "NA",
|
||||
"intensity": "NA"
|
||||
}
|
||||
|
||||
|
||||
Let's begin!
|
||||
User's query: German red wine, under 100, pairs with spicy food.
|
||||
"sweetness_keyword": "N/A",
|
||||
"sweetness_min": "N/A",
|
||||
"sweetness_max": "N/A",
|
||||
"acidity_keyword": "N/A",
|
||||
"acidity_min": "N/A",
|
||||
"acidity_max": "N/A",
|
||||
"tannin_keyword": "N/A",
|
||||
"tannin_min": "N/A",
|
||||
"tannin_max": "N/A",
|
||||
"intensity_keyword": "N/A",
|
||||
"intensity_min": "N/A",
|
||||
"intensity_max": "N/A"
|
||||
<here are some examples>
|
||||
"""
|
||||
|
||||
requiredKeys = ["sweetness_keyword", "sweetness_min", "sweetness_max",
|
||||
"acidity_keyword", "acidity_min", "acidity_max",
|
||||
"tannin_keyword", "tannin_min", "tannin_max",
|
||||
"intensity_keyword", "intensity_min", "intensity_max"]
|
||||
errornote = ""
|
||||
|
||||
for attempt in 1:5
|
||||
usermsg =
|
||||
context =
|
||||
"""
|
||||
<internal_context_for_assistant>
|
||||
$conversiontable
|
||||
User's query: $input
|
||||
$errornote
|
||||
</internal_context_for_assistant>
|
||||
"""
|
||||
|
||||
_prompt =
|
||||
[
|
||||
Dict(:name=> "system", :text=> systemmsg),
|
||||
Dict(:name=> "user", :text=> usermsg)
|
||||
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
|
||||
)
|
||||
|
||||
# put in model format
|
||||
prompt = GeneralUtils.formatLLMtext(_prompt; formatname="llama3instruct")
|
||||
prompt *=
|
||||
"""
|
||||
<|start_header_id|>assistant<|end_header_id|>
|
||||
"""
|
||||
for attempt in 1:10
|
||||
response = a.context.text2textInstructLLM(a.id, msg)
|
||||
response = GeneralUtils.clean_json_response(response)
|
||||
println("\n--- extractWineAttributes_2-1()")
|
||||
println(response)
|
||||
println("--- \n")
|
||||
|
||||
response = a.func[:text2textInstructLLM](prompt)
|
||||
responsedict = copy(JSON3.read(response))
|
||||
|
||||
# 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 ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
response = GeneralUtils.remove_french_accents(response)
|
||||
think, response = GeneralUtils.extractthink(response)
|
||||
responsedict = nothing
|
||||
try
|
||||
_responsedict = JSON.parse(response)
|
||||
responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
|
||||
catch
|
||||
println("\nERROR YiemAgent extractWineAttributes_2() failed to parse response: $response", @__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
|
||||
if !occursin("keyword", string(k))
|
||||
if v !== "NA" && (!occursin('-', v) || length(v) > 5)
|
||||
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 ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
# check whether all answer's key points are in responsedict
|
||||
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
if !ispass
|
||||
errornote = errormsg
|
||||
println("\nERROR YiemAgent extractWineAttributes_2() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
continue
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# some time LLM says NA-2. Need to convert NA to 1
|
||||
# delete some key words from responsedict
|
||||
for (k, v) in responsedict
|
||||
if occursin("NA", v) && occursin("-", v)
|
||||
new_v = replace(v, "NA"=>"1")
|
||||
responsedict[k] = new_v
|
||||
if k ∈ ["sweetness_keyword", "acidity_keyword", "tannin_keyword", "intensity_keyword"]
|
||||
delete!(responsedict, k)
|
||||
end
|
||||
end
|
||||
|
||||
# get result in String. Reject "N/A" value
|
||||
result = ""
|
||||
for (k, v) in responsedict
|
||||
# some time LLM generate text with "(some comment)". this line removes it
|
||||
if !occursin("NA", v)
|
||||
if typeof(v) <: Number
|
||||
result *= "$k: $v, "
|
||||
elseif typeof(v) == String && !occursin("N/A", v)
|
||||
result *= "$k: $v, "
|
||||
end
|
||||
end
|
||||
result = result[1:end-2] # remove the ending ", "
|
||||
|
||||
println("\n--- extractWineAttributes_2-2()")
|
||||
println(result)
|
||||
println("--- \n")
|
||||
return result
|
||||
end
|
||||
error("wineattributes_wordToNumber() failed to get a response")
|
||||
error("extractWineAttributes_2() failed to get a response")
|
||||
end
|
||||
|
||||
|
||||
@@ -711,54 +701,67 @@ function paraphrase(text2textInstructLLM::Function, text::String)
|
||||
- N/A
|
||||
|
||||
You should then respond to the user with:
|
||||
1) Paraphrase: Paraphrased text
|
||||
Paraphrase: Paraphrased text
|
||||
|
||||
You should only respond in format as described below:
|
||||
Paraphrase: ...
|
||||
|
||||
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:"]
|
||||
dictkey = ["paraphrase"]
|
||||
|
||||
errornote = ""
|
||||
errornote = "N/A"
|
||||
response = nothing # placeholder for show when error msg show up
|
||||
|
||||
|
||||
for attempt in 1:10
|
||||
usermsg = """
|
||||
Text: $text
|
||||
$errornote
|
||||
P.S. $errornote
|
||||
"""
|
||||
|
||||
_prompt =
|
||||
[
|
||||
Dict(:name => "system", :text => systemmsg),
|
||||
Dict(:name => "user", :text => usermsg)
|
||||
Dict("name" => "system", "text" => systemmsg),
|
||||
Dict("name" => "user", "text" => usermsg)
|
||||
]
|
||||
|
||||
# put in model format
|
||||
prompt = GeneralUtils.formatLLMtext(_prompt; formatname="llama3instruct")
|
||||
prompt *= """
|
||||
<|start_header_id|>assistant<|end_header_id|>
|
||||
"""
|
||||
prompt = GeneralUtils.formatLLMtext(_prompt, a.llmFormatName)
|
||||
|
||||
try
|
||||
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: ..."
|
||||
if occursin("respond:", response)
|
||||
errornote = "You don't need to intro your response"
|
||||
error("\n~~~ paraphrase() response contain : ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
error("\nparaphrase() response contain : ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
end
|
||||
response = GeneralUtils.remove_french_accents(response)
|
||||
response = replace(response, '*'=>"")
|
||||
response = replace(response, '$' => "USD")
|
||||
response = replace(response, '`' => "")
|
||||
response = GeneralUtils.remove_french_accents(response)
|
||||
responsedict = GeneralUtils.textToDict(response, ["Paraphrase"],
|
||||
rightmarker=":", symbolkey=true, lowercasekey=true)
|
||||
|
||||
# check whether response has all answer's key points
|
||||
detected_kw = GeneralUtils.detect_keyword(header, response)
|
||||
if 0 ∈ values(detected_kw)
|
||||
errornote = "\nYiemAgent paraphrase() response does not have all answer's key points"
|
||||
continue
|
||||
elseif sum(values(detected_kw)) > length(header)
|
||||
errornote = "\nnYiemAgent paraphrase() response has duplicated answer's key points"
|
||||
continue
|
||||
end
|
||||
|
||||
responsedict = GeneralUtils.textToDict(response, header;
|
||||
dictKey=dictkey, symbolkey=true)
|
||||
|
||||
for i ∈ [:paraphrase]
|
||||
if length(JSON3.write(responsedict[i])) == 0
|
||||
error("$i is empty ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
if length(JSON.json(responsedict[i])) == 0
|
||||
error("$i is empty ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -770,10 +773,10 @@ function paraphrase(text2textInstructLLM::Function, text::String)
|
||||
end
|
||||
end
|
||||
|
||||
println("\n~~~ paraphrase() ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
println("\nparaphrase() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(Dict(responsedict))
|
||||
|
||||
result = responsedict[:paraphrase]
|
||||
result = responsedict["paraphrase"]
|
||||
|
||||
return result
|
||||
catch e
|
||||
@@ -781,10 +784,10 @@ function paraphrase(text2textInstructLLM::Function, text::String)
|
||||
showerror(io, e)
|
||||
errorMsg = String(take!(io))
|
||||
st = sprint((io, v) -> show(io, "text/plain", v), stacktrace(catch_backtrace()))
|
||||
println("\nAttempt $attempt. Error occurred: $errorMsg\n$st ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
println("\nAttempt $attempt. Error occurred: $errorMsg\n$st ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
end
|
||||
end
|
||||
error("generatechat failed to generate a response")
|
||||
error("paraphrase() failed to generate a response")
|
||||
end
|
||||
|
||||
|
||||
@@ -817,7 +820,7 @@ function jsoncorrection(config::T1, input::T2, correctJsonExample::T3;
|
||||
|
||||
for attempt in 1:maxattempt
|
||||
try
|
||||
d = copy(JSON3.read(incorrectjson))
|
||||
d = copy(JSON.parsefile(incorrectjson))
|
||||
correctjson = incorrectjson
|
||||
return correctjson
|
||||
catch e
|
||||
@@ -842,10 +845,10 @@ function jsoncorrection(config::T1, input::T2, correctJsonExample::T3;
|
||||
"""
|
||||
|
||||
# apply LLM specific instruct format
|
||||
externalService = config[:externalservice][:text2textinstruct]
|
||||
llminfo = externalService[:llminfo]
|
||||
externalService = config["externalservice"]["text2textinstruct"]
|
||||
llminfo = externalService["llminfo"]
|
||||
prompt =
|
||||
if llminfo[:name] == "llama3instruct"
|
||||
if llminfo["name"] == "llama3instruct"
|
||||
formatLLMtext_llama3instruct("system", _prompt)
|
||||
else
|
||||
error("llm model name is not defied yet $(@__LINE__)")
|
||||
@@ -853,21 +856,21 @@ function jsoncorrection(config::T1, input::T2, correctJsonExample::T3;
|
||||
|
||||
# send formatted input to user using GeneralUtils.sendReceiveMqttMsg
|
||||
msgMeta = GeneralUtils.generate_msgMeta(
|
||||
externalService[:mqtttopic],
|
||||
externalService["mqtttopic"],
|
||||
senderName= "jsoncorrection",
|
||||
senderId= string(uuid4()),
|
||||
receiverName= "text2textinstruct",
|
||||
mqttBroker= config[:mqttServerInfo][:broker],
|
||||
mqttBrokerPort= config[:mqttServerInfo][:port],
|
||||
mqttBroker= config["mqttServerInfo"]["broker"],
|
||||
mqttBrokerPort= config["mqttServerInfo"]["port"],
|
||||
)
|
||||
|
||||
outgoingMsg = Dict(
|
||||
:msgMeta=> msgMeta,
|
||||
:payload=> Dict(
|
||||
:text=> prompt,
|
||||
:kwargs=> Dict(
|
||||
:max_tokens=> 512,
|
||||
:stop=> ["<|eot_id|>"],
|
||||
"msgMeta"=> msgMeta,
|
||||
"payload"=> Dict(
|
||||
"text"=> prompt,
|
||||
"kwargs"=> Dict(
|
||||
"max_tokens"=> 512,
|
||||
"stop"=> ["<|eot_id|>"],
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -890,7 +893,7 @@ end
|
||||
# "thought" is step-by-step reasoning about the current situation.
|
||||
# "plan" is what to do to complete the task from the current situation.
|
||||
# “action_name” is the name of the action taken, which can be one of the following functions:
|
||||
# 1) 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".
|
||||
# "action_input" is the input to the action
|
||||
# "observation" is result of the preceding immediate action.
|
||||
@@ -947,7 +950,7 @@ end
|
||||
# ]
|
||||
|
||||
# # put in model format
|
||||
# prompt = GeneralUtils.formatLLMtext(_prompt; formatname="llama3instruct")
|
||||
# prompt = GeneralUtils.formatLLMtext(_prompt, "granite3")
|
||||
# prompt *=
|
||||
# """
|
||||
# <|start_header_id|>assistant<|end_header_id|>
|
||||
@@ -979,7 +982,7 @@ end
|
||||
# state[:isterminal] = true
|
||||
# state[:reward] = 1
|
||||
# end
|
||||
# println("--> 5 Evaluator ", Dates.now(), " ", @__FILE__, " ", @__LINE__)
|
||||
# println("--> 5 Evaluator ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# pprintln(Dict(responsedict))
|
||||
# return responsedict[:score]
|
||||
# catch e
|
||||
|
||||
+317
-133
@@ -1,193 +1,215 @@
|
||||
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
|
||||
|
||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
||||
|
||||
|
||||
mutable struct agentcontext
|
||||
text2textInstructLLM::Function
|
||||
getTextEmbedding::Function
|
||||
executeSQL::Function
|
||||
similarSQLVectorDB::Function
|
||||
insertSQLVectorDB::Function
|
||||
similarSommelierDecision::Function
|
||||
insertSommelierDecision::Function
|
||||
end
|
||||
|
||||
abstract type agent end
|
||||
|
||||
|
||||
mutable struct companion <: agent
|
||||
name::String # agent name
|
||||
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
|
||||
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
|
||||
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
|
||||
chathistory= [
|
||||
Dict(:name=>"user", :text=> "Wassup!", :timestamp=> Dates.now()),
|
||||
Dict(:name=>"assistant", :text=> "Hi I'm your assistant.", :timestamp=> Dates.now()),
|
||||
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}
|
||||
|
||||
# communication function
|
||||
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}(),
|
||||
memory = Dict{String, Any}(
|
||||
"events"=> Vector{Dict{String, Any}}(),
|
||||
"state"=> Dict{String, Any}(), # state of the agent
|
||||
"recap"=> OrderedDict{String, Any}(), # recap summary of the conversation
|
||||
)
|
||||
|
||||
newAgent = companion(
|
||||
name,
|
||||
id,
|
||||
systemmsg,
|
||||
tools,
|
||||
maxHistoryMsg,
|
||||
chathistory,
|
||||
memory,
|
||||
text2textInstructLLM
|
||||
context,
|
||||
llmFormatName
|
||||
)
|
||||
|
||||
return newAgent
|
||||
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
|
||||
name::String # agent name
|
||||
id::String # agent id
|
||||
retailername::String
|
||||
tools::Dict
|
||||
maxHistoryMsg::Integer # e.g. 21th and earlier messages will get summarized
|
||||
|
||||
""" Memory
|
||||
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
|
||||
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
|
||||
chathistory::Vector{Dict{String, Any}}
|
||||
memory::Dict{String, Any}
|
||||
context::agentcontext
|
||||
llmFormatName::String
|
||||
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(
|
||||
func, # NamedTuple of functions
|
||||
context::agentcontext, # app context
|
||||
;
|
||||
name::String= "Assistant",
|
||||
id::String= string(uuid4()),
|
||||
retailername::String= "retailer_name",
|
||||
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
|
||||
"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 => "" ,
|
||||
"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" => "" ,
|
||||
),
|
||||
"winestock"=> Dict(
|
||||
: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>""",
|
||||
:output => """<output>Output are wines that match the search query in JSON format.""",
|
||||
"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>""",
|
||||
"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}(
|
||||
:chatbox=> "",
|
||||
:shortmem=> OrderedDict{Symbol, Any}(
|
||||
:available_wine=> [],
|
||||
:found_wine=> [], # used by decisionMaker(). This is to prevent decisionMaker() keep presenting the same wines
|
||||
""" Memory
|
||||
|
||||
Chat history use openai format as follow:
|
||||
|
||||
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"),
|
||||
]
|
||||
),
|
||||
:events=> Vector{Dict{Symbol, Any}}(),
|
||||
:state=> Dict{Symbol, Any}(
|
||||
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."
|
||||
),
|
||||
:recap=> OrderedDict{Symbol, Any}(),
|
||||
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}(
|
||||
),
|
||||
"recap"=> OrderedDict{String, Any}(),
|
||||
|
||||
)
|
||||
|
||||
newAgent = sommelier(
|
||||
@@ -198,7 +220,169 @@ function sommelier(
|
||||
maxHistoryMsg,
|
||||
chathistory,
|
||||
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 (not Markdown format)
|
||||
"plan": "...",
|
||||
"action_name": "...",
|
||||
"action_input": "..."
|
||||
|
||||
# available actions
|
||||
"CHAT_BOX", which you can use to talk with the user. The input is dialogue you want to chat with the user according to your plan.
|
||||
"CHECK_WINE", allows you to check information about wines you want in your inventory's database. The input is text that specify supported search criteria includeing: retailer_name, wine price, winery, name, vintage, region, country, type, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity.
|
||||
Example query 1: "Dry, full-bodied red wine from 1) region: Burgundy, country: France or 2) region: Tuscany, country: Italy. Grape varietal: Merlot or Syrah. price 100 to 1000 USD."
|
||||
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
|
||||
|
||||
+230
-269
@@ -1,9 +1,10 @@
|
||||
module util
|
||||
|
||||
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 ..type
|
||||
|
||||
@@ -25,14 +26,14 @@ 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",
|
||||
"receiveprompt"=>Dict(
|
||||
"mqtttopic"=> "testtopic/receive",
|
||||
),
|
||||
:receiveinternal=>Dict(
|
||||
:mqtttopic=> "testtopic/internal",
|
||||
"receiveinternal"=>Dict(
|
||||
"mqtttopic"=> "testtopic/internal",
|
||||
),
|
||||
:text2text=>Dict(
|
||||
:mqtttopic=> "testtopic/text2text",
|
||||
"text2text"=>Dict(
|
||||
"mqtttopic"=> "testtopic/text2text",
|
||||
),
|
||||
)
|
||||
julia> a = YiemAgent.sommelier(
|
||||
@@ -51,14 +52,25 @@ julia> YiemAgent.clearhistory(a)
|
||||
"""
|
||||
function clearhistory(a::T) where {T<:agent}
|
||||
empty!(a.chathistory)
|
||||
empty!(a.memory[:shortmem])
|
||||
empty!(a.memory[:events])
|
||||
a.memory[:chatbox] = ""
|
||||
empty!(a.memory["shortmem"])
|
||||
empty!(a.memory["events"])
|
||||
a.memory["chatbox"] = ""
|
||||
end
|
||||
|
||||
|
||||
""" 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
|
||||
-----
|
||||
a::agent
|
||||
@@ -75,44 +87,24 @@ end
|
||||
Example\n
|
||||
-----
|
||||
```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
|
||||
-----
|
||||
"""
|
||||
function addNewMessage(a::T1, name::String, text::T2;
|
||||
maximumMsg::Integer=20) where {T1<:agent, T2<:AbstractString}
|
||||
function addNewMessage(a::T1, name::String, userinput::T2;
|
||||
maximumMsg::Integer=30) where {T1<:agent, T2<:AbstractDict}
|
||||
if name ∉ ["system", "user", "assistant"] # guard against typo
|
||||
error("name is not in agent.availableRole $(@__LINE__)")
|
||||
end
|
||||
|
||||
#[PENDING] summarize the oldest 10 message
|
||||
#TODO summarize the oldest 10 message
|
||||
if length(a.chathistory) > maximumMsg
|
||||
summarize(a.chathistory)
|
||||
else
|
||||
d = Dict(:name=> name, :text=> text, :timestamp=> Dates.now())
|
||||
push!(a.chathistory, d)
|
||||
userinput["timestamp"] = Dates.now()
|
||||
push!(a.chathistory, userinput)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -122,33 +114,39 @@ This function takes in a vector of dictionaries and outputs a single string wher
|
||||
|
||||
# Arguments
|
||||
- `vecd::Vector`
|
||||
a vector of dictionaries
|
||||
A vector of dictionaries containing chat messages
|
||||
- `withkey::Bool`
|
||||
whether to include the key in the output text. Default is true
|
||||
Whether to include the name as a prefix in the output text. Default is true
|
||||
- `range::Union{Nothing,UnitRange,Int}`
|
||||
Optional range of messages to include. If nothing, includes all messages
|
||||
|
||||
# Return
|
||||
a string with the formatted dictionaries
|
||||
# Returns
|
||||
A formatted string where each line contains either:
|
||||
- If withkey=true: "name> message\n"
|
||||
- If withkey=false: "message\n"
|
||||
|
||||
# Example
|
||||
```jldoctest
|
||||
|
||||
julia> using Revise
|
||||
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)
|
||||
"John> Hello\nJane> Goodbye\n"
|
||||
```
|
||||
# Signature
|
||||
"""
|
||||
function chatHistoryToText(vecd::Vector; withkey=true)::String
|
||||
function chatHistoryToText(vecd::Vector; withkey=true, range=nothing)::String
|
||||
# Initialize an empty string to hold the final text
|
||||
text = ""
|
||||
|
||||
# Get the elements within the specified range, or all elements if no range provided
|
||||
elements = isnothing(range) ? vecd : vecd[range]
|
||||
|
||||
# Determine whether to include the key in the output text or not
|
||||
if withkey
|
||||
# Loop through each dictionary in the input vector
|
||||
for d in vecd
|
||||
for d in elements
|
||||
# Extract the 'name' and 'text' keys from the dictionary
|
||||
name = d[:name]
|
||||
name = titlecase(d[:name])
|
||||
_text = d[:text]
|
||||
|
||||
# Append the formatted string to the text variable
|
||||
@@ -156,7 +154,7 @@ function chatHistoryToText(vecd::Vector; withkey=true)::String
|
||||
end
|
||||
else
|
||||
# Loop through each dictionary in the input vector
|
||||
for d in vecd
|
||||
for d in elements
|
||||
# Iterate over all key-value pairs in the dictionary
|
||||
for (k, v) in d
|
||||
# Append the formatted string to the text variable
|
||||
@@ -191,268 +189,231 @@ end
|
||||
|
||||
|
||||
|
||||
""" Create a dictionary representing an event with optional details.
|
||||
|
||||
# Arguments
|
||||
- `event_description::Union{String, Nothing}`
|
||||
A description of the event
|
||||
- `timestamp::Union{DateTime, Nothing}`
|
||||
The time when the event occurred
|
||||
- `subject::Union{String, Nothing}`
|
||||
The subject or entity associated with the event
|
||||
- `thought::Union{AbstractDict, Nothing}`
|
||||
Any associated thoughts or metadata
|
||||
- `action_name::Union{String, Nothing}`
|
||||
The name of the action performed (e.g., "CHAT", "CHECKINVENTORY")
|
||||
- `action_input::Union{String, Nothing}`
|
||||
Input or parameters for the action
|
||||
- `location::Union{String, Nothing}`
|
||||
Where the event took place
|
||||
- `equipment_used::Union{String, Nothing}`
|
||||
Equipment involved in the event
|
||||
- `material_used::Union{String, Nothing}`
|
||||
Materials used during the event
|
||||
- `outcome::Union{String, Nothing}`
|
||||
The result or consequence of the event after action execution
|
||||
- `note::Union{String, Nothing}`
|
||||
Additional notes or comments
|
||||
|
||||
# Returns
|
||||
A dictionary with event details as symbol-keyed key-value pairs
|
||||
"""
|
||||
function eventdict(;
|
||||
event_description::Union{String, Nothing}=nothing,
|
||||
timestamp::Union{DateTime, Nothing}=nothing,
|
||||
subject::Union{String, Nothing}=nothing,
|
||||
thought::Union{AbstractDict, Nothing}=nothing,
|
||||
actionname::Union{String, Nothing}=nothing, # "CHAT", "CHECKINVENTORY", "PRESENTBOX", etc
|
||||
actioninput::Union{String, Nothing}=nothing,
|
||||
action_name::Union{String, Nothing}=nothing, # "CHAT", "CHECKINVENTORY", "PRESENT_WINE_GUIDELINE", etc
|
||||
action_input::Union{String, Nothing}=nothing,
|
||||
location::Union{String, Nothing}=nothing,
|
||||
equipment_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,
|
||||
)
|
||||
return Dict{Symbol, Any}(
|
||||
:event_description=> event_description,
|
||||
:timestamp=> timestamp,
|
||||
:subject=> subject,
|
||||
:thought=> thought,
|
||||
:actionname=> actionname,
|
||||
:actioninput=> actioninput,
|
||||
:location=> location,
|
||||
:equipment_used=> equipment_used,
|
||||
:material_used=> material_used,
|
||||
:outcome=> outcome,
|
||||
:note=> note,
|
||||
|
||||
d = Dict{String, Any}(
|
||||
"event_description"=> event_description,
|
||||
"timestamp"=> timestamp,
|
||||
"subject"=> subject,
|
||||
"thought"=> thought,
|
||||
"action_name"=> action_name,
|
||||
"action_input"=> action_input,
|
||||
"location"=> location,
|
||||
"equipment_used"=> equipment_used,
|
||||
"material_used"=> material_used,
|
||||
"observation"=> observation,
|
||||
"note"=> note,
|
||||
)
|
||||
|
||||
return d
|
||||
end
|
||||
|
||||
|
||||
function createTimeline(memory::T1; skiprecent::Integer=0) where {T1<:AbstractVector}
|
||||
events = memory[1:end-skiprecent]
|
||||
""" Create a formatted timeline string from a sequence of events.
|
||||
|
||||
# Arguments
|
||||
- `events::T1`
|
||||
Vector of event dictionaries containing subject, action_input and optional outcome fields
|
||||
Each event dictionary should have the following keys:
|
||||
- :subject - The subject or entity performing the action
|
||||
- :action_input - The action or input performed by the subject
|
||||
- :observation - (Optional) The result or outcome of the action
|
||||
|
||||
# Returns
|
||||
- `timeline::String`
|
||||
A formatted string representing the events with their subjects, actions, and optional outcomes
|
||||
Format: "{index}) {subject}> {action_input} {outcome}\n" for each event
|
||||
|
||||
# Example
|
||||
|
||||
events = [
|
||||
Dict("subject" => "User", "action_input" => "Hello", "observation" => nothing),
|
||||
Dict("subject" => "Assistant", "action_input" => "Hi there!", "observation" => "with a smile")
|
||||
]
|
||||
timeline = createTimeline(events)
|
||||
# 1) User> Hello
|
||||
# 2) Assistant> Hi there! with a smile
|
||||
|
||||
"""
|
||||
function createTimeline(events::T1; eventindex::Union{UnitRange, Nothing}=nothing
|
||||
) where {T1<:AbstractVector}
|
||||
# Initialize empty timeline string
|
||||
timeline = ""
|
||||
for (i, event) in enumerate(events)
|
||||
if event[:outcome] === nothing
|
||||
timeline *= "$i) $(event[:subject])> $(event[:actioninput])\n"
|
||||
|
||||
# Determine which indices to use - either provided range or full length
|
||||
ind =
|
||||
if eventindex !== nothing
|
||||
[eventindex...]
|
||||
else
|
||||
timeline *= "$i) $(event[:subject])> $(event[:actioninput]) $(event[:outcome])\n"
|
||||
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["action_name"] == "CHAT_BOX"
|
||||
# timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"])\n"
|
||||
# elseif event["action_name"] == "CHECKINVENTORY" && event["observation"] === nothing
|
||||
# timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"]), observation: Not done yet.\n"
|
||||
if event["action_name"] == "CHECK_WINE"
|
||||
timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"]), observation: $(event["observation"])\\n"
|
||||
else
|
||||
timeline *= "Event_$i $(event["subject"])> action_name: $(event["action_name"]), action_input: $(event["action_input"])\\n"
|
||||
end
|
||||
end
|
||||
|
||||
# Return formatted timeline string
|
||||
return timeline
|
||||
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
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# This file is machine-generated - editing it directly is not advised
|
||||
|
||||
julia_version = "1.11.4"
|
||||
manifest_format = "2.0"
|
||||
project_hash = "71d91126b5a1fb1020e1098d9d492de2a4438fd2"
|
||||
|
||||
[[deps.Base64]]
|
||||
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
|
||||
version = "1.11.0"
|
||||
|
||||
[[deps.InteractiveUtils]]
|
||||
deps = ["Markdown"]
|
||||
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
|
||||
version = "1.11.0"
|
||||
|
||||
[[deps.Logging]]
|
||||
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
|
||||
version = "1.11.0"
|
||||
|
||||
[[deps.Markdown]]
|
||||
deps = ["Base64"]
|
||||
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
|
||||
version = "1.11.0"
|
||||
|
||||
[[deps.Random]]
|
||||
deps = ["SHA"]
|
||||
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
|
||||
version = "1.11.0"
|
||||
|
||||
[[deps.SHA]]
|
||||
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
|
||||
version = "0.7.0"
|
||||
|
||||
[[deps.Serialization]]
|
||||
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
|
||||
version = "1.11.0"
|
||||
|
||||
[[deps.Test]]
|
||||
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
|
||||
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
|
||||
version = "1.11.0"
|
||||
@@ -0,0 +1,2 @@
|
||||
[deps]
|
||||
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
|
||||
@@ -8,31 +8,46 @@ using Base.Threads
|
||||
|
||||
|
||||
# load config
|
||||
config = JSON3.read("./test/config.json")
|
||||
# config = copy(JSON3.read("../mountvolume/config.json"))
|
||||
config = JSON.parsefile("/appfolder/app/dev/YiemAgent/test/config.json")
|
||||
# config = copy(JSON.parsefile("../mountvolume/config.json"))
|
||||
|
||||
|
||||
function executeSQL(sql::T) where {T<:AbstractString}
|
||||
DBconnection = LibPQ.Connection("host=192.168.88.12 port=10201 dbname=wineDB user=yiemtechnologies password=yiemtechnologies@Postgres_0.0")
|
||||
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)
|
||||
DBconnection = LibPQ.Connection("host=192.168.88.12 port=10203 dbname=SQLVectorDB user=yiemtechnologies password=yiemtechnologies@Postgres_0.0")
|
||||
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)
|
||||
function text2textInstructLLM(prompt::String; maxattempt::Integer=3, modelsize::String="medium",
|
||||
llmkwargs=Dict(
|
||||
:num_ctx => 32768,
|
||||
:temperature => 0.1,
|
||||
)
|
||||
)
|
||||
msgMeta = GeneralUtils.generate_msgMeta(
|
||||
config[:externalservice][:text2textinstruct][:mqtttopic];
|
||||
config[:externalservice][:loadbalancer][:mqtttopic];
|
||||
msgPurpose="inference",
|
||||
senderName="yiemagent",
|
||||
senderId=string(uuid4()),
|
||||
receiverName="text2textinstruct",
|
||||
senderId=sessionId,
|
||||
receiverName="text2textinstruct_$modelsize",
|
||||
mqttBrokerAddress=config[:mqttServerInfo][:broker],
|
||||
mqttBrokerPort=config[:mqttServerInfo][:port],
|
||||
)
|
||||
@@ -41,15 +56,24 @@ function text2textInstructLLM(prompt::String)
|
||||
:msgMeta => msgMeta,
|
||||
:payload => Dict(
|
||||
:text => prompt,
|
||||
:kwargs => Dict(
|
||||
:num_ctx => 16384,
|
||||
:temperature => 0.2,
|
||||
)
|
||||
:kwargs => llmkwargs
|
||||
)
|
||||
)
|
||||
|
||||
_response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=6000)
|
||||
response = nothing
|
||||
for attempts in 1:maxattempt
|
||||
_response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=180, 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
|
||||
@@ -57,11 +81,11 @@ end
|
||||
# get text embedding from a LLM service
|
||||
function getEmbedding(text::T) where {T<:AbstractString}
|
||||
msgMeta = GeneralUtils.generate_msgMeta(
|
||||
config[:externalservice][:text2textinstruct][:mqtttopic];
|
||||
config[:externalservice][:loadbalancer][:mqtttopic];
|
||||
msgPurpose="embedding",
|
||||
senderName="yiemagent",
|
||||
senderId=string(uuid4()),
|
||||
receiverName="text2textinstruct",
|
||||
senderId=sessionId,
|
||||
receiverName="textembedding",
|
||||
mqttBrokerAddress=config[:mqttServerInfo][:broker],
|
||||
mqttBrokerPort=config[:mqttServerInfo][:port],
|
||||
)
|
||||
@@ -72,7 +96,8 @@ function getEmbedding(text::T) where {T<:AbstractString}
|
||||
:text => [text] # must be a vector of string
|
||||
)
|
||||
)
|
||||
response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=6000)
|
||||
|
||||
response = GeneralUtils.sendReceiveMqttMsg(outgoingMsg; timeout=120, maxattempt=3)
|
||||
embedding = response[:response][:embeddings]
|
||||
return embedding
|
||||
end
|
||||
@@ -80,10 +105,8 @@ 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
|
||||
@@ -95,29 +118,29 @@ function findSimilarTextFromVectorDB(text::T1, tablename::T2, embeddingColumnNam
|
||||
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__)
|
||||
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__)
|
||||
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=1) where {T1<:AbstractString, T2<:AbstractString}
|
||||
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]
|
||||
@@ -134,14 +157,14 @@ function insertSQLVectorDB(query::T1, SQL::T2; maxdistance::Integer=1) where {T1
|
||||
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__)
|
||||
println(sql)
|
||||
# println("\n~~~ added new decision to vectorDB ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# println(sql)
|
||||
_ = executeSQLVectorDB(sql)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function similarSommelierDecision(recentevents::T1; maxdistance::Integer=5
|
||||
function similarSommelierDecision(recentevents::T1; maxdistance::Integer=3
|
||||
)::Union{AbstractDict, Nothing} where {T1<:AbstractString}
|
||||
tablename = "sommelier_decision_repository"
|
||||
# find similar
|
||||
@@ -156,7 +179,7 @@ function similarSommelierDecision(recentevents::T1; maxdistance::Integer=5
|
||||
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(JSON3.read(_output_str))
|
||||
output = copy(JSON.parsefile(_output_str))
|
||||
return output
|
||||
else
|
||||
println("\n~~~ similar decision not found, max distance $maxdistance ", @__FILE__, " ", @__LINE__)
|
||||
@@ -174,9 +197,9 @@ function insertSommelierDecision(recentevents::T1, decision::T2; maxdistance::In
|
||||
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 = a.func[:getEmbedding](recentevents)[1]
|
||||
recentevents_embedding = getEmbedding(recentevents)[1]
|
||||
recentevents = replace(recentevents, "'" => "")
|
||||
decision_json = JSON3.write(decision)
|
||||
decision_json = JSON.json(decision)
|
||||
decision_base64 = base64encode(decision_json)
|
||||
decision = replace(decision_json, "'" => "")
|
||||
|
||||
@@ -214,9 +237,11 @@ a = YiemAgent.sommelier(
|
||||
)
|
||||
|
||||
while true
|
||||
println("your respond: ")
|
||||
print("\nyour respond: ")
|
||||
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")
|
||||
end
|
||||
|
||||
@@ -224,14 +249,13 @@ end
|
||||
# response = YiemAgent.conversation(a, Dict(:text=> "I want to get a French red wine under 100."))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"""
|
||||
hello I want to get a bottle of red wine for my boss. I have a budget around 50 dollars. Show me some options.
|
||||
|
||||
I have no idea about his wine taste but he likes spicy food.
|
||||
|
||||
|
||||
"""
|
||||
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
{
|
||||
"mqttServerInfo": {
|
||||
"description": "mqtt server info",
|
||||
"port": 1883,
|
||||
"broker": "mqtt.yiem.cc"
|
||||
},
|
||||
"testingOrProduction": {
|
||||
"value": "testing",
|
||||
"description": "agent status, couldbe testing or production"
|
||||
},
|
||||
"agentid": {
|
||||
"value": "2b74b87a-5413-4fe2-a4d3-405891051680",
|
||||
"description": "a unique id for this agent"
|
||||
},
|
||||
"agentCentralConfigTopic": {
|
||||
"mqtttopic": "/yiem_branch_1/agent/sommelier/backend/config/api/v1.1",
|
||||
"description": "a central agent server's topic to get this agent config"
|
||||
},
|
||||
"servicetopic": {
|
||||
"mqtttopic": [
|
||||
"/yiem/hq/agent/sommelier/backend/prompt/api_v1/testing"
|
||||
],
|
||||
"description": "a topic this agent are waiting for service request"
|
||||
},
|
||||
"role": {
|
||||
"value": "sommelier",
|
||||
"description": "agent role"
|
||||
},
|
||||
"organization": {
|
||||
"value": "yiem_hq",
|
||||
"description": "organization name"
|
||||
},
|
||||
"externalservice": {
|
||||
"text2textinstruct": {
|
||||
"mqtttopic": "/loadbalancer/requestingservice",
|
||||
"description": "text to text service with instruct LLM",
|
||||
"llminfo": {
|
||||
"name": "llama3instruct"
|
||||
}
|
||||
},
|
||||
"virtualWineCustomer_1": {
|
||||
"mqtttopic": "/virtualenvironment/winecustomer",
|
||||
"description": "text to text service with instruct LLM that act as wine customer",
|
||||
"llminfo": {
|
||||
"name": "llama3instruct"
|
||||
}
|
||||
},
|
||||
"text2textchat": {
|
||||
"mqtttopic": "/loadbalancer/requestingservice",
|
||||
"description": "text to text service with instruct LLM",
|
||||
"llminfo": {
|
||||
"name": "llama3instruct"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
using GeneralUtils
|
||||
|
||||
response = "trajectory_evaluation:\nThe trajectory is correct so far. The thought accurately reflects the user's question, and the action taken is a valid attempt to retrieve data from the database that matches the specified criteria.\n\nanswer_evaluation:\nThe observation provides information about two red wines from Bordeaux rive droite in France, which partially answers the question. However, it does not provide a complete answer as it only lists the wine names and characteristics, but does not explicitly state whether there are any other wines that match the criteria.\n\naccepted_as_answer: No\n\nscore: 6\nThe trajectory is mostly correct, but the observation does not fully address the question.\n\nsuggestion: Consider adding more filters or parameters to the database query to retrieve a complete list of wines that match the specified criteria."
|
||||
|
||||
responsedict = GeneralUtils.textToDict(response,
|
||||
["trajectory_evaluation", "answer_evaluation", "accepted_as_answer", "score", "suggestion"],
|
||||
rightmarker=":", symbolkey=true)
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.2 MiB |
+2
-2
@@ -46,7 +46,7 @@ thoughtDict = OrderedDict(
|
||||
: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
|
||||
# @show thoughtJsonStr
|
||||
|
||||
@@ -100,7 +100,7 @@ Here are some examples:
|
||||
|
||||
Let's begin!
|
||||
|
||||
$(JSON3.write(thoughtDict))
|
||||
$(JSON.json(thoughtDict))
|
||||
{Thought_$nextThoughtIndice
|
||||
"""
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ using Base.Threads
|
||||
|
||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
||||
|
||||
config = copy(JSON3.read("config.json"))
|
||||
config = copy(JSON.parsefile("config.json"))
|
||||
|
||||
instanceInternalTopic = config[:serviceInternalTopic][:mqtttopic] * "/1"
|
||||
|
||||
@@ -66,7 +66,7 @@ tools=Dict( # update input format
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -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
@@ -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 |
Reference in New Issue
Block a user