Path: redb-route/redb.Route.Llm.Tools/LlmToolJson.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm.Tools/LlmToolJson.cs ---- using System.Text.Json; namespace redb.Route.Llm.Tools; /// /// Internal JSON helpers shared by the LLM-tool DSL extensions /// (, , , /// , , ). /// internal static class LlmToolJson { /// /// Parses as a JSON object. Accepts either a /// or any other type whose renders the JSON document. /// Throws on null / non-object / malformed input. /// /// The raw exchange body (typically exchange.In.Body). /// Tool name used to build a helpful error message. /// A disposable whose root is an object. public static JsonDocument ParseObject(object? body, string toolName) { if (body is null) throw new ArgumentException($"{toolName} input is empty — expected a JSON object."); var raw = body as string ?? body.ToString() ?? string.Empty; JsonDocument doc; try { doc = JsonDocument.Parse(raw); } catch (JsonException ex) { throw new ArgumentException($"{toolName} input is not valid JSON.", ex); } if (doc.RootElement.ValueKind != JsonValueKind.Object) { doc.Dispose(); throw new ArgumentException($"{toolName} input must be a JSON object."); } return doc; } /// Reads a required string property from a JSON object root. public static string RequiredString(JsonElement root, string name, string toolName) { if (!root.TryGetProperty(name, out var v) || v.ValueKind != JsonValueKind.String) throw new ArgumentException($"{toolName} input must include '{name}' as a string."); return v.GetString() ?? string.Empty; } /// Reads an optional string property, returning when missing. public static string? OptionalString(JsonElement root, string name, string? fallback = null) => root.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : fallback; /// Reads an optional bool property, returning when missing or not a bool. public static bool OptionalBool(JsonElement root, string name, bool fallback = false) => root.TryGetProperty(name, out var v) ? v.ValueKind switch { JsonValueKind.True => true, JsonValueKind.False => false, _ => fallback } : fallback; /// Reads an optional integer property, returning when missing or not numeric. public static int? OptionalInt(JsonElement root, string name, int? fallback = null) => root.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var i) ? i : fallback; }