-
-
Notifications
You must be signed in to change notification settings - Fork 605
fix json format use llm #1275
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
fix json format use llm #1275
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d6dafcf
fix json format use llm
yileicn 83bdcbd
Use LLM to fix JSON formatting in the instruction api.
yileicn f5f0381
Co-authored-by: adenchen123 <[email protected]>
yileicn 7e0d4b1
Merge branch 'master' of https://github.com/SciSharp/BotSharp
yileicn ec87c54
fix compile error
yileicn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
src/Infrastructure/BotSharp.Abstraction/Instructs/Enums/ResponseFormatType.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Text; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace BotSharp.Abstraction.Instructs.Enums | ||
| { | ||
| public enum ResponseFormatType | ||
| { | ||
| Text = 0, | ||
| Json = 1 | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
src/Infrastructure/BotSharp.Abstraction/Utilities/IJsonRepairService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| namespace BotSharp.Abstraction.Utilities; | ||
|
|
||
| /// <summary> | ||
| /// Service for repairing malformed JSON using LLM. | ||
| /// </summary> | ||
| public interface IJsonRepairService | ||
| { | ||
| /// <summary> | ||
| /// Repair malformed JSON and deserialize to target type. | ||
| /// </summary> | ||
| /// <typeparam name="T">Target type</typeparam> | ||
| /// <param name="malformedJson">The malformed JSON string</param> | ||
| /// <returns>Deserialized object or default if repair fails</returns> | ||
| Task<T?> RepairAndDeserialize<T>(string malformedJson); | ||
|
|
||
| /// <summary> | ||
| /// Repair malformed JSON string. | ||
| /// </summary> | ||
| /// <param name="malformedJson">The malformed JSON string</param> | ||
| /// <returns>Repaired JSON string</returns> | ||
| Task<string> Repair(string malformedJson); | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
yileicn marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
src/Infrastructure/BotSharp.Core/JsonRepair/JsonRepairPlugin.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| using BotSharp.Abstraction.Plugins; | ||
| using BotSharp.Abstraction.Utilities; | ||
| using Microsoft.Extensions.Configuration; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
|
|
||
| namespace BotSharp.Core.JsonRepair; | ||
|
|
||
| public class JsonRepairPlugin : IBotSharpPlugin | ||
| { | ||
| public string Id => "b2e8f9c4-6d5a-4f28-cbe1-cf8b92e344cb"; | ||
| public string Name => "JSON Repair"; | ||
| public string Description => "Repair malformed JSON using LLM"; | ||
|
|
||
| public void RegisterDI(IServiceCollection services, IConfiguration config) | ||
| { | ||
| services.AddScoped<IJsonRepairService, JsonRepairService>(); | ||
| } | ||
| } | ||
|
|
113 changes: 113 additions & 0 deletions
113
src/Infrastructure/BotSharp.Core/JsonRepair/JsonRepairService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| using BotSharp.Abstraction.Templating; | ||
|
|
||
| namespace BotSharp.Core.JsonRepair; | ||
|
|
||
| /// <summary> | ||
| /// Service for repairing malformed JSON using LLM. | ||
| /// </summary> | ||
| public class JsonRepairService : IJsonRepairService | ||
| { | ||
| private readonly IServiceProvider _services; | ||
| private readonly ILogger<JsonRepairService> _logger; | ||
|
|
||
| private const string ROUTER_AGENT_ID = "01fcc3e5-9af7-49e6-ad7a-a760bd12dc4a"; | ||
| private const string TEMPLATE_NAME = "json_repair"; | ||
|
|
||
| public JsonRepairService( | ||
| IServiceProvider services, | ||
| ILogger<JsonRepairService> logger) | ||
| { | ||
| _services = services; | ||
| _logger = logger; | ||
| } | ||
|
|
||
| public async Task<string> Repair(string malformedJson) | ||
| { | ||
| var json = malformedJson.CleanJsonStr(); | ||
| if (IsValidJson(json)) return json; | ||
|
|
||
| var repairedJson = await RepairByLLM(json); | ||
| if(IsValidJson(repairedJson)) return repairedJson; | ||
|
|
||
| // Try repairing again if still invalid | ||
| repairedJson = await RepairByLLM(json); | ||
|
|
||
| return IsValidJson(repairedJson) ? repairedJson : json; | ||
| } | ||
|
|
||
| public async Task<T?> RepairAndDeserialize<T>(string malformedJson) | ||
| { | ||
| var json = await Repair(malformedJson); | ||
|
|
||
| return json.Json<T>(); | ||
| } | ||
|
|
||
|
|
||
| private static bool IsValidJson(string malformedJson) | ||
| { | ||
| if (string.IsNullOrWhiteSpace(malformedJson)) | ||
| return false; | ||
|
|
||
| try | ||
| { | ||
| JsonDocument.Parse(malformedJson); | ||
| return true; | ||
| } | ||
| catch (JsonException) | ||
| { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| private async Task<string> RepairByLLM(string malformedJson) | ||
| { | ||
| var agentService = _services.GetRequiredService<IAgentService>(); | ||
| var router = await agentService.GetAgent(ROUTER_AGENT_ID); | ||
|
|
||
| var template = router.Templates?.FirstOrDefault(x => x.Name == TEMPLATE_NAME)?.Content; | ||
| if (string.IsNullOrEmpty(template)) | ||
| { | ||
| _logger.LogWarning($"Template '{TEMPLATE_NAME}' not found in agent '{ROUTER_AGENT_ID}'"); | ||
| return malformedJson; | ||
| } | ||
|
|
||
| var render = _services.GetRequiredService<ITemplateRender>(); | ||
| var prompt = render.Render(template, new Dictionary<string, object> | ||
| { | ||
| { "input", malformedJson } | ||
| }); | ||
|
|
||
| try | ||
| { | ||
| var completion = CompletionProvider.GetChatCompletion(_services, | ||
| provider: router?.LlmConfig?.Provider, | ||
| model: router?.LlmConfig?.Model); | ||
|
|
||
| var agent = new Agent | ||
| { | ||
| Id = Guid.Empty.ToString(), | ||
| Name = "JsonRepair", | ||
| Instruction = "You are a JSON repair expert." | ||
| }; | ||
|
|
||
| var dialogs = new List<RoleDialogModel> | ||
| { | ||
| new RoleDialogModel(AgentRole.User, prompt) | ||
| { | ||
| FunctionName = TEMPLATE_NAME | ||
| } | ||
| }; | ||
|
|
||
| var response = await completion.GetChatCompletions(agent, dialogs); | ||
|
|
||
| _logger.LogInformation($"JSON repair result: {response.Content}"); | ||
| return response.Content.CleanJsonStr(); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogError(ex, "Failed to repair and deserialize JSON"); | ||
| return malformedJson; | ||
| } | ||
| } | ||
| } | ||
|
|
3 changes: 3 additions & 0 deletions
3
...tSharp.Core/data/agents/01fcc3e5-9af7-49e6-ad7a-a760bd12dc4a/templates/json_repair.liquid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| Fix the malformed JSON below and output valid JSON only. | ||
|
|
||
| {{ input }} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.