Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5829c82d05 | |||
| c7a98f1710 |
@@ -14,6 +14,7 @@ module YiemAgent
|
||||
|
||||
include("tools/getWeather.jl")
|
||||
include("tools/getTime.jl")
|
||||
include("tools/searchWine.jl")
|
||||
include("tools/writeTool.jl")
|
||||
|
||||
include("toolRegistry.jl")
|
||||
@@ -22,6 +23,7 @@ module YiemAgent
|
||||
function register_all_tools(store::toolRegistry.toolStore)
|
||||
registerTool(store, getWeatherTool())
|
||||
registerTool(store, getTimeTool())
|
||||
registerTool(store, searchWineTool())
|
||||
registerTool(store, writeToolTool())
|
||||
registerTool(store, listTool(store))
|
||||
return store.tools
|
||||
|
||||
+12
-8
@@ -5,7 +5,7 @@ export yiemAgent, _agentLoop, OpenAiToUserMessage, _extractToolCalls,
|
||||
executeToolCallsParallel, executeToolCalls
|
||||
|
||||
using JSON, DataStructures, Dates, UUIDs, HTTP, Random, PrettyPrinting, Serialization,
|
||||
DataFrames, Base.Threads, NATS
|
||||
DataFrames, Base.Threads, NATS, LibPQ
|
||||
using GeneralUtils
|
||||
using ..type, ..utils, ..toolRegistry
|
||||
|
||||
@@ -379,7 +379,7 @@ function _processMessage(
|
||||
# call prepareContext()
|
||||
state = agentState(systemPrompt, nothing, tools, agentMsgHistory)
|
||||
agentEventSink("_processMessage 8 _state.messages length $(length(agentMsgHistory))")
|
||||
preparedContext = prepareContext(state, agentEventSink)
|
||||
preparedContext = prepareContext(state, agentEventSink, llmCall)
|
||||
agentEventSink("_processMessage 9 _state.messages length $(length(agentMsgHistory))")
|
||||
# Call formatMessagesForLLM() to format for LLM
|
||||
formattedMessages = formatMessagesForLLM(preparedContext, agentEventSink)
|
||||
@@ -409,6 +409,7 @@ function _processMessage(
|
||||
beforeToolCall,
|
||||
afterToolCall,
|
||||
parallelToolExecute ? "parallel" : "sequential",
|
||||
llmCall,
|
||||
)
|
||||
|
||||
signal = abortSignal(false)
|
||||
@@ -1000,13 +1001,14 @@ function executePreparedToolCall(
|
||||
prep::preparedToolCall,
|
||||
signal::Union{Nothing,abortSignal},
|
||||
agentEventSink,
|
||||
llmCall::Union{Any,Nothing}=nothing,
|
||||
)::executedOutcome
|
||||
agentEventSink("executePreparedToolCall 1")
|
||||
agentEventSink("executePreparedToolCall 2")
|
||||
agentEventSink("executePreparedToolCall 3")
|
||||
|
||||
try
|
||||
result = prep.tool.execute(prep.toolCall.id, prep.args, signal, agentEventSink)
|
||||
result = prep.tool.execute(prep.toolCall.id, prep.args, signal, agentEventSink, llmCall)
|
||||
agentEventSink(result.content[1].text)
|
||||
agentEventSink("executePreparedToolCall 4")
|
||||
return executedOutcome(result, false)
|
||||
@@ -1184,6 +1186,7 @@ function executeToolCallsSequential(
|
||||
signal::abortSignal,
|
||||
agentEventSink,
|
||||
)::agentToolCallBatch
|
||||
llmCall = config.llmCall
|
||||
agentEventSink("executeToolCallsSequential 1")
|
||||
finalizedCalls = finalizedOutcome[]
|
||||
messages = toolResultMessage[]
|
||||
@@ -1199,8 +1202,7 @@ function executeToolCallsSequential(
|
||||
agentEventSink("executeToolCallsSequential 2-2")
|
||||
else
|
||||
agentEventSink("executeToolCallsSequential 3")
|
||||
#XXX
|
||||
executed = executePreparedToolCall(prep, signal, agentEventSink)
|
||||
executed = executePreparedToolCall(prep, signal, agentEventSink, llmCall)
|
||||
agentEventSink("executeToolCallsSequential 3-1")
|
||||
finalized = finalizeExecutedToolCall(context, assistantMsg, prep, executed, config,
|
||||
signal, agentEventSink)
|
||||
@@ -1287,6 +1289,7 @@ function executeToolCallsParallel(
|
||||
)::agentToolCallBatch
|
||||
|
||||
entries = Union{finalizedOutcome,Task}[]
|
||||
llmCall = config.llmCall
|
||||
|
||||
for tc in toolCalls
|
||||
agentEventSink(toolExecStartEvent(tc.id, tc.name, tc.arguments))
|
||||
@@ -1300,7 +1303,7 @@ function executeToolCallsParallel(
|
||||
push!(entries, finalized)
|
||||
else
|
||||
t = Task() do
|
||||
executed = executePreparedToolCall(prep, signal, agentEventSink)
|
||||
executed = executePreparedToolCall(prep, signal, agentEventSink, llmCall)
|
||||
finalized = finalizeExecutedToolCall(context, assistantMsg, prep, executed, config, signal)
|
||||
agentEventSink(toolExecEndEvent(finalized.toolCall.id, finalized.toolCall.name,
|
||||
finalized.result, finalized.isError))
|
||||
@@ -1388,6 +1391,7 @@ function executeToolCalls(
|
||||
agentEventSink,
|
||||
)::agentToolCallBatch
|
||||
|
||||
llmCall = config.llmCall
|
||||
agentEventSink("_executeToolCalls 1")
|
||||
hasSequential = false
|
||||
for tc in toolCalls
|
||||
@@ -1400,11 +1404,11 @@ function executeToolCalls(
|
||||
agentEventSink("_executeToolCalls 2")
|
||||
if config.toolExecution == "sequential" || hasSequential
|
||||
agentEventSink("_executeToolCalls 3")
|
||||
return executeToolCallsSequential(context, assistantMsg, toolCalls, config, signal,
|
||||
return executeToolCallsSequential(context, assistantMsg, toolCalls, config, signal,
|
||||
agentEventSink)
|
||||
else
|
||||
agentEventSink("_executeToolCalls 4")
|
||||
return executeToolCallsParallel(context, assistantMsg, toolCalls, config, signal,
|
||||
return executeToolCallsParallel(context, assistantMsg, toolCalls, config, signal,
|
||||
agentEventSink)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -45,7 +45,7 @@ Execute the getTime tool.
|
||||
Returns mock time data for the given timezone or city.
|
||||
"""
|
||||
function getTimeExecute(toolCallId::String, args::Dict{String,Any}, signal::Union{Nothing,abortSignal},
|
||||
onPartialResult)
|
||||
onPartialResult, llmCall=nothing)
|
||||
tz = get(args, "timezone", nothing)
|
||||
city = get(args, "city", "")
|
||||
if tz !== nothing
|
||||
|
||||
@@ -7,7 +7,7 @@ Execute the getWeather tool.
|
||||
Returns mock weather data for the given city and temperature units.
|
||||
"""
|
||||
function getWeatherExecute(toolCallId::String, args::Dict{String,Any}, signal::Union{Nothing,abortSignal},
|
||||
agentEventSink)
|
||||
agentEventSink, llmCall=nothing)
|
||||
|
||||
agentEventSink("Getting weather...")
|
||||
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
using .type
|
||||
using LibPQ, DataFrames, JSON, DataStructures
|
||||
using Dates, Random, HTTP
|
||||
using GeneralUtils
|
||||
|
||||
# ── Database config — update for your environment ───────────────────────
|
||||
const DB_CONFIG = Dict{String,Any}(
|
||||
"host" => "localhost",
|
||||
"port" => 5432,
|
||||
"dbname" => "winedb",
|
||||
"user" => "postgres",
|
||||
"password" => "",
|
||||
)
|
||||
|
||||
"""
|
||||
Execute the search_wine_database! tool.
|
||||
|
||||
Uses the agent's LLM to generate SQL from the free-form text query,
|
||||
then executes it against the wine database and returns formatted results.
|
||||
"""
|
||||
function searchWineExecute(
|
||||
toolCallId::String,
|
||||
args::Dict{String,Any},
|
||||
signal::Union{Nothing,abortSignal},
|
||||
agentEventSink,
|
||||
llmCall,
|
||||
)::agentToolResult
|
||||
#WORKING
|
||||
search_query = get(args, "searchQuery", "")::String
|
||||
|
||||
if isempty(search_query)
|
||||
return agentToolResult(
|
||||
[textContent("Please provide a search query for the wine database.")],
|
||||
Dict{Any,Any}(), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
agentEventSink("searchWineExecute: query=$search_query")
|
||||
|
||||
# ── SQL generation prompt ───────────────────────────────────────────
|
||||
systemmsg = """
|
||||
# database_search_guidelines
|
||||
- Keep SQL queries focused only on the provided information.
|
||||
- Use wildcard character (%) to search more effectively.
|
||||
- Do not create any table in the database.
|
||||
- Text information in the database is usually stored in lower case.
|
||||
If your search returns empty, try using lower case to search.
|
||||
- Overly strict conditions usually yield empty results.
|
||||
- Use ILIKE for case-insensitive text matching.
|
||||
- Only output the SQL query — do not wrap it in backticks or add comments.
|
||||
|
||||
# situation
|
||||
You are a wine store database assistant. You will be given a user's
|
||||
natural language search query and the database table schema.
|
||||
|
||||
# objective
|
||||
Generate a single SQL query to find wines matching the user's request.
|
||||
|
||||
# your responsibility includes
|
||||
Fulfill the objective.
|
||||
|
||||
# you should respond with ONLY the SQL query string, ending with ';'
|
||||
"""
|
||||
|
||||
table_schema = """
|
||||
CREATE TABLE wine (
|
||||
wine_id uuid primary key default gen_random_uuid (),
|
||||
wine_name varchar(128) not null,
|
||||
winery varchar(128) not null,
|
||||
vintage integer not null,
|
||||
region varchar(128) not null,
|
||||
country varchar(128) not null,
|
||||
wine_type varchar(128) not null,
|
||||
grape varchar(128) not null,
|
||||
serving_temperature varchar(128) not null,
|
||||
intensity integer,
|
||||
sweetness integer,
|
||||
tannin integer,
|
||||
acidity integer,
|
||||
fizziness integer,
|
||||
tasting_notes text,
|
||||
image_url jsonb,
|
||||
manufacturer_sku text,
|
||||
note text,
|
||||
other_attributes jsonb,
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp,
|
||||
description text
|
||||
);
|
||||
|
||||
CREATE TABLE retailer (
|
||||
retailer_id uuid primary key default gen_random_uuid (),
|
||||
retailer_name varchar(128) not null,
|
||||
retailer_username varchar(128) not null,
|
||||
retailer_password varchar(128) not null,
|
||||
retailer_address text not null,
|
||||
country varchar(128) not null,
|
||||
contact_person varchar(128) not null,
|
||||
telephone varchar(128) not null,
|
||||
email varchar(128) not null,
|
||||
note text,
|
||||
other_attributes jsonb,
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp,
|
||||
description text
|
||||
);
|
||||
|
||||
CREATE TABLE retailer_wine (
|
||||
retailer_id uuid references retailer(retailer_id),
|
||||
wine_id uuid references wine(wine_id),
|
||||
constraint retailer_wine_id primary key (retailer_id, wine_id),
|
||||
price NUMERIC(10, 2),
|
||||
currency varchar(3) not null,
|
||||
created_time timestamptz default current_timestamp,
|
||||
updated_time timestamptz default current_timestamp
|
||||
);
|
||||
"""
|
||||
|
||||
context = "<internal_context_for_assistant>\n<database_table_schema>\n$table_schema\n</database_table_schema>\n</internal_context_for_assistant>\n\n"
|
||||
input = context * "User query: $search_query\n\nGenerate the SQL query:"
|
||||
|
||||
# ── Call LLM for SQL generation ────────────────────────────────────
|
||||
max_attempts = 5
|
||||
generated_sql = nothing
|
||||
|
||||
for attempt in 1:max_attempts
|
||||
msg = Dict(
|
||||
"messages" => [
|
||||
Dict(
|
||||
"role" => "system",
|
||||
"content" => [Dict("type" => "text", "text" => systemmsg)],
|
||||
),
|
||||
Dict(
|
||||
"role" => "user",
|
||||
"content" => [Dict("type" => "text", "text" => input)],
|
||||
),
|
||||
],
|
||||
"temperature" => 0.7,
|
||||
)
|
||||
|
||||
llm_response = llmCall(msg)
|
||||
|
||||
# Clean the response — extract SQL from potential markdown/code blocks
|
||||
sql_text = _clean_sql_response(llm_response)
|
||||
|
||||
# Validate it looks like SQL
|
||||
if _is_valid_sql(sql_text)
|
||||
generated_sql = sql_text
|
||||
agentEventSink("searchWine: generated SQL (attempt $attempt)\n$sql_text")
|
||||
break
|
||||
else
|
||||
agentEventSink("searchWine: invalid SQL attempt $attempt: $sql_text")
|
||||
end
|
||||
end
|
||||
|
||||
if generated_sql === nothing
|
||||
return agentToolResult(
|
||||
[textContent("Failed to generate a valid SQL query for your search. Please try rephrasing.")],
|
||||
Dict{Any,Any}("error" => "sql_generation_failed"), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
# ── Execute SQL ────────────────────────────────────────────────────
|
||||
try
|
||||
conn = LibPQ.Connection(DB_CONFIG)
|
||||
|
||||
# Ensure LIMIT to prevent large result sets
|
||||
sanitized_sql = _ensure_limit(generated_sql)
|
||||
agentEventSink("searchWine: executing\n$sanitized_sql")
|
||||
|
||||
result = LibPQ.execute(conn, sanitized_sql)
|
||||
close(conn)
|
||||
|
||||
if !LibPQ.hasdata(result)
|
||||
return agentToolResult(
|
||||
[textContent("No wines found matching your search. Try loosening your criteria.")],
|
||||
Dict{Any,Any}("count" => 0), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
df = DataFrame(result)
|
||||
num_rows, num_cols = size(df)
|
||||
|
||||
if num_cols > 30
|
||||
return agentToolResult(
|
||||
[textContent("The result has more than 30 columns. Please be more specific in your search.")],
|
||||
Dict{Any,Any}("error" => "too_many_columns"), nothing, false
|
||||
)
|
||||
end
|
||||
|
||||
# Randomly sample up to 2 rows for display if more than 2 results
|
||||
display_df = df
|
||||
if num_rows > 2
|
||||
idx = sample(1:num_rows, min(2, num_rows), replace=false)
|
||||
display_df = df[idx, :]
|
||||
end
|
||||
|
||||
# Convert to vector of dicts
|
||||
result_vec = GeneralUtils.dfToVectorDict(display_df)
|
||||
|
||||
# Fetch bottle images if available
|
||||
for d in result_vec
|
||||
image_url_json_str = get(d, "image_url", nothing)
|
||||
if image_url_json_str !== nothing && !isempty(string(image_url_json_str))
|
||||
try
|
||||
image_url_json_obj = JSON.parse(string(image_url_json_str))
|
||||
base_url = "http://192.168.88.106:8080/"
|
||||
if haskey(image_url_json_obj, "bottle")
|
||||
url = base_url * string(image_url_json_obj["bottle"])
|
||||
image_data = HTTP.get(url)
|
||||
image_base64_string = base64encode(image_data.body)
|
||||
d["image"] = image_base64_string
|
||||
end
|
||||
catch
|
||||
# Skip image fetch on error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Format results as readable text
|
||||
result_str = _format_wine_results(display_df)
|
||||
|
||||
return agentToolResult(
|
||||
[textContent(result_str)],
|
||||
Dict{Any,Any}(
|
||||
"count" => num_rows,
|
||||
"displayed" => size(display_df, 1),
|
||||
),
|
||||
nothing, false
|
||||
)
|
||||
|
||||
catch e
|
||||
errMsg = sprint(showerror, e)
|
||||
return agentToolResult(
|
||||
[textContent("Database error: $errMsg")],
|
||||
Dict{Any,Any}("error" => errMsg), nothing, false
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
"""
|
||||
Extract a SQL query string from the LLM response, handling potential
|
||||
markdown code blocks, extra text, or JSON wrapping.
|
||||
"""
|
||||
function _clean_sql_response(response)::String
|
||||
text = string(response)
|
||||
|
||||
# Try to extract from code block
|
||||
if occursin("```", text)
|
||||
extracted = GeneralUtils.extract_triple_backtick_text(text)
|
||||
if !isempty(extracted)
|
||||
text = extracted[1]
|
||||
# Remove "sql\n" prefix if present
|
||||
if startswith(text, "sql\n") || startswith(text, "SQL\n")
|
||||
text = text[5:end]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Remove JSON wrapping if present
|
||||
text = strip(text)
|
||||
if startswith(text, "{") && occursin("action_input", text)
|
||||
# Parse as JSON and extract action_input
|
||||
try
|
||||
parsed = JSON.parse(text)
|
||||
if parsed isa Dict
|
||||
text = get(parsed, "action_input", text)
|
||||
end
|
||||
catch
|
||||
# Keep original
|
||||
end
|
||||
end
|
||||
|
||||
# Extract SQL keywords to find the actual query
|
||||
lines = split(strip(text), '\n')
|
||||
sql_lines = String[]
|
||||
for line in lines
|
||||
stripped = strip(line)
|
||||
if occursin(r"(?i)(SELECT|FROM|WHERE|JOIN|ORDER|LIMIT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH)", stripped)
|
||||
# Take everything from this line to the end
|
||||
push!(sql_lines, line)
|
||||
elseif !isempty(sql_lines)
|
||||
# Continue collecting if we already found SQL
|
||||
push!(sql_lines, line)
|
||||
end
|
||||
end
|
||||
|
||||
result = join(sql_lines, "\n")
|
||||
|
||||
# Ensure it ends with semicolon
|
||||
result = strip(result)
|
||||
if !endswith(result, ";")
|
||||
result *= ";"
|
||||
end
|
||||
|
||||
return result
|
||||
end
|
||||
|
||||
"""
|
||||
Check if a string looks like a valid SQL query.
|
||||
"""
|
||||
function _is_valid_sql(sql::String)::Bool
|
||||
sql = strip(sql)
|
||||
# Must start with a SQL keyword
|
||||
has_sql_keyword = occursin(r"(?i)(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH)\s", sql) ||
|
||||
occursin(r"(?i)(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH)\s*;", sql)
|
||||
# Must end with semicolon
|
||||
has_semicolon = endswith(sql, ";")
|
||||
# Must not be too short (reject single words)
|
||||
reasonable_length = length(sql) > 10
|
||||
return has_sql_keyword && has_semicolon && reasonable_length
|
||||
end
|
||||
|
||||
"""
|
||||
Ensure the SQL query has a LIMIT clause to prevent loading excessive data.
|
||||
"""
|
||||
function _ensure_limit(sql::String)::String
|
||||
sql = strip(sql)
|
||||
if !occursin(r"(?i)LIMIT", sql)
|
||||
# Remove existing semicolon, add LIMIT, re-add semicolon
|
||||
if endswith(sql, ";")
|
||||
sql = sql[1:end-1]
|
||||
end
|
||||
sql *= " ORDER BY RANDOM() LIMIT 2;"
|
||||
end
|
||||
return sql
|
||||
end
|
||||
|
||||
"""
|
||||
Format wine database results as human-readable text.
|
||||
"""
|
||||
function _format_wine_results(df::DataFrame)::String
|
||||
lines = String[]
|
||||
num_rows = size(df, 1)
|
||||
|
||||
for i in 1:num_rows
|
||||
row = df[i, :]
|
||||
push!(lines, "$(i). $(get(row, :wine_name, "Unknown")) $(get(row, :vintage, ""))")
|
||||
|
||||
winery = get(row, :winery, "Unknown")
|
||||
region = get(row, :region, "Unknown")
|
||||
country = get(row, :country, "Unknown")
|
||||
push!(lines, " Winery: $winery")
|
||||
push!(lines, " Region: $region, $country")
|
||||
|
||||
grape = get(row, :grape, "Unknown")
|
||||
wtype = get(row, :wine_type, "Unknown")
|
||||
push!(lines, " Grape: $grape")
|
||||
push!(lines, " Type: $wtype")
|
||||
|
||||
sweetness = get(row, :sweetness, "N/A")
|
||||
intensity = get(row, :intensity, "N/A")
|
||||
tannin_val = get(row, :tannin, "N/A")
|
||||
acidity = get(row, :acidity, "N/A")
|
||||
push!(lines, " Profile: Sweetness: $sweetness, Intensity: $intensity, Tannin: $tannin_val, Acidity: $acidity")
|
||||
|
||||
tasting = get(row, :tasting_notes, nothing)
|
||||
if tasting !== nothing && !isempty(string(tasting))
|
||||
tn = string(tasting)
|
||||
limit = min(200, length(tn))
|
||||
push!(lines, " Notes: $(tn[1:limit])$(length(tn) > limit ? "..." : "")")
|
||||
end
|
||||
|
||||
price = get(row, :price, "N/A")
|
||||
currency = get(row, :currency, "")
|
||||
retailer = get(row, :retailer_name, "N/A")
|
||||
push!(lines, " Price: $price $currency at $retailer")
|
||||
push!(lines, "")
|
||||
end
|
||||
|
||||
return join(lines, "\n")
|
||||
end
|
||||
|
||||
"""
|
||||
Define and return the searchWine agentTool.
|
||||
"""
|
||||
function searchWineTool()::agentTool
|
||||
return agentTool(
|
||||
name = "searchWine",
|
||||
label = "Search Wine Database",
|
||||
description = "Search the wine database for wines matching a free-text query. Uses the LLM to generate SQL and execute it against the database. Returns wine details including name, winery, vintage, tasting notes, and price.",
|
||||
inputSchema = Dict{String,Any}(
|
||||
"type" => "object",
|
||||
"properties" => Dict(
|
||||
"searchQuery" => Dict(
|
||||
"type" => "string",
|
||||
"description" => "Free-text description of the wine you're looking for, e.g., 'a light-bodied red wine from France under 50 dollars'",
|
||||
),
|
||||
),
|
||||
"required" => ["searchQuery"],
|
||||
),
|
||||
execute = searchWineExecute,
|
||||
prepareArguments = nothing,
|
||||
validateRequiredArgs = nothing,
|
||||
parallelToolExecute = false,
|
||||
)
|
||||
end
|
||||
@@ -130,7 +130,7 @@ function writeToolTool()::agentTool
|
||||
),
|
||||
"required" => ["name", "label", "description", "inputSchema", "executeCode"]
|
||||
),
|
||||
execute = (toolCallId::String, args::Dict{String,Any}, signal::Union{Nothing,abortSignal}, onPartialResult) -> begin
|
||||
execute = (toolCallId::String, args::Dict{String,Any}, signal::Union{Nothing,abortSignal}, onPartialResult, llmCall=nothing) -> begin
|
||||
tool_name = get(args, "name", "")::String
|
||||
tool_label = get(args, "label", tool_name)::String
|
||||
tool_description = get(args, "description", "")::String
|
||||
|
||||
@@ -358,6 +358,7 @@ struct agentContext # Snapshot of the agent's conversa
|
||||
systemPrompt::String # System prompt for the agent
|
||||
messages::Vector{agentMessage} # Conversation messages
|
||||
tools::Union{OrderedDict{String, agentTool}, Nothing} # Available tools keyed by name
|
||||
llmCall::Union{Any, Nothing} # LLM call function (for tools that need it)
|
||||
end
|
||||
|
||||
|
||||
@@ -451,6 +452,7 @@ struct agentLoopConfig
|
||||
beforeToolCall::Union{Function, Nothing}
|
||||
afterToolCall::Union{Function, Nothing}
|
||||
toolExecution::String
|
||||
llmCall::Union{Any, Nothing} # LLM call function (for tools like searchWine)
|
||||
end
|
||||
|
||||
"""
|
||||
|
||||
+2
-2
@@ -109,7 +109,7 @@ prepareContext(state).messages == deepcopy(state.messages)
|
||||
# end
|
||||
```
|
||||
"""
|
||||
function prepareContext(state::agentState, agentEventSink)::agentContext
|
||||
function prepareContext(state::agentState, agentEventSink, llmCall=nothing)::agentContext
|
||||
|
||||
#TODO filter tools from state.tools based on user intend in user message and tool description
|
||||
filteredTools = state.tools
|
||||
@@ -120,7 +120,7 @@ function prepareContext(state::agentState, agentEventSink)::agentContext
|
||||
#TODO add system prompt, adjust/modify and inject additional context into messages
|
||||
preparedMessages = deepcopy(state.messages) # messages that will be send to LLM
|
||||
|
||||
agentCtx = agentContext(preparedSystemPrompt, preparedMessages, filteredTools)
|
||||
agentCtx = agentContext(preparedSystemPrompt, preparedMessages, filteredTools, llmCall)
|
||||
|
||||
return agentCtx
|
||||
end
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,375 +0,0 @@
|
||||
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" => "<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.""",
|
||||
),
|
||||
)
|
||||
|
||||
""" 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"),
|
||||
]
|
||||
),
|
||||
Dict(
|
||||
"role" => "user",
|
||||
"content" => [
|
||||
Dict("type" => "text", "text" => "<internal_context_for_assistant>
|
||||
LLM context here...
|
||||
</internal_context_for_assistant>
|
||||
Do you know this wine? Just give me brief intro."
|
||||
),
|
||||
Dict(
|
||||
"type" => "image_url",
|
||||
"image_url" => Dict("url" => data1_uri)
|
||||
),
|
||||
]
|
||||
),
|
||||
]
|
||||
|
||||
shortmem = Dict(
|
||||
"1"=> Dict("plan"=> "...", "action_name"=> "...", "action_input"=> "...", "action_result"=> "..."),
|
||||
"2"=> Dict("plan"=> "...", "action_name"=> "...", "action_input"=> "...", "action_result"=> "..."),
|
||||
...
|
||||
)
|
||||
"""
|
||||
memory = Dict{String, Any}(
|
||||
"shortmem"=> OrderedDict{String, Any}(),
|
||||
"scratchpad"=> "",
|
||||
"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" => "<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
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
end # module type
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user