Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@
ToolNameCollisionPolicy,
ToolNotFoundBehavior,
)
from .run_budget import RunBudget, RunBudgetError
from .run_context import AgentHookContext, RunContextWrapper, TContext
from .run_error_handlers import (
RunErrorData,
Expand Down Expand Up @@ -495,6 +496,8 @@ def enable_verbose_stdout_logging() -> None:
"RunResult",
"RunResultStreaming",
"ResponsesWebSocketSession",
"RunBudget",
"RunBudgetError",
"RunConfig",
"OutputGuardrailBlockedMessageArgs",
"OutputGuardrailBlockedMessageFormatter",
Expand Down
5 changes: 5 additions & 0 deletions src/agents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,9 @@ async def _run_agent_impl(context: ToolContext, input_json: str) -> Any:
resolved_run_config = run_config
if resolved_run_config is None and isinstance(context, ToolContext):
resolved_run_config = context.run_config
if resolved_run_config is not None and resolved_run_config.budget is not None:
resolved_run_config = copy.copy(resolved_run_config)
resolved_run_config.budget = None
tool_state_scope_id = get_agent_tool_state_scope(context)
if isinstance(context, ToolContext):
# Use a fresh ToolContext to avoid sharing approval state with parent runs.
Expand Down Expand Up @@ -1158,6 +1161,8 @@ async def close_stream() -> None:

return run_result.final_output

# Keep the live policy with the implementation, which survives tool rebinding.
cast(Any, _run_agent_impl).__agents_run_config__ = run_config
run_agent_tool = _build_wrapped_function_tool(
name=tool_name_resolved,
description=tool_description_resolved,
Expand Down
2 changes: 2 additions & 0 deletions src/agents/extensions/models/any_llm_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,7 @@ async def _get_response_via_responses(
# The request completed, so it counts even when the provider omits usage.
else Usage(requests=1)
)
usage._total_missing = response.usage is None or response.usage.total_tokens is None

span_response.span_data.usage = model_usage_to_span_usage(usage)

Expand Down Expand Up @@ -672,6 +673,7 @@ async def _get_response_via_chat(
# The request completed, so it counts even when the provider omits usage.
else Usage(requests=1)
)
usage._total_missing = response.usage is None or response.usage.total_tokens is None

# Some providers signal a filtered non-streaming completion only through
# finish_reason="content_filter" and an otherwise empty message. Preserve
Expand Down
1 change: 1 addition & 0 deletions src/agents/extensions/models/litellm_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ async def get_response(
# The request completed, so it counts even when the provider omits usage.
else Usage(requests=1)
)
usage._total_missing = response_usage is None or response_usage.total_tokens is None
else:
usage = Usage(requests=1)
logger.warning("No usage information returned from Litellm")
Expand Down
10 changes: 8 additions & 2 deletions src/agents/memory/openai_responses_compaction_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,8 +485,14 @@ async def _run_compaction_locked(
compacted = await self.client.responses.compact(**compact_kwargs)

compacted_usage = getattr(compacted, "usage", None)
if wrapper is not None and compacted_usage is not None:
wrapper.usage.add(_response_usage_to_usage(compacted_usage))
if wrapper is not None:
usage = (
_response_usage_to_usage(compacted_usage) if compacted_usage is not None else None
)
if wrapper._budget is not None:
wrapper._budget.observe(usage)
if usage is not None:
wrapper.usage.add(usage)

output_items = redact_items(
_strip_orphaned_assistant_ids(
Expand Down
6 changes: 5 additions & 1 deletion src/agents/models/chatcmpl_stream_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1369,7 +1369,7 @@ def _build_response_usage(usage: CompletionUsage | None) -> ResponseUsage | None
"""Convert the streamed provider usage into a Responses usage payload."""
if usage is None:
return None
return ResponseUsage(
result = ResponseUsage(
input_tokens=usage.prompt_tokens or 0,
output_tokens=usage.completion_tokens or 0,
total_tokens=usage.total_tokens or 0,
Expand All @@ -1386,3 +1386,7 @@ def _build_response_usage(usage: CompletionUsage | None) -> ResponseUsage | None
cache_write_tokens=_cache_write_tokens(usage.prompt_tokens_details),
),
)
if usage.total_tokens is None:
# Keep the public numeric default without reporting a measured zero.
object.__setattr__(result, "_agents_sdk_total_missing", True)
return result
1 change: 1 addition & 0 deletions src/agents/models/openai_chatcompletions.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@ async def get_response(
# The request completed, so it counts even when the provider omits usage.
else Usage(requests=1)
)
usage._total_missing = response.usage is None or response.usage.total_tokens is None

# Record the request and token usage on the span before the terminal
# branches below, so a ModelBehaviorError raised for a truncated empty
Expand Down
24 changes: 16 additions & 8 deletions src/agents/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
from .memory.resumable_session import ResumableSession
from .models._run_context import ModelToolHooks
from .result import RunResult, RunResultStreaming
from .run_budget import _check_resume, _prepare_budget
from .run_config import (
DEFAULT_MAX_TURNS,
CallModelData,
Expand Down Expand Up @@ -723,6 +724,7 @@ async def _run_impl(
run_state: RunState[TContext] | None = (
cast(RunState[TContext], input) if is_resumed_state else None
)
budget = _prepare_budget(run_config, starting_agent, run_state)
resolved_reasoning_item_id_policy: ReasoningItemIdPolicy | None = (
run_config.reasoning_item_id_policy
if run_config.reasoning_item_id_policy is not None
Expand Down Expand Up @@ -766,6 +768,7 @@ async def _run_impl(
)
context_wrapper._resolve_function_approval_owners(starting_agent)
validate_resume_policy(run_state, context_wrapper, run_config)
await _check_resume(run_state, run_config.budget, context_wrapper)
context = context_wrapper.context

reject_unrecoverable_terminal_state(run_state)
Expand All @@ -792,7 +795,7 @@ async def _run_impl(
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
)
context_wrapper = ensure_context_wrapper(context)
context_wrapper = ensure_context_wrapper(context)._for_new_root(budget)
if isinstance(session, ResumableRun):
await session.begin(
input,
Expand Down Expand Up @@ -2794,6 +2797,9 @@ def run_streamed(
else contextlib.nullcontext(),
):
input = _prepare_private_input(starting_agent, input, run_config, kwargs)
budget = _prepare_budget(
run_config, starting_agent, input if isinstance(input, RunState) else None
)
# Handle RunState input
is_resumed_state = isinstance(input, RunState)
run_state: RunState[TContext] | None = None
Expand Down Expand Up @@ -2863,7 +2869,7 @@ def run_streamed(
previous_response_id=previous_response_id,
auto_previous_response_id=auto_previous_response_id,
)
context_wrapper = ensure_context_wrapper(context)
context_wrapper = ensure_context_wrapper(context)._for_new_root(budget)
context_wrapper._resolve_function_approval_owners(starting_agent)
set_agent_tool_state_scope(context_wrapper, uuid4().hex)
# input_for_state is the same as input_for_result here
Expand Down Expand Up @@ -3034,8 +3040,10 @@ async def run_loop() -> None:
if run_config.tracing_disabled
else contextlib.nullcontext(),
):
if isinstance(session, ResumableRun):
try:
try:
if is_resumed_state and run_state is not None:
await _check_resume(run_state, run_config.budget, context_wrapper)
if isinstance(session, ResumableRun):
await session.begin(
input,
ModelToolHooks(
Expand All @@ -3044,10 +3052,10 @@ async def run_loop() -> None:
run_config.tool_not_found_behavior,
)
session.bind_state(run_state)
except BaseException:
streamed_result.is_complete = True
streamed_result._event_queue.put_nowait(QueueCompleteSentinel())
raise
except BaseException:
streamed_result.is_complete = True
streamed_result._event_queue.put_nowait(QueueCompleteSentinel())
raise
configuration_agent = (
run_state._current_agent
if run_state is not None and run_state._current_agent is not None
Expand Down
Loading
Loading