Coverage for app / agents / written_calls.py: 97%

63 statements  

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

1"""A tool call written out as text, in place of the call. 

2 

3A model sometimes answers with a tool call's arguments as its reply — a 

4JSON object shaped exactly like a tool's input — instead of making the call. 

5CHAINR Bot on gpt-oss did it with ``render_document`` on a revision: the 

6person was sent the document's arguments as JSON, the image links in them 

7unrendered, and the document was never made. Two things invite it: a final 

8call with tools unbound (the tool loop's cap), where langchain-aws shows the 

9model its earlier calls as ``[Called <tool> with parameters: {…}]`` text; 

10and earlier calls quoted in the request (``<prior_tool_calls>``). 

11 

12:func:`written_tool_call` recognises one; the tool loop sends it back once 

13(``BaseAgent.run_with_tools``). A reply that is JSON and matches no bound 

14tool's arguments is an answer, and is left alone — as is any reply when the 

15request asked for JSON, which the caller says. 

16""" 

17 

18from __future__ import annotations 

19 

20import re 

21from collections.abc import Sequence 

22from typing import Any 

23 

24from langchain_core.utils.function_calling import convert_to_openai_tool 

25 

26from app.util import safe_json 

27 

28#: A reply that is one JSON fence and nothing else. 

29_FENCED = re.compile(r"^```(?:json)?[ \t]*\n(.*)\n```$", re.DOTALL) 

30#: How langchain-aws writes a tool call into text when no tools are bound. 

31_CALLED = re.compile(r"^\[Called ([\w.-]+) with parameters: (\{.*\})\]$", re.DOTALL) 

32 

33#: The tool loop's message when a reply was a call written out as text and 

34#: the tools are still there. 

35SEND_BACK = ( 

36 "Your reply was a {tool} call written out as text, so nothing was done " 

37 "and the person would see only its arguments. Make the call with the tool " 

38 "itself, or, if you no longer need it, write your answer to the person in " 

39 "prose." 

40) 

41 

42#: The last call's message once the tool loop's rounds are spent. 

43TOOLS_SPENT = ( 

44 "You have reached the maximum number of tool calls, and tools are no " 

45 "longer available. Using the results gathered so far, write your final " 

46 "answer to the person in prose. Do not write out a tool call or its " 

47 "arguments." 

48) 

49 

50#: When that last reply was still a call written out as text. 

51TOOLS_GONE = ( 

52 "That reply was a {tool} call written out as text, and tools are no longer " 

53 "available, so it cannot run. Write your final answer to the person in " 

54 "prose, using the results gathered so far." 

55) 

56 

57 

58#: When a reply had no answer in it (:func:`holds_no_answer`). 

59NO_ANSWER = ( 

60 "That reply had no answer in it, only punctuation or notes in brackets. " 

61 "Write your answer to the person in prose, using the results gathered so " 

62 "far." 

63) 

64 

65#: When a reply made tool calls whose arguments were not a JSON object. 

66MALFORMED_CALLS = ( 

67 "Your {tools} call{plural} could not run: the arguments were not a JSON " 

68 "object. Call {it} again with valid arguments if you still need {it}, or " 

69 "write your answer to the person." 

70) 

71 

72 

73def without_invalid_calls(response: Any) -> tuple[Any, list[str]]: 

74 """``response`` with the tool calls whose arguments did not parse taken 

75 out — their content blocks and ``invalid_tool_calls`` — and their tools' 

76 names. Sent back as they were, one such call made Bedrock refuse the next 

77 request ("toolUse.input is invalid"), and the turn failed mid-revision.""" 

78 invalid = list(getattr(response, "invalid_tool_calls", None) or []) 

79 if not invalid: 

80 return response, [] 

81 ids = {str(call.get("id")) for call in invalid if call.get("id")} 

82 content = response.content 

83 if isinstance(content, list): 

84 content = [ 

85 block 

86 for block in content 

87 if not ( 

88 isinstance(block, dict) 

89 and block.get("type") in ("tool_use", "tool_call", "function_call") 

90 and str(block.get("id")) in ids 

91 ) 

92 ] 

93 names = [str(call.get("name") or "tool") for call in invalid] 

94 return ( 

95 response.model_copy(update={"content": content, "invalid_tool_calls": []}), 

96 names, 

97 ) 

98 

99 

100def malformed_note(names: Sequence[str]) -> str: 

101 """What the model is told of the calls :func:`without_invalid_calls` took 

102 out.""" 

103 unique = list(dict.fromkeys(names)) 

104 many = len(names) > 1 

105 return MALFORMED_CALLS.format( 

106 tools=", ".join(unique), 

107 plural="s" if many else "", 

108 it="them" if many else "it", 

109 ) 

110 

111 

112#: A bracketed note: ``[Applied framework: …]``, a citation marker. 

113_BRACKETED = re.compile(r"\[[^\]\n]*\]") 

114#: A letter, in any script. 

115_LETTER = re.compile(r"[^\W\d_]") 

116 

117 

118def holds_no_answer(text: str) -> bool: 

119 """Whether ``text`` has no word outside its bracketed notes: a reply of 

120 ``.`` and ``[Applied framework: …]`` went to the quality check as an 

121 answer. A short answer ("Yes.") has words, and is one.""" 

122 body = _BRACKETED.sub(" ", text or "") 

123 return _LETTER.search(body) is None 

124 

125 

126def _arguments(tool: Any) -> tuple[set[str], set[str]]: 

127 """A tool's argument names and the required ones.""" 

128 try: 

129 params = convert_to_openai_tool(tool)["function"].get("parameters") or {} 

130 except Exception: # noqa: BLE001 — a tool whose schema cannot be read takes no part 

131 return set(), set() 

132 return set(params.get("properties") or {}), set(params.get("required") or []) 

133 

134 

135def written_tool_call(text: str, tools: Sequence[Any]) -> str | None: 

136 """The name of the bound tool ``text`` is a call to, written out — the 

137 whole reply being that tool's arguments as a JSON object (fenced or not), 

138 or langchain-aws's ``[Called <tool> with parameters: {…}]`` — else None. 

139 

140 Arguments match a tool when every key is one of its arguments and every 

141 argument it requires is there. 

142 """ 

143 body = (text or "").strip() 

144 if not body or not tools: 

145 return None 

146 called = _CALLED.match(body) 

147 if called: 

148 names = {t.name for t in tools} 

149 return called.group(1) if called.group(1) in names else None 

150 fenced = _FENCED.match(body) 

151 if fenced: 

152 body = fenced.group(1).strip() 

153 if not body.startswith("{"): 

154 return None 

155 try: 

156 args = safe_json.loads_exact(body) 

157 except ValueError: 

158 return None 

159 if not isinstance(args, dict) or not args: 

160 return None 

161 keys = set(args) 

162 for tool in tools: 

163 properties, required = _arguments(tool) 

164 if properties and keys <= properties and required <= keys: 

165 return tool.name 

166 return None