diff --git a/Project.toml b/Project.toml index 393d3f9..45c05ba 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "GeneralUtils" uuid = "c6c72f09-b708-4ac8-ac7c-2084d70108fe" -version = "0.4.2" +version = "0.4.3" authors = ["tonaerospace "] [deps] diff --git a/src/interface.jl b/src/interface.jl index 54359ff..8ff94b9 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -6,7 +6,8 @@ export noNegative!, randomWithProb, randomChoiceWithProb, findIndex, limitvalue, matMul_3Dto4D_batchwise, isNotEqual, linearToCartesian, vectorMax, findMax, multiply_last, multiplyRandomElements, replaceElements, replaceElements!, isBetween, isLess, allTrue, getStringBetweenCharacters, mkDictPath!, dict_to_string_html, - getDictPath, detectKeywordVariation, textToDict, dictify, ordereddictify + getDictPath, detectKeywordVariation, textToDict, dictify, ordereddictify, + clean_json_response using JSON, DataStructures, Distributions, Random, Dates, UUIDs, DataFrames, CSV using ..util, ..communication @@ -1696,6 +1697,52 @@ function dict_to_string_html(d::AbstractDict; indent_level=1, indent_str=" ") return join(lines, "\n") end +""" Convert a plain text string containing key-value pairs into a JSON-formatted string. + +This function takes text containing key-value pairs (typically extracted from LLM responses) +and wraps them in proper JSON braces to create a valid JSON string. It cleans the input +by removing common formatting artifacts like braces, code block markers, and language +specifiers before wrapping the content. + +# Arguments +- `text::String` + A string containing key-value pairs, typically in the format `key: value, key: value`. + May contain leading/trailing braces, code block markers (```), or language specifiers + (e.g., `json`) that will be removed. + +# Return +- `String` + A JSON-formatted string with the key-value pairs wrapped in `{}` braces. + +# Notes +- The function removes `{`, `}`, `````, and `json` from the input before wrapping. +- The output is always wrapped in curly braces to create valid JSON structure. +- This is typically used to sanitize LLM responses that contain key-value data + but may include formatting artifacts. + +# Examples +```jldoctest +julia> text = "thought: Hello, action: CHATBOX, input: How can I help?" +julia> clean_json_response(text) +"{thought: Hello, action: CHATBOX, input: How can I help?}" + +julia> text = "{thought: Hello, action: CHATBOX}" +julia> clean_json_response(text) +"{thought: Hello, action: CHATBOX}" + +julia> text = "```json{thought: Hello, action: CHATBOX}```" +julia> clean_json_response(text) +"{thought: Hello, action: CHATBOX}" +``` +""" +function clean_json_response(text::String) + text = replace(text, '{' => "") + text = replace(text, '}' => "") + text = replace(text, "```" => "") + text = replace(text, "json" => "") + text = '{' * text * '}' + return text +end