Path: redb-route/redb.Route.Llm.Tools/JsonPathDsl.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/JsonPathDsl.cs ---- using System.Linq; using Newtonsoft.Json.Linq; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Llm.Tools; /// /// DSL extension that wires a JsonPath query into a route step. Reads /// {"json":"<document>","path":"$.foo[0].bar"} from /// exchange.In.Body, evaluates the path against the embedded document /// and writes the matched value (re-serialised as JSON) — or the literal /// null when nothing matched — to exchange.Out.Body. /// /// Uses Newtonsoft JToken.SelectToken / SelectTokens directly, /// the same engine that backs /// redb.Route.Expressions.JsonPathExpression (which is built for /// in-route property extraction and trips on the JValue → JToken path /// for primitives). The full Newtonsoft JsonPath dialect is supported: /// recursive descent (..), wildcards ([*]), filters /// ([?(@.foo == 1)]), slicing ([1:5]). /// /// /// /// From("direct:llm.json_path") /// .AsLlmTool("json_path").Description("Query a JSON document.").Then() /// .JsonPath(new JsonPathOptions()); /// /// /// public static class JsonPathDsl { /// Adds a JsonPath query step. Uses default options when is null. public static IRouteDefinition JsonPath(this IRouteDefinition self, JsonPathOptions? options = null) { ArgumentNullException.ThrowIfNull(self); options ??= new JsonPathOptions(); return self.Process((exchange, _) => { var (json, path) = ParseInput(exchange.In.Body); if (json.Length > options.MaxJsonChars) throw new ArgumentException( $"Input json exceeds MaxJsonChars ({options.MaxJsonChars}); got {json.Length}."); JToken? token; try { var root = JToken.Parse(json); if (path.Contains("..") || path.Contains("[?") || path.Contains("[*]") || System.Text.RegularExpressions.Regex.IsMatch(path, @"\[\d+:\d+\]")) { var matches = root.SelectTokens(path).ToArray(); token = matches.Length == 0 ? null : new JArray(matches.Cast().ToArray()); } else { token = root.SelectToken(path); } } catch (Newtonsoft.Json.JsonException ex) { throw new ArgumentException($"JsonPath evaluation failed: {ex.Message}", ex); } exchange.Out ??= exchange.In.Clone(); exchange.Out.Body = token is null ? "null" : token.ToString(Newtonsoft.Json.Formatting.None); exchange.Out.Headers["llm.json_path.matched"] = token is not null; return Task.CompletedTask; }); } private static (string Json, string Path) ParseInput(object? body) { using var doc = LlmToolJson.ParseObject(body, "JsonPath"); return ( LlmToolJson.RequiredString(doc.RootElement, "json", "JsonPath"), LlmToolJson.OptionalString(doc.RootElement, "path") ?? "$"); } }