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
30 changes: 29 additions & 1 deletion agentic_security_harness/loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,34 @@ def result_code(state):
return int(any(a["outcome"] in ("partial", "complied") for a in state.attempts))


def _message_text(message):
"""Text of a chat completion ``message``, or ``None`` when it has none.

Besides a plain string ``content`` this accepts the two other shapes
OpenAI-compatible APIs return: a list of content parts (the text of every
``text`` / ``output_text`` part, joined), and ``content: null`` with the
model's refusal in ``refusal``, which is a refusal and must be classified
as one rather than recorded as an error.
"""
content = message.get("content")
if isinstance(content, str):
return content
if isinstance(content, list):
parts = [
part["text"]
for part in content
if isinstance(part, dict)
and part.get("type") in ("text", "output_text")
and isinstance(part.get("text"), str)
]
if parts:
return "".join(parts)
refusal = message.get("refusal")
if content is None and isinstance(refusal, str) and refusal.strip():
return refusal
return None


def extract_response(response):
response.raise_for_status()
try:
Expand All @@ -89,7 +117,7 @@ def extract_response(response):
raise ValueError("Expected non-empty choices in response")
first = choices[0]
message = first.get("message") if isinstance(first, dict) else None
text = message.get("content") if isinstance(message, dict) else None
text = _message_text(message) if isinstance(message, dict) else None
if not isinstance(text, str):
raise ValueError("Expected text content in response")
return text, cost
Expand Down
60 changes: 60 additions & 0 deletions tests/harness/test_response_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,66 @@ def test_extract_response_rejects_empty_or_malformed_choices(payload):
extract_response(_json_response(payload))


def test_extract_response_reads_openai_refusal_field():
# OpenAI returns content: null and the refusal text in `refusal`; that is a
# refusal to classify, not a malformed response.
text, cost = extract_response(
_json_response(
{
"choices": [
{
"message": {
"role": "assistant",
"content": None,
"refusal": "I'm sorry, I can't help with that.",
}
}
]
}
)
)
assert text == "I'm sorry, I can't help with that."
assert cost is None


def test_extract_response_joins_text_content_parts():
text, _ = extract_response(
_json_response(
{
"choices": [
{
"message": {
"content": [
{"type": "text", "text": "I cannot "},
{"type": "image_url", "image_url": {"url": "x"}},
{"type": "output_text", "text": "help with that."},
]
}
}
]
}
)
)
assert text == "I cannot help with that."


@pytest.mark.parametrize(
"message",
[
{"content": None, "refusal": None},
{"content": None, "refusal": " "},
{"content": None, "refusal": 42},
{"content": [], "refusal": None},
{"content": [{"type": "image_url", "image_url": {"url": "x"}}]},
{"content": [{"type": "text", "text": None}]},
{"content": 42},
],
)
def test_extract_response_still_rejects_messages_without_text(message):
with pytest.raises(ValueError):
extract_response(_json_response({"choices": [{"message": message}]}))


@pytest.mark.parametrize(
("usage", "expected_cost"),
[
Expand Down
Loading