module type export agent, sommelier, companion, virtualcustomer, agentcontext 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 find_related_tables_for_user_question::Function pg_conn_str::String agentconfig::AbstractDict end abstract type agent end mutable struct sommelier <: agent name::String # agent name id::String # agent id retailername::String retailerid::String tools::Dict maxHistoryMsg::Integer # e.g. 21th and earlier messages will get summarized 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( context::agentcontext, # agent functions, db connect and other context ; name::String= "Assistant", id::String= string(uuid4()), retailername::String= "not specified", retailerid::String= "not specified", maxHistoryMsg::Integer= 20, chathistory::Vector{Dict{String, Any}} = Vector{Dict{String, Any}}(), llmFormatName::String= "granite3" ) tools = Dict( # update input format "chatbox"=> Dict( "description" => "Useful for when you need to ask the user for more context. Do not ask the user their own question.", "input" => """Input is a text in JSON format.{\"Q1\": \"How are you doing?\", \"Q2\": \"How may I help you?\"}""", "output" => "" , ), "winestock"=> Dict( "description" => "A handy tool for searching wine in your inventory that match the user preferences.", "input" => """Input is a JSON-formatted string that contains a detailed and precise search query.{\"wine type\": \"rose\", \"price\": \"max 35\", \"sweetness level\": \"sweet\", \"intensity level\": \"light bodied\", \"Tannin level\": \"low\", \"Acidity level\": \"low\"}""", "output" => """Output are wines that match the search query in JSON format.""", ), ) """ 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:;base64," --- chathistory= [ Dict( "role" => "system", "content" => [ Dict("type" => "text", "text" => "You are a helpful assistant"), ] ), Dict( "role" => "user", "content" => [ Dict("type" => "text", "text" => " LLM context here... Do you know this wine? Just give me brief intro." ), Dict( "type" => "image_url", "image_url" => Dict("url" => data1_uri) ), ] ), ] shortmem = Dict( "1"=> Dict("plan"=> "...", "action_name"=> "...", "action_input"=> "...", "action_result"=> "..."), "2"=> Dict("plan"=> "...", "action_name"=> "...", "action_input"=> "...", "action_result"=> "..."), ... ) """ memory = Dict{String, Any}( "shortmem"=> OrderedDict{String, Any}(), "scratchpad"=> "", "recap"=> OrderedDict{String, Any}(), ) newAgent = sommelier( name, id, retailername, retailerid, tools, maxHistoryMsg, chathistory, memory, 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. - 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. - User usually ask for something similar. This means you should use the search term based on the profile they like. # 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 in JSON format 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. # 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. "SEARCH_WINE_DATABASE", allows you to search information about wines you want in your inventory's database. The input is strictly supported search term including: retailer_name, wine price, winery, name, vintage, region, country, type of wine, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity. Example query 1: "Dry, full-bodied red wine from Burgundy, France. Grape varietal could be 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 from Tuscany, Italy or Bordeaux, 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" => "Useful for when you need to ask the user for more context. Do not ask the user their own question.", "input" => """Input is a text in JSON format.{\"Q1\": \"How are you doing?\", \"Q2\": \"How may I help you?\"}""", "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 end end # module type