| 1 |
"""How a tool runner with `run_tools_eagerly` runs tool calls. `setup()` turns the option on. |
| 2 |
|
| 3 |
Most tests here assert a timeline: what the caller saw, in order, and where each tool started. |
| 4 |
|
| 5 |
"a: content_block_stop" the caller got this stream event |
| 6 |
"lookup(a) STARTS" the runner called the tool |
| 7 |
"loop body ends" the caller finished its `for stream in runner` body |
| 8 |
|
| 9 |
Every reply is made of `call("a")`, which is the model calling `lookup(key="a")` with the id `toolu_a`, and |
| 10 |
`text("...")`. Every test runs on the sync and on the async runner: `replies_of()`, `events_of()` and `settled()` |
| 11 |
let one test body drive both. The first five tests are the behavior in short. |
| 12 |
""" |
| 13 |
|
| 14 |
from __future__ import annotations |
| 15 |
|
| 16 |
import os |
| 17 |
import json |
| 18 |
import inspect |
| 19 |
from typing import Any, TypeVar, NamedTuple |
| 20 |
from collections.abc import Callable, Iterator, Awaitable, AsyncIterator |
| 21 |
from typing_extensions import override |
| 22 |
|
| 23 |
import httpx2 |
| 24 |
import pytest |
| 25 |
from respx import MockRouter |
| 26 |
|
| 27 |
from anthropic import Anthropic, AsyncAnthropic, beta_tool, beta_async_tool |
| 28 |
from anthropic._compat import PYDANTIC_V1 |
| 29 |
from anthropic.lib.tools import ToolError |
| 30 |
from anthropic.types.beta import BetaMessageParam |
| 31 |
from anthropic.lib.streaming import BetaMessageStream, BetaAsyncMessageStream |
| 32 |
|
| 33 |
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") |
| 34 |
|
| 35 |
pytestmark = [ |
| 36 |
pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1"), |
| 37 |
pytest.mark.respx(base_url=base_url), |
| 38 |
] |
| 39 |
|
| 40 |
_T = TypeVar("_T") |
| 41 |
|
| 42 |
|
| 43 |
async def test_runs_each_tool_once_the_model_has_moved_on_from_its_call(setup: SetupFactory) -> None: |
| 44 |
test = setup([reply(call("a"), call("b")), done()]) |
| 45 |
|
| 46 |
async for stream in replies_of(test.runner): |
| 47 |
async for event in events_of(stream): |
| 48 |
test.see(event) |
| 49 |
test.timeline.append("loop body ends") |
| 50 |
|
| 51 |
assert first_reply(test.timeline) == [ |
| 52 |
"message_start", |
| 53 |
"a: content_block_start", |
| 54 |
"a: content_block_delta", |
| 55 |
"input_json", |
| 56 |
"a: content_block_stop", |
| 57 |
"b: content_block_start", # the model has moved on from a |
| 58 |
"lookup(a) STARTS", |
| 59 |
"b: content_block_delta", |
| 60 |
"input_json", |
| 61 |
"b: content_block_stop", |
| 62 |
"message_delta (tool_use)", # the model has moved on from b |
| 63 |
"lookup(b) STARTS", |
| 64 |
"message_stop", |
| 65 |
"loop body ends", |
| 66 |
] |
| 67 |
|
| 68 |
|
| 69 |
async def test_runs_every_tool_after_the_loop_body_when_not_streaming_as_before(setup: SetupFactory) -> None: |
| 70 |
test = setup([reply(call("a"), call("b")), done()], stream=False) |
| 71 |
|
| 72 |
async for _message in replies_of(test.runner): |
| 73 |
test.timeline.append("loop body ends") |
| 74 |
|
| 75 |
assert first_reply(test.timeline) == ["loop body ends", "lookup(a) STARTS", "lookup(b) STARTS"] |
| 76 |
|
| 77 |
|
| 78 |
async def test_holds_a_call_that_the_caller_defers_until_the_loop_body_ends(setup: SetupFactory) -> None: |
| 79 |
test = setup([reply(call("a"), call("b"), call("c")), done()]) |
| 80 |
|
| 81 |
async for stream in replies_of(test.runner): |
| 82 |
async for event in events_of(stream): |
| 83 |
test.see(event) |
| 84 |
if event.type == "content_block_stop" and event.content_block.type == "tool_use": |
| 85 |
if event.content_block.id == "toolu_b": |
| 86 |
test.runner.defer_tool_call(event.content_block) |
| 87 |
test.timeline.append("loop body ends") |
| 88 |
|
| 89 |
assert first_reply(test.timeline) == [ |
| 90 |
"message_start", |
| 91 |
"a: content_block_start", |
| 92 |
"a: content_block_delta", |
| 93 |
"input_json", |
| 94 |
"a: content_block_stop", |
| 95 |
"b: content_block_start", |
| 96 |
"lookup(a) STARTS", |
| 97 |
"b: content_block_delta", |
| 98 |
"input_json", |
| 99 |
"b: content_block_stop", # the caller defers b here |
| 100 |
"c: content_block_start", # b would have run after this event |
| 101 |
"c: content_block_delta", |
| 102 |
"input_json", |
| 103 |
"c: content_block_stop", |
| 104 |
"message_delta (tool_use)", |
| 105 |
"lookup(c) STARTS", |
| 106 |
"message_stop", |
| 107 |
"loop body ends", |
| 108 |
"lookup(b) STARTS", |
| 109 |
] |
| 110 |
# The results go back in the model's order, whatever order the calls ran in. |
| 111 |
assert results_sent(test) == [ |
| 112 |
{"type": "tool_result", "tool_use_id": "toolu_a", "content": "value of a"}, |
| 113 |
{"type": "tool_result", "tool_use_id": "toolu_b", "content": "value of b"}, |
| 114 |
{"type": "tool_result", "tool_use_id": "toolu_c", "content": "value of c"}, |
| 115 |
] |
| 116 |
|
| 117 |
|
| 118 |
async def test_lists_the_calls_that_are_being_held_so_that_the_caller_can_decide_about_them( |
| 119 |
setup: SetupFactory, |
| 120 |
) -> None: |
| 121 |
test = setup([reply(call("a"), call("b")), done()]) |
| 122 |
|
| 123 |
async for stream in replies_of(test.runner): |
| 124 |
async for event in events_of(stream): |
| 125 |
if event.type == "content_block_start" and event.content_block.type == "tool_use": |
| 126 |
if event.content_block.id == "toolu_b": |
| 127 |
test.runner.defer_tool_call(event.content_block) |
| 128 |
|
| 129 |
held = test.runner.deferred_tool_calls |
| 130 |
|
| 131 |
assert [tool_use.to_dict() for tool_use in held] == [ |
| 132 |
{"type": "tool_use", "id": "toolu_b", "name": "lookup", "input": {"key": "b"}} |
| 133 |
] |
| 134 |
break # the caller decides against b |
| 135 |
|
| 136 |
assert test.timeline == ["lookup(a) STARTS"] |
| 137 |
|
| 138 |
|
| 139 |
async def test_runs_each_call_once(setup: SetupFactory) -> None: |
| 140 |
test = setup([reply(call("a"), call("b"))]) |
| 141 |
|
| 142 |
async for stream in replies_of(test.runner): |
| 143 |
test.runner.defer_tool_call("toolu_a") |
| 144 |
message = await settled(stream.get_final_message()) |
| 145 |
|
| 146 |
response = await settled(test.runner.generate_tool_call_response()) |
| 147 |
# append_messages() drops the cached response, so the second call answers the reply again. |
| 148 |
test.runner.append_messages(message, response) |
| 149 |
assert await settled(test.runner.generate_tool_call_response()) == response |
| 150 |
break |
| 151 |
|
| 152 |
assert test.timeline == ["lookup(b) STARTS", "lookup(a) STARTS"] |
| 153 |
|
| 154 |
|
| 155 |
# --------------------------------------------------------------------------------------------------------- |
| 156 |
# without `run_tools_eagerly` |
| 157 |
# --------------------------------------------------------------------------------------------------------- |
| 158 |
|
| 159 |
|
| 160 |
async def test_without_the_option_every_tool_runs_after_the_loop_body_as_before(setup: SetupFactory) -> None: |
| 161 |
test = setup([reply(call("a"), call("b")), done()], run_tools_eagerly=False) |
| 162 |
|
| 163 |
async for stream in replies_of(test.runner): |
| 164 |
async for event in events_of(stream): |
| 165 |
test.see(event) |
| 166 |
test.timeline.append("loop body ends") |
| 167 |
|
| 168 |
assert first_reply(test.timeline) == [ |
| 169 |
"message_start", |
| 170 |
"a: content_block_start", |
| 171 |
"a: content_block_delta", |
| 172 |
"input_json", |
| 173 |
"a: content_block_stop", |
| 174 |
"b: content_block_start", |
| 175 |
"b: content_block_delta", |
| 176 |
"input_json", |
| 177 |
"b: content_block_stop", |
| 178 |
"message_delta (tool_use)", |
| 179 |
"message_stop", |
| 180 |
"loop body ends", |
| 181 |
"lookup(a) STARTS", |
| 182 |
"lookup(b) STARTS", |
| 183 |
] |
| 184 |
|
| 185 |
|
| 186 |
async def test_without_the_option_there_is_nothing_to_defer(setup: SetupFactory) -> None: |
| 187 |
test = setup([reply(call("a")), done()], run_tools_eagerly=False) |
| 188 |
|
| 189 |
async for stream in replies_of(test.runner): |
| 190 |
test.runner.defer_tool_call("toolu_a") |
| 191 |
await settled(stream.get_final_message()) |
| 192 |
assert test.runner.deferred_tool_calls == [] |
| 193 |
test.timeline.append("loop body ends") |
| 194 |
|
| 195 |
assert first_reply(test.timeline) == ["loop body ends", "lookup(a) STARTS"] |
| 196 |
|
| 197 |
|
| 198 |
async def test_without_the_option_the_tools_run_again_after_append_messages_as_before(setup: SetupFactory) -> None: |
| 199 |
test = setup([reply(call("a"))], run_tools_eagerly=False) |
| 200 |
|
| 201 |
async for _stream in replies_of(test.runner): |
| 202 |
await settled(test.runner.generate_tool_call_response()) |
| 203 |
test.runner.append_messages({"role": "user", "content": "Go on."}) |
| 204 |
await settled(test.runner.generate_tool_call_response()) |
| 205 |
break |
| 206 |
|
| 207 |
assert test.timeline == ["lookup(a) STARTS", "lookup(a) STARTS"] |
| 208 |
|
| 209 |
|
| 210 |
# --------------------------------------------------------------------------------------------------------- |
| 211 |
# the `run_tools_eagerly` option |
| 212 |
# --------------------------------------------------------------------------------------------------------- |
| 213 |
|
| 214 |
|
| 215 |
async def test_the_option_is_not_sent_to_the_api(setup: SetupFactory) -> None: |
| 216 |
test = setup([reply_ending("compaction", compaction()), reply(call("a")), done()]) |
| 217 |
|
| 218 |
test.runner.compact_before_next_turn() |
| 219 |
await settled(test.runner.until_done()) |
| 220 |
|
| 221 |
assert ["compaction" in request for request in test.requests] == [True, False, False] |
| 222 |
assert ["run_tools_eagerly" in request for request in test.requests] == [False, False, False] |
| 223 |
|
| 224 |
|
| 225 |
async def test_yields_the_stream_that_messages_stream_returns(setup: SetupFactory) -> None: |
| 226 |
test = setup([done()]) |
| 227 |
|
| 228 |
async for stream in replies_of(test.runner): |
| 229 |
assert type(stream) is (BetaMessageStream if test.sync else BetaAsyncMessageStream) |
| 230 |
assert (await settled(stream.get_final_message())).stop_reason == "end_turn" |
| 231 |
|
| 232 |
assert test.requests[0]["stream"] is True |
| 233 |
|
| 234 |
|
| 235 |
@pytest.mark.parametrize("stream", [False, None], ids=["stream=False", "stream left out"]) |
| 236 |
def test_the_option_needs_stream( |
| 237 |
sync: bool, client: Anthropic, async_client: AsyncAnthropic, stream: bool | None |
| 238 |
) -> None: |
| 239 |
tool_runner: Any = (client if sync else async_client).beta.messages.tool_runner |
| 240 |
options = {} if stream is None else {"stream": stream} |
| 241 |
|
| 242 |
with pytest.raises(ValueError, match="`run_tools_eagerly=True` and `stream=False` are mutually exclusive"): |
| 243 |
tool_runner(**PARAMS, tools=[], run_tools_eagerly=True, **options) |
| 244 |
|
| 245 |
tool_runner(**PARAMS, tools=[], run_tools_eagerly=False, **options) |
| 246 |
|
| 247 |
|
| 248 |
# --------------------------------------------------------------------------------------------------------- |
| 249 |
# when a tool call runs |
| 250 |
# --------------------------------------------------------------------------------------------------------- |
| 251 |
|
| 252 |
|
| 253 |
@pytest.mark.parametrize("read", ["events", "text_stream", "get_final_message", "until_done"]) |
| 254 |
async def test_runs_the_calls_while_the_caller_reads_the_stream_however_it_reads_it( |
| 255 |
setup: SetupFactory, read: str |
| 256 |
) -> None: |
| 257 |
test = setup([reply(call("a"), text("Found a."), call("b")), done()]) |
| 258 |
|
| 259 |
async for stream in replies_of(test.runner): |
| 260 |
if read == "events": |
| 261 |
async for _event in events_of(stream): |
| 262 |
pass |
| 263 |
elif read == "text_stream": |
| 264 |
async for _text in events_of(stream.text_stream): |
| 265 |
pass |
| 266 |
elif read == "get_final_message": |
| 267 |
await settled(stream.get_final_message()) |
| 268 |
else: |
| 269 |
await settled(stream.until_done()) |
| 270 |
test.timeline.append("loop body ends") |
| 271 |
|
| 272 |
assert first_reply(test.timeline) == ["lookup(a) STARTS", "lookup(b) STARTS", "loop body ends"] |
| 273 |
|
| 274 |
|
| 275 |
async def test_runs_the_calls_after_the_loop_body_when_the_caller_does_not_read_the_stream( |
| 276 |
setup: SetupFactory, |
| 277 |
) -> None: |
| 278 |
test = setup([reply(call("a"), call("b")), done()]) |
| 279 |
|
| 280 |
async for _stream in replies_of(test.runner): |
| 281 |
test.timeline.append("loop body ends") |
| 282 |
|
| 283 |
assert first_reply(test.timeline) == ["loop body ends", "lookup(a) STARTS", "lookup(b) STARTS"] |
| 284 |
|
| 285 |
|
| 286 |
async def test_runs_the_remaining_calls_after_the_loop_body_when_the_caller_stops_reading_early( |
| 287 |
setup: SetupFactory, |
| 288 |
) -> None: |
| 289 |
test = setup([reply(call("a"), call("b"), call("c")), done()]) |
| 290 |
|
| 291 |
async for stream in replies_of(test.runner): |
| 292 |
async for event in events_of(stream): |
| 293 |
test.see(event) |
| 294 |
if event.type == "content_block_delta" and event.index == 1: |
| 295 |
break |
| 296 |
test.timeline.append("loop body ends") |
| 297 |
|
| 298 |
assert first_reply(test.timeline)[-5:] == [ |
| 299 |
"lookup(a) STARTS", |
| 300 |
"b: content_block_delta", |
| 301 |
"loop body ends", |
| 302 |
"lookup(b) STARTS", |
| 303 |
"lookup(c) STARTS", |
| 304 |
] |
| 305 |
assert [result["tool_use_id"] for result in results_sent(test)] == ["toolu_a", "toolu_b", "toolu_c"] |
| 306 |
|
| 307 |
|
| 308 |
async def test_does_not_wait_for_the_reply_to_end(setup: SetupFactory) -> None: |
| 309 |
test = setup([event_by_event(reply(call("a"), text("Found a."), call("b"))), done()]) |
| 310 |
|
| 311 |
await settled(test.runner.until_done()) |
| 312 |
|
| 313 |
assert first_reply(test.timeline) == [ |
| 314 |
"server sends message_start", |
| 315 |
"server sends a: content_block_start", |
| 316 |
"server sends a: content_block_delta", |
| 317 |
"server sends a: content_block_stop", |
| 318 |
"server sends text: content_block_start", # the model has moved on from a |
| 319 |
"server sends text: content_block_delta", |
| 320 |
"lookup(a) STARTS", |
| 321 |
"server sends text: content_block_stop", |
| 322 |
"server sends b: content_block_start", |
| 323 |
"server sends b: content_block_delta", |
| 324 |
"server sends b: content_block_stop", |
| 325 |
"server sends message_delta (tool_use)", # the model has moved on from b |
| 326 |
"server sends message_stop", |
| 327 |
"lookup(b) STARTS", |
| 328 |
] |
| 329 |
|
| 330 |
|
| 331 |
async def test_runs_no_call_once_reading_the_reply_has_failed(setup: SetupFactory) -> None: |
| 332 |
test = setup([event_by_event(reply(call("a"), call("b")), fails_before="b: content_block_delta")]) |
| 333 |
|
| 334 |
with pytest.raises(httpx2.ReadError): |
| 335 |
async for stream in replies_of(test.runner): |
| 336 |
async for event in events_of(stream): |
| 337 |
test.see(event) |
| 338 |
|
| 339 |
# The model had moved on from a, and the caller was done with the event that showed it. |
| 340 |
assert test.timeline[-3:] == [ |
| 341 |
"server sends b: content_block_start", |
| 342 |
"b: content_block_start", |
| 343 |
"server fails", |
| 344 |
] |
| 345 |
|
| 346 |
|
| 347 |
async def test_runs_the_calls_one_at_a_time(setup: SetupFactory) -> None: |
| 348 |
test = setup([reply(call("a"), call("b")), done()], log_returns=True) |
| 349 |
|
| 350 |
await settled(test.runner.until_done()) |
| 351 |
|
| 352 |
assert first_reply(test.timeline) == [ |
| 353 |
"lookup(a) STARTS", |
| 354 |
"lookup(a) returns", |
| 355 |
"lookup(b) STARTS", |
| 356 |
"lookup(b) returns", |
| 357 |
] |
| 358 |
|
| 359 |
|
| 360 |
async def test_sends_the_error_result_of_a_call_that_failed_while_the_reply_streamed(setup: SetupFactory) -> None: |
| 361 |
def fail(key: str) -> str: |
| 362 |
raise ToolError(f"No value for {key}.") |
| 363 |
|
| 364 |
test = setup([reply(call("a"), text("Looking.")), done()], lookup=fail) |
| 365 |
|
| 366 |
async for stream in replies_of(test.runner): |
| 367 |
await settled(stream.get_final_message()) |
| 368 |
test.timeline.append("loop body ends") |
| 369 |
|
| 370 |
assert first_reply(test.timeline) == ["lookup(a) STARTS", "loop body ends"] |
| 371 |
assert results_sent(test) == [ |
| 372 |
{"type": "tool_result", "tool_use_id": "toolu_a", "content": "No value for a.", "is_error": True} |
| 373 |
] |
| 374 |
|
| 375 |
|
| 376 |
# --------------------------------------------------------------------------------------------------------- |
| 377 |
# defer_tool_call() |
| 378 |
# --------------------------------------------------------------------------------------------------------- |
| 379 |
|
| 380 |
|
| 381 |
@pytest.mark.parametrize("argument", ["the block", "the id"]) |
| 382 |
async def test_defer_tool_call_takes(setup: SetupFactory, argument: str) -> None: |
| 383 |
test = setup([reply(call("a"), call("b")), done()]) |
| 384 |
|
| 385 |
async for stream in replies_of(test.runner): |
| 386 |
async for event in events_of(stream): |
| 387 |
if event.type == "content_block_stop" and event.content_block.type == "tool_use": |
| 388 |
if event.content_block.id == "toolu_a": |
| 389 |
block = event.content_block |
| 390 |
test.runner.defer_tool_call(block if argument == "the block" else block.id) |
| 391 |
test.timeline.append("loop body ends") |
| 392 |
|
| 393 |
assert first_reply(test.timeline) == ["lookup(b) STARTS", "loop body ends", "lookup(a) STARTS"] |
| 394 |
|
| 395 |
|
| 396 |
@pytest.mark.parametrize( |
| 397 |
"at", |
| 398 |
["a: content_block_start", "a: content_block_stop", "b: content_block_start"], |
| 399 |
ids=["when the call starts streaming", "when the call has streamed", "when the model moves on from the call"], |
| 400 |
) |
| 401 |
async def test_holds_a_call_that_is_deferred(setup: SetupFactory, at: str) -> None: |
| 402 |
test = setup([reply(call("a"), call("b")), done()]) |
| 403 |
|
| 404 |
async for stream in replies_of(test.runner): |
| 405 |
async for event in events_of(stream): |
| 406 |
if test.label(event) == at: |
| 407 |
test.runner.defer_tool_call("toolu_a") |
| 408 |
test.timeline.append("loop body ends") |
| 409 |
|
| 410 |
assert first_reply(test.timeline) == ["lookup(b) STARTS", "loop body ends", "lookup(a) STARTS"] |
| 411 |
|
| 412 |
|
| 413 |
async def test_gives_the_timing_from_before_when_the_caller_defers_every_call(setup: SetupFactory) -> None: |
| 414 |
test = setup([reply(call("a"), call("b")), done()]) |
| 415 |
|
| 416 |
async for stream in replies_of(test.runner): |
| 417 |
async for event in events_of(stream): |
| 418 |
test.see(event) |
| 419 |
if event.type == "content_block_start" and event.content_block.type == "tool_use": |
| 420 |
test.runner.defer_tool_call(event.content_block) |
| 421 |
test.timeline.append("loop body ends") |
| 422 |
|
| 423 |
assert first_reply(test.timeline) == [ |
| 424 |
"message_start", |
| 425 |
"a: content_block_start", |
| 426 |
"a: content_block_delta", |
| 427 |
"input_json", |
| 428 |
"a: content_block_stop", |
| 429 |
"b: content_block_start", |
| 430 |
"b: content_block_delta", |
| 431 |
"input_json", |
| 432 |
"b: content_block_stop", |
| 433 |
"message_delta (tool_use)", |
| 434 |
"message_stop", |
| 435 |
"loop body ends", |
| 436 |
"lookup(a) STARTS", |
| 437 |
"lookup(b) STARTS", |
| 438 |
] |
| 439 |
|
| 440 |
|
| 441 |
async def test_defer_tool_call_does_nothing_before_the_loop_starts_because_there_is_no_reply_yet( |
| 442 |
setup: SetupFactory, |
| 443 |
) -> None: |
| 444 |
test = setup([reply(call("a")), done()]) |
| 445 |
|
| 446 |
test.runner.defer_tool_call("toolu_a") |
| 447 |
assert test.runner.deferred_tool_calls == [] |
| 448 |
|
| 449 |
async for stream in replies_of(test.runner): |
| 450 |
await settled(stream.get_final_message()) |
| 451 |
test.timeline.append("loop body ends") |
| 452 |
|
| 453 |
assert first_reply(test.timeline) == ["lookup(a) STARTS", "loop body ends"] |
| 454 |
assert test.runner.deferred_tool_calls == [] |
| 455 |
|
| 456 |
|
| 457 |
async def test_defer_tool_call_changes_nothing_for_a_call_that_has_run(setup: SetupFactory) -> None: |
| 458 |
test = setup([reply(call("a"), call("b")), done()]) |
| 459 |
|
| 460 |
held: list[list[str]] = [] |
| 461 |
async for stream in replies_of(test.runner): |
| 462 |
async for event in events_of(stream): |
| 463 |
if test.label(event) == "b: content_block_delta": |
| 464 |
test.timeline.append("defer_tool_call(a)") |
| 465 |
test.runner.defer_tool_call("toolu_a") |
| 466 |
test.runner.defer_tool_call("toolu_b") |
| 467 |
held.append(ids(test.runner.deferred_tool_calls)) |
| 468 |
test.timeline.append("loop body ends") |
| 469 |
|
| 470 |
assert first_reply(test.timeline) == [ |
| 471 |
"lookup(a) STARTS", |
| 472 |
"defer_tool_call(a)", |
| 473 |
"loop body ends", |
| 474 |
"lookup(b) STARTS", |
| 475 |
] |
| 476 |
assert held[0] == ["toolu_b"] |
| 477 |
assert [result["tool_use_id"] for result in results_sent(test)] == ["toolu_a", "toolu_b"] |
| 478 |
|
| 479 |
|
| 480 |
async def test_defer_tool_call_lasts_for_one_reply(setup: SetupFactory) -> None: |
| 481 |
# The second reply reuses the id of the call that was held in the first. |
| 482 |
test = setup([reply(call("a")), reply(call("a")), done()]) |
| 483 |
|
| 484 |
held: list[list[str]] = [] |
| 485 |
async for stream in replies_of(test.runner): |
| 486 |
if not held: |
| 487 |
test.runner.defer_tool_call("toolu_a") |
| 488 |
await settled(stream.get_final_message()) |
| 489 |
held.append(ids(test.runner.deferred_tool_calls)) |
| 490 |
test.timeline.append("loop body ends") |
| 491 |
|
| 492 |
assert test.timeline == [ |
| 493 |
"loop body ends", |
| 494 |
"lookup(a) STARTS", # held in the first reply |
| 495 |
"request 2", |
| 496 |
"lookup(a) STARTS", # not held in the second |
| 497 |
"loop body ends", |
| 498 |
"request 3", |
| 499 |
"loop body ends", |
| 500 |
] |
| 501 |
assert held == [["toolu_a"], [], []] |
| 502 |
|
| 503 |
|
| 504 |
async def test_lets_the_caller_refuse_a_held_call_by_removing_its_tool(setup: SetupFactory) -> None: |
| 505 |
test = setup([reply(call("a"), call("b")), done()]) |
| 506 |
|
| 507 |
with pytest.warns(UserWarning, match="Tool 'lookup' not found in tool runner"): |
| 508 |
async for stream in replies_of(test.runner): |
| 509 |
async for event in events_of(stream): |
| 510 |
if test.label(event) == "b: content_block_start": |
| 511 |
test.runner.defer_tool_call(event.content_block) |
| 512 |
test.runner.remove_tools("lookup") |
| 513 |
|
| 514 |
assert first_reply(test.timeline) == ["lookup(a) STARTS"] |
| 515 |
assert results_sent(test) == [ |
| 516 |
{"type": "tool_result", "tool_use_id": "toolu_a", "content": "value of a"}, |
| 517 |
not_found("toolu_b"), |
| 518 |
] |
| 519 |
|
| 520 |
|
| 521 |
async def test_runs_a_held_call_when_the_caller_asks_for_the_tool_response(setup: SetupFactory) -> None: |
| 522 |
test = setup([reply(call("a"), call("b"))]) |
| 523 |
|
| 524 |
async for stream in replies_of(test.runner): |
| 525 |
test.runner.defer_tool_call("toolu_a") |
| 526 |
await settled(stream.get_final_message()) |
| 527 |
test.timeline.append("generate_tool_call_response()") |
| 528 |
response = await settled(test.runner.generate_tool_call_response()) |
| 529 |
|
| 530 |
assert [result["tool_use_id"] for result in tool_results(response)] == ["toolu_a", "toolu_b"] |
| 531 |
break |
| 532 |
|
| 533 |
assert test.timeline == ["lookup(b) STARTS", "generate_tool_call_response()", "lookup(a) STARTS"] |
| 534 |
|
| 535 |
|
| 536 |
# --------------------------------------------------------------------------------------------------------- |
| 537 |
# deferred_tool_calls |
| 538 |
# --------------------------------------------------------------------------------------------------------- |
| 539 |
|
| 540 |
|
| 541 |
async def test_deferred_tool_calls_lists_the_held_calls_in_the_models_order_with_their_whole_input( |
| 542 |
setup: SetupFactory, |
| 543 |
) -> None: |
| 544 |
test = setup([reply(call("a"), call("b"), call("c"))]) |
| 545 |
|
| 546 |
async for stream in replies_of(test.runner): |
| 547 |
# c is deferred by id before its block has streamed, and before b. |
| 548 |
test.runner.defer_tool_call("toolu_c") |
| 549 |
async for event in events_of(stream): |
| 550 |
if test.label(event) == "b: content_block_stop": |
| 551 |
test.runner.defer_tool_call("toolu_b") |
| 552 |
|
| 553 |
assert [tool_use.to_dict() for tool_use in test.runner.deferred_tool_calls] == [ |
| 554 |
{"type": "tool_use", "id": "toolu_b", "name": "lookup", "input": {"key": "b"}}, |
| 555 |
{"type": "tool_use", "id": "toolu_c", "name": "lookup", "input": {"key": "c"}}, |
| 556 |
] |
| 557 |
break |
| 558 |
|
| 559 |
|
| 560 |
async def test_deferred_tool_calls_lists_a_held_call_from_when_its_block_has_finished_streaming( |
| 561 |
setup: SetupFactory, |
| 562 |
) -> None: |
| 563 |
test = setup([reply(call("a"), call("b"))]) |
| 564 |
held: list[str] = [] |
| 565 |
|
| 566 |
async for stream in replies_of(test.runner): |
| 567 |
test.runner.defer_tool_call("toolu_a") |
| 568 |
test.runner.defer_tool_call("toolu_b") |
| 569 |
async for event in events_of(stream): |
| 570 |
held.append(f"{test.label(event)} -> {ids(test.runner.deferred_tool_calls)}") |
| 571 |
break |
| 572 |
|
| 573 |
assert held == [ |
| 574 |
"message_start -> []", |
| 575 |
"a: content_block_start -> []", |
| 576 |
"a: content_block_delta -> []", |
| 577 |
"input_json -> []", |
| 578 |
"a: content_block_stop -> ['toolu_a']", |
| 579 |
"b: content_block_start -> ['toolu_a']", |
| 580 |
"b: content_block_delta -> ['toolu_a']", |
| 581 |
"input_json -> ['toolu_a']", |
| 582 |
"b: content_block_stop -> ['toolu_a', 'toolu_b']", |
| 583 |
"message_delta (tool_use) -> ['toolu_a', 'toolu_b']", |
| 584 |
"message_stop -> ['toolu_a', 'toolu_b']", |
| 585 |
] |
| 586 |
|
| 587 |
|
| 588 |
async def test_deferred_tool_calls_is_empty_once_generate_tool_call_response_has_run_the_held_calls( |
| 589 |
setup: SetupFactory, |
| 590 |
) -> None: |
| 591 |
test = setup([reply(call("a"))]) |
| 592 |
|
| 593 |
async for stream in replies_of(test.runner): |
| 594 |
test.runner.defer_tool_call("toolu_a") |
| 595 |
await settled(stream.get_final_message()) |
| 596 |
assert ids(test.runner.deferred_tool_calls) == ["toolu_a"] |
| 597 |
|
| 598 |
await settled(test.runner.generate_tool_call_response()) |
| 599 |
|
| 600 |
assert test.runner.deferred_tool_calls == [] |
| 601 |
break |
| 602 |
|
| 603 |
|
| 604 |
async def test_deferred_tool_calls_lists_the_held_calls_of_a_reply_that_is_cut_off(setup: SetupFactory) -> None: |
| 605 |
# The runner runs no tools for such a reply, but generate_tool_call_response() does. |
| 606 |
test = setup([reply_ending("max_tokens", call("a"), call("b"))]) |
| 607 |
|
| 608 |
async for stream in replies_of(test.runner): |
| 609 |
test.runner.defer_tool_call("toolu_a") |
| 610 |
test.runner.defer_tool_call("toolu_b") |
| 611 |
await settled(stream.get_final_message()) |
| 612 |
|
| 613 |
assert ids(test.runner.deferred_tool_calls) == ["toolu_a", "toolu_b"] |
| 614 |
assert test.timeline == [] |
| 615 |
|
| 616 |
await settled(test.runner.generate_tool_call_response()) |
| 617 |
break |
| 618 |
|
| 619 |
assert test.timeline == ["lookup(a) STARTS", "lookup(b) STARTS"] |
| 620 |
|
| 621 |
|
| 622 |
# --------------------------------------------------------------------------------------------------------- |
| 623 |
# a reply that is cut off |
| 624 |
# --------------------------------------------------------------------------------------------------------- |
| 625 |
|
| 626 |
|
| 627 |
@pytest.mark.parametrize( |
| 628 |
"cut_off_reply", |
| 629 |
[ |
| 630 |
pytest.param(lambda: reply_ending("refusal", call("a"), call("b", '{"key": "b"')), id="a refusal"), |
| 631 |
pytest.param( |
| 632 |
lambda: reply_ending("end_turn", call("a"), call("b", '{"key": "b"'), fallback(), text("Here it is.")), |
| 633 |
id="a refusal that hands the reply to a fallback model", |
| 634 |
), |
| 635 |
pytest.param( |
| 636 |
# What arrived of the input is enough to call the tool with. |
| 637 |
lambda: reply_ending("max_tokens", call("a"), call("b", '{"key": "b", "note": "unfinis')), |
| 638 |
id="max_tokens", |
| 639 |
), |
| 640 |
], |
| 641 |
) |
| 642 |
async def test_never_runs_the_call_that_was_cut_off_by(setup: SetupFactory, cut_off_reply: Callable[[], Reply]) -> None: |
| 643 |
test = setup([cut_off_reply()]) |
| 644 |
|
| 645 |
await settled(test.runner.until_done()) |
| 646 |
|
| 647 |
assert test.timeline == ["lookup(a) STARTS"] |
| 648 |
assert len(test.requests) == 1 |
| 649 |
|
| 650 |
|
| 651 |
async def test_runs_the_calls_after_a_fallback_block_once_the_loop_body_ends_in_order(setup: SetupFactory) -> None: |
| 652 |
test = setup([reply(call("a"), call("b"), fallback(), call("c")), done()]) |
| 653 |
|
| 654 |
async for stream in replies_of(test.runner): |
| 655 |
await settled(stream.get_final_message()) |
| 656 |
test.timeline.append("loop body ends") |
| 657 |
|
| 658 |
# The fallback block started while b was still waiting for the model to move on. |
| 659 |
assert first_reply(test.timeline) == [ |
| 660 |
"lookup(a) STARTS", |
| 661 |
"loop body ends", |
| 662 |
"lookup(b) STARTS", |
| 663 |
"lookup(c) STARTS", |
| 664 |
] |
| 665 |
assert [result["tool_use_id"] for result in results_sent(test)] == ["toolu_a", "toolu_b", "toolu_c"] |
| 666 |
|
| 667 |
|
| 668 |
async def test_runs_no_later_call_once_the_caller_leaves_the_loop(setup: SetupFactory) -> None: |
| 669 |
test = setup([reply(call("a"), call("b"))]) |
| 670 |
|
| 671 |
async for stream in replies_of(test.runner): |
| 672 |
async for event in events_of(stream): |
| 673 |
if test.label(event) == "b: content_block_delta": |
| 674 |
break |
| 675 |
break |
| 676 |
|
| 677 |
assert test.timeline == ["lookup(a) STARTS"] |
| 678 |
assert len(test.requests) == 1 |
| 679 |
|
| 680 |
|
| 681 |
# --------------------------------------------------------------------------------------------------------- |
| 682 |
# a call that has run |
| 683 |
# --------------------------------------------------------------------------------------------------------- |
| 684 |
|
| 685 |
|
| 686 |
async def test_a_call_that_has_run_keeps_its_result_after_remove_tools_which_refuses_a_call_that_has_not( |
| 687 |
setup: SetupFactory, |
| 688 |
) -> None: |
| 689 |
test = setup([reply(call("a"), call("b")), done()]) |
| 690 |
|
| 691 |
with pytest.warns(UserWarning, match="Tool 'lookup' not found in tool runner"): |
| 692 |
async for stream in replies_of(test.runner): |
| 693 |
async for event in events_of(stream): |
| 694 |
if test.label(event) == "b: content_block_delta": |
| 695 |
test.runner.remove_tools("lookup") |
| 696 |
|
| 697 |
assert first_reply(test.timeline) == ["lookup(a) STARTS"] |
| 698 |
assert results_sent(test) == [ |
| 699 |
{"type": "tool_result", "tool_use_id": "toolu_a", "content": "value of a"}, |
| 700 |
not_found("toolu_b"), |
| 701 |
] |
| 702 |
|
| 703 |
|
| 704 |
async def test_a_call_that_has_run_keeps_its_result_after_add_tools_replaces_its_tool(setup: SetupFactory) -> None: |
| 705 |
test = setup([reply(call("a"), call("b")), done()]) |
| 706 |
replacement = lookup_tool(test.sync, [], lookup=lambda key: f"new value of {key}") |
| 707 |
|
| 708 |
async for stream in replies_of(test.runner): |
| 709 |
async for event in events_of(stream): |
| 710 |
if test.label(event) == "b: content_block_delta": |
| 711 |
test.runner.add_tools(replacement) |
| 712 |
|
| 713 |
assert results_sent(test) == [ |
| 714 |
{"type": "tool_result", "tool_use_id": "toolu_a", "content": "value of a"}, |
| 715 |
{"type": "tool_result", "tool_use_id": "toolu_b", "content": "new value of b"}, |
| 716 |
] |
| 717 |
|
| 718 |
|
| 719 |
async def test_a_call_to_a_tool_removed_earlier_in_the_conversation_gets_a_not_found_result( |
| 720 |
setup: SetupFactory, |
| 721 |
) -> None: |
| 722 |
test = setup( |
| 723 |
[reply(call("a"), text("Looking.")), done()], |
| 724 |
messages=[ |
| 725 |
{"role": "user", "content": "Look this up."}, |
| 726 |
{ |
| 727 |
"role": "system", |
| 728 |
"content": [{"type": "tool_removal", "tool": {"type": "tool_reference", "name": "lookup"}}], |
| 729 |
}, |
| 730 |
], |
| 731 |
) |
| 732 |
|
| 733 |
with pytest.warns(UserWarning, match="Tool 'lookup' not found in tool runner"): |
| 734 |
await settled(test.runner.until_done()) |
| 735 |
|
| 736 |
assert first_reply(test.timeline) == [] |
| 737 |
assert results_sent(test) == [not_found("toolu_a")] |
| 738 |
|
| 739 |
|
| 740 |
async def test_a_call_that_has_run_does_not_answer_a_later_reply_that_reuses_its_id(setup: SetupFactory) -> None: |
| 741 |
# The second reply's call comes after a fallback block, so it runs after the loop body. |
| 742 |
test = setup([reply(call("a")), reply(fallback(), call("a", json.dumps({"key": "again"}))), done()]) |
| 743 |
|
| 744 |
await settled(test.runner.until_done()) |
| 745 |
|
| 746 |
assert [result["content"] for result in tool_results(test.requests[2]["messages"][-1])] == ["value of again"] |
| 747 |
|
| 748 |
|
| 749 |
# --------------------------------------------------------------------------------------------------------- |
| 750 |
# Fixtures |
| 751 |
# --------------------------------------------------------------------------------------------------------- |
| 752 |
|
| 753 |
Block = dict[str, Any] |
| 754 |
"""One content block of a canned reply.""" |
| 755 |
|
| 756 |
PARAMS: dict[str, Any] = { |
| 757 |
"model": "claude-haiku-4-5", |
| 758 |
"max_tokens": 1024, |
| 759 |
"messages": [{"role": "user", "content": "Look these up."}], |
| 760 |
} |
| 761 |
|
| 762 |
|
| 763 |
class Reply(NamedTuple): |
| 764 |
blocks: tuple[Block, ...] |
| 765 |
stop_reason: str |
| 766 |
|
| 767 |
|
| 768 |
def call(key: str, json_input: str | None = None) -> Block: |
| 769 |
"""The model calls `lookup(key=key)` with the id `toolu_<key>`. `json_input` is the input as sent, which may be |
| 770 |
cut off.""" |
| 771 |
return {"type": "tool_use", "key": key, "json": json.dumps({"key": key}) if json_input is None else json_input} |
| 772 |
|
| 773 |
|
| 774 |
def text(value: str) -> Block: |
| 775 |
return {"type": "text", "text": value} |
| 776 |
|
| 777 |
|
| 778 |
def fallback() -> Block: |
| 779 |
"""The block a refusal starts when it hands the reply to a fallback model.""" |
| 780 |
return { |
| 781 |
"type": "fallback", |
| 782 |
"from": {"model": "claude-haiku-4-5"}, |
| 783 |
"to": {"model": "claude-opus-4-8"}, |
| 784 |
"trigger": {"type": "refusal", "category": None}, |
| 785 |
} |
| 786 |
|
| 787 |
|
| 788 |
def compaction() -> Block: |
| 789 |
"""The block that a compaction request is answered with.""" |
| 790 |
return {"type": "compaction", "content": "Summary so far.", "signature": "sig_01"} |
| 791 |
|
| 792 |
|
| 793 |
def reply(*blocks: Block) -> Reply: |
| 794 |
"""A reply that asks for tool results.""" |
| 795 |
return Reply(blocks, "tool_use") |
| 796 |
|
| 797 |
|
| 798 |
def reply_ending(stop_reason: str, *blocks: Block) -> Reply: |
| 799 |
"""A reply that ends for another reason.""" |
| 800 |
return Reply(blocks, stop_reason) |
| 801 |
|
| 802 |
|
| 803 |
def done() -> Reply: |
| 804 |
"""The reply that ends the conversation.""" |
| 805 |
return reply_ending("end_turn", text("Done.")) |
| 806 |
|
| 807 |
|
| 808 |
def not_found(tool_use_id: str) -> dict[str, Any]: |
| 809 |
return { |
| 810 |
"type": "tool_result", |
| 811 |
"tool_use_id": tool_use_id, |
| 812 |
"content": "Error: Tool 'lookup' not found", |
| 813 |
"is_error": True, |
| 814 |
} |
| 815 |
|
| 816 |
|
| 817 |
def ids(tool_uses: list[Any]) -> list[str]: |
| 818 |
return [tool_use.id for tool_use in tool_uses] |
| 819 |
|
| 820 |
|
| 821 |
def first_reply(timeline: list[str]) -> list[str]: |
| 822 |
"""The timeline up to the second request, which is everything about the first reply.""" |
| 823 |
return timeline[: timeline.index("request 2")] if "request 2" in timeline else timeline |
| 824 |
|
| 825 |
|
| 826 |
def tool_results(message: BetaMessageParam | None) -> list[Any]: |
| 827 |
if message is None or isinstance(message["content"], str): |
| 828 |
return [] |
| 829 |
return [block for block in message["content"] if isinstance(block, dict) and block["type"] == "tool_result"] |
| 830 |
|
| 831 |
|
| 832 |
def results_sent(test: Setup) -> list[Any]: |
| 833 |
"""The tool results the runner sent back for the first reply.""" |
| 834 |
return next(results for message in test.requests[1]["messages"] if (results := tool_results(message))) |
| 835 |
|
| 836 |
|
| 837 |
def label_of(event: dict[str, Any], blocks: dict[int, str]) -> str: |
| 838 |
"""Names a stream event, given as JSON, after the block it belongs to, such as `a: content_block_stop`.""" |
| 839 |
if event["type"] == "content_block_start": |
| 840 |
block = event["content_block"] |
| 841 |
blocks[event["index"]] = block["id"].removeprefix("toolu_") if block["type"] == "tool_use" else block["type"] |
| 842 |
if event["type"] in ("content_block_start", "content_block_delta", "content_block_stop"): |
| 843 |
return f"{blocks[event['index']]}: {event['type']}" |
| 844 |
if event["type"] == "message_delta": |
| 845 |
return f"message_delta ({event['delta']['stop_reason']})" |
| 846 |
return str(event["type"]) |
| 847 |
|
| 848 |
|
| 849 |
def empty_message() -> dict[str, Any]: |
| 850 |
return { |
| 851 |
"id": "msg_1", |
| 852 |
"type": "message", |
| 853 |
"role": "assistant", |
| 854 |
"model": "claude-haiku-4-5", |
| 855 |
"content": [], |
| 856 |
"stop_reason": None, |
| 857 |
"stop_sequence": None, |
| 858 |
"usage": {"input_tokens": 10, "output_tokens": 0}, |
| 859 |
} |
| 860 |
|
| 861 |
|
| 862 |
def to_events(canned: Reply) -> list[dict[str, Any]]: |
| 863 |
"""The reply as the stream events the API sends for it.""" |
| 864 |
events: list[dict[str, Any]] = [{"type": "message_start", "message": empty_message()}] |
| 865 |
for index, block in enumerate(canned.blocks): |
| 866 |
start: dict[str, Any] = block |
| 867 |
delta: dict[str, Any] | None = None |
| 868 |
if block["type"] == "tool_use": |
| 869 |
start = {"type": "tool_use", "id": f"toolu_{block['key']}", "name": "lookup", "input": {}} |
| 870 |
delta = {"type": "input_json_delta", "partial_json": block["json"]} |
| 871 |
elif block["type"] == "text": |
| 872 |
start = {"type": "text", "text": ""} |
| 873 |
delta = {"type": "text_delta", "text": block["text"]} |
| 874 |
events.append({"type": "content_block_start", "index": index, "content_block": start}) |
| 875 |
if delta is not None: |
| 876 |
events.append({"type": "content_block_delta", "index": index, "delta": delta}) |
| 877 |
events.append({"type": "content_block_stop", "index": index}) |
| 878 |
events.append( |
| 879 |
{ |
| 880 |
"type": "message_delta", |
| 881 |
"delta": {"stop_reason": canned.stop_reason, "stop_sequence": None}, |
| 882 |
"usage": {"output_tokens": 20}, |
| 883 |
} |
| 884 |
) |
| 885 |
events.append({"type": "message_stop"}) |
| 886 |
return events |
| 887 |
|
| 888 |
|
| 889 |
def to_message(canned: Reply) -> dict[str, Any]: |
| 890 |
"""The reply as the message the API sends for it when not streaming.""" |
| 891 |
content = [ |
| 892 |
{"type": "tool_use", "id": f"toolu_{block['key']}", "name": "lookup", "input": json.loads(block["json"])} |
| 893 |
if block["type"] == "tool_use" |
| 894 |
else block |
| 895 |
for block in canned.blocks |
| 896 |
] |
| 897 |
return {**empty_message(), "content": content, "stop_reason": canned.stop_reason} |
| 898 |
|
| 899 |
|
| 900 |
def sse(event: dict[str, Any]) -> bytes: |
| 901 |
return f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode() |
| 902 |
|
| 903 |
|
| 904 |
class EventByEvent(httpx2.SyncByteStream, httpx2.AsyncByteStream): |
| 905 |
"""A reply that the server sends one event at a time, as a server still generating would. Each event goes on the |
| 906 |
timeline when it is sent.""" |
| 907 |
|
| 908 |
def __init__(self, canned: Reply, fails_before: str | None) -> None: |
| 909 |
self.timeline: list[str] = [] |
| 910 |
"""Replaced by the test's timeline once the reply is handed to `setup()`.""" |
| 911 |
|
| 912 |
self._events = to_events(canned) |
| 913 |
self._fails_before = fails_before |
| 914 |
|
| 915 |
def _send(self) -> Iterator[bytes]: |
| 916 |
blocks: dict[int, str] = {} |
| 917 |
for event in self._events: |
| 918 |
label = label_of(event, blocks) |
| 919 |
if label == self._fails_before: |
| 920 |
self.timeline.append("server fails") |
| 921 |
raise httpx2.ReadError("The connection was lost.") |
| 922 |
self.timeline.append(f"server sends {label}") |
| 923 |
yield sse(event) |
| 924 |
|
| 925 |
@override |
| 926 |
def __iter__(self) -> Iterator[bytes]: |
| 927 |
yield from self._send() |
| 928 |
|
| 929 |
@override |
| 930 |
async def __aiter__(self) -> AsyncIterator[bytes]: |
| 931 |
for chunk in self._send(): |
| 932 |
yield chunk |
| 933 |
|
| 934 |
|
| 935 |
def event_by_event(canned: Reply, *, fails_before: str | None = None) -> EventByEvent: |
| 936 |
return EventByEvent(canned, fails_before) |
| 937 |
|
| 938 |
|
| 939 |
def lookup_tool( |
| 940 |
sync: bool, timeline: list[str], *, lookup: Callable[[str], str] | None = None, log_returns: bool = False |
| 941 |
) -> Any: |
| 942 |
"""A `lookup` tool that writes to `timeline` when it starts, and returns `value of <key>` unless `lookup` says |
| 943 |
otherwise.""" |
| 944 |
|
| 945 |
def run(key: str) -> str: |
| 946 |
timeline.append(f"lookup({key}) STARTS") |
| 947 |
value = f"value of {key}" if lookup is None else lookup(key) |
| 948 |
if log_returns: |
| 949 |
timeline.append(f"lookup({key}) returns") |
| 950 |
return value |
| 951 |
|
| 952 |
if sync: |
| 953 |
|
| 954 |
@beta_tool(name="lookup") |
| 955 |
def sync_lookup(key: str) -> str: |
| 956 |
"""Look up a key.""" |
| 957 |
return run(key) |
| 958 |
|
| 959 |
return sync_lookup |
| 960 |
|
| 961 |
@beta_async_tool(name="lookup") |
| 962 |
async def async_lookup(key: str) -> str: |
| 963 |
"""Look up a key.""" |
| 964 |
return run(key) |
| 965 |
|
| 966 |
return async_lookup |
| 967 |
|
| 968 |
|
| 969 |
class Setup: |
| 970 |
def __init__(self, *, sync: bool, runner: Any, timeline: list[str], requests: list[Any]) -> None: |
| 971 |
self.sync = sync |
| 972 |
self.runner = runner |
| 973 |
self.timeline = timeline |
| 974 |
self.requests = requests |
| 975 |
self._blocks: dict[int, str] = {} |
| 976 |
|
| 977 |
def label(self, event: Any) -> str: |
| 978 |
"""Names a stream event after the block it belongs to, such as `a: content_block_stop`.""" |
| 979 |
return label_of(event.to_dict(), self._blocks) |
| 980 |
|
| 981 |
def see(self, event: Any) -> None: |
| 982 |
"""Adds a stream event to the timeline, as the caller saw it.""" |
| 983 |
self.timeline.append(self.label(event)) |
| 984 |
|
| 985 |
|
| 986 |
class SetupFactory: |
| 987 |
"""Makes a runner whose requests are answered by `replies`, in order, and whose `lookup` tool writes to the |
| 988 |
timeline when it starts. A `Reply` arrives in one piece.""" |
| 989 |
|
| 990 |
def __init__(self, sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter) -> None: |
| 991 |
self._sync = sync |
| 992 |
self._client = client.with_options(max_retries=0) if sync else async_client.with_options(max_retries=0) |
| 993 |
self._respx_mock = respx_mock |
| 994 |
|
| 995 |
def __call__( |
| 996 |
self, |
| 997 |
replies: list[Reply | EventByEvent], |
| 998 |
*, |
| 999 |
stream: bool = True, |
| 1000 |
run_tools_eagerly: bool = True, |
| 1001 |
lookup: Callable[[str], str] | None = None, |
| 1002 |
log_returns: bool = False, |
| 1003 |
messages: list[Any] | None = None, |
| 1004 |
) -> Setup: |
| 1005 |
timeline: list[str] = [] |
| 1006 |
requests: list[Any] = [] |
| 1007 |
responses = iter(replies) |
| 1008 |
for canned in replies: |
| 1009 |
if isinstance(canned, EventByEvent): |
| 1010 |
canned.timeline = timeline |
| 1011 |
|
| 1012 |
def respond(request: httpx2.Request) -> httpx2.Response: |
| 1013 |
requests.append(json.loads(request.content)) |
| 1014 |
if len(requests) > 1: |
| 1015 |
timeline.append(f"request {len(requests)}") |
| 1016 |
|
| 1017 |
canned = next(responses) |
| 1018 |
if not stream: |
| 1019 |
assert isinstance(canned, Reply) |
| 1020 |
return httpx2.Response(200, json=to_message(canned)) |
| 1021 |
headers = {"content-type": "text/event-stream"} |
| 1022 |
if isinstance(canned, EventByEvent): |
| 1023 |
return httpx2.Response(200, stream=canned, headers=headers) |
| 1024 |
return httpx2.Response(200, content=b"".join(map(sse, to_events(canned))), headers=headers) |
| 1025 |
|
| 1026 |
self._respx_mock.post("/v1/messages").mock(side_effect=respond) |
| 1027 |
|
| 1028 |
tool_runner: Any = self._client.beta.messages.tool_runner |
| 1029 |
runner = tool_runner( |
| 1030 |
**{**PARAMS, "messages": messages or PARAMS["messages"]}, |
| 1031 |
tools=[lookup_tool(self._sync, timeline, lookup=lookup, log_returns=log_returns)], |
| 1032 |
stream=stream, |
| 1033 |
**({"run_tools_eagerly": True} if run_tools_eagerly and stream else {}), |
| 1034 |
) |
| 1035 |
return Setup(sync=self._sync, runner=runner, timeline=timeline, requests=requests) |
| 1036 |
|
| 1037 |
|
| 1038 |
@pytest.fixture(params=[True, False], ids=["sync", "async"]) |
| 1039 |
def sync(request: pytest.FixtureRequest) -> bool: |
| 1040 |
return bool(request.param) |
| 1041 |
|
| 1042 |
|
| 1043 |
@pytest.fixture |
| 1044 |
def setup(sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter) -> SetupFactory: |
| 1045 |
return SetupFactory(sync, client, async_client, respx_mock) |
| 1046 |
|
| 1047 |
|
| 1048 |
async def replies_of(runner: Any) -> AsyncIterator[Any]: |
| 1049 |
"""What the runner yields, whether it is the sync or the async one.""" |
| 1050 |
if hasattr(runner, "__anext__"): |
| 1051 |
async for item in runner: |
| 1052 |
yield item |
| 1053 |
else: |
| 1054 |
for item in runner: |
| 1055 |
yield item |
| 1056 |
|
| 1057 |
|
| 1058 |
async def events_of(stream: Any) -> AsyncIterator[Any]: |
| 1059 |
"""What the stream yields, whether it is the sync or the async one.""" |
| 1060 |
if hasattr(stream, "__anext__"): |
| 1061 |
async for event in stream: |
| 1062 |
yield event |
| 1063 |
else: |
| 1064 |
for event in stream: |
| 1065 |
yield event |
| 1066 |
|
| 1067 |
|
| 1068 |
async def settled(value: _T | Awaitable[_T]) -> _T: |
| 1069 |
"""The result of a call on either runner: awaited on the async one.""" |
| 1070 |
if inspect.isawaitable(value): |
| 1071 |
return await value |
| 1072 |
return value |