forked from openai/openai-agents-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfake_model.py
More file actions
365 lines (327 loc) · 14.3 KB
/
Copy pathfake_model.py
File metadata and controls
365 lines (327 loc) · 14.3 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
from __future__ import annotations
from collections.abc import AsyncIterator
from typing import Any
from openai.types.responses import (
Response,
ResponseCompletedEvent,
ResponseContentPartAddedEvent,
ResponseContentPartDoneEvent,
ResponseCreatedEvent,
ResponseCustomToolCall,
ResponseFunctionCallArgumentsDeltaEvent,
ResponseFunctionCallArgumentsDoneEvent,
ResponseFunctionToolCall,
ResponseInProgressEvent,
ResponseOutputItemAddedEvent,
ResponseOutputItemDoneEvent,
ResponseOutputMessage,
ResponseOutputText,
ResponseReasoningSummaryPartAddedEvent,
ResponseReasoningSummaryPartDoneEvent,
ResponseReasoningSummaryTextDeltaEvent,
ResponseReasoningSummaryTextDoneEvent,
ResponseTextDeltaEvent,
ResponseTextDoneEvent,
ResponseUsage,
)
from openai.types.responses.response_reasoning_item import ResponseReasoningItem
from openai.types.responses.response_reasoning_summary_part_added_event import (
Part as AddedEventPart,
)
from openai.types.responses.response_reasoning_summary_part_done_event import Part as DoneEventPart
from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails
from agents.agent_output import AgentOutputSchemaBase
from agents.handoffs import Handoff
from agents.items import (
ModelResponse,
TResponseInputItem,
TResponseOutputItem,
TResponseStreamEvent,
)
from agents.model_settings import ModelSettings
from agents.models.interface import Model, ModelTracing
from agents.tool import Tool
from agents.tracing import SpanError, generation_span
from agents.usage import Usage
class FakeModel(Model):
def __init__(
self,
tracing_enabled: bool = False,
initial_output: list[TResponseOutputItem] | Exception | None = None,
):
if initial_output is None:
initial_output = []
self.turn_outputs: list[list[TResponseOutputItem] | Exception] = (
[initial_output] if initial_output else []
)
self.tracing_enabled = tracing_enabled
self.last_turn_args: dict[str, Any] = {}
self.first_turn_args: dict[str, Any] | None = None
self.hardcoded_usage: Usage | None = None
def set_hardcoded_usage(self, usage: Usage):
self.hardcoded_usage = usage
def set_next_output(self, output: list[TResponseOutputItem] | Exception):
self.turn_outputs.append(output)
def add_multiple_turn_outputs(self, outputs: list[list[TResponseOutputItem] | Exception]):
self.turn_outputs.extend(outputs)
def get_next_output(self) -> list[TResponseOutputItem] | Exception:
if not self.turn_outputs:
return []
return self.turn_outputs.pop(0)
async def get_response(
self,
system_instructions: str | None,
input: str | list[TResponseInputItem],
model_settings: ModelSettings,
tools: list[Tool],
output_schema: AgentOutputSchemaBase | None,
handoffs: list[Handoff],
tracing: ModelTracing,
*,
previous_response_id: str | None,
conversation_id: str | None,
prompt: Any | None,
) -> ModelResponse:
turn_args = {
"system_instructions": system_instructions,
"input": input,
"model_settings": model_settings,
"tools": tools,
"output_schema": output_schema,
"previous_response_id": previous_response_id,
"conversation_id": conversation_id,
}
if self.first_turn_args is None:
self.first_turn_args = turn_args.copy()
self.last_turn_args = turn_args
with generation_span(disabled=not self.tracing_enabled) as span:
output = self.get_next_output()
if isinstance(output, Exception):
span.set_error(
SpanError(
message="Error",
data={
"name": output.__class__.__name__,
"message": str(output),
},
)
)
raise output
# Convert apply_patch_call dicts to ResponseCustomToolCall
# to avoid Pydantic validation errors
converted_output = []
for item in output:
if isinstance(item, dict) and item.get("type") == "apply_patch_call":
import json
operation = item.get("operation", {})
operation_json = (
json.dumps(operation) if isinstance(operation, dict) else str(operation)
)
converted_item = ResponseCustomToolCall(
type="custom_tool_call",
name="apply_patch",
call_id=item.get("call_id") or "",
input=operation_json,
)
converted_output.append(converted_item)
else:
converted_output.append(item)
return ModelResponse(
output=converted_output,
usage=self.hardcoded_usage or Usage(),
response_id="resp-789",
)
async def stream_response(
self,
system_instructions: str | None,
input: str | list[TResponseInputItem],
model_settings: ModelSettings,
tools: list[Tool],
output_schema: AgentOutputSchemaBase | None,
handoffs: list[Handoff],
tracing: ModelTracing,
*,
previous_response_id: str | None = None,
conversation_id: str | None = None,
prompt: Any | None = None,
) -> AsyncIterator[TResponseStreamEvent]:
turn_args = {
"system_instructions": system_instructions,
"input": input,
"model_settings": model_settings,
"tools": tools,
"output_schema": output_schema,
"previous_response_id": previous_response_id,
"conversation_id": conversation_id,
}
if self.first_turn_args is None:
self.first_turn_args = turn_args.copy()
self.last_turn_args = turn_args
with generation_span(disabled=not self.tracing_enabled) as span:
output = self.get_next_output()
if isinstance(output, Exception):
span.set_error(
SpanError(
message="Error",
data={
"name": output.__class__.__name__,
"message": str(output),
},
)
)
raise output
response = get_response_obj(output, usage=self.hardcoded_usage)
sequence_number = 0
yield ResponseCreatedEvent(
type="response.created",
response=response,
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseInProgressEvent(
type="response.in_progress",
response=response,
sequence_number=sequence_number,
)
sequence_number += 1
for output_index, output_item in enumerate(output):
yield ResponseOutputItemAddedEvent(
type="response.output_item.added",
item=output_item,
output_index=output_index,
sequence_number=sequence_number,
)
sequence_number += 1
if isinstance(output_item, ResponseReasoningItem):
if output_item.summary:
for summary_index, summary in enumerate(output_item.summary):
yield ResponseReasoningSummaryPartAddedEvent(
type="response.reasoning_summary_part.added",
item_id=output_item.id,
output_index=output_index,
summary_index=summary_index,
part=AddedEventPart(text=summary.text, type=summary.type),
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseReasoningSummaryTextDeltaEvent(
type="response.reasoning_summary_text.delta",
item_id=output_item.id,
output_index=output_index,
summary_index=summary_index,
delta=summary.text,
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseReasoningSummaryTextDoneEvent(
type="response.reasoning_summary_text.done",
item_id=output_item.id,
output_index=output_index,
summary_index=summary_index,
text=summary.text,
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseReasoningSummaryPartDoneEvent(
type="response.reasoning_summary_part.done",
item_id=output_item.id,
output_index=output_index,
summary_index=summary_index,
part=DoneEventPart(text=summary.text, type=summary.type),
sequence_number=sequence_number,
)
sequence_number += 1
elif isinstance(output_item, ResponseFunctionToolCall):
yield ResponseFunctionCallArgumentsDeltaEvent(
type="response.function_call_arguments.delta",
item_id=output_item.call_id,
output_index=output_index,
delta=output_item.arguments,
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseFunctionCallArgumentsDoneEvent(
type="response.function_call_arguments.done",
item_id=output_item.call_id,
output_index=output_index,
arguments=output_item.arguments,
name=output_item.name,
sequence_number=sequence_number,
)
sequence_number += 1
elif isinstance(output_item, ResponseOutputMessage):
for content_index, content_part in enumerate(output_item.content or []):
if isinstance(content_part, ResponseOutputText):
yield ResponseContentPartAddedEvent(
type="response.content_part.added",
item_id=output_item.id,
output_index=output_index,
content_index=content_index,
part=content_part,
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseTextDeltaEvent(
type="response.output_text.delta",
item_id=output_item.id,
output_index=output_index,
content_index=content_index,
delta=content_part.text,
logprobs=[],
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseTextDoneEvent(
type="response.output_text.done",
item_id=output_item.id,
output_index=output_index,
content_index=content_index,
text=content_part.text,
logprobs=[],
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseContentPartDoneEvent(
type="response.content_part.done",
item_id=output_item.id,
output_index=output_index,
content_index=content_index,
part=content_part,
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseOutputItemDoneEvent(
type="response.output_item.done",
item=output_item,
output_index=output_index,
sequence_number=sequence_number,
)
sequence_number += 1
yield ResponseCompletedEvent(
type="response.completed",
response=response,
sequence_number=sequence_number,
)
def get_response_obj(
output: list[TResponseOutputItem],
response_id: str | None = None,
usage: Usage | None = None,
) -> Response:
return Response(
id=response_id or "resp-789",
created_at=123,
model="test_model",
object="response",
output=output,
tool_choice="none",
tools=[],
top_p=None,
parallel_tool_calls=False,
usage=ResponseUsage(
input_tokens=usage.input_tokens if usage else 0,
output_tokens=usage.output_tokens if usage else 0,
total_tokens=usage.total_tokens if usage else 0,
input_tokens_details=InputTokensDetails(cached_tokens=0),
output_tokens_details=OutputTokensDetails(reasoning_tokens=0),
),
)