Coverage for src/lilbee/server/chat_dispatch/tool_args.py: 100%

11 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-08-14 11:46 +0000

1"""Tool-arguments parsing shared by the route layer and the dispatcher.""" 

2 

3from __future__ import annotations 

4 

5import json 

6from typing import Any 

7 

8 

9def parse_tool_arguments(raw: str) -> dict[str, Any]: 

10 """Turn an OpenAI tool-call ``arguments`` JSON string into a dict. 

11 

12 Falls back to ``{"_raw": raw}`` when the model produces malformed JSON or 

13 a non-object value, so the canonical layer holds invariants the route 

14 layer would otherwise have to defend. 

15 """ 

16 if not raw.strip(): 

17 # Whitespace-only counts as empty: json.loads would otherwise turn it 

18 # into {"_raw": " "} while "" yields {}. 

19 return {} 

20 try: 

21 parsed = json.loads(raw) 

22 except ValueError: 

23 # JSONDecodeError only: raw is a str, so json.loads cannot raise 

24 # TypeError here, and catching it widened this to hide real bugs. 

25 return {"_raw": raw} 

26 return parsed if isinstance(parsed, dict) else {"_raw": raw}