update
This commit is contained in:
+367
-131
@@ -84,7 +84,7 @@ julia> config = Dict(
|
||||
julia> output_thoughtDict = Dict(
|
||||
"thought_1" => "The customer wants to buy a bottle of wine. This is a good start!",
|
||||
"action_1" => Dict{String, Any}(
|
||||
"action"=>"CHATBOX",
|
||||
"action"=>"CHAT_BOX",
|
||||
"input"=>"What occasion are you buying the wine for?"
|
||||
),
|
||||
"observation_1" => ""
|
||||
@@ -94,7 +94,175 @@ julia> output_thoughtDict = Dict(
|
||||
- [] use customerinfo
|
||||
- [] user storeinfo
|
||||
|
||||
"""
|
||||
"""
|
||||
# function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
|
||||
# ) where {T<:agent}
|
||||
# println("\nExecuting YiemAgent decisionMaker()")
|
||||
# # lessonDict = copy(JSON.parsefile("lesson.json"))
|
||||
|
||||
# # lesson =
|
||||
# # if isempty(lessonDict)
|
||||
# # ""
|
||||
# # else
|
||||
# # lessons = Dict{String, Any}()
|
||||
# # for (k, v) in lessonDict
|
||||
# # lessons[k] = lessonDict[k][:lesson]
|
||||
# # end
|
||||
|
||||
# # """
|
||||
# # You have attempted to help the user before and failed, either because your reasoning for the
|
||||
# # recommendation was incorrect or your response did not exactly match the user expectation.
|
||||
# # The following lesson(s) give a plan to avoid failing to help the user in the same way you
|
||||
# # did previously. Use them to improve your strategy to help the user.
|
||||
|
||||
# # Here are some lessons in JSON format:
|
||||
# # $(JSON.json(lessons))
|
||||
|
||||
# # When providing the thought and action for the current trial, that into account these failed
|
||||
# # trajectories and make sure not to repeat the same mistakes and incorrect answers.
|
||||
# # """
|
||||
# # end
|
||||
|
||||
# # recentevents_ind = GeneralUtils.recentElementsIndex(
|
||||
# # length(a.memory["events"]), recentevents; includelatest=true)
|
||||
|
||||
# systemmsg =
|
||||
# """
|
||||
# # Store Policy
|
||||
# - Generally speaking, the store inventory has some wines from France, the United States, Australia, Spain, and Italy, but you won't know exactly until you check your inventory.
|
||||
# - If you found wines in the store's database, they are in stock.
|
||||
# - You can only recommend wines that are currently in our inventory
|
||||
# - Before searching the database for wine, ensure you have at least the following information: 1) budget, 2) wine type, and 3) occasion. Additional details are always helpful. If the user is unsure, provide relevant information and gather insights to make reasonable inferences.
|
||||
# - Ask the user one question at a time.
|
||||
# - Do not ask the user about wine's flavor e.g. floral, citrusy, nutty or some thing similar as these terms cannot be used to search the database.
|
||||
# - Once the user has selected their wine, if you haven't already, ask the user whether they need any further assistance. Do not offer any additional services.
|
||||
# - Only end the conversation when the user explicitly intends to do so. When ending, ensure a polite farewell and an invitation to return in the future.
|
||||
# - Spicy foods should be paired only with light red wines.
|
||||
# - We do not sell organic, sustainable, gluten-free, and sulfite-free wine. Inform the user 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 $(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.
|
||||
|
||||
# # 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.
|
||||
# """
|
||||
|
||||
|
||||
# requiredKeys = ["plan", "action_name", "action_input"]
|
||||
# context =
|
||||
# """
|
||||
# <internal_context_for_assistant>
|
||||
# <thought_history>
|
||||
# $(GeneralUtils.dict_to_string_html(a.memory["shortmem"]))
|
||||
# </thought_history>
|
||||
# </internal_context_for_assistant>
|
||||
|
||||
# """
|
||||
|
||||
# # add context to text of the latest message (in the front).
|
||||
# # use for loop because in openai format, each msg may contain both text and image.
|
||||
# for d in a.chathistory[end]["content"]
|
||||
# if d["type"] == "text"
|
||||
# d["text"] = context * d["text"]
|
||||
# break
|
||||
# end
|
||||
# end
|
||||
# errornote = "N/A"
|
||||
# response = nothing # placeholder for show when error msg show up
|
||||
|
||||
# for attempt in 1:maxattempt
|
||||
# if attempt > 1
|
||||
# println("\nYiemAgent decisionMaker() attempt $attempt/$maxattempt ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# end
|
||||
|
||||
# msg = Dict(
|
||||
# "model" => "gemma-4-E4B-it-UD-Q4_K_XL",
|
||||
# "messages" => a.chathistory,
|
||||
# "temperature" => 0.7
|
||||
# )
|
||||
|
||||
# response = a.context.text2textInstructLLM(a.id, msg)
|
||||
# response = GeneralUtils.clean_json_response(response)
|
||||
|
||||
# response = GeneralUtils.remove_french_accents(response)
|
||||
# think, response = GeneralUtils.extractthink(response)
|
||||
# response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to
|
||||
# response = strip(response)
|
||||
# responsedict = nothing
|
||||
# try
|
||||
# _responsedict = JSON.parse(response)
|
||||
# responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
|
||||
# catch
|
||||
# println("\nERROR YiemAgent decisionMaker() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# continue
|
||||
# end
|
||||
|
||||
# # check whether all answer's key points are in responsedict
|
||||
# ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
# if !ispass
|
||||
# errornote = errormsg
|
||||
# println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
# continue
|
||||
# end
|
||||
|
||||
# if responsedict["action_name"] ∉ ["CHAT_BOX", "CHECK_WINE", "PRESENT_WINE_GUIDELINE", "END_CONVER_GUIDELINE"]
|
||||
# errornote = "Your previous attempt didn't use the given functions"
|
||||
# println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)--> $(responsedict["action_name"])", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# continue
|
||||
# end
|
||||
|
||||
# # println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# # pprintln(responsedict)
|
||||
|
||||
# return responsedict
|
||||
# end
|
||||
# error("DecisionMaker failed to generate a thought ", response)
|
||||
# end
|
||||
function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
|
||||
) where {T<:agent}
|
||||
println("\nExecuting YiemAgent decisionMaker()")
|
||||
@@ -166,30 +334,40 @@ function decisionMaker(a::T; recentevents::Integer=20, maxattempt=10
|
||||
response = String(split(response, ", observation")[1]) # in case LLM generate observation key which it isn't supposed to
|
||||
response = strip(response)
|
||||
responsedict = nothing
|
||||
try
|
||||
_responsedict = JSON.parse(response)
|
||||
responsedict = GeneralUtils.dictify(_responsedict, keytype=String)
|
||||
catch
|
||||
println("\nERROR YiemAgent decisionMaker() failed to parse response: $response", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
if occursin(requiredKeys[2], response)
|
||||
try
|
||||
_responsedict = JSON.parse(response)
|
||||
responsedict = GeneralUtils.dictify(_responsedict; keytype=String, sort_order=requiredKeys)
|
||||
catch
|
||||
println("\nERROR YiemAgent decisionMaker() failed to parse response: $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
end
|
||||
|
||||
# fall back to normal text because LLM default to natural chat when it didn't use action_call
|
||||
else
|
||||
responsedict = OrderedDict(
|
||||
"plan"=> "I will talk to the user",
|
||||
"action_name"=> "CHAT_BOX",
|
||||
"action_input"=> response[2:end-1] # remove { } at the front and back that added by clean_json_response
|
||||
)
|
||||
end
|
||||
|
||||
# check whether all answer's key points are in responsedict
|
||||
ispass, errormsg = checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
ispass, errormsg = GeneralUtils.checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
if !ispass
|
||||
errornote = errormsg
|
||||
println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
continue
|
||||
end
|
||||
|
||||
if responsedict["action_name"] ∉ ["CHATBOX", "CHECKWINE", "PRESENTBOX", "ENDCONVERGUIDELINE"]
|
||||
if responsedict["action_name"] ∉ ["CHAT_BOX", "CHECK_WINE", "PRESENT_WINE_GUIDELINE", "END_CONVER_GUIDELINE"]
|
||||
errornote = "Your previous attempt didn't use the given functions"
|
||||
println("\nERROR YiemAgent decisionMaker() $errornote --(not qualify response)--> $(responsedict["action_name"])", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
end
|
||||
|
||||
println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(Dict(responsedict))
|
||||
# println("\nYiem decisionMaker() ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# pprintln(responsedict)
|
||||
|
||||
return responsedict
|
||||
end
|
||||
@@ -246,7 +424,7 @@ function evaluator(a::T1, timeline, decisiondict, evaluateecontext
|
||||
<You should follow the following guidelines>
|
||||
- The trainee's plan, action_name, and action_input must be logically consistent
|
||||
- The trainee's action_input should be in a proper format as specified by the tools.
|
||||
- The trainee's action name and action input should make sense. For example, if the trainee isn't finished talking, he shouldn't use the ENDCONVERGUIDELINE tool.
|
||||
- The trainee's action name and action input should make sense. For example, if the trainee isn't finished talking, he shouldn't use the END_CONVER_GUIDELINE tool.
|
||||
</You should follow the following guidelines>
|
||||
<You should then respond to the user with>
|
||||
1) trajectory_evaluation: Analyze the trajectory of a solution to answer the user's original question.
|
||||
@@ -390,7 +568,7 @@ message => Dict(
|
||||
"""
|
||||
function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Object{String, Any}},
|
||||
maximumMsg=50)
|
||||
userinput = GeneralUtils.dictify(userinput; keytype=String)
|
||||
userinput = GeneralUtils.dictify(userinput; keytype=String, sort_order=["text"])
|
||||
|
||||
# find text in usermsg
|
||||
usertext = nothing
|
||||
@@ -419,7 +597,7 @@ function conversation(a::sommelier; userinput::Union{Dict{String, Any}, JSON.Obj
|
||||
chatresponse = nothing
|
||||
while chatresponse === nothing
|
||||
action_name, result = think(a)
|
||||
if action_name ∈ ["CHATBOX"]
|
||||
if action_name ∈ ["CHAT_BOX"]
|
||||
chatresponse = result
|
||||
end
|
||||
end
|
||||
@@ -452,7 +630,7 @@ function conversation(a::Union{companion, virtualcustomer}, userinput::Dict;
|
||||
event_description="the user talks to the assistant.",
|
||||
timestamp=Dates.now(),
|
||||
subject="user",
|
||||
action_name="CHATBOX",
|
||||
action_name="CHAT_BOX",
|
||||
action_input=userinput["text"],
|
||||
)
|
||||
)
|
||||
@@ -465,7 +643,7 @@ function conversation(a::Union{companion, virtualcustomer}, userinput::Dict;
|
||||
event_description="the assistant talks to the user.",
|
||||
timestamp=Dates.now(),
|
||||
subject="assistant",
|
||||
action_name="CHATBOX",
|
||||
action_name="CHAT_BOX",
|
||||
action_input=chatresponse,
|
||||
)
|
||||
)
|
||||
@@ -484,17 +662,21 @@ julia>
|
||||
```
|
||||
|
||||
"""
|
||||
function think(a::T)::Union{NamedTuple{(:action_name, :result), Tuple{String, String}}, NamedTuple{(:action_name, :result), Tuple{String, Nothing}}} where {T<:agent}
|
||||
function think(a::T) where {T<:agent}
|
||||
# a.memory[:recap] = generateSituationReport(a, a.context["text"2textInstructLLM]; skiprecent=0)
|
||||
thoughtDict = decisionMaker(a)
|
||||
|
||||
println("\n--- YiemAgent think() 1 ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(thoughtDict)
|
||||
println("---")
|
||||
|
||||
# # map action and input() to llm function
|
||||
# response =
|
||||
# if thoughtDict["action_name"] == "CHATBOX" || thoughtDict["action_name"] == "ENDCONVERGUIDELINE"
|
||||
# if thoughtDict["action_name"] == "CHAT_BOX" || thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
|
||||
# (result=thoughtDict["plan"], errormsg=nothing, success=true)
|
||||
# elseif thoughtDict["action_name"] == "CHECKWINE"
|
||||
# elseif thoughtDict["action_name"] == "CHECK_WINE"
|
||||
# checkwine(a, thoughtDict["action_input"])
|
||||
# elseif thoughtDict["action_name"] == "PRESENTBOX"
|
||||
# elseif thoughtDict["action_name"] == "PRESENT_WINE_GUIDELINE"
|
||||
# (result=thoughtDict["action_input"], errormsg=nothing, success=true)
|
||||
# else
|
||||
# error("undefined LLM function. Requesting $(thoughtDict["action_name"])")
|
||||
@@ -510,23 +692,23 @@ function think(a::T)::Union{NamedTuple{(:action_name, :result), Tuple{String, St
|
||||
# success::Bool = haskey(response, "success") ? response["success"] : false
|
||||
|
||||
result = nothing
|
||||
if thoughtDict["action_name"] ∈ ["CHATBOX"]
|
||||
if thoughtDict["action_name"] ∈ ["CHAT_BOX"]
|
||||
result = thoughtDict["action_input"]
|
||||
elseif thoughtDict["action_name"] == "ENDCONVERGUIDELINE"
|
||||
elseif thoughtDict["action_name"] == "END_CONVER_GUIDELINE"
|
||||
|
||||
# add ENDCONVERGUIDELINE guideline in to scratchpad
|
||||
endconversation_guideline =
|
||||
# add guideline in to context
|
||||
guideline =
|
||||
"""
|
||||
<end_conversation_guideline>
|
||||
- Provide customer with store contact info and business hours
|
||||
- Invite customer to comeback
|
||||
- Provide customer with store contact info and business hours
|
||||
- Invite customer to comeback
|
||||
<store_info>
|
||||
Business Hours: everyday 9.00-20.00
|
||||
Tel. 0863055790
|
||||
</store_info>
|
||||
</end_conversation_guideline>
|
||||
<store_info>
|
||||
Business Hours: everyday 9.00-20.00
|
||||
Tel. 0863055790
|
||||
</store_info>
|
||||
"""
|
||||
thoughtDict["action_result"] = endconversation_guideline
|
||||
thoughtDict["action_result"] = guideline
|
||||
max_ind =
|
||||
if length(a.memory["shortmem"]) == 0
|
||||
0
|
||||
@@ -536,13 +718,59 @@ function think(a::T)::Union{NamedTuple{(:action_name, :result), Tuple{String, St
|
||||
end
|
||||
a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
|
||||
|
||||
elseif thoughtDict["action_name"] ∈ ["PRESENTBOX"] #PENDING
|
||||
chatresponse = presentbox(a, thoughtDict)
|
||||
result = chatresponse
|
||||
elseif thoughtDict["action_name"] ∈ ["PRESENT_WINE_GUIDELINE"] #WORKING
|
||||
|
||||
# add guideline in to context
|
||||
guideline =
|
||||
"""
|
||||
<wine_presentation_guideline>
|
||||
- Provide detailed introductions of the wines you've found to the user.
|
||||
- Explain how the wine could match the user's intention and what its effects might mean for the user's experience.
|
||||
- If multiple wines are available, highlight their differences and provide a comprehensive comparison of how each option aligns with the user's intention and what the potential effects of each option could mean for the user's experience.
|
||||
- Provide your personal recommendation and provide a brief explanation of why you recommend it.
|
||||
- People don't describe wine quality level in numbers so use convertion_table if neccessary
|
||||
<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.
|
||||
3 to 4: May correspond to "medium bodied" or a similar description.
|
||||
4 to 5: May correspond to "med full bodied", "medium full" or a similar description.
|
||||
4 to 5: May correspond to "full bodied" or a similar description.
|
||||
Sweetness level:
|
||||
1 to 2: May correspond to "dry", "no sweet" or a similar description.
|
||||
2 to 3: May correspond to "off dry", "less sweet" or a similar description.
|
||||
3 to 4: May correspond to "semi sweet" or a similar description.
|
||||
4 to 5: May correspond to "sweet" or a similar description.
|
||||
4 to 5: May correspond to "very sweet" or a similar description.
|
||||
Tannin level:
|
||||
1 to 2: May correspond to "low tannin" or a similar description.
|
||||
2 to 3: May correspond to "semi low tannin" or a similar description.
|
||||
3 to 4: May correspond to "medium tannin" or a similar description.
|
||||
4 to 5: May correspond to "semi high tannin" or a similar description.
|
||||
4 to 5: May correspond to "high tannin" or a similar description.
|
||||
Acidity level:
|
||||
1 to 2: May correspond to "low acidity" or a similar description.
|
||||
2 to 3: May correspond to "semi low acidity" or a similar description.
|
||||
3 to 4: May correspond to "medium acidity" or a similar description.
|
||||
4 to 5: May correspond to "semi high acidity" or a similar description.
|
||||
4 to 5: May correspond to "high acidity" or a similar description.
|
||||
</conversion_table>
|
||||
</wine_presentation_guideline>
|
||||
"""
|
||||
thoughtDict["action_result"] = guideline
|
||||
max_ind =
|
||||
if length(a.memory["shortmem"]) == 0
|
||||
0
|
||||
else
|
||||
k = keys(a.memory["shortmem"])
|
||||
maximum(parse.(Int, k))
|
||||
end
|
||||
a.memory["shortmem"]["$(max_ind + 1)"] = thoughtDict
|
||||
|
||||
elseif thoughtDict["action_name"] == "CHECKWINE"
|
||||
df = checkwine(a, thoughtDict["action_input"])
|
||||
thoughtDict["action_result"] = GeneralUtils.dfToString(df)
|
||||
elseif thoughtDict["action_name"] == "CHECK_WINE"
|
||||
result = checkwine(a, thoughtDict["action_input"])
|
||||
|
||||
thoughtDict["action_result"] = result[:result_str]
|
||||
max_ind =
|
||||
if length(a.memory["shortmem"]) == 0
|
||||
0
|
||||
@@ -555,6 +783,9 @@ function think(a::T)::Union{NamedTuple{(:action_name, :result), Tuple{String, St
|
||||
error("condition is not defined ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
end
|
||||
|
||||
println("\n--- YiemAgent think() 2 ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
pprintln(thoughtDict)
|
||||
println("---")
|
||||
return (action_name=thoughtDict["action_name"], result=result)
|
||||
end
|
||||
|
||||
@@ -562,27 +793,32 @@ end
|
||||
function presentbox(a::sommelier, thoughtDict; maxtattempt::Integer=10, recentevents::Integer=10)
|
||||
recentchat_ind = GeneralUtils.recentElementsIndex(length(a.chathistory), recentevents;
|
||||
includelatest=true)
|
||||
recentchat = createChatLog(a.chathistory; index=recentchat_ind)
|
||||
|
||||
systemmsg =
|
||||
"""
|
||||
<situation>
|
||||
You have checked the inventory and found wines that may match what the user wants.
|
||||
</situation>
|
||||
<Your role>
|
||||
Your name is $(a.name). You are a helpful English-speaking assistant, acting as a polite, website-based sommelier for $(a.retailername)'s wine store.
|
||||
</Your role>
|
||||
<Situation>
|
||||
You have checked the inventory and found wines that may match what the user wants
|
||||
</Situation>
|
||||
<Your mission>
|
||||
<objective>
|
||||
Present the wines to the user in a way that keep the conversation smooth and engaging.
|
||||
</Your mission>
|
||||
</objective>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<At each round of conversation, you will be given the following information>
|
||||
Name of the wines that needs to be introduced: name of wines you are going to introduce to the user
|
||||
Database search result: the result of a database search using SQL commands you have found so far
|
||||
</At each round of conversation, you will be given the following information>
|
||||
<You should follow the following guidelines>
|
||||
- Provide detailed introductions of the wines you've found to the user.
|
||||
- Explain how the wine could match the user's intention and what its effects might mean for the user's experience.
|
||||
- If multiple wines are available, highlight their differences and provide a comprehensive comparison of how each option aligns with the user's intention and what the potential effects of each option could mean for the user's experience.
|
||||
- Provide your personal recommendation and provide a brief explanation of why you recommend it.
|
||||
|
||||
</You should follow the following guidelines>
|
||||
<You should then respond to the user with>
|
||||
dialogue: Your presentation to the user
|
||||
@@ -715,102 +951,102 @@ function presentbox(a::sommelier, thoughtDict; maxtattempt::Integer=10, recentev
|
||||
error("presentbox() failed to generate a response")
|
||||
end
|
||||
|
||||
function endconversation(a::sommelier, thoughtDict; maxattempt::Integer=10)
|
||||
text =
|
||||
"""
|
||||
---
|
||||
# function endconversation(a::sommelier, thoughtDict; maxattempt::Integer=10)
|
||||
# text =
|
||||
# """
|
||||
# ---
|
||||
|
||||
"""
|
||||
requiredKeys = ["dialogue"]
|
||||
# """
|
||||
# requiredKeys = ["dialogue"]
|
||||
|
||||
system_msg = Dict(
|
||||
"role" => "system",
|
||||
"content" => [
|
||||
Dict("type" => "text", "text" => systemmsg),
|
||||
]
|
||||
)
|
||||
# system_msg = Dict(
|
||||
# "role" => "system",
|
||||
# "content" => [
|
||||
# Dict("type" => "text", "text" => systemmsg),
|
||||
# ]
|
||||
# )
|
||||
|
||||
for attempt in 1:maxattempt
|
||||
# for attempt in 1:maxattempt
|
||||
|
||||
unformatPrompt =
|
||||
[
|
||||
Dict("name" => "system", "text" => systemmsg),
|
||||
]
|
||||
# unformatPrompt =
|
||||
# [
|
||||
# Dict("name" => "system", "text" => systemmsg),
|
||||
# ]
|
||||
|
||||
# put in model format
|
||||
prompt = GeneralUtils.formatLLMtext(unformatPrompt, a.llmFormatName)
|
||||
# add info
|
||||
prompt = prompt * context
|
||||
# # put in model format
|
||||
# prompt = GeneralUtils.formatLLMtext(unformatPrompt, a.llmFormatName)
|
||||
# # add info
|
||||
# prompt = prompt * context
|
||||
|
||||
response = a.context.text2textInstructLLM(prompt; senderId=a.id)
|
||||
response = GeneralUtils.deFormatLLMtext(response, a.llmFormatName)
|
||||
response = GeneralUtils.remove_french_accents(response)
|
||||
# response = replace(response, '$'=>"USD")
|
||||
think, response = GeneralUtils.extractthink(response)
|
||||
# response = a.context.text2textInstructLLM(prompt; senderId=a.id)
|
||||
# response = GeneralUtils.deFormatLLMtext(response, a.llmFormatName)
|
||||
# response = GeneralUtils.remove_french_accents(response)
|
||||
# # response = replace(response, '$'=>"USD")
|
||||
# think, response = GeneralUtils.extractthink(response)
|
||||
|
||||
responsedict = nothing
|
||||
try
|
||||
responsedict = copy(JSON.parsefile(response))
|
||||
catch
|
||||
println("\nERROR YiemAgent generatechat() failed to parse response: $response", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
end
|
||||
# responsedict = nothing
|
||||
# try
|
||||
# responsedict = copy(JSON.parsefile(response))
|
||||
# catch
|
||||
# println("\nERROR YiemAgent generatechat() failed to parse response: $response", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# continue
|
||||
# end
|
||||
|
||||
# check whether all answer's key points are in responsedict
|
||||
ispass, errormsg = checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
if !ispass
|
||||
errornote = errormsg
|
||||
println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
continue
|
||||
end
|
||||
# # check whether all answer's key points are in responsedict
|
||||
# ispass, errormsg = checkAgentResponse_JSON(responsedict, requiredKeys)
|
||||
# if !ispass
|
||||
# errornote = errormsg
|
||||
# println("\nERROR YiemAgent generatechat() $errornote --(not qualify response)> $responsedict", @__FILE__, ":", @__LINE__, " $(Dates.now())\n")
|
||||
# continue
|
||||
# end
|
||||
|
||||
# sometime the model response like this "here's how I would respond: ..."
|
||||
if occursin("respond:", response)
|
||||
errornote = "Your previous response contains 'response:' which is not allowed"
|
||||
println("\nERROR YiemAgent generatechat() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
elseif occursin("Your thoughts:", response) || occursin("your thoughts:", response)
|
||||
errornote = "You don't need to put 'Your thoughts:' in your response"
|
||||
println("\nERROR YiemAgent generatechat() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
end
|
||||
response = GeneralUtils.remove_french_accents(response)
|
||||
response = replace(response, '*'=>"")
|
||||
response = replace(response, '$' => "USD")
|
||||
response = replace(response, '`' => "")
|
||||
response = replace(response, "<|eot_id|>"=>"")
|
||||
# # sometime the model response like this "here's how I would respond: ..."
|
||||
# if occursin("respond:", response)
|
||||
# errornote = "Your previous response contains 'response:' which is not allowed"
|
||||
# println("\nERROR YiemAgent generatechat() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# continue
|
||||
# elseif occursin("Your thoughts:", response) || occursin("your thoughts:", response)
|
||||
# errornote = "You don't need to put 'Your thoughts:' in your response"
|
||||
# println("\nERROR YiemAgent generatechat() $errornote ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# continue
|
||||
# end
|
||||
# response = GeneralUtils.remove_french_accents(response)
|
||||
# response = replace(response, '*'=>"")
|
||||
# response = replace(response, '$' => "USD")
|
||||
# response = replace(response, '`' => "")
|
||||
# response = replace(response, "<|eot_id|>"=>"")
|
||||
|
||||
# check whether an agent recommend wines before checking inventory or recommend wines
|
||||
# outside its inventory
|
||||
# ask LLM whether there are any winery mentioned in the response
|
||||
mentioned_winery = detectWineryName(a, response)
|
||||
if mentioned_winery != "None"
|
||||
mentioned_winery = String.(strip.(split(mentioned_winery, ",")))
|
||||
# # check whether an agent recommend wines before checking inventory or recommend wines
|
||||
# # outside its inventory
|
||||
# # ask LLM whether there are any winery mentioned in the response
|
||||
# mentioned_winery = detectWineryName(a, response)
|
||||
# if mentioned_winery != "None"
|
||||
# mentioned_winery = String.(strip.(split(mentioned_winery, ",")))
|
||||
|
||||
# check whether the wine is in event
|
||||
isWineInEvent = false
|
||||
for winename in mentioned_winery
|
||||
for event in a.memory["events"]
|
||||
if event["observation"] !== nothing && occursin(winename, event["observation"])
|
||||
isWineInEvent = true
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
# # check whether the wine is in event
|
||||
# isWineInEvent = false
|
||||
# for winename in mentioned_winery
|
||||
# for event in a.memory["events"]
|
||||
# if event["observation"] !== nothing && occursin(winename, event["observation"])
|
||||
# isWineInEvent = true
|
||||
# break
|
||||
# end
|
||||
# end
|
||||
# end
|
||||
|
||||
# then the agent is not supposed to recommend the wine
|
||||
if isWineInEvent == false
|
||||
errornote = "You recommended wines that are not in your inventory before. Please only recommend wines that you have previously found in your inventory."
|
||||
println("\nERROR YiemAgent generatechat() $errornote $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
continue
|
||||
end
|
||||
end
|
||||
result = responsedict["dialogue"]
|
||||
# # then the agent is not supposed to recommend the wine
|
||||
# if isWineInEvent == false
|
||||
# errornote = "You recommended wines that are not in your inventory before. Please only recommend wines that you have previously found in your inventory."
|
||||
# println("\nERROR YiemAgent generatechat() $errornote $response ", @__FILE__, ":", @__LINE__, " $(Dates.now())")
|
||||
# continue
|
||||
# end
|
||||
# end
|
||||
# result = responsedict["dialogue"]
|
||||
|
||||
return result
|
||||
end
|
||||
error("generatechat failed to generate a response")
|
||||
end
|
||||
# return result
|
||||
# end
|
||||
# error("generatechat failed to generate a response")
|
||||
# end
|
||||
|
||||
|
||||
function generatequestion(a, text2textInstructLLM::Function, timeline)::String
|
||||
|
||||
Reference in New Issue
Block a user