Coverage for app / tools / wire.py: 98%

62 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""What a model is shown of the tools it may call. 

2 

3A tool is bound by its argument schema. On a route that holds tool arguments 

4to their schema (``ModelCapabilities.strict_tools``: Bedrock's structured 

5outputs — Claude 4.5 / 4.6, gpt-oss, Qwen3 235B), with 

6``STRICT_BUILTIN_TOOLS`` on, a tool whose schema CHAIN-R wrote is bound as a 

7strict spec: ``strict_tool_schema`` of its arguments with ``strict: True``, 

8which langchain-aws carries to Converse's ``toolSpec.strict``. The model's 

9call is then decoded to that schema: it names a tool that exists and fills 

10its arguments as declared, rather than being trusted to. 

11 

12**Which tools.** Those the factory that made them marks (``platform_owned``): 

13every built-in, through ``resolve_tool`` and ``general_tools``; the knowledge 

14tools; and a scripted tool standing in for one, so an evaluation sends the 

15request live traffic sends. Never a webhook tool (a free-form payload), a 

16scripted tool standing in for none (any arguments), or an MCP server's (a 

17schema someone else wrote, which a strict mode may refuse). A platform tool 

18whose schema strict decoding cannot express stays as it is, and is named in 

19``NOT_STRICT`` with why. 

20 

21**Only the model's view changes.** The tool loop still runs the tool itself 

22(``ToolNode`` over the tools, not these specs), and its pydantic arguments 

23still enforce what a strict schema cannot carry — bounds, lengths — which 

24the spec states in words instead. 

25 

26**A refusal is remembered.** A route that refuses the strict request 

27(``model_errors.refused_schema``) is bound as before from then on, for the 

28life of the process (``provider_refusals``). 

29 

30Off by default: Bedrock compiles a grammar for each new tool set before 

31answering ("up to a few minutes", then cached 24 hours), and every agent's 

32knowledge tools make its set its own. ``app/diagnostics/structured_probe.py`` 

33measures what that costs a first turn. 

34""" 

35 

36from __future__ import annotations 

37 

38from functools import lru_cache 

39from typing import Any 

40 

41from langchain_core.tools import BaseTool 

42from pydantic import BaseModel 

43 

44from app.util.logger import get_logger 

45from app.util.model_output import SchemaNotStrict, bedrock_problems, strict_tool_schema 

46 

47logger = get_logger(__name__) 

48 

49#: The tool metadata key that says who wrote a tool's argument schema. 

50SCHEMA_OWNER = "schema_owner" 

51#: ``SCHEMA_OWNER``'s value for a schema CHAIN-R wrote. 

52PLATFORM = "platform" 

53 

54#: Built-in tools whose schema strict decoding cannot express, each with why. 

55#: They are bound as they always were. A test fails when one becomes 

56#: expressible, and when a built-in is neither expressible nor named here. 

57NOT_STRICT: dict[str, str] = { 

58 "render_chart": "its data rows are free-form objects keyed by the chart's series", 

59 "render_map": "its overlay is a GeoJSON object of any shape", 

60} 

61 

62 

63def platform_owned(tool: BaseTool) -> BaseTool: 

64 """Mark ``tool`` as one whose argument schema CHAIN-R wrote, which makes 

65 it eligible to be bound strictly. Returns the tool.""" 

66 tool.metadata = {**(tool.metadata or {}), SCHEMA_OWNER: PLATFORM} 

67 return tool 

68 

69 

70def is_platform_owned(tool: Any) -> bool: 

71 metadata = getattr(tool, "metadata", None) or {} 

72 return metadata.get(SCHEMA_OWNER) == PLATFORM 

73 

74 

75@lru_cache(maxsize=512) 

76def strict_parameters(args_schema: type[BaseModel]) -> dict[str, Any] | None: 

77 """The strict input schema for ``args_schema``, or None when strict 

78 decoding cannot express it or Bedrock would refuse it.""" 

79 try: 

80 schema = strict_tool_schema(args_schema) 

81 except SchemaNotStrict: 

82 return None 

83 return None if bedrock_problems(schema) else schema 

84 

85 

86def strict_spec(tool: Any) -> dict[str, Any] | None: 

87 """``tool`` as an OpenAI-format function spec marked ``strict``, or None 

88 when it is not the platform's or its schema cannot be held strictly.""" 

89 if not is_platform_owned(tool): 

90 return None 

91 args_schema = getattr(tool, "args_schema", None) 

92 if not (isinstance(args_schema, type) and issubclass(args_schema, BaseModel)): 

93 return None 

94 parameters = strict_parameters(args_schema) 

95 if parameters is None: 

96 return None 

97 return { 

98 "type": "function", 

99 "function": { 

100 "name": tool.name, 

101 "description": tool.description or tool.name, 

102 "parameters": parameters, 

103 "strict": True, 

104 }, 

105 } 

106 

107 

108def strict_tools_on(llm: Any) -> bool: 

109 """Whether tools bound to ``llm`` are bound strictly: the switch is on, 

110 its route holds tool arguments to their schema, and it has not refused 

111 to.""" 

112 from app.common.settings import get_settings 

113 from app.services import provider_refusals 

114 from app.services.model_capabilities import capabilities_for 

115 from app.services.provider_refusals import Feature 

116 from app.services.structured_output import provider_model 

117 

118 if not get_settings().STRICT_BUILTIN_TOOLS: 

119 return False 

120 provider, model = provider_model(llm) 

121 if not provider: 

122 return False 

123 return capabilities_for(provider, model).strict_tools and not ( 

124 provider_refusals.refused(provider, model, Feature.STRICT_TOOLS) 

125 ) 

126 

127 

128def for_binding(tools: list[Any], llm: Any) -> list[Any]: 

129 """What to pass ``llm.bind_tools`` for ``tools``: each platform tool's 

130 strict spec where ``llm`` takes one, every other tool as it is.""" 

131 if not strict_tools_on(llm): 

132 return list(tools) 

133 return [strict_spec(tool) or tool for tool in tools] 

134 

135 

136def is_strict(bound: list[Any]) -> bool: 

137 """Whether a list from ``for_binding`` holds any strict spec.""" 

138 return any( 

139 isinstance(spec, dict) and (spec.get("function") or {}).get("strict") 

140 for spec in bound 

141 ) 

142 

143 

144def refused(llm: Any, bound: list[Any], exc: BaseException) -> bool: 

145 """Whether ``exc`` is ``llm``'s route refusing strict tools it was sent 

146 (``bound`` from ``for_binding``). If so, remembered: the caller binds 

147 the tools as they are, now and from then on.""" 

148 from app.services import model_errors, provider_refusals 

149 from app.services.provider_refusals import Feature 

150 from app.services.structured_output import provider_model 

151 

152 if not is_strict(bound) or not model_errors.refused_schema(exc): 

153 return False 

154 provider, model = provider_model(llm) 

155 provider_refusals.remember(provider, model, Feature.STRICT_TOOLS) 

156 logger.warning( 

157 "[tools] %s/%s refused strict tools (%s) — binding them as they are " 

158 "from now on", 

159 provider, 

160 model, 

161 model_errors.describe(exc), 

162 ) 

163 return True