add new function

This commit is contained in:
2026-06-30 21:02:25 +07:00
parent e54454b099
commit fb7942a965
2 changed files with 49 additions and 2 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
name = "GeneralUtils"
uuid = "c6c72f09-b708-4ac8-ac7c-2084d70108fe"
version = "0.4.2"
version = "0.4.3"
authors = ["tonaerospace <tonaerospace.etc@gmail.com>"]
[deps]
+48 -1
View File
@@ -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