Skip to content
71 changes: 71 additions & 0 deletions examples/model_providers/mid_run_steering.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Change a flight search in progress, then ask a separate follow-up.

Run with Python's default provider or pass --codex to use CodexProvider.
The flight data is fictional. Both providers use a live model.
"""

import argparse
import asyncio

from agents import Agent, ItemHelpers, MessageReceipt, RunConfig, Runner
from agents.decorators import tool
from agents.models.codex import CodexProvider


async def main(use_codex: bool) -> None:
search_started = asyncio.Event()
finish_search = asyncio.Event()

@tool
async def search_flights() -> str:
"""Search for flights from Seattle to Boston. Prices are per person."""
search_started.set()
await finish_search.wait()
return "Flight A: $220, one stop. Flight B: $310, nonstop. Flight C: $350, nonstop."

agent = Agent(
name="Flight assistant",
instructions="Call search_flights once. Use its results for the search and follow-ups.",
tools=[search_flights],
)
config = RunConfig(model_provider=CodexProvider()) if use_codex else RunConfig()
try:
stream = Runner.run_streamed(
agent, "Find flights from Seattle to Boston.", run_config=config
)

async def simulate_ui() -> tuple[MessageReceipt, MessageReceipt]:
# A real UI sends each message from its own event handler.
await search_started.wait()
try:
steering = stream.steer("Only show nonstop flights.")
follow_up = stream.queue("What would two seats on the cheapest nonstop cost?")
return steering, follow_up
finally:
finish_search.set()

ui = asyncio.create_task(simulate_ui())
try:
# The stream shows both answers. At the end, stream.final_output holds the last one.
async for event in stream.stream_events():
if (
event.type == "run_item_stream_event"
and event.item.type == "message_output_item"
):
print(ItemHelpers.text_message_output(event.item))
if search_started.is_set():
steering, follow_up = await ui
print("Steering:", steering.status)
print("Follow-up:", follow_up.status)
finally:
# The run can finish without calling the search tool.
ui.cancel()
await asyncio.gather(ui, return_exceptions=True)
finally:
await config.model_provider.aclose()


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--codex", action="store_true")
asyncio.run(main(parser.parse_args().codex))
4 changes: 4 additions & 0 deletions src/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@
RunErrorHandlerResult,
RunErrorHandlers,
)
from .run_inbox import MessageOutcome, MessageReceipt, RunInbox
from .run_state import RunState
from .stream_events import (
AgentUpdatedStreamEvent,
Expand Down Expand Up @@ -520,6 +521,9 @@ def enable_verbose_stdout_logging() -> None:
"RunBudget",
"RunBudgetError",
"RunConfig",
"RunInbox",
"MessageOutcome",
"MessageReceipt",
"OutputGuardrailBlockedMessageArgs",
"OutputGuardrailBlockedMessageFormatter",
"ToolNameCollisionPolicy",
Expand Down
35 changes: 26 additions & 9 deletions src/agents/handoffs/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
RunItem,
ToolApprovalItem,
TResponseInputItem,
_copy_observer,
_CopyObserver,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -111,11 +113,8 @@ def _nest_handoff_history_with_provenance(
) -> tuple[HandoffInputData, tuple[NestedHistoryOwnedItem, ...]]:
"""Return nested input and exact provenance for items moved into default history."""

normalized_history = _normalize_input_history(handoff_input_data.input_history)
flattened_history = [
_strip_transcript_item_metadata(item)
for item in _flatten_nested_history_messages(normalized_history)
]
observe = _copy_observer.get()
flattened_history = _flatten_nested_history_messages(handoff_input_data, observe)

# Partition items between summary segments and lossless model input while retaining order.
normalized_pre_items: list[tuple[TResponseInputItem, bool, RunItem]] = []
Expand All @@ -135,6 +134,9 @@ def _nest_handoff_history_with_provenance(
normalized_new_items.append((plain_input, forward_verbatim, run_item))

normalized_items = normalized_pre_items + normalized_new_items
if observe is not None:
for plain_input, _, run_item in normalized_items:
observe(run_item, plain_input)

owned_items: list[NestedHistoryOwnedItem] = []
if history_mapper is not None:
Expand All @@ -147,6 +149,9 @@ def _nest_handoff_history_with_provenance(
)

copied_history = [deepcopy(item) for item in history_items]
if observe is not None:
for source, target in zip(history_items, copied_history, strict=True):
observe(source, target)
owned_items = [
replace(
owned_item,
Expand Down Expand Up @@ -464,15 +469,27 @@ def _stringify_content(content: Any) -> str:


def _flatten_nested_history_messages(
items: list[TResponseInputItem],
data: HandoffInputData,
observe: _CopyObserver | None,
) -> list[TResponseInputItem]:
flattened: list[TResponseInputItem] = []
for item in items:
history = data.input_history
# A bare string cannot identify an occurrence without its surrounding inputs.
sources = (data,) if isinstance(history, str) else history
for source, item in zip(sources, _normalize_input_history(history), strict=True):
nested_transcript = _extract_nested_history_transcript(item)
if nested_transcript is not None:
flattened.extend(nested_transcript)
# A user quote recovered from an assistant summary is history.
for message in nested_transcript:
cleaned = _strip_transcript_item_metadata(message)
if observe is not None:
observe(None, cleaned)
flattened.append(cleaned)
continue
flattened.append(deepcopy(item))
cleaned = _strip_transcript_item_metadata(deepcopy(item))
if observe is not None:
observe(source, cleaned)
flattened.append(cleaned)
return flattened


Expand Down
50 changes: 41 additions & 9 deletions src/agents/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import abc
import json
import weakref
from collections.abc import Mapping
from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias, TypeVar, cast
from uuid import uuid4
Expand Down Expand Up @@ -73,6 +75,30 @@
if TYPE_CHECKING:
from .agent import Agent

# A handoff filter can convert a message before editing or moving it. Record
# these copies at the conversion boundary without adding fields to model input.
_CopyObserver = Callable[[object, object], None]
_copy_observer: ContextVar[_CopyObserver | None] = ContextVar(
"handoff_input_copy_observer", default=None
)


@contextmanager
def _observe_input_copies(observer: _CopyObserver | None) -> Iterator[None]:
def notify(source: object, target: object) -> None:
if observer is not None:
observer(source, target)

token = _copy_observer.set(notify if observer is not None else None)
try:
yield
finally:
# Child tasks may have inherited the callback. Release the messages
# and stop accepting copies as soon as the filter returns.
observer = None
_copy_observer.reset(token)


TResponse = Response
"""A type alias for the Response type from the OpenAI SDK."""

Expand Down Expand Up @@ -150,7 +176,10 @@ def _get_agent_via_weakref(self, attr_name: str, ref_name: str) -> Any:

def to_input_item(self) -> TResponseInputItem:
"""Converts this item into an input item suitable for passing to the model."""
return _output_item_to_input_item(self.raw_item)
result = _output_item_to_input_item(self.raw_item)
if (observe := _copy_observer.get()) is not None:
observe(self, result)
return result


@dataclass
Expand Down Expand Up @@ -814,14 +843,17 @@ def input_to_new_input_list(
cls, input: str | list[TResponseInputItem]
) -> list[TResponseInputItem]:
"""Converts a string or list of input items into a list of input items."""
observe = _copy_observer.get()
if isinstance(input, str):
return [
{
"content": input,
"role": "user",
}
]
return cast(list[TResponseInputItem], _to_dump_compatible(input))
message: TResponseInputItem = {"content": input, "role": "user"}
if observe is not None:
observe(input, message)
return [message]
result = cast(list[TResponseInputItem], _to_dump_compatible(input))
if observe is not None:
for source, target in zip(input, result, strict=True):
observe(source, target)
return result

@classmethod
def text_message_outputs(cls, items: list[RunItem]) -> str:
Expand Down
Loading
Loading