Coverage for app / tools / registry.py: 78%
1228 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2Built-in tool registry for svc-ai.
4Each entry in BUILTIN_TOOLS defines:
5 - name: canonical identifier (matches ToolConfig.name sent from svc-core)
6 - description: human-readable summary
7 - schema: OpenAI function-calling schema (returned to svc-core for caching/display)
8 - factory: callable(config: dict) → LangChain StructuredTool
9"""
11from __future__ import annotations
13import ast
14import asyncio
15import json
16import math
17import operator
18import re
19from collections.abc import Iterable, Mapping, Sequence
20from dataclasses import dataclass, field
21from enum import Enum
22from html.parser import HTMLParser
23from typing import Any, Callable, Literal
25import httpx
26from langchain_core.tools import StructuredTool
27from pydantic import BaseModel, Field, ValidationError, model_validator
29from app.common.settings import get_settings
30from app.documents.markdown import unwrap_link_targets
31from app.documents.spec import DocumentSpec, StoredDocument, document_fence
32from app.documents.visuals.mermaid import vocabulary as mermaid_vocabulary
33from app.util.time import aware_utcnow
34from app.util.schema import openai_schema_from_model, tool_description
35from app.util.registry import BuiltinRegistry
36from app.util import source_registry, source_trailers, text_pages, vocab
37from app.tools import limits
38from app.tools.clarify import ASK_USER_SCHEMA, ask_user_tool_factory
39from app.tools.wire import platform_owned
40from app.tools.web import (
41 URL_FETCH_SCHEMA,
42 WEB_SEARCH_SCHEMA,
43 url_fetch_config_from_web_search,
44 url_fetch_tool_factory,
45 web_search_tool_factory,
46)
47from app.tools.web.fetch import (
48 PublicOnlyTransport,
49 Resolver,
50 assert_public_https_url,
51 system_resolver,
52)
53from app.tools.web.policy import DomainPolicy
56# ---------------------------------------------------------------------------
57# Input schemas
58# ---------------------------------------------------------------------------
61class QueryKnowledgeBaseInput(BaseModel):
62 query: str = Field(
63 description="The question or query to search for in the knowledge base"
64 )
65 top_k: int = Field(default=5, description="Number of results to retrieve")
68class QueryKnowledgeGraphInput(BaseModel):
69 query: str = Field(
70 description=(
71 "Exact entity name from the graph schema OR an entity type label to browse all entities "
72 "of that type (e.g. 'Person', 'Technology'). Never pass natural-language phrases or questions."
73 )
74 )
75 depth: int = Field(
76 default=2,
77 description="Number of relationship hops to traverse from matching entities",
78 )
81# ---------------------------------------------------------------------------
82# ToolDefinition dataclass
83# ---------------------------------------------------------------------------
86class ToolCategory(str, Enum):
87 """
88 Determines how a tool is assigned to agents.
90 GENERAL — injected automatically into every agent. Use for universal
91 reasoning utilities (arithmetic, time, web lookup) that any
92 agent role can legitimately call.
94 SPECIALIST — must be explicitly wired to an agent via its tool config.
95 Use for domain-specific capabilities that require specific
96 configuration (e.g. a particular KB collection) or that
97 should not be universally available (e.g. external APIs,
98 data-source connectors).
99 """
101 GENERAL = "general"
102 SPECIALIST = "specialist"
105@dataclass
106class ToolDefinition:
107 name: str
108 description: str
109 schema: dict[str, Any] # OpenAI function schema for display / svc-core caching
110 factory: Callable[[dict[str, Any]], StructuredTool]
111 category: ToolCategory = field(default=ToolCategory.SPECIALIST)
112 #: The tool fetches from the web, so it takes the agent's web_search
113 #: domain policy whenever its own config names no domains
114 #: (``run_tool_config``) — an operator's allowlist holds for every tool
115 #: that reaches out, not only for the search.
116 inherits_web_policy: bool = False
119# time
122def _datetime_factory(config: dict[str, Any]) -> StructuredTool:
123 def date_time() -> str:
124 return aware_utcnow().isoformat()
126 return StructuredTool.from_function(
127 func=date_time,
128 name="date_time",
129 description="""
130 Get the current UTC time in ISO format.
131 """,
132 )
135_DATETIME_SCHEMA: dict[str, Any] = {
136 "type": "function",
137 "function": {
138 "name": "date_time",
139 "description": "Get the current UTC time in ISO format",
140 "parameters": {"type": "object", "properties": {}, "required": []},
141 },
142}
145# ---------------------------------------------------------------------------
146# query_knowledge_base
147# ---------------------------------------------------------------------------
150def _query_kb_factory(config: dict[str, Any]) -> StructuredTool:
151 _collection = config.get("collection", "")
152 _top_k = config.get("top_k", 5)
154 async def query_knowledge_base(query: str, top_k: int = _top_k) -> str:
155 from app.models.spec import RAGConfig
156 from app.services import rag as rag_service
158 if not _collection:
159 return "query_knowledge_base: no collection configured for this tool."
160 rag_config = RAGConfig(collection=_collection, top_k=top_k)
161 return await rag_service.search(rag_config, query)
163 return StructuredTool.from_function(
164 coroutine=query_knowledge_base,
165 name="query_knowledge_base",
166 description="Query a RAG knowledge base collection for relevant information",
167 args_schema=QueryKnowledgeBaseInput,
168 )
171def _query_kg_factory(config: dict[str, Any]) -> StructuredTool:
172 _knowledge_id = config.get("knowledge_id", "")
173 _depth = config.get("depth", 2)
175 async def query_knowledge_graph(query: str, depth: int = _depth) -> str:
176 from app.util import neo4j_client
178 if not _knowledge_id:
179 return "query_knowledge_graph: no knowledge_id configured for this tool."
180 return await neo4j_client.query_and_format(
181 _knowledge_id, query, depth=depth, limit=10
182 )
184 return StructuredTool.from_function(
185 coroutine=query_knowledge_graph,
186 name="query_knowledge_graph",
187 description=(
188 "Traverse a knowledge graph to find entities and their relationships. "
189 "Returns matching entities and their connections up to the specified depth."
190 ),
191 args_schema=QueryKnowledgeGraphInput,
192 )
195_QUERY_KG_SCHEMA: dict[str, Any] = openai_schema_from_model(
196 "query_knowledge_graph",
197 "Traverse a knowledge graph to find entities and their relationships",
198 QueryKnowledgeGraphInput,
199)
202_QUERY_KB_SCHEMA: dict[str, Any] = openai_schema_from_model(
203 "query_knowledge_base",
204 "Query a RAG knowledge base collection for relevant information",
205 QueryKnowledgeBaseInput,
206)
209# ---------------------------------------------------------------------------
210# calculate — safe AST expression evaluator
211# ---------------------------------------------------------------------------
213_CALC_OPS: dict[type, Any] = {
214 ast.Add: operator.add,
215 ast.Sub: operator.sub,
216 ast.Mult: operator.mul,
217 ast.Div: operator.truediv,
218 ast.FloorDiv: operator.floordiv,
219 ast.Mod: operator.mod,
220 ast.Pow: operator.pow,
221 ast.USub: operator.neg,
222 ast.UAdd: operator.pos,
223}
225_CALC_FUNCS: dict[str, Any] = {
226 "sqrt": math.sqrt,
227 "log": math.log,
228 "log2": math.log2,
229 "log10": math.log10,
230 "floor": math.floor,
231 "ceil": math.ceil,
232 "round": round,
233 "abs": abs,
234 "min": min,
235 "max": max,
236 "pow": pow,
237 "sin": math.sin,
238 "cos": math.cos,
239 "tan": math.tan,
240 "asin": math.asin,
241 "acos": math.acos,
242 "atan": math.atan,
243 "atan2": math.atan2,
244 "sinh": math.sinh,
245 "cosh": math.cosh,
246 "tanh": math.tanh,
247 "exp": math.exp,
248 "factorial": math.factorial,
249 "gamma": math.gamma,
250 "lgamma": math.lgamma,
251 "comb": math.comb,
252 "perm": math.perm,
253 "gcd": math.gcd,
254 "hypot": math.hypot,
255 "degrees": math.degrees,
256 "radians": math.radians,
257}
259_CALC_NAMES: dict[str, float] = {
260 "pi": math.pi,
261 "e": math.e,
262 "inf": math.inf,
263 "tau": math.tau,
264}
267def _safe_eval_expr(node: ast.expr) -> float | int:
268 """Recursively evaluate an AST expression node using only safe operations."""
269 if isinstance(node, ast.Constant):
270 if isinstance(node.value, (int, float)):
271 return node.value
272 raise ValueError(f"Unsupported constant: {node.value!r}")
274 if isinstance(node, ast.BinOp):
275 fn = _CALC_OPS.get(type(node.op))
276 if fn is None:
277 raise ValueError(f"Unsupported operator: {type(node.op).__name__}")
278 return fn(_safe_eval_expr(node.left), _safe_eval_expr(node.right))
280 if isinstance(node, ast.UnaryOp):
281 fn = _CALC_OPS.get(type(node.op))
282 if fn is None:
283 raise ValueError(f"Unsupported unary operator: {type(node.op).__name__}")
284 return fn(_safe_eval_expr(node.operand))
286 if isinstance(node, ast.Call):
287 if not isinstance(node.func, ast.Name):
288 raise ValueError("Only named functions are allowed (e.g. sqrt, log)")
289 fn = _CALC_FUNCS.get(node.func.id)
290 if fn is None:
291 raise ValueError(
292 f"Unknown function: {node.func.id!r}. Allowed: {sorted(_CALC_FUNCS)}"
293 )
294 if node.keywords:
295 raise ValueError("Keyword arguments are not supported in expressions")
296 args = [_safe_eval_expr(a) for a in node.args]
297 return fn(*args)
299 if isinstance(node, ast.Name):
300 if node.id in _CALC_NAMES:
301 return _CALC_NAMES[node.id]
302 raise ValueError(
303 f"Unknown name: {node.id!r}. Allowed constants: {sorted(_CALC_NAMES)}"
304 )
306 raise ValueError(f"Unsupported expression type: {type(node).__name__}")
309class CalculateInput(BaseModel):
310 expression: str = Field(
311 description=(
312 "A safe mathematical expression to evaluate, OR a solve() call to find "
313 "roots/solutions of an equation.\n\n"
314 "Numeric mode — supports: +, -, *, /, //, **, % and functions: "
315 "sqrt, log, log2, log10, floor, ceil, round, abs, min, max, pow, "
316 "sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, "
317 "exp, factorial, gamma, lgamma, comb, perm, gcd, hypot, "
318 "degrees, radians. "
319 "Constants: pi, e, inf, tau.\n\n"
320 "Symbolic solver — use solve(expression, variable) to find roots:\n"
321 " solve(x**2 - 4, x) → roots of x²-4=0\n"
322 " solve(x**3 - 6*x**2 + 11*x - 6, x) → roots of a cubic\n"
323 " solve(x**6 - 132*x**5 + ..., x) → roots of any polynomial\n"
324 "Returns exact symbolic form plus numeric approximations. "
325 "Complex roots are flagged clearly.\n\n"
326 "Examples: '2 ** 10', 'sqrt(144)', 'gamma(pi/2 + 1)', "
327 "'round(1/3, 4)', 'comb(10, 3)', 'solve(x**2 - 4, x)', "
328 "'solve(x**3 - 6*x**2 + 11*x - 6, x)'"
329 )
330 )
333# ---------------------------------------------------------------------------
334# solve() — SymPy-backed symbolic equation solver
335# ---------------------------------------------------------------------------
338def _sympy_approx(val: Any) -> str:
339 """Return a human-readable numeric approximation of a SymPy expression.
341 Returns an empty string when the value cannot be evaluated numerically
342 (e.g. it contains unresolved free symbols).
343 """
344 try:
345 import sympy
347 n = complex(sympy.N(val, 12))
348 if abs(n.imag) < 1e-9 * (abs(n.real) + 1):
349 r = n.real
350 return str(int(r)) if r == int(r) else f"{r:.10g}"
351 return f"{n.real:.6g}{n.imag:+.6g}j"
352 except Exception:
353 return ""
356def _solve_with_sympy(expression: str) -> str:
357 """Solve an equation or system of equations using SymPy.
359 Handles ``solve(expr, var)`` and ``solve(expr, var1, var2, ...)`` syntax.
360 Expects ``expression`` to already be a valid ``solve(...)`` call string.
362 Strategy
363 --------
364 Single-variable polynomial: ``sympy.roots()`` first (gives exact roots
365 with multiplicities), falling back to ``sympy.solve()`` for transcendental
366 or non-polynomial expressions.
367 Multi-variable / system: ``sympy.solve()`` directly.
368 """
369 try:
370 import sympy
371 except ImportError:
372 return "[calculate] solve() requires sympy — not installed in this environment."
374 # ── Parse the solve() call via AST ────────────────────────────────────────
375 try:
376 tree = ast.parse(expression.strip(), mode="eval")
377 except SyntaxError as exc:
378 return f"[calculate] Syntax error in solve(): {exc}"
380 call = tree.body
381 args = getattr(call, "args", [])
382 if not args:
383 return "[calculate] solve() requires at least one argument: solve(expression, variable)"
385 expr_src = ast.unparse(args[0])
387 var_names: list[str] = []
388 for arg in args[1:]:
389 if isinstance(arg, ast.Name):
390 var_names.append(arg.id)
391 elif isinstance(arg, (ast.Tuple, ast.List)):
392 var_names.extend(e.id for e in arg.elts if isinstance(e, ast.Name))
394 # ── Build SymPy namespace ──────────────────────────────────────────────────
395 ns: dict[str, Any] = {
396 "pi": sympy.pi,
397 "e": sympy.E,
398 "I": sympy.I,
399 "oo": sympy.oo,
400 "inf": sympy.oo,
401 "tau": 2 * sympy.pi,
402 "sqrt": sympy.sqrt,
403 "exp": sympy.exp,
404 "log": sympy.log,
405 "sin": sympy.sin,
406 "cos": sympy.cos,
407 "tan": sympy.tan,
408 "asin": sympy.asin,
409 "acos": sympy.acos,
410 "atan": sympy.atan,
411 "atan2": sympy.atan2,
412 "sinh": sympy.sinh,
413 "cosh": sympy.cosh,
414 "tanh": sympy.tanh,
415 "abs": sympy.Abs,
416 "Abs": sympy.Abs,
417 "factorial": sympy.factorial,
418 "gamma": sympy.gamma,
419 "floor": sympy.floor,
420 "ceil": sympy.ceiling,
421 }
423 sym_vars: list[Any] = []
424 for name in var_names:
425 sym = sympy.Symbol(name)
426 ns[name] = sym
427 sym_vars.append(sym)
429 try:
430 sym_expr = sympy.sympify(expr_src, locals=ns)
431 except Exception as exc:
432 return f"[calculate] Could not parse expression symbolically: {exc}"
434 if not sym_vars:
435 free = sorted(sym_expr.free_symbols, key=str)
436 if not free:
437 val = _sympy_approx(sym_expr)
438 return f"Expression value: {sym_expr}" + (f" ≈ {val}" if val else "")
439 sym_vars = free
441 var_label = ", ".join(str(v) for v in sym_vars)
443 # ── Single-variable: use roots() to get multiplicities ────────────────────
444 if len(sym_vars) == 1:
445 var = sym_vars[0]
446 root_dict: dict[Any, int] = {}
447 try:
448 root_dict = sympy.roots(sym_expr, var)
449 except Exception:
450 pass # not a polynomial or roots() failed — fall through to solve()
452 # roots() returns {} for transcendental / irreducible-over-radicals polynomials.
453 # Fall back to solve() which may still find closed-form roots.
454 if not root_dict:
455 try:
456 sols = sympy.solve(sym_expr, var)
457 if sols:
458 root_dict = {s: 1 for s in sols}
459 except Exception as exc:
460 return f"[calculate] solve() error: {exc}"
462 if not root_dict:
463 return (
464 f"No closed-form roots found for the expression in {var}.\n"
465 "The expression may be transcendental or irreducible over simple radicals."
466 )
468 real_rows: list[str] = []
469 complex_rows: list[str] = []
470 for root, mult in root_dict.items():
471 exact = str(root)
472 approx = _sympy_approx(root)
473 mult_tag = f" (multiplicity {mult})" if mult > 1 else ""
474 row = f" {exact}" + (f" ≈ {approx}" if approx else "") + mult_tag
475 is_complex = False
476 try:
477 is_complex = root.is_real is False
478 except Exception:
479 is_complex = bool(approx and "j" in approx)
480 if is_complex:
481 complex_rows.append(row + " [complex]")
482 else:
483 real_rows.append(row)
485 lines = [f"Solutions for {var_label}:"]
486 for i, row in enumerate(real_rows + complex_rows, 1):
487 lines.append(f"{i}." + row)
488 return "\n".join(lines)
490 # ── Multi-variable / system ────────────────────────────────────────────────
491 try:
492 solutions = sympy.solve(sym_expr, *sym_vars)
493 except Exception as exc:
494 return f"[calculate] solve() error: {exc}"
496 if not solutions:
497 return "No solutions found."
499 if isinstance(solutions, dict):
500 lines = [f"Solution ({var_label}):"]
501 for var, val in solutions.items():
502 approx = _sympy_approx(val)
503 lines.append(f" {var} = {val}" + (f" ≈ {approx}" if approx else ""))
504 return "\n".join(lines)
506 if isinstance(solutions, list):
507 lines = [f"Solutions for {var_label}:"]
508 for i, sol in enumerate(solutions, 1):
509 if isinstance(sol, (list, tuple)):
510 parts = []
511 for v, s in zip(sym_vars, sol):
512 approx = _sympy_approx(s)
513 parts.append(f"{v} = {s}" + (f" ≈ {approx}" if approx else ""))
514 lines.append(f"{i}. (" + ", ".join(parts) + ")")
515 else:
516 approx = _sympy_approx(sol)
517 lines.append(f"{i}. {sol}" + (f" ≈ {approx}" if approx else ""))
518 return "\n".join(lines)
520 approx = _sympy_approx(solutions)
521 return f"Solution for {var_label}: {solutions}" + (
522 f" ≈ {approx}" if approx else ""
523 )
526# ---------------------------------------------------------------------------
527# calculate factory
528# ---------------------------------------------------------------------------
531def _calculate_factory(config: dict[str, Any]) -> StructuredTool:
532 def calculate(expression: str) -> str:
533 stripped = expression.strip()
534 try:
535 tree = ast.parse(stripped, mode="eval")
536 except SyntaxError as exc:
537 return f"[calculate] Syntax error: {exc}"
539 # Route solve() calls to the SymPy symbolic solver.
540 if (
541 isinstance(tree.body, ast.Call)
542 and isinstance(tree.body.func, ast.Name)
543 and tree.body.func.id == "solve"
544 ):
545 return _solve_with_sympy(stripped)
547 # Numeric evaluation for all other expressions.
548 try:
549 result = _safe_eval_expr(tree.body)
550 except Exception as exc:
551 return f"[calculate] Error: {exc}"
552 # Format integers without decimal point, floats with reasonable precision.
553 if isinstance(result, float) and result.is_integer():
554 return str(int(result))
555 if isinstance(result, float):
556 formatted = f"{result:.10g}"
557 return formatted
558 return str(result)
560 return StructuredTool.from_function(
561 func=calculate,
562 name="calculate",
563 description=(
564 "Evaluate a numeric expression or solve an equation symbolically. "
565 "For numeric expressions: arithmetic, trig, log, gamma, combinatorics. "
566 "For equations: use solve(expression, variable) — e.g. "
567 "solve(x**2 - 4, x) returns the roots [−2, 2] with exact + numeric forms. "
568 "Use for any computation requiring precision rather than estimation."
569 ),
570 args_schema=CalculateInput,
571 )
574_CALCULATE_SCHEMA: dict[str, Any] = openai_schema_from_model(
575 "calculate",
576 (
577 "Evaluate a numeric expression OR solve an equation symbolically. "
578 "Supports arithmetic, trig, log, gamma, combinatorics, and rounding. "
579 "Use solve(expr, var) to find roots of any polynomial or equation."
580 ),
581 CalculateInput,
582)
585# ---------------------------------------------------------------------------
586# validate_code_syntax — static syntax and execution-flow analysis
587# ---------------------------------------------------------------------------
589_CODE_SIZE_LIMIT = 256 * 1024 # 256 KB — prevents memory/CPU exhaustion
591SupportedLanguage = Literal[
592 "python", "javascript", "typescript", "json", "sql", "html", "xml", "yaml"
593]
596class ValidateCodeInput(BaseModel):
597 code: str = Field(
598 description=(
599 "Source code to validate (max 256 KB). "
600 "Checks syntax correctness and, for Python, analyses execution flow: "
601 "unreachable code, infinite loops, nesting depth, and structural metrics."
602 )
603 )
604 language: SupportedLanguage = Field(
605 description=f"Language of the code: {vocab.one_of(SupportedLanguage)}."
606 )
609# ── Python: AST-based flow visitor ──────────────────────────────────────────
612def _py_has_break(nodes: list[ast.AST]) -> bool:
613 """True if a Break exists in nodes without crossing into a nested loop."""
614 for node in nodes:
615 if isinstance(node, ast.Break):
616 return True
617 if isinstance(node, (ast.For, ast.AsyncFor, ast.While)):
618 continue # break inside nested loop belongs to that loop
619 if _py_has_break(list(ast.iter_child_nodes(node))):
620 return True
621 return False
624def _py_check_unreachable(stmts: list[ast.stmt], issues: list[tuple[int, str]]) -> None:
625 """Append a warning for the first statement that follows a guaranteed exit."""
626 for i, stmt in enumerate(stmts):
627 if isinstance(stmt, (ast.Return, ast.Raise, ast.Break, ast.Continue)):
628 if i < len(stmts) - 1:
629 next_stmt = stmts[i + 1]
630 if isinstance(next_stmt, ast.Pass):
631 continue
632 ln = getattr(next_stmt, "lineno", 0)
633 term = type(stmt).__name__.lower()
634 issues.append((ln, f"Unreachable code after '{term}' statement"))
635 break
638class _PyFlowVisitor(ast.NodeVisitor):
639 """Walk an AST collecting structural metrics and execution-flow issues."""
641 def __init__(self) -> None:
642 self.issues: list[tuple[int, str]] = []
643 self.functions = 0
644 self.classes = 0
645 self.loops = 0
646 self.conditionals = 0
647 self.imports = 0
648 self._depth = 0
649 self.max_depth = 0
651 def _enter(self, stmts: list[ast.stmt]) -> None:
652 self._depth += 1
653 self.max_depth = max(self.max_depth, self._depth)
654 _py_check_unreachable(stmts, self.issues)
656 def _leave(self) -> None:
657 self._depth -= 1
659 def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
660 self.functions += 1
661 self._enter(node.body)
662 self.generic_visit(node)
663 self._leave()
665 visit_AsyncFunctionDef = visit_FunctionDef # type: ignore[assignment]
667 def visit_ClassDef(self, node: ast.ClassDef) -> None:
668 self.classes += 1
669 self._enter(node.body)
670 self.generic_visit(node)
671 self._leave()
673 def visit_While(self, node: ast.While) -> None:
674 self.loops += 1
675 self._enter(node.body)
676 is_true = isinstance(node.test, ast.Constant) and node.test.value is True
677 if is_true and not _py_has_break(list(node.body)):
678 self.issues.append(
679 (
680 node.lineno,
681 "Potential infinite loop: 'while True' with no 'break' in loop body",
682 )
683 )
684 self.generic_visit(node)
685 self._leave()
687 def visit_For(self, node: ast.For) -> None:
688 self.loops += 1
689 self._enter(node.body)
690 self.generic_visit(node)
691 self._leave()
693 visit_AsyncFor = visit_For # type: ignore[assignment]
695 def visit_If(self, node: ast.If) -> None:
696 self.conditionals += 1
697 self._enter(node.body)
698 if node.orelse:
699 _py_check_unreachable(node.orelse, self.issues)
700 self.generic_visit(node)
701 self._leave()
703 def visit_Import(self, node: ast.Import) -> None:
704 self.imports += len(node.names)
705 self.generic_visit(node)
707 def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
708 self.imports += 1
709 self.generic_visit(node)
712def _validate_python(code: str) -> str:
713 try:
714 tree = ast.parse(code, filename="<input>")
715 except SyntaxError as exc:
716 col = f", column {exc.offset}" if exc.offset else ""
717 return f"Syntax: INVALID\n\nSyntax error (line {exc.lineno}{col}):\n {exc.msg}"
719 visitor = _PyFlowVisitor()
720 visitor.visit(tree)
721 lines = code.splitlines()
722 header = (
723 f"Syntax: VALID ({len(lines)} lines, {len(code):,} characters)\n\n"
724 f"Structural metrics:\n"
725 f" Functions : {visitor.functions}\n"
726 f" Classes : {visitor.classes}\n"
727 f" Loops : {visitor.loops}\n"
728 f" Conditionals (if) : {visitor.conditionals}\n"
729 f" Import statements : {visitor.imports}\n"
730 f" Max nesting depth : {visitor.max_depth}"
731 )
732 if not visitor.issues:
733 return header + "\n\nExecution flow: no issues detected."
734 issues_txt = "\n".join(
735 f" WARNING line {ln:>4} : {msg}" for ln, msg in sorted(visitor.issues)
736 )
737 return (
738 header + f"\n\nExecution flow — {len(visitor.issues)} issue(s):\n{issues_txt}"
739 )
742# ── JSON ──────────────────────────────────────────────────────────────────
745def _validate_json(code: str) -> str:
746 try:
747 obj = json.loads(code)
748 except json.JSONDecodeError as exc:
749 return (
750 f"Syntax: INVALID\n\n"
751 f"JSON error (line {exc.lineno}, column {exc.colno}):\n"
752 f" {exc.msg}"
753 )
754 if isinstance(obj, dict):
755 detail = f"Object with {len(obj)} key(s)"
756 elif isinstance(obj, list):
757 detail = f"Array with {len(obj)} element(s)"
758 else:
759 detail = type(obj).__name__
760 return f"Syntax: VALID ({len(code.splitlines())} lines)\n\nRoot type: {detail}"
763# ── HTML ──────────────────────────────────────────────────────────────────
766class _HtmlValidator(HTMLParser):
767 _VOID: frozenset[str] = frozenset(
768 {
769 "area",
770 "base",
771 "br",
772 "col",
773 "embed",
774 "hr",
775 "img",
776 "input",
777 "link",
778 "meta",
779 "param",
780 "source",
781 "track",
782 "wbr",
783 }
784 )
786 def __init__(self) -> None:
787 super().__init__()
788 self._stack: list[str] = []
789 self.issues: list[str] = []
790 self.tag_count = 0
792 def handle_starttag(self, tag: str, attrs: list) -> None: # type: ignore[override]
793 self.tag_count += 1
794 if tag not in self._VOID:
795 self._stack.append(tag)
797 def handle_endtag(self, tag: str) -> None:
798 if tag in self._VOID:
799 return
800 if self._stack and self._stack[-1] == tag:
801 self._stack.pop()
802 else:
803 expected = f" (expected </{self._stack[-1]}>)" if self._stack else ""
804 self.issues.append(f"Unexpected closing tag </{tag}>{expected}")
807def _validate_html(code: str) -> str:
808 v = _HtmlValidator()
809 try:
810 v.feed(code)
811 except Exception as exc:
812 return f"Syntax: INVALID\n\nHTML parse error: {exc}"
813 lines = code.splitlines()
814 if v._stack:
815 v.issues.append(f"Unclosed tag(s): {', '.join(f'<{t}>' for t in v._stack)}")
816 header = f"Syntax: {'VALID' if not v.issues else 'INVALID'} ({len(lines)} lines, {v.tag_count} tag(s))"
817 if not v.issues:
818 return header + "\n\nStructure: no issues detected."
819 return (
820 header
821 + "\n\nStructure — {} issue(s):\n".format(len(v.issues))
822 + "\n".join(f" WARNING : {i}" for i in v.issues)
823 )
826# ── XML ───────────────────────────────────────────────────────────────────
829def _validate_xml(code: str) -> str:
830 import xml.etree.ElementTree as ET
832 try:
833 root = ET.fromstring(code) # nosec B314
834 except ET.ParseError as exc:
835 return f"Syntax: INVALID\n\nXML parse error: {exc}"
836 except Exception as exc:
837 return f"Syntax: INVALID\n\nXML error: {exc}"
838 elements = list(root.iter())
839 return (
840 f"Syntax: VALID ({len(code.splitlines())} lines)\n\n"
841 f"Root element : <{root.tag}>\n"
842 f"Total elements: {len(elements)}"
843 )
846# ── YAML ──────────────────────────────────────────────────────────────────
849def _validate_yaml(code: str) -> str:
850 try:
851 import yaml
852 except ImportError:
853 return "YAML validation unavailable: pyyaml is not installed."
854 try:
855 obj = yaml.safe_load(code)
856 except Exception as exc:
857 return f"Syntax: INVALID\n\nYAML error: {exc}"
858 if obj is None:
859 detail = "Empty document"
860 elif isinstance(obj, dict):
861 detail = f"Mapping with {len(obj)} key(s)"
862 elif isinstance(obj, list):
863 detail = f"Sequence with {len(obj)} element(s)"
864 else:
865 detail = type(obj).__name__
866 return f"Syntax: VALID ({len(code.splitlines())} lines)\n\nRoot type: {detail}"
869# ── SQL ───────────────────────────────────────────────────────────────────
872def _validate_sql(code: str) -> str:
873 """Structural SQL validation: parenthesis balance and string termination.
875 Does not validate table/column names or full grammar — that requires a
876 DBMS-specific parser. Catches the most common structural mistakes.
877 """
878 issues: list[str] = []
879 depth = 0
880 in_single = False
881 in_double = False
882 i = 0
883 n = len(code)
884 while i < n:
885 ch = code[i]
886 if ch == "'" and not in_double:
887 if in_single and i + 1 < n and code[i + 1] == "'":
888 i += 2
889 continue
890 in_single = not in_single
891 elif ch == '"' and not in_single:
892 in_double = not in_double
893 elif not in_single and not in_double:
894 if ch == "(":
895 depth += 1
896 elif ch == ")":
897 depth -= 1
898 if depth < 0:
899 issues.append("Unexpected closing parenthesis ')'")
900 depth = 0
901 i += 1
903 if in_single:
904 issues.append("Unterminated single-quoted string literal")
905 if in_double:
906 issues.append("Unterminated double-quoted string literal")
907 if depth > 0:
908 issues.append(f"Unmatched opening parenthesis ({depth} unclosed)")
910 _SQL_STARTERS = [
911 "SELECT",
912 "INSERT",
913 "UPDATE",
914 "DELETE",
915 "CREATE",
916 "DROP",
917 "ALTER",
918 "TRUNCATE",
919 "BEGIN",
920 "COMMIT",
921 "ROLLBACK",
922 "WITH",
923 "MERGE",
924 "REPLACE",
925 "EXPLAIN",
926 ]
927 stripped = code.strip().upper()
928 stmt_type = next((kw for kw in _SQL_STARTERS if stripped.startswith(kw)), "UNKNOWN")
929 lines = code.splitlines()
930 valid = "VALID" if not issues else "INVALID"
931 header = f"Syntax: {valid} ({len(lines)} lines)\n\nStatement type: {stmt_type}"
932 if not issues:
933 return header + "\n\nStructure: no issues detected."
934 return (
935 header
936 + "\n\nStructural issues:\n"
937 + "\n".join(f" ERROR : {e}" for e in issues)
938 )
941# ── JavaScript / TypeScript ────────────────────────────────────────────────
944def _validate_js(code: str, language: str) -> str:
945 """Bracket-balance and string-termination check for JS/TS.
947 Full grammar validation requires a JS runtime. This safe, static check
948 uses a state machine to track string/comment/template-literal context and
949 catches the most common structural mistakes without executing any code.
950 Template literal expressions (${...}) are skipped to avoid false positives.
951 """
952 issues: list[str] = []
953 stack: list[tuple[str, int]] = [] # (opener_char, line_number)
954 _PAIRS = {"(": ")", "[": "]", "{": "}"}
955 _CLOSERS = {v: k for k, v in _PAIRS.items()}
957 # state: "code" | "single" | "double" | "template" | "line_cmt" | "block_cmt"
958 state = "code"
959 line = 1
960 i = 0
961 n = len(code)
963 while i < n:
964 ch = code[i]
965 nc = code[i + 1] if i + 1 < n else ""
967 if ch == "\n":
968 if state == "line_cmt":
969 state = "code"
970 line += 1
971 i += 1
972 continue
974 if state == "block_cmt":
975 if ch == "*" and nc == "/":
976 state = "code"
977 i += 2
978 else:
979 i += 1
980 continue
982 if state == "line_cmt":
983 i += 1
984 continue
986 if state == "single":
987 if ch == "\\" and nc:
988 i += 2
989 elif ch == "'":
990 state = "code"
991 i += 1
992 else:
993 i += 1
994 continue
996 if state == "double":
997 if ch == "\\" and nc:
998 i += 2
999 elif ch == '"':
1000 state = "code"
1001 i += 1
1002 else:
1003 i += 1
1004 continue
1006 if state == "template":
1007 if ch == "\\" and nc:
1008 i += 2
1009 elif ch == "`":
1010 state = "code"
1011 i += 1
1012 else:
1013 i += 1
1014 continue
1016 # state == "code"
1017 if ch == "/" and nc == "/":
1018 state = "line_cmt"
1019 i += 2
1020 elif ch == "/" and nc == "*":
1021 state = "block_cmt"
1022 i += 2
1023 elif ch == "'":
1024 state = "single"
1025 i += 1
1026 elif ch == '"':
1027 state = "double"
1028 i += 1
1029 elif ch == "`":
1030 state = "template"
1031 i += 1
1032 elif ch in _PAIRS:
1033 stack.append((ch, line))
1034 i += 1
1035 elif ch in _CLOSERS:
1036 expected = _CLOSERS[ch]
1037 if not stack:
1038 issues.append(
1039 f"Line {line}: unexpected '{ch}' — no matching '{expected}'"
1040 )
1041 elif stack[-1][0] != expected:
1042 opened, open_line = stack[-1]
1043 issues.append(
1044 f"Line {line}: '{ch}' closes '{opened}' opened at line {open_line} — mismatched"
1045 )
1046 stack.pop()
1047 else:
1048 stack.pop()
1049 i += 1
1050 else:
1051 i += 1
1053 if state == "single":
1054 issues.append("Unterminated single-quoted string")
1055 elif state == "double":
1056 issues.append("Unterminated double-quoted string")
1057 elif state == "template":
1058 issues.append("Unterminated template literal")
1059 elif state == "block_cmt":
1060 issues.append("Unterminated block comment /* ... */")
1061 for opener, open_line in stack:
1062 issues.append(f"Line {open_line}: '{opener}' was never closed")
1064 lines = code.splitlines()
1065 valid = "VALID" if not issues else "INVALID"
1066 header = f"Syntax: {valid} ({len(lines)} lines, {len(code):,} characters)"
1067 note = (
1068 "\n\nNote: full grammar validation requires a JS runtime. "
1069 "This check covers bracket balance, string termination, and comment structure only."
1070 )
1071 if not issues:
1072 return header + "\n\nStructure: no issues detected." + note
1073 shown = issues[:20]
1074 extra = f"\n ... and {len(issues) - 20} more" if len(issues) > 20 else ""
1075 return (
1076 header
1077 + "\n\nStructural issues:\n"
1078 + "\n".join(f" ERROR : {e}" for e in shown)
1079 + extra
1080 + note
1081 )
1084# ── Dispatcher ────────────────────────────────────────────────────────────
1087def _dispatch_validate(code: str, language: str) -> str:
1088 if len(code.encode()) > _CODE_SIZE_LIMIT:
1089 return (
1090 f"[validate_code_syntax] Input exceeds {_CODE_SIZE_LIMIT // 1024} KB limit. "
1091 "Provide a smaller code sample."
1092 )
1093 prefix = f"Language: {language}\n"
1094 lang = language.lower().strip()
1095 if lang == "python":
1096 return prefix + _validate_python(code)
1097 if lang in ("javascript", "typescript"):
1098 return prefix + _validate_js(code, lang)
1099 if lang == "json":
1100 return prefix + _validate_json(code)
1101 if lang == "sql":
1102 return prefix + _validate_sql(code)
1103 if lang == "html":
1104 return prefix + _validate_html(code)
1105 if lang == "xml":
1106 return prefix + _validate_xml(code)
1107 if lang == "yaml":
1108 return prefix + _validate_yaml(code)
1109 return (
1110 f"Unsupported language: {language!r}. "
1111 f"Supported: {vocab.listing(SupportedLanguage, sep=', ')}."
1112 )
1115def _validate_code_factory(config: dict[str, Any]) -> StructuredTool:
1116 def validate_code_syntax(code: str, language: str) -> str:
1117 return _dispatch_validate(code, language)
1119 return StructuredTool.from_function(
1120 func=validate_code_syntax,
1121 name="validate_code_syntax",
1122 description=(
1123 "Statically validate source code syntax and analyse execution flow "
1124 "without executing any code. "
1125 "Python: full AST analysis — detects syntax errors, unreachable code after "
1126 "return/raise/break/continue, potential infinite 'while True' loops, "
1127 "and reports structural metrics (functions, classes, loops, conditionals, "
1128 "import count, max nesting depth). "
1129 "JavaScript/TypeScript: state-machine bracket-balance and string-termination checks. "
1130 "JSON: full parse validation with root-type report. "
1131 "SQL: parenthesis balance and string-termination check. "
1132 "HTML: tag-balance validation. "
1133 "XML: strict well-formedness validation. "
1134 "YAML: safe-load parse validation. "
1135 "Never executes code — safe on any input."
1136 ),
1137 args_schema=ValidateCodeInput,
1138 )
1141_VALIDATE_CODE_SCHEMA: dict[str, Any] = openai_schema_from_model(
1142 "validate_code_syntax",
1143 (
1144 "Statically validate source code syntax and analyse execution flow "
1145 "without executing it. Supports Python (full AST + flow analysis), "
1146 "JavaScript, TypeScript, JSON, SQL, HTML, XML, and YAML."
1147 ),
1148 ValidateCodeInput,
1149)
1152# ---------------------------------------------------------------------------
1153# render_chart — categorical bar / grouped / line / area / pie charts
1154# ---------------------------------------------------------------------------
1157class _ChartSeriesItem(BaseModel):
1158 key: str = Field(
1159 description=(
1160 "The data field name whose numeric values form this series' y-axis. "
1161 "MUST exactly match a key present in every data record (e.g. 'sales', 'adoption')."
1162 )
1163 )
1164 label: str | None = Field(
1165 default=None, description="Legend display name (defaults to key if omitted)"
1166 )
1167 color: str | None = Field(
1168 default=None, description="Optional CSS / hex colour, e.g. '#6366f1'"
1169 )
1172#: The code-fence language each render tool returns. fe-core renders these,
1173#: graph.py's artifact guard captures them, and the synthesis and evaluator
1174#: prompts name them; ``render_document`` returns DOCUMENT_FENCE_LANGUAGE.
1175RENDER_FENCE_LANGUAGES: dict[str, str] = {
1176 "render_chart": "chart",
1177 "render_plot": "plot",
1178 "render_mermaid": "mermaid",
1179 "render_graph": "graph",
1180 "render_map": "map",
1181}
1182_CHART_FENCE = RENDER_FENCE_LANGUAGES["render_chart"]
1183_PLOT_FENCE = RENDER_FENCE_LANGUAGES["render_plot"]
1184_MERMAID_FENCE = RENDER_FENCE_LANGUAGES["render_mermaid"]
1185_GRAPH_FENCE = RENDER_FENCE_LANGUAGES["render_graph"]
1186_MAP_FENCE = RENDER_FENCE_LANGUAGES["render_map"]
1189#: Chart kinds ``render_chart`` draws — the x-axis carries category labels.
1190ChartType = Literal["bar", "grouped", "line", "area", "pie"]
1192_CHART_TYPES: dict[str, str] = {
1193 "bar": "one metric per category — use y_key for simplicity",
1194 "grouped": "multiple metrics side-by-side — requires series",
1195 "line": "ordered trend",
1196 "area": "filled line",
1197 "pie": "proportional breakdown",
1198}
1201class RenderChartInput(BaseModel):
1202 """Use for CATEGORICAL data where the x-axis has string labels (day names, months, regions…).
1204 Data is an array of record objects — NOT [x, y] numeric pairs.
1205 For numeric XY data (both axes are numbers), use render_plot instead.
1206 """
1208 chart_type: ChartType = Field(
1209 description=f"Chart type: {vocab.inline(_CHART_TYPES, ChartType)}."
1210 )
1211 data: list[dict[str, Any]] = Field(
1212 description=(
1213 "Non-empty array of data RECORDS — NOT [x, y] pairs. "
1214 "Each record is an object containing one category-label field and one or more numeric fields.\n"
1215 ' bar example: [{"month": "Jan", "sales": 120}, {"month": "Feb", "sales": 95}]\n'
1216 ' grouped example: [{"source": "Coal", "price": 50, "efficiency": 33}, ...]\n'
1217 "If your data is numeric (x, y) pairs, use render_plot instead."
1218 )
1219 )
1220 x_key: str | None = Field(
1221 default=None,
1222 description=(
1223 "Field name used as the category (x-axis) label. "
1224 "Defaults to 'name' if omitted. Must be a string-valued field in each record."
1225 ),
1226 )
1227 y_key: str | None = Field(
1228 default=None,
1229 description=(
1230 "Single-series shorthand: the numeric field to plot on the y-axis. "
1231 "Use this instead of series when there is exactly one metric. "
1232 "Example: if records have 'adoption', set y_key='adoption'. "
1233 "Ignored when series is also provided."
1234 ),
1235 )
1236 series: list[_ChartSeriesItem] | None = Field(
1237 default=None,
1238 description=(
1239 "Series definitions — required for 'grouped', optional for other types. "
1240 "Each entry's 'key' must match a numeric field in every data record. "
1241 "Use y_key instead when charting a single metric. "
1242 'Example: [{"key": "price", "label": "Price ($/MWh)"}, {"key": "efficiency", "label": "Efficiency (%)"}]'
1243 ),
1244 )
1245 title: str | None = Field(
1246 default=None, description="Optional chart title shown above the chart"
1247 )
1250def _plain(items: list[Any] | None) -> list[dict[str, Any]]:
1251 """A render tool's nested items as plain records. LangChain validates a
1252 call against the tool's ``args_schema`` and passes each nested item on as
1253 the schema's model (``_PlotSeriesItem``), not the dict the model sent, so
1254 a tool that reads them as dicts — or writes them into its fence — takes
1255 them through here. Unset fields are left out, as the model left them."""
1256 return [
1257 item.model_dump(exclude_none=True)
1258 if isinstance(item, BaseModel)
1259 else dict(item)
1260 for item in items or []
1261 ]
1264def _render_chart_factory(config: dict[str, Any]) -> StructuredTool:
1265 def render_chart(
1266 chart_type: ChartType,
1267 data: list[dict[str, Any]],
1268 x_key: str | None = None,
1269 y_key: str | None = None,
1270 series: list[dict[str, Any]] | None = None,
1271 title: str | None = None,
1272 ) -> str:
1273 if not data:
1274 return "[render_chart] 'data' must be a non-empty list of records."
1275 data = _plain(data)
1276 series = _plain(series) if series else None
1278 # Normalise y_key shorthand → single-entry series (series takes precedence)
1279 if y_key and not series:
1280 series = [{"key": y_key}]
1282 if chart_type == "grouped" and not series:
1283 return (
1284 "[render_chart] 'series' (or 'y_key') is required for grouped charts. "
1285 "Provide a list where each entry has a 'key' matching a numeric field in data."
1286 )
1288 if series:
1289 available = set(data[0].keys())
1290 for s in series:
1291 k = s.get("key", "")
1292 if k not in available:
1293 return (
1294 f"[render_chart] series key '{k}' not found in data records. "
1295 f"Available keys: {sorted(available)}"
1296 )
1298 cfg: dict[str, Any] = {"type": chart_type, "data": data}
1299 if title:
1300 cfg["title"] = title
1301 if x_key:
1302 cfg["x_key"] = x_key
1303 if series:
1304 cfg["series"] = series
1306 return f"```{_CHART_FENCE}\n{json.dumps(cfg, ensure_ascii=False)}\n```"
1308 return StructuredTool.from_function(
1309 func=render_chart,
1310 name="render_chart",
1311 description=tool_description(
1312 RenderChartInput,
1313 f"Return a ```{_CHART_FENCE} code fence to embed verbatim in your response.",
1314 ),
1315 args_schema=RenderChartInput,
1316 )
1319_RENDER_CHART_SCHEMA: dict[str, Any] = openai_schema_from_model(
1320 "render_chart",
1321 f"Render a categorical chart. Returns a ```{_CHART_FENCE} fence to embed verbatim in your response.",
1322 RenderChartInput,
1323)
1326# ---------------------------------------------------------------------------
1327# render_plot — numeric XY scatter / line / histogram
1328# ---------------------------------------------------------------------------
1331class _PlotSeriesItem(BaseModel):
1332 name: str = Field(description="Display name for this series in the legend")
1333 data: list[list[float]] = Field(
1334 description=(
1335 "List of [x, y] numeric pairs. BOTH values must be numbers — never strings. "
1336 "Example: [[1, 22], [2, 24], [3, 23]]"
1337 )
1338 )
1339 color: str | None = Field(default=None, description="Optional CSS / hex colour")
1340 best_fit: bool | None = Field(
1341 default=None,
1342 description="If true, overlay a linear regression line on this series (scatter only)",
1343 )
1346#: Plot kinds ``render_plot`` draws — both axes are numbers.
1347PlotType = Literal["scatter", "line", "histogram"]
1349_PLOT_TYPES: dict[str, str] = {
1350 "scatter": "unordered XY points",
1351 "line": "ordered XY trend",
1352 "histogram": "frequency distribution of values",
1353}
1356class RenderPlotInput(BaseModel):
1357 """Use for NUMERIC data where both axes are numbers (index, epoch, measurement).
1359 Data is a list of [x, y] numeric pairs (series) or a flat list of values (histogram).
1360 If the x-axis would have string labels (day names, categories), use render_chart instead.
1361 """
1363 plot_type: PlotType = Field(
1364 description=(
1365 f"Plot type: {vocab.inline(_PLOT_TYPES, PlotType)}. Both axes must "
1366 "be numbers — if the x-axis has string labels, use render_chart instead."
1367 )
1368 )
1369 series: list[_PlotSeriesItem] | None = Field(
1370 default=None,
1371 description=(
1372 "Series for scatter / line plots. Each has a name and data as [[x, y], ...] pairs. "
1373 "Both x and y MUST be numbers — use render_chart if the x-axis is a string label."
1374 ),
1375 )
1376 histogram_data: list[float] | None = Field(
1377 default=None,
1378 description=(
1379 "Flat array of numeric values for a histogram. "
1380 "Use INSTEAD of series when plot_type is 'histogram'. "
1381 "Example: [72, 85, 91, 63, 78, 88, 95, 71]"
1382 ),
1383 )
1384 title: str | None = Field(default=None, description="Optional plot title")
1385 x_label: str | None = Field(default=None, description="X-axis label")
1386 y_label: str | None = Field(default=None, description="Y-axis label")
1387 bins: int | None = Field(
1388 default=None,
1389 description="Number of histogram buckets (2–50, default 10). Only for 'histogram' type.",
1390 )
1391 best_fit: bool | None = Field(
1392 default=None,
1393 description="If true, draw a linear regression line for ALL scatter series globally.",
1394 )
1397def _render_plot_factory(config: dict[str, Any]) -> StructuredTool:
1398 def render_plot(
1399 plot_type: PlotType,
1400 series: list[dict[str, Any]] | None = None,
1401 histogram_data: list[float] | None = None,
1402 title: str | None = None,
1403 x_label: str | None = None,
1404 y_label: str | None = None,
1405 bins: int | None = None,
1406 best_fit: bool | None = None,
1407 ) -> str:
1408 if plot_type == "histogram":
1409 if not histogram_data:
1410 return (
1411 "[render_plot] 'histogram_data' (a flat list of numbers) is required "
1412 "when plot_type is 'histogram'."
1413 )
1414 cfg: dict[str, Any] = {"type": "histogram", "data": histogram_data}
1415 if title:
1416 cfg["title"] = title
1417 if y_label:
1418 cfg["ylabel"] = y_label
1419 if x_label:
1420 cfg["xlabel"] = x_label
1421 if bins is not None:
1422 cfg["bins"] = max(2, min(50, bins))
1423 else:
1424 series = _plain(series)
1425 if not series:
1426 return (
1427 f"[render_plot] 'series' is required for plot_type '{plot_type}'. "
1428 "Each series must have a name and data as [[x, y], ...] numeric pairs."
1429 )
1430 for s in series:
1431 pts = s.get("data", [])
1432 bad = [
1433 p for p in pts if not (isinstance(p, (list, tuple)) and len(p) >= 2)
1434 ]
1435 if bad:
1436 return (
1437 f"[render_plot] series '{s.get('name')}': each data point must be a "
1438 "[x, y] pair of numbers. Found non-pair entries: check your data format."
1439 )
1441 # Normalise series: best_fit field name consistency
1442 normalised = []
1443 for s in series:
1444 entry: dict[str, Any] = {"name": s["name"], "data": s["data"]}
1445 if s.get("color"):
1446 entry["color"] = s["color"]
1447 if s.get("best_fit") is not None:
1448 entry["bestFit"] = s["best_fit"]
1449 normalised.append(entry)
1451 cfg = {"type": plot_type, "series": normalised}
1452 if title:
1453 cfg["title"] = title
1454 if x_label:
1455 cfg["xlabel"] = x_label
1456 if y_label:
1457 cfg["ylabel"] = y_label
1458 if best_fit is not None:
1459 cfg["bestFit"] = best_fit
1461 return f"```{_PLOT_FENCE}\n{json.dumps(cfg, ensure_ascii=False)}\n```"
1463 return StructuredTool.from_function(
1464 func=render_plot,
1465 name="render_plot",
1466 description=tool_description(
1467 RenderPlotInput,
1468 f"Return a ```{_PLOT_FENCE} code fence to embed verbatim in your response.",
1469 ),
1470 args_schema=RenderPlotInput,
1471 )
1474_RENDER_PLOT_SCHEMA: dict[str, Any] = openai_schema_from_model(
1475 "render_plot",
1476 f"Render a numeric plot. Returns a ```{_PLOT_FENCE} fence to embed verbatim in your response.",
1477 RenderPlotInput,
1478)
1481# ---------------------------------------------------------------------------
1482# render_mermaid — the Mermaid diagram types a PDF can draw too
1483# ---------------------------------------------------------------------------
1486class RenderMermaidInput(BaseModel):
1487 """Use for diagrams written in Mermaid: flows, interactions over time,
1488 states, classes, data models, shares of a whole and schedules.
1490 Pass the complete Mermaid source, opening with its diagram type. Only the
1491 types named under `diagram` are drawn; any other is refused, as is source
1492 that cannot be read, with the line at fault.
1493 """
1495 diagram: str = Field(
1496 description=(
1497 "Complete Mermaid diagram source, opening with its diagram type: one of "
1498 f"{mermaid_vocabulary.offered()} "
1499 f"({vocab.member(mermaid_vocabulary.MermaidKeyword, 'flowchart')} may also be "
1500 f"written {vocab.member(mermaid_vocabulary.MermaidKeyword, 'graph')}).\n"
1501 "Example:\n"
1502 " flowchart LR\n"
1503 " A[Start] --> B{Decision}\n"
1504 " B -->|Yes| C[End]"
1505 )
1506 )
1509def _render_mermaid_factory(config: dict[str, Any]) -> StructuredTool:
1510 def render_mermaid(diagram: str) -> str:
1511 code = diagram.strip()
1512 if not code:
1513 return "[render_mermaid] 'diagram' must not be empty."
1514 # Read by the same code that draws it in a PDF, so every diagram
1515 # this returns can be drawn there too.
1516 from app.documents.visuals.mermaid.visual import check
1518 problem = check(code)
1519 if problem:
1520 return (
1521 f"[render_mermaid] Not drawn: {problem}. Fix the diagram and call "
1522 "render_mermaid again."
1523 )
1524 return f"```{_MERMAID_FENCE}\n{code}\n```"
1526 return StructuredTool.from_function(
1527 func=render_mermaid,
1528 name="render_mermaid",
1529 description=tool_description(
1530 RenderMermaidInput,
1531 f"Return a ```{_MERMAID_FENCE} code fence to embed verbatim in your response.",
1532 ),
1533 args_schema=RenderMermaidInput,
1534 )
1537_RENDER_MERMAID_SCHEMA: dict[str, Any] = openai_schema_from_model(
1538 "render_mermaid",
1539 f"Render a Mermaid diagram. Returns a ```{_MERMAID_FENCE} fence to embed verbatim in your response.",
1540 RenderMermaidInput,
1541)
1544# ---------------------------------------------------------------------------
1545# render_document — a structured report the user can download as a PDF
1546# ---------------------------------------------------------------------------
1549_UNBOUND_PLACEHOLDER = re.compile(r"^\{[A-Za-z_][\w.]*\}$")
1552class RenderDocumentInput(DocumentSpec):
1553 """Use when the user asks for a report, brief, write-up or document to keep,
1554 share or download (for example "as a PDF"), or when a skill has produced a
1555 finished report. The document is attached to your reply as a card with a
1556 PDF download. Do NOT copy the returned fence into your reply — it is
1557 attached automatically; mention the document briefly instead.
1558 Do not use for short answers. A visual belongs in the body: call its
1559 render tool and put the fence it returns where it belongs.
1560 """
1562 @model_validator(mode="before")
1563 @classmethod
1564 def _unbound_is_absent(cls, data: Any) -> Any:
1565 # A skill's tool node binds each field to "{node.field}"; a field the
1566 # node did not produce stays the literal placeholder, which is absent.
1567 if isinstance(data, dict):
1568 return {
1569 k: v
1570 for k, v in data.items()
1571 if not (isinstance(v, str) and _UNBOUND_PLACEHOLDER.match(v))
1572 }
1573 return data
1576def _document_problems(exc: ValidationError) -> str:
1577 problems = "; ".join(
1578 f"{'.'.join(str(p) for p in e['loc']) or 'document'}: {e['msg']}"
1579 for e in exc.errors()[:5]
1580 )
1581 return f"[render_document] invalid document — {problems}. Fix it and call again."
1584def _render_document_factory(
1585 config: dict[str, Any],
1586 *,
1587 resolver: Resolver = system_resolver,
1588 transport: httpx.AsyncBaseTransport | None = None,
1589 store: Any = None,
1590) -> StructuredTool:
1591 """``config``: ``allowed_domains`` / ``blocked_domains`` — the run's web
1592 policy (``run_tool_config``), which every image the body links is fetched
1593 under."""
1594 from app.documents.images import DocumentImageEmbedder
1596 settings = get_settings()
1597 embedder = DocumentImageEmbedder(
1598 # The run's web policy and the workspace's Tools rules, read at each
1599 # image fetched.
1600 DomainPolicy.for_run(
1601 {
1602 "allowed_domains": config.get("allowed_domains") or [],
1603 "blocked_domains": config.get("blocked_domains") or [],
1604 }
1605 ),
1606 settings=settings,
1607 store=store,
1608 resolver=resolver,
1609 transport=transport,
1610 )
1612 async def render_document(**kwargs: Any) -> str:
1613 try:
1614 spec = RenderDocumentInput.model_validate(kwargs)
1615 except ValidationError as exc:
1616 return _document_problems(exc)
1617 # A body that cites the run's source ids is renumbered and its
1618 # sources list built from them, as a chat answer's is
1619 # (``answer_sources``); a document citing none keeps its own list.
1620 from app.agents import answer_sources
1622 renumbered = answer_sources.renumber_document(
1623 spec.model_dump(), source_registry.current()
1624 )
1625 if renumbered is not None:
1626 spec = RenderDocumentInput.model_validate(renumbered)
1627 # ```` — a model's brackets around a link — is the
1628 # image it meant, not a link to "[https:".
1629 spec = spec.model_copy(update={"body": unwrap_link_targets(spec.body)})
1630 # Each visual in the body re-made by its own tool, so the card and
1631 # the PDF draw only what a tool checked; one it refuses is removed
1632 # and the model told (``answer_artifacts.remake_body_fences``).
1633 from app.agents import answer_artifacts
1635 visuals = await answer_artifacts.remake_body_fences(
1636 answer_artifacts.notes_to_fences(spec.body)
1637 )
1638 if visuals.body != spec.body:
1639 try:
1640 spec = RenderDocumentInput.model_validate(
1641 {**spec.model_dump(), "body": visuals.body}
1642 )
1643 except ValidationError as exc:
1644 return _document_problems(exc)
1645 # The images the body links, fetched and stored now so the PDF and
1646 # the card draw copies; the model is told any it could not embed.
1647 report = (
1648 await embedder.embed(spec.body)
1649 if settings.document_images_enabled and spec.body
1650 else None
1651 )
1652 # A file found under another name is what the document links.
1653 body, images = report.apply(spec.body) if report else (spec.body, [])
1654 stored = StoredDocument.model_validate(
1655 {
1656 **spec.model_dump(),
1657 "body": body,
1658 "images": [i.model_dump() for i in images],
1659 }
1660 )
1661 fence = document_fence(stored)
1662 notes = [
1663 n for n in (report.for_model() if report else None, visuals.note()) if n
1664 ]
1665 return "\n\n".join([fence, *notes])
1667 return StructuredTool.from_function(
1668 coroutine=render_document,
1669 name="render_document",
1670 description=tool_description(
1671 RenderDocumentInput,
1672 "Attach a structured report to the reply, downloadable as a PDF.",
1673 ),
1674 args_schema=RenderDocumentInput,
1675 # The argument check runs before the function; answer the model (or
1676 # the skill's tool node) with the problem instead of raising.
1677 handle_validation_error=_document_problems,
1678 )
1681_RENDER_DOCUMENT_SCHEMA: dict[str, Any] = openai_schema_from_model(
1682 "render_document",
1683 "Attach a structured report to the reply, downloadable as a PDF.",
1684 RenderDocumentInput,
1685)
1688# ---------------------------------------------------------------------------
1689# render_graph — 2D / 3D interactive network graphs and geographic maps
1690# ---------------------------------------------------------------------------
1693class _GraphNodeItem(BaseModel):
1694 id: str = Field(
1695 description="Unique node identifier (referenced by edge source/target)"
1696 )
1697 label: str | None = Field(
1698 default=None,
1699 description="Display label on the node (defaults to id if omitted)",
1700 )
1701 x: float | None = Field(
1702 default=None,
1703 description="X position — use longitude for geo maps, or any numeric coordinate for fixed layout",
1704 )
1705 y: float | None = Field(
1706 default=None,
1707 description="Y position — use latitude for geo maps, or any numeric coordinate for fixed layout",
1708 )
1709 z: float | None = Field(
1710 default=None, description="Z position for 3D graphs; omit for 2D"
1711 )
1712 color: str | None = Field(
1713 default=None, description="Optional CSS/hex colour, e.g. '#6366f1'"
1714 )
1715 size: float | None = Field(
1716 default=None, description="Node radius in pixels (default: 7)"
1717 )
1720class _GraphEdgeItem(BaseModel):
1721 source: str = Field(description="id of the source node")
1722 target: str = Field(description="id of the target node")
1723 label: str | None = Field(
1724 default=None, description="Edge label shown near the midpoint, e.g. '2.4 km'"
1725 )
1726 weight: float | None = Field(
1727 default=None,
1728 description="Numeric weight used to tune spring length in force-directed layout",
1729 )
1730 color: str | None = Field(
1731 default=None, description="Optional CSS/hex colour for this edge"
1732 )
1735class RenderGraphInput(BaseModel):
1736 """Use for network / relationship graphs and geographic maps.
1738 Renders an interactive 2D or 3D node-edge diagram with pan/zoom, force-directed
1739 layout (when no coordinates are provided), or fixed-position layout (when x/y
1740 coordinates are supplied). Use for: relationship webs, transport/geography maps,
1741 dependency graphs, knowledge graphs, or any data best expressed as nodes and edges.
1742 """
1744 nodes: list[_GraphNodeItem] = Field(
1745 description=(
1746 "Non-empty list of nodes. Each node MUST have a unique 'id'. "
1747 "Provide 'x'/'y' for fixed-position layouts (e.g. geographic maps — use longitude for x, latitude for y); "
1748 "omit coordinates for automatic force-directed placement. "
1749 'Example: [{"id": "london", "label": "London", "x": -0.118, "y": 51.509}]'
1750 )
1751 )
1752 edges: list[_GraphEdgeItem] = Field(
1753 description=(
1754 "List of edges connecting nodes by their ids. May be empty. "
1755 'Example: [{"source": "london", "target": "oxford", "label": "90 km", "weight": 90}]'
1756 )
1757 )
1758 graph_type: Literal["2d", "3d"] = Field(
1759 default="2d",
1760 description=(
1761 "'2d' (default): flat graph, drag to pan, scroll to zoom. "
1762 "'3d': perspective-projected 3D graph, drag to rotate — provide 'z' on nodes for true 3D positioning."
1763 ),
1764 )
1765 title: str | None = Field(
1766 default=None, description="Optional title shown above the graph"
1767 )
1768 directed: bool | None = Field(
1769 default=None,
1770 description="Set true to render arrowheads on edges showing direction (default: false)",
1771 )
1772 geo: bool | None = Field(
1773 default=None,
1774 description=(
1775 "Set true when node coordinates are geographic (x = longitude, y = latitude). "
1776 "Flips the y-axis so north points up. Always set this when using lat/lng coordinates."
1777 ),
1778 )
1781def _render_graph_factory(config: dict[str, Any]) -> StructuredTool:
1782 def render_graph(
1783 nodes: list[dict[str, Any]],
1784 edges: list[dict[str, Any]],
1785 graph_type: str = "2d",
1786 title: str | None = None,
1787 directed: bool | None = None,
1788 geo: bool | None = None,
1789 ) -> str:
1790 nodes, edges = _plain(nodes), _plain(edges)
1791 if not nodes:
1792 return "[render_graph] 'nodes' must be a non-empty list."
1794 node_ids = [n.get("id") for n in nodes]
1795 if any(nid is None for nid in node_ids):
1796 return "[render_graph] every node must have an 'id' field."
1797 if len(set(node_ids)) != len(node_ids):
1798 return "[render_graph] node ids must be unique."
1800 id_set = set(node_ids)
1801 for e in edges:
1802 src, tgt = e.get("source"), e.get("target")
1803 if src not in id_set:
1804 return f"[render_graph] edge source '{src}' does not match any node id. Available: {sorted(id_set)}"
1805 if tgt not in id_set:
1806 return f"[render_graph] edge target '{tgt}' does not match any node id. Available: {sorted(id_set)}"
1808 cfg: dict[str, Any] = {
1809 "type": graph_type or "2d",
1810 "nodes": nodes,
1811 "edges": edges,
1812 }
1813 if title:
1814 cfg["title"] = title
1815 if directed:
1816 cfg["directed"] = True
1817 if geo:
1818 cfg["geo"] = True
1820 return f"```{_GRAPH_FENCE}\n{json.dumps(cfg, ensure_ascii=False)}\n```"
1822 return StructuredTool.from_function(
1823 func=render_graph,
1824 name="render_graph",
1825 description=tool_description(
1826 RenderGraphInput,
1827 f"Return a ```{_GRAPH_FENCE} code fence to embed verbatim in your response.",
1828 ),
1829 args_schema=RenderGraphInput,
1830 )
1833_RENDER_GRAPH_SCHEMA: dict[str, Any] = openai_schema_from_model(
1834 "render_graph",
1835 f"Render an interactive 2D/3D network graph or geographic map. Returns a ```{_GRAPH_FENCE} fence to embed verbatim in your response.",
1836 RenderGraphInput,
1837)
1840# ---------------------------------------------------------------------------
1841# render_map — real tile map with GeoJSON overlay (Leaflet / OpenStreetMap)
1842# ---------------------------------------------------------------------------
1845class _MapFeatureProperties(BaseModel):
1846 name: str | None = Field(
1847 default=None, description="Feature label shown in click popup"
1848 )
1849 description: str | None = Field(
1850 default=None, description="Additional text shown in click popup below the name"
1851 )
1852 color: str | None = Field(
1853 default=None,
1854 description="CSS/hex colour for lines and polygon fills, e.g. '#6366f1'",
1855 )
1856 stroke: str | None = Field(
1857 default=None, description="Border/line colour (overrides color for lines)"
1858 )
1859 fill: str | None = Field(
1860 default=None, description="Polygon fill colour (overrides color for polygons)"
1861 )
1862 marker_color: str | None = Field(
1863 default=None, alias="marker-color", description="Point marker fill colour"
1864 )
1867class RenderMapInput(BaseModel):
1868 """Use for real-world geographic maps with tile backgrounds (streets, terrain, satellite).
1870 Renders an interactive Leaflet map with OpenStreetMap tiles — no API key required.
1871 Accepts standard GeoJSON (FeatureCollection, Feature, or any geometry type).
1872 Use for: city maps, route planning, area boundaries, points of interest, any data
1873 with real geographic coordinates (latitude / longitude).
1874 """
1876 geojson: dict[str, Any] = Field(
1877 description=(
1878 "A valid GeoJSON object — typically a FeatureCollection. "
1879 "MUST be a complete, well-formed GeoJSON object with a 'type' field.\n"
1880 "Coordinate order is [longitude, latitude] (GeoJSON standard).\n"
1881 "Feature properties support: name, description, color, stroke, fill, marker-color.\n"
1882 "Example FeatureCollection:\n"
1883 ' {"type":"FeatureCollection","features":[\n'
1884 ' {"type":"Feature","geometry":{"type":"Point","coordinates":[-0.1278,51.5074]},\n'
1885 ' "properties":{"name":"Big Ben","color":"#6366f1"}}\n'
1886 " ]}"
1887 )
1888 )
1889 title: str | None = Field(
1890 default=None, description="Optional map title shown above the map"
1891 )
1892 center: list[float] | None = Field(
1893 default=None,
1894 description=(
1895 "Override the initial map centre as [latitude, longitude] (note: lat first, opposite of GeoJSON). "
1896 "If omitted, the map auto-fits to the GeoJSON bounds."
1897 ),
1898 )
1899 zoom: int | None = Field(
1900 default=None,
1901 description="Initial zoom level (1=world, 10=city, 15=street). Only used when center is also provided.",
1902 )
1905def _render_map_factory(config: dict[str, Any]) -> StructuredTool:
1906 def render_map(
1907 geojson: dict[str, Any],
1908 title: str | None = None,
1909 center: list[float] | None = None,
1910 zoom: int | None = None,
1911 ) -> str:
1912 geo_type = geojson.get("type")
1913 if not geo_type:
1914 return (
1915 "[render_map] 'geojson' must be a GeoJSON object with a 'type' field."
1916 )
1918 valid_types = {
1919 "FeatureCollection",
1920 "Feature",
1921 "Point",
1922 "MultiPoint",
1923 "LineString",
1924 "MultiLineString",
1925 "Polygon",
1926 "MultiPolygon",
1927 "GeometryCollection",
1928 }
1929 if geo_type not in valid_types:
1930 return f"[render_map] invalid GeoJSON type '{geo_type}'. Must be one of: {sorted(valid_types)}"
1932 if geo_type == "FeatureCollection" and not isinstance(
1933 geojson.get("features"), list
1934 ):
1935 return "[render_map] FeatureCollection must have a 'features' array."
1937 if center is not None and (
1938 len(center) != 2 or not all(isinstance(v, (int, float)) for v in center)
1939 ):
1940 return (
1941 "[render_map] 'center' must be a [latitude, longitude] pair of numbers."
1942 )
1944 cfg: dict[str, Any] = {"geojson": geojson}
1945 if title:
1946 cfg["title"] = title
1947 if center:
1948 cfg["center"] = center
1949 if zoom is not None:
1950 cfg["zoom"] = zoom
1952 return f"```{_MAP_FENCE}\n{json.dumps(cfg, ensure_ascii=False)}\n```"
1954 return StructuredTool.from_function(
1955 func=render_map,
1956 name="render_map",
1957 description=tool_description(
1958 RenderMapInput,
1959 f"Return a ```{_MAP_FENCE} code fence to embed verbatim in your response.",
1960 ),
1961 args_schema=RenderMapInput,
1962 )
1965_RENDER_MAP_SCHEMA: dict[str, Any] = openai_schema_from_model(
1966 "render_map",
1967 f"Render a real tile map with GeoJSON overlay. Returns a ```{_MAP_FENCE} fence to embed verbatim in your response.",
1968 RenderMapInput,
1969)
1972# ---------------------------------------------------------------------------
1973# geocode — forward geocoding via Nominatim (OpenStreetMap, no API key)
1974# ---------------------------------------------------------------------------
1976_GEOCODE_MAX_CALLS = 30
1979class GeocodeInput(BaseModel):
1980 """Look up geographic coordinates for a place name, address, or landmark.
1982 Uses a public geocoding service — no API key required, worldwide coverage.
1983 Always call this before render_map or render_graph when you need coordinates
1984 for a named location and do not already know them precisely.
1985 Returns lat/lng and ready-to-paste GeoJSON coordinates for each result.
1986 """
1988 query: str = Field(
1989 description=(
1990 "Place name, address, or landmark to geocode. "
1991 "Be specific for better accuracy: 'Tower Bridge, London' beats 'Tower Bridge'. "
1992 "Supports full addresses, postcodes, landmarks, cities, and countries. "
1993 "Examples: 'Big Ben, London', 'Eiffel Tower, Paris', '10 Downing Street', "
1994 "'Central Park, New York City', 'SW1A 1AA'"
1995 )
1996 )
1997 limit: int = Field(
1998 default=5,
1999 description=(
2000 "Maximum number of results to return (1–10). "
2001 "Use 1 for a single best match, higher values when the query may be ambiguous."
2002 ),
2003 )
2004 include_boundary: bool = Field(
2005 default=False,
2006 description=(
2007 "If true, include a GeoJSON polygon of the location's administrative boundary "
2008 "where one exists (e.g. city outline, country border, district shape). "
2009 "Useful for rendering area overlays on a map. May not be available for all places."
2010 ),
2011 )
2014def _geocode_factory(config: dict[str, Any]) -> StructuredTool:
2015 max_calls: int = config.get("max_calls", _GEOCODE_MAX_CALLS)
2016 budget = limits.Budget(max_calls)
2018 async def geocode(
2019 query: str,
2020 limit: int = 5,
2021 include_boundary: bool = False,
2022 ) -> str:
2023 if not budget.take():
2024 return limits.reached("geocode", max_calls)
2026 limit = max(1, min(10, limit))
2028 try:
2029 import httpx
2030 except ImportError:
2031 return "[geocode] unavailable: httpx is not installed."
2033 params: dict[str, Any] = {
2034 "q": query,
2035 "format": "json",
2036 "limit": limit,
2037 "addressdetails": 1,
2038 "accept-language": "en",
2039 }
2040 if include_boundary:
2041 params["polygon_geojson"] = 1
2043 try:
2044 async with httpx.AsyncClient(
2045 timeout=10.0,
2046 headers={"User-Agent": "ChainR-AI/1.0 (+https://datachainr.com)"},
2047 ) as client:
2048 resp = await client.get(
2049 "https://nominatim.openstreetmap.org/search",
2050 params=params,
2051 )
2052 resp.raise_for_status()
2053 results: list[dict[str, Any]] = resp.json()
2054 except Exception as exc:
2055 return f"[geocode] Request failed: {exc}"
2057 if not results:
2058 return f"[geocode] No results found for '{query}'."
2060 lines: list[str] = [
2061 f"Geocode results for '{query}' ({len(results)} result(s)):\n"
2062 ]
2063 for i, r in enumerate(results, 1):
2064 lat = r.get("lat", "")
2065 lon = r.get("lon", "")
2066 display = r.get("display_name", "unknown")
2067 place_class = r.get("class", "")
2068 place_type = r.get("type", "")
2069 importance = float(r.get("importance") or 0)
2071 lines.append(f"{i}. {display}")
2072 lines.append(
2073 f" Type: {place_class}/{place_type} importance: {importance:.3f}"
2074 )
2075 lines.append(f" Coordinates (lat, lng): {lat}, {lon}")
2076 lines.append(f" GeoJSON coordinates [lng, lat]: [{lon}, {lat}]")
2078 # Ready-to-use GeoJSON Point feature
2079 feature = {
2080 "type": "Feature",
2081 "geometry": {"type": "Point", "coordinates": [float(lon), float(lat)]},
2082 "properties": {"name": display.split(",")[0].strip()},
2083 }
2084 lines.append(
2085 f" GeoJSON Feature: {json.dumps(feature, separators=(',', ':'))}"
2086 )
2088 # Bounding box: Nominatim returns [min_lat, max_lat, min_lon, max_lon]
2089 bbox = r.get("boundingbox")
2090 if bbox and len(bbox) == 4:
2091 lines.append(
2092 f" Bounding box: SW [{bbox[0]}, {bbox[2]}] NE [{bbox[1]}, {bbox[3]}]"
2093 )
2095 # Structured address
2096 addr = r.get("address") or {}
2097 addr_parts = [
2098 addr.get("road") or addr.get("pedestrian") or addr.get("path"),
2099 addr.get("suburb") or addr.get("quarter") or addr.get("neighbourhood"),
2100 addr.get("city")
2101 or addr.get("town")
2102 or addr.get("village")
2103 or addr.get("municipality"),
2104 addr.get("state") or addr.get("county") or addr.get("region"),
2105 addr.get("country"),
2106 ]
2107 readable = ", ".join(p for p in addr_parts if p)
2108 if readable:
2109 lines.append(f" Address: {readable}")
2111 # Boundary polygon (only if requested and present)
2112 if include_boundary and "geojson" in r:
2113 geo_str = json.dumps(r["geojson"], separators=(",", ":"))
2114 if len(geo_str) > 3000:
2115 geo_str = geo_str[:3000] + "…[truncated]"
2116 lines.append(f" Boundary GeoJSON: {geo_str}")
2118 lines.append("")
2120 lines.append(
2121 "Reminder: GeoJSON coordinates are [longitude, latitude] order. "
2122 "render_map 'center' uses [latitude, longitude] order."
2123 )
2124 return "\n".join(lines)
2126 return limits.attach(
2127 StructuredTool.from_function(
2128 coroutine=geocode,
2129 name="geocode",
2130 description=tool_description(
2131 GeocodeInput,
2132 "Look up coordinates for a place name. Returns GeoJSON-ready coordinates for use with render_map.",
2133 ),
2134 args_schema=GeocodeInput,
2135 ),
2136 budget,
2137 )
2140_GEOCODE_SCHEMA: dict[str, Any] = openai_schema_from_model(
2141 "geocode",
2142 "Forward-geocode a place name or address to coordinates (a public geocoding service, no API key).",
2143 GeocodeInput,
2144)
2147# ---------------------------------------------------------------------------
2148# Registry
2149# ---------------------------------------------------------------------------
2152# ---------------------------------------------------------------------------
2153# Tool registry
2154#
2155# GENERAL tools — automatically injected into every agent.
2156# SPECIALIST tools — must be explicitly assigned via agent tool config.
2157# ---------------------------------------------------------------------------
2159_BUILTIN_TOOLS: dict[str, ToolDefinition] = {
2160 # ── General reasoning tools ─────────────────────────────────────────────
2161 "current_time": ToolDefinition(
2162 name="current_time",
2163 description="Get the current UTC time in ISO format",
2164 schema=_DATETIME_SCHEMA,
2165 factory=_datetime_factory,
2166 category=ToolCategory.GENERAL,
2167 ),
2168 "calculate": ToolDefinition(
2169 name="calculate",
2170 description="Safely evaluate a mathematical expression and return the result",
2171 schema=_CALCULATE_SCHEMA,
2172 factory=_calculate_factory,
2173 category=ToolCategory.GENERAL,
2174 ),
2175 "validate_code_syntax": ToolDefinition(
2176 name="validate_code_syntax",
2177 description=(
2178 "Statically validate source code syntax and analyse execution flow "
2179 "without executing it"
2180 ),
2181 schema=_VALIDATE_CODE_SCHEMA,
2182 factory=_validate_code_factory,
2183 category=ToolCategory.GENERAL,
2184 ),
2185 "web_search": ToolDefinition(
2186 name="web_search",
2187 description="Search the live web",
2188 schema=WEB_SEARCH_SCHEMA,
2189 factory=web_search_tool_factory,
2190 category=ToolCategory.GENERAL,
2191 ),
2192 "url_fetch": ToolDefinition(
2193 name="url_fetch",
2194 description="Read the main content of a web page or document (use after web_search)",
2195 schema=URL_FETCH_SCHEMA,
2196 factory=url_fetch_tool_factory,
2197 category=ToolCategory.GENERAL,
2198 inherits_web_policy=True,
2199 ),
2200 "geocode": ToolDefinition(
2201 name="geocode",
2202 description=(
2203 "Forward-geocode a place name or address to lat/lng coordinates "
2204 "(a public geocoding service, no API key). Use before render_map when coordinates are unknown."
2205 ),
2206 schema=_GEOCODE_SCHEMA,
2207 factory=_geocode_factory,
2208 category=ToolCategory.GENERAL,
2209 ),
2210 # ── Rich visualisation tools ─────────────────────────────────────────────
2211 "render_chart": ToolDefinition(
2212 name="render_chart",
2213 description=(
2214 f"Render a categorical chart ({vocab.listing(ChartType, sep=', ')}) "
2215 "with validated schema. "
2216 f"Returns a ```{_CHART_FENCE} code fence for embedding in the response."
2217 ),
2218 schema=_RENDER_CHART_SCHEMA,
2219 factory=_render_chart_factory,
2220 category=ToolCategory.GENERAL,
2221 ),
2222 "render_plot": ToolDefinition(
2223 name="render_plot",
2224 description=(
2225 f"Render a numeric plot ({vocab.listing(PlotType, sep=', ')}) "
2226 "with validated schema. "
2227 f"Returns a ```{_PLOT_FENCE} code fence for embedding in the response."
2228 ),
2229 schema=_RENDER_PLOT_SCHEMA,
2230 factory=_render_plot_factory,
2231 category=ToolCategory.GENERAL,
2232 ),
2233 "render_mermaid": ToolDefinition(
2234 name="render_mermaid",
2235 description=(
2236 f"Render a Mermaid diagram: a {mermaid_vocabulary.described()}. "
2237 f"Returns a ```{_MERMAID_FENCE} code fence for embedding in the response."
2238 ),
2239 schema=_RENDER_MERMAID_SCHEMA,
2240 factory=_render_mermaid_factory,
2241 category=ToolCategory.GENERAL,
2242 ),
2243 "render_graph": ToolDefinition(
2244 name="render_graph",
2245 description=(
2246 "Render an interactive 2D/3D network graph or geographic map with nodes and edges. "
2247 f"Returns a ```{_GRAPH_FENCE} code fence for embedding in the response."
2248 ),
2249 schema=_RENDER_GRAPH_SCHEMA,
2250 factory=_render_graph_factory,
2251 category=ToolCategory.GENERAL,
2252 ),
2253 "render_map": ToolDefinition(
2254 name="render_map",
2255 description=(
2256 "Render a real tile map with a GeoJSON overlay. "
2257 f"Returns a ```{_MAP_FENCE} code fence for embedding in the response."
2258 ),
2259 schema=_RENDER_MAP_SCHEMA,
2260 factory=_render_map_factory,
2261 category=ToolCategory.GENERAL,
2262 ),
2263 "render_document": ToolDefinition(
2264 name="render_document",
2265 description=(
2266 "Attach a structured report (title, summary, findings, Markdown "
2267 "body, sources) to the reply as a document card with a PDF download. "
2268 "Returns a ```document code fence."
2269 ),
2270 schema=_RENDER_DOCUMENT_SCHEMA,
2271 factory=_render_document_factory,
2272 category=ToolCategory.GENERAL,
2273 inherits_web_policy=True,
2274 ),
2275 "ask_user": ToolDefinition(
2276 name="ask_user",
2277 description=(
2278 "Ask the user clarifying questions and wait for their answers "
2279 "before continuing"
2280 ),
2281 schema=ASK_USER_SCHEMA,
2282 factory=ask_user_tool_factory,
2283 category=ToolCategory.GENERAL,
2284 ),
2285 # ── Specialist tools ────────────────────────────────────────────────────
2286 "query_knowledge_base": ToolDefinition(
2287 name="query_knowledge_base",
2288 description="Query a RAG knowledge base collection for relevant information",
2289 schema=_QUERY_KB_SCHEMA,
2290 factory=_query_kb_factory,
2291 category=ToolCategory.SPECIALIST,
2292 ),
2293 "query_knowledge_graph": ToolDefinition(
2294 name="query_knowledge_graph",
2295 description="Traverse a knowledge graph to find entities and their relationships",
2296 schema=_QUERY_KG_SCHEMA,
2297 factory=_query_kg_factory,
2298 category=ToolCategory.SPECIALIST,
2299 ),
2300}
2302BUILTIN_TOOLS: BuiltinRegistry[ToolDefinition] = BuiltinRegistry(
2303 _BUILTIN_TOOLS.values(), key=lambda t: t.name
2304)
2306# Tools whose output is a rich-rendering code fence (see RENDER_FENCE_LANGUAGES) that
2307# the frontend displays. Referenced by agents/base.py (the rendering hint is
2308# only injected when one of these is bound) and agents/graph.py (synthesis
2309# tool binding, artifact fence extraction).
2310RENDER_TOOL_NAMES: frozenset[str] = frozenset(
2311 name for name in BUILTIN_TOOLS.keys() if name.startswith("render_")
2312)
2313#: The tool that makes a document: a workflow with a step of its own that
2314#: calls it keeps it to that step (``AgentFactory.from_graph_definition``).
2315DOCUMENT_TOOL = "render_document"
2318def resolve_tool(name: str, config: dict[str, Any] | None = None) -> StructuredTool:
2319 """Resolve a built-in tool name to a LangChain StructuredTool.
2321 Raises:
2322 ValueError: If the tool name is not in the registry.
2323 """
2324 defn = BUILTIN_TOOLS.get_or_raise(name, label="built-in tool")
2325 return platform_owned(defn.factory(config or {}))
2328def general_tools(
2329 config_overrides: dict[str, dict[str, Any]] | None = None,
2330) -> list[StructuredTool]:
2331 """Instantiate every GENERAL-category tool with default (or overridden) config.
2333 These tools are injected into every agent automatically at construction
2334 time — no per-agent configuration required.
2336 Args:
2337 config_overrides: Optional per-tool config dict keyed by tool name.
2338 Overrides are merged on top of the tool's default empty config,
2339 allowing callers to customise rate limits, domain filters, etc.
2340 without preventing the tool from being auto-injected.
2342 Returns:
2343 Fresh ``StructuredTool`` instances in registry declaration order.
2344 """
2345 overrides = dict(config_overrides or {})
2346 web_cfg = overrides.get("web_search")
2347 return [
2348 platform_owned(
2349 defn.factory(run_tool_config(name, web_cfg, overrides.get(name)))
2350 )
2351 for name, defn in BUILTIN_TOOLS.items()
2352 if defn.category == ToolCategory.GENERAL
2353 ]
2356def run_tool_config(
2357 name: str,
2358 web_cfg: Mapping[str, Any] | None,
2359 own: Mapping[str, Any] | None = None,
2360) -> dict[str, Any]:
2361 """A built-in tool's config in a run: its own, and — for a tool that
2362 fetches from the web (``inherits_web_policy``) and names no domains of its
2363 own — the run's web_search domain policy, so an operator's allowlist
2364 cannot be bypassed by fetching a URL directly or linking an image."""
2365 config = dict(own or {})
2366 defn = BUILTIN_TOOLS.get(name)
2367 if defn is None or not defn.inherits_web_policy or not web_cfg:
2368 return config
2369 if config.get("allowed_domains") or config.get("blocked_domains"):
2370 return config
2371 return {**config, **url_fetch_config_from_web_search(dict(web_cfg))}
2374# ---------------------------------------------------------------------------
2375# Per-knowledge-base tool factories
2376# ---------------------------------------------------------------------------
2379def _kb_tool_name(prefix: str, kb_name: str) -> str:
2380 """Derive a valid tool identifier from a knowledge base name."""
2381 sanitized = re.sub(r"[^a-z0-9]+", "_", kb_name.lower().strip()).strip("_")
2382 sanitized = sanitized[:40] or "kb"
2383 return f"{prefix}_{sanitized}"
2386def make_kb_rag_tool(
2387 kb_id: str,
2388 kb_name: str,
2389 description: str = "",
2390 top_k: int = 5,
2391) -> tuple[dict[str, Any], StructuredTool]:
2392 """
2393 Build a pre-configured RAG query tool for a specific vector knowledge base.
2395 The tool name is derived from kb_name so agents can distinguish between
2396 multiple knowledge bases without needing to supply a collection ID.
2398 Returns:
2399 (openai_function_schema, langchain_structured_tool)
2400 """
2401 tool_name = _kb_tool_name("search", kb_name)
2402 tool_desc = f"Search the '{kb_name}' knowledge base for relevant information."
2403 if description:
2404 tool_desc += f" {description}"
2406 _collection = kb_id
2407 _top_k = top_k
2409 class _Input(BaseModel):
2410 query: str = Field(
2411 description=f"The question or search query for the '{kb_name}' knowledge base"
2412 )
2414 async def _search(query: str) -> str:
2415 from app.models.spec import RAGConfig
2416 from app.services import rag as rag_service
2418 rag_config = RAGConfig(collection=_collection, top_k=_top_k)
2419 return await rag_service.search(rag_config, query, lexical=True)
2421 tool = StructuredTool.from_function(
2422 coroutine=_search,
2423 name=tool_name,
2424 description=tool_desc,
2425 args_schema=_Input,
2426 )
2428 schema: dict[str, Any] = {
2429 "type": "function",
2430 "function": {
2431 "name": tool_name,
2432 "description": tool_desc,
2433 "parameters": {
2434 "type": "object",
2435 "properties": {
2436 "query": {
2437 "type": "string",
2438 "description": f"The question or search query for the '{kb_name}' knowledge base",
2439 },
2440 },
2441 "required": ["query"],
2442 },
2443 },
2444 }
2446 return schema, tool
2449_FILES_SOURCES_MARKER = source_trailers.DOCUMENT
2452def make_kb_files_tool(
2453 kb_id: str,
2454 kb_name: str,
2455 description: str = "",
2456) -> tuple[dict[str, Any], StructuredTool]:
2457 """
2458 Build a file list/retrieval tool for a file-based knowledge base.
2460 When ``filename`` is omitted the tool lists every stored document (original
2461 names, folders, page/chunk counts). When ``filename`` is provided it is
2462 resolved tolerantly — original or sanitised name, case-insensitive, with or
2463 without extension, close misspellings — and the document's full *parsed*
2464 text is returned (assembled from the indexed chunks, so PDF/Office files
2465 read correctly), with a "did you mean" list on a miss.
2467 Returns:
2468 (openai_function_schema, langchain_structured_tool)
2469 """
2470 tool_name = _kb_tool_name("files", kb_name)
2471 tool_desc = (
2472 f"List or read documents stored in the '{kb_name}' knowledge base. "
2473 "Call with no filename to list all documents; call with a document name "
2474 f"(exact or approximate) to read it, {READ_PART_CHARS:,} characters at a time."
2475 )
2476 if description:
2477 tool_desc += f" {description}"
2479 _kb_id = kb_id
2481 class _Input(BaseModel):
2482 filename: str = Field(
2483 default="",
2484 description=(
2485 "Leave empty to list all available documents. "
2486 "Provide a document name (as shown in the listing or as the user "
2487 "wrote it — approximate names are resolved) to read it, a part "
2488 f"at a time ({READ_PART_CHARS:,} characters)."
2489 ),
2490 )
2491 offset: int = Field(
2492 default=0,
2493 description=(
2494 "Where to start reading, in characters: 0 for the beginning, or "
2495 "the offset the previous part ended with."
2496 ),
2497 )
2499 async def _query(filename: str = "", offset: int = 0) -> str:
2500 from app.knowledge import documents as documents_service
2502 if not filename.strip():
2503 docs = await documents_service.list_documents(_kb_id, force=True)
2504 if not docs:
2505 return f"No documents found in knowledge base '{kb_name}'."
2506 lines = [f"Documents in '{kb_name}' ({len(docs)}):"]
2507 lines += [f"- {d.describe()}" for d in docs]
2508 return "\n".join(lines)
2510 best, alternatives = await documents_service.resolve_document(_kb_id, filename)
2511 if best is None:
2512 docs = await documents_service.list_documents(_kb_id)
2513 suggestions = alternatives or docs[:15]
2514 msg = f"No document named '{filename}' in knowledge base '{kb_name}'."
2515 if suggestions:
2516 msg += " Closest available documents:\n" + "\n".join(
2517 f"- {d.display_name}" for d in suggestions
2518 )
2519 else:
2520 msg += " The knowledge base has no documents."
2521 return msg
2523 doc = await documents_service.get_document_text(
2524 _kb_id, best, max_chars=_READABLE_CHARS
2525 )
2526 where, body = _document_part(
2527 doc.text,
2528 offset,
2529 document=best.display_name,
2530 truncated=doc.truncated,
2531 tool=tool_name,
2532 search=None,
2533 )
2534 header = f"# {best.display_name}"
2535 if best.display_name.lower() != filename.strip().lower():
2536 header += f" (matched from '{filename.strip()}')"
2537 meta: list[str] = []
2538 if best.folder_path:
2539 meta.append(f"folder: {best.folder_path}/")
2540 if best.max_page:
2541 meta.append(f"pages: {best.max_page}")
2542 if doc.chunk_count:
2543 meta.append(f"chunks: {doc.chunk_count}")
2544 if where:
2545 meta.append(where)
2546 if meta:
2547 header += "\n" + " · ".join(meta)
2548 if doc.note:
2549 header += f"\nNote: {doc.note}"
2550 if not doc.text:
2551 return header + _FILES_SOURCES_MARKER + json.dumps([best.display_name])
2552 return (
2553 f"{header}\n\n{body}"
2554 + _FILES_SOURCES_MARKER
2555 + json.dumps([best.display_name])
2556 )
2558 tool = StructuredTool.from_function(
2559 coroutine=_query,
2560 name=tool_name,
2561 description=tool_desc,
2562 args_schema=_Input,
2563 )
2565 schema: dict[str, Any] = {
2566 "type": "function",
2567 "function": {
2568 "name": tool_name,
2569 "description": tool_desc,
2570 "parameters": {
2571 "type": "object",
2572 "properties": {
2573 "filename": {
2574 "type": "string",
2575 "description": (
2576 "Leave empty to list all available documents. "
2577 "Provide a document name (exact or approximate) to read its full text."
2578 ),
2579 },
2580 },
2581 "required": [],
2582 },
2583 },
2584 }
2586 return schema, tool
2589def make_kb_graph_tool(
2590 kb_id: str,
2591 kb_name: str,
2592 description: str = "",
2593 depth: int = 2,
2594) -> tuple[dict[str, Any], StructuredTool]:
2595 """
2596 Build a pre-configured graph traversal tool for a specific graph knowledge base.
2598 Returns:
2599 (openai_function_schema, langchain_structured_tool)
2600 """
2601 tool_name = _kb_tool_name("explore", kb_name)
2602 tool_desc = (
2603 f"Explore the '{kb_name}' knowledge graph to find entities and relationships."
2604 )
2605 if description:
2606 tool_desc += f" {description}"
2608 _knowledge_id = kb_id
2609 _depth = depth
2611 class _Input(BaseModel):
2612 query: str = Field(
2613 description=(
2614 f"Exact entity name from the '{kb_name}' graph schema (e.g. 'Alice Smith', 'Docker') "
2615 "OR an entity type label to browse all entities of that type (e.g. 'Person', 'Technology'). "
2616 "Never pass natural-language phrases or questions — only names or labels."
2617 )
2618 )
2620 async def _explore(query: str) -> str:
2621 from app.util import neo4j_client
2623 return await neo4j_client.query_and_format(
2624 _knowledge_id, query, depth=_depth, limit=10
2625 )
2627 tool = StructuredTool.from_function(
2628 coroutine=_explore,
2629 name=tool_name,
2630 description=tool_desc,
2631 args_schema=_Input,
2632 )
2634 schema: dict[str, Any] = {
2635 "type": "function",
2636 "function": {
2637 "name": tool_name,
2638 "description": tool_desc,
2639 "parameters": {
2640 "type": "object",
2641 "properties": {
2642 "query": {
2643 "type": "string",
2644 "description": (
2645 f"Exact entity name from the '{kb_name}' graph schema "
2646 "OR an entity type label to browse all entities of that type. "
2647 "Never pass natural-language phrases."
2648 ),
2649 },
2650 },
2651 "required": ["query"],
2652 },
2653 },
2654 }
2656 return schema, tool
2659# ---------------------------------------------------------------------------
2660# Webhook tool factory
2661# ---------------------------------------------------------------------------
2664class WebhookToolInput(BaseModel):
2665 payload: dict[str, Any] = Field(
2666 default_factory=dict, description="JSON payload to POST to the webhook"
2667 )
2670def make_kb_chained_graph_tool(graph_kbs: list[dict[str, Any]]) -> StructuredTool:
2671 """
2672 Build a replacement for the generic ``query_knowledge_graph`` tool that
2673 queries all configured graph knowledge bases.
2675 The returned tool has the same name (``query_knowledge_graph``) so it
2676 overwrites the generic version when deduplication-by-name is applied in
2677 ``WorkerAgent.process_with_history``.
2679 The ``knowledge_id`` is baked in at registration time — the LLM only
2680 supplies ``query`` and ``depth``. When multiple graph KBs are attached,
2681 all are queried and results are merged so the LLM sees a unified answer.
2682 """
2683 _kb_map: dict[str, str] = {kb["id"]: kb["name"] for kb in graph_kbs}
2684 kb_names = ", ".join(_kb_map.values())
2686 class _Input(BaseModel):
2687 query: str = Field(
2688 description=(
2689 "Exact entity name from the graph schema OR an entity type label to browse all "
2690 "entities of that type (e.g. 'Person', 'Technology'). "
2691 "Never pass natural-language phrases or questions — only names or labels."
2692 )
2693 )
2694 depth: int = Field(
2695 default=2,
2696 description="Number of relationship hops to traverse from matching entities",
2697 )
2699 async def _chained_query(query: str, depth: int = 2) -> str:
2700 from app.util import neo4j_client
2702 results: list[str] = []
2703 for kb_id, kb_name in _kb_map.items():
2704 section = await neo4j_client.query_and_format(
2705 kb_id, query, depth=depth, limit=10
2706 )
2707 # Only include sections that found something
2708 if "No entities found" not in section:
2709 results.append(f"[{kb_name}]\n{section}")
2711 if not results:
2712 return f"No entities found matching '{query}' in any knowledge graph."
2713 return "\n\n".join(results)
2715 return StructuredTool.from_function(
2716 coroutine=_chained_query,
2717 name="query_knowledge_graph",
2718 description=(
2719 f"Traverse knowledge graph(s) ({kb_names}) to find entities and their "
2720 "relationships. Returns matching entities and their connections up to "
2721 "the specified depth."
2722 ),
2723 args_schema=_Input,
2724 )
2727class ScriptedToolInput(BaseModel):
2728 """Arguments for a scripted tool that stands in for no real one.
2730 Permissive on purpose: the agent may call it however its description
2731 suggests, and the call is recorded with whatever it passed.
2732 """
2734 model_config = {"extra": "allow"}
2736 query: str = Field(default="", description="What to look up.")
2739def make_scripted_tool(
2740 name: str,
2741 response: str,
2742 description: str = "",
2743 stands_in_for: StructuredTool | None = None,
2744) -> StructuredTool:
2745 """A tool that answers every call with ``response`` and does nothing else.
2747 ``stands_in_for`` is the real tool it replaces: its description,
2748 argument schema and metadata are kept, so the agent sees — and calls —
2749 the same tool it would in production, bound strictly where it would be
2750 (``app/tools/wire.py``). Without one, the tool is new and takes a free-form
2751 query. Either way nothing is fetched, so a scripted answer can never
2752 reach the network.
2753 """
2754 _response = response
2756 async def _call(**_: Any) -> str:
2757 return _response
2759 return StructuredTool.from_function(
2760 coroutine=_call,
2761 name=name,
2762 description=(
2763 (stands_in_for.description if stands_in_for else "")
2764 or description
2765 or f"Look up {name.replace('_', ' ')}."
2766 ),
2767 args_schema=(
2768 stands_in_for.args_schema
2769 if stands_in_for is not None and stands_in_for.args_schema is not None
2770 else ScriptedToolInput
2771 ),
2772 metadata=dict(stands_in_for.metadata or {}) if stands_in_for else None,
2773 )
2776def make_webhook_tool(
2777 name: str,
2778 url: str,
2779 description: str = "",
2780 *,
2781 resolver: Resolver = system_resolver,
2782 transport: httpx.AsyncBaseTransport | None = None,
2783) -> StructuredTool:
2784 """
2785 Create a LangChain StructuredTool that POSTs to an HTTP webhook.
2787 The tool sends the ``payload`` dict as JSON and returns the response body
2788 as a string. Used for ``type="webhook"`` ToolConfig entries in AgentConfig.
2790 The URL is held to url_fetch's rule: https on 443 to a public address,
2791 checked before the call and again as the connection opens
2792 (``PublicOnlyTransport``), and a redirect is not followed. svc-ai's
2793 neighbours (qdrant, tempo) answer unauthenticated requests, and the
2794 response goes back to the model.
2796 Args:
2797 name: Tool identifier (must be a valid Python identifier).
2798 url: Webhook URL to POST to.
2799 description: Human-readable description shown to the LLM.
2800 resolver / transport: test seams, as for ``url_fetch``.
2801 """
2802 _url = url
2803 _description = description or f"Call the {name} webhook"
2804 policy = DomainPolicy(require_https=True)
2806 async def _call(payload: dict[str, Any] = {}) -> str: # noqa: B006
2807 try:
2808 await assert_public_https_url(_url, policy, resolver)
2809 async with httpx.AsyncClient(
2810 timeout=30.0,
2811 follow_redirects=False,
2812 transport=transport or PublicOnlyTransport(resolver),
2813 ) as client:
2814 resp = await client.post(_url, json=payload)
2815 resp.raise_for_status()
2816 return resp.text
2817 except Exception as exc:
2818 return f"Webhook error: {exc}"
2820 return StructuredTool.from_function(
2821 coroutine=_call,
2822 name=name,
2823 description=_description,
2824 args_schema=WebhookToolInput,
2825 )
2828# ---------------------------------------------------------------------------
2829# Unified knowledge tools (one stable tool set regardless of KB count)
2830# ---------------------------------------------------------------------------
2831#
2832# Per-KB tools (``search_<kb>``, ``files_<kb>``, ``explore_<kb>``) derive their
2833# names from user-typed KB names: they get long and ugly, collide when two
2834# names sanitise identically, change whenever a KB is renamed (breaking stored
2835# traces and prompts), and multiply the tool schema tokens by the number of
2836# KBs. The tools below keep fixed names and take the knowledge base as an
2837# optional argument whose allowed values are listed in the description — the
2838# model sees a short, stable interface and can still target one KB precisely.
2841def _kb_slug(name: str) -> str:
2842 # Drop apostrophes before splitting so "Founder's" and "Founders" agree.
2843 cleaned = re.sub(r"[\'\u2019`]", "", (name or "").lower())
2844 return re.sub(r"[^a-z0-9]+", " ", cleaned).strip()
2847def _resolve_kb(selector: str, kbs: list[dict[str, Any]]) -> dict[str, Any] | None:
2848 """Match a KB by id, exact name, case-insensitive name, or unique substring."""
2849 sel = (selector or "").strip()
2850 if not sel or not kbs:
2851 return None
2852 for kb in kbs:
2853 if str(kb.get("id", "")) == sel or str(kb.get("name", "")) == sel:
2854 return kb
2855 slug = _kb_slug(sel)
2856 exact = [kb for kb in kbs if _kb_slug(str(kb.get("name", ""))) == slug]
2857 if len(exact) == 1:
2858 return exact[0]
2859 partial = [
2860 kb
2861 for kb in kbs
2862 if slug
2863 and (
2864 slug in _kb_slug(str(kb.get("name", "")))
2865 or _kb_slug(str(kb.get("name", ""))) in slug
2866 )
2867 ]
2868 return partial[0] if len(partial) == 1 else None
2871def _kb_choices(kbs: list[dict[str, Any]]) -> str:
2872 return ", ".join(f"'{kb.get('name', kb.get('id'))}'" for kb in kbs)
2875#: The knowledge tools' names — the same four whatever is attached, so the
2876#: retrieval prompts and an agent's knowledge-base context can name them.
2877SEARCH_KNOWLEDGE_TOOL = "search_knowledge"
2878READ_DOCUMENT_TOOL = "read_document"
2879LIST_DOCUMENTS_TOOL = "list_documents"
2880EXPLORE_GRAPH_TOOL = "explore_graph"
2882#: The most of a stored document one ``read_document`` call returns, in
2883#: characters (url_fetch's page is 8,000). It returned up to 60,000 on every
2884#: call, and a turn that read four guidance pages carried them all on every
2885#: later round of its tool loop (``util/text_pages``).
2886READ_PART_CHARS = 12_000
2887#: The most of a document read at all; a part comes from within it.
2888_READABLE_CHARS = 2_000_000
2891def _document_part(
2892 text: str,
2893 offset: int,
2894 *,
2895 document: str,
2896 truncated: bool,
2897 tool: str,
2898 search: str | None = SEARCH_KNOWLEDGE_TOOL,
2899) -> tuple[str | None, str]:
2900 """A part of a stored document's ``text`` as ``read_document`` returns it:
2901 where it is (None when ``offset`` is past the end) and the part with a
2902 closing line that says where the next begins."""
2903 piece = text_pages.part(text, offset, READ_PART_CHARS)
2904 if piece is None:
2905 return None, (
2906 f"{document} has {len(text):,} characters; offset {offset:,} is past "
2907 "its end. Read from offset 0, or from the offset a part gave."
2908 )
2909 if piece.more:
2910 tail = (
2911 f'[Continues: call {tool} with document "{document}" and offset '
2912 f"{piece.end} for the next part"
2913 + (f", or {search} for a passage" if search else "")
2914 + ".]"
2915 )
2916 elif truncated:
2917 tail = "[End of what can be read of this document.]"
2918 else:
2919 tail = "[End of the document.]"
2920 return piece.where(), f"{piece.text}\n\n{tail}"
2923def make_knowledge_tools(
2924 knowledge_bases: list[dict[str, Any]],
2925 attachments: Sequence[Any] = (),
2926 empty: Iterable[str] = (),
2927 default: Iterable[str] | None = None,
2928) -> list[StructuredTool]:
2929 """Build the unified knowledge tool set for the given KB descriptors.
2931 Emits ``search_knowledge`` / ``read_document`` / ``list_documents`` when at
2932 least one vector KB is attached and ``explore_graph`` when at least one
2933 graph KB is attached. Every tool accepts an optional ``knowledge_base``
2934 selector (name or id); when omitted, all KBs of the relevant kind are
2935 used and results are labelled per KB.
2937 ``attachments`` are the documents the person attached to the
2938 conversation (``app/util/attachments.py``): ``read_document`` given one
2939 of their names or ids reads that document, as ``read_attachment`` would,
2940 instead of reporting a knowledge base file missing.
2942 Each knowledge base's kind (``app/knowledge/categories.py``) shapes what
2943 a search of it returns: dated results newest first, or a framework
2944 labelled as a method to apply.
2946 ``empty`` are the knowledge bases confirmed to hold nothing (the gate's
2947 count): ``search_knowledge`` leaves them out, and says so when it is
2948 asked for only those. The tools' descriptions are the same either way,
2949 so the cached tool block does not change as knowledge fills.
2951 ``default`` are the knowledge bases a search that names none searches:
2952 the turn's mix (``knowledge.mix``), so the agent's own search reads the
2953 kinds the turn reads — run 1's a-dpia searched all sixteen of its
2954 agent's, dated news included, for a question about a DPIA. None: every
2955 one. Naming any knowledge base searches that one.
2956 """
2957 from app.knowledge import categories as knowledge_categories
2958 from app.util.knowledge_categories import KnowledgeCategory
2960 vector_kbs = [kb for kb in knowledge_bases if kb.get("source_type") != "graph"]
2961 graph_kbs = [kb for kb in knowledge_bases if kb.get("source_type") == "graph"]
2962 nothing = {str(kb_id) for kb_id in empty}
2963 defaults = None if default is None else {str(kb_id) for kb_id in default}
2964 tools: list[StructuredTool] = []
2966 if vector_kbs:
2967 v_choices = _kb_choices(vector_kbs)
2968 single_vector = len(vector_kbs) == 1
2970 def _select_vector(selector: str) -> list[dict[str, Any]] | str:
2971 if not selector.strip() or single_vector:
2972 return vector_kbs
2973 kb = _resolve_kb(selector, vector_kbs)
2974 if kb is None:
2975 return (
2976 f"Unknown knowledge base '{selector}'. Choose one of: {v_choices}."
2977 )
2978 return [kb]
2980 class _SearchInput(BaseModel):
2981 query: str = Field(
2982 description=(
2983 "What to look for, as a natural-language question or a short "
2984 "keyword phrase. Exact names, identifiers and figures are matched "
2985 "literally as well as semantically."
2986 )
2987 )
2988 knowledge_base: str = Field(
2989 default="",
2990 description=(
2991 "Optional. Restrict the search to one knowledge base by name"
2992 + (f" — one of: {v_choices}" if not single_vector else "")
2993 + ". Leave empty to search those that apply to this request."
2994 ),
2995 )
2996 top_k: int = Field(
2997 default=6,
2998 ge=1,
2999 le=20,
3000 description=(
3001 "How many passages to return in all: the best across the "
3002 "knowledge bases searched"
3003 ),
3004 )
3006 async def _search(
3007 query: str, knowledge_base: str = "", top_k: int = 6
3008 ) -> tuple[str, list[dict[str, Any]]]:
3009 from app.models.spec import RAGConfig
3010 from app.services import embeddings
3011 from app.services import rag as rag_service
3013 selected = _select_vector(knowledge_base)
3014 if isinstance(selected, str):
3015 return selected, []
3016 if not knowledge_base.strip() and defaults:
3017 selected = [
3018 kb for kb in selected if str(kb.get("id", "")) in defaults
3019 ] or selected
3020 holding = [kb for kb in selected if str(kb.get("id", "")) not in nothing]
3021 if not holding:
3022 names = ", ".join(str(kb.get("name", kb["id"])) for kb in selected)
3023 return (
3024 f"{names}: {rag_service.EMPTY_MESSAGE}"
3025 if len(selected) == 1
3026 else f"None of these knowledge bases holds anything yet: {names}.",
3027 [],
3028 )
3029 selected = holding
3031 def _config(kb: dict[str, Any]) -> RAGConfig:
3032 return RAGConfig(
3033 collection=str(kb["id"]),
3034 # A knowledge base's own setting is the most it gives.
3035 top_k=min(
3036 int((kb.get("config") or {}).get("top_k") or top_k), top_k
3037 ),
3038 # Broad: the agent asked to search everything attached.
3039 score_threshold=embeddings.active().floors.loose,
3040 )
3042 found_by_kb = dict(
3043 zip(
3044 (str(kb["id"]) for kb in selected),
3045 await asyncio.gather(
3046 *(
3047 rag_service.search_hits(_config(kb), query)
3048 for kb in selected
3049 )
3050 ),
3051 )
3052 )
3053 # The best top_k in all, not top_k of each: a search of thirteen
3054 # knowledge bases returned 22–31k tokens (scenario run 7).
3055 kept = dict(rag_service.best_overall(found_by_kb, top_k))
3056 by_id = {str(kb["id"]): kb for kb in selected}
3057 sections: list[str] = []
3058 sources: list[dict[str, str]] = []
3059 # What each knowledge base searched gave, beside the text: the
3060 # turn's retrieval record counts it (``knowledge_report``), no
3061 # model reads it.
3062 searched: dict[str, dict[str, Any]] = {
3063 str(kb["id"]): {
3064 "knowledge_id": str(kb["id"]),
3065 "category": knowledge_categories.behaviour(kb).category.value,
3066 "found": 0,
3067 "hits": [],
3068 }
3069 for kb in selected
3070 }
3071 nothing_found: list[str] = []
3072 below_best: list[str] = []
3073 if len(selected) > 1:
3074 for kb in selected:
3075 if str(kb["id"]) not in kept:
3076 (
3077 below_best if found_by_kb[str(kb["id"])] else nothing_found
3078 ).append(str(kb.get("name", kb["id"])))
3079 # Each knowledge base kept, the one holding the best passage first.
3080 for kb_id, hits_kept in kept.items():
3081 kb = by_id[kb_id]
3082 name = str(kb.get("name", kb_id))
3083 kind = knowledge_categories.behaviour(kb)
3084 hits: list[tuple[str, int]] = []
3085 body = rag_service.format_hits(
3086 hits_kept,
3087 dated=kind.category is KnowledgeCategory.temporal,
3088 hits=hits,
3089 )
3090 body, found = rag_service.split_sources(body)
3091 searched[kb_id].update(
3092 found=rag_service.result_count(body),
3093 # Which passages, so the record counts each once.
3094 hits=[[doc, chunk] for doc, chunk in hits],
3095 )
3096 sources += [
3097 {**s, "kb_name": name}
3098 if isinstance(s, dict)
3099 else {"source": s, "kb_name": name}
3100 for s in found
3101 ]
3102 label = f"### {name}" if len(selected) > 1 else ""
3103 if kind.tool_note and body != rag_service.NO_RESULTS:
3104 # What its kind means for the agent: dated results, or a
3105 # method to apply rather than facts. Never above nothing:
3106 # memory read the dated line as an answer resting on
3107 # dated knowledge.
3108 sections.append(
3109 "\n".join(
3110 part for part in (label, kind.tool_note, body) if part
3111 )
3112 )
3113 else:
3114 sections.append(f"{label}\n{body}".strip())
3115 if not kept and len(selected) == 1:
3116 sections.append(rag_service.NO_RESULTS)
3117 if below_best:
3118 sections.append(
3119 "Also matched, below the best passages above: "
3120 + ", ".join(below_best)
3121 + " (name one to search it alone)."
3122 )
3123 if nothing_found:
3124 sections.append(
3125 "No results above the relevance threshold in: "
3126 + ", ".join(nothing_found)
3127 + "."
3128 )
3129 # One trailer for the whole result, naming each source's
3130 # knowledge base: a trailer per section read as one malformed
3131 # list, and a search of several knowledge bases cited nothing.
3132 return (
3133 rag_service.append_sources("\n\n".join(sections), sources),
3134 list(searched.values()),
3135 )
3137 tools.append(
3138 StructuredTool.from_function(
3139 coroutine=_search,
3140 name=SEARCH_KNOWLEDGE_TOOL,
3141 description=(
3142 "Semantic + keyword search over the attached knowledge base(s) "
3143 f"({v_choices}). Returns the most relevant passages with source "
3144 "file, page and relevance score. Use for facts, figures and topics; "
3145 f"use {READ_DOCUMENT_TOOL} to read a specific file, a part at a time."
3146 ),
3147 args_schema=_SearchInput,
3148 response_format="content_and_artifact",
3149 )
3150 )
3152 class _ReadInput(BaseModel):
3153 document: str = Field(
3154 description=(
3155 "The document to read, as the user or the listing names it — e.g. "
3156 "'README', 'Annual Report 2024.pdf', 'annual_report_2024'. Approximate "
3157 "names, different casing, missing extensions and underscores are resolved."
3158 )
3159 )
3160 knowledge_base: str = Field(
3161 default="",
3162 description=(
3163 "Optional. Which knowledge base holds the document"
3164 + (f" — one of: {v_choices}" if not single_vector else "")
3165 + ". Leave empty to look across all; only needed when the same "
3166 "file name exists in several knowledge bases."
3167 ),
3168 )
3169 offset: int = Field(
3170 default=0,
3171 description=(
3172 "Where to start, in characters: 0 for the beginning, or the "
3173 "offset the previous part ended with, to read on."
3174 ),
3175 )
3177 async def _read(
3178 document: str, knowledge_base: str = "", offset: int = 0
3179 ) -> str:
3180 from app.knowledge import documents as documents_service
3181 from app.tools import attachments as attachment_tools
3183 attached = attachment_tools.strong_match(attachments, document)
3184 if attached is not None and not knowledge_base.strip():
3185 # The person's document, not a file of the knowledge bases.
3186 return (
3187 f"'{document.strip()}' is a document the person attached to "
3188 "this conversation, not a knowledge base file. Read with "
3189 f"{attachment_tools.READ_ATTACHMENT_TOOL} from here on.\n\n"
3190 + attachment_tools.read_page(attached)
3191 )
3192 selected = _select_vector(knowledge_base)
3193 if isinstance(selected, str):
3194 return selected
3195 hits: list[tuple[dict[str, Any], Any]] = []
3196 alternatives: list[tuple[dict[str, Any], Any]] = []
3197 for kb in selected:
3198 best, alts = await documents_service.resolve_document(
3199 str(kb["id"]), document, manifest=kb.get("documents")
3200 )
3201 if best is not None:
3202 hits.append((kb, best))
3203 alternatives.extend((kb, a) for a in alts)
3204 if len(hits) > 1:
3205 options = "\n".join(
3206 f"- {ref.display_name} (knowledge base '{kb.get('name', kb['id'])}')"
3207 for kb, ref in hits
3208 )
3209 return (
3210 f"'{document}' matches a document in more than one knowledge base. "
3211 f"Call {READ_DOCUMENT_TOOL} again with knowledge_base set to the "
3212 "right one:\n" + options
3213 )
3214 if not hits:
3215 msg = (
3216 f"No document named '{document}' in "
3217 + (
3218 f"knowledge base '{selected[0].get('name', selected[0]['id'])}'"
3219 if len(selected) == 1
3220 else "any attached knowledge base"
3221 )
3222 + "."
3223 )
3224 if alternatives:
3225 msg += " Closest available documents:\n" + "\n".join(
3226 f"- {ref.display_name} (in '{kb.get('name', kb['id'])}')"
3227 for kb, ref in alternatives[:10]
3228 )
3229 else:
3230 listing: list[str] = []
3231 for kb in selected:
3232 docs = await documents_service.list_documents(
3233 str(kb["id"]), manifest=kb.get("documents")
3234 )
3235 listing += [
3236 f"- {d.display_name} (in '{kb.get('name', kb['id'])}')"
3237 for d in docs[:10]
3238 ]
3239 msg += (
3240 (" Available documents:\n" + "\n".join(listing))
3241 if listing
3242 else " No documents are stored."
3243 )
3244 return msg
3246 kb, best = hits[0]
3247 doc = await documents_service.get_document_text(
3248 str(kb["id"]), best, max_chars=_READABLE_CHARS
3249 )
3250 where, body = _document_part(
3251 doc.text,
3252 offset,
3253 document=best.display_name,
3254 truncated=doc.truncated,
3255 tool=READ_DOCUMENT_TOOL,
3256 )
3257 header = f"# {best.display_name}"
3258 if best.display_name.lower() != document.strip().lower():
3259 header += f" (matched from '{document.strip()}')"
3260 meta = [f"knowledge base: {kb.get('name', kb['id'])}"]
3261 if best.folder_path:
3262 meta.append(f"folder: {best.folder_path}/")
3263 if best.max_page:
3264 meta.append(f"pages: {best.max_page}")
3265 if doc.chunk_count:
3266 meta.append(f"chunks: {doc.chunk_count}")
3267 if where:
3268 meta.append(where)
3269 header += "\n" + " · ".join(meta)
3270 if doc.note:
3271 header += f"\nNote: {doc.note}"
3272 # The id the answer cites the document by (``util/source_registry``).
3273 entry: Any = best.display_name
3274 registry = source_registry.current()
3275 if registry is not None:
3276 sid = registry.cite(
3277 {
3278 "tool": READ_DOCUMENT_TOOL,
3279 "source": best.display_name,
3280 "title": best.display_name,
3281 "kb_id": str(kb["id"]),
3282 "kb_name": str(kb.get("name", kb["id"])),
3283 "document_id": str(getattr(best, "document_id", "") or ""),
3284 }
3285 )
3286 header = f"Cite as: [{sid}]\n{header}"
3287 entry = {"source": best.display_name, "citation_id": sid}
3288 marker = _FILES_SOURCES_MARKER + json.dumps([entry])
3289 if not doc.text:
3290 return header + marker
3291 return f"{header}\n\n{body}" + marker
3293 tools.append(
3294 StructuredTool.from_function(
3295 coroutine=_read,
3296 name=READ_DOCUMENT_TOOL,
3297 description=(
3298 "Read one stored document by name (exact or approximate), a part "
3299 f"at a time: up to {READ_PART_CHARS:,} characters from offset, "
3300 "ending with where the next part begins. Works even before the "
3301 "file is indexed for search. Use when the user names a file, or "
3302 "when search results are thin and the answer is likely in a "
3303 "specific document."
3304 ),
3305 args_schema=_ReadInput,
3306 )
3307 )
3309 class _ListInput(BaseModel):
3310 knowledge_base: str = Field(
3311 default="",
3312 description=(
3313 "Optional. List only this knowledge base"
3314 + (f" — one of: {v_choices}" if not single_vector else "")
3315 + ". Leave empty to list all."
3316 ),
3317 )
3319 async def _list(knowledge_base: str = "") -> str:
3320 from app.knowledge import documents as documents_service
3322 selected = _select_vector(knowledge_base)
3323 if isinstance(selected, str):
3324 return selected
3325 out: list[str] = []
3326 for kb in selected:
3327 docs = await documents_service.list_documents(
3328 str(kb["id"]), force=True, manifest=kb.get("documents")
3329 )
3330 name = kb.get("name", kb["id"])
3331 if not docs:
3332 out.append(f"Knowledge base '{name}': no documents stored.")
3333 continue
3334 out.append(
3335 f"Knowledge base '{name}' ({len(docs)} document{'s' if len(docs) != 1 else ''}):"
3336 )
3337 out += [f"- {d.describe()}" for d in docs]
3338 return "\n".join(out)
3340 tools.append(
3341 StructuredTool.from_function(
3342 coroutine=_list,
3343 name=LIST_DOCUMENTS_TOOL,
3344 description=(
3345 "List the documents stored in the attached knowledge base(s) with "
3346 "folder, page/chunk counts and indexing status. Use to discover "
3347 f"exact file names before {READ_DOCUMENT_TOOL}."
3348 ),
3349 args_schema=_ListInput,
3350 )
3351 )
3353 if graph_kbs:
3354 g_choices = _kb_choices(graph_kbs)
3355 single_graph = len(graph_kbs) == 1
3357 class _ExploreInput(BaseModel):
3358 entity: str = Field(
3359 description=(
3360 "An exact entity name from the graph (e.g. 'Alice Smith') OR an "
3361 "entity type label to list all entities of that type (e.g. "
3362 "'Person'). Not a sentence or question."
3363 )
3364 )
3365 knowledge_base: str = Field(
3366 default="",
3367 description=(
3368 "Optional. Restrict to one graph"
3369 + (f" — one of: {g_choices}" if not single_graph else "")
3370 + ". Leave empty to query all graphs."
3371 ),
3372 )
3373 depth: int = Field(
3374 default=2, ge=1, le=4, description="Relationship hops to traverse"
3375 )
3377 async def _explore(
3378 entity: str, knowledge_base: str = "", depth: int = 2
3379 ) -> str:
3380 from app.util import neo4j_client
3382 if knowledge_base.strip() and not single_graph:
3383 kb = _resolve_kb(knowledge_base, graph_kbs)
3384 if kb is None:
3385 return f"Unknown knowledge graph '{knowledge_base}'. Choose one of: {g_choices}."
3386 selected = [kb]
3387 else:
3388 selected = graph_kbs
3389 sections: list[str] = []
3390 sources: list[dict[str, str]] = []
3391 for kb in selected:
3392 kb_depth = int((kb.get("config") or {}).get("depth", depth))
3393 body = await neo4j_client.query_and_format(
3394 str(kb["id"]), entity, depth=kb_depth, limit=10
3395 )
3396 # One trailer for the whole result, as search_knowledge's.
3397 body, found = source_trailers.split(body, source_trailers.GRAPH)
3398 name = str(kb.get("name", kb["id"]))
3399 # One id for what this graph says of the entity
3400 # (``util/source_registry``).
3401 registry = source_registry.current()
3402 sid = (
3403 registry.cite(
3404 {
3405 "tool": EXPLORE_GRAPH_TOOL,
3406 "source": f"Entity:{entity}",
3407 "title": f"{entity} ({name})",
3408 "kb_id": str(kb["id"]),
3409 "kb_name": name,
3410 }
3411 )
3412 if registry is not None and found
3413 else ""
3414 )
3415 sources += [
3416 {
3417 "source": s,
3418 "kb_name": name,
3419 **({"citation_id": sid} if sid else {}),
3420 }
3421 for s in found
3422 if isinstance(s, str) and s
3423 ]
3424 cite = f"Cite as: [{sid}]\n" if sid else ""
3425 label = f"### {name}\n" if len(selected) > 1 else ""
3426 sections.append(label + cite + body)
3427 return source_trailers.append(
3428 "\n\n".join(sections), source_trailers.GRAPH, sources
3429 )
3431 tools.append(
3432 StructuredTool.from_function(
3433 coroutine=_explore,
3434 name=EXPLORE_GRAPH_TOOL,
3435 description=(
3436 f"Explore the attached knowledge graph(s) ({g_choices}): find an "
3437 "entity by exact name or list a type, and return its properties "
3438 "and relationships up to `depth` hops."
3439 ),
3440 args_schema=_ExploreInput,
3441 )
3442 )
3444 return [platform_owned(tool) for tool in tools]