Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions agentic_security/http_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,22 @@ async def verify(self) -> httpx.Response:
def model_name(self) -> str:
"""Extract the model name from the request body (JSON).

Returns the value of the 'model' field if present, otherwise 'unknown'.
Returns the value of the 'model' field if it is a non-empty string,
otherwise 'unknown'. A body that is valid JSON but not an object (a
list, a string, ``null``), or a 'model' that is not a string, also
gives 'unknown' instead of raising or leaking a non-string value into
cost accounting.
"""
try:
body_json = json.loads(self.body)
return body_json.get("model", "unknown")
except json.JSONDecodeError, TypeError:
return "unknown"
if not isinstance(body_json, dict):
return "unknown"
model = body_json.get("model")
if isinstance(model, str) and model:
return model
return "unknown"

@property
def modality(self) -> Modality:
Expand Down
39 changes: 39 additions & 0 deletions tests/unit/test_model_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import pytest

from agentic_security.http_spec import LLMSpec
from agentic_security.probe_actor.cost_module import calculate_cost


def make_spec(body: str) -> LLMSpec:
return LLMSpec(method="POST", url="http://example.com/v1", headers={}, body=body)


@pytest.mark.parametrize(
"body, expected",
[
('{"model": "gpt-4o", "prompt": "<<PROMPT>>"}', "gpt-4o"),
('{"prompt": "hi"}', "unknown"),
("not json at all", "unknown"),
("", "unknown"),
# Valid JSON that is not an object.
("[1, 2, 3]", "unknown"),
('"just a string"', "unknown"),
("null", "unknown"),
("42", "unknown"),
# A "model" field that is not a usable name.
('{"model": null}', "unknown"),
('{"model": ""}', "unknown"),
('{"model": 5}', "unknown"),
('{"model": ["a", "b"]}', "unknown"),
('{"model": {"name": "x"}}', "unknown"),
],
)
def test_model_name(body, expected):
assert make_spec(body).model_name == expected


def test_model_name_is_safe_for_cost_calculation():
# An unhashable "model" value used to reach `model not in PRICING`
# and raise TypeError.
spec = make_spec('{"model": ["a"]}')
assert calculate_cost(1000, spec.model_name) is None
Loading