Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_ai_stop_reasons.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
test_ai_stop_reasons.py · 5.9 KB · 139 lines
1"""stop_reason is read before content, and each unusual stop says so.
2
3- refusal: the content is not an answer; the user reads that the model
4 declined, with the provider's category and explanation.
5- max_tokens: the partial text is kept and marked as cut off, and a tool
6 call in the same response is NOT run -- its input may be unfinished.
7- pause_turn: the paused content goes back as-is and the turn resumes; if
8 the round limit arrives first the user is told so.
9"""
10
11import json
12
13import object_ai
14import object_mcp
15import object_records
16from ai_fakes import (
17 anthropic_message,
18 chat_server,
19 install_fake_transport,
20 text_block,
21 tool_block,
22)
23from test_object_server import request
24
25
26def _run(responses, *, dispatched=None, sent=None, **kwargs):
27 def send_http(url, headers, body):
28 if sent is not None:
29 sent.append(json.loads(body))
30 return responses.pop(0)
31
32 def dispatch_tool(name, arguments):
33 if dispatched is not None:
34 dispatched.append((name, arguments))
35 return {"http_status": 200, "response": {"ok": True}}
36
37 kwargs.setdefault("tools", object_ai.mcp_tools_as_provider_tools(
38 ["global_search"], object_mcp.TOOLS, service="anthropic"))
39 return object_ai.run_chat(send_http=send_http, dispatch_tool=dispatch_tool,
40 service="anthropic", model="claude-haiku-5-5", key="sk-test",
41 message="hi", **kwargs)
42
43
44def test_refusal_names_category_and_explanation_and_ignores_content():
45 dispatched = []
46 result = _run([anthropic_message(
47 [text_block("Sure, here is"), tool_block("global_search", {"query": "x"})],
48 stop_reason="refusal",
49 stop_details={"category": "cyber", "explanation": "This looks like intrusion work."},
50 )], dispatched=dispatched)
51 assert result["stop_reason"] == "refusal"
52 assert result["refusal"] == {"category": "cyber",
53 "explanation": "This looks like intrusion work."}
54 assert result["reply"] == ("The model declined to answer this request (cyber): "
55 "This looks like intrusion work.")
56 assert "Sure, here is" not in result["reply"]
57 assert dispatched == []
58
59
60def test_refusal_without_details_still_reads_as_a_refusal():
61 result = _run([anthropic_message([], stop_reason="refusal")])
62 assert result["reply"] == "The model declined to answer this request."
63 assert result["refusal"] == {"category": None, "explanation": None}
64
65
66def test_max_tokens_keeps_the_partial_text_marks_it_and_runs_no_tool():
67 dispatched = []
68 result = _run([anthropic_message(
69 [text_block("Here is the first half"), tool_block("global_search", {"query": "x"})],
70 stop_reason="max_tokens",
71 )], dispatched=dispatched, max_tokens=4096)
72 assert result["stop_reason"] == "max_tokens"
73 assert result["cut_off"] is True
74 assert result["reply"].startswith("Here is the first half\n\n(The answer was cut off")
75 assert "4096-token" in result["reply"]
76 assert dispatched == []
77 assert result["rounds"] == 1
78
79
80def test_openai_length_is_treated_as_max_tokens():
81 def send_http(url, headers, body):
82 return 200, json.dumps({"choices": [{"finish_reason": "length",
83 "message": {"content": "partial"}}]}).encode()
84
85 result = object_ai.run_chat(send_http=send_http, dispatch_tool=lambda n, a: {},
86 service="openai", model="gpt-5-mini", key="sk-test",
87 message="hi")
88 assert result["stop_reason"] == "max_tokens"
89 assert result["reply"].startswith("partial\n\n(The answer was cut off")
90
91
92def test_pause_turn_resends_the_paused_content_and_continues():
93 paused = [text_block("Working on it...")]
94 sent = []
95 dispatched = []
96 result = _run([
97 anthropic_message(paused, stop_reason="pause_turn"),
98 anthropic_message([tool_block("global_search", {"query": "x"})], stop_reason="tool_use"),
99 anthropic_message([text_block("Done.")]),
100 ], sent=sent, dispatched=dispatched)
101 assert result["reply"] == "Done."
102 assert result["rounds"] == 3
103 assert result["stop_reason"] == "end_turn"
104 assert dispatched == [("global_search", {"query": "x"})]
105 # The second request carries the paused content back verbatim, and no
106 # new user message was invented to follow it.
107 assert sent[1]["messages"][-1] == {"role": "assistant", "content": paused}
108
109
110def test_pause_turn_at_the_round_limit_tells_the_user():
111 result = _run([anthropic_message([text_block("Partway")], stop_reason="pause_turn")],
112 max_rounds=1)
113 assert result["truncated"] is True
114 assert result["stop_reason"] == "pause_turn"
115 assert result["reply"].startswith("Partway\n\n(The model paused a long-running turn")
116
117
118def test_normal_replies_report_end_turn():
119 result = _run([anthropic_message([text_block("hello")])])
120 assert result["stop_reason"] == "end_turn"
121 assert "refusal" not in result and "cut_off" not in result
122
123
124def test_endpoint_returns_and_records_a_refusal_as_a_reply(tmp_path, monkeypatch):
125 data_dir, headers = chat_server(tmp_path, monkeypatch)
126 install_fake_transport(monkeypatch, [anthropic_message(
127 [], stop_reason="refusal",
128 stop_details={"category": "harm", "explanation": "Not something I can help with."},
129 usage={"input_tokens": 12, "output_tokens": 3},
130 )])
131 status, _, chat = request("/api/ai/chat", method="POST", headers=headers,
132 body=json.dumps({"message": "hi"}).encode())
133 assert status == 200, chat
134 assert chat["stop_reason"] == "refusal"
135 assert chat["refusal"]["category"] == "harm"
136 assert chat["reply"].startswith("The model declined")
137 # Tokens of a refused turn are still spent and still recorded.
138 [row] = object_records.read_collection_records("ai_usage", base_dir=data_dir)
139 assert row["tokens_in"] == "12"