-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathtest_items_helpers.py
More file actions
731 lines (630 loc) · 27.1 KB
/
test_items_helpers.py
File metadata and controls
731 lines (630 loc) · 27.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
from __future__ import annotations
import gc
import json
import weakref
from typing import Any, cast
from openai.types.responses.computer_action import Click as BatchedClick, Type as BatchedType
from openai.types.responses.response_computer_tool_call import (
ActionScreenshot,
ResponseComputerToolCall,
)
from openai.types.responses.response_computer_tool_call_param import ResponseComputerToolCallParam
from openai.types.responses.response_file_search_tool_call import ResponseFileSearchToolCall
from openai.types.responses.response_file_search_tool_call_param import (
ResponseFileSearchToolCallParam,
)
from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall
from openai.types.responses.response_function_tool_call_param import ResponseFunctionToolCallParam
from openai.types.responses.response_function_web_search import (
ActionSearch,
ResponseFunctionWebSearch,
)
from openai.types.responses.response_function_web_search_param import ResponseFunctionWebSearchParam
from openai.types.responses.response_input_item_param import ResponseInputItemParam
from openai.types.responses.response_output_message import ResponseOutputMessage
from openai.types.responses.response_output_message_param import ResponseOutputMessageParam
from openai.types.responses.response_output_refusal import ResponseOutputRefusal
from openai.types.responses.response_output_text import ResponseOutputText
from openai.types.responses.response_output_text_param import ResponseOutputTextParam
from openai.types.responses.response_reasoning_item import ResponseReasoningItem, Summary
from openai.types.responses.response_reasoning_item_param import ResponseReasoningItemParam
from openai.types.responses.response_tool_search_call import ResponseToolSearchCall
from openai.types.responses.response_tool_search_output_item import ResponseToolSearchOutputItem
from pydantic import TypeAdapter
from agents import (
Agent,
HandoffOutputItem,
ItemHelpers,
MessageOutputItem,
ModelResponse,
ReasoningItem,
RunItem,
TResponseInputItem,
Usage,
)
from agents.items import ToolCallItem, ToolCallOutputItem
def make_message(
content_items: list[ResponseOutputText | ResponseOutputRefusal],
) -> ResponseOutputMessage:
"""
Helper to construct a ResponseOutputMessage with a single batch of content
items, using a fixed id/status.
"""
return ResponseOutputMessage(
id="msg123",
content=content_items,
role="assistant",
status="completed",
type="message",
)
def test_extract_last_content_of_text_message() -> None:
# Build a message containing two text segments.
content1 = ResponseOutputText(annotations=[], text="Hello ", type="output_text", logprobs=[])
content2 = ResponseOutputText(annotations=[], text="world!", type="output_text", logprobs=[])
message = make_message([content1, content2])
# Helpers should yield the last segment's text.
assert ItemHelpers.extract_last_content(message) == "world!"
def test_extract_last_content_of_refusal_message() -> None:
# Build a message whose last content entry is a refusal.
content1 = ResponseOutputText(
annotations=[], text="Before refusal", type="output_text", logprobs=[]
)
refusal = ResponseOutputRefusal(refusal="I cannot do that", type="refusal")
message = make_message([content1, refusal])
# Helpers should extract the refusal string when last content is a refusal.
assert ItemHelpers.extract_last_content(message) == "I cannot do that"
def test_extract_last_content_non_message_returns_empty() -> None:
# Construct some other type of output item, e.g. a tool call, to verify non-message returns "".
tool_call = ResponseFunctionToolCall(
id="tool123",
arguments="{}",
call_id="call123",
name="func",
type="function_call",
)
assert ItemHelpers.extract_last_content(tool_call) == ""
def test_extract_last_text_returns_text_only() -> None:
# A message whose last segment is text yields the text.
first_text = ResponseOutputText(annotations=[], text="part1", type="output_text", logprobs=[])
second_text = ResponseOutputText(annotations=[], text="part2", type="output_text", logprobs=[])
message = make_message([first_text, second_text])
assert ItemHelpers.extract_last_text(message) == "part2"
# Whereas when last content is a refusal, extract_last_text returns None.
message2 = make_message([first_text, ResponseOutputRefusal(refusal="no", type="refusal")])
assert ItemHelpers.extract_last_text(message2) is None
def test_extract_text_concatenates_all_text_segments() -> None:
first_text = ResponseOutputText(annotations=[], text="part1", type="output_text", logprobs=[])
second_text = ResponseOutputText(annotations=[], text="part2", type="output_text", logprobs=[])
refusal = ResponseOutputRefusal(refusal="no", type="refusal")
message = make_message([first_text, refusal, second_text])
assert ItemHelpers.extract_text(message) == "part1part2"
assert (
ItemHelpers.extract_text(
ResponseFunctionToolCall(
id="tool123",
arguments="{}",
call_id="call123",
name="func",
type="function_call",
)
)
is None
)
def test_extract_text_tolerates_none_text_content() -> None:
"""Regression: ``content_item.text`` can be ``None`` when output items
are assembled via ``model_construct`` (e.g. partial streaming responses)
or surfaced through provider gateways like LiteLLM. Without the ``or ""``
guard, ``extract_text`` raised
``TypeError: can only concatenate str (not "NoneType") to str`` deep
inside ``execute_tools_and_side_effects`` and aborted the agent turn.
"""
none_text = ResponseOutputText.model_construct(
annotations=[], text=None, type="output_text", logprobs=[]
)
real_text = ResponseOutputText(annotations=[], text="hello", type="output_text", logprobs=[])
# Single None-text item: result is None (since concatenated text is "").
assert ItemHelpers.extract_text(make_message([none_text])) is None
# Mixed content: real text is preserved, None is skipped.
assert ItemHelpers.extract_text(make_message([real_text, none_text])) == "hello"
assert ItemHelpers.extract_text(make_message([none_text, real_text])) == "hello"
def test_input_to_new_input_list_from_string() -> None:
result = ItemHelpers.input_to_new_input_list("hi")
# Should wrap the string into a list with a single dict containing content and user role.
assert isinstance(result, list)
assert result == [{"content": "hi", "role": "user"}]
def test_input_to_new_input_list_deep_copies_lists() -> None:
# Given a list of message dictionaries, ensure the returned list is a deep copy.
original: list[TResponseInputItem] = [{"content": "abc", "role": "developer"}]
new_list = ItemHelpers.input_to_new_input_list(original)
assert new_list == original
# Mutating the returned list should not mutate the original.
new_list.pop()
assert "content" in original[0] and original[0].get("content") == "abc"
def test_text_message_output_concatenates_text_segments() -> None:
# Build a message with both text and refusal segments, only text segments are concatenated.
pieces: list[ResponseOutputText | ResponseOutputRefusal] = []
pieces.append(ResponseOutputText(annotations=[], text="a", type="output_text", logprobs=[]))
pieces.append(ResponseOutputRefusal(refusal="denied", type="refusal"))
pieces.append(ResponseOutputText(annotations=[], text="b", type="output_text", logprobs=[]))
message = make_message(pieces)
# Wrap into MessageOutputItem to feed into text_message_output.
item = MessageOutputItem(agent=Agent(name="test"), raw_item=message)
assert ItemHelpers.text_message_output(item) == "ab"
def test_text_message_outputs_across_list_of_runitems() -> None:
"""
Compose several RunItem instances, including a non-message run item, and ensure
that only MessageOutputItem instances contribute any text. The non-message
(ReasoningItem) should be ignored by Helpers.text_message_outputs.
"""
message1 = make_message(
[ResponseOutputText(annotations=[], text="foo", type="output_text", logprobs=[])]
)
message2 = make_message(
[ResponseOutputText(annotations=[], text="bar", type="output_text", logprobs=[])]
)
item1: RunItem = MessageOutputItem(agent=Agent(name="test"), raw_item=message1)
item2: RunItem = MessageOutputItem(agent=Agent(name="test"), raw_item=message2)
# Create a non-message run item of a different type, e.g., a reasoning trace.
reasoning = ResponseReasoningItem(id="rid", summary=[], type="reasoning")
non_message_item: RunItem = ReasoningItem(agent=Agent(name="test"), raw_item=reasoning)
# Confirm only the message outputs are concatenated.
assert ItemHelpers.text_message_outputs([item1, non_message_item, item2]) == "foobar"
def test_message_output_item_retains_agent_until_release() -> None:
# Construct the run item with an inline agent to ensure the run item keeps a strong reference.
message = make_message([ResponseOutputText(annotations=[], text="hello", type="output_text")])
agent = Agent(name="inline")
item = MessageOutputItem(agent=agent, raw_item=message)
assert item.agent is agent
assert item.agent.name == "inline"
# Releasing the agent should keep the weak reference alive while strong refs remain.
item.release_agent()
assert item.agent is agent
agent_ref = weakref.ref(agent)
del agent
gc.collect()
# Once the original agent is collected, the weak reference should drop.
assert agent_ref() is None
assert item.agent is None
def test_handoff_output_item_retains_agents_until_gc() -> None:
raw_item: TResponseInputItem = {
"call_id": "call1",
"output": "handoff",
"type": "function_call_output",
}
owner_agent = Agent(name="owner")
source_agent = Agent(name="source")
target_agent = Agent(name="target")
item = HandoffOutputItem(
agent=owner_agent,
raw_item=raw_item,
source_agent=source_agent,
target_agent=target_agent,
)
item.release_agent()
assert item.agent is owner_agent
assert item.source_agent is source_agent
assert item.target_agent is target_agent
owner_ref = weakref.ref(owner_agent)
source_ref = weakref.ref(source_agent)
target_ref = weakref.ref(target_agent)
del owner_agent
del source_agent
del target_agent
gc.collect()
assert owner_ref() is None
assert source_ref() is None
assert target_ref() is None
assert item.agent is None
assert item.source_agent is None
assert item.target_agent is None
def test_handoff_output_item_converts_protocol_payload() -> None:
raw_item = cast(
TResponseInputItem,
{
"type": "function_call_output",
"call_id": "call-123",
"output": "ok",
},
)
owner_agent = Agent(name="owner")
source_agent = Agent(name="source")
target_agent = Agent(name="target")
item = HandoffOutputItem(
agent=owner_agent,
raw_item=raw_item,
source_agent=source_agent,
target_agent=target_agent,
)
converted = item.to_input_item()
assert converted["type"] == "function_call_output"
assert converted["call_id"] == "call-123"
assert converted["output"] == "ok"
def test_handoff_output_item_stringifies_object_output() -> None:
raw_item = cast(
TResponseInputItem,
{
"type": "function_call_output",
"call_id": "call-obj",
"output": {"assistant": "Weather Assistant"},
},
)
owner_agent = Agent(name="owner")
source_agent = Agent(name="source")
target_agent = Agent(name="target")
item = HandoffOutputItem(
agent=owner_agent,
raw_item=raw_item,
source_agent=source_agent,
target_agent=target_agent,
)
converted = item.to_input_item()
assert converted["type"] == "function_call_output"
assert converted["call_id"] == "call-obj"
assert isinstance(converted["output"], dict)
assert converted["output"] == {"assistant": "Weather Assistant"}
def test_tool_call_output_item_preserves_function_output_structure() -> None:
agent = Agent(name="tester")
raw_item = {
"type": "function_call_output",
"call_id": "call-keep",
"output": [{"type": "output_text", "text": "value"}],
}
item = ToolCallOutputItem(agent=agent, raw_item=raw_item, output="value")
payload = item.to_input_item()
assert isinstance(payload, dict)
assert payload["type"] == "function_call_output"
assert payload["output"] == raw_item["output"]
def test_tool_call_output_item_constructs_function_call_output_dict():
# Build a simple ResponseFunctionToolCall.
call = ResponseFunctionToolCall(
id="call-abc",
arguments='{"x": 1}',
call_id="call-abc",
name="do_something",
type="function_call",
)
payload = ItemHelpers.tool_call_output_item(call, "result-string")
assert isinstance(payload, dict)
assert payload["type"] == "function_call_output"
assert payload["call_id"] == call.id
assert payload["output"] == "result-string"
# The following tests ensure that every possible output item type defined by
# OpenAI's API can be converted back into an input item dict via
# ModelResponse.to_input_items. The output and input schema for each item are
# intended to be symmetric, so given any ResponseOutputItem, its model_dump
# should produce a dict that can satisfy the corresponding TypedDict input
# type. These tests construct minimal valid instances of each output type,
# invoke to_input_items, and then verify that the resulting dict can be used
# to round-trip back into a Pydantic output model without errors.
def test_to_input_items_for_message() -> None:
"""An output message should convert into an input dict matching the message's own structure."""
content = ResponseOutputText(
annotations=[], text="hello world", type="output_text", logprobs=[]
)
message = ResponseOutputMessage(
id="m1", content=[content], role="assistant", status="completed", type="message"
)
resp = ModelResponse(output=[message], usage=Usage(), response_id=None)
input_items = resp.to_input_items()
assert isinstance(input_items, list) and len(input_items) == 1
# The dict should contain exactly the primitive values of the message
expected: ResponseOutputMessageParam = {
"id": "m1",
"content": [
{
"annotations": [],
"logprobs": [],
"text": "hello world",
"type": "output_text",
}
],
"role": "assistant",
"status": "completed",
"type": "message",
}
assert input_items[0] == expected
def test_to_input_items_for_function_call() -> None:
"""A function tool call output should produce the same dict as a function tool call input."""
tool_call = ResponseFunctionToolCall(
id="f1", arguments="{}", call_id="c1", name="func", type="function_call"
)
resp = ModelResponse(output=[tool_call], usage=Usage(), response_id=None)
input_items = resp.to_input_items()
assert isinstance(input_items, list) and len(input_items) == 1
expected: ResponseFunctionToolCallParam = {
"id": "f1",
"arguments": "{}",
"call_id": "c1",
"name": "func",
"type": "function_call",
}
assert input_items[0] == expected
def test_to_input_items_for_file_search_call() -> None:
"""A file search tool call output should produce the same dict as a file search input."""
fs_call = ResponseFileSearchToolCall(
id="fs1", queries=["query"], status="completed", type="file_search_call"
)
resp = ModelResponse(output=[fs_call], usage=Usage(), response_id=None)
input_items = resp.to_input_items()
assert isinstance(input_items, list) and len(input_items) == 1
expected: ResponseFileSearchToolCallParam = {
"id": "fs1",
"queries": ["query"],
"status": "completed",
"type": "file_search_call",
}
assert input_items[0] == expected
def test_to_input_items_for_web_search_call() -> None:
"""A web search tool call output should produce the same dict as a web search input."""
ws_call = ResponseFunctionWebSearch(
id="w1",
action=ActionSearch(type="search", query="query"),
status="completed",
type="web_search_call",
)
resp = ModelResponse(output=[ws_call], usage=Usage(), response_id=None)
input_items = resp.to_input_items()
assert isinstance(input_items, list) and len(input_items) == 1
expected: ResponseFunctionWebSearchParam = {
"id": "w1",
"status": "completed",
"type": "web_search_call",
"action": {"type": "search", "query": "query"},
}
assert input_items[0] == expected
def test_to_input_items_for_computer_call_click() -> None:
"""A computer call output should yield a dict whose shape matches the computer call input."""
action = ActionScreenshot(type="screenshot")
comp_call = ResponseComputerToolCall(
id="comp1",
action=action,
type="computer_call",
call_id="comp1",
pending_safety_checks=[],
status="completed",
)
resp = ModelResponse(output=[comp_call], usage=Usage(), response_id=None)
input_items = resp.to_input_items()
assert isinstance(input_items, list) and len(input_items) == 1
converted_dict = input_items[0]
# Top-level keys should match what we expect for a computer call input
expected: ResponseComputerToolCallParam = {
"id": "comp1",
"type": "computer_call",
"action": {"type": "screenshot"},
"call_id": "comp1",
"pending_safety_checks": [],
"status": "completed",
}
assert converted_dict == expected
def test_to_input_items_for_computer_call_batched_actions() -> None:
"""A batched computer call should preserve its actions list when replayed as input."""
comp_call = ResponseComputerToolCall(
id="comp2",
actions=[
BatchedClick(type="click", x=3, y=4, button="left"),
BatchedType(type="type", text="hello"),
],
type="computer_call",
call_id="comp2",
pending_safety_checks=[],
status="completed",
)
resp = ModelResponse(output=[comp_call], usage=Usage(), response_id=None)
input_items = resp.to_input_items()
assert isinstance(input_items, list) and len(input_items) == 1
assert input_items[0] == {
"id": "comp2",
"type": "computer_call",
"actions": [
{"type": "click", "x": 3, "y": 4, "button": "left"},
{"type": "type", "text": "hello"},
],
"call_id": "comp2",
"pending_safety_checks": [],
"status": "completed",
}
def test_to_input_items_for_reasoning() -> None:
"""A reasoning output should produce the same dict as a reasoning input item."""
rc = Summary(text="why", type="summary_text")
reasoning = ResponseReasoningItem(id="rid1", summary=[rc], type="reasoning")
resp = ModelResponse(output=[reasoning], usage=Usage(), response_id=None)
input_items = resp.to_input_items()
assert isinstance(input_items, list) and len(input_items) == 1
converted_dict = input_items[0]
expected: ResponseReasoningItemParam = {
"id": "rid1",
"summary": [{"text": "why", "type": "summary_text"}],
"type": "reasoning",
}
print(converted_dict)
print(expected)
assert converted_dict == expected
def test_to_input_items_for_tool_search_strips_created_by() -> None:
"""Tool-search output items should reuse the replay sanitizer before round-tripping."""
tool_search_call = ResponseToolSearchCall(
id="tsc_123",
call_id="call_tsc_123",
arguments={"query": "profile"},
execution="server",
status="completed",
type="tool_search_call",
created_by="server",
)
tool_search_output = ResponseToolSearchOutputItem(
id="tso_123",
call_id="call_tsc_123",
execution="server",
status="completed",
tools=[],
type="tool_search_output",
created_by="server",
)
resp = ModelResponse(
output=[tool_search_call, tool_search_output], usage=Usage(), response_id=None
)
input_items = resp.to_input_items()
assert input_items == [
{
"id": "tsc_123",
"call_id": "call_tsc_123",
"arguments": {"query": "profile"},
"execution": "server",
"status": "completed",
"type": "tool_search_call",
},
{
"id": "tso_123",
"call_id": "call_tsc_123",
"execution": "server",
"status": "completed",
"tools": [],
"type": "tool_search_output",
},
]
def test_input_to_new_input_list_copies_the_ones_produced_by_pydantic() -> None:
"""Validated input items should be copied and made JSON dump compatible."""
original = ResponseOutputMessageParam(
id="a75654dc-7492-4d1c-bce0-89e8312fbdd7",
content=[
ResponseOutputTextParam(
type="output_text",
text="Hey, what's up?",
annotations=[],
logprobs=[],
)
],
role="assistant",
status="completed",
type="message",
)
validated = TypeAdapter(list[ResponseInputItemParam]).validate_python([original])
new_list = ItemHelpers.input_to_new_input_list(validated)
assert len(new_list) == 1
assert new_list[0]["id"] == original["id"] # type: ignore
assert new_list[0]["role"] == original["role"] # type: ignore
assert new_list[0]["status"] == original["status"] # type: ignore
assert new_list[0]["type"] == original["type"]
assert isinstance(new_list[0]["content"], list)
first_content = cast(dict[str, object], new_list[0]["content"][0])
assert first_content["type"] == "output_text"
assert first_content["text"] == "Hey, what's up?"
assert isinstance(first_content["annotations"], list)
assert isinstance(first_content["logprobs"], list)
# This used to fail when validated payloads retained ValidatorIterator fields.
json.dumps(new_list)
def test_tool_call_item_to_input_item_keeps_payload_api_safe() -> None:
agent = Agent(name="test", instructions="test")
raw_item = ResponseFunctionToolCall(
id="fc_1",
call_id="call_1",
name="my_tool",
arguments="{}",
type="function_call",
status="completed",
)
item = ToolCallItem(
agent=agent,
raw_item=raw_item,
title="My Tool",
description="A helpful tool",
)
result = item.to_input_item()
result_dict = cast(dict[str, Any], result)
assert isinstance(result, dict)
assert result_dict["type"] == "function_call"
assert "title" not in result_dict
assert "description" not in result_dict
# ---------------------------------------------------------------------------
# ToolCallItem / ToolCallOutputItem convenience properties
# ---------------------------------------------------------------------------
def test_tool_call_item_tool_name_from_function_call() -> None:
"""tool_name is extracted from ResponseFunctionToolCall.name."""
agent = Agent(name="test", instructions="test")
raw_item = ResponseFunctionToolCall(
id="fc_1",
call_id="call_abc",
name="my_tool",
arguments="{}",
type="function_call",
status="completed",
)
item = ToolCallItem(agent=agent, raw_item=raw_item)
assert item.tool_name == "my_tool"
def test_tool_call_item_tool_name_from_dict() -> None:
"""tool_name is extracted from a raw dict with a 'name' key."""
agent = Agent(name="test", instructions="test")
raw_item: dict[str, Any] = {"type": "function_call", "name": "dict_tool", "call_id": "cid_1"}
item = ToolCallItem(agent=agent, raw_item=raw_item)
assert item.tool_name == "dict_tool"
def test_tool_call_item_tool_name_none_for_computer_call() -> None:
"""tool_name is None for tool types that carry no 'name' field."""
from openai.types.responses.response_computer_tool_call import ResponseComputerToolCall
agent = Agent(name="test", instructions="test")
raw_item = ResponseComputerToolCall(
id="cu_1",
call_id="call_cu",
type="computer_call",
status="completed",
action={"type": "screenshot"},
actions=[],
pending_safety_checks=[],
)
item = ToolCallItem(agent=agent, raw_item=raw_item)
assert item.tool_name is None
def test_tool_call_item_call_id_from_function_call() -> None:
"""call_id is extracted from ResponseFunctionToolCall.call_id."""
agent = Agent(name="test", instructions="test")
raw_item = ResponseFunctionToolCall(
id="fc_2",
call_id="call_xyz",
name="another_tool",
arguments="{}",
type="function_call",
status="completed",
)
item = ToolCallItem(agent=agent, raw_item=raw_item)
assert item.call_id == "call_xyz"
def test_tool_call_item_call_id_from_dict() -> None:
"""call_id is extracted from a raw dict with a 'call_id' key."""
agent = Agent(name="test", instructions="test")
raw_item: dict[str, Any] = {"type": "function_call", "name": "t", "call_id": "cid_dict"}
item = ToolCallItem(agent=agent, raw_item=raw_item)
assert item.call_id == "cid_dict"
def test_tool_call_output_item_call_id_from_dict() -> None:
"""ToolCallOutputItem.call_id is extracted from the raw dict (TypedDict) payload."""
agent = Agent(name="test", instructions="test")
raw_item: dict[str, Any] = {
"type": "function_call_output",
"call_id": "call_out_1",
"output": "result",
}
item = ToolCallOutputItem(agent=agent, raw_item=raw_item, output="result")
assert item.call_id == "call_out_1"
def test_tool_call_output_item_call_id_none_when_missing() -> None:
"""ToolCallOutputItem.call_id returns None when the raw item has no call_id."""
agent = Agent(name="test", instructions="test")
raw_item: dict[str, Any] = {"type": "custom_output", "output": "result"}
item = ToolCallOutputItem(agent=agent, raw_item=raw_item, output="result")
assert item.call_id is None
def test_tool_call_items_can_be_joined_by_call_id() -> None:
"""Demonstrates the motivating use-case: correlate outputs to calls via call_id."""
agent = Agent(name="test", instructions="test")
call = ToolCallItem(
agent=agent,
raw_item=ResponseFunctionToolCall(
id="fc_join",
call_id="call_join",
name="join_tool",
arguments="{}",
type="function_call",
status="completed",
),
)
output = ToolCallOutputItem(
agent=agent,
raw_item={"type": "function_call_output", "call_id": "call_join", "output": "done"},
output="done",
)
assert call.call_id == output.call_id
assert call.tool_name == "join_tool"