Path: redb-route/redb.Route.Llm.Tools/XPathDsl.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/XPathDsl.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using FrameworkXPathExpression = redb.Route.Expressions.XPathExpression;
namespace redb.Route.Llm.Tools;
///
/// DSL extension that wires an XPath query into a route step. Reads
/// {"xml":"<document>","xpath":"//book[1]/title"} from
/// exchange.In.Body, evaluates the path against the embedded document
/// using (W3C XPath 1.0 — same engine
/// the rest of redb.Route uses for xpath(...) in routes) and writes
/// the matched value as a string — or the literal null when nothing
/// matched — to exchange.Out.Body.
///
///
/// From("direct:llm.xpath")
/// .AsLlmTool("xpath").Description("Query an XML document.").Then()
/// .XPath(new XPathOptions());
///
///
///
public static class XPathDsl
{
/// Adds an XPath query step. Uses default options when is null.
public static IRouteDefinition XPath(this IRouteDefinition self, XPathOptions? options = null)
{
ArgumentNullException.ThrowIfNull(self);
options ??= new XPathOptions();
return self.Process((exchange, _) =>
{
var (xml, xpath) = ParseInput(exchange.In.Body);
if (xml.Length > options.MaxXmlChars)
throw new ArgumentException(
$"Input xml exceeds MaxXmlChars ({options.MaxXmlChars}); got {xml.Length}.");
var child = exchange.CreateChild(new Message(xml));
string? value;
try
{
value = new FrameworkXPathExpression(xpath).Evaluate(child);
}
catch (InvalidOperationException)
{
value = null;
}
exchange.Out ??= exchange.In.Clone();
exchange.Out.Body = value is null ? "null" : value;
exchange.Out.Headers["llm.xpath.matched"] = value is not null;
return Task.CompletedTask;
});
}
private static (string Xml, string XPath) ParseInput(object? body)
{
using var doc = LlmToolJson.ParseObject(body, "XPath");
return (
LlmToolJson.RequiredString(doc.RootElement, "xml", "XPath"),
LlmToolJson.OptionalString(doc.RootElement, "xpath") ?? "/");
}
}