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 | class OpenAIResponsesModel(Model):
"""
Implementation of `Model` that uses the OpenAI Responses API.
"""
def __init__(
self,
model: str | ChatModel,
openai_client: AsyncOpenAI,
) -> None:
print(f"\nDEBUG: OpenAIResponsesModel initialized with model: {model}\n")
self.model = model
self._client = openai_client
# Track interaction counter and token totals for cli display
self.interaction_counter = 0
self.total_input_tokens = 0
self.total_output_tokens = 0
self.total_reasoning_tokens = 0
self.agent_name = "Agent" # Default name
def set_agent_name(self, name: str) -> None:
"""Set the agent name for CLI display purposes."""
self.agent_name = name
def _non_null_or_not_given(self, value: Any) -> Any:
return value if value is not None else NOT_GIVEN
async def get_response(
self,
system_instructions: str | None,
input: str | list[TResponseInputItem],
model_settings: ModelSettings,
tools: list[Tool],
output_schema: AgentOutputSchema | None,
handoffs: list[Handoff],
tracing: ModelTracing,
) -> ModelResponse:
# Increment the interaction counter for CLI display
self.interaction_counter += 1
# --- Snapshot inputs for token accounting parity with IN: ---
sys_tokens = 0
tool_defs_tokens = 0
try:
# Count system tokens dynamically
if system_instructions:
try:
from cai.sdk.agents.models.openai_chatcompletions import count_tokens_with_tiktoken as _ct
sys_tokens, _ = _ct(str(system_instructions))
except Exception:
sys_tokens = len(str(system_instructions)) // 4
# Count tool definition tokens from params_json_schema
if tools:
try:
import json as _json
import tiktoken as _t
try:
enc = _t.get_encoding("cl100k_base")
except Exception:
enc = _t.get_encoding("gpt2")
for tool in tools:
schema = getattr(tool, "params_json_schema", None)
if schema:
as_str = _json.dumps(schema)
tool_defs_tokens += len(enc.encode(as_str)) if enc else len(as_str) // 4
except Exception:
pass
self._last_request_breakdown = {
"system_tokens": int(sys_tokens or 0),
"tool_definitions_tokens": int(tool_defs_tokens or 0),
"messages_breakdown": {"user": 0, "assistant": 0, "tool_calls": 0, "tool_results": 0},
}
except Exception:
self._last_request_breakdown = None
with response_span(disabled=tracing.is_disabled()) as span_response:
try:
async with model_wait_hints():
response = await self._fetch_response(
system_instructions,
input,
model_settings,
tools,
output_schema,
handoffs,
stream=False,
)
if _debug.DONT_LOG_MODEL_DATA:
logger.debug("LLM responded")
else:
logger.debug(
"LLM resp:\n"
f"{json.dumps([x.model_dump() for x in response.output], indent=2)}\n"
)
usage = (
Usage(
requests=1,
input_tokens=response.usage.input_tokens,
output_tokens=response.usage.output_tokens,
total_tokens=response.usage.total_tokens,
)
if response.usage
else Usage()
)
if tracing.include_data():
span_response.span_data.response = response
span_response.span_data.input = input
# Print the agent message for CLI display
from cai.util import cli_print_agent_messages
try:
# Create a message-like object to display
message_obj = type(
"ResponseWrapper",
(),
{
"content": "\n".join(
[
str(item.get("content", ""))
if hasattr(item, "get")
else str(getattr(item, "text", ""))
for item in response.output
if hasattr(item, "get") or hasattr(item, "text")
]
),
"tool_calls": [
type(
"ToolCallWrapper",
(),
{"name": item.name, "arguments": item.arguments},
)
for item in response.output
if hasattr(item, "name") and hasattr(item, "arguments")
],
},
)
cli_print_agent_messages(
agent_name=getattr(self, "agent_name", "Agent"),
message=message_obj,
counter=getattr(self, "interaction_counter", 0),
model=str(self.model),
debug=False,
interaction_input_tokens=usage.input_tokens,
interaction_output_tokens=usage.output_tokens,
interaction_reasoning_tokens=0,
total_input_tokens=getattr(self, "total_input_tokens", 0),
total_output_tokens=getattr(self, "total_output_tokens", 0),
total_reasoning_tokens=getattr(self, "total_reasoning_tokens", 0),
interaction_cost=None,
total_cost=None,
)
# Update token totals
self.total_input_tokens += usage.input_tokens
self.total_output_tokens += usage.output_tokens
# Store actual tokens to align usage metrics with IN:
try:
self._last_request_actual_input_tokens = int(usage.input_tokens or 0)
# Compute overhead to reconcile totals
br = self._last_request_breakdown or {}
sys_t = int(br.get("system_tokens", 0) or 0)
tool_t = int(br.get("tool_definitions_tokens", 0) or 0)
msg_map = br.get("messages_breakdown", {}) or {}
msg_sum = sum(int(v or 0) for v in msg_map.values())
known = sys_t + tool_t + msg_sum
overhead = int(self._last_request_actual_input_tokens) - known
self._last_request_breakdown_overhead = int(overhead) if overhead > 0 else 0
except Exception:
self._last_request_breakdown_overhead = 0
except Exception as e:
logger.error(f"Error printing agent message: {e}")
except Exception as e:
span_response.set_error(
SpanError(
message="Error getting response",
data={
"error": str(e) if tracing.include_data() else e.__class__.__name__,
},
)
)
request_id = e.request_id if isinstance(e, APIStatusError) else None
logger.error(f"Error getting response: {e}. (request_id: {request_id})")
raise
return ModelResponse(
output=response.output,
usage=usage,
referenceable_id=response.id,
)
async def stream_response(
self,
system_instructions: str | None,
input: str | list[TResponseInputItem],
model_settings: ModelSettings,
tools: list[Tool],
output_schema: AgentOutputSchema | None,
handoffs: list[Handoff],
tracing: ModelTracing,
) -> AsyncIterator[ResponseStreamEvent]:
"""
Yields a partial message as it is generated, as well as the usage information.
"""
# Increment the interaction counter for CLI display
self.interaction_counter += 1
with response_span(disabled=tracing.is_disabled()) as span_response:
stream_wait_hints = ModelStreamWaitHints()
await stream_wait_hints.start()
try:
stream = await self._fetch_response(
system_instructions,
input,
model_settings,
tools,
output_schema,
handoffs,
stream=True,
)
final_response: Response | None = None
async for chunk in stream:
await stream_wait_hints.stop()
if isinstance(chunk, ResponseCompletedEvent):
final_response = chunk.response
yield chunk
if final_response and tracing.include_data():
span_response.span_data.response = final_response
span_response.span_data.input = input
# Print the agent message for CLI display
from cai.util import cli_print_agent_messages
try:
# Create a message-like object to display
message_obj = type(
"ResponseWrapper",
(),
{
"content": "\n".join(
[
str(item.get("content", ""))
if hasattr(item, "get")
else str(getattr(item, "text", ""))
for item in final_response.output
if hasattr(item, "get") or hasattr(item, "text")
]
),
"tool_calls": [
type(
"ToolCallWrapper",
(),
{"name": item.name, "arguments": item.arguments},
)
for item in final_response.output
if hasattr(item, "name") and hasattr(item, "arguments")
],
},
)
cli_print_agent_messages(
agent_name=getattr(self, "agent_name", "Agent"),
message=message_obj,
counter=getattr(self, "interaction_counter", 0),
model=str(self.model),
debug=False,
interaction_input_tokens=final_response.usage.input_tokens,
interaction_output_tokens=final_response.usage.output_tokens,
interaction_reasoning_tokens=0,
total_input_tokens=getattr(self, "total_input_tokens", 0),
total_output_tokens=getattr(self, "total_output_tokens", 0),
total_reasoning_tokens=getattr(self, "total_reasoning_tokens", 0),
interaction_cost=None,
total_cost=None,
)
# Update token totals
self.total_input_tokens += final_response.usage.input_tokens
self.total_output_tokens += final_response.usage.output_tokens
# Store actual tokens to align usage metrics with IN: for streamed path
try:
self._last_request_actual_input_tokens = int(final_response.usage.input_tokens or 0)
br = self._last_request_breakdown or {}
sys_t = int(br.get("system_tokens", 0) or 0)
tool_t = int(br.get("tool_definitions_tokens", 0) or 0)
msg_map = br.get("messages_breakdown", {}) or {}
msg_sum = sum(int(v or 0) for v in msg_map.values())
known = sys_t + tool_t + msg_sum
overhead = int(self._last_request_actual_input_tokens) - known
self._last_request_breakdown_overhead = int(overhead) if overhead > 0 else 0
except Exception:
self._last_request_breakdown_overhead = 0
except Exception as e:
logger.error(f"Error printing agent message: {e}")
except Exception as e:
span_response.set_error(
SpanError(
message="Error streaming response",
data={
"error": str(e) if tracing.include_data() else e.__class__.__name__,
},
)
)
logger.error(f"Error streaming response: {e}")
raise
finally:
try:
await stream_wait_hints.stop()
except Exception:
pass
@overload
async def _fetch_response(
self,
system_instructions: str | None,
input: str | list[TResponseInputItem],
model_settings: ModelSettings,
tools: list[Tool],
output_schema: AgentOutputSchema | None,
handoffs: list[Handoff],
stream: Literal[True],
) -> AsyncStream[ResponseStreamEvent]: ...
@overload
async def _fetch_response(
self,
system_instructions: str | None,
input: str | list[TResponseInputItem],
model_settings: ModelSettings,
tools: list[Tool],
output_schema: AgentOutputSchema | None,
handoffs: list[Handoff],
stream: Literal[False],
) -> Response: ...
async def _fetch_response(
self,
system_instructions: str | None,
input: str | list[TResponseInputItem],
model_settings: ModelSettings,
tools: list[Tool],
output_schema: AgentOutputSchema | None,
handoffs: list[Handoff],
stream: Literal[True] | Literal[False] = False,
) -> Response | AsyncStream[ResponseStreamEvent]:
list_input = ItemHelpers.input_to_new_input_list(input)
parallel_tool_calls = (
True
if model_settings.parallel_tool_calls and tools and len(tools) > 0
else False
if model_settings.parallel_tool_calls is False
else NOT_GIVEN
)
tool_choice = Converter.convert_tool_choice(model_settings.tool_choice)
converted_tools = Converter.convert_tools(tools, handoffs)
response_format = Converter.get_response_format(output_schema)
if _debug.DONT_LOG_MODEL_DATA:
logger.debug("Calling LLM")
else:
logger.debug(
f"Calling LLM {self.model} with input:\n"
f"{json.dumps(list_input, indent=2)}\n"
f"Tools:\n{json.dumps(converted_tools.tools, indent=2)}\n"
f"Stream: {stream}\n"
f"Tool choice: {tool_choice}\n"
f"Response format: {response_format}\n"
)
return await self._client.responses.create(
instructions=self._non_null_or_not_given(system_instructions),
model=self.model,
input=list_input,
include=converted_tools.includes,
tools=converted_tools.tools,
temperature=self._non_null_or_not_given(model_settings.temperature),
top_p=self._non_null_or_not_given(model_settings.top_p),
truncation=self._non_null_or_not_given(model_settings.truncation),
max_output_tokens=self._non_null_or_not_given(model_settings.max_tokens),
tool_choice=tool_choice,
parallel_tool_calls=parallel_tool_calls,
stream=stream,
extra_headers=_HEADERS,
text=response_format,
store=self._non_null_or_not_given(model_settings.store),
)
def _get_client(self) -> AsyncOpenAI:
if self._client is None:
api_key = resolve_llm_openai_compatible_api_key(str(self.model))
if not api_key:
raise UserError(
"Missing API key for selected model. "
"For alias-family models (alias*/cai*/csi*), set ALIAS_API_KEY. "
"For OpenAI models, set OPENAI_API_KEY."
)
self._client = AsyncOpenAI(api_key=api_key)
return self._client
|