8878 lines
363 KiB
Python
8878 lines
363 KiB
Python
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import importlib.util
|
||
import json
|
||
import re
|
||
import sys
|
||
import time
|
||
import uuid
|
||
import warnings
|
||
from collections.abc import (
|
||
AsyncGenerator,
|
||
AsyncIterable,
|
||
AsyncIterator,
|
||
Callable,
|
||
Iterable,
|
||
Iterator,
|
||
Mapping,
|
||
Sequence,
|
||
)
|
||
from contextlib import asynccontextmanager
|
||
from dataclasses import dataclass, field, replace
|
||
from datetime import UTC, datetime, timedelta
|
||
from decimal import Decimal
|
||
from types import NoneType, SimpleNamespace
|
||
from typing import Any, Literal, cast
|
||
from unittest.mock import patch
|
||
|
||
import anyio
|
||
import pytest
|
||
from pydantic import TypeAdapter
|
||
|
||
from pydantic_ai import (
|
||
Agent,
|
||
AgentStreamEvent,
|
||
BinaryContent,
|
||
BinaryImage,
|
||
CodeExecutionTool,
|
||
DocumentUrl,
|
||
ExternalToolset,
|
||
FunctionToolset,
|
||
ImageGenerationTool,
|
||
ImageGenerator,
|
||
ModelMessage,
|
||
ModelRequest,
|
||
ModelRequestTimeout,
|
||
ModelResponse,
|
||
MultiModalContent,
|
||
NativeOutput,
|
||
PartDeltaEvent,
|
||
PartStartEvent,
|
||
PendingModelResponse,
|
||
PrefixedToolset,
|
||
PromptedOutput,
|
||
RequestUsage,
|
||
RetryFeedbackPart,
|
||
RetryInfo,
|
||
RunContext,
|
||
RunTimedOut,
|
||
RunUsage,
|
||
SystemPromptPart,
|
||
TextPart,
|
||
Tool,
|
||
ToolAvailabilityDeltaPart,
|
||
ToolCallPart,
|
||
ToolReturn,
|
||
ToolReturnPart,
|
||
ToolsetTool,
|
||
UserContent,
|
||
UserPromptPart,
|
||
WebSearchTool,
|
||
WebSearchUserLocation,
|
||
)
|
||
from pydantic_ai._warnings import PydanticAIDeprecationWarning
|
||
from pydantic_ai.agent import WrapperAgent
|
||
from pydantic_ai.capabilities import (
|
||
BatchModelRequests,
|
||
Capability,
|
||
DynamicCapability,
|
||
HandleDeferredToolCalls,
|
||
Hooks,
|
||
ImageGeneration,
|
||
Instrumentation,
|
||
ModelFallback,
|
||
NativeTool,
|
||
PrepareTools,
|
||
ProcessEventStream,
|
||
ResolveModelId,
|
||
RetryOnModelErrors,
|
||
SelectModel,
|
||
SetToolMetadata,
|
||
Toolset,
|
||
WrapperCapability,
|
||
durable_operation,
|
||
)
|
||
from pydantic_ai.capabilities.abstract import AbstractCapability, CapabilityOrdering
|
||
from pydantic_ai.capabilities.combined import CombinedCapability
|
||
from pydantic_ai.durable_exec._operation import ToolsetCallToolId
|
||
from pydantic_ai.exceptions import (
|
||
ContentFilterError,
|
||
FallbackExceptionGroup,
|
||
IncompleteToolCall,
|
||
ModelAPIError,
|
||
ModelAuthenticationError,
|
||
ModelContextWindowExceededError,
|
||
ModelHTTPError,
|
||
ModelNotFoundError,
|
||
ModelOverloadedError,
|
||
ModelQuotaExceededError,
|
||
ModelRateLimitError,
|
||
ModelRetry,
|
||
ModelTimeoutError,
|
||
ModelUnavailableError,
|
||
SkipModelRequest,
|
||
UnexpectedModelBehavior,
|
||
UsageLimitExceeded,
|
||
UserError,
|
||
)
|
||
from pydantic_ai.images import (
|
||
ImageGenerationInput,
|
||
ImageGenerationResult,
|
||
ImageGenerationSettings,
|
||
TestImageGenerationModel,
|
||
)
|
||
from pydantic_ai.messages import ModelRequestAttempt, UploadedFile
|
||
from pydantic_ai.models import (
|
||
Model,
|
||
ModelRequestContext,
|
||
ModelRequestParameters,
|
||
ModelResolutionContext,
|
||
ModelSelectionContext,
|
||
StreamedResponse,
|
||
infer_model,
|
||
)
|
||
from pydantic_ai.models._batch_model import BatchPool
|
||
from pydantic_ai.models.batch import Batch, EncodedBatchRequest
|
||
from pydantic_ai.models.fallback import FallbackModel
|
||
from pydantic_ai.models.function import AgentInfo, DeltaToolCall, DeltaToolCalls, FunctionModel, StreamFunctionDef
|
||
from pydantic_ai.models.instrumented import InstrumentationSettings
|
||
from pydantic_ai.models.test import TestModel
|
||
from pydantic_ai.models.wrapper import WrapperModel
|
||
from pydantic_ai.profiles import ModelProfile
|
||
from pydantic_ai.realtime import RealtimeModel, RealtimeModelProfile, RealtimeModelSettings
|
||
from pydantic_ai.realtime.codec import RealtimeCodecEvent, RealtimeConnection, RealtimeInput, ResponseDone
|
||
from pydantic_ai.run import AgentRunResult
|
||
from pydantic_ai.settings import ModelSettings
|
||
from pydantic_ai.tools import DeferredToolRequests, ToolDefinition
|
||
from pydantic_ai.toolsets._dynamic import DynamicToolset
|
||
from pydantic_ai.toolsets.abstract import AbstractToolset
|
||
from pydantic_ai.toolsets.external import TOOL_SCHEMA_VALIDATOR
|
||
from pydantic_ai.usage import UsageLimits
|
||
from pydantic_ai.workspaces import CommandResult, Workspace, WorkspaceBackend, WorkspaceRef, WrapperWorkspace
|
||
from pydantic_graph import GraphBuilder, StepContext
|
||
from tests.function_model_prefix import FALLBACK_REWINDS, TOOLS_CHANGE_MID_RUN
|
||
|
||
from ..._inline_snapshot import snapshot
|
||
from ...batch_utils import FAST_BATCH_SETTINGS, FAST_POLLING, FailingBatchTestModel, SlowBatchTestModel
|
||
from ...continuation_utils import ScriptedContinuationModel, StreamSegment, scripted_response
|
||
from ...realtime_connections import InferredConnection
|
||
from ..span_utils import drop_fastmcp_client_spans
|
||
|
||
try:
|
||
from temporalio import activity, workflow
|
||
from temporalio.activity import _Definition as ActivityDefinition # pyright: ignore[reportPrivateUsage]
|
||
from temporalio.api.enums.v1 import EventType
|
||
from temporalio.client import Client, WorkflowFailureError, WorkflowHistory
|
||
from temporalio.common import RetryPolicy
|
||
from temporalio.exceptions import ActivityError, ApplicationError
|
||
from temporalio.worker import (
|
||
Interceptor,
|
||
Replayer,
|
||
StartActivityInput,
|
||
UnsandboxedWorkflowRunner,
|
||
Worker,
|
||
WorkflowInboundInterceptor,
|
||
WorkflowInterceptorClassInput,
|
||
WorkflowOutboundInterceptor,
|
||
)
|
||
from temporalio.workflow import ActivityConfig, ActivityHandle, ChildWorkflowConfig
|
||
|
||
import pydantic_ai.durable_exec.temporal._toolset as temporal_toolset
|
||
from pydantic_ai.durable_exec._toolset import unwrap_tool_call_result
|
||
from pydantic_ai.durable_exec.temporal import (
|
||
AgentPlugin,
|
||
PydanticAIPlugin,
|
||
TemporalAgent, # pyright: ignore[reportDeprecated]
|
||
TemporalDurability,
|
||
TemporalWrapperToolset,
|
||
)
|
||
from pydantic_ai.durable_exec.temporal._durability import worker_registrations
|
||
from pydantic_ai.durable_exec.temporal._function_toolset import (
|
||
TemporalFunctionToolset,
|
||
temporalize_function_toolset,
|
||
)
|
||
from pydantic_ai.durable_exec.temporal._run_context import TemporalRunContext
|
||
from pydantic_ai.durable_exec.temporal._toolset import CallToolParams
|
||
|
||
except ImportError: # pragma: lax no cover
|
||
pytest.skip('temporal not installed', allow_module_level=True)
|
||
|
||
|
||
# The 3.14 durable-exec CI leg takes this skip; every other leg falls through. `lax` rather than
|
||
# plain because which of the two arms a run measures depends on its Python version.
|
||
if sys.version_info >= (3, 14): # pragma: lax no cover
|
||
pytest.skip(
|
||
'temporalio sandbox is incompatible with Python 3.14: '
|
||
'sandbox module state accumulates across validation cycles causing import failures after ~22 workflows '
|
||
'(remove when https://github.com/temporalio/sdk-python/issues/1326 closes)',
|
||
allow_module_level=True,
|
||
)
|
||
|
||
try:
|
||
from logfire.testing import CaptureLogfire
|
||
except ImportError: # pragma: lax no cover
|
||
pytest.skip('logfire not installed', allow_module_level=True)
|
||
|
||
try:
|
||
from fastmcp.client.transports import StdioTransport
|
||
|
||
from pydantic_ai.mcp import MCPToolset
|
||
except ImportError: # pragma: lax no cover
|
||
pytest.skip('mcp not installed', allow_module_level=True)
|
||
|
||
try:
|
||
from pydantic_ai.models.openai import OpenAIChatModel
|
||
from pydantic_ai.providers.openai import OpenAIProvider
|
||
except ImportError: # pragma: lax no cover
|
||
pytest.skip('openai not installed', allow_module_level=True)
|
||
|
||
|
||
with workflow.unsafe.imports_passed_through():
|
||
# Workaround for a race condition when running `logfire.info` inside an activity with attributes to serialize and pandas importable:
|
||
# AttributeError: partially initialized module 'pandas' has no attribute '_pandas_parser_CAPI' (most likely due to a circular import)
|
||
try:
|
||
import pandas # pyright: ignore[reportUnusedImport] # noqa: F401
|
||
except ImportError: # pragma: lax no cover
|
||
pass
|
||
|
||
# https://github.com/temporalio/sdk-python/blob/3244f8bffebee05e0e7efefb1240a75039903dda/tests/test_client.py#L112C1-L113C1
|
||
|
||
from ..._inline_snapshot import snapshot
|
||
|
||
# Loads `vcr`, which Temporal doesn't like without passing through the import
|
||
from ...conftest import IsDatetime, IsInt, IsList, IsSameStr, IsStr
|
||
from ...workspace_fakes import FakeWorkspace
|
||
from ..decision_spans import ShipIt, ShipItDecisionModel, decide_span_lineage
|
||
from ..preamble_text import (
|
||
RunAndStreamResult,
|
||
StructuredOutput,
|
||
plain_run_and_stream,
|
||
preamble_text_agents,
|
||
preamble_text_before_output_tool,
|
||
run_and_stream,
|
||
)
|
||
|
||
# `_shared` loads the same sandbox-sensitive modules, so import it passed-through as well.
|
||
from ._shared import (
|
||
BASE_ACTIVITY_CONFIG,
|
||
TASK_QUEUE,
|
||
Answer,
|
||
BasicSpan,
|
||
Deps,
|
||
DurableCheckpointEvent,
|
||
DurableUnserializableEvent,
|
||
DynamicToolsetDeps,
|
||
Response,
|
||
StreamDurableAgentWorkflow,
|
||
_durability_fn_model, # pyright: ignore[reportPrivateUsage]
|
||
_durability_model_fn, # pyright: ignore[reportPrivateUsage]
|
||
_durability_reveal_tool, # pyright: ignore[reportPrivateUsage]
|
||
_scheduled_activity_count, # pyright: ignore[reportPrivateUsage]
|
||
_select_builtin_tool, # pyright: ignore[reportPrivateUsage]
|
||
_stream_durable_agent, # pyright: ignore[reportPrivateUsage]
|
||
_stream_events_collected, # pyright: ignore[reportPrivateUsage]
|
||
_stream_fn_model, # pyright: ignore[reportPrivateUsage]
|
||
_stream_model_events_in_activity, # pyright: ignore[reportPrivateUsage]
|
||
_workflow_failure_cause, # pyright: ignore[reportPrivateUsage]
|
||
code_execution_builtin_model,
|
||
event_stream_handler,
|
||
get_country,
|
||
get_weather,
|
||
http_client,
|
||
model,
|
||
scheduled_activity_types,
|
||
web_search_builtin_model,
|
||
web_search_model,
|
||
workflow_activity_raises,
|
||
workflow_raises,
|
||
)
|
||
|
||
|
||
# `TemporalAgent` is deprecated in favor of `capabilities=[TemporalDurability(...)]`.
|
||
# These tests exercise the wrapper-agent path on purpose; suppress the warning here
|
||
# rather than globally in `pyproject.toml`. The `pytestmark` entry below covers warnings
|
||
# emitted *inside* test functions; the `filterwarnings` call below covers warnings emitted
|
||
# at module import time (e.g. module-level construction of `TemporalAgent`).
|
||
warnings.filterwarnings('ignore', message='`TemporalAgent` is deprecated', category=PydanticAIDeprecationWarning)
|
||
|
||
pytestmark = [
|
||
pytest.mark.vcr,
|
||
pytest.mark.xdist_group(name='temporal-durability'),
|
||
pytest.mark.filterwarnings(
|
||
'ignore:`TemporalAgent` is deprecated:pydantic_ai._warnings.PydanticAIDeprecationWarning'
|
||
),
|
||
]
|
||
|
||
|
||
simple_durability = TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)
|
||
|
||
simple_durable_agent = Agent(_durability_fn_model, name='durability_simple_agent', capabilities=[simple_durability])
|
||
|
||
|
||
@workflow.defn
|
||
class SimpleDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await simple_durable_agent.run(prompt)
|
||
return result.output
|
||
|
||
|
||
@workflow.defn
|
||
class RunSyncDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return simple_durable_agent.run_sync(prompt).output
|
||
|
||
|
||
async def test_durability_run_sync_in_workflow_fails_the_workflow(client: Client):
|
||
"""`agent.run_sync()` inside a workflow fails the workflow with a clear error instead of hanging.
|
||
|
||
Temporal's workflow event loop leaves `run_until_complete()` (and `is_closed()`) unimplemented, so
|
||
before this was detected up front, `run_sync()` raised the bare `NotImplementedError` `asyncio`'s
|
||
abstract loop raises. That type isn't among the plugin's `workflow_failure_exception_types`, so it
|
||
failed the workflow *task*, which Temporal retries forever -- the caller hung instead of seeing an
|
||
error. `UserError` is in that list, so the failure now reaches the caller.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[RunSyncDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(simple_durable_agent)],
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
RunSyncDurableAgentWorkflow.run,
|
||
args=['What is the capital of Mexico?'],
|
||
id=RunSyncDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert 'does not implement `run_until_complete()`' in str(exc_info.value.cause)
|
||
assert '`await agent.run()` rather than `agent.run_sync()`' in str(exc_info.value.cause)
|
||
|
||
|
||
_sync_graph_builder = GraphBuilder(name='run_sync_graph', input_type=str, output_type=str)
|
||
|
||
|
||
@_sync_graph_builder.step
|
||
async def _echo_step(ctx: StepContext[None, None, str]) -> str:
|
||
return ctx.inputs # pragma: no cover
|
||
|
||
|
||
_sync_graph_builder.add(
|
||
_sync_graph_builder.edge_from(_sync_graph_builder.start_node).to(_echo_step),
|
||
_sync_graph_builder.edge_from(_echo_step).to(_sync_graph_builder.end_node),
|
||
)
|
||
|
||
_sync_graph = _sync_graph_builder.build()
|
||
|
||
|
||
@workflow.defn
|
||
class GraphRunSyncWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return _sync_graph.run_sync(inputs='hello')
|
||
|
||
|
||
async def test_durability_graph_run_sync_in_workflow_fails_the_workflow(client: Client):
|
||
"""`Graph.run_sync()` inside a workflow fails the workflow too, not just the workflow task.
|
||
|
||
`pydantic_graph`'s sync entry points raise `UnsupportedEventLoopError` directly rather than going
|
||
through the `pydantic_ai` wrapper that converts it to `UserError`, so the plugin has to recognize
|
||
that type as well; otherwise this path keeps hanging with a good message nobody ever sees.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[GraphRunSyncWorkflow],
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
GraphRunSyncWorkflow.run,
|
||
id=GraphRunSyncWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert 'does not implement `run_until_complete()`' in str(exc_info.value.cause)
|
||
|
||
|
||
async def test_durability_simple_agent_run_in_workflow(client: Client):
|
||
"""TemporalDurability routes model requests through activities."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[SimpleDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(simple_durable_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
SimpleDurableAgentWorkflow.run,
|
||
args=['What is the capital of Mexico?'],
|
||
id=SimpleDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'Echo: What is the capital of Mexico?'
|
||
|
||
|
||
# --- Durability with the `ModelFallback` capability ---
|
||
|
||
|
||
def _failing_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
raise ModelAPIError(model_name='failing', message='boom')
|
||
|
||
|
||
def _fallback_target_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
return ModelResponse(parts=[TextPart('from fallback')])
|
||
|
||
|
||
fallback_durable_agent = Agent(
|
||
FunctionModel(_failing_model_fn, model_name='failing'),
|
||
name='durability_fallback_agent',
|
||
capabilities=[
|
||
# The default `fallback_on`: the model error reaches the workflow as itself, not as `ActivityError`.
|
||
ModelFallback('fallback_target'),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
models={'fallback_target': FunctionModel(_fallback_target_fn, model_name='fallback_target')},
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class FallbackDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> tuple[str, str | None]:
|
||
result = await fallback_durable_agent.run(prompt)
|
||
return result.output, result.response.model_id
|
||
|
||
|
||
async def test_durability_fallback_attempts_run_as_activities(client: Client):
|
||
"""Each model `ModelFallback` moves to runs in its own activity, not inline in workflow code."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[FallbackDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(fallback_durable_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
FallbackDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=FallbackDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await wf.result()
|
||
history = await wf.fetch_history()
|
||
# The response records the candidate that answered, which is what the workflow resumes a continuation on.
|
||
assert output == ('from fallback', 'fallback_target')
|
||
# The failed attempt on the agent's model and the one on the fallback model.
|
||
assert _scheduled_activity_count(history) == 2
|
||
|
||
|
||
def _echo_sent_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
return ModelResponse(parts=[TextPart(f'{info.instructions} {(info.model_settings or {}).get("temperature")}')])
|
||
|
||
|
||
def _per_model_instructions(ctx: RunContext[Any]) -> str:
|
||
return f'You are {ctx.model.model_name}.'
|
||
|
||
|
||
def _per_model_settings(ctx: RunContext[Any]) -> ModelSettings:
|
||
return {'temperature': 0.9 if ctx.model.model_name == 'per_model_target' else 0.1}
|
||
|
||
|
||
per_model_fallback_durable_agent = Agent(
|
||
FunctionModel(_failing_model_fn, model_name='failing'),
|
||
name='durability_per_model_fallback_agent',
|
||
instructions=_per_model_instructions,
|
||
model_settings=_per_model_settings,
|
||
capabilities=[
|
||
ModelFallback('per_model_target'),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
models={'per_model_target': FunctionModel(_echo_sent_fn, model_name='per_model_target')},
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class PerModelFallbackDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> tuple[str, str | None]:
|
||
result = await per_model_fallback_durable_agent.run(prompt)
|
||
request = result.all_messages()[0]
|
||
assert isinstance(request, ModelRequest)
|
||
return result.output, request.instructions
|
||
|
||
|
||
async def test_durability_fallback_resolves_instructions_and_settings_for_the_candidate(client: Client):
|
||
"""In workflow code, the instructions and settings are resolved again for the model `ModelFallback` moves to."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[PerModelFallbackDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(per_model_fallback_durable_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
PerModelFallbackDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=PerModelFallbackDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == ('You are per_model_target. 0.9', 'You are per_model_target.')
|
||
|
||
|
||
def _echo_instructions_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
return ModelResponse(parts=[TextPart(info.instructions or '')])
|
||
|
||
|
||
mcp_instructions_fallback_durable_agent = Agent(
|
||
FunctionModel(_failing_model_fn, model_name='failing'),
|
||
name='durability_mcp_instructions_fallback_agent',
|
||
instructions=_per_model_instructions,
|
||
toolsets=[
|
||
MCPToolset(
|
||
StdioTransport(command='python', args=['-m', 'tests.mcp_server']),
|
||
id='mcp_instructions',
|
||
include_instructions=True,
|
||
init_timeout=20,
|
||
)
|
||
],
|
||
capabilities=[
|
||
ModelFallback('mcp_instructions_target'),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
models={
|
||
'mcp_instructions_target': FunctionModel(_echo_instructions_fn, model_name='mcp_instructions_target')
|
||
},
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class MCPInstructionsFallbackDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await mcp_instructions_fallback_durable_agent.run(prompt)).output
|
||
|
||
|
||
@pytest.mark.subprocess(reason='connects to `tests.mcp_server` over stdio')
|
||
async def test_durability_fallback_reuses_durable_toolset_instructions(client: Client):
|
||
"""An attempt at another model resolves the agent's instructions again, but not a toolset's from a durable unit.
|
||
|
||
Asking an MCP server for its instructions again would schedule an activity that a replay of a history recorded
|
||
before doesn't have, so the step's are reused.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[MCPInstructionsFallbackDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(mcp_instructions_fallback_durable_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
MCPInstructionsFallbackDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=MCPInstructionsFallbackDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await wf.result()
|
||
history = await wf.fetch_history()
|
||
assert output == snapshot("""\
|
||
<pyai:context id="toolset:mcp_instructions">
|
||
Be a helpful assistant.
|
||
</pyai:context>
|
||
A later <pyai:context> element with the same id replaces the earlier one and stays in effect until replaced again.
|
||
|
||
You are mcp_instructions_target.\
|
||
""")
|
||
assert [name for name in scheduled_activity_types(history) if name.endswith('__get_instructions')] == snapshot(
|
||
['agent__durability_mcp_instructions_fallback_agent__mcp_server__mcp_instructions__get_instructions']
|
||
)
|
||
|
||
|
||
def _sticky_target_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
if any(isinstance(part, UserPromptPart) for part in messages[-1].parts):
|
||
return ModelResponse(parts=[ToolCallPart('sticky_noop')])
|
||
return ModelResponse(parts=[TextPart('from sticky target')])
|
||
|
||
|
||
def _down_target_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
raise ModelAPIError(model_name='down_target', message='boom')
|
||
|
||
|
||
def _working_primary_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
return ModelResponse(parts=[TextPart('from primary')])
|
||
|
||
|
||
def sticky_noop() -> str:
|
||
return 'ok'
|
||
|
||
|
||
sticky_fallback_durable_agent = Agent(
|
||
FunctionModel(_failing_model_fn, model_name='failing'),
|
||
name='durability_sticky_fallback_agent',
|
||
toolsets=[FunctionToolset(tools=[sticky_noop], id='sticky_noop')],
|
||
capabilities=[
|
||
ModelFallback('sticky_target', sticky=True),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
models={'sticky_target': FunctionModel(_sticky_target_fn, model_name='sticky_target')},
|
||
),
|
||
],
|
||
)
|
||
|
||
sticky_wrap_around_durable_agent = Agent(
|
||
FunctionModel(_working_primary_fn, model_name='primary'),
|
||
name='durability_sticky_wrap_around_agent',
|
||
capabilities=[
|
||
ModelFallback('down_target', sticky=True),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
models={'down_target': FunctionModel(_down_target_fn, model_name='down_target')},
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
def _served_and_recorded(messages: list[ModelMessage]) -> list[tuple[str | None, str | None]]:
|
||
"""The model behind each response, and the model it records it came from, which `sticky` follows."""
|
||
return [(message.model_name, message.model_id) for message in messages if isinstance(message, ModelResponse)]
|
||
|
||
|
||
@workflow.defn
|
||
class StickyFallbackDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> list[list[tuple[str | None, str | None]]]:
|
||
first = await sticky_fallback_durable_agent.run(prompt)
|
||
second = await sticky_fallback_durable_agent.run(prompt, message_history=first.all_messages())
|
||
return [_served_and_recorded(first.new_messages()), _served_and_recorded(second.new_messages())]
|
||
|
||
|
||
@workflow.defn
|
||
class StickyWrapAroundDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> list[tuple[str | None, str | None]]:
|
||
history: list[ModelMessage] = [
|
||
ModelRequest(parts=[UserPromptPart('earlier')]),
|
||
# An answer the conversation fell back to after the primary failed.
|
||
ModelResponse(
|
||
parts=[TextPart('earlier answer')],
|
||
model_name='down_target',
|
||
model_id='down_target',
|
||
failed_attempts=[
|
||
ModelRequestAttempt(
|
||
model_name='primary',
|
||
outcome='error',
|
||
timestamp=datetime(2026, 1, 1, tzinfo=UTC),
|
||
duration=timedelta(),
|
||
)
|
||
],
|
||
),
|
||
]
|
||
result = await sticky_wrap_around_durable_agent.run(prompt, message_history=history)
|
||
return _served_and_recorded(result.new_messages())
|
||
|
||
|
||
async def test_durability_sticky_fallback_goes_straight_to_the_candidate(client: Client):
|
||
"""Under durable execution, sticky steps and runs skip the failing primary, though the step's model is wrapped."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[StickyFallbackDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(sticky_fallback_durable_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
StickyFallbackDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=StickyFallbackDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await wf.result()
|
||
history = await wf.fetch_history()
|
||
sticky = ('sticky_target', 'sticky_target')
|
||
assert output == [[sticky, sticky], [sticky, sticky]]
|
||
# The primary is attempted once, at the first run's first step; every other step goes straight to the candidate.
|
||
model_requests = [
|
||
event
|
||
for event in history.events
|
||
if event.activity_task_scheduled_event_attributes.activity_type.name.endswith('__model_request')
|
||
]
|
||
assert len(model_requests) == 5
|
||
|
||
|
||
async def test_durability_sticky_fallback_wraps_around_to_the_wrapped_primary(client: Client):
|
||
"""When the sticky candidate fails, the chain comes back around to the wrapped primary, whose answer records it."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[StickyWrapAroundDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(sticky_wrap_around_durable_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
StickyWrapAroundDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=StickyWrapAroundDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await wf.result()
|
||
history = await wf.fetch_history()
|
||
# The answer records the primary, so the conversation goes back to starting from it.
|
||
assert output == [('primary', 'function:primary')]
|
||
# The failed attempt on the sticky candidate, then the primary.
|
||
assert _scheduled_activity_count(history) == 2
|
||
|
||
|
||
exhausted_fallback_durable_agent = Agent(
|
||
FunctionModel(_failing_model_fn, model_name='failing'),
|
||
name='durability_exhausted_fallback_agent',
|
||
capabilities=[
|
||
ModelFallback('also_failing'),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
models={'also_failing': FunctionModel(_failing_model_fn, model_name='also_failing')},
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class ExhaustedFallbackDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
return await exhausted_fallback_durable_agent.run(prompt)
|
||
|
||
|
||
async def test_durability_exhausted_fallback_fails_the_workflow(client: Client):
|
||
"""A `ModelFallback` chain that runs out raises its group in workflow code, which fails the workflow.
|
||
|
||
Failing only the workflow task instead would have Temporal retry it until the execution times out.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[ExhaustedFallbackDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(exhausted_fallback_durable_agent)],
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
ExhaustedFallbackDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=ExhaustedFallbackDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
execution_timeout=timedelta(seconds=30),
|
||
)
|
||
cause = _workflow_failure_cause(exc_info.value)
|
||
assert cause.type == FallbackExceptionGroup.__name__
|
||
|
||
|
||
# --- Durability with the `RetryOnModelErrors` capability ---
|
||
|
||
|
||
def _unavailable_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
raise ModelHTTPError.for_category(
|
||
ModelUnavailableError, status_code=503, model_name='unavailable', headers={'retry-after-ms': '10'}
|
||
)
|
||
|
||
|
||
retry_durable_agent = Agent(
|
||
FunctionModel(_unavailable_model_fn, model_name='unavailable'),
|
||
name='durability_retry_agent',
|
||
capabilities=[
|
||
RetryOnModelErrors(max_attempts=2),
|
||
ModelFallback('fallback_target'),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
models={'fallback_target': FunctionModel(_fallback_target_fn, model_name='fallback_target')},
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class RetryDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> tuple[str, list[tuple[str, str, float | None]]]:
|
||
result = await retry_durable_agent.run(prompt)
|
||
attempts = result.response.failed_attempts or []
|
||
return result.output, [(attempt.model_name, attempt.kind, attempt.retry_after) for attempt in attempts]
|
||
|
||
|
||
async def test_durability_retry_waits_on_a_durable_timer(client: Client):
|
||
"""Each retry is an activity of its own, and the wait before it is a workflow timer, not a sleep in workflow code.
|
||
|
||
Once the model's attempts are used up, `ModelFallback` moves on to the next model, without a wait.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[RetryDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(retry_durable_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
RetryDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=RetryDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await wf.result()
|
||
history = await wf.fetch_history()
|
||
assert output == (
|
||
'from fallback',
|
||
[('unavailable', 'retry', 0.01), ('unavailable', 'fallback', 0.01)],
|
||
)
|
||
assert _scheduled_activity_count(history) == 3
|
||
assert len([e for e in history.events if e.HasField('timer_started_event_attributes')]) == 1
|
||
|
||
|
||
_flaky_calls: list[str] = []
|
||
|
||
|
||
def _flaky_once_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
_flaky_calls.append('flaky')
|
||
if len(_flaky_calls) == 1:
|
||
raise ModelHTTPError.for_category(
|
||
ModelUnavailableError, status_code=503, model_name='flaky', headers={'retry-after-ms': '10'}
|
||
)
|
||
return ModelResponse(parts=[TextPart('recovered')])
|
||
|
||
|
||
retry_owner_durable_agent = Agent(
|
||
FunctionModel(_flaky_once_model_fn, model_name='flaky'),
|
||
name='durability_retry_owner_agent',
|
||
capabilities=[
|
||
RetryOnModelErrors(),
|
||
TemporalDurability(
|
||
# A retry policy that would retry the model error itself, were it retryable.
|
||
activity_config=ActivityConfig(
|
||
start_to_close_timeout=timedelta(seconds=60),
|
||
retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(milliseconds=10)),
|
||
),
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class RetryOwnerDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await retry_owner_durable_agent.run(prompt)).output
|
||
|
||
|
||
async def test_durability_retry_owns_model_errors_over_the_activity_retry_policy(client: Client):
|
||
"""With `RetryOnModelErrors`, a model error isn't retried by the activity's retry policy, but by the capability.
|
||
|
||
The failed attempt and the retry are activities of their own, with a workflow timer between them, rather than one
|
||
activity that Temporal attempts twice. The retry policy is left to crashes and timeouts.
|
||
"""
|
||
_flaky_calls.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[RetryOwnerDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(retry_owner_durable_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
RetryOwnerDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=RetryOwnerDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await wf.result()
|
||
history = await wf.fetch_history()
|
||
assert output == 'recovered'
|
||
assert _flaky_calls == ['flaky', 'flaky']
|
||
assert _scheduled_activity_count(history) == 2
|
||
assert len([e for e in history.events if e.HasField('timer_started_event_attributes')]) == 1
|
||
|
||
|
||
def test_durability_warns_that_retry_on_model_errors_ignores_non_retryable_model_errors():
|
||
"""With `RetryOnModelErrors`, an explicit `non_retryable_model_errors` other than the default has no effect.
|
||
|
||
Every model error is non-retryable in the model activity then, so the agent warns that the list is ignored.
|
||
"""
|
||
with pytest.warns(
|
||
UserWarning, match='`non_retryable_model_errors` is ignored because the agent has `RetryOnModelErrors`'
|
||
):
|
||
Agent(
|
||
FunctionModel(_fallback_target_fn, model_name='ignored'),
|
||
name='durability_ignored_non_retryable_agent',
|
||
capabilities=[
|
||
RetryOnModelErrors(),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG, non_retryable_model_errors=[ModelUnavailableError]
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
def test_durability_does_not_warn_about_the_default_non_retryable_model_errors():
|
||
"""`RetryOnModelErrors` with the default `non_retryable_model_errors` is the normal setup, so it doesn't warn."""
|
||
with warnings.catch_warnings():
|
||
warnings.simplefilter('error')
|
||
Agent(
|
||
FunctionModel(_fallback_target_fn, model_name='default'),
|
||
name='durability_default_non_retryable_agent',
|
||
capabilities=[RetryOnModelErrors(), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
dynamic_retry_durable_agent = Agent(
|
||
FunctionModel(_fallback_target_fn, model_name='dynamic_retry'),
|
||
name='durability_dynamic_retry_agent',
|
||
capabilities=[
|
||
DynamicCapability(lambda ctx: RetryOnModelErrors(), id='dynamic_retry'),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DynamicRetryDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await dynamic_retry_durable_agent.run(prompt)).output
|
||
|
||
|
||
async def test_durability_rejects_a_retry_on_model_errors_only_a_run_resolves(client: Client):
|
||
"""A `RetryOnModelErrors` a `DynamicCapability` returns is only seen once the run has started.
|
||
|
||
The model activity's retry policy was set when the agent was bound, so rather than have the activity and the
|
||
capability both retry model errors, the run fails with a `UserError`.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DynamicRetryDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(dynamic_retry_durable_agent)],
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
DynamicRetryDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=DynamicRetryDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
execution_timeout=timedelta(seconds=30),
|
||
)
|
||
cause = _workflow_failure_cause(exc_info.value)
|
||
assert cause.type == UserError.__name__
|
||
assert 'must be one of the capabilities the agent is built with' in str(cause)
|
||
|
||
|
||
wrapped_retry_durable_agent = Agent(
|
||
FunctionModel(_flaky_once_model_fn, model_name='flaky'),
|
||
name='durability_wrapped_retry_agent',
|
||
capabilities=[
|
||
WrapperCapability(wrapped=RetryOnModelErrors()),
|
||
TemporalDurability(
|
||
# A retry policy that would retry the model error itself, were it retryable.
|
||
activity_config=ActivityConfig(
|
||
start_to_close_timeout=timedelta(seconds=60),
|
||
retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(milliseconds=10)),
|
||
),
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class WrappedRetryDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await wrapped_retry_durable_agent.run(prompt)).output
|
||
|
||
|
||
async def test_durability_detects_a_retry_on_model_errors_a_wrapper_capability_wraps(client: Client):
|
||
"""A `RetryOnModelErrors` inside a `WrapperCapability` on the agent is seen when the agent is bound.
|
||
|
||
So the capability owns retrying model errors, as when it's on the agent directly: the failed attempt and the retry
|
||
are activities of their own with a workflow timer between them, not one activity that Temporal attempts twice.
|
||
"""
|
||
_flaky_calls.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[WrappedRetryDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(wrapped_retry_durable_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
WrappedRetryDurableAgentWorkflow.run,
|
||
args=['hello'],
|
||
id=WrappedRetryDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await wf.result()
|
||
history = await wf.fetch_history()
|
||
assert output == 'recovered'
|
||
assert _flaky_calls == ['flaky', 'flaky']
|
||
assert _scheduled_activity_count(history) == 2
|
||
assert len([e for e in history.events if e.HasField('timer_started_event_attributes')]) == 1
|
||
|
||
|
||
_backup_streamed: list[str] = []
|
||
|
||
|
||
def _late_stream_failure_agent(name: str, *, fail_after_output: bool) -> Agent[object, str]:
|
||
"""An agent whose model fails partway through a stream, or before it, with a `ModelFallback` to another model."""
|
||
|
||
async def primary(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str]:
|
||
if fail_after_output:
|
||
yield 'partial'
|
||
raise ModelAPIError('primary', 'stream broke')
|
||
|
||
async def backup(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str]:
|
||
_backup_streamed.append(name)
|
||
yield 'from backup'
|
||
|
||
async def handler(ctx: RunContext[object], stream: AsyncIterable[AgentStreamEvent]) -> None:
|
||
async for _event in stream:
|
||
pass
|
||
|
||
return Agent(
|
||
FunctionModel(stream_function=primary, model_name='primary'),
|
||
deps_type=object,
|
||
name=name,
|
||
capabilities=[
|
||
ModelFallback('backup'),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
models={'backup': FunctionModel(stream_function=backup, model_name='backup')},
|
||
event_stream_handler=handler,
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
late_stream_failure_agent = _late_stream_failure_agent('durability_late_stream_failure', fail_after_output=True)
|
||
early_stream_failure_agent = _late_stream_failure_agent('durability_early_stream_failure', fail_after_output=False)
|
||
|
||
|
||
@workflow.defn
|
||
class LateStreamFailureWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> tuple[str, int, int, int]:
|
||
usage = RunUsage()
|
||
try:
|
||
output = (await late_stream_failure_agent.run(prompt, usage=usage)).output
|
||
except ModelAPIError as error:
|
||
output = f'raised: {error.message}'
|
||
return output, usage.input_tokens, usage.output_tokens, usage.requests
|
||
|
||
|
||
@workflow.defn
|
||
class EarlyStreamFailureWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await early_stream_failure_agent.run(prompt)).output
|
||
|
||
|
||
async def test_durability_stream_failing_after_output_does_not_fall_back(client: Client):
|
||
"""A stream that fails after producing output in its activity is raised, not fallen back from, and its usage counts.
|
||
|
||
The activity delivers the output to the event handler before the workflow sees the stream, as outside durable
|
||
execution, where only a stream that fails before its first event falls back. The error crosses the activity
|
||
boundary with what the stream produced, so the interrupted response is committed with its usage.
|
||
"""
|
||
_backup_streamed.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[LateStreamFailureWorkflow],
|
||
plugins=[AgentPlugin(late_stream_failure_agent)],
|
||
):
|
||
result = await client.execute_workflow(
|
||
LateStreamFailureWorkflow.run,
|
||
args=['hello'],
|
||
id=LateStreamFailureWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert result == ('raised: stream broke', 50, 1, 1)
|
||
assert _backup_streamed == []
|
||
|
||
|
||
async def test_durability_stream_failing_before_output_falls_back(client: Client):
|
||
"""A stream that fails before producing any output still falls back to the next model."""
|
||
_backup_streamed.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[EarlyStreamFailureWorkflow],
|
||
plugins=[AgentPlugin(early_stream_failure_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
EarlyStreamFailureWorkflow.run,
|
||
args=['hello'],
|
||
id=EarlyStreamFailureWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'from backup'
|
||
assert _backup_streamed == ['durability_early_stream_failure']
|
||
|
||
|
||
@workflow.defn
|
||
class FirstSharedAgentWorkflow:
|
||
__pydantic_ai_agents__ = [simple_durable_agent]
|
||
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await simple_durable_agent.run(prompt)).output
|
||
|
||
|
||
@workflow.defn
|
||
class SecondSharedAgentWorkflow:
|
||
__pydantic_ai_agents__ = [simple_durable_agent]
|
||
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await simple_durable_agent.run(prompt)).output
|
||
|
||
|
||
async def test_durability_agent_shared_by_workflows_and_agent_plugin(client: Client):
|
||
"""An agent listed on several workflows and also passed to `AgentPlugin` registers its activities once."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[FirstSharedAgentWorkflow, SecondSharedAgentWorkflow],
|
||
plugins=[AgentPlugin(simple_durable_agent)],
|
||
):
|
||
outputs = [
|
||
await client.execute_workflow(
|
||
workflow_class.run, args=['Hi'], id=workflow_class.__name__, task_queue=TASK_QUEUE
|
||
)
|
||
for workflow_class in (FirstSharedAgentWorkflow, SecondSharedAgentWorkflow)
|
||
]
|
||
|
||
assert outputs == ['Echo: Hi', 'Echo: Hi']
|
||
|
||
|
||
# --- Model errors reach workflow code with their original type ---
|
||
|
||
|
||
def _overloaded_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
raise ModelHTTPError(503, 'overloaded-model', body={'error': 'overloaded'}, headers={'Retry-After': '7'})
|
||
|
||
|
||
async def _overloaded_stream_fn(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str]:
|
||
raise ModelHTTPError(503, 'overloaded-model', body={'error': 'overloaded'}, headers={'Retry-After': '7'})
|
||
yield '' # pragma: no cover
|
||
|
||
|
||
def _broken_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
raise ValueError('not a model error')
|
||
|
||
|
||
def _timeout_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
raise ModelTimeoutError('timeout-model', 'Request timed out.', phase='read')
|
||
|
||
|
||
def _describe(error: Exception) -> str:
|
||
if isinstance(error, ModelHTTPError):
|
||
return f'{type(error).__name__} {error.status_code} {error.retry_after} {error.body}'
|
||
return type(error).__name__
|
||
|
||
|
||
async def _describe_model_error(
|
||
ctx: RunContext[None], *, request_context: ModelRequestContext, error: Exception
|
||
) -> ModelResponse:
|
||
"""Recover with a description of the error the hook received in workflow code."""
|
||
return ModelResponse(parts=[TextPart(_describe(error))])
|
||
|
||
|
||
async def _drain_events(ctx: RunContext[None], stream: AsyncIterable[AgentStreamEvent]) -> None:
|
||
async for _ in stream:
|
||
pass
|
||
|
||
|
||
def _model_error_agent(name: str, model: FunctionModel, *, streamed: bool = False) -> Agent[None, str]:
|
||
# A failure to open a streamed request isn't handed to `on_model_request_error`, so the streamed
|
||
# agent lets the error reach the workflow, which describes it instead.
|
||
capabilities: list[AbstractCapability[None]] = (
|
||
[ProcessEventStream(_drain_events)] if streamed else [Hooks[None](model_request_error=_describe_model_error)]
|
||
)
|
||
capabilities.append(TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG))
|
||
return Agent(model, name=name, deps_type=type(None), capabilities=capabilities)
|
||
|
||
|
||
model_error_agent = _model_error_agent('durability_model_error', FunctionModel(_overloaded_model_fn))
|
||
streamed_model_error_agent = _model_error_agent(
|
||
'durability_streamed_model_error', FunctionModel(stream_function=_overloaded_stream_fn), streamed=True
|
||
)
|
||
other_error_agent = _model_error_agent('durability_other_error', FunctionModel(_broken_model_fn))
|
||
timeout_agent = Agent(
|
||
FunctionModel(_timeout_model_fn),
|
||
name='durability_timeout_error',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class ModelTimeoutWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
try:
|
||
return (await timeout_agent.run('hello')).output
|
||
except ModelTimeoutError as error:
|
||
# What a retry policy's `non_retryable_error_types` matched, on the activity failure the error rebuilt from.
|
||
activity_error = error.__cause__
|
||
assert isinstance(activity_error, ActivityError)
|
||
application_error = activity_error.cause
|
||
assert isinstance(application_error, ApplicationError)
|
||
return f'{type(error).__name__} {error.phase} {application_error.type}'
|
||
|
||
|
||
@workflow.defn
|
||
class ModelErrorWorkflow:
|
||
@workflow.run
|
||
async def run(self, agent_name: str) -> str:
|
||
agent = {agent.name: agent for agent in (model_error_agent, streamed_model_error_agent, other_error_agent)}[
|
||
agent_name
|
||
]
|
||
try:
|
||
return (await agent.run('hello')).output
|
||
except ModelHTTPError as error:
|
||
return _describe(error)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
'agent',
|
||
[pytest.param(model_error_agent, id='request'), pytest.param(streamed_model_error_agent, id='stream')],
|
||
)
|
||
async def test_durability_model_error_reaches_workflow_with_its_type(client: Client, agent: Agent[None, str]):
|
||
"""A model activity's `ModelHTTPError` reaches workflow code as itself, fields included, not as `ActivityError`."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[ModelErrorWorkflow],
|
||
plugins=[AgentPlugin(agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
ModelErrorWorkflow.run,
|
||
args=[agent.name],
|
||
id=f'{ModelErrorWorkflow.__name__}_{agent.name}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == "ModelHTTPError 503 7.0 {'error': 'overloaded'}"
|
||
|
||
|
||
async def test_durability_categorized_model_error_reaches_workflow_as_its_category(client: Client):
|
||
"""Workflow code catches a model activity's `ModelTimeoutError` as itself, while the retry policy sees the
|
||
`ModelAPIError` type it saw before error categories existed."""
|
||
async with Worker(
|
||
client, task_queue=TASK_QUEUE, workflows=[ModelTimeoutWorkflow], plugins=[AgentPlugin(timeout_agent)]
|
||
):
|
||
output = await client.execute_workflow(
|
||
ModelTimeoutWorkflow.run, id=ModelTimeoutWorkflow.__name__, task_queue=TASK_QUEUE
|
||
)
|
||
assert output == 'ModelTimeoutError read ModelAPIError'
|
||
|
||
|
||
# --- Model errors that `non_retryable_model_errors` stops Temporal from retrying ---
|
||
|
||
_non_retryable_attempts: list[str] = []
|
||
|
||
|
||
def _non_retryable_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
prompt = messages[0].parts[0]
|
||
assert isinstance(prompt, UserPromptPart) and isinstance(prompt.content, str)
|
||
_non_retryable_attempts.append(prompt.content)
|
||
if prompt.content == 'context_window':
|
||
raise ModelHTTPError.for_category(ModelContextWindowExceededError, status_code=400, model_name='test-model')
|
||
if prompt.content == 'overloaded':
|
||
raise ModelOverloadedError('test-model', 'Model is overloaded.')
|
||
if prompt.content == 'authentication':
|
||
raise ModelHTTPError.for_category(ModelAuthenticationError, status_code=401, model_name='test-model')
|
||
if prompt.content == 'not_found':
|
||
raise ModelHTTPError.for_category(ModelNotFoundError, status_code=404, model_name='test-model')
|
||
if prompt.content == 'quota':
|
||
raise ModelHTTPError.for_category(ModelQuotaExceededError, status_code=402, model_name='test-model')
|
||
if prompt.content == 'request_timeout':
|
||
raise ModelRequestTimeout('test-model', 1.0, setting='first_event_timeout')
|
||
raise ModelHTTPError.for_category(ModelRateLimitError, status_code=429, model_name='test-model')
|
||
|
||
|
||
non_retryable_agent = Agent(
|
||
FunctionModel(_non_retryable_model_fn),
|
||
name='durability_non_retryable_model_errors',
|
||
capabilities=[
|
||
TemporalDurability(
|
||
activity_config=ActivityConfig(
|
||
start_to_close_timeout=timedelta(seconds=60),
|
||
retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(milliseconds=10)),
|
||
),
|
||
non_retryable_model_errors=[
|
||
ModelContextWindowExceededError,
|
||
ModelUnavailableError,
|
||
ModelAuthenticationError,
|
||
],
|
||
)
|
||
],
|
||
)
|
||
|
||
|
||
default_non_retryable_agent = Agent(
|
||
FunctionModel(_non_retryable_model_fn),
|
||
name='durability_default_non_retryable_model_errors',
|
||
capabilities=[
|
||
TemporalDurability(
|
||
activity_config=ActivityConfig(
|
||
start_to_close_timeout=timedelta(seconds=60),
|
||
retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(milliseconds=10)),
|
||
),
|
||
)
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class NonRetryableModelErrorWorkflow:
|
||
@workflow.run
|
||
async def run(self, error_kind: str, default: bool = False) -> str:
|
||
agent = default_non_retryable_agent if default else non_retryable_agent
|
||
try:
|
||
return (await agent.run(error_kind)).output
|
||
except ModelAPIError as error:
|
||
activity_error = error.__cause__
|
||
assert isinstance(activity_error, ActivityError)
|
||
application_error = activity_error.cause
|
||
assert isinstance(application_error, ApplicationError)
|
||
return f'{type(error).__name__} {application_error.type} non_retryable={application_error.non_retryable}'
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
('error_kind', 'attempts', 'expected'),
|
||
[
|
||
pytest.param(
|
||
'context_window',
|
||
1,
|
||
'ModelContextWindowExceededError ModelHTTPError non_retryable=True',
|
||
id='listed-category',
|
||
),
|
||
pytest.param(
|
||
'overloaded', 1, 'ModelOverloadedError ModelAPIError non_retryable=True', id='subclass-of-listed-category'
|
||
),
|
||
pytest.param('rate_limit', 3, 'ModelRateLimitError ModelHTTPError non_retryable=False', id='unlisted-category'),
|
||
pytest.param(
|
||
'authentication',
|
||
1,
|
||
'ModelAuthenticationError ModelHTTPError non_retryable=True',
|
||
id='listed-rejection-category',
|
||
),
|
||
pytest.param(
|
||
# A sibling of a listed category isn't covered by it.
|
||
'not_found',
|
||
3,
|
||
'ModelNotFoundError ModelHTTPError non_retryable=False',
|
||
id='unlisted-rejection-category',
|
||
),
|
||
],
|
||
)
|
||
async def test_durability_non_retryable_model_errors(client: Client, error_kind: str, attempts: int, expected: str):
|
||
"""A model error that's an instance of a class in `non_retryable_model_errors` fails the activity on its first
|
||
attempt and still reaches workflow code as its own class, with the `ApplicationError` type a retry policy saw
|
||
before; any other model error is retried as the retry policy says."""
|
||
_non_retryable_attempts.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[NonRetryableModelErrorWorkflow],
|
||
plugins=[AgentPlugin(non_retryable_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
NonRetryableModelErrorWorkflow.run,
|
||
args=[error_kind],
|
||
id=f'{NonRetryableModelErrorWorkflow.__name__}_{error_kind}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == expected
|
||
assert _non_retryable_attempts == [error_kind] * attempts
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
('error_kind', 'attempts', 'expected'),
|
||
[
|
||
pytest.param(
|
||
'context_window',
|
||
1,
|
||
'ModelContextWindowExceededError ModelHTTPError non_retryable=True',
|
||
id='context-window',
|
||
),
|
||
pytest.param(
|
||
'authentication', 1, 'ModelAuthenticationError ModelHTTPError non_retryable=True', id='authentication'
|
||
),
|
||
pytest.param('not_found', 1, 'ModelNotFoundError ModelHTTPError non_retryable=True', id='not-found'),
|
||
pytest.param('quota', 1, 'ModelQuotaExceededError ModelHTTPError non_retryable=True', id='quota'),
|
||
pytest.param('request_timeout', 1, 'ModelRequestTimeout ModelRequestTimeout non_retryable=True', id='timeout'),
|
||
pytest.param('rate_limit', 3, 'ModelRateLimitError ModelHTTPError non_retryable=False', id='rate-limit'),
|
||
pytest.param('overloaded', 3, 'ModelOverloadedError ModelAPIError non_retryable=False', id='overloaded'),
|
||
],
|
||
)
|
||
async def test_durability_default_non_retryable_model_errors(
|
||
client: Client, error_kind: str, attempts: int, expected: str
|
||
):
|
||
"""By default, a model error another attempt can't fix (a rejected request, an exhausted quota, or a request that
|
||
ran out of its deadline) fails the activity on its first attempt, while a transient one is retried as the retry
|
||
policy says."""
|
||
_non_retryable_attempts.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[NonRetryableModelErrorWorkflow],
|
||
plugins=[AgentPlugin(default_non_retryable_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
NonRetryableModelErrorWorkflow.run,
|
||
args=[error_kind, True],
|
||
id=f'{NonRetryableModelErrorWorkflow.__name__}_default_{error_kind}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == expected
|
||
assert _non_retryable_attempts == [error_kind] * attempts
|
||
|
||
|
||
async def test_durability_non_model_error_still_reaches_workflow_as_activity_error(client: Client):
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[ModelErrorWorkflow],
|
||
plugins=[AgentPlugin(other_error_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
ModelErrorWorkflow.run,
|
||
args=[other_error_agent.name],
|
||
id=f'{ModelErrorWorkflow.__name__}_{other_error_agent.name}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'ActivityError'
|
||
|
||
|
||
# --- A model error's `retry_after` is the delay before Temporal's next attempt ---
|
||
|
||
_retry_after_attempts: list[float] = []
|
||
|
||
|
||
def _retry_after_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
prompt = messages[0].parts[0]
|
||
assert isinstance(prompt, UserPromptPart) and isinstance(prompt.content, str)
|
||
_retry_after_attempts.append(time.monotonic())
|
||
raise ModelHTTPError.for_category(
|
||
ModelRateLimitError, status_code=429, model_name='test-model', retry_after=float(prompt.content)
|
||
)
|
||
|
||
|
||
def _retry_after_agent(name: str, retry_policy: RetryPolicy) -> Agent[None, str]:
|
||
return Agent(
|
||
FunctionModel(_retry_after_model_fn),
|
||
name=name,
|
||
capabilities=[
|
||
TemporalDurability(
|
||
activity_config=ActivityConfig(start_to_close_timeout=timedelta(seconds=60), retry_policy=retry_policy)
|
||
)
|
||
],
|
||
)
|
||
|
||
|
||
# The retry policy's own backoff would wait 30 seconds before the second attempt.
|
||
retry_after_agent = _retry_after_agent(
|
||
'durability_retry_after', RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=30))
|
||
)
|
||
# `maximum_interval` caps the delay a provider asks for.
|
||
capped_retry_after_agent = _retry_after_agent(
|
||
'durability_capped_retry_after',
|
||
RetryPolicy(
|
||
maximum_attempts=2, initial_interval=timedelta(milliseconds=10), maximum_interval=timedelta(milliseconds=100)
|
||
),
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class RetryAfterWorkflow:
|
||
@workflow.run
|
||
async def run(self, capped: bool, retry_after: str) -> str:
|
||
agent = capped_retry_after_agent if capped else retry_after_agent
|
||
try:
|
||
return (await agent.run(retry_after)).output
|
||
except ModelRateLimitError as error:
|
||
activity_error = error.__cause__
|
||
assert isinstance(activity_error, ActivityError)
|
||
application_error = activity_error.cause
|
||
assert isinstance(application_error, ApplicationError)
|
||
return f'{error.retry_after} {application_error.next_retry_delay}'
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
('capped', 'retry_after', 'expected'),
|
||
[
|
||
pytest.param(False, '0.05', '0.05 0:00:00.050000', id='retry-after'),
|
||
# Too large for a `timedelta`, which the cap keeps from failing the conversion.
|
||
pytest.param(True, '1e15', '1000000000000000.0 0:00:00.100000', id='capped-at-maximum-interval'),
|
||
],
|
||
)
|
||
async def test_durability_model_error_retry_after_delays_next_attempt(
|
||
client: Client, capped: bool, retry_after: str, expected: str
|
||
):
|
||
"""Temporal waits a model error's `retry_after`, up to the retry policy's `maximum_interval`, before attempting
|
||
the model request again, rather than the retry policy's backoff, and the workflow still receives the error as its
|
||
own class."""
|
||
_retry_after_attempts.clear()
|
||
agent = capped_retry_after_agent if capped else retry_after_agent
|
||
async with Worker(client, task_queue=TASK_QUEUE, workflows=[RetryAfterWorkflow], plugins=[AgentPlugin(agent)]):
|
||
output = await client.execute_workflow(
|
||
RetryAfterWorkflow.run,
|
||
args=[capped, retry_after],
|
||
id=f'{RetryAfterWorkflow.__name__}_{capped}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == expected
|
||
assert len(_retry_after_attempts) == 2
|
||
# Well before the 30-second backoff of the uncapped policy, and well before the requested delay of the capped one.
|
||
assert _retry_after_attempts[1] - _retry_after_attempts[0] < 10
|
||
|
||
|
||
# --- Subclasses of the framework's non-retryable errors aren't retried either ---
|
||
|
||
|
||
class _AppConfigError(UserError):
|
||
"""An application's own `UserError`, which a retry policy can't name in advance."""
|
||
|
||
|
||
_subclass_attempts: list[str] = []
|
||
|
||
|
||
def _raise_framework_error(kind: str) -> None:
|
||
_subclass_attempts.append(kind)
|
||
if kind == 'unexpected_model_behavior':
|
||
raise UnexpectedModelBehavior('Unexpected response.')
|
||
if kind == 'content_filter':
|
||
raise ContentFilterError('Content filter triggered.')
|
||
if kind == 'incomplete_tool_call':
|
||
raise IncompleteToolCall('Token limit exceeded while generating a tool call.')
|
||
raise _AppConfigError('The app is misconfigured.')
|
||
|
||
|
||
def _subclass_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
prompt = messages[0].parts[0]
|
||
assert isinstance(prompt, UserPromptPart) and isinstance(prompt.content, str)
|
||
kind, _, where = prompt.content.partition(':')
|
||
if where == 'model':
|
||
_raise_framework_error(kind)
|
||
return ModelResponse(parts=[ToolCallPart('raise_framework_error', {'kind': kind})])
|
||
|
||
|
||
def raise_framework_error(kind: str) -> str:
|
||
_raise_framework_error(kind)
|
||
return 'unreachable' # pragma: no cover
|
||
|
||
|
||
subclass_error_agent = Agent(
|
||
FunctionModel(_subclass_model_fn),
|
||
name='durability_non_retryable_subclasses',
|
||
toolsets=[FunctionToolset(tools=[raise_framework_error], id='subclass_toolset')],
|
||
capabilities=[
|
||
TemporalDurability(
|
||
activity_config=ActivityConfig(
|
||
start_to_close_timeout=timedelta(seconds=60),
|
||
retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(milliseconds=10)),
|
||
),
|
||
)
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class NonRetryableSubclassWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
try:
|
||
return (await subclass_error_agent.run(prompt)).output
|
||
except ActivityError as error:
|
||
application_error = error.cause
|
||
assert isinstance(application_error, ApplicationError)
|
||
return f'{application_error.type}: {application_error.message}'
|
||
|
||
|
||
@pytest.mark.parametrize('where', ['model', 'tool'])
|
||
@pytest.mark.parametrize(
|
||
('kind', 'error_type', 'message'),
|
||
[
|
||
pytest.param('unexpected_model_behavior', 'UnexpectedModelBehavior', 'Unexpected response.', id='listed-class'),
|
||
pytest.param(
|
||
'content_filter', 'ContentFilterError', 'Content filter triggered.', id='unexpected-model-behavior-subclass'
|
||
),
|
||
pytest.param(
|
||
'incomplete_tool_call',
|
||
'IncompleteToolCall',
|
||
'Token limit exceeded while generating a tool call.',
|
||
id='incomplete-tool-call',
|
||
),
|
||
pytest.param('app_config', '_AppConfigError', 'The app is misconfigured.', id='user-error-subclass'),
|
||
],
|
||
)
|
||
async def test_durability_non_retryable_error_subclasses(
|
||
client: Client, where: str, kind: str, error_type: str, message: str
|
||
):
|
||
"""An activity that raises a subclass of an error the retry policy lists as non-retryable, like a
|
||
`ContentFilterError` or an application's own `UserError`, fails on its first attempt, as the listed class does.
|
||
|
||
Temporal's `non_retryable_error_types` matches the error's exact type name, which a subclass doesn't have. The
|
||
error keeps its own type name and message.
|
||
"""
|
||
_subclass_attempts.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[NonRetryableSubclassWorkflow],
|
||
plugins=[AgentPlugin(subclass_error_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
NonRetryableSubclassWorkflow.run,
|
||
args=[f'{kind}:{where}'],
|
||
id=f'{NonRetryableSubclassWorkflow.__name__}_{kind}_{where}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == f'{error_type}: {message}'
|
||
assert _subclass_attempts == [kind]
|
||
|
||
|
||
# --- `ModelSettings['request_timeout']` runs on the workflow's clock ---
|
||
|
||
|
||
async def _hanging_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
await asyncio.sleep(3600)
|
||
raise AssertionError('unreachable') # pragma: no cover
|
||
|
||
|
||
async def _hanging_stream_fn(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str]:
|
||
await asyncio.sleep(3600)
|
||
yield 'unreachable' # pragma: no cover
|
||
|
||
|
||
def _request_timeout_agent(name: str, model: FunctionModel, *, streamed: bool = False) -> Agent[None, str]:
|
||
capabilities: list[AbstractCapability[None]] = [ProcessEventStream(_drain_events)] if streamed else []
|
||
capabilities.append(TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG))
|
||
return Agent(
|
||
model,
|
||
name=name,
|
||
deps_type=type(None),
|
||
capabilities=capabilities,
|
||
model_settings={'request_timeout': 0.2},
|
||
)
|
||
|
||
|
||
request_timeout_agent = _request_timeout_agent(
|
||
'durability_request_timeout', FunctionModel(_hanging_model_fn, model_name='hanging')
|
||
)
|
||
streamed_request_timeout_agent = _request_timeout_agent(
|
||
'durability_streamed_request_timeout',
|
||
FunctionModel(stream_function=_hanging_stream_fn, model_name='hanging'),
|
||
streamed=True,
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class RequestTimeoutWorkflow:
|
||
@workflow.run
|
||
async def run(self, agent_name: str) -> str:
|
||
agent = {agent.name: agent for agent in (request_timeout_agent, streamed_request_timeout_agent)}[agent_name]
|
||
try:
|
||
await agent.run('hello')
|
||
except ModelRequestTimeout as error:
|
||
return f'{type(error).__name__} {error.model_name} {error.timeout}'
|
||
raise AssertionError('unreachable') # pragma: no cover
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
'agent',
|
||
[pytest.param(request_timeout_agent, id='request'), pytest.param(streamed_request_timeout_agent, id='stream')],
|
||
)
|
||
async def test_durability_request_timeout_cancels_the_model_activity(client: Client, agent: Agent[None, str]):
|
||
"""The deadline is a workflow timer: when it fires, the hanging model activity is cancelled and the workflow sees
|
||
`ModelRequestTimeout`, well within the activity's own timeouts."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[RequestTimeoutWorkflow],
|
||
plugins=[AgentPlugin(agent)],
|
||
):
|
||
handle = await client.start_workflow(
|
||
RequestTimeoutWorkflow.run,
|
||
args=[agent.name],
|
||
id=f'{RequestTimeoutWorkflow.__name__}_{agent.name}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await handle.result()
|
||
history = await handle.fetch_history()
|
||
|
||
assert output == 'ModelRequestTimeout hanging 0.2'
|
||
event_types = {event.WhichOneof('attributes') for event in history.events}
|
||
assert {'timer_started_event_attributes', 'activity_task_cancel_requested_event_attributes'} <= event_types
|
||
|
||
# The deadline replays from history, so a replayed run raises at the same point.
|
||
await Replayer(
|
||
workflows=[RequestTimeoutWorkflow], workflow_runner=UnsandboxedWorkflowRunner(), plugins=[AgentPlugin(agent)]
|
||
).replay_workflow(history)
|
||
|
||
|
||
_pausing_model_fresh_starts = 0
|
||
|
||
|
||
async def _pauses_forever_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
"""Keeps pausing its response, each segment taking more than half of the `request_timeout` below.
|
||
|
||
Only its first fresh request is served: after that it is unavailable, so the fallback moves on.
|
||
"""
|
||
global _pausing_model_fresh_starts
|
||
last = messages[-1]
|
||
segment = len(last.parts) if isinstance(last, ModelResponse) and last.state == 'suspended' else 0
|
||
if segment == 0:
|
||
_pausing_model_fresh_starts += 1
|
||
if _pausing_model_fresh_starts > 1:
|
||
raise ModelAPIError('pauses', 'unavailable')
|
||
await asyncio.sleep(0.15)
|
||
return ModelResponse(
|
||
parts=[TextPart(f'segment {segment}. ')], provider_response_id=f'segment-{segment}', state='suspended'
|
||
)
|
||
|
||
|
||
def _fallback_answer_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
return ModelResponse(parts=[TextPart('fallback answer')])
|
||
|
||
|
||
fallback_continuation_agent = Agent(
|
||
FallbackModel(
|
||
FunctionModel(_pauses_forever_fn, model_name='pauses'),
|
||
FunctionModel(_fallback_answer_fn, model_name='fallback'),
|
||
),
|
||
name='durability_fallback_continuation',
|
||
deps_type=type(None),
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
model_settings={'request_timeout': 0.25},
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class FallbackContinuationWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> list[str]:
|
||
result = await fallback_continuation_agent.run('hello')
|
||
response = result.all_messages()[-1]
|
||
assert isinstance(response, ModelResponse)
|
||
return [
|
||
result.output,
|
||
*(
|
||
f'{attempt.model_name}: {(attempt.error or "").split(":")[0]}'
|
||
for attempt in response.failed_attempts or []
|
||
),
|
||
]
|
||
|
||
|
||
@pytest.mark.moves_cache_prefix(reason=FALLBACK_REWINDS)
|
||
async def test_durability_fallback_continuation_keeps_its_deadline_across_activities(client: Client):
|
||
"""A `FallbackModel` runs inside each continuation segment's activity, and the deadline of the model it picked
|
||
carries over from one activity to the next: the second segment times out, and the fallback answers."""
|
||
global _pausing_model_fresh_starts
|
||
_pausing_model_fresh_starts = 0
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[FallbackContinuationWorkflow],
|
||
plugins=[AgentPlugin(fallback_continuation_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
FallbackContinuationWorkflow.run,
|
||
id=FallbackContinuationWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == snapshot(['fallback answer', 'pauses: ModelRequestTimeout', 'pauses: ModelAPIError'])
|
||
|
||
|
||
# --- `ModelSettings['first_event_timeout']` runs in the model activity, which sees the stream's events ---
|
||
|
||
|
||
async def _stalls_before_first_event_fn(
|
||
messages: list[ModelMessage], info: AgentInfo
|
||
) -> AsyncIterator[str | DeltaToolCalls]:
|
||
yield {} # opens the stream without producing an event
|
||
await asyncio.sleep(3600)
|
||
|
||
|
||
async def _pauses_after_first_event_fn(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str]:
|
||
yield 'partial '
|
||
await asyncio.sleep(0.1)
|
||
yield 'answer'
|
||
|
||
|
||
def _first_event_timeout_agent(name: str, stream_function: StreamFunctionDef) -> Agent[None, str]:
|
||
return Agent(
|
||
FunctionModel(stream_function=stream_function, model_name='slow'),
|
||
name=name,
|
||
deps_type=type(None),
|
||
capabilities=[ProcessEventStream(_drain_events), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
model_settings={'first_event_timeout': 0.05},
|
||
)
|
||
|
||
|
||
stalled_first_event_agent = _first_event_timeout_agent(
|
||
'durability_first_event_timeout_stalled', _stalls_before_first_event_fn
|
||
)
|
||
paused_first_event_agent = _first_event_timeout_agent(
|
||
'durability_first_event_timeout_paused', _pauses_after_first_event_fn
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class FirstEventTimeoutWorkflow:
|
||
@workflow.run
|
||
async def run(self, agent_name: str) -> str:
|
||
agent = {agent.name: agent for agent in (stalled_first_event_agent, paused_first_event_agent)}[agent_name]
|
||
try:
|
||
return (await agent.run('hello')).output
|
||
except ModelRequestTimeout as error:
|
||
return f'{type(error).__name__} {error.setting} {error.timeout}'
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
('agent', 'expected'),
|
||
[
|
||
pytest.param(stalled_first_event_agent, 'ModelRequestTimeout first_event_timeout 0.05', id='stalled'),
|
||
pytest.param(paused_first_event_agent, 'partial answer', id='paused-after-first-event'),
|
||
],
|
||
)
|
||
async def test_durability_first_event_timeout_runs_in_the_model_activity(
|
||
client: Client, agent: Agent[None, str], expected: str
|
||
):
|
||
"""The workflow only gets a streamed response once the activity has consumed it, so the activity enforces the
|
||
deadline: a stream that stalls before its first event times out, and one that pauses after it doesn't."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[FirstEventTimeoutWorkflow],
|
||
plugins=[AgentPlugin(agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
FirstEventTimeoutWorkflow.run,
|
||
args=[agent.name],
|
||
id=f'{FirstEventTimeoutWorkflow.__name__}_{agent.name}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == expected
|
||
|
||
|
||
# --- Durability with tools ---
|
||
|
||
|
||
def _tool_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
"""Model function that calls `get_country` tool then returns the result."""
|
||
# Check if we already have a tool result
|
||
for msg in reversed(messages):
|
||
for part in msg.parts:
|
||
if isinstance(part, ToolReturnPart):
|
||
return ModelResponse(parts=[TextPart(content=f'The country is: {part.content}')])
|
||
|
||
# First call: invoke the tool
|
||
if info.function_tools:
|
||
return ModelResponse(parts=[ToolCallPart(tool_name='get_country', args='{}')])
|
||
|
||
return ModelResponse(parts=[TextPart(content='no tools')]) # pragma: no cover
|
||
|
||
|
||
durability_country_toolset = FunctionToolset[Deps](tools=[get_country], id='durability_country')
|
||
|
||
|
||
_tool_fn_model = FunctionModel(_tool_model_fn)
|
||
|
||
|
||
complex_durability = TemporalDurability[Deps](deps_type=Deps, activity_config=BASE_ACTIVITY_CONFIG)
|
||
|
||
complex_durable_agent = Agent(
|
||
_tool_fn_model,
|
||
deps_type=Deps,
|
||
toolsets=[durability_country_toolset],
|
||
capabilities=[complex_durability],
|
||
name='durability_complex_agent',
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class ComplexDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str, deps: Deps) -> str:
|
||
result = await complex_durable_agent.run(prompt, deps=deps)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_agent_with_tools_in_workflow(client: Client):
|
||
"""TemporalDurability wraps toolsets and routes tool calls through activities."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[ComplexDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(complex_durable_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
ComplexDurableAgentWorkflow.run,
|
||
args=['What country?', Deps(country='France')],
|
||
id=ComplexDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'The country is: France'
|
||
|
||
|
||
# --- `RunContext.in_durable_context` ---
|
||
|
||
|
||
def _in_durable_context_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
for msg in messages:
|
||
for part in msg.parts:
|
||
if isinstance(part, ToolReturnPart):
|
||
return ModelResponse(parts=[TextPart(content=f'activity: {part.content}')])
|
||
return ModelResponse(parts=[ToolCallPart(tool_name='tool_in_durable_context', args='{}')])
|
||
|
||
|
||
async def tool_in_durable_context(ctx: RunContext[None]) -> bool:
|
||
return ctx.in_durable_context
|
||
|
||
|
||
class _ReportInDurableContext(AbstractCapability[Any]):
|
||
async def after_run(self, ctx: RunContext[Any], *, result: AgentRunResult[Any]) -> AgentRunResult[Any]:
|
||
return replace(result, output=f'workflow: {ctx.in_durable_context}, {result.output}')
|
||
|
||
|
||
_in_durable_context_agent = Agent(
|
||
FunctionModel(_in_durable_context_model_fn),
|
||
name='durability_in_durable_context',
|
||
toolsets=[FunctionToolset(tools=[tool_in_durable_context], id='in_durable_context')],
|
||
capabilities=[_ReportInDurableContext(), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class InDurableContextWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await _in_durable_context_agent.run(prompt)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_run_context_in_durable_context(client: Client):
|
||
"""`ctx.in_durable_context` is `True` in workflow code only, not in activities or outside a workflow."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[InDurableContextWorkflow],
|
||
plugins=[AgentPlugin(_in_durable_context_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
InDurableContextWorkflow.run,
|
||
args=['Hello'],
|
||
id=InDurableContextWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'workflow: True, activity: False'
|
||
|
||
result = await _in_durable_context_agent.run('Hello')
|
||
assert result.output == 'workflow: False, activity: False'
|
||
|
||
|
||
# --- Default `run_id` and `conversation_id` ---
|
||
|
||
|
||
def _stable_ids_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
returns = sum(isinstance(part, ToolReturnPart) for message in messages for part in message.parts)
|
||
if returns < 2:
|
||
return ModelResponse(parts=[ToolCallPart(tool_name='record_ids', args='{}', tool_call_id=f'call-{returns}')])
|
||
return ModelResponse(parts=[TextPart(content='done')])
|
||
|
||
|
||
_stable_ids_seen: list[tuple[str | None, str | None]] = []
|
||
|
||
|
||
async def record_ids(ctx: RunContext[object]) -> str:
|
||
_stable_ids_seen.append((ctx.run_id, ctx.conversation_id))
|
||
return 'ok'
|
||
|
||
|
||
_stable_ids_agent = Agent(
|
||
FunctionModel(_stable_ids_model_fn),
|
||
name='durability_stable_ids',
|
||
toolsets=[FunctionToolset(tools=[record_ids], id='stable_ids')],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
_stable_ids_later_draws: list[str] = []
|
||
|
||
|
||
@workflow.defn
|
||
class StableIdsWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> list[str]:
|
||
result = await _stable_ids_agent.run(prompt)
|
||
# What the workflow's own code draws next depends on how many draws the agent run made.
|
||
_stable_ids_later_draws.append(str(workflow.uuid4()))
|
||
return [result.run_id, result.conversation_id]
|
||
|
||
|
||
async def test_durability_default_ids_survive_replay(client: Client):
|
||
"""Without `run_id=` or `conversation_id=`, every replay of the workflow resolves the same IDs.
|
||
|
||
With workflow caching off, the worker replays the workflow from history for each activity result,
|
||
so before the IDs were replay-stable, each tool activity saw a different `run_id`.
|
||
"""
|
||
_stable_ids_seen.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[StableIdsWorkflow],
|
||
plugins=[AgentPlugin(_stable_ids_agent)],
|
||
max_cached_workflows=0,
|
||
):
|
||
handle = await client.start_workflow(
|
||
StableIdsWorkflow.run, args=['Hello'], id=f'stable-ids-{uuid.uuid4()}', task_queue=TASK_QUEUE
|
||
)
|
||
run_id, conversation_id = await handle.result()
|
||
assert _stable_ids_seen == [(run_id, conversation_id)] * 2
|
||
assert run_id.startswith(f'{handle.result_run_id}:')
|
||
assert conversation_id != run_id
|
||
|
||
|
||
# --- Run deadline (`timeout=`) ---
|
||
|
||
|
||
_deadline_seen: list[tuple[datetime | None, datetime | None]] = []
|
||
|
||
_deadline_sub_agent = Agent(TestModel(), name='durability_deadline_sub_agent')
|
||
|
||
|
||
@_deadline_sub_agent.tool
|
||
def _record_sub_agent_deadline(ctx: RunContext[object]) -> str:
|
||
_deadline_seen.append((None, ctx.deadline))
|
||
return 'ok'
|
||
|
||
|
||
async def record_deadline(ctx: RunContext[object]) -> str:
|
||
# An agent run from a tool inherits the run's deadline, even inside an activity.
|
||
await _deadline_sub_agent.run('sub')
|
||
_deadline_seen.append((ctx.deadline, None))
|
||
return 'ok'
|
||
|
||
|
||
def _deadline_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
returns = sum(isinstance(part, ToolReturnPart) for message in messages for part in message.parts)
|
||
if returns < 2:
|
||
return ModelResponse(
|
||
parts=[ToolCallPart(tool_name='record_deadline', args='{}', tool_call_id=f'call-{returns}')]
|
||
)
|
||
return ModelResponse(parts=[TextPart(content='done')])
|
||
|
||
|
||
_deadline_agent = Agent(
|
||
FunctionModel(_deadline_model_fn),
|
||
name='durability_deadline',
|
||
toolsets=[FunctionToolset(tools=[record_deadline], id='deadline')],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DeadlineWorkflow:
|
||
@workflow.run
|
||
async def run(self, timeout: float) -> list[str]:
|
||
start = workflow.now()
|
||
result = await _deadline_agent.run('Hello', timeout=timeout)
|
||
return [result.output, start.isoformat()]
|
||
|
||
|
||
async def test_durability_deadline_survives_replay(client: Client):
|
||
"""The deadline comes from `workflow.now()`, so every replay of the workflow computes the same one.
|
||
|
||
With workflow caching off, the worker replays the workflow from history for each activity result.
|
||
"""
|
||
_deadline_seen.clear()
|
||
timeout = 3600
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DeadlineWorkflow],
|
||
plugins=[AgentPlugin(_deadline_agent)],
|
||
max_cached_workflows=0,
|
||
):
|
||
handle = await client.start_workflow(
|
||
DeadlineWorkflow.run, args=[timeout], id=f'deadline-{uuid.uuid4()}', task_queue=TASK_QUEUE
|
||
)
|
||
output, start = await handle.result()
|
||
assert output == 'done'
|
||
deadline = datetime.fromisoformat(start) + timedelta(seconds=timeout)
|
||
# Each tool activity sees the deadline, and so does the agent it runs.
|
||
assert sorted(_deadline_seen, key=lambda seen: seen[0] is None) == [
|
||
(deadline, None),
|
||
(deadline, None),
|
||
(None, deadline),
|
||
(None, deadline),
|
||
]
|
||
|
||
|
||
_selection_seen: list[tuple[int, str | None, str | None, str | None]] = []
|
||
|
||
|
||
def _record_selection(ctx: ModelSelectionContext[object]) -> Model:
|
||
deadline = ctx.deadline.isoformat() if ctx.deadline is not None else None
|
||
_selection_seen.append((ctx.run_step, ctx.run_id, ctx.conversation_id, deadline))
|
||
assert ctx.model is not None
|
||
return ctx.model
|
||
|
||
|
||
_selection_agent = Agent(
|
||
FunctionModel(_deadline_model_fn),
|
||
name='durability_selection_run_fields',
|
||
toolsets=[FunctionToolset(tools=[record_deadline], id='deadline')],
|
||
capabilities=[SelectModel(_record_selection), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class SelectionRunFieldsWorkflow:
|
||
@workflow.run
|
||
async def run(self, timeout: float) -> tuple[list[tuple[int, str | None, str | None, str | None]], list[str]]:
|
||
# The selector runs in the workflow, so each replay records its selections afresh.
|
||
_selection_seen.clear()
|
||
start = workflow.now()
|
||
result = await _selection_agent.run('Hello', timeout=timeout)
|
||
return list(_selection_seen), [result.run_id, result.conversation_id, start.isoformat()]
|
||
|
||
|
||
async def test_durability_selector_sees_run_ids_and_deadline(client: Client):
|
||
"""A model selector in the workflow sees the run's replay-stable IDs and deadline on every step.
|
||
|
||
Step one is selected during run setup and later steps in the graph; with workflow caching off, every
|
||
activity result replays the workflow, and each replay selects with the same values.
|
||
"""
|
||
timeout = 3600
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[SelectionRunFieldsWorkflow],
|
||
plugins=[AgentPlugin(_selection_agent)],
|
||
max_cached_workflows=0,
|
||
):
|
||
workflow_id = f'selection-run-fields-{uuid.uuid4()}'
|
||
handle = await client.start_workflow(
|
||
SelectionRunFieldsWorkflow.run, args=[timeout], id=workflow_id, task_queue=TASK_QUEUE
|
||
)
|
||
selections, (run_id, conversation_id, start) = await handle.result()
|
||
deadline = (datetime.fromisoformat(start) + timedelta(seconds=timeout)).isoformat()
|
||
assert run_id.startswith(f'{handle.result_run_id}:')
|
||
assert [tuple(selection) for selection in selections] == [
|
||
(step, run_id, conversation_id, deadline) for step in (1, 2, 3)
|
||
]
|
||
|
||
|
||
async def slow_deadline_tool() -> str:
|
||
await asyncio.sleep(30)
|
||
return 'never reached' # pragma: no cover
|
||
|
||
|
||
def _call_slow_deadline_tool(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
return ModelResponse(parts=[ToolCallPart(tool_name='slow_deadline_tool', args='{}', tool_call_id='call-slow')])
|
||
|
||
|
||
_timed_out_agent = Agent(
|
||
FunctionModel(_call_slow_deadline_tool),
|
||
name='durability_timed_out',
|
||
toolsets=[FunctionToolset(tools=[slow_deadline_tool], id='slow_deadline')],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class TimedOutWorkflow:
|
||
@workflow.run
|
||
async def run(self, timeout: float) -> list[str]:
|
||
try:
|
||
await _timed_out_agent.run('Hello', timeout=timeout)
|
||
except RunTimedOut as exc:
|
||
return [type(message).__name__ for message in exc.all_messages()]
|
||
return [] # pragma: no cover
|
||
|
||
|
||
async def test_durability_timeout_fires_as_workflow_timer_and_replays(client: Client):
|
||
"""Expiry inside a workflow uses a workflow timer and replays deterministically.
|
||
|
||
How far the run gets before the timer fires depends on activity scheduling, so this asserts only that the
|
||
run timed out; the partial state a timed-out run keeps is covered by `test_run_timeout.py`.
|
||
"""
|
||
workflow_id = f'timed-out-{uuid.uuid4()}'
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[TimedOutWorkflow],
|
||
plugins=[AgentPlugin(_timed_out_agent)],
|
||
):
|
||
handle = await client.start_workflow(TimedOutWorkflow.run, args=[0.2], id=workflow_id, task_queue=TASK_QUEUE)
|
||
messages = await handle.result()
|
||
# The run timed out, with at least its prompt recorded, wherever it was when the timer fired.
|
||
assert messages[0] == 'ModelRequest'
|
||
|
||
history = await handle.fetch_history()
|
||
assert any(event.HasField('timer_fired_event_attributes') for event in history.events)
|
||
replay = await Replayer(workflows=[TimedOutWorkflow], plugins=[PydanticAIPlugin()]).replay_workflow(history)
|
||
assert replay.replay_failure is None
|
||
|
||
|
||
async def test_durability_replays_history_recorded_before_stable_default_ids(
|
||
client: Client, monkeypatch: pytest.MonkeyPatch
|
||
):
|
||
"""A history recorded before every run drew a default `run_id` replays without drawing one.
|
||
|
||
Unsandboxed, so the module-level list sees the workflow's draws in both the original run and the replay.
|
||
"""
|
||
_stable_ids_later_draws.clear()
|
||
|
||
# Without the patch marker, the workflow runs the way it did before: no draw from the workflow's
|
||
# random sequence, and a random `run_id`.
|
||
def unpatched(patch_id: str) -> bool:
|
||
return False
|
||
|
||
monkeypatch.setattr(workflow, 'patched', unpatched)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[StableIdsWorkflow],
|
||
plugins=[AgentPlugin(_stable_ids_agent)],
|
||
workflow_runner=UnsandboxedWorkflowRunner(),
|
||
):
|
||
handle = await client.start_workflow(
|
||
StableIdsWorkflow.run, args=['Hello'], id=f'legacy-ids-{uuid.uuid4()}', task_queue=TASK_QUEUE
|
||
)
|
||
run_id, _ = await handle.result()
|
||
assert ':' not in run_id
|
||
monkeypatch.undo()
|
||
|
||
history = await handle.fetch_history()
|
||
replay = await Replayer(
|
||
workflows=[StableIdsWorkflow], plugins=[PydanticAIPlugin()], workflow_runner=UnsandboxedWorkflowRunner()
|
||
).replay_workflow(history)
|
||
assert replay.replay_failure is None
|
||
# The replay drew nothing for the run's ID, so the workflow's next draw matches the recorded one.
|
||
assert len(_stable_ids_later_draws) == 2 and _stable_ids_later_draws[0] == _stable_ids_later_draws[1]
|
||
|
||
|
||
# --- A capability operation called from the capability's own tool ---
|
||
|
||
|
||
def _operation_from_tool_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
for msg in messages:
|
||
for part in msg.parts:
|
||
if isinstance(part, ToolReturnPart):
|
||
return ModelResponse(parts=[TextPart(content=str(part.content))])
|
||
return ModelResponse(parts=[ToolCallPart(tool_name='lookup', args='{}')])
|
||
|
||
|
||
class _OperationFromTool(AbstractCapability[Any]):
|
||
id = 'operation_from_tool'
|
||
|
||
@durable_operation('fetch')
|
||
async def fetch(self, ctx: RunContext[Any]) -> str:
|
||
return activity.info().activity_type
|
||
|
||
def get_toolset(self) -> FunctionToolset[Any]:
|
||
toolset = FunctionToolset[Any](id=self.id)
|
||
|
||
@toolset.tool
|
||
async def lookup(ctx: RunContext[Any]) -> str:
|
||
return await self.fetch(ctx)
|
||
|
||
return toolset
|
||
|
||
|
||
_operation_from_tool_agent = Agent(
|
||
FunctionModel(_operation_from_tool_model_fn),
|
||
name='operation_from_tool',
|
||
capabilities=[_OperationFromTool(), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class OperationFromToolWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await _operation_from_tool_agent.run(prompt)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_operation_called_from_a_tool_runs_in_the_tool_activity(client: Client):
|
||
"""The tool's activity records the operation's result, so it doesn't start an activity of its own."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[OperationFromToolWorkflow],
|
||
plugins=[AgentPlugin(_operation_from_tool_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
OperationFromToolWorkflow.run,
|
||
args=['Hello'],
|
||
id=OperationFromToolWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'agent__operation_from_tool__toolset__operation_from_tool__call_tool'
|
||
|
||
|
||
# --- Durability outside workflow (transparent passthrough) ---
|
||
|
||
|
||
async def test_durability_outside_workflow_is_transparent():
|
||
"""TemporalDurability is a no-op outside a workflow — calls pass through to the real model."""
|
||
result = await simple_durable_agent.run('Hello')
|
||
assert result.output == 'Echo: Hello'
|
||
|
||
|
||
# --- Durability wrap_run disables threads ---
|
||
|
||
|
||
_threads_durability = TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)
|
||
|
||
_threads_agent = Agent(_durability_fn_model, name='sync_tool_test', capabilities=[_threads_durability])
|
||
|
||
|
||
@workflow.defn
|
||
class ThreadsDurableWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await _threads_agent.run(prompt)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_wrap_run_disables_threads(client: Client):
|
||
"""wrap_run disables threads when inside a Temporal workflow."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[ThreadsDurableWorkflow],
|
||
plugins=[AgentPlugin(_threads_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
ThreadsDurableWorkflow.run,
|
||
args=['test'],
|
||
id='ThreadsDurableWorkflow',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'Echo: test'
|
||
|
||
|
||
# --- Durability wrap_run refuses external-event waits ---
|
||
|
||
|
||
def _approval_needed_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
return ModelResponse(parts=[ToolCallPart('delete', {'path': 'a.txt'}, tool_call_id='call-1')])
|
||
|
||
|
||
def _ask_in_process(ctx: RunContext[None], requests: DeferredToolRequests, token: str) -> None:
|
||
raise AssertionError('unreachable') # pragma: no cover
|
||
|
||
|
||
_external_event_agent = Agent(
|
||
FunctionModel(_approval_needed_fn),
|
||
name='external_event_test',
|
||
deps_type=type(None),
|
||
capabilities=[
|
||
TemporalDurability[None](activity_config=BASE_ACTIVITY_CONFIG),
|
||
HandleDeferredToolCalls[None](_ask_in_process),
|
||
],
|
||
)
|
||
|
||
|
||
@_external_event_agent.tool_plain(name='delete', requires_approval=True)
|
||
def _delete_needs_approval(path: str) -> str:
|
||
raise AssertionError('unreachable') # pragma: no cover
|
||
|
||
|
||
@workflow.defn
|
||
class ExternalEventWaitWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await _external_event_agent.run(prompt)
|
||
return result.output # pragma: no cover
|
||
|
||
|
||
async def test_durability_wrap_run_refuses_external_event_waits(client: Client):
|
||
"""A workflow can't record a wait for an external event yet, so the engine fails the workflow clearly instead of waiting in process."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[ExternalEventWaitWorkflow],
|
||
plugins=[AgentPlugin(_external_event_agent)],
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
ExternalEventWaitWorkflow.run,
|
||
args=['clean up'],
|
||
id=ExternalEventWaitWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert 'does not support waiting for external events yet' in str(exc_info.value.cause)
|
||
|
||
|
||
# --- Durability validation ---
|
||
|
||
|
||
def test_durability_requires_agent_name():
|
||
"""TemporalDurability raises UserError when agent has no name."""
|
||
durability = TemporalDurability()
|
||
with pytest.raises(UserError, match='unique `name`'):
|
||
Agent(_durability_fn_model, capabilities=[durability])
|
||
|
||
|
||
def test_durability_explicit_name_overrides_agent_name_and_supports_unnamed_agent():
|
||
named_agent = Agent(_durability_fn_model, name='agent-name', capabilities=[TemporalDurability(name='custom')])
|
||
bound = TemporalDurability.from_agent(named_agent)
|
||
assert bound is not None
|
||
assert bound.name == 'custom'
|
||
activity_names = [
|
||
ActivityDefinition.must_from_callable(activity).name # pyright: ignore[reportUnknownMemberType]
|
||
for activity in bound.temporal_activities
|
||
]
|
||
assert all(name is not None and name.startswith('agent__custom__') for name in activity_names)
|
||
|
||
unnamed_agent = Agent(_durability_fn_model, capabilities=[TemporalDurability(name='unnamed-custom')])
|
||
unnamed_bound = TemporalDurability.from_agent(unnamed_agent)
|
||
assert unnamed_bound is not None
|
||
assert unnamed_bound.name == 'unnamed-custom'
|
||
|
||
|
||
def test_durability_requires_model():
|
||
"""TemporalDurability raises UserError when the agent has no model at all."""
|
||
durability = TemporalDurability()
|
||
with pytest.raises(UserError, match='needs to have a `model`'):
|
||
Agent(name='test', capabilities=[durability])
|
||
|
||
|
||
def test_durability_rejects_default_model_key():
|
||
"""TemporalDurability raises UserError when 'default' is used in the models dict."""
|
||
with pytest.raises(UserError, match="'default' is reserved"):
|
||
Agent(
|
||
_durability_fn_model,
|
||
name='test',
|
||
capabilities=[TemporalDurability(models={'default': _durability_fn_model})],
|
||
)
|
||
|
||
|
||
def test_durability_rejects_a_second_engine():
|
||
with pytest.raises(
|
||
UserError,
|
||
match=r'An agent can have only one durable execution engine, but this one would have 2: '
|
||
r'`TemporalDurability`, `TemporalDurability`\.',
|
||
):
|
||
Agent(
|
||
_durability_fn_model,
|
||
name='duplicate_durability',
|
||
capabilities=[TemporalDurability(), TemporalDurability()],
|
||
)
|
||
|
||
|
||
def test_durability_from_agent_rejects_duplicates():
|
||
"""`Agent` refuses a second engine before binding, but `from_agent` accepts any `AbstractAgent`."""
|
||
|
||
class _TwoEngines(WrapperAgent[None, str]):
|
||
@property
|
||
def root_capability(self) -> CombinedCapability[None]:
|
||
return CombinedCapability([TemporalDurability(), TemporalDurability()])
|
||
|
||
agent = _TwoEngines(Agent(_durability_fn_model, name='duplicate_durability'))
|
||
with pytest.raises(
|
||
UserError,
|
||
match=r'Multiple TemporalDurability capabilities are attached to this agent; attach at most one\.',
|
||
):
|
||
TemporalDurability.from_agent(agent)
|
||
|
||
|
||
def test_durability_rejects_construction_inside_workflow(monkeypatch: pytest.MonkeyPatch):
|
||
"""`TemporalDurability.for_agent` rejects construction inside a workflow.
|
||
|
||
Activities have to be registered with the worker before the workflow runs, so
|
||
`for_agent` (which discovers and registers activities) must run at module level
|
||
or in worker setup code — not inside `@workflow.run`.
|
||
"""
|
||
from temporalio import workflow as _wf
|
||
|
||
monkeypatch.setattr(_wf, 'in_workflow', lambda: True)
|
||
with pytest.raises(UserError, match=r'must be constructed outside of a Temporal workflow'):
|
||
Agent(_durability_fn_model, name='test', capabilities=[TemporalDurability()])
|
||
|
||
|
||
def test_durability_image_output_rejected():
|
||
"""TemporalDurability rejects image output rather than letting it fail on payload size."""
|
||
agent = Agent(_durability_fn_model, name='test', capabilities=[TemporalDurability()])
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
with pytest.raises(UserError) as exc_info:
|
||
bound._validate_model_request_parameters( # pyright: ignore[reportPrivateUsage]
|
||
ModelRequestParameters(allow_image_output=True),
|
||
)
|
||
assert str(exc_info.value) == snapshot(
|
||
'Image output is not supported with Temporal because the image would ride the activity payload, '
|
||
'which is capped by the server blob-size limit (2MB by default, leaving about 1.5MB of raw image '
|
||
'bytes once base64-encoded).'
|
||
)
|
||
|
||
|
||
# --- Model registry ---
|
||
|
||
|
||
def test_durability_find_model_id_by_identity():
|
||
"""_find_model_id matches models by identity."""
|
||
m1 = FunctionModel(lambda messages, info: ModelResponse(parts=[TextPart(content='hi')]))
|
||
m2 = FunctionModel(lambda messages, info: ModelResponse(parts=[TextPart(content='hi')]))
|
||
agent = Agent(m1, name='test', capabilities=[TemporalDurability(models={'alt': m2})])
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
assert bound._find_model_id(m1) is None # default → None # pyright: ignore[reportPrivateUsage]
|
||
assert bound._find_model_id(m2) == 'alt' # pyright: ignore[reportPrivateUsage]
|
||
|
||
|
||
def test_durability_find_model_id_prefers_registered_wrapper_identity():
|
||
"""Temporal preserves a registered wrapper's alias before considering its inner model."""
|
||
model = FunctionModel(lambda messages, info: ModelResponse(parts=[TextPart(content='bare')]))
|
||
wrapped = WrapperModel(model)
|
||
agent = Agent(model, name='test', capabilities=[TemporalDurability(models={'wrapped': wrapped})])
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
assert bound._find_model_id(wrapped) == 'wrapped' # pyright: ignore[reportPrivateUsage]
|
||
# An unregistered wrapper (e.g. a user-built `InstrumentedModel`) around a registered
|
||
# wrapper peels off to the shallowest registered match instead of collapsing to the default.
|
||
assert bound._find_model_id(WrapperModel(wrapped)) == 'wrapped' # pyright: ignore[reportPrivateUsage]
|
||
# An unregistered wrapper around the bare default still takes the default's fast path.
|
||
assert bound._find_model_id(WrapperModel(model)) is None # pyright: ignore[reportPrivateUsage]
|
||
|
||
|
||
def test_durability_find_model_id_does_not_unwrap_registered_wrappers():
|
||
"""A registered wrapper's identity holds at its registered depth.
|
||
|
||
Its bare inner model must not inherit the wrapper's alias — the activity would rebuild the
|
||
wrapper and add behavior the request never had — so the bare model counts as unregistered.
|
||
"""
|
||
default = FunctionModel(lambda messages, info: ModelResponse(parts=[TextPart(content='default')]))
|
||
inner = FunctionModel(lambda messages, info: ModelResponse(parts=[TextPart(content='inner')]))
|
||
agent = Agent(default, name='test', capabilities=[TemporalDurability(models={'wrapped_alt': WrapperModel(inner)})])
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
with pytest.raises(UserError, match='was not registered with `TemporalDurability`'):
|
||
bound._find_model_id(inner) # pyright: ignore[reportPrivateUsage]
|
||
|
||
|
||
def test_durability_temporal_activities():
|
||
"""temporal_activities returns all registered activities after for_agent."""
|
||
agent = Agent(_durability_fn_model, name='test', capabilities=[TemporalDurability()])
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
# 5 base activities + call/validation activities for the agent's <agent> FunctionToolset
|
||
assert len(bound.temporal_activities) == 7
|
||
|
||
|
||
def test_durability_temporal_registrations_before_binding():
|
||
"""An unbound capability has no Temporal registrations."""
|
||
assert worker_registrations(TemporalDurability()) == ([], [])
|
||
|
||
|
||
def test_durability_temporal_activities_with_toolsets():
|
||
"""temporal_activities includes toolset activities for agent's toolsets."""
|
||
agent = Agent(
|
||
_durability_fn_model,
|
||
name='test',
|
||
toolsets=[FunctionToolset(id='test_toolset')],
|
||
capabilities=[TemporalDurability()],
|
||
)
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
# 5 base activities + call/validation activities for both function toolsets
|
||
assert len(bound.temporal_activities) == 9
|
||
|
||
|
||
def test_durability_temporal_activities_rejects_omitting_child_workflows():
|
||
"""Direct activity registration must fail before a worker can omit required workflows."""
|
||
|
||
async def child_tool() -> str:
|
||
return 'done' # pragma: no cover
|
||
|
||
toolset = FunctionToolset(id='child_tools')
|
||
toolset.add_function(
|
||
child_tool,
|
||
metadata={'temporal': {'child_workflow': ChildWorkflowConfig()}},
|
||
)
|
||
agent = Agent(
|
||
_durability_fn_model,
|
||
name='test',
|
||
toolsets=[toolset],
|
||
capabilities=[TemporalDurability()],
|
||
)
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
|
||
with pytest.raises(
|
||
UserError,
|
||
match=r'cannot be used when a tool is configured to run as a child workflow(?s:.*)`AgentPlugin\(agent, register_workflows=False\)`',
|
||
):
|
||
_ = bound.temporal_activities
|
||
|
||
|
||
def test_durability_temporal_activities_rejects_child_workflow_metadata_capability():
|
||
"""Selector-based child workflow metadata also requires plugin registration."""
|
||
agent = Agent(
|
||
_durability_fn_model,
|
||
name='test',
|
||
capabilities=[
|
||
SetToolMetadata(temporal={'child_workflow': ChildWorkflowConfig()}),
|
||
TemporalDurability(),
|
||
],
|
||
)
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
|
||
with pytest.raises(
|
||
UserError,
|
||
match=r'cannot be used when a tool is configured to run as a child workflow(?s:.*)`AgentPlugin\(agent, register_workflows=False\)`',
|
||
):
|
||
_ = bound.temporal_activities
|
||
|
||
|
||
def test_durability_duplicate_toolset_id_rejected():
|
||
"""Two distinct toolsets under one `id` are rejected at binding time.
|
||
|
||
The registry maps `id` → activity wrapper, so a duplicate would silently replace the
|
||
first entry and route both toolsets' calls through the last one's activities.
|
||
"""
|
||
with pytest.raises(UserError, match="Two toolsets have the same `id` 'dup'"):
|
||
Agent(
|
||
_durability_fn_model,
|
||
name='durability_dup_toolset',
|
||
toolsets=[FunctionToolset(id='dup'), FunctionToolset(id='dup')],
|
||
capabilities=[TemporalDurability()],
|
||
)
|
||
|
||
|
||
def test_durability_same_toolset_instance_reused():
|
||
"""The same toolset instance appearing twice maps to one wrapper, not an `id` conflict.
|
||
|
||
Its activities must register with the worker exactly once — Temporal rejects duplicate
|
||
activity names at worker start.
|
||
"""
|
||
ts = FunctionToolset[Any](id='shared_fn')
|
||
agent = Agent(
|
||
_durability_fn_model,
|
||
name='durability_shared_toolset',
|
||
toolsets=[ts, ts],
|
||
capabilities=[TemporalDurability()],
|
||
)
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
# 5 base activities + call/validation activities for <agent> and the shared toolset (once)
|
||
assert len(bound.temporal_activities) == 9
|
||
|
||
|
||
def test_durability_activity_config_not_mutated():
|
||
"""The capability normalizes the retry policy on copies of the caller's config.
|
||
|
||
A `RetryPolicy` (or `ActivityConfig`) shared with other Temporal activities must not
|
||
gain the capability's non-retryable error types, and constructing multiple capabilities
|
||
from the same config must not accumulate duplicate entries.
|
||
"""
|
||
retry_policy = RetryPolicy(non_retryable_error_types=['MyError'])
|
||
config = ActivityConfig(start_to_close_timeout=timedelta(seconds=60), retry_policy=retry_policy)
|
||
|
||
durability = TemporalDurability(activity_config=config)
|
||
TemporalDurability(activity_config=config)
|
||
|
||
assert retry_policy.non_retryable_error_types == ['MyError']
|
||
assert config.get('retry_policy') is retry_policy
|
||
normalized = durability.activity_config.get('retry_policy')
|
||
assert normalized is not None
|
||
assert normalized is not retry_policy
|
||
assert normalized.non_retryable_error_types == [
|
||
'MyError',
|
||
'UserError',
|
||
'PydanticUserError',
|
||
'UnexpectedModelBehavior',
|
||
'FallbackExceptionGroup',
|
||
'WorkspaceTimeoutError',
|
||
'WorkspaceOutputLimitError',
|
||
'WorkspaceReadOnlyError',
|
||
'WorkspaceUnavailableError',
|
||
'PayloadsTooLarge',
|
||
'PayloadSizeError',
|
||
]
|
||
|
||
|
||
def test_durability_custom_retry_policy_keeps_non_retryable_errors():
|
||
"""A caller-supplied `retry_policy` must not drop the framework's non-retryable errors.
|
||
|
||
A `retry_policy` in `model_activity_config` or a per-toolset config would otherwise
|
||
replace the normalized base policy wholesale, letting a `UserError` or a
|
||
continuation-ceiling `UnexpectedModelBehavior` retry the whole (paid) segment.
|
||
"""
|
||
toolset = FunctionToolset[None](id='my_toolset')
|
||
|
||
async def my_tool() -> str:
|
||
return 'ok' # pragma: no cover
|
||
|
||
toolset.add_function(my_tool)
|
||
|
||
durability = TemporalDurability(
|
||
model_activity_config=ActivityConfig(retry_policy=RetryPolicy(non_retryable_error_types=['ModelError'])),
|
||
toolset_activity_config={
|
||
'my_toolset': ActivityConfig(retry_policy=RetryPolicy(non_retryable_error_types=['ToolError'])),
|
||
},
|
||
)
|
||
agent = Agent(
|
||
_durability_fn_model,
|
||
name='custom_retry_agent',
|
||
deps_type=type(None),
|
||
toolsets=[toolset],
|
||
capabilities=[durability],
|
||
)
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
|
||
model_retry = bound._model_activity_config.get('retry_policy') # pyright: ignore[reportPrivateUsage]
|
||
assert model_retry is not None
|
||
assert model_retry.non_retryable_error_types == [
|
||
'ModelError',
|
||
'UserError',
|
||
'PydanticUserError',
|
||
'UnexpectedModelBehavior',
|
||
'FallbackExceptionGroup',
|
||
'WorkspaceTimeoutError',
|
||
'WorkspaceOutputLimitError',
|
||
'WorkspaceReadOnlyError',
|
||
'WorkspaceUnavailableError',
|
||
'PayloadsTooLarge',
|
||
'PayloadSizeError',
|
||
]
|
||
|
||
toolset_wrapper = bound._toolsets_by_id['my_toolset'] # pyright: ignore[reportPrivateUsage]
|
||
assert isinstance(toolset_wrapper, TemporalFunctionToolset)
|
||
assert toolset_wrapper.durable_config is not None
|
||
toolset_retry = toolset_wrapper.durable_config.get('retry_policy')
|
||
assert toolset_retry is not None
|
||
assert toolset_retry.non_retryable_error_types == [
|
||
'ToolError',
|
||
'UserError',
|
||
'PydanticUserError',
|
||
'UnexpectedModelBehavior',
|
||
'FallbackExceptionGroup',
|
||
'WorkspaceTimeoutError',
|
||
'WorkspaceOutputLimitError',
|
||
'WorkspaceReadOnlyError',
|
||
'WorkspaceUnavailableError',
|
||
'PayloadsTooLarge',
|
||
'PayloadSizeError',
|
||
]
|
||
|
||
|
||
def test_durability_event_stream_handler_activity_config_keeps_non_retryable_errors() -> None:
|
||
durability = TemporalDurability(
|
||
activity_config=ActivityConfig(summary='base'),
|
||
event_stream_handler_activity_config=ActivityConfig(
|
||
summary='handle stream event',
|
||
retry_policy=RetryPolicy(non_retryable_error_types=['HandlerError']),
|
||
),
|
||
)
|
||
config = durability._event_stream_handler_activity_config # pyright: ignore[reportPrivateUsage]
|
||
assert config.get('summary') == 'handle stream event'
|
||
retry_policy = config.get('retry_policy')
|
||
assert retry_policy is not None
|
||
assert retry_policy.non_retryable_error_types == [
|
||
'HandlerError',
|
||
'UserError',
|
||
'PydanticUserError',
|
||
'UnexpectedModelBehavior',
|
||
'FallbackExceptionGroup',
|
||
'WorkspaceTimeoutError',
|
||
'WorkspaceOutputLimitError',
|
||
'WorkspaceReadOnlyError',
|
||
'WorkspaceUnavailableError',
|
||
'PayloadsTooLarge',
|
||
'PayloadSizeError',
|
||
]
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
'kwargs,expected',
|
||
[
|
||
pytest.param(
|
||
{'activity_config': {'timeout': timedelta(seconds=1)}},
|
||
'Invalid Temporal `ActivityConfig` in `activity_config`',
|
||
id='activity_config',
|
||
),
|
||
pytest.param(
|
||
{'model_activity_config': {'start_to_close': timedelta(seconds=1)}},
|
||
'Invalid Temporal `ActivityConfig` in `model_activity_config`',
|
||
id='model_activity_config',
|
||
),
|
||
pytest.param(
|
||
{'event_stream_handler_activity_config': {'summry': 'oops', 'task_q': 'oops'}},
|
||
'Invalid Temporal `ActivityConfig` in `event_stream_handler_activity_config`',
|
||
id='event_stream_handler_activity_config',
|
||
),
|
||
pytest.param(
|
||
{'toolset_activity_config': {'my_toolset': {'my_tool': False}}},
|
||
"Invalid Temporal `ActivityConfig` in `toolset_activity_config['my_toolset']`",
|
||
id='toolset_activity_config',
|
||
),
|
||
pytest.param(
|
||
{'model_activity_config': {'start_to_close_timeout': 'five minutes'}},
|
||
'Invalid Temporal `ActivityConfig` in `model_activity_config`',
|
||
id='unusable-value',
|
||
),
|
||
],
|
||
)
|
||
def test_durability_rejects_unknown_activity_config_keys(kwargs: dict[str, Any], expected: str):
|
||
"""An `ActivityConfig` key Temporal doesn't know fails at construction, not mid-workflow.
|
||
|
||
`ActivityConfig` is a `total=False` `TypedDict`, so an unknown key survives construction and
|
||
would only fail when it's splatted into `workflow.start_activity()` inside workflow code —
|
||
where the resulting `TypeError` isn't a `workflow_failure_exception_types` member and so fails
|
||
the workflow *task*, which Temporal retries forever. The last case is the shape reported in
|
||
#6917: a per-tool map (which belongs in tool `metadata`) passed as a toolset's config.
|
||
"""
|
||
with pytest.raises(UserError, match=re.escape(expected)):
|
||
TemporalDurability(**kwargs)
|
||
|
||
|
||
def test_durability_coerces_activity_config_values():
|
||
"""Validation keeps the coerced config, not the caller's raw one.
|
||
|
||
A config that round-tripped through JSON carries `'PT5M'` where Temporal wants a `timedelta`.
|
||
That validates fine, so only *keeping* the coerced result stops the raw string from reaching
|
||
`workflow.start_activity()` and wedging the workflow task — the same failure an unknown key
|
||
causes, just via a value.
|
||
"""
|
||
durability = TemporalDurability(
|
||
activity_config={'start_to_close_timeout': 'PT5M'}, # pyright: ignore[reportArgumentType]
|
||
toolset_activity_config={'my_toolset': {'schedule_to_close_timeout': 'PT9M'}}, # pyright: ignore[reportArgumentType]
|
||
)
|
||
|
||
assert durability.activity_config.get('start_to_close_timeout') == timedelta(minutes=5)
|
||
assert durability._model_activity_config.get('start_to_close_timeout') == timedelta(minutes=5) # pyright: ignore[reportPrivateUsage]
|
||
toolset_config = durability._toolset_activity_config['my_toolset'] # pyright: ignore[reportPrivateUsage]
|
||
assert toolset_config.get('schedule_to_close_timeout') == timedelta(minutes=9)
|
||
|
||
|
||
def test_durability_activity_config_tolerates_unschemable_annotations(monkeypatch: pytest.MonkeyPatch):
|
||
"""A new `ActivityConfig` key Pydantic can't schema must not break module import.
|
||
|
||
temporalio 1.34 added `event_groups: Sequence[EventGroup] | None` to `ActivityConfig`
|
||
(#9572), which made the module-level `TypeAdapter(_ValidatedActivityConfig)` build raise
|
||
`PydanticSchemaGenerationError` at import. The locked temporalio predates that key, so this
|
||
test imports the production module under an isolated name so the test does not replace
|
||
class identities held by already-imported Temporal integration modules.
|
||
"""
|
||
|
||
class _EventGroup:
|
||
"""Stands in for a temporalio type Pydantic has no schema for."""
|
||
|
||
source_agent = TemporalAgent( # pyright: ignore[reportDeprecated]
|
||
Agent(_durability_fn_model, name='activity_registration_source', deps_type=type(None))
|
||
)
|
||
sentinel_activity: Callable[..., object] = source_agent.temporal_activities[0]
|
||
|
||
class _CustomTemporalToolset(TemporalWrapperToolset[None]):
|
||
@property
|
||
def temporal_activities(self) -> list[Callable[..., object]]:
|
||
return [sentinel_activity]
|
||
|
||
def temporalize_toolset(
|
||
toolset: AbstractToolset[None],
|
||
activity_name_prefix: str,
|
||
activity_config: ActivityConfig,
|
||
tool_activity_config: dict[str, ActivityConfig | Literal[False]],
|
||
deps_type: type[None],
|
||
run_context_type: type[TemporalRunContext[None]],
|
||
agent: object | None,
|
||
) -> AbstractToolset[None]:
|
||
return _CustomTemporalToolset(toolset)
|
||
|
||
existing_agent = TemporalAgent( # pyright: ignore[reportDeprecated]
|
||
Agent(
|
||
_durability_fn_model,
|
||
name='unschemable_before_import',
|
||
deps_type=type(None),
|
||
toolsets=[FunctionToolset[None](id='custom')],
|
||
),
|
||
temporalize_toolset_func=temporalize_toolset,
|
||
)
|
||
assert sentinel_activity in existing_agent.temporal_activities
|
||
|
||
annotations = dict(ActivityConfig.__annotations__)
|
||
annotations['event_groups'] = Sequence[_EventGroup] | None
|
||
with monkeypatch.context() as import_patch:
|
||
import_patch.setattr(ActivityConfig, '__annotations__', annotations)
|
||
module_name = f'{temporal_toolset.__name__}__unschemable_test'
|
||
module_spec = importlib.util.spec_from_file_location(module_name, temporal_toolset.__file__)
|
||
assert module_spec is not None
|
||
assert module_spec.loader is not None
|
||
imported_module = importlib.util.module_from_spec(module_spec)
|
||
import_patch.setitem(sys.modules, module_name, imported_module)
|
||
module_spec.loader.exec_module(imported_module)
|
||
validate_activity_config: Callable[[ActivityConfig, str], ActivityConfig] = (
|
||
imported_module.validate_activity_config
|
||
)
|
||
|
||
# The import must complete with the plain-class annotation while validation stays strict.
|
||
with pytest.raises(UserError, match='unknown_key'):
|
||
validate_activity_config(cast(ActivityConfig, {'unknown_key': 1}), 'activity_config')
|
||
|
||
with pytest.raises(UserError, match='event_groups'):
|
||
validate_activity_config(cast(ActivityConfig, {'event_groups': [object()]}), 'activity_config')
|
||
|
||
# The unschemable type passes through while an ISO duration keeps its coercion.
|
||
event_group = _EventGroup()
|
||
config = validate_activity_config(
|
||
cast(ActivityConfig, {'start_to_close_timeout': 'PT5M', 'event_groups': [event_group]}),
|
||
'activity_config',
|
||
)
|
||
expected_config: dict[str, object] = {
|
||
'start_to_close_timeout': timedelta(minutes=5),
|
||
'event_groups': [event_group],
|
||
}
|
||
assert config == expected_config
|
||
|
||
# A new agent still registers custom wrapper activities after the import check restores SDK state.
|
||
custom_agent = TemporalAgent( # pyright: ignore[reportDeprecated]
|
||
Agent(
|
||
_durability_fn_model,
|
||
name='unschemable_after_import',
|
||
deps_type=type(None),
|
||
toolsets=[FunctionToolset[None](id='custom')],
|
||
),
|
||
temporalize_toolset_func=temporalize_toolset,
|
||
)
|
||
assert sentinel_activity in custom_agent.temporal_activities
|
||
# Both of each agent's toolsets return the same sentinel, which the plugin registers once.
|
||
assert AgentPlugin(custom_agent).configure_worker({}) == {
|
||
'activities': list(dict.fromkeys(custom_agent.temporal_activities)),
|
||
'workflows': [],
|
||
}
|
||
assert AgentPlugin(existing_agent).configure_worker({}) == {
|
||
'activities': list(dict.fromkeys(existing_agent.temporal_activities)),
|
||
'workflows': [],
|
||
}
|
||
|
||
|
||
def test_durability_shared_instance_across_agents():
|
||
"""Same TemporalDurability instance can be reused across multiple agents.
|
||
|
||
for_agent returns a new bound copy; the original stays pristine.
|
||
"""
|
||
durability = TemporalDurability()
|
||
a1 = Agent(_durability_fn_model, name='a1', capabilities=[durability])
|
||
a2 = Agent(_durability_fn_model, name='a2', capabilities=[durability])
|
||
# Original is unbound
|
||
assert durability.name == ''
|
||
assert durability.temporal_activities == []
|
||
# Each agent has its own bound copy
|
||
b1 = TemporalDurability.from_agent(a1)
|
||
b2 = TemporalDurability.from_agent(a2)
|
||
assert b1 is not None and b2 is not None
|
||
assert b1 is not b2
|
||
assert b1.name == 'a1'
|
||
assert b2.name == 'a2'
|
||
|
||
|
||
# --- _find_model_id rejects unregistered models ---
|
||
|
||
|
||
_rt_primary_model = FunctionModel(_durability_model_fn, model_name='primary')
|
||
|
||
_rt_alt_model = FunctionModel(
|
||
lambda messages, info: ModelResponse(parts=[TextPart(content='alt-response')]),
|
||
model_name='alt',
|
||
)
|
||
|
||
_rt_durability = TemporalDurability(models={'alt': _rt_alt_model}, activity_config=BASE_ACTIVITY_CONFIG)
|
||
|
||
_rt_agent = Agent(_rt_primary_model, name='runtime_model_test', capabilities=[_rt_durability])
|
||
|
||
|
||
@workflow.defn
|
||
class RuntimeModelWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await _rt_agent.run(prompt, model=_rt_alt_model)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_runtime_registered_model_is_used(client: Client):
|
||
"""agent.run(model=registered_model) routes through the registered model's activity."""
|
||
async with Worker(
|
||
client, task_queue=TASK_QUEUE, workflows=[RuntimeModelWorkflow], plugins=[AgentPlugin(_rt_agent)]
|
||
):
|
||
output = await client.execute_workflow(
|
||
RuntimeModelWorkflow.run,
|
||
args=['ignored'],
|
||
id='RuntimeModelWorkflow',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'alt-response'
|
||
|
||
|
||
async def test_durability_resolve_model_id_uses_models_registry():
|
||
"""resolve_model_id maps a registered model-id string to its registered Model instance."""
|
||
primary = FunctionModel(_durability_model_fn, model_name='primary')
|
||
alt = FunctionModel(_durability_model_fn, model_name='alt')
|
||
|
||
durability = TemporalDurability(models={'alt': alt}, activity_config=BASE_ACTIVITY_CONFIG)
|
||
agent = Agent(primary, name='resolve_registry_test', capabilities=[durability])
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
resolution_ctx = ModelResolutionContext[Any](agent=agent, deps=None)
|
||
|
||
# String matches a registered model → returns that exact instance.
|
||
assert await bound.resolve_model_id(resolution_ctx, model_id='alt') is alt
|
||
|
||
# String not in registry → defer (None) so the default `infer_model` flow — or a
|
||
# user's `ResolveModelId` capability — handles it, and so an exception raised by a
|
||
# user resolver is never masked by this capability's backstop.
|
||
assert await bound.resolve_model_id(resolution_ctx, model_id='test') is None
|
||
|
||
|
||
async def test_durability_default_string_registered_in_models_becomes_default():
|
||
"""A `models=` key equal to the agent's raw default model string supplies the default instance.
|
||
|
||
The user explicitly mapped that string to an instance, so binding uses it as `'default'`
|
||
(rather than building an orphaned one via `infer_model`), and run-time resolution of the
|
||
default string returns the same instance — keeping the identity match that gives the
|
||
default the `model_id=None` fast path across the activity boundary.
|
||
"""
|
||
custom = FunctionModel(_durability_model_fn, model_name='custom-default')
|
||
durability = TemporalDurability(models={'test': custom}, activity_config=BASE_ACTIVITY_CONFIG)
|
||
agent = Agent('test', name='default_collision_test', capabilities=[durability])
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
|
||
assert await bound.resolve_model_id(ModelResolutionContext(agent=agent, deps=None), model_id='test') is custom
|
||
assert bound._find_model_id(custom) is None # identity-matches 'default' # pyright: ignore[reportPrivateUsage]
|
||
|
||
|
||
async def test_durability_default_string_not_in_models_defers_to_resolution_chain():
|
||
"""A plain string default isn't resolved at bind time — it defers to run-time resolution.
|
||
|
||
Building the default eagerly here could construct the wrong provider — with its
|
||
authentication/configuration side effects — before a sibling `ResolveModelId` gets to
|
||
reinterpret the string, so no `'default'` is registered and the raw string re-resolves
|
||
through the capability chain (or `infer_model`) on the worker.
|
||
"""
|
||
durability = TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)
|
||
agent = Agent('test', name='default_defers_test', capabilities=[durability])
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
|
||
# No concrete default was built at bind time, so the registry is empty and resolving the
|
||
# default string defers (`None`) to the chain / `infer_model` rather than a pre-built instance.
|
||
assert bound._models_by_id == {} # pyright: ignore[reportPrivateUsage]
|
||
assert await bound.resolve_model_id(ModelResolutionContext(agent=agent, deps=None), model_id='test') is None
|
||
|
||
|
||
# --- Deps-aware model resolution via the `ResolveModelId` capability ---
|
||
|
||
|
||
def _tenant_resolver(ctx: ModelResolutionContext[str], model_id: str) -> FunctionModel | None:
|
||
"""Resolve the 'tenant-model' alias to a model built from the run's deps.
|
||
|
||
Matches the alias exactly: the run's original model-id string (not the resolved
|
||
model's `'function:tenant-model'`) is what crosses the durable boundary, so the
|
||
worker-side re-resolution sees the same string the caller wrote.
|
||
"""
|
||
if model_id != 'tenant-model':
|
||
return None
|
||
tenant = ctx.deps
|
||
|
||
def fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
return ModelResponse(parts=[TextPart(content=f'tenant:{tenant}')])
|
||
|
||
return FunctionModel(fn, model_name='tenant-model')
|
||
|
||
|
||
_tenant_agent = Agent(
|
||
_rt_primary_model,
|
||
name='tenant_resolver_test',
|
||
deps_type=str,
|
||
capabilities=[ResolveModelId(_tenant_resolver), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class TenantModelWorkflow:
|
||
@workflow.run
|
||
async def run(self, tenant: str) -> str:
|
||
result = await _tenant_agent.run('hi', model='tenant-model', deps=tenant)
|
||
# A string the resolver doesn't recognize defers to the default `infer_model` flow.
|
||
fallthrough = await _tenant_agent.run('hi', model='test', deps=tenant)
|
||
return f'{result.output} | {fallthrough.output}'
|
||
|
||
|
||
async def test_durability_resolve_model_id_capability_is_deps_aware(client: Client):
|
||
"""A deps-aware `ResolveModelId` resolver rebuilds the model with the run's deps inside the activity.
|
||
|
||
The response content is produced by the model *inside* the model-request activity, so it
|
||
proves the activity re-ran the capability chain with the deserialized deps — not just that
|
||
the workflow-side resolution saw them.
|
||
|
||
The resolver is deliberately *synchronous*: workflow-side resolution runs before
|
||
`TemporalDurability.wrap_run`'s `disable_threads()` guard is active, so this also pins
|
||
that `ResolveModelId` invokes sync resolvers inline rather than via a thread executor
|
||
(which is unavailable inside the deterministic workflow sandbox and would hang).
|
||
"""
|
||
async with Worker(
|
||
client, task_queue=TASK_QUEUE, workflows=[TenantModelWorkflow], plugins=[AgentPlugin(_tenant_agent)]
|
||
):
|
||
for tenant in ('acme', 'globex'):
|
||
output = await client.execute_workflow(
|
||
TenantModelWorkflow.run,
|
||
args=[tenant],
|
||
id=f'TenantModelWorkflow-{tenant}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == f'tenant:{tenant} | success (no tool calls)'
|
||
|
||
|
||
_alias_default_agent = Agent(
|
||
'tenant-model',
|
||
name='alias_default_test',
|
||
deps_type=str,
|
||
capabilities=[ResolveModelId(_tenant_resolver), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class AliasDefaultWorkflow:
|
||
@workflow.run
|
||
async def run(self, tenant: str) -> str:
|
||
result = await _alias_default_agent.run('hi', deps=tenant)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_alias_default_model(client: Client):
|
||
"""An agent whose *default* model is an alias only a `ResolveModelId` capability can resolve.
|
||
|
||
`infer_model` can't build `'tenant-model'`, so binding registers no concrete default;
|
||
every request carries the raw alias string across the activity boundary and the
|
||
worker-side chain re-resolves it with the run's deps.
|
||
"""
|
||
async with Worker(
|
||
client, task_queue=TASK_QUEUE, workflows=[AliasDefaultWorkflow], plugins=[AgentPlugin(_alias_default_agent)]
|
||
):
|
||
output = await client.execute_workflow(
|
||
AliasDefaultWorkflow.run,
|
||
args=['acme'],
|
||
id='AliasDefaultWorkflow',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'tenant:acme'
|
||
|
||
|
||
# --- Outer capability swaps `request_context.model` inside a workflow ---
|
||
|
||
|
||
# The swapped-in model never runs — the request is rejected before it is dispatched — so this
|
||
# reuses the shared durability model function rather than defining an unreachable one.
|
||
_swap_target_registered = FunctionModel(_durability_model_fn)
|
||
|
||
|
||
class _SwapModelCapability(AbstractCapability[Any]):
|
||
"""Outer capability that swaps the request's model to a fresh, unregistered instance."""
|
||
|
||
async def before_model_request(
|
||
self, ctx: RunContext[Any], request_context: ModelRequestContext
|
||
) -> ModelRequestContext:
|
||
request_context.model = FunctionModel(_durability_model_fn)
|
||
return request_context
|
||
|
||
|
||
_swap_model_durability = TemporalDurability(
|
||
# A *different* instance is registered under the same `model_id`: registration is matched by
|
||
# identity, so the swapped-in instance is still unregistered.
|
||
models={_swap_target_registered.model_id: _swap_target_registered},
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
)
|
||
|
||
_swap_model_agent = Agent(
|
||
_durability_fn_model,
|
||
name='durability_swap_model_agent',
|
||
capabilities=[_SwapModelCapability(), _swap_model_durability],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class SwapModelWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await _swap_model_agent.run(prompt)
|
||
return result.output # pragma: no cover
|
||
|
||
|
||
async def test_durability_outer_capability_model_swap_rejected(client: Client):
|
||
"""A model swapped in by an outer capability's `before_model_request` is rejected too.
|
||
|
||
Managed-style capabilities sit outside the durability capability and may replace
|
||
`request_context.model` with a freshly-built instance the registry has never seen. Another
|
||
instance registered under the same `model_id` doesn't make it registered — registration is
|
||
matched by identity, and rebuilding from a `model_id` is exactly the assumption this rejects.
|
||
Such a capability should supply its model through `resolve_model_id` (from a string) instead.
|
||
"""
|
||
async with Worker(
|
||
client, task_queue=TASK_QUEUE, workflows=[SwapModelWorkflow], plugins=[AgentPlugin(_swap_model_agent)]
|
||
):
|
||
with workflow_raises(
|
||
UserError,
|
||
snapshot(
|
||
"The model instance 'function:function:_durability_model_fn:' was not registered with `TemporalDurability`, so it cannot be used inside a workflow. A `Model` instance cannot be serialized across the activity boundary, and rebuilding it from its `model_id` would build a different model — the same model name on the provider the worker environment implies — so the request would go to another endpoint with other credentials. Register the instance in `models=` on `TemporalDurability` and reference it by key (or pass the registered instance), or pass a model-name string and build the instance from it with a `ResolveModelId` capability."
|
||
),
|
||
):
|
||
await client.execute_workflow(
|
||
SwapModelWorkflow.run,
|
||
args=['ignored'],
|
||
id='SwapModelWorkflow',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
|
||
# --- Unregistered `Model` instances are rejected ---
|
||
|
||
|
||
# A per-tenant endpoint and API key: rebuilding this from `'openai:gpt-5.6-sol'` on the worker
|
||
# would quietly send the request to `api.openai.com` with the ambient key instead.
|
||
_tenant_endpoint_model = OpenAIChatModel(
|
||
'gpt-5.6-sol',
|
||
provider=OpenAIProvider(api_key='tenant-key', base_url='https://tenant.example.com/v1', http_client=http_client),
|
||
)
|
||
|
||
|
||
_unregistered_instance_agent = Agent(
|
||
_rt_primary_model,
|
||
name='durability_unregistered_instance',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class UnregisteredModelInstanceWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await _unregistered_instance_agent.run(prompt, model=_tenant_endpoint_model)
|
||
return result.output # pragma: no cover
|
||
|
||
|
||
async def test_durability_unregistered_model_instance_errors(client: Client):
|
||
"""An unregistered `Model` instance is rejected in the workflow, before any activity runs.
|
||
|
||
A `Model` can't be serialized into an activity, and rebuilding this one from its `model_id`
|
||
would build the same model name on the default provider — dropping the tenant's `base_url` and
|
||
API key, so the request would silently go to `api.openai.com` with the worker's credentials.
|
||
Registering the instance in `models=`, or passing a string a `ResolveModelId` capability builds
|
||
on the worker, are the two supported paths.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[UnregisteredModelInstanceWorkflow],
|
||
plugins=[AgentPlugin(_unregistered_instance_agent)],
|
||
):
|
||
with workflow_raises(
|
||
UserError,
|
||
snapshot(
|
||
"The model instance 'openai:gpt-5.6-sol' was not registered with `TemporalDurability`, so it cannot be used inside a workflow. A `Model` instance cannot be serialized across the activity boundary, and rebuilding it from its `model_id` would build a different model — the same model name on the provider the worker environment implies — so the request would go to another endpoint with other credentials. Register the instance in `models=` on `TemporalDurability` and reference it by key (or pass the registered instance), or pass a model-name string and build the instance from it with a `ResolveModelId` capability."
|
||
),
|
||
):
|
||
await client.execute_workflow(
|
||
UnregisteredModelInstanceWorkflow.run,
|
||
args=['ignored'],
|
||
id='UnregisteredModelInstanceWorkflow',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
|
||
# --- Runtime capability validation ---
|
||
|
||
|
||
async def test_durability_validates_only_resolved_runtime_capability_layers():
|
||
"""Temporal accepts resolved and safe per-run layers but rejects per-run dynamic layers."""
|
||
|
||
@dataclass
|
||
class _BaseOne(AbstractCapability[None]):
|
||
pass
|
||
|
||
@dataclass
|
||
class _BaseTwo(AbstractCapability[None]):
|
||
pass
|
||
|
||
@dataclass
|
||
class _ExtraOne(AbstractCapability[None]):
|
||
pass
|
||
|
||
@dataclass
|
||
class _ExtraTwo(AbstractCapability[None]):
|
||
pass
|
||
|
||
@dataclass
|
||
class _SkipRequest(AbstractCapability[None]):
|
||
async def before_model_request(
|
||
self, ctx: RunContext[None], request_context: ModelRequestContext
|
||
) -> ModelRequestContext:
|
||
raise SkipModelRequest(ModelResponse(parts=[TextPart(content='skipped')]))
|
||
|
||
def base_factory(ctx: RunContext[None]) -> AbstractCapability[None]:
|
||
return CombinedCapability([_BaseOne(), _BaseTwo(), _SkipRequest()])
|
||
|
||
def extra_factory(ctx: RunContext[None]) -> AbstractCapability[None]:
|
||
return CombinedCapability([_ExtraOne(), _ExtraTwo()])
|
||
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='runtime_capability_layers',
|
||
deps_type=type(None),
|
||
capabilities=[base_factory, WrapperCapability(wrapped=TemporalDurability())],
|
||
)
|
||
|
||
# Only `in_workflow` is faked, so keep the default-ID hook and replay telemetry off the real workflow APIs.
|
||
with (
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.in_workflow', return_value=True),
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.patched', return_value=False),
|
||
patch(
|
||
'pydantic_ai.durable_exec.temporal._durability.workflow.unsafe.is_replaying_history_events',
|
||
return_value=False,
|
||
),
|
||
):
|
||
result = await agent.run('hello', capabilities=[Instrumentation(InstrumentationSettings())])
|
||
assert result.output == 'skipped'
|
||
|
||
with pytest.raises(UserError, match='Capabilities added per-run inside a Temporal workflow'):
|
||
await agent.run('hello', capabilities=[extra_factory])
|
||
|
||
|
||
# --- get_serialization_name returns None ---
|
||
|
||
|
||
class _SentinelContinueAsNew(BaseException):
|
||
"""Stand in for `temporalio.workflow.ContinueAsNewError`, which cannot be instantiated directly."""
|
||
|
||
|
||
@dataclass
|
||
class _SkipRequestAfterDurability(AbstractCapability[None]):
|
||
"""Skip the model request after `TemporalDurability.before_model_request` runs."""
|
||
|
||
def get_ordering(self) -> CapabilityOrdering | None:
|
||
return CapabilityOrdering(position='innermost', wrapped_by=[TemporalDurability])
|
||
|
||
async def before_model_request(
|
||
self, ctx: RunContext[None], request_context: ModelRequestContext
|
||
) -> ModelRequestContext:
|
||
raise SkipModelRequest(ModelResponse(parts=[TextPart(content='skipped')]))
|
||
|
||
|
||
async def test_durability_continue_as_new_none_is_passthrough():
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='can_none_passthrough',
|
||
deps_type=NoneType,
|
||
capabilities=[TemporalDurability(), _SkipRequestAfterDurability()],
|
||
)
|
||
|
||
with (
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.in_workflow', return_value=True),
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.patched', return_value=False),
|
||
patch(
|
||
'pydantic_ai.durable_exec.temporal._durability.workflow.info',
|
||
return_value=SimpleNamespace(is_continue_as_new_suggested=lambda: True),
|
||
),
|
||
):
|
||
result = await agent.run('hello')
|
||
|
||
assert result.output == 'skipped'
|
||
|
||
|
||
@pytest.mark.parametrize('stream', [False, True])
|
||
@pytest.mark.parametrize('is_async', [False, True])
|
||
async def test_durability_continue_as_new_invokes_user_callable(stream: bool, is_async: bool):
|
||
received_contexts: list[RunContext[None]] = []
|
||
|
||
def sync_continue_as_new(ctx: RunContext[None]) -> None:
|
||
received_contexts.append(ctx)
|
||
raise _SentinelContinueAsNew
|
||
|
||
async def async_continue_as_new(ctx: RunContext[None]) -> None:
|
||
sync_continue_as_new(ctx)
|
||
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='can_invoked',
|
||
deps_type=NoneType,
|
||
capabilities=[TemporalDurability(continue_as_new=async_continue_as_new if is_async else sync_continue_as_new)],
|
||
)
|
||
|
||
with (
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.in_workflow', return_value=True),
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.patched', return_value=False),
|
||
patch(
|
||
'pydantic_ai.durable_exec.temporal._durability.workflow.info',
|
||
return_value=SimpleNamespace(is_continue_as_new_suggested=lambda: True),
|
||
),
|
||
):
|
||
with pytest.raises(_SentinelContinueAsNew):
|
||
if stream:
|
||
async with agent.run_stream('hello'):
|
||
pass # pragma: no cover
|
||
else:
|
||
await agent.run('hello')
|
||
|
||
assert len(received_contexts) == 1
|
||
assert received_contexts[0].messages == snapshot(
|
||
[
|
||
ModelRequest(
|
||
parts=[UserPromptPart(content='hello', timestamp=IsDatetime())],
|
||
timestamp=IsDatetime(),
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
)
|
||
]
|
||
)
|
||
|
||
|
||
async def test_durability_continue_as_new_deferred_by_user_callable():
|
||
"""Returning without calling `workflow.continue_as_new()` lets the model request proceed."""
|
||
received_run_steps: list[int] = []
|
||
|
||
def continue_as_new(ctx: RunContext[None]) -> None:
|
||
received_run_steps.append(ctx.run_step)
|
||
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='can_deferred',
|
||
deps_type=NoneType,
|
||
capabilities=[
|
||
TemporalDurability(continue_as_new=continue_as_new),
|
||
_SkipRequestAfterDurability(),
|
||
],
|
||
)
|
||
|
||
with (
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.in_workflow', return_value=True),
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.patched', return_value=False),
|
||
patch(
|
||
'pydantic_ai.durable_exec.temporal._durability.workflow.info',
|
||
return_value=SimpleNamespace(is_continue_as_new_suggested=lambda: True),
|
||
),
|
||
):
|
||
result = await agent.run('hello')
|
||
|
||
assert result.output == 'skipped'
|
||
assert received_run_steps == [1]
|
||
|
||
|
||
_continue_as_new_model_requests: list[list[ModelMessage]] = []
|
||
|
||
|
||
def _continue_as_new_model_fn(messages: list[ModelMessage], _: AgentInfo) -> ModelResponse:
|
||
_continue_as_new_model_requests.append(messages)
|
||
tool_return = next(
|
||
(
|
||
part
|
||
for message in messages
|
||
for part in message.parts
|
||
if isinstance(part, ToolReturnPart) and part.tool_name == 'record_transition'
|
||
),
|
||
None,
|
||
)
|
||
if tool_return is None:
|
||
return ModelResponse(
|
||
parts=[ToolCallPart('record_transition', {'value': 'first request completed'}, tool_call_id='transition')],
|
||
usage=RequestUsage(input_tokens=2, output_tokens=3),
|
||
)
|
||
return ModelResponse(
|
||
parts=[TextPart(f'successor received: {tool_return.content}')],
|
||
usage=RequestUsage(input_tokens=5, output_tokens=7),
|
||
)
|
||
|
||
|
||
def _continue_as_new(ctx: RunContext[None]) -> None:
|
||
workflow.continue_as_new(args=[None, ctx.messages, ctx.usage])
|
||
|
||
|
||
_continue_as_new_durability = TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
continue_as_new=_continue_as_new,
|
||
)
|
||
_continue_as_new_agent = Agent(
|
||
FunctionModel(_continue_as_new_model_fn),
|
||
name='continue_as_new_agent',
|
||
deps_type=NoneType,
|
||
capabilities=[_continue_as_new_durability],
|
||
)
|
||
|
||
|
||
@_continue_as_new_agent.tool_plain
|
||
def record_transition(value: str) -> str:
|
||
return value
|
||
|
||
|
||
@dataclass
|
||
class ContinueAsNewResult:
|
||
output: str
|
||
messages: list[ModelMessage]
|
||
usage: RunUsage
|
||
continued_run_id: str | None
|
||
|
||
|
||
@workflow.defn
|
||
class ContinueAsNewWorkflow:
|
||
@workflow.run
|
||
async def run(
|
||
self,
|
||
prompt: str | None,
|
||
message_history: list[ModelMessage] | None = None,
|
||
usage: RunUsage | None = None,
|
||
) -> ContinueAsNewResult:
|
||
result = await _continue_as_new_agent.run(prompt, message_history=message_history, usage=usage)
|
||
return ContinueAsNewResult(
|
||
output=result.output,
|
||
messages=result.all_messages(),
|
||
usage=result.usage,
|
||
continued_run_id=workflow.info().continued_run_id,
|
||
)
|
||
|
||
|
||
async def test_durability_continue_as_new_real_workflow_transition(client: Client):
|
||
_continue_as_new_model_requests.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[ContinueAsNewWorkflow],
|
||
plugins=[AgentPlugin(_continue_as_new_agent)],
|
||
):
|
||
result = await client.execute_workflow(
|
||
ContinueAsNewWorkflow.run,
|
||
args=['start', None, None],
|
||
id=ContinueAsNewWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert result.output == 'successor received: first request completed'
|
||
assert result.continued_run_id is not None
|
||
assert result.usage == RunUsage(requests=2, input_tokens=7, output_tokens=10, tool_calls=1)
|
||
# The successor run continues the conversation (same `conversation_id`) under a new `run_id`;
|
||
# everything up to the tool return was recorded by the predecessor run.
|
||
predecessor_run_id = IsSameStr()
|
||
conversation_id = IsSameStr()
|
||
assert result.messages == snapshot(
|
||
[
|
||
ModelRequest(
|
||
parts=[UserPromptPart(content='start', timestamp=IsDatetime())],
|
||
timestamp=IsDatetime(),
|
||
run_id=predecessor_run_id,
|
||
conversation_id=conversation_id,
|
||
),
|
||
ModelResponse(
|
||
parts=[
|
||
ToolCallPart(
|
||
tool_name='record_transition',
|
||
args={'value': 'first request completed'},
|
||
tool_call_id='transition',
|
||
)
|
||
],
|
||
usage=RequestUsage(input_tokens=2, output_tokens=3),
|
||
model_name='function:_continue_as_new_model_fn:',
|
||
model_id='function:function:_continue_as_new_model_fn:',
|
||
timestamp=IsDatetime(),
|
||
run_id=predecessor_run_id,
|
||
conversation_id=conversation_id,
|
||
),
|
||
ModelRequest(
|
||
parts=[
|
||
ToolReturnPart(
|
||
tool_name='record_transition',
|
||
content='first request completed',
|
||
tool_call_id='transition',
|
||
timestamp=IsDatetime(),
|
||
)
|
||
],
|
||
timestamp=IsDatetime(),
|
||
run_id=predecessor_run_id,
|
||
conversation_id=conversation_id,
|
||
),
|
||
ModelResponse(
|
||
parts=[TextPart(content='successor received: first request completed')],
|
||
usage=RequestUsage(input_tokens=5, output_tokens=7),
|
||
model_name='function:_continue_as_new_model_fn:',
|
||
model_id='function:function:_continue_as_new_model_fn:',
|
||
timestamp=IsDatetime(),
|
||
run_id=IsStr(),
|
||
conversation_id=conversation_id,
|
||
),
|
||
]
|
||
)
|
||
assert result.messages[3].run_id != result.messages[0].run_id
|
||
# The predecessor's request, then the successor's, which resends the carried-over history.
|
||
assert _continue_as_new_model_requests == [result.messages[:1], result.messages[:3]]
|
||
|
||
|
||
async def test_durability_continue_as_new_outside_workflow_is_passthrough():
|
||
received_contexts: list[RunContext[None]] = []
|
||
|
||
def continue_as_new(ctx: RunContext[None]) -> None: # pragma: no cover
|
||
received_contexts.append(ctx)
|
||
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='can_outside_workflow',
|
||
deps_type=NoneType,
|
||
capabilities=[
|
||
TemporalDurability(continue_as_new=continue_as_new),
|
||
_SkipRequestAfterDurability(),
|
||
],
|
||
)
|
||
|
||
result = await agent.run('hello')
|
||
|
||
assert result.output == 'skipped'
|
||
assert received_contexts == []
|
||
|
||
|
||
async def test_durability_continue_as_new_not_suggested_is_passthrough():
|
||
received_contexts: list[RunContext[None]] = []
|
||
|
||
def continue_as_new(ctx: RunContext[None]) -> None: # pragma: no cover
|
||
received_contexts.append(ctx)
|
||
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='can_not_suggested',
|
||
deps_type=NoneType,
|
||
capabilities=[
|
||
TemporalDurability(continue_as_new=continue_as_new),
|
||
_SkipRequestAfterDurability(),
|
||
],
|
||
)
|
||
|
||
with (
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.in_workflow', return_value=True),
|
||
patch('pydantic_ai.durable_exec.temporal._durability.workflow.patched', return_value=False),
|
||
patch(
|
||
'pydantic_ai.durable_exec.temporal._durability.workflow.info',
|
||
return_value=SimpleNamespace(is_continue_as_new_suggested=lambda: False),
|
||
),
|
||
):
|
||
result = await agent.run('hello')
|
||
|
||
assert result.output == 'skipped'
|
||
assert received_contexts == []
|
||
|
||
|
||
def test_durability_get_serialization_name():
|
||
"""TemporalDurability.get_serialization_name() returns None."""
|
||
assert TemporalDurability.get_serialization_name() is None
|
||
|
||
|
||
def test_durability_plugin_requires_durability_capability():
|
||
"""`AgentPlugin` raises a clear error when the agent has no `TemporalDurability`."""
|
||
plain_agent = Agent(_durability_fn_model, name='no_cap_agent')
|
||
with pytest.raises(UserError, match='no `TemporalDurability` capability'):
|
||
AgentPlugin(plain_agent)
|
||
|
||
|
||
# --- Toolset without ID raises UserError ---
|
||
|
||
|
||
def test_durability_rejects_a_url_mcp_toolset_with_only_a_derived_id():
|
||
"""A URL `MCPToolset`'s hostname-derived `id` doesn't name activities: Temporal requires one chosen for it."""
|
||
toolset = MCPToolset('https://mcp.example.com/mcp')
|
||
assert toolset.id == 'mcp.example.com'
|
||
with pytest.raises(UserError, match='need to have a unique `id` in order to be used with Temporal'):
|
||
Agent(_durability_fn_model, name='derived_id_test', toolsets=[toolset], capabilities=[TemporalDurability()])
|
||
|
||
|
||
def test_durability_unwrapped_toolset_without_id_is_allowed():
|
||
"""An unwrapped leaf toolset doesn't need an ID because it isn't registered as an activity."""
|
||
durability = TemporalDurability()
|
||
agent = Agent(
|
||
_durability_fn_model,
|
||
name='no_id_test',
|
||
toolsets=[ExternalToolset(tool_defs=[ToolDefinition(name='ext_tool')])],
|
||
capabilities=[durability],
|
||
)
|
||
assert TemporalDurability.from_agent(agent) is not None
|
||
|
||
|
||
# --- temporalize returning non-TemporalWrapperToolset (passthrough / unwrapped leaf) ---
|
||
|
||
|
||
def test_durability_non_temporal_wrapper_toolset_not_in_registry():
|
||
"""When temporalize returns a non-TemporalWrapperToolset, it's not added to the registry."""
|
||
agent = Agent(
|
||
_durability_fn_model,
|
||
name='external_ts_test',
|
||
toolsets=[ExternalToolset(tool_defs=[ToolDefinition(name='ext_tool')], id='ext')],
|
||
capabilities=[TemporalDurability()],
|
||
)
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
# ExternalToolset is not wrapped into a TemporalWrapperToolset by the default
|
||
# temporalize_toolset, so 'ext' should not appear in _toolsets_by_id.
|
||
assert 'ext' not in bound._toolsets_by_id # pyright: ignore[reportPrivateUsage]
|
||
# The agent's built-in <agent> FunctionToolset IS wrapped.
|
||
assert '<agent>' in bound._toolsets_by_id # pyright: ignore[reportPrivateUsage]
|
||
|
||
|
||
# --- get_wrapper_toolset returns None when no temporal toolsets ---
|
||
|
||
|
||
def test_durability_get_wrapper_toolset_returns_none():
|
||
"""get_wrapper_toolset returns None when `_toolsets_by_id` is empty."""
|
||
# An unbound capability has an empty registry — `for_agent` is what populates it.
|
||
durability = TemporalDurability()
|
||
assert len(durability._toolsets_by_id) == 0 # pyright: ignore[reportPrivateUsage]
|
||
|
||
dummy_toolset = FunctionToolset[object](id='dummy')
|
||
assert durability.get_wrapper_toolset(dummy_toolset) is None
|
||
|
||
|
||
# --- get_wrapper_toolset swap returns unchanged toolset ---
|
||
|
||
|
||
def test_durability_get_wrapper_toolset_swap_unchanged():
|
||
"""get_wrapper_toolset's swap returns a toolset unchanged if its ID is not in the registry."""
|
||
agent = Agent(_durability_fn_model, name='swap_test', capabilities=[TemporalDurability()])
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
|
||
# Create a new toolset not registered with this durability
|
||
unregistered_toolset = FunctionToolset(id='unregistered')
|
||
result = bound.get_wrapper_toolset(unregistered_toolset)
|
||
# The toolset should be returned as-is since its ID is not in the registry
|
||
assert result is unregistered_toolset
|
||
|
||
|
||
# --- `run_sync()` / `run_stream()` / `run_stream_events()` inside a workflow ---
|
||
# The deprecated `TemporalAgent` wrapper rejects all three inside a workflow (see
|
||
# `test_temporal_agent_run_sync_in_workflow` and friends). The `TemporalDurability`
|
||
# capability has no such guards, so these tests pin what the capability actually does:
|
||
# the two streaming entry points work, and `run_sync()` does not.
|
||
# `test_temporal_durability_buffers_caller_streams` already covers the single-step text
|
||
# happy path for both streaming methods; these add the durability `event_stream_handler`
|
||
# under `run_stream()` (completing the handler matrix alongside `run()` and `iter()`) and
|
||
# a multi-step tool-calling run under `run_stream_events()`.
|
||
|
||
|
||
_run_stream_handler_events: list[tuple[str, bool]] = []
|
||
|
||
|
||
async def _run_stream_durability_handler(ctx: RunContext[object], stream: AsyncIterable[AgentStreamEvent]) -> None:
|
||
async for event in stream:
|
||
_run_stream_handler_events.append((type(event).__name__, activity.in_activity()))
|
||
|
||
|
||
_run_stream_durable_agent = Agent(
|
||
_stream_fn_model,
|
||
name='durability_run_stream_agent',
|
||
capabilities=[
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG, event_stream_handler=_run_stream_durability_handler)
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class RunStreamDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> tuple[str, list[str]]:
|
||
async with _run_stream_durable_agent.run_stream(prompt) as result:
|
||
deltas = [delta async for delta in result.stream_text(delta=True)]
|
||
return await result.get_output(), deltas
|
||
|
||
|
||
async def test_durability_run_stream_in_workflow(client: Client) -> None:
|
||
"""`agent.run_stream()` works inside a workflow under the `TemporalDurability` capability.
|
||
|
||
The model streams inside the request-stream activity — the capability's handler sees the model
|
||
events with `activity.in_activity()` true — and the workflow-side `StreamedRunResult` is fed by
|
||
the activity's final response, one event per part, so it stays deterministic across replays.
|
||
The single text delta is not a durability artifact: `run_stream()` consumes events up to the
|
||
`FinalResultEvent` before yielding, so `stream_text(delta=True)` returns the same one chunk for
|
||
this model outside a workflow.
|
||
"""
|
||
_run_stream_handler_events.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[RunStreamDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(_run_stream_durable_agent)],
|
||
):
|
||
output, deltas = await client.execute_workflow(
|
||
RunStreamDurableAgentWorkflow.run,
|
||
args=['Hello'],
|
||
id=RunStreamDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert output == snapshot('Streamed response')
|
||
assert deltas == snapshot(['Streamed response'])
|
||
assert _run_stream_handler_events == snapshot(
|
||
[
|
||
('PartStartEvent', True),
|
||
('FinalResultEvent', True),
|
||
('PartDeltaEvent', True),
|
||
('PartDeltaEvent', True),
|
||
('PartEndEvent', True),
|
||
]
|
||
)
|
||
|
||
|
||
_run_stream_events_durable_agent = Agent(
|
||
TestModel(custom_output_text='Streamed events output'),
|
||
name='durability_run_stream_events_agent',
|
||
tools=[_durability_reveal_tool],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class RunStreamEventsDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> list[str]:
|
||
async with _run_stream_events_durable_agent.run_stream_events(prompt) as stream:
|
||
return [type(event).__name__ async for event in stream]
|
||
|
||
|
||
_preamble_text_agents = preamble_text_agents(lambda: TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG))
|
||
|
||
|
||
@workflow.defn
|
||
class StructuredOutputAfterPreambleTextWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> list[RunAndStreamResult]:
|
||
return [await run_and_stream(agent) for agent in _preamble_text_agents]
|
||
|
||
|
||
async def test_durability_structured_output_after_preamble_text_in_workflow(client: Client) -> None:
|
||
"""Text streamed before a tool call isn't the final result when the output type is structured.
|
||
|
||
The workflow replays the activity's stream against the parameters the activity's model prepared, in which `'auto'`
|
||
has resolved to tool output, so the text isn't output, as in a plain run. The handler passed to `run()` sees the
|
||
replayed events; one set on the capability runs in the activity and would see the live stream.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[StructuredOutputAfterPreambleTextWorkflow],
|
||
plugins=[AgentPlugin(agent) for agent in _preamble_text_agents],
|
||
):
|
||
output = await client.execute_workflow(
|
||
StructuredOutputAfterPreambleTextWorkflow.run,
|
||
id=StructuredOutputAfterPreambleTextWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert output == await plain_run_and_stream()
|
||
|
||
|
||
_rejected_native_output_agent = Agent(
|
||
FunctionModel(
|
||
stream_function=preamble_text_before_output_tool, profile=ModelProfile(supports_json_schema_output=False)
|
||
),
|
||
name='durability_rejected_native_output',
|
||
output_type=NativeOutput(StructuredOutput),
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class RejectedNativeOutputWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> list[str]:
|
||
async with _rejected_native_output_agent.run_stream_events('hello') as stream:
|
||
return [type(event).__name__ async for event in stream]
|
||
|
||
|
||
async def test_durability_streamed_request_the_model_rejects_fails_in_the_activity(client: Client) -> None:
|
||
"""A streamed request the model rejects fails in the activity, as a request that isn't streamed does.
|
||
|
||
The workflow prepares the request again for the replay only once the activity has returned, so
|
||
`prepare_request` rejecting native output for this model reaches the workflow as an `ActivityError`.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[RejectedNativeOutputWorkflow],
|
||
plugins=[AgentPlugin(_rejected_native_output_agent)],
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
RejectedNativeOutputWorkflow.run,
|
||
id=RejectedNativeOutputWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
activity_error = exc_info.value.cause
|
||
assert isinstance(activity_error, ActivityError)
|
||
assert str(activity_error.cause) == snapshot('UserError: Native structured output is not supported by this model.')
|
||
|
||
|
||
async def test_durability_run_stream_events_in_workflow(client: Client) -> None:
|
||
"""`agent.run_stream_events()` works inside a workflow under the `TemporalDurability` capability.
|
||
|
||
Model events are replayed workflow-side after each model-request activity completes, so the
|
||
workflow sees the full event stream (including tool call/result events) and the final
|
||
`AgentRunResultEvent`.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[RunStreamEventsDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(_run_stream_events_durable_agent)],
|
||
):
|
||
events = await client.execute_workflow(
|
||
RunStreamEventsDurableAgentWorkflow.run,
|
||
args=['Hello'],
|
||
id=RunStreamEventsDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert events == snapshot(
|
||
[
|
||
'PartStartEvent',
|
||
'PartEndEvent',
|
||
'FunctionToolCallEvent',
|
||
'FunctionToolResultEvent',
|
||
'ToolAvailabilityDeltaEvent',
|
||
'PartStartEvent',
|
||
'FinalResultEvent',
|
||
'PartEndEvent',
|
||
'AgentRunResultEvent',
|
||
]
|
||
)
|
||
|
||
|
||
async def test_durability_streaming_in_workflow(client: Client):
|
||
"""`ProcessEventStream` routes model requests through a streaming activity."""
|
||
_stream_events_collected.clear()
|
||
_stream_model_events_in_activity.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[StreamDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(_stream_durable_agent)],
|
||
):
|
||
output, model_events_in_activity = await client.execute_workflow(
|
||
StreamDurableAgentWorkflow.run,
|
||
args=['Hello streaming'],
|
||
id=StreamDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
# The non-streaming FunctionModel function is NOT used for the streaming activity;
|
||
# instead, request_stream_activity uses the stream_function path.
|
||
# The final response is assembled from the streamed chunks.
|
||
assert output == 'Streamed response'
|
||
assert model_events_in_activity
|
||
assert not any(model_events_in_activity)
|
||
|
||
|
||
# --- ProcessEventStream capability fires workflow-side ---
|
||
|
||
_process_events_collected: list[AgentStreamEvent] = []
|
||
|
||
_process_model_events_in_activity: list[bool] = []
|
||
|
||
|
||
async def _process_event_stream_handler(
|
||
ctx: RunContext[object],
|
||
stream: AsyncIterable[AgentStreamEvent],
|
||
) -> None:
|
||
async for event in stream:
|
||
if isinstance(event, (PartStartEvent, PartDeltaEvent)):
|
||
_process_model_events_in_activity.append(activity.in_activity())
|
||
_process_events_collected.append(event)
|
||
|
||
|
||
_process_durability = TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)
|
||
|
||
_process_durable_agent = Agent(
|
||
_stream_fn_model,
|
||
name='durability_process_agent',
|
||
capabilities=[
|
||
ProcessEventStream(_process_event_stream_handler),
|
||
_process_durability,
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class ProcessStreamDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> tuple[str, list[bool], list[str], list[str]]:
|
||
result = await _process_durable_agent.run(prompt)
|
||
model_event_kinds = [
|
||
type(event).__name__
|
||
for event in _process_events_collected
|
||
if isinstance(event, (PartStartEvent, PartDeltaEvent))
|
||
]
|
||
text_parts = [
|
||
event.part.content
|
||
for event in _process_events_collected
|
||
if isinstance(event, PartStartEvent) and isinstance(event.part, TextPart)
|
||
]
|
||
return result.output, _process_model_events_in_activity, text_parts, model_event_kinds
|
||
|
||
|
||
def test_durability_tool_metadata_disables_activity():
|
||
"""Tool metadata={'temporal': False} disables activity wrapping for that tool."""
|
||
|
||
async def slow_tool() -> str:
|
||
# Registered with the toolset; the test only verifies wrapping.
|
||
return 'slow' # pragma: no cover
|
||
|
||
toolset = FunctionToolset[object](id='meta_toolset')
|
||
toolset.add_function(slow_tool, metadata={'temporal': False})
|
||
|
||
agent = Agent(
|
||
_durability_fn_model,
|
||
name='meta_disable_test',
|
||
toolsets=[toolset],
|
||
capabilities=[TemporalDurability()],
|
||
)
|
||
bound = TemporalDurability.from_agent(agent)
|
||
assert bound is not None
|
||
|
||
# Should have wrapped the toolset (capability discovered it at for_agent time);
|
||
# the per-tool skip is applied at call time via resolve_tool_activity_config.
|
||
assert 'meta_toolset' in bound._toolsets_by_id # pyright: ignore[reportPrivateUsage]
|
||
|
||
|
||
async def test_durability_resolves_supported_and_rejected_tool_activity_opt_outs():
|
||
"""Capability-owned config preserves every legacy `metadata={'temporal': False}` outcome."""
|
||
|
||
async def async_tool() -> str: ... # pragma: no branch
|
||
|
||
def sync_tool() -> str: ... # pragma: no branch
|
||
|
||
toolset = FunctionToolset[None](id='opt_out_tools')
|
||
toolset.add_function(async_tool, metadata={'temporal': False})
|
||
toolset.add_function(sync_tool, metadata={'temporal': False})
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='opt_outs',
|
||
deps_type=type(None),
|
||
toolsets=[toolset],
|
||
capabilities=[TemporalDurability()],
|
||
)
|
||
durability = TemporalDurability.from_agent(agent)
|
||
assert durability is not None
|
||
ctx = RunContext[None](deps=None, model=TestModel(), usage=RunUsage())
|
||
tools = await toolset.get_tools(ctx)
|
||
|
||
assert (
|
||
durability._resolve_temporal_tool_config( # pyright: ignore[reportPrivateUsage]
|
||
ToolsetCallToolId('function', toolset_id='opt_out_tools'), tools['async_tool'], 'async_tool'
|
||
)
|
||
is False
|
||
)
|
||
with pytest.raises(UserError, match='non-async tools are run in threads'):
|
||
durability._resolve_temporal_tool_config( # pyright: ignore[reportPrivateUsage]
|
||
ToolsetCallToolId('function', toolset_id='opt_out_tools'), tools['sync_tool'], 'sync_tool'
|
||
)
|
||
|
||
with pytest.raises(UserError, match='dynamic-toolset tools cannot run inside the workflow'):
|
||
durability._resolve_temporal_tool_config( # pyright: ignore[reportPrivateUsage]
|
||
ToolsetCallToolId('dynamic', toolset_id='dynamic_opt_out'), tools['async_tool'], 'async_tool'
|
||
)
|
||
|
||
mcp_toolset = MCPToolset(StdioTransport(command='python', args=['-m', 'tests.mcp_server']), id='mcp_opt_out')
|
||
mcp_tool = ToolsetTool(
|
||
toolset=mcp_toolset,
|
||
tool_def=ToolDefinition(name='mcp_tool', metadata={'temporal': False}),
|
||
max_retries=1,
|
||
args_validator=TOOL_SCHEMA_VALIDATOR,
|
||
)
|
||
with pytest.raises(UserError, match='MCP tools require the use of IO'):
|
||
durability._resolve_temporal_tool_config( # pyright: ignore[reportPrivateUsage]
|
||
ToolsetCallToolId('mcp', toolset_id='mcp_opt_out'), mcp_tool, 'mcp_tool'
|
||
)
|
||
|
||
|
||
async def test_durability_tool_opt_out_without_mcp_extra(monkeypatch: pytest.MonkeyPatch):
|
||
"""A plain tool opting out of activities must not import `pydantic_ai.mcp`.
|
||
|
||
Regression test for #8249: the opt-out branch used an unguarded `from pydantic_ai.mcp import
|
||
MCPToolset`, which raised `ImportError` for every tool with `metadata={'temporal': False}` -- even
|
||
non-MCP function tools -- when the optional `mcp` extra was not installed. Simulate that install by
|
||
making `pydantic_ai.mcp` unimportable.
|
||
"""
|
||
|
||
async def async_tool() -> str: ... # pragma: no branch
|
||
|
||
toolset = FunctionToolset[None](id='opt_out_without_mcp')
|
||
toolset.add_function(async_tool, metadata={'temporal': False})
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='opt_out_without_mcp',
|
||
deps_type=type(None),
|
||
toolsets=[toolset],
|
||
capabilities=[TemporalDurability()],
|
||
)
|
||
durability = TemporalDurability.from_agent(agent)
|
||
assert durability is not None
|
||
ctx = RunContext[None](deps=None, model=TestModel(), usage=RunUsage())
|
||
tools = await toolset.get_tools(ctx)
|
||
|
||
monkeypatch.setitem(sys.modules, 'pydantic_ai.mcp', None)
|
||
assert (
|
||
durability._resolve_temporal_tool_config( # pyright: ignore[reportPrivateUsage]
|
||
ToolsetCallToolId('function', toolset_id='opt_out_without_mcp'), tools['async_tool'], 'async_tool'
|
||
)
|
||
is False
|
||
)
|
||
|
||
|
||
async def test_durability_mcp_opt_out_identified_by_operation_kind():
|
||
"""An MCP tool's opt-out is rejected via the operation kind, not `tool.toolset` identity.
|
||
|
||
`PrefixedToolset` rewrites `ToolsetTool.toolset` to the wrapper, so an `isinstance(tool.toolset,
|
||
MCPToolset)` check cannot identify an MCP tool once wrapped; the durable operation's `toolset_kind`
|
||
can, and it also avoids importing the optional `mcp` package in this path (#8249).
|
||
"""
|
||
|
||
mcp_toolset = MCPToolset(StdioTransport(command='python', args=['-m', 'tests.mcp_server']), id='mcp_wrapped')
|
||
prefixed = PrefixedToolset[Any](mcp_toolset, prefix='wrapped')
|
||
prefixed_tool = ToolsetTool(
|
||
toolset=prefixed,
|
||
tool_def=ToolDefinition(name='wrapped_mcp_tool', metadata={'temporal': False}),
|
||
max_retries=1,
|
||
args_validator=TOOL_SCHEMA_VALIDATOR,
|
||
)
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='mcp_wrapped',
|
||
deps_type=type(None),
|
||
toolsets=[prefixed],
|
||
capabilities=[TemporalDurability()],
|
||
)
|
||
durability = TemporalDurability.from_agent(agent)
|
||
assert durability is not None
|
||
with pytest.raises(UserError, match='MCP tools require the use of IO'):
|
||
durability._resolve_temporal_tool_config( # pyright: ignore[reportPrivateUsage]
|
||
ToolsetCallToolId('mcp', toolset_id='mcp_wrapped'), prefixed_tool, 'wrapped_mcp_tool'
|
||
)
|
||
|
||
|
||
async def test_durability_mcp_instructions_use_operation_activity_summary(monkeypatch: pytest.MonkeyPatch):
|
||
"""The common MCP instructions operation retains Temporal's legacy activity summary."""
|
||
mcp_toolset = MCPToolset(
|
||
StdioTransport(command='python', args=['-m', 'tests.mcp_server']),
|
||
id='instructions_summary',
|
||
include_instructions=True,
|
||
)
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='instructions_summary',
|
||
toolsets=[mcp_toolset],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
durability = TemporalDurability.from_agent(agent)
|
||
assert durability is not None
|
||
wrapped = durability._toolsets_by_id['instructions_summary'] # pyright: ignore[reportPrivateUsage]
|
||
dispatched_summaries: list[str] = []
|
||
|
||
async def execute_activity(*args: Any, **config: Any) -> str:
|
||
dispatched_summaries.append(config['summary'])
|
||
return 'server instructions'
|
||
|
||
monkeypatch.setattr('pydantic_ai.durable_exec.temporal._operation_backend.execute_activity', execute_activity)
|
||
ctx = RunContext[None](deps=None, model=TestModel(), usage=RunUsage())
|
||
with patch('pydantic_ai.durable_exec.temporal._durability.workflow.in_workflow', return_value=True):
|
||
assert await wrapped.get_instructions(ctx) == 'server instructions'
|
||
assert dispatched_summaries == ['get instructions: instructions_summary']
|
||
|
||
|
||
async def test_durability_process_event_stream_fires_workflow_side(client: Client):
|
||
"""ProcessEventStream sees the activity's final response replayed in the workflow, each part complete."""
|
||
_process_events_collected.clear()
|
||
_process_model_events_in_activity.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[ProcessStreamDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(_process_durable_agent)],
|
||
):
|
||
output, model_events_in_activity, text_parts, model_event_kinds = await client.execute_workflow(
|
||
ProcessStreamDurableAgentWorkflow.run,
|
||
args=['Hello'],
|
||
id=ProcessStreamDurableAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'Streamed response'
|
||
assert model_events_in_activity
|
||
assert not any(model_events_in_activity)
|
||
|
||
assert text_parts == ['Streamed response']
|
||
assert model_event_kinds == ['PartStartEvent']
|
||
|
||
|
||
# --- Capability events emitted workflow-side reach the handler activity ---
|
||
|
||
|
||
@dataclass
|
||
class _EmittingCapability(AbstractCapability[Any]):
|
||
"""Emits a capability event from a hook, which runs in workflow code."""
|
||
|
||
event_factory: Any = None
|
||
|
||
async def before_model_request(
|
||
self, ctx: RunContext[Any], request_context: ModelRequestContext
|
||
) -> ModelRequestContext:
|
||
await ctx.emit(self.event_factory())
|
||
return request_context
|
||
|
||
|
||
_emitted_handler_events: list[tuple[str, str, bool]] = []
|
||
|
||
|
||
async def _capability_event_handler(ctx: RunContext[object], stream: AsyncIterable[AgentStreamEvent]) -> None:
|
||
async for event in stream:
|
||
# `isinstance` against the class this module imported, which is the point: the sandbox
|
||
# re-executes application modules, and the payload still validates into the host's class.
|
||
if isinstance(event, DurableCheckpointEvent):
|
||
_emitted_handler_events.append((type(event).__name__, event.label, activity.in_activity()))
|
||
|
||
|
||
_capability_event_agent = Agent(
|
||
TestModel(custom_output_text='done'),
|
||
name='durability_capability_event_agent',
|
||
capabilities=[
|
||
_EmittingCapability(id='emitter', event_factory=lambda: DurableCheckpointEvent(label='one')),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG, event_stream_handler=_capability_event_handler),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class CapabilityEventWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await _capability_event_agent.run(prompt)).output
|
||
|
||
|
||
async def test_durability_capability_event_reaches_event_stream_handler_activity(client: Client) -> None:
|
||
"""A capability event emitted workflow-side reaches the handler activity as a typed event.
|
||
|
||
This is the one emission path Temporal supports today: hooks run in workflow code, so the event
|
||
reaches the run's event stream and is dispatched to the durability handler in its own activity,
|
||
where it has to survive the payload round trip rather than degrading to `UnknownCapabilityEvent`.
|
||
|
||
Class identity survives too. The sandbox re-executes application modules, so the workflow side
|
||
holds its own copy of the event class, but `set_replay_isolation_guard` keeps the host's class
|
||
registered and the family schema canonicalizes the copy on the way out. The handler's own
|
||
`isinstance` check is what asserts it.
|
||
"""
|
||
_emitted_handler_events.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[CapabilityEventWorkflow],
|
||
plugins=[AgentPlugin(_capability_event_agent)],
|
||
):
|
||
assert (
|
||
await client.execute_workflow(
|
||
CapabilityEventWorkflow.run,
|
||
args=['Hello'],
|
||
id=CapabilityEventWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
== 'done'
|
||
)
|
||
|
||
assert _emitted_handler_events == [('DurableCheckpointEvent', 'one', True)]
|
||
|
||
|
||
class _Unserializable:
|
||
pass
|
||
|
||
|
||
_unserializable_event_agent = Agent(
|
||
TestModel(custom_output_text='done'),
|
||
name='durability_unserializable_event_agent',
|
||
capabilities=[
|
||
_EmittingCapability(id='emitter', event_factory=lambda: DurableUnserializableEvent(blob=_Unserializable())),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG, event_stream_handler=_capability_event_handler),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class UnserializableEventWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await _unserializable_event_agent.run(prompt)).output
|
||
|
||
|
||
async def test_durability_unserializable_event_payload_names_events(client: Client) -> None:
|
||
"""An event payload that can't be serialized reports the surfaces that ride activity payloads."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[UnserializableEventWorkflow],
|
||
plugins=[AgentPlugin(_unserializable_event_agent)],
|
||
):
|
||
with workflow_raises(
|
||
UserError,
|
||
f'A value passed to a Temporal activity failed to be serialized '
|
||
f'(Unable to serialize unknown type: {_Unserializable!r}). '
|
||
"Temporal requires all values that are passed to activities to be serializable using Pydantic's "
|
||
'`TypeAdapter`. Besides `deps`, this includes `model_settings`, the `RunContext` `metadata` and '
|
||
'`tool_call_metadata`, tool `metadata`, and the payload fields of any emitted `CustomEvent` or '
|
||
'`CapabilityEvent`, which ride the event stream handler activity.',
|
||
):
|
||
await client.execute_workflow(
|
||
UnserializableEventWorkflow.run,
|
||
args=['Hello'],
|
||
id=UnserializableEventWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
|
||
# --- Tool results completed in one workflow task replay in recorded order ---
|
||
#
|
||
# Both tool tasks come back from one `asyncio.wait` call, whose `done` set iterates in an order that
|
||
# follows task identity, so a worker replaying the history can iterate it differently than the
|
||
# worker that recorded it. Each `FunctionToolResultEvent` is one event-handler activity, and Temporal
|
||
# matches activities on replay by type and sequence, not by input: a replay that reorders the result
|
||
# events hands each handler activity the other tool's result without a nondeterminism error.
|
||
# https://github.com/pydantic/pydantic-ai/issues/11182
|
||
|
||
_COMPLETION_ORDER_TOOLS = ('completion_order_tool_a', 'completion_order_tool_b')
|
||
|
||
|
||
@dataclass
|
||
class _CompletionOrderGate:
|
||
"""Holds both tool activities until the test releases them, so they complete together."""
|
||
|
||
arrived: set[str] = field(default_factory=set[str])
|
||
both_arrived: asyncio.Event = field(default_factory=asyncio.Event)
|
||
release: asyncio.Event = field(default_factory=asyncio.Event)
|
||
|
||
|
||
_completion_order_gate = _CompletionOrderGate()
|
||
|
||
|
||
async def _completion_order_gated(name: str) -> str:
|
||
_completion_order_gate.arrived.add(name)
|
||
if _completion_order_gate.arrived == set(_COMPLETION_ORDER_TOOLS):
|
||
_completion_order_gate.both_arrived.set()
|
||
await _completion_order_gate.release.wait()
|
||
return f'{name} done'
|
||
|
||
|
||
async def completion_order_tool_a() -> str:
|
||
return await _completion_order_gated('completion_order_tool_a')
|
||
|
||
|
||
async def completion_order_tool_b() -> str:
|
||
return await _completion_order_gated('completion_order_tool_b')
|
||
|
||
|
||
async def _completion_order_model(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str | DeltaToolCalls]:
|
||
if len(messages) == 1:
|
||
yield {
|
||
0: DeltaToolCall(name='completion_order_tool_a', json_args='{}', tool_call_id='call_a'),
|
||
1: DeltaToolCall(name='completion_order_tool_b', json_args='{}', tool_call_id='call_b'),
|
||
}
|
||
else:
|
||
yield 'done'
|
||
|
||
|
||
async def _completion_order_event_handler(ctx: RunContext[object], stream: AsyncIterable[AgentStreamEvent]) -> None:
|
||
async for _ in stream:
|
||
pass
|
||
|
||
|
||
_completion_order_agent = Agent(
|
||
FunctionModel(stream_function=_completion_order_model),
|
||
name='durability_completion_order',
|
||
tools=[completion_order_tool_a, completion_order_tool_b],
|
||
capabilities=[
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG, event_stream_handler=_completion_order_event_handler)
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class CompletionOrderWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await _completion_order_agent.run(prompt)).output
|
||
|
||
|
||
def _completion_order_event_key(data: bytes) -> tuple[str, str]:
|
||
event = json.loads(data)['event']
|
||
return event['event_kind'], event['part']['tool_call_id']
|
||
|
||
|
||
_completion_order_replayed_inputs: list[tuple[str, str]] = []
|
||
|
||
|
||
class _CompletionOrderInterceptor(Interceptor):
|
||
"""Records the input of each event-handler activity the replayed workflow schedules."""
|
||
|
||
def workflow_interceptor_class(self, input: WorkflowInterceptorClassInput) -> type[WorkflowInboundInterceptor]:
|
||
return _CompletionOrderInboundInterceptor
|
||
|
||
|
||
class _CompletionOrderInboundInterceptor(WorkflowInboundInterceptor):
|
||
def init(self, outbound: WorkflowOutboundInterceptor) -> None:
|
||
super().init(_CompletionOrderOutboundInterceptor(outbound))
|
||
|
||
|
||
class _CompletionOrderOutboundInterceptor(WorkflowOutboundInterceptor):
|
||
def start_activity(self, input: StartActivityInput) -> ActivityHandle[object]:
|
||
if input.activity.endswith('__event_stream_handler'):
|
||
payload = workflow.payload_converter().to_payloads([input.args[0]])[0]
|
||
_completion_order_replayed_inputs.append(_completion_order_event_key(payload.data))
|
||
return super().start_activity(input)
|
||
|
||
|
||
def _completion_order_workflow_worker(client: Client, task_queue: str, *, max_cached_workflows: int) -> Worker:
|
||
return Worker(
|
||
client,
|
||
task_queue=task_queue,
|
||
workflows=[CompletionOrderWorkflow],
|
||
workflow_runner=UnsandboxedWorkflowRunner(),
|
||
max_cached_workflows=max_cached_workflows,
|
||
)
|
||
|
||
|
||
@dataclass
|
||
class _CompletionOrderWait:
|
||
"""How an `asyncio.wait` that returns both tool tasks iterates its `done` set: by task name, either way round."""
|
||
|
||
reverse: bool = False
|
||
tools_done_together: bool = False
|
||
|
||
|
||
def _completion_order_task_name(future: asyncio.Future[object]) -> str:
|
||
# Temporal's workflow loop appends ` (workflow: ..., id: ..., run: ...)` to every task name.
|
||
return future.get_name().partition(' (')[0] if isinstance(future, asyncio.Task) else ''
|
||
|
||
|
||
class _CompletionOrderDoneSet(set[asyncio.Future[object]]):
|
||
"""A `done` set that iterates by task name, one of the orders a plain set can produce."""
|
||
|
||
def __init__(self, done: Iterable[asyncio.Future[object]], *, reverse: bool):
|
||
super().__init__(done)
|
||
self.reverse = reverse
|
||
|
||
def __iter__(self) -> Iterator[asyncio.Future[object]]:
|
||
return iter(sorted(super().__iter__(), key=_completion_order_task_name, reverse=self.reverse))
|
||
|
||
|
||
@pytest.fixture
|
||
def completion_order_wait(monkeypatch: pytest.MonkeyPatch) -> _CompletionOrderWait:
|
||
order = _CompletionOrderWait()
|
||
real_wait = asyncio.wait
|
||
|
||
async def wait(
|
||
fs: Iterable[asyncio.Future[object]], *, timeout: float | None = None, return_when: str = asyncio.ALL_COMPLETED
|
||
) -> tuple[set[asyncio.Future[object]], set[asyncio.Future[object]]]:
|
||
done, pending = await real_wait(fs, timeout=timeout, return_when=return_when)
|
||
if not set(_COMPLETION_ORDER_TOOLS) <= {_completion_order_task_name(future) for future in done}:
|
||
return done, pending
|
||
order.tools_done_together = True
|
||
return _CompletionOrderDoneSet(done, reverse=order.reverse), pending
|
||
|
||
monkeypatch.setattr(asyncio, 'wait', wait)
|
||
return order
|
||
|
||
|
||
async def test_tool_results_completed_together_replay_in_recorded_order(
|
||
client: Client, completion_order_wait: _CompletionOrderWait
|
||
):
|
||
"""A replay that iterates the `done` set the other way round schedules the event-handler inputs it recorded.
|
||
|
||
Both tool completions land in one workflow task by construction: the workflow worker stops while the tools are
|
||
held, the tools are released, and a fresh workflow worker starts once history holds both completions. The
|
||
recording iterates `done` in call order and the replay in reverse; the replay must still send each handler
|
||
activity the result the history holds for it. The workers and the replayer run unsandboxed so the patched
|
||
`asyncio.wait` and the gate are the module state the workflow and the tools see.
|
||
"""
|
||
global _completion_order_gate
|
||
_completion_order_gate = _CompletionOrderGate()
|
||
task_queue = f'completion-order-{uuid.uuid4()}'
|
||
with anyio.fail_after(30):
|
||
# Activities only: this worker has no workflows, so it never polls workflow tasks.
|
||
async with Worker(client, task_queue=task_queue, plugins=[AgentPlugin(_completion_order_agent)]):
|
||
# No cache, so no sticky queue holds the next workflow task for the stopped worker.
|
||
async with _completion_order_workflow_worker(client, task_queue, max_cached_workflows=0):
|
||
handle = await client.start_workflow(
|
||
CompletionOrderWorkflow.run, args=['go'], id=task_queue, task_queue=task_queue
|
||
)
|
||
await _completion_order_gate.both_arrived.wait()
|
||
_completion_order_gate.release.set()
|
||
# The next workflow task only starts once history holds both tool completions.
|
||
events = handle.fetch_history_events(wait_new_event=True)
|
||
tool_activities: set[int] = set()
|
||
completed = 0
|
||
while completed < len(_COMPLETION_ORDER_TOOLS):
|
||
event = await anext(events)
|
||
if event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED:
|
||
if event.activity_task_scheduled_event_attributes.activity_type.name.endswith('__call_tool'):
|
||
tool_activities.add(event.event_id)
|
||
elif event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_COMPLETED:
|
||
completed += event.activity_task_completed_event_attributes.scheduled_event_id in tool_activities
|
||
async with _completion_order_workflow_worker(client, task_queue, max_cached_workflows=100):
|
||
assert await handle.result() == 'done'
|
||
history = await handle.fetch_history()
|
||
|
||
recorded = [
|
||
_completion_order_event_key(event.activity_task_scheduled_event_attributes.input.payloads[0].data)
|
||
for event in history.events
|
||
if event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED
|
||
and event.activity_task_scheduled_event_attributes.activity_type.name.endswith('__event_stream_handler')
|
||
]
|
||
assert recorded == [
|
||
('function_tool_call', 'call_a'),
|
||
('function_tool_call', 'call_b'),
|
||
('function_tool_result', 'call_a'),
|
||
('function_tool_result', 'call_b'),
|
||
]
|
||
|
||
completion_order_wait.reverse = True
|
||
completion_order_wait.tools_done_together = False
|
||
_completion_order_replayed_inputs.clear()
|
||
await Replayer(
|
||
workflows=[CompletionOrderWorkflow],
|
||
plugins=[AgentPlugin(_completion_order_agent)],
|
||
workflow_runner=UnsandboxedWorkflowRunner(),
|
||
data_converter=client.data_converter,
|
||
interceptors=[_CompletionOrderInterceptor()],
|
||
).replay_workflow(history)
|
||
assert completion_order_wait.tools_done_together
|
||
assert _completion_order_replayed_inputs == recorded
|
||
|
||
|
||
# ==========================================
|
||
# TemporalDurability capability — parity with TemporalAgent wrapper tests
|
||
# ==========================================
|
||
#
|
||
# Each test below is the capability-path equivalent of a `TemporalAgent`-based
|
||
# test earlier in this file. They assert the same behaviors but use
|
||
# `Agent(..., capabilities=[TemporalDurability(...)])` and `AgentPlugin`
|
||
# instead of wrapping the agent.
|
||
|
||
|
||
# --- Complex agent: full Logfire span tree ---
|
||
|
||
complex_durability_for_logfire = TemporalDurability[Deps](
|
||
deps_type=Deps,
|
||
event_stream_handler=event_stream_handler,
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
model_activity_config=ActivityConfig(start_to_close_timeout=timedelta(seconds=90)),
|
||
toolset_activity_config={
|
||
'durability_complex_country': ActivityConfig(start_to_close_timeout=timedelta(seconds=120)),
|
||
},
|
||
)
|
||
|
||
complex_durable_logfire_agent = Agent(
|
||
model,
|
||
deps_type=Deps,
|
||
output_type=Response,
|
||
capabilities=[complex_durability_for_logfire],
|
||
toolsets=[
|
||
FunctionToolset[Deps](tools=[get_country], id='durability_complex_country'),
|
||
MCPToolset(
|
||
StdioTransport(command='python', args=['-m', 'tests.mcp_server']),
|
||
id='durability_complex_mcp',
|
||
init_timeout=20,
|
||
),
|
||
ExternalToolset(tool_defs=[ToolDefinition(name='external')], id='durability_complex_external'),
|
||
],
|
||
tools=[get_weather],
|
||
name='durability_complex_agent_logfire',
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class ComplexDurableAgentLogfireWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str, deps: Deps) -> Response:
|
||
result = await complex_durable_logfire_agent.run(prompt, deps=deps)
|
||
return result.output
|
||
|
||
|
||
@pytest.mark.subprocess(reason='connects to `tests.mcp_server` over stdio')
|
||
async def test_durability_complex_agent_logfire_span_tree(
|
||
allow_model_requests: None, client_with_logfire: Client, capfire: CaptureLogfire
|
||
):
|
||
"""Capability-path equivalent of `test_complex_agent_run_in_workflow`.
|
||
|
||
Asserts the Logfire span tree shape — span names will use
|
||
`agent__durability_complex_agent_logfire__*` instead of `agent__complex_agent__*`,
|
||
but the structure should otherwise match. Run with `--inline-snapshot=create`
|
||
to populate the expected value on first run; needs a fresh VCR cassette under
|
||
the new test name (record in CI / locally with `--record-mode=once`).
|
||
"""
|
||
async with Worker(
|
||
client_with_logfire,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[ComplexDurableAgentLogfireWorkflow],
|
||
plugins=[AgentPlugin(complex_durable_logfire_agent)],
|
||
):
|
||
output = await client_with_logfire.execute_workflow(
|
||
ComplexDurableAgentLogfireWorkflow.run,
|
||
args=[
|
||
'Tell me: the capital of the country; the weather there; the product name',
|
||
Deps(country='Mexico'),
|
||
],
|
||
id=ComplexDurableAgentLogfireWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == snapshot(
|
||
Response(
|
||
answers=[
|
||
Answer(label='Capital of the country', answer='Mexico City'),
|
||
Answer(label='Weather in the capital', answer='Sunny'),
|
||
Answer(label='Product Name', answer='Pydantic AI'),
|
||
]
|
||
)
|
||
)
|
||
exporter = capfire.exporter
|
||
|
||
spans = exporter.exported_spans_as_dict()
|
||
basic_spans_by_id = {
|
||
span['context']['span_id']: BasicSpan(
|
||
parent_id=span['parent']['span_id'] if span['parent'] else None,
|
||
content=attributes.get('event') or attributes.get('logfire.msg') or span['name'],
|
||
)
|
||
for span in spans
|
||
if (attributes := span.get('attributes'))
|
||
}
|
||
root_span = None
|
||
for basic_span in basic_spans_by_id.values():
|
||
if basic_span.parent_id is None:
|
||
root_span = basic_span
|
||
else:
|
||
parent_id = basic_span.parent_id
|
||
parent_span = basic_spans_by_id[parent_id]
|
||
parent_span.children.append(basic_span)
|
||
|
||
def _normalize_json_spans(span: BasicSpan) -> None:
|
||
"""Normalize non-deterministic tool_call_ids in JSON event spans."""
|
||
import json
|
||
|
||
for child in span.children:
|
||
if child.content.startswith('{'):
|
||
try:
|
||
data = json.loads(child.content)
|
||
_strip_volatile_fields(data)
|
||
child.content = json.dumps(data)
|
||
except json.JSONDecodeError:
|
||
pass
|
||
_normalize_json_spans(child)
|
||
|
||
def _strip_volatile_fields(obj: dict[str, Any]) -> None:
|
||
for k, v in obj.items():
|
||
if k in ('tool_call_id', 'timestamp'):
|
||
obj[k] = None
|
||
elif isinstance(v, dict):
|
||
_strip_volatile_fields(cast(dict[str, Any], v))
|
||
|
||
assert root_span is not None
|
||
drop_fastmcp_client_spans(root_span)
|
||
_normalize_json_spans(root_span)
|
||
|
||
assert root_span == snapshot(
|
||
BasicSpan(
|
||
content='StartWorkflow:ComplexDurableAgentLogfireWorkflow',
|
||
children=[
|
||
BasicSpan(content='RunWorkflow:ComplexDurableAgentLogfireWorkflow'),
|
||
BasicSpan(
|
||
content='durability_complex_agent_logfire run',
|
||
children=IsList(
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__mcp_server__durability_complex_mcp__get_tools',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__mcp_server__durability_complex_mcp__get_tools',
|
||
children=[BasicSpan(content='tools/list')],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='chat gpt-4o',
|
||
children=[
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__model_request_stream',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__model_request_stream',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=1'),
|
||
BasicSpan(
|
||
content='{"index": 0, "part": {"tool_name": "get_country", "args": "", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "previous_part_kind": null, "canonical_system": null, "event_kind": "part_start"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "{}", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "part": {"tool_name": "get_country", "args": "{}", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "next_part_kind": "tool-call", "canonical_system": null, "event_kind": "part_end"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 1, "part": {"tool_name": "get_product_name", "args": "", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "previous_part_kind": "tool-call", "canonical_system": null, "event_kind": "part_start"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 1, "delta": {"tool_name_delta": null, "args_delta": "{}", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 1, "part": {"tool_name": "get_product_name", "args": "{}", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "next_part_kind": null, "canonical_system": null, "event_kind": "part_end"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=1'),
|
||
BasicSpan(
|
||
content='{"part": {"tool_name": "get_country", "args": "{}", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "args_valid": true, "event_kind": "function_tool_call"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=1'),
|
||
BasicSpan(
|
||
content='{"part": {"tool_name": "get_product_name", "args": "{}", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "args_valid": true, "event_kind": "function_tool_call"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='running tool: get_country',
|
||
children=[
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__toolset__durability_complex_country__call_tool',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__toolset__durability_complex_country__call_tool'
|
||
)
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=1'),
|
||
BasicSpan(
|
||
content='{"part": {"tool_name": "get_country", "content": "Mexico", "tool_call_id": null, "tool_kind": null, "metadata": null, "timestamp": null, "outcome": "success", "retry": null, "part_kind": "tool-return"}, "content": null, "event_kind": "function_tool_result"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='running tool: get_product_name',
|
||
children=[
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__mcp_server__durability_complex_mcp__call_tool',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__mcp_server__durability_complex_mcp__call_tool',
|
||
children=[BasicSpan(content='tools/call get_product_name')],
|
||
)
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=1'),
|
||
BasicSpan(
|
||
content='{"part": {"tool_name": "get_product_name", "content": "Pydantic AI", "tool_call_id": null, "tool_kind": null, "metadata": null, "timestamp": null, "outcome": "success", "retry": null, "part_kind": "tool-return"}, "content": null, "event_kind": "function_tool_result"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='chat gpt-4o',
|
||
children=[
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__model_request_stream',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__model_request_stream',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=2'),
|
||
BasicSpan(
|
||
content='{"index": 0, "part": {"tool_name": "get_weather", "args": "", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "previous_part_kind": null, "canonical_system": null, "event_kind": "part_start"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "{\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "city", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\":\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "Mexico", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " City", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\"}", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "part": {"tool_name": "get_weather", "args": "{\\"city\\":\\"Mexico City\\"}", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "next_part_kind": null, "canonical_system": null, "event_kind": "part_end"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=2'),
|
||
BasicSpan(
|
||
content='{"part": {"tool_name": "get_weather", "args": "{\\"city\\":\\"Mexico City\\"}", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "args_valid": true, "event_kind": "function_tool_call"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='running tool: get_weather',
|
||
children=[
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__toolset__<agent>__call_tool',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__toolset__<agent>__call_tool'
|
||
)
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=2'),
|
||
BasicSpan(
|
||
content='{"part": {"tool_name": "get_weather", "content": "sunny", "tool_call_id": null, "tool_kind": null, "metadata": null, "timestamp": null, "outcome": "success", "retry": null, "part_kind": "tool-return"}, "content": null, "event_kind": "function_tool_result"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='chat gpt-4o',
|
||
children=[
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__model_request_stream',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__model_request_stream',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=3'),
|
||
BasicSpan(
|
||
content='{"index": 0, "part": {"tool_name": "final_result", "args": "", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "previous_part_kind": null, "canonical_system": null, "event_kind": "part_start"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"tool_name": "final_result", "tool_call_id": null, "event_kind": "final_result"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "{\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "answers", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\":[", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "{\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "label", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\":\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "Capital", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " of", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " the", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " country", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\",\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "answer", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\":\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "Mexico", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " City", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\"},{\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "label", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\":\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "Weather", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " in", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " the", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " capital", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\",\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "answer", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\":\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "Sunny", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\"},{\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "label", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\":\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "Product", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " Name", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\",\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "answer", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\":\\"", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "P", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "yd", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "antic", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": " AI", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "\\"}", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "delta": {"tool_name_delta": null, "args_delta": "]}", "tool_call_id": null, "provider_name": null, "provider_details": null, "part_delta_kind": "tool_call"}, "event_kind": "part_delta"}'
|
||
),
|
||
BasicSpan(
|
||
content='{"index": 0, "part": {"tool_name": "final_result", "args": "{\\"answers\\":[{\\"label\\":\\"Capital of the country\\",\\"answer\\":\\"Mexico City\\"},{\\"label\\":\\"Weather in the capital\\",\\"answer\\":\\"Sunny\\"},{\\"label\\":\\"Product Name\\",\\"answer\\":\\"Pydantic AI\\"}]}", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "next_part_kind": null, "canonical_system": null, "event_kind": "part_end"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=3'),
|
||
BasicSpan(
|
||
content='{"part": {"tool_name": "final_result", "args": "{\\"answers\\":[{\\"label\\":\\"Capital of the country\\",\\"answer\\":\\"Mexico City\\"},{\\"label\\":\\"Weather in the capital\\",\\"answer\\":\\"Sunny\\"},{\\"label\\":\\"Product Name\\",\\"answer\\":\\"Pydantic AI\\"}]}", "tool_call_id": null, "tool_kind": null, "id": null, "provider_name": null, "provider_details": null, "part_kind": "tool-call"}, "args_valid": true, "event_kind": "output_tool_call"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
),
|
||
BasicSpan(
|
||
content='StartActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(
|
||
content='RunActivity:agent__durability_complex_agent_logfire__event_stream_handler',
|
||
children=[
|
||
BasicSpan(content='ctx.run_step=3'),
|
||
BasicSpan(
|
||
content='{"part": {"tool_name": "final_result", "content": "Final result processed.", "tool_call_id": null, "tool_kind": null, "metadata": null, "timestamp": null, "outcome": "success", "retry": null, "part_kind": "tool-return"}, "event_kind": "output_tool_result"}'
|
||
),
|
||
],
|
||
)
|
||
],
|
||
),
|
||
check_order=False,
|
||
),
|
||
),
|
||
BasicSpan(content='CompleteWorkflow:ComplexDurableAgentLogfireWorkflow'),
|
||
],
|
||
)
|
||
)
|
||
|
||
|
||
# --- Model retry ---
|
||
|
||
|
||
_durability_model_retry_agent = Agent(model, name='durability_model_retry_agent', capabilities=[TemporalDurability()])
|
||
|
||
|
||
@_durability_model_retry_agent.tool_plain
|
||
def durability_get_weather_in_city(city: str) -> str:
|
||
if city != 'Mexico City':
|
||
raise ModelRetry('Did you mean Mexico City?')
|
||
return 'sunny'
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityModelRetryWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
result = await _durability_model_retry_agent.run(prompt)
|
||
return result
|
||
|
||
|
||
async def test_durability_agent_with_model_retry(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_temporal_agent_with_model_retry`.
|
||
|
||
Needs a fresh VCR cassette (different test name from the wrapper test);
|
||
record locally with `--record-mode=once`.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityModelRetryWorkflow],
|
||
plugins=[AgentPlugin(_durability_model_retry_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityModelRetryWorkflow.run,
|
||
args=['What is the weather in CDMX?'],
|
||
id=DurabilityModelRetryWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result = await wf.result()
|
||
assert result.output == snapshot('The weather in Mexico City is currently sunny.')
|
||
assert result.all_messages() == snapshot(
|
||
[
|
||
ModelRequest(
|
||
parts=[UserPromptPart(content='What is the weather in CDMX?', timestamp=IsDatetime())],
|
||
timestamp=IsDatetime(),
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
ModelResponse(
|
||
parts=[
|
||
ToolCallPart(
|
||
tool_name='durability_get_weather_in_city',
|
||
args='{"city":"CDMX"}',
|
||
tool_call_id='call_TtLEMpCeAhnG48btCDrw8lhl',
|
||
)
|
||
],
|
||
usage=RequestUsage(
|
||
input_tokens=48,
|
||
output_tokens=20,
|
||
details={
|
||
'accepted_prediction_tokens': 0,
|
||
'audio_tokens': 0,
|
||
'reasoning_tokens': 0,
|
||
'rejected_prediction_tokens': 0,
|
||
},
|
||
cost=Decimal('0.00032'),
|
||
output_reasoning_tokens=0,
|
||
),
|
||
model_name='gpt-4o-2024-08-06',
|
||
model_id='openai:gpt-4o',
|
||
timestamp=IsDatetime(),
|
||
provider_name='openai',
|
||
provider_url='https://api.openai.com/v1/',
|
||
canonical_system='openai',
|
||
provider_details={
|
||
'finish_reason': 'tool_calls',
|
||
'service_tier': 'default',
|
||
'timestamp': '2026-05-08T21:37:16Z',
|
||
},
|
||
provider_response_id='chatcmpl-DdNAiT49qrYrZOaeeAd39RynAa1g7',
|
||
finish_reason='tool_call',
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
ModelRequest(
|
||
parts=[
|
||
ToolReturnPart(
|
||
content='Did you mean Mexico City?',
|
||
tool_name='durability_get_weather_in_city',
|
||
tool_call_id='call_TtLEMpCeAhnG48btCDrw8lhl',
|
||
timestamp=IsDatetime(),
|
||
outcome='retried',
|
||
retry=RetryInfo(cause='model_retry', attempt=1, max_retries=1),
|
||
)
|
||
],
|
||
timestamp=IsDatetime(),
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
ModelResponse(
|
||
parts=[
|
||
ToolCallPart(
|
||
tool_name='durability_get_weather_in_city',
|
||
args='{"city":"Mexico City"}',
|
||
tool_call_id='call_d8k0Vk8dw6eWKFWF8Dj0rCL6',
|
||
)
|
||
],
|
||
usage=RequestUsage(
|
||
input_tokens=93,
|
||
output_tokens=20,
|
||
details={
|
||
'accepted_prediction_tokens': 0,
|
||
'audio_tokens': 0,
|
||
'reasoning_tokens': 0,
|
||
'rejected_prediction_tokens': 0,
|
||
},
|
||
cost=Decimal('0.0004325'),
|
||
output_reasoning_tokens=0,
|
||
),
|
||
model_name='gpt-4o-2024-08-06',
|
||
model_id='openai:gpt-4o',
|
||
timestamp=IsDatetime(),
|
||
provider_name='openai',
|
||
provider_url='https://api.openai.com/v1/',
|
||
canonical_system='openai',
|
||
provider_details={
|
||
'finish_reason': 'tool_calls',
|
||
'service_tier': 'default',
|
||
'timestamp': '2026-05-08T21:37:17Z',
|
||
},
|
||
provider_response_id='chatcmpl-DdNAjt5pJt1nYbeCdbHGbo4ntTKy8',
|
||
finish_reason='tool_call',
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
ModelRequest(
|
||
parts=[
|
||
ToolReturnPart(
|
||
tool_name='durability_get_weather_in_city',
|
||
content='sunny',
|
||
tool_call_id='call_d8k0Vk8dw6eWKFWF8Dj0rCL6',
|
||
timestamp=IsDatetime(),
|
||
)
|
||
],
|
||
timestamp=IsDatetime(),
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
ModelResponse(
|
||
parts=[TextPart(content='The weather in Mexico City is currently sunny.')],
|
||
usage=RequestUsage(
|
||
input_tokens=127,
|
||
output_tokens=10,
|
||
details={
|
||
'accepted_prediction_tokens': 0,
|
||
'audio_tokens': 0,
|
||
'reasoning_tokens': 0,
|
||
'rejected_prediction_tokens': 0,
|
||
},
|
||
cost=Decimal('0.0004175'),
|
||
output_reasoning_tokens=0,
|
||
),
|
||
model_name='gpt-4o-2024-08-06',
|
||
model_id='openai:gpt-4o',
|
||
timestamp=IsDatetime(),
|
||
provider_name='openai',
|
||
provider_url='https://api.openai.com/v1/',
|
||
canonical_system='openai',
|
||
provider_details={
|
||
'finish_reason': 'stop',
|
||
'service_tier': 'default',
|
||
'timestamp': '2026-05-08T21:37:18Z',
|
||
},
|
||
provider_response_id='chatcmpl-DdNAkzvAFU1knSut20EiutyMs7PZy',
|
||
finish_reason='stop',
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
]
|
||
)
|
||
|
||
|
||
# --- Multi-model selection by ID ---
|
||
|
||
_durability_model_1 = TestModel(custom_output_text='Response from model 1')
|
||
|
||
_durability_model_2 = TestModel(custom_output_text='Response from model 2')
|
||
|
||
_durability_model_3 = TestModel(custom_output_text='Response from model 3')
|
||
|
||
|
||
_durability_multi_model_agent = Agent(
|
||
_durability_model_1,
|
||
name='durability_multi_model_agent',
|
||
capabilities=[
|
||
TemporalDurability(
|
||
models={
|
||
'model_2': _durability_model_2,
|
||
'model_3': _durability_model_3,
|
||
},
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
)
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityMultiModelWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str, model_id: str | None = None) -> str:
|
||
result = await _durability_multi_model_agent.run(prompt, model=model_id)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_multi_model_selection_in_workflow(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_temporal_agent_multi_model_selection_in_workflow`."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityMultiModelWorkflow],
|
||
plugins=[AgentPlugin(_durability_multi_model_agent)],
|
||
):
|
||
# Default model (no model arg)
|
||
output = await client.execute_workflow(
|
||
DurabilityMultiModelWorkflow.run,
|
||
args=['Hello', None],
|
||
id='DurabilityMultiModelWorkflow_default',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'Response from model 1'
|
||
|
||
# Selecting registered second model by ID
|
||
output = await client.execute_workflow(
|
||
DurabilityMultiModelWorkflow.run,
|
||
args=['Hello', 'model_2'],
|
||
id='DurabilityMultiModelWorkflow_model2',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'Response from model 2'
|
||
|
||
# Selecting registered third model by ID
|
||
output = await client.execute_workflow(
|
||
DurabilityMultiModelWorkflow.run,
|
||
args=['Hello', 'model_3'],
|
||
id='DurabilityMultiModelWorkflow_model3',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'Response from model 3'
|
||
|
||
|
||
# --- Model selection by instance ---
|
||
|
||
_durability_model_instance_map = {
|
||
'default_instance': _durability_model_1,
|
||
'model_2_instance': _durability_model_2,
|
||
}
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityMultiModelInstanceWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str, instance_key: str) -> str:
|
||
model_instance = _durability_model_instance_map[instance_key]
|
||
result = await _durability_multi_model_agent.run(prompt, model=model_instance)
|
||
return result.output
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
('instance_key', 'expected_output'),
|
||
[
|
||
pytest.param('default_instance', 'Response from model 1', id='default_instance'),
|
||
pytest.param('model_2_instance', 'Response from model 2', id='registered_instance'),
|
||
],
|
||
)
|
||
async def test_durability_model_selection_by_instance(
|
||
allow_model_requests: None, client: Client, instance_key: str, expected_output: str
|
||
):
|
||
"""Capability-path equivalent of `test_temporal_agent_model_selection_by_instance`."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityMultiModelInstanceWorkflow],
|
||
plugins=[AgentPlugin(_durability_multi_model_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityMultiModelInstanceWorkflow.run,
|
||
args=['Hello', instance_key],
|
||
id=f'DurabilityMultiModelInstanceWorkflow_{instance_key}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == expected_output
|
||
|
||
|
||
# --- Web search builtin tool ---
|
||
|
||
_durability_web_search_agent = Agent(
|
||
web_search_model,
|
||
name='durability_web_search_agent',
|
||
capabilities=[
|
||
NativeTool(WebSearchTool(user_location=WebSearchUserLocation(city='Mexico City', country='MX'))),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
model_activity_config=ActivityConfig(start_to_close_timeout=timedelta(seconds=300)),
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityWebSearchAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await _durability_web_search_agent.run(prompt)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_web_search_in_workflow(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_web_search_agent_run_in_workflow`.
|
||
|
||
Needs a fresh VCR cassette (different test name from the wrapper test);
|
||
record in CI / locally with `--record-mode=once`.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityWebSearchAgentWorkflow],
|
||
plugins=[AgentPlugin(_durability_web_search_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityWebSearchAgentWorkflow.run,
|
||
args=['In one sentence, what is the top news story in my country today?'],
|
||
id=DurabilityWebSearchAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == snapshot(
|
||
"Mexico's central bank cut its benchmark interest rate by 25 basis points to 6.50%--effective today, May 8, 2026--signaling the end of its rate‐cut cycle. ([banxico.org.mx](https://www.banxico.org.mx/publicaciones-y-prensa/anuncios-de-las-decisiones-de-politica-monetaria/%7B8A05C722-0A97-4527-2166-0CE802CE6838%7D.pdf?utm_source=openai))"
|
||
)
|
||
|
||
|
||
# --- Dynamic builtin tools select-by-model ---
|
||
|
||
_durability_builtin_tool_agent = Agent(
|
||
web_search_builtin_model,
|
||
name='durability_builtin_tool_dynamic_agent',
|
||
capabilities=[
|
||
NativeTool(_select_builtin_tool),
|
||
TemporalDurability(
|
||
models={'code': code_execution_builtin_model},
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityBuiltinToolWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str, model_id: str | None = None) -> str:
|
||
result = await _durability_builtin_tool_agent.run(prompt, model=model_id)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_dynamic_builtin_tools_select_by_model(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_temporal_dynamic_builtin_tools_select_by_model`."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityBuiltinToolWorkflow],
|
||
plugins=[AgentPlugin(_durability_builtin_tool_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityBuiltinToolWorkflow.run,
|
||
args=['Hello', None],
|
||
id='DurabilityBuiltinToolWorkflow_default',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'search model'
|
||
assert isinstance(web_search_builtin_model.last_model_request_parameters, ModelRequestParameters)
|
||
assert web_search_builtin_model.last_model_request_parameters.native_tools
|
||
assert isinstance(web_search_builtin_model.last_model_request_parameters.native_tools[0], WebSearchTool)
|
||
|
||
output = await client.execute_workflow(
|
||
DurabilityBuiltinToolWorkflow.run,
|
||
args=['Hello', 'code'],
|
||
id='DurabilityBuiltinToolWorkflow_code',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'code model'
|
||
assert isinstance(code_execution_builtin_model.last_model_request_parameters, ModelRequestParameters)
|
||
assert code_execution_builtin_model.last_model_request_parameters.native_tools
|
||
assert isinstance(
|
||
code_execution_builtin_model.last_model_request_parameters.native_tools[0],
|
||
CodeExecutionTool,
|
||
)
|
||
|
||
|
||
# --- @agent.toolset returning an MCP toolset ---
|
||
|
||
_durability_mcp_dynamic_toolset_agent = Agent(
|
||
model,
|
||
name='durability_mcp_dynamic_toolset_agent',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@_durability_mcp_dynamic_toolset_agent.toolset(id='durability_mcp_toolset')
|
||
def _durability_my_mcp_dynamic_toolset(ctx: RunContext[object]) -> MCPToolset[object]:
|
||
# Exercised only by the skipped test below.
|
||
return MCPToolset('https://mcp.deepwiki.com/mcp') # pragma: no cover
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityMCPDynamicToolsetAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
# This body runs only under the skipped test below.
|
||
result = await _durability_mcp_dynamic_toolset_agent.run(prompt) # pragma: no cover
|
||
return result.output # pragma: no cover
|
||
|
||
|
||
@pytest.mark.skip(
|
||
reason=(
|
||
'Pending: replays of this MCP toolset workflow trip the Temporal sandbox with '
|
||
'`Module certifi was imported after initial workflow load`. Issue tracked.'
|
||
)
|
||
)
|
||
async def test_durability_mcp_dynamic_toolset_in_workflow(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_mcp_dynamic_toolset_in_workflow`.
|
||
|
||
Needs a fresh VCR cassette (different test name from the wrapper test);
|
||
record in CI / locally with `--record-mode=once`.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityMCPDynamicToolsetAgentWorkflow],
|
||
plugins=[AgentPlugin(_durability_mcp_dynamic_toolset_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityMCPDynamicToolsetAgentWorkflow.run,
|
||
args=['Can you tell me about the pydantic/pydantic-ai repo? Keep it short.'],
|
||
id='test_durability_mcp_dynamic_toolset_workflow',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
# The deepwiki MCP server should return info about the pydantic-ai repo
|
||
assert 'pydantic' in output.lower() or 'agent' in output.lower()
|
||
|
||
|
||
# --- MCPToolset over HTTP ---
|
||
|
||
_durability_mcptoolset_agent = Agent(
|
||
model,
|
||
name='durability_mcptoolset_agent',
|
||
toolsets=[MCPToolset('https://mcp.deepwiki.com/mcp', id='durability_deepwiki')],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityMCPToolsetAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
# This body runs only under the skipped test below.
|
||
result = await _durability_mcptoolset_agent.run(prompt) # pragma: no cover
|
||
return result.output # pragma: no cover
|
||
|
||
|
||
@pytest.mark.skip(
|
||
reason=(
|
||
'Pending: replays of this MCP toolset workflow trip the Temporal sandbox with '
|
||
'`Module certifi was imported after initial workflow load`. Issue tracked.'
|
||
)
|
||
)
|
||
async def test_durability_mcptoolset_in_workflow(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_mcptoolset_in_temporal_workflow`.
|
||
|
||
Needs a fresh VCR cassette (different test name from the wrapper test);
|
||
record in CI / locally with `--record-mode=once`.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityMCPToolsetAgentWorkflow],
|
||
plugins=[AgentPlugin(_durability_mcptoolset_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityMCPToolsetAgentWorkflow.run,
|
||
args=['Can you tell me more about the pydantic/pydantic-ai repo? Keep your answer short'],
|
||
id=DurabilityMCPToolsetAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == snapshot()
|
||
|
||
|
||
# --- @agent.toolset returning a FunctionToolset ---
|
||
|
||
|
||
def _durability_my_dynamic_toolset(ctx: RunContext[DynamicToolsetDeps]) -> FunctionToolset[DynamicToolsetDeps]:
|
||
toolset = FunctionToolset[DynamicToolsetDeps](id='durability_dynamic_weather')
|
||
|
||
@toolset.tool_plain
|
||
def get_dynamic_weather(location: str) -> str:
|
||
"""Get the weather for a location."""
|
||
user = ctx.deps.user_name
|
||
return f'Weather in {location} for {user}: sunny.'
|
||
|
||
return toolset
|
||
|
||
|
||
_durability_dynamic_toolset_agent = Agent(
|
||
TestModel(),
|
||
name='durability_dynamic_toolset_agent',
|
||
deps_type=DynamicToolsetDeps,
|
||
toolsets=[DynamicToolset(_durability_my_dynamic_toolset, id='durability_my_dynamic_tools')],
|
||
capabilities=[
|
||
TemporalDurability[DynamicToolsetDeps](deps_type=DynamicToolsetDeps, activity_config=BASE_ACTIVITY_CONFIG)
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityDynamicToolsetAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str, deps: DynamicToolsetDeps) -> str:
|
||
result = await _durability_dynamic_toolset_agent.run(prompt, deps=deps)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_dynamic_toolset_in_workflow(client: Client):
|
||
"""Capability-path equivalent of `test_dynamic_toolset_in_workflow`."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityDynamicToolsetAgentWorkflow],
|
||
plugins=[AgentPlugin(_durability_dynamic_toolset_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityDynamicToolsetAgentWorkflow.run,
|
||
args=['Get the weather for London', DynamicToolsetDeps(user_name='Alice')],
|
||
id='test_durability_dynamic_toolset_workflow',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == snapshot('{"get_dynamic_weather":"Weather in a for Alice: sunny."}')
|
||
|
||
|
||
def _dynamic_activity_config_toolset(ctx: RunContext[Any]) -> FunctionToolset[Any]:
|
||
toolset = FunctionToolset[Any](id='dynamic_activity_config_inner')
|
||
|
||
@toolset.tool_plain(metadata={'temporal': ActivityConfig(start_to_close_timeout=timedelta(seconds=30))})
|
||
def timed_tool() -> str:
|
||
assert activity.in_activity()
|
||
return 'timed result'
|
||
|
||
return toolset
|
||
|
||
|
||
# Passed at construction time so the durability capability actually wraps it (see #6902).
|
||
_dynamic_activity_config_agent = Agent(
|
||
TestModel(),
|
||
name='dynamic_activity_config_agent',
|
||
toolsets=[DynamicToolset(_dynamic_activity_config_toolset, id='dynamic_activity_config')],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DynamicToolActivityConfigWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _dynamic_activity_config_agent.run('Call the tool')).output
|
||
|
||
|
||
async def test_durability_dynamic_tool_timedelta_activity_config_survives_round_trip(client: Client):
|
||
"""A `timedelta` in a dynamic tool's `ActivityConfig` metadata reaches `execute_activity` intact.
|
||
|
||
The tool is discovered inside the get-tools activity, so its metadata comes back to the
|
||
workflow as JSON and the `timedelta` arrives as the string `'PT5M'`. Handing that to
|
||
`workflow.execute_activity` raises inside protobuf's `Duration.FromTimedelta`, which is a
|
||
workflow-*task* failure that Temporal retries forever — hence the short `execution_timeout`,
|
||
so a regression fails the test instead of hanging it.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DynamicToolActivityConfigWorkflow],
|
||
plugins=[AgentPlugin(_dynamic_activity_config_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DynamicToolActivityConfigWorkflow.run,
|
||
id='test_dynamic_tool_activity_config',
|
||
task_queue=TASK_QUEUE,
|
||
execution_timeout=timedelta(seconds=30),
|
||
)
|
||
assert output == snapshot('{"timed_tool":"timed result"}')
|
||
|
||
|
||
@dataclass
|
||
class _TemporalDynamicToolCapability(AbstractCapability[Any]):
|
||
def get_toolset(self) -> FunctionToolset[Any]:
|
||
toolset = FunctionToolset[Any]()
|
||
|
||
@toolset.tool_plain
|
||
def dynamic_capability_tool() -> str:
|
||
assert activity.in_activity()
|
||
return 'called in activity'
|
||
|
||
return toolset
|
||
|
||
|
||
def _temporal_dynamic_capability_factory(ctx: RunContext[Any]) -> AbstractCapability[Any]:
|
||
return _TemporalDynamicToolCapability()
|
||
|
||
|
||
_temporal_dynamic_capability_agent = Agent(
|
||
TestModel(),
|
||
name='temporal_dynamic_capability_agent',
|
||
capabilities=[
|
||
DynamicCapability(_temporal_dynamic_capability_factory, id='dyn'),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class TemporalDynamicCapabilityWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _temporal_dynamic_capability_agent.run('Call the tool')).output
|
||
|
||
|
||
async def test_durability_dynamic_capability_tool_runs_in_activity(client: Client):
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[TemporalDynamicCapabilityWorkflow],
|
||
plugins=[AgentPlugin(_temporal_dynamic_capability_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
TemporalDynamicCapabilityWorkflow.run,
|
||
id='test_temporal_dynamic_capability',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == '{"dynamic_capability_tool":"called in activity"}'
|
||
|
||
|
||
def test_durability_dynamic_capability_requires_id() -> None:
|
||
with pytest.raises(UserError, match=r"DynamicCapability\(\.\.\., id='user-tools'\)"):
|
||
Agent(
|
||
TestModel(),
|
||
name='idless_dynamic_capability',
|
||
capabilities=[
|
||
DynamicCapability(_temporal_dynamic_capability_factory),
|
||
TemporalDurability(),
|
||
],
|
||
)
|
||
|
||
|
||
async def test_durability_dynamic_capability_transparent_outside_workflow():
|
||
"""Outside a workflow, dynamic-capability tools resolve and run inline, not via activities.
|
||
|
||
The durable wrapper's `for_run` must hand the run the *resolved* dynamic toolset:
|
||
delegating to the unresolved construction-time factory would silently contribute no tools.
|
||
"""
|
||
in_activity_flags: list[bool] = []
|
||
|
||
def dynamic_tool() -> str:
|
||
in_activity_flags.append(activity.in_activity())
|
||
return 'inline result'
|
||
|
||
def factory(ctx: RunContext[Any]) -> AbstractCapability[Any]:
|
||
return Capability(tools=[dynamic_tool])
|
||
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='temporal_dynamic_capability_outside',
|
||
capabilities=[
|
||
DynamicCapability(factory, id='dyn_outside'),
|
||
TemporalDurability(),
|
||
],
|
||
)
|
||
|
||
result = await agent.run('Call the tool')
|
||
assert result.output == '{"dynamic_tool":"inline result"}'
|
||
assert in_activity_flags == [False]
|
||
|
||
|
||
# --- ImageGeneration through a durable run ---
|
||
|
||
|
||
class _DurabilityImageGenerationModel(TestImageGenerationModel):
|
||
"""Fails the activity unless the direct generator ran inside one."""
|
||
|
||
async def generate(
|
||
self,
|
||
prompt: str,
|
||
*,
|
||
images: Sequence[ImageGenerationInput] | None = None,
|
||
settings: ImageGenerationSettings | None = None,
|
||
) -> ImageGenerationResult:
|
||
assert activity.in_activity()
|
||
return await super().generate(prompt, images=images, settings=settings)
|
||
|
||
|
||
def _durability_image_generation_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
if len(messages) == 1:
|
||
return ModelResponse(parts=[ToolCallPart('generate_image', {'prompt': 'A tiny test image'})])
|
||
image = next(
|
||
part.content
|
||
for message in messages
|
||
if isinstance(message, ModelRequest)
|
||
for part in message.parts
|
||
if isinstance(part, ToolReturnPart)
|
||
)
|
||
assert isinstance(image, BinaryImage), image
|
||
return ModelResponse(parts=[TextPart(f'{image.media_type} {len(image.data)}')])
|
||
|
||
|
||
_durability_image_generation_agent = Agent(
|
||
FunctionModel(_durability_image_generation_fn),
|
||
name='durability_image_generation_agent',
|
||
capabilities=[
|
||
ImageGeneration(
|
||
native=False,
|
||
local=ImageGenerator(_DurabilityImageGenerationModel()),
|
||
id='images',
|
||
),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class TemporalImageGenerationWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _durability_image_generation_agent.run('Generate an image')).output
|
||
|
||
|
||
async def test_durability_image_generation_capability_runs_in_activity(client: Client):
|
||
"""An `ImageGeneration` capability generates inside an activity, and the bytes cross back.
|
||
|
||
The pieces are pinned separately elsewhere — a `BinaryImage` as an activity result payload, the
|
||
capability toolset resolving activity-side — but not the combination this exercises: an agent
|
||
carrying `ImageGeneration(id=...)` registering its `generate_image` toolset with the worker and
|
||
running it in a durable workflow, with the generated image returned as the tool-result payload.
|
||
|
||
The tool return is only observable inside `_durability_image_generation_fn`, which is where the
|
||
`BinaryImage` check lives; the workflow hands back the agent's `str` output, so the projection is
|
||
how that observation gets out. `67` is the length of the fixed 1x1 PNG `TestImageGenerationModel`
|
||
returns, so the pair pins that a 67-byte `image/png` crossed the activity boundary intact.
|
||
|
||
A generator that ran in workflow code instead trips the `activity.in_activity()` assert above,
|
||
where an `AssertionError` is a workflow-*task* failure that Temporal retries forever — hence the
|
||
short `execution_timeout`, so that regression fails the test instead of hanging it.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[TemporalImageGenerationWorkflow],
|
||
plugins=[AgentPlugin(_durability_image_generation_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
TemporalImageGenerationWorkflow.run,
|
||
id='test_temporal_image_generation',
|
||
task_queue=TASK_QUEUE,
|
||
execution_timeout=timedelta(seconds=30),
|
||
)
|
||
assert output == snapshot('image/png 67')
|
||
|
||
|
||
def _durability_native_image_generation_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
native = [tool.kind for tool in info.model_request_parameters.native_tools]
|
||
function = [tool.name for tool in info.function_tools]
|
||
return ModelResponse(parts=[TextPart(f'native={native} function={function}')])
|
||
|
||
|
||
_durability_native_image_generation_profile = ModelProfile(supported_native_tools=frozenset({ImageGenerationTool}))
|
||
|
||
_durability_fallback_image_generation_agent = Agent(
|
||
FallbackModel(
|
||
FunctionModel(
|
||
_durability_native_image_generation_fn,
|
||
model_name='primary',
|
||
profile=_durability_native_image_generation_profile,
|
||
),
|
||
FunctionModel(
|
||
_durability_native_image_generation_fn,
|
||
model_name='secondary',
|
||
profile=_durability_native_image_generation_profile,
|
||
),
|
||
),
|
||
name='durability_fallback_image_generation_agent',
|
||
capabilities=[
|
||
ImageGeneration(fallback_image_model=TestImageGenerationModel(), quality='high', id='fallback_images'),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class TemporalFallbackImageGenerationWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _durability_fallback_image_generation_agent.run('Generate an image')).output
|
||
|
||
|
||
async def test_durability_image_generation_notice_meets_the_fallback_model_in_workflow_code(client: Client):
|
||
"""In workflow code the dropped-settings notice meets the `FallbackModel` itself without crashing or warning.
|
||
|
||
`TemporalDurability` leaves the agent's own model on the run context, so the notice's prepare
|
||
function meets the `FallbackModel` itself, which has no profile of its own. Every member here
|
||
runs the native tool, which carries `quality`, so none of them drops it and no warning fires:
|
||
under `filterwarnings = ['error']` a warning, or a crash reading the `FallbackModel`'s profile,
|
||
fails the workflow task, which Temporal retries until the `execution_timeout` fails the test.
|
||
The output pins that the request carried the native tool and withheld the direct generator.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[TemporalFallbackImageGenerationWorkflow],
|
||
plugins=[AgentPlugin(_durability_fallback_image_generation_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
TemporalFallbackImageGenerationWorkflow.run,
|
||
id='test_temporal_fallback_image_generation',
|
||
task_queue=TASK_QUEUE,
|
||
execution_timeout=timedelta(seconds=30),
|
||
)
|
||
assert output == snapshot("native=['image_generation'] function=[]")
|
||
|
||
|
||
_durability_fallback_drops_quality_agent = Agent(
|
||
FallbackModel(
|
||
FunctionModel(
|
||
_durability_native_image_generation_fn,
|
||
model_name='no_native',
|
||
profile=ModelProfile(supported_native_tools=frozenset()),
|
||
),
|
||
FunctionModel(
|
||
_durability_native_image_generation_fn,
|
||
model_name='native',
|
||
profile=_durability_native_image_generation_profile,
|
||
),
|
||
),
|
||
name='durability_fallback_drops_quality_agent',
|
||
capabilities=[
|
||
ImageGeneration(fallback_image_model=TestImageGenerationModel(), quality='high', id='fallback_drops_quality'),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class TemporalFallbackDropsQualityWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _durability_fallback_drops_quality_agent.run('Generate an image')).output
|
||
|
||
|
||
async def test_durability_image_generation_notice_names_the_fallback_member_that_drops_a_setting_in_workflow_code(
|
||
client: Client,
|
||
):
|
||
"""In workflow code the dropped-settings notice names the `FallbackModel` member that drops a setting.
|
||
|
||
`TemporalDurability` leaves the agent's own model on the run context, so the notice's prepare
|
||
function reads each member's profile, as it does outside a workflow. `no_native` has no native
|
||
tool and takes the direct generator, which can't apply `quality`, so one warning names it;
|
||
`native` carries `quality` on the native tool and goes unnamed. The warning is raised in
|
||
workflow code and reaches `pytest.warns` in the test. The output pins that `no_native`
|
||
answered with the direct generator.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[TemporalFallbackDropsQualityWorkflow],
|
||
plugins=[AgentPlugin(_durability_fallback_drops_quality_agent)],
|
||
):
|
||
# `pytest.warns` records every warning in the process with the project's ignore filters lifted,
|
||
# so it wraps only the run, and only `UserWarning`s are compared: a `ResourceWarning` from
|
||
# another test's garbage would otherwise land here.
|
||
with pytest.warns(UserWarning) as recorded:
|
||
output = await client.execute_workflow(
|
||
TemporalFallbackDropsQualityWorkflow.run,
|
||
id='test_temporal_fallback_drops_quality',
|
||
task_queue=TASK_QUEUE,
|
||
execution_timeout=timedelta(seconds=30),
|
||
)
|
||
assert [str(warning.message) for warning in recorded if issubclass(warning.category, UserWarning)] == [
|
||
"The direct `ImageGeneration` fallback ignored native-tool setting(s) on 'no_native': `quality`. "
|
||
'Configure provider-specific direct settings on the `ImageGenerator` or `ImageGenerationModel` instead.'
|
||
]
|
||
assert output == snapshot("native=[] function=['generate_image']")
|
||
|
||
|
||
# --- ToolReturn metadata round-trip ---
|
||
|
||
|
||
def _durability_tool_return_metadata_model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
if len(messages) == 1:
|
||
return ModelResponse(parts=[ToolCallPart('durability_analyze_data', {})])
|
||
else:
|
||
return ModelResponse(parts=[TextPart('done')])
|
||
|
||
|
||
_durability_tool_return_metadata_agent = Agent(
|
||
FunctionModel(_durability_tool_return_metadata_model),
|
||
name='durability_tool_return_metadata_agent',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@_durability_tool_return_metadata_agent.tool_plain
|
||
def durability_analyze_data() -> ToolReturn:
|
||
return ToolReturn(
|
||
return_value='analysis result',
|
||
content='extra content for model',
|
||
metadata={'key': 'value', 'count': 42},
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityToolReturnMetadataWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> list[ModelMessage]:
|
||
result = await _durability_tool_return_metadata_agent.run(prompt)
|
||
return result.all_messages()
|
||
|
||
|
||
async def test_durability_tool_return_metadata_survives(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_tool_return_metadata_survives_temporal`.
|
||
|
||
Regression test for https://github.com/pydantic/pydantic-ai/issues/4676 — `ToolReturn`
|
||
`metadata` and `content` survive Temporal serialization on the capability path too.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityToolReturnMetadataWorkflow],
|
||
plugins=[AgentPlugin(_durability_tool_return_metadata_agent)],
|
||
):
|
||
messages = await client.execute_workflow(
|
||
DurabilityToolReturnMetadataWorkflow.run,
|
||
args=['analyze'],
|
||
id=DurabilityToolReturnMetadataWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert messages == snapshot(
|
||
[
|
||
ModelRequest(
|
||
parts=[UserPromptPart(content='analyze', timestamp=IsDatetime())],
|
||
timestamp=IsDatetime(),
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
ModelResponse(
|
||
parts=[ToolCallPart(tool_name='durability_analyze_data', args={}, tool_call_id=IsStr())],
|
||
usage=RequestUsage(input_tokens=IsInt(), output_tokens=IsInt()),
|
||
model_name='function:_durability_tool_return_metadata_model:',
|
||
model_id='function:function:_durability_tool_return_metadata_model:',
|
||
timestamp=IsDatetime(),
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
ModelRequest(
|
||
parts=[
|
||
ToolReturnPart(
|
||
tool_name='durability_analyze_data',
|
||
content='analysis result',
|
||
tool_call_id=IsStr(),
|
||
metadata={'key': 'value', 'count': 42},
|
||
timestamp=IsDatetime(),
|
||
),
|
||
UserPromptPart(content='extra content for model', timestamp=IsDatetime()),
|
||
],
|
||
timestamp=IsDatetime(),
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
ModelResponse(
|
||
parts=[TextPart(content='done')],
|
||
usage=RequestUsage(input_tokens=IsInt(), output_tokens=IsInt()),
|
||
model_name='function:_durability_tool_return_metadata_model:',
|
||
model_id='function:function:_durability_tool_return_metadata_model:',
|
||
timestamp=IsDatetime(),
|
||
run_id=IsStr(),
|
||
conversation_id=IsStr(),
|
||
),
|
||
]
|
||
)
|
||
|
||
|
||
# --- Deferred tool reveal round-trip ---
|
||
|
||
|
||
def _durability_reveal_model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
tool_names = {tool.name for tool in info.function_tools}
|
||
responses = sum(isinstance(message, ModelResponse) for message in messages)
|
||
if responses == 0:
|
||
assert 'durability_refund' not in tool_names
|
||
return ModelResponse(parts=[ToolCallPart('load_capability', {'id': 'billing'}, tool_call_id='load')])
|
||
if responses == 1:
|
||
assert 'durability_refund' in tool_names
|
||
return ModelResponse(parts=[ToolCallPart('durability_refund', {}, tool_call_id='refund')])
|
||
if responses == 2:
|
||
assert 'durability_hidden' not in tool_names
|
||
return ModelResponse(parts=[ToolCallPart('durability_opener', {}, tool_call_id='open')])
|
||
if responses == 3:
|
||
assert 'durability_hidden' in tool_names
|
||
return ModelResponse(parts=[ToolCallPart('durability_hidden', {}, tool_call_id='hidden')])
|
||
return ModelResponse(parts=[TextPart('done')])
|
||
|
||
|
||
_durability_billing = Capability[None](id='billing', defer_loading=True)
|
||
|
||
|
||
@_durability_billing.tool
|
||
def durability_refund(ctx: RunContext[None]) -> str:
|
||
# The always-visible check exercises the availability snapshot carried across the activity
|
||
# boundary: `durability_opener` is never revealed, so the `discovered_tool_names` fallback
|
||
# alone would answer False for it inside the activity.
|
||
return (
|
||
f'refund available: {ctx.is_tool_available("durability_refund")}, '
|
||
f'opener available: {ctx.is_tool_available("durability_opener")}'
|
||
)
|
||
|
||
|
||
_durability_reveal_agent = Agent(
|
||
FunctionModel(_durability_reveal_model),
|
||
name='durability_reveal_agent',
|
||
deps_type=type(None),
|
||
capabilities=[_durability_billing, TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@_durability_reveal_agent.tool
|
||
def durability_opener(ctx: RunContext[None]) -> ToolReturn[str]:
|
||
return ToolReturn(
|
||
return_value='opened',
|
||
tools=['durability_hidden'],
|
||
)
|
||
|
||
|
||
@_durability_reveal_agent.tool_plain(defer_loading=True)
|
||
def durability_hidden() -> str:
|
||
return 'secret'
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityRevealWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> list[ModelMessage]:
|
||
result = await _durability_reveal_agent.run(prompt)
|
||
return result.all_messages()
|
||
|
||
|
||
async def test_durability_tool_reveals_survive_workflow_and_activity(allow_model_requests: None, client: Client):
|
||
"""Capability and activity-authored reveals both become durable history facts."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityRevealWorkflow],
|
||
plugins=[AgentPlugin(_durability_reveal_agent)],
|
||
):
|
||
messages = await client.execute_workflow(
|
||
DurabilityRevealWorkflow.run,
|
||
args=['refund and open'],
|
||
id=DurabilityRevealWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
deltas = [
|
||
part
|
||
for message in messages
|
||
if isinstance(message, ModelRequest)
|
||
for part in message.parts
|
||
if isinstance(part, ToolAvailabilityDeltaPart)
|
||
]
|
||
assert [(part.tools_added, part.tool_call_id) for part in deltas] == [
|
||
(['durability_refund'], 'load'),
|
||
(['durability_hidden'], 'open'),
|
||
]
|
||
returns = {
|
||
part.tool_name: part.content
|
||
for message in messages
|
||
if isinstance(message, ModelRequest)
|
||
for part in message.parts
|
||
if isinstance(part, ToolReturnPart)
|
||
}
|
||
assert returns['durability_refund'] == 'refund available: True, opener available: True'
|
||
assert returns['durability_opener'] == 'opened'
|
||
|
||
|
||
# A fallback model cannot exercise Temporal's re-preparation seam: `FallbackModel.request()`
|
||
# prepares the history separately for every inner model, so the required mutation would still pass.
|
||
# Use raw model IDs across workflow executions instead, so only the worker-side concrete model can
|
||
# project the serialized reveal history.
|
||
def _cross_model_reveal_secondary(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
parts = [part for message in messages for part in message.parts]
|
||
assert not any(isinstance(part, ToolAvailabilityDeltaPart) for part in parts)
|
||
assert any(
|
||
isinstance(part, UserPromptPart)
|
||
and part.content == '<system>The following tool(s) are now available: `cross_model_refund`</system>'
|
||
for part in parts
|
||
)
|
||
assert 'cross_model_refund' in {tool.name for tool in info.function_tools}
|
||
if not any(isinstance(part, ToolReturnPart) and part.tool_name == 'cross_model_refund' for part in parts):
|
||
return ModelResponse(parts=[ToolCallPart('cross_model_refund', {}, tool_call_id='refund')])
|
||
return ModelResponse(parts=[TextPart('refund complete')])
|
||
|
||
|
||
def _cross_model_reveal_primary(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
deltas = [part for message in messages for part in message.parts if isinstance(part, ToolAvailabilityDeltaPart)]
|
||
if not deltas:
|
||
return ModelResponse(
|
||
parts=[ToolCallPart('load_capability', {'id': 'cross-model-billing'}, tool_call_id='load')]
|
||
)
|
||
assert [(part.tools_added, part.tool_call_id) for part in deltas] == [(['cross_model_refund'], 'load')]
|
||
return ModelResponse(parts=[TextPart('capability loaded')], usage=RequestUsage(input_tokens=1, output_tokens=1))
|
||
|
||
|
||
def _infer_cross_model(model_id: Any, **kwargs: Any) -> Model:
|
||
if model := _cross_model_reveal_models.get(str(model_id)):
|
||
return model
|
||
return infer_model(model_id, **kwargs)
|
||
|
||
|
||
_cross_model_reveal_models = {
|
||
'openai:cross-model-secondary': FunctionModel(
|
||
_cross_model_reveal_secondary,
|
||
model_name='cross-model-secondary',
|
||
profile=ModelProfile(),
|
||
),
|
||
'anthropic:cross-model-primary': FunctionModel(
|
||
_cross_model_reveal_primary,
|
||
model_name='cross-model-primary',
|
||
profile=ModelProfile(tool_addition_mode='by_reference', tool_deferral_mode='standalone'),
|
||
),
|
||
}
|
||
|
||
|
||
_cross_model_billing = Capability[None](id='cross-model-billing', defer_loading=True)
|
||
|
||
|
||
@_cross_model_billing.tool
|
||
def cross_model_refund(ctx: RunContext[None]) -> str:
|
||
return f'refund available in activity: {ctx.is_tool_available("cross_model_refund")}'
|
||
|
||
|
||
_cross_model_reveal_base_agent = Agent(
|
||
_cross_model_reveal_models['openai:cross-model-secondary'],
|
||
name='cross_model_reveal_agent',
|
||
deps_type=type(None),
|
||
capabilities=[
|
||
_cross_model_billing,
|
||
],
|
||
)
|
||
|
||
_cross_model_reveal_agent = TemporalAgent( # pyright: ignore[reportDeprecated]
|
||
_cross_model_reveal_base_agent,
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
)
|
||
|
||
|
||
@dataclass
|
||
class CrossModelRevealResult:
|
||
output: str
|
||
messages: list[ModelMessage]
|
||
|
||
|
||
@workflow.defn
|
||
class CrossModelRevealWorkflow:
|
||
@workflow.run
|
||
async def run(
|
||
self, prompt: str, model_id: str, message_history: list[ModelMessage] | None
|
||
) -> CrossModelRevealResult:
|
||
result = await _cross_model_reveal_agent.run(prompt, model=model_id, message_history=message_history)
|
||
return CrossModelRevealResult(output=result.output, messages=result.all_messages())
|
||
|
||
|
||
async def test_durability_reprepares_reveal_history_for_different_model(client: Client):
|
||
"""A serialized reveal is projected onto a different model's channel in a later workflow.
|
||
|
||
Raw model IDs keep message preparation out of the workflow. The channel-bearing primary
|
||
authors the reveal; the channel-less secondary receives an announcement, then calls the
|
||
newly available tool inside an activity.
|
||
"""
|
||
with patch(
|
||
'pydantic_ai.durable_exec.temporal._model.models.infer_model',
|
||
side_effect=_infer_cross_model,
|
||
):
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[CrossModelRevealWorkflow],
|
||
plugins=[AgentPlugin(_cross_model_reveal_agent)],
|
||
):
|
||
first = await client.execute_workflow(
|
||
CrossModelRevealWorkflow.run,
|
||
args=['load refund capability', 'anthropic:cross-model-primary', None],
|
||
id=f'{CrossModelRevealWorkflow.__name__}-primary',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
second = await client.execute_workflow(
|
||
CrossModelRevealWorkflow.run,
|
||
args=['issue refund', 'openai:cross-model-secondary', first.messages],
|
||
id=f'{CrossModelRevealWorkflow.__name__}-secondary',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert first.output == 'capability loaded'
|
||
assert second.output == 'refund complete'
|
||
tool_return = next(
|
||
part.content
|
||
for message in second.messages
|
||
for part in message.parts
|
||
if isinstance(part, ToolReturnPart) and part.tool_name == 'cross_model_refund'
|
||
)
|
||
assert tool_return == 'refund available in activity: True'
|
||
|
||
|
||
# --- Loading a deferred capability from code with `ctx.load_capability` ---
|
||
|
||
|
||
def _code_load_model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
"""Opens a case, calls `code_load_invoice` once it's visible, then answers with its result."""
|
||
returns = {
|
||
part.tool_name: part.content
|
||
for message in messages
|
||
for part in message.parts
|
||
if isinstance(part, ToolReturnPart)
|
||
}
|
||
if 'code_load_invoice' in returns:
|
||
return ModelResponse(parts=[TextPart(str(returns['code_load_invoice']))])
|
||
if 'code_load_invoice' in {tool.name for tool in info.function_tools}:
|
||
return ModelResponse(parts=[ToolCallPart('code_load_invoice', {}, tool_call_id='invoice')])
|
||
return ModelResponse(parts=[ToolCallPart('open_case', {}, tool_call_id='open')])
|
||
|
||
|
||
def _code_load_billing() -> Capability[None]:
|
||
billing = Capability[None](
|
||
id='code-load-billing', description='Billing.', instructions='Quote the invoice.', defer_loading=True
|
||
)
|
||
|
||
@billing.tool_plain
|
||
def code_load_invoice() -> str:
|
||
return 'Invoice paid.'
|
||
|
||
return billing
|
||
|
||
|
||
_code_load_hooks = Hooks[None]()
|
||
|
||
|
||
@_code_load_hooks.on.after_tool_execute
|
||
async def _load_billing_after_open_case(
|
||
ctx: RunContext[None], *, call: ToolCallPart, tool_def: ToolDefinition, args: dict[str, Any], result: Any
|
||
) -> Any:
|
||
if tool_def.name == 'open_case':
|
||
ctx.load_capability('code-load-billing')
|
||
return result
|
||
|
||
|
||
_code_load_hook_agent = Agent(
|
||
FunctionModel(_code_load_model),
|
||
name='code_load_hook_agent',
|
||
deps_type=type(None),
|
||
capabilities=[_code_load_billing(), _code_load_hooks, TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@_code_load_hook_agent.tool_plain(name='open_case')
|
||
def _code_load_open_case() -> str:
|
||
return 'Case opened.'
|
||
|
||
|
||
@workflow.defn
|
||
class CodeLoadHookWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _code_load_hook_agent.run('Was my invoice paid?')).output
|
||
|
||
|
||
async def test_durability_load_capability_from_tool_hook(client: Client):
|
||
"""A tool hook runs in the workflow, so it can load a capability whose tool then runs in an activity, and it replays."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[CodeLoadHookWorkflow],
|
||
plugins=[AgentPlugin(_code_load_hook_agent)],
|
||
):
|
||
handle = await client.start_workflow(
|
||
CodeLoadHookWorkflow.run, id=CodeLoadHookWorkflow.__name__, task_queue=TASK_QUEUE
|
||
)
|
||
output = await handle.result()
|
||
history = await handle.fetch_history()
|
||
|
||
replay = await Replayer(workflows=[CodeLoadHookWorkflow], plugins=[PydanticAIPlugin()]).replay_workflow(history)
|
||
|
||
assert (output, replay.replay_failure) == ('Invoice paid.', None)
|
||
|
||
|
||
_code_load_tool_agent = Agent(
|
||
FunctionModel(_code_load_model),
|
||
name='code_load_tool_agent',
|
||
deps_type=type(None),
|
||
capabilities=[_code_load_billing(), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@_code_load_tool_agent.tool(name='open_case')
|
||
async def _code_load_open_case_and_load(ctx: RunContext[None]) -> str:
|
||
ctx.load_capability('code-load-billing')
|
||
return 'Case opened.' # pragma: no cover
|
||
|
||
|
||
@workflow.defn
|
||
class CodeLoadToolWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _code_load_tool_agent.run('Open a billing case.')).output
|
||
|
||
|
||
async def test_durability_load_capability_from_tool_raises(client: Client):
|
||
"""A tool runs in an activity, whose recorded result replays without re-running it, so loading from it raises."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[CodeLoadToolWorkflow],
|
||
plugins=[AgentPlugin(_code_load_tool_agent)],
|
||
):
|
||
with workflow_activity_raises(
|
||
UserError,
|
||
'`ctx.load_capability()` is not supported inside a durable execution activity, step, or task, whose '
|
||
'recorded result is replayed without re-running your code. Load the capability from a tool hook such as '
|
||
'`after_tool_execute` instead.',
|
||
):
|
||
await client.execute_workflow(
|
||
CodeLoadToolWorkflow.run, id=CodeLoadToolWorkflow.__name__, task_queue=TASK_QUEUE
|
||
)
|
||
|
||
|
||
_load_before_run_hooks = Hooks[None]()
|
||
|
||
|
||
@_load_before_run_hooks.on.before_run
|
||
async def _load_billing_before_run(ctx: RunContext[None]) -> None:
|
||
ctx.load_capability('code-load-billing')
|
||
|
||
|
||
_load_before_request_hooks = Hooks[None]()
|
||
|
||
|
||
@_load_before_request_hooks.on.before_model_request
|
||
async def _load_billing_before_request(
|
||
ctx: RunContext[None], request_context: ModelRequestContext
|
||
) -> ModelRequestContext:
|
||
ctx.load_capability('code-load-billing')
|
||
return request_context
|
||
|
||
|
||
_load_after_request_hooks = Hooks[None]()
|
||
|
||
|
||
@_load_after_request_hooks.on.after_model_request
|
||
async def _load_billing_after_request(
|
||
ctx: RunContext[None], *, request_context: ModelRequestContext, response: ModelResponse
|
||
) -> ModelResponse:
|
||
if response.tool_calls:
|
||
ctx.load_capability('code-load-billing')
|
||
return response
|
||
|
||
|
||
_code_load_after_request_agent = Agent(
|
||
FunctionModel(_code_load_model),
|
||
name='code_load_after_request_agent',
|
||
deps_type=type(None),
|
||
capabilities=[
|
||
_code_load_billing(),
|
||
_load_after_request_hooks,
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@_code_load_after_request_agent.tool_plain(name='open_case')
|
||
def _code_load_after_request_open_case() -> str:
|
||
return 'Case opened.'
|
||
|
||
|
||
@workflow.defn
|
||
class CodeLoadAfterRequestWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _code_load_after_request_agent.run('Was my invoice paid?')).output
|
||
|
||
|
||
_code_load_before_run_agent = Agent(
|
||
FunctionModel(_code_load_model),
|
||
name='code_load_before_run_agent',
|
||
deps_type=type(None),
|
||
capabilities=[
|
||
_code_load_billing(),
|
||
_load_before_run_hooks,
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
_code_load_before_request_agent = Agent(
|
||
FunctionModel(_code_load_model),
|
||
name='code_load_before_request_agent',
|
||
deps_type=type(None),
|
||
capabilities=[
|
||
_code_load_billing(),
|
||
_load_before_request_hooks,
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class CodeLoadBeforeRunWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _code_load_before_run_agent.run('Was my invoice paid?')).output
|
||
|
||
|
||
@workflow.defn
|
||
class CodeLoadBeforeRequestWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await _code_load_before_request_agent.run('Was my invoice paid?')).output
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
'agent, workflow_cls',
|
||
[
|
||
(_code_load_before_run_agent, CodeLoadBeforeRunWorkflow),
|
||
(_code_load_before_request_agent, CodeLoadBeforeRequestWorkflow),
|
||
(_code_load_after_request_agent, CodeLoadAfterRequestWorkflow),
|
||
],
|
||
ids=['before_run', 'before_model_request', 'after_model_request'],
|
||
)
|
||
async def test_durability_load_capability_from_a_capability_hook(
|
||
client: Client, agent: Agent[None, str], workflow_cls: type[Any]
|
||
):
|
||
"""Capability hooks run in the workflow, so a load from one takes effect on the request that follows and replays.
|
||
|
||
From `before_run` or `before_model_request` that's the first request; from `after_model_request` on the response
|
||
that opens a case, the next one. Either way the model calls the capability's tool once it has it.
|
||
"""
|
||
async with Worker(client, task_queue=TASK_QUEUE, workflows=[workflow_cls], plugins=[AgentPlugin(agent)]):
|
||
handle = await client.start_workflow(workflow_cls.run, id=workflow_cls.__name__, task_queue=TASK_QUEUE)
|
||
output = await handle.result()
|
||
history = await handle.fetch_history()
|
||
|
||
replay = await Replayer(workflows=[workflow_cls], plugins=[PydanticAIPlugin()]).replay_workflow(history)
|
||
|
||
assert (output, replay.replay_failure) == ('Invoice paid.', None)
|
||
|
||
|
||
# --- Passing image (BinaryImage) input through to a workflow ---
|
||
|
||
_durability_multimodal_agent = Agent(
|
||
TestModel(),
|
||
name='durability_multimodal_content_agent',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@_durability_multimodal_agent.tool
|
||
def _durability_get_multimodal_content(ctx: RunContext[object]) -> list[str | MultiModalContent]:
|
||
"""Return a list with text, BinaryContent, and DocumentUrl."""
|
||
return [
|
||
'test',
|
||
BinaryImage(data=b'\x89PNG', media_type='image/png'),
|
||
DocumentUrl(url='https://example.com/doc/12345', media_type='application/pdf'),
|
||
]
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityMultiModalContentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: list[UserContent]) -> list[ModelMessage]:
|
||
result = await _durability_multimodal_agent.run(prompt)
|
||
return result.all_messages()
|
||
|
||
|
||
async def test_durability_passing_image_to_run(client: Client):
|
||
"""Capability-path equivalent of `test_multimodal_content_serialization_in_workflow` — image input.
|
||
|
||
Verifies BinaryImage / DocumentUrl survive Temporal serialization both as workflow
|
||
input and as tool return values when running on the TemporalDurability capability path.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityMultiModalContentWorkflow],
|
||
plugins=[AgentPlugin(_durability_multimodal_agent)],
|
||
):
|
||
prompt: list[str | MultiModalContent] = [
|
||
'Process these files and call the tool',
|
||
BinaryImage(data=b'\x89PNG', media_type='image/png'),
|
||
DocumentUrl(url='https://example.com/doc/12345', media_type='application/pdf'),
|
||
]
|
||
messages = await client.execute_workflow(
|
||
DurabilityMultiModalContentWorkflow.run,
|
||
args=[prompt],
|
||
id='test_durability_passing_image_to_run',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
# media_type is preserved through serialization for both BinaryContent and DocumentUrl.
|
||
media_types: list[tuple[str, str]] = []
|
||
for message in messages:
|
||
for part in message.parts:
|
||
if isinstance(part, UserPromptPart):
|
||
for content in part.content:
|
||
if isinstance(content, (BinaryContent, DocumentUrl)):
|
||
media_types.append((type(content).__name__, content.media_type))
|
||
elif isinstance(part, ToolReturnPart):
|
||
for content in part.content_items():
|
||
if isinstance(content, (BinaryContent, DocumentUrl)):
|
||
media_types.append((type(content).__name__, content.media_type))
|
||
# The image `BinaryContent` round-trips as `BinaryImage`: narrowing is applied during
|
||
# validation on the way back across the activity boundary.
|
||
assert media_types == [
|
||
('BinaryImage', 'image/png'),
|
||
('DocumentUrl', 'application/pdf'),
|
||
('BinaryImage', 'image/png'),
|
||
('DocumentUrl', 'application/pdf'),
|
||
]
|
||
|
||
|
||
# --- UploadedFile output round-trip ---
|
||
|
||
_durability_uploaded_file_agent = Agent(
|
||
TestModel(
|
||
custom_output_args={
|
||
'file_id': 'file-abc123',
|
||
'provider_name': 'openai',
|
||
'media_type': 'image/png',
|
||
'identifier': 'file-1',
|
||
}
|
||
),
|
||
name='durability_uploaded_file_agent',
|
||
output_type=UploadedFile,
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityUploadedFileAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> UploadedFile:
|
||
result = await _durability_uploaded_file_agent.run(prompt)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_uploaded_file_serialization_preserves_media_type(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_uploaded_file_serialization_preserves_media_type`."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityUploadedFileAgentWorkflow],
|
||
plugins=[AgentPlugin(_durability_uploaded_file_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityUploadedFileAgentWorkflow.run,
|
||
args=['Return a file reference'],
|
||
id=DurabilityUploadedFileAgentWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == snapshot(
|
||
UploadedFile(file_id='file-abc123', provider_name='openai', _media_type='image/png', _identifier='file-1')
|
||
)
|
||
|
||
|
||
# --- Toolsets at runtime ---
|
||
|
||
|
||
def _runtime_tool_model(messages: list[ModelMessage], _: AgentInfo) -> ModelResponse:
|
||
if any(isinstance(part, ToolReturnPart) for message in messages for part in message.parts):
|
||
return ModelResponse(parts=[TextPart('done')])
|
||
return ModelResponse(parts=[ToolCallPart('runtime_tool', {}, tool_call_id='call-1')])
|
||
|
||
|
||
_runtime_tool_agent = Agent(
|
||
FunctionModel(_runtime_tool_model),
|
||
name='runtime_tool_agent',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
async def _opted_out_runtime_tool() -> str:
|
||
return 'tool-result'
|
||
|
||
|
||
# Rejected before any tool runs.
|
||
async def _not_opted_out_runtime_tool() -> str: # pragma: no cover
|
||
return 'other-result'
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityOptedOutRuntimeFunctionToolsetWorkflow:
|
||
@workflow.run
|
||
async def run(self, partially_opted_out: bool) -> str:
|
||
toolset = FunctionToolset(id='runtime')
|
||
toolset.add_function(_opted_out_runtime_tool, name='runtime_tool', metadata={'temporal': False})
|
||
if partially_opted_out:
|
||
toolset.add_function(_not_opted_out_runtime_tool)
|
||
return (await _runtime_tool_agent.run('use the tool', toolsets=[toolset])).output
|
||
|
||
|
||
async def test_durability_runtime_function_toolset_opt_out(allow_model_requests: None, client: Client):
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityOptedOutRuntimeFunctionToolsetWorkflow],
|
||
plugins=[AgentPlugin(_runtime_tool_agent)],
|
||
):
|
||
assert (
|
||
await client.execute_workflow(
|
||
DurabilityOptedOutRuntimeFunctionToolsetWorkflow.run,
|
||
args=[False],
|
||
id=f'{DurabilityOptedOutRuntimeFunctionToolsetWorkflow.__name__}-full',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
== 'done'
|
||
)
|
||
with workflow_raises(
|
||
UserError,
|
||
snapshot(
|
||
"FunctionToolset 'runtime' cannot be added at runtime with Temporal, because toolsets that execute their own tools or resolve dynamically must be registered for durable execution when the agent is constructed. Pass them to the agent constructor instead -- not to `run(toolsets=...)` or `override(toolsets=...)`, and not via a post-construction `@agent.toolset`. Non-executing toolsets like `ExternalToolset` can be passed at runtime. Async tools that don't need durable wrapping can opt out with durable=False (or metadata={'temporal': False}, which takes precedence when set) to be allowed at runtime."
|
||
),
|
||
):
|
||
await client.execute_workflow(
|
||
DurabilityOptedOutRuntimeFunctionToolsetWorkflow.run,
|
||
args=[True],
|
||
id=f'{DurabilityOptedOutRuntimeFunctionToolsetWorkflow.__name__}-partial',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityRuntimeFunctionToolsetWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await simple_durable_agent.run(prompt, toolsets=[FunctionToolset()])
|
||
return result.output # pragma: no cover
|
||
|
||
|
||
async def test_durability_rejects_runtime_executing_toolsets_in_workflow(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_temporal_agent_run_in_workflow_with_executing_toolsets`.
|
||
|
||
Executing toolsets can't be added per-run inside a workflow because their activities must
|
||
be registered with the worker before the workflow runs.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityRuntimeFunctionToolsetWorkflow],
|
||
plugins=[AgentPlugin(simple_durable_agent)],
|
||
):
|
||
with workflow_raises(
|
||
UserError,
|
||
snapshot(
|
||
"FunctionToolset cannot be added at runtime with Temporal, because toolsets that execute their own tools or resolve dynamically must be registered for durable execution when the agent is constructed. Pass them to the agent constructor instead -- not to `run(toolsets=...)` or `override(toolsets=...)`, and not via a post-construction `@agent.toolset`. Non-executing toolsets like `ExternalToolset` can be passed at runtime. Async tools that don't need durable wrapping can opt out with durable=False (or metadata={'temporal': False}, which takes precedence when set) to be allowed at runtime."
|
||
),
|
||
):
|
||
await client.execute_workflow(
|
||
DurabilityRuntimeFunctionToolsetWorkflow.run,
|
||
args=['What is the capital of Mexico?'],
|
||
id=DurabilityRuntimeFunctionToolsetWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityOverriddenExecutingToolsetWorkflow:
|
||
@workflow.run
|
||
async def run(self, kind: str) -> None:
|
||
toolsets = {
|
||
'function': FunctionToolset(id='override_fn'),
|
||
'mcp': MCPToolset(StdioTransport(command='python', args=['-m', 'tests.mcp_server']), id='override_mcp'),
|
||
'dynamic': DynamicToolset(lambda _: FunctionToolset(), id='override_dynamic'),
|
||
}
|
||
with simple_durable_agent.override(toolsets=[toolsets[kind]]):
|
||
await simple_durable_agent.run('Hello')
|
||
|
||
|
||
@pytest.mark.parametrize('kind', ['function', 'mcp', 'dynamic'])
|
||
async def test_durability_rejects_overridden_executing_toolsets_in_workflow(client: Client, kind: str):
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityOverriddenExecutingToolsetWorkflow],
|
||
plugins=[AgentPlugin(simple_durable_agent)],
|
||
):
|
||
labels = {'function': 'FunctionToolset', 'mcp': 'MCPToolset', 'dynamic': 'DynamicToolset'}
|
||
message = (
|
||
f"{labels[kind]} 'override_{'fn' if kind == 'function' else kind}' cannot be added at runtime with "
|
||
'Temporal, because toolsets that execute their own tools or resolve dynamically must be registered '
|
||
'for durable execution when the agent is constructed. Pass them to the agent constructor instead -- '
|
||
'not to `run(toolsets=...)` or `override(toolsets=...)`, and not via a post-construction '
|
||
'`@agent.toolset`. Non-executing toolsets like `ExternalToolset` can be passed at runtime.'
|
||
) + (
|
||
" Async tools that don't need durable wrapping can opt out with durable=False (or "
|
||
"metadata={'temporal': False}, which takes precedence when set) to be allowed at runtime."
|
||
if kind == 'function'
|
||
else ''
|
||
)
|
||
with workflow_raises(UserError, message):
|
||
await client.execute_workflow(
|
||
DurabilityOverriddenExecutingToolsetWorkflow.run,
|
||
args=[kind],
|
||
id=f'{DurabilityOverriddenExecutingToolsetWorkflow.__name__}-{kind}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
|
||
def _registered_collision_tool() -> str:
|
||
return 'registered' # pragma: no cover
|
||
|
||
|
||
_id_collision_agent = Agent(
|
||
_durability_fn_model,
|
||
name='durability_id_collision_agent',
|
||
toolsets=[FunctionToolset([_registered_collision_tool], id='shared')],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
_colliding_external_toolset = ExternalToolset(tool_defs=[ToolDefinition(name='external')], id='shared')
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityCollidingRuntimeToolsetIdWorkflow:
|
||
@workflow.run
|
||
async def run(self, override: bool) -> None:
|
||
if override:
|
||
with _id_collision_agent.override(toolsets=[_colliding_external_toolset]):
|
||
await _id_collision_agent.run('Hello')
|
||
else:
|
||
await _id_collision_agent.run('Hello', toolsets=[_colliding_external_toolset])
|
||
|
||
|
||
@pytest.mark.parametrize('override', [False, True])
|
||
async def test_durability_rejects_runtime_toolset_reusing_registered_id(client: Client, override: bool):
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityCollidingRuntimeToolsetIdWorkflow],
|
||
plugins=[AgentPlugin(_id_collision_agent)],
|
||
):
|
||
message = (
|
||
"A toolset added at run time has the same `id` 'shared' as one the agent was constructed with. "
|
||
"Toolset `id`s must be unique: the `id` identifies which registered toolset's activity a tool call "
|
||
'is dispatched to inside the workflow, so this run would have called the construction-time '
|
||
"toolset's tools instead. Give the toolset a different `id`."
|
||
)
|
||
with workflow_raises(UserError, message):
|
||
await client.execute_workflow(
|
||
DurabilityCollidingRuntimeToolsetIdWorkflow.run,
|
||
args=[override],
|
||
id=f'{DurabilityCollidingRuntimeToolsetIdWorkflow.__name__}-{override}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
|
||
_late_decorator_agent = Agent(
|
||
_durability_fn_model,
|
||
name='durability_late_decorator_agent',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityLateDecoratorToolsetWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
@_late_decorator_agent.toolset(id='late_decorator')
|
||
def late_toolset(ctx: RunContext[object]) -> FunctionToolset[object]:
|
||
return FunctionToolset[object]() # pragma: no cover
|
||
|
||
result = await _late_decorator_agent.run(prompt)
|
||
return result.output # pragma: no cover
|
||
|
||
|
||
async def test_durability_rejects_decorator_toolset_in_workflow(client: Client):
|
||
"""A `@agent.toolset` registered after the capability bound is rejected inside a workflow.
|
||
|
||
The decorator lands in `agent.toolsets` only, so the runtime-toolset guard must subtract the
|
||
agent's *construction* toolsets to catch it: reading the wrong list would wave the
|
||
never-registered toolset through, and its tool calls would run undurably in workflow code.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityLateDecoratorToolsetWorkflow],
|
||
plugins=[AgentPlugin(_late_decorator_agent)],
|
||
):
|
||
message = (
|
||
"DynamicToolset 'late_decorator' cannot be added at runtime with Temporal, because toolsets that "
|
||
'execute their own tools or resolve dynamically must be registered for durable execution when the '
|
||
'agent is constructed. Pass them to the agent constructor instead -- not to `run(toolsets=...)` or '
|
||
'`override(toolsets=...)`, and not via a post-construction `@agent.toolset`. Non-executing '
|
||
'toolsets like `ExternalToolset` can be passed at runtime.'
|
||
)
|
||
with workflow_raises(UserError, message):
|
||
await client.execute_workflow(
|
||
DurabilityLateDecoratorToolsetWorkflow.run,
|
||
args=['Hello'],
|
||
id=DurabilityLateDecoratorToolsetWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
|
||
async def test_durability_allows_overridden_toolsets_outside_workflow(allow_model_requests: None):
|
||
with simple_durable_agent.override(toolsets=[FunctionToolset(id='override_outside')]):
|
||
result = await simple_durable_agent.run('Hello outside')
|
||
assert result.output == 'Echo: Hello outside'
|
||
|
||
|
||
async def test_durability_allows_runtime_toolsets_outside_workflow(allow_model_requests: None):
|
||
"""Outside a workflow the capability is transparent, so per-run executing toolsets are fine."""
|
||
|
||
def call_then_answer(messages: list[ModelMessage], _: AgentInfo) -> ModelResponse:
|
||
if any(isinstance(part, ToolReturnPart) for message in messages for part in message.parts):
|
||
return ModelResponse(parts=[TextPart('done')])
|
||
return ModelResponse(parts=[ToolCallPart('runtime_tool', {}, tool_call_id='call-1')])
|
||
|
||
def runtime_tool() -> str:
|
||
return 'tool-result'
|
||
|
||
agent = Agent(
|
||
FunctionModel(call_then_answer),
|
||
name='durability_runtime_outside_workflow',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
result = await agent.run(
|
||
'Call the runtime tool.', toolsets=[FunctionToolset(tools=[runtime_tool], id='runtime_fn')]
|
||
)
|
||
assert result.output == 'done'
|
||
|
||
|
||
def _durability_request_external_tool(messages: list[ModelMessage], agent_info: AgentInfo) -> ModelResponse:
|
||
return ModelResponse(parts=[ToolCallPart('external', {'query': 'runtime'}, tool_call_id='call-1')])
|
||
|
||
|
||
_durability_runtime_external_agent = Agent(
|
||
FunctionModel(_durability_request_external_tool),
|
||
name='durability_runtime_external_agent',
|
||
output_type=[str, DeferredToolRequests],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
_durability_runtime_external_toolset = ExternalToolset(
|
||
tool_defs=[
|
||
ToolDefinition(
|
||
name='external',
|
||
parameters_json_schema={
|
||
'type': 'object',
|
||
'properties': {'query': {'type': 'string'}},
|
||
'required': ['query'],
|
||
},
|
||
)
|
||
],
|
||
id='external',
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityRuntimeExternalToolsetWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> DeferredToolRequests | str:
|
||
result = await _durability_runtime_external_agent.run(prompt, toolsets=[_durability_runtime_external_toolset])
|
||
return result.output
|
||
|
||
|
||
async def test_durability_run_in_workflow_with_runtime_external_toolset(allow_model_requests: None, client: Client):
|
||
"""Capability-path equivalent of `test_temporal_agent_run_in_workflow_with_runtime_external_toolset`."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityRuntimeExternalToolsetWorkflow],
|
||
plugins=[AgentPlugin(_durability_runtime_external_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityRuntimeExternalToolsetWorkflow.run,
|
||
args=['Call the runtime external tool.'],
|
||
id=DurabilityRuntimeExternalToolsetWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == DeferredToolRequests(
|
||
calls=[ToolCallPart('external', {'query': 'runtime'}, tool_call_id='call-1')],
|
||
validated_args={'call-1': {'query': 'runtime'}},
|
||
)
|
||
|
||
|
||
# --- Capability-contributed toolsets ---
|
||
|
||
|
||
def _durability_call_where_am_i(messages: list[ModelMessage], agent_info: AgentInfo) -> ModelResponse:
|
||
for message in messages:
|
||
for part in message.parts:
|
||
if isinstance(part, ToolReturnPart):
|
||
return ModelResponse(parts=[TextPart(str(part.content))])
|
||
return ModelResponse(parts=[ToolCallPart('where_am_i', {}, tool_call_id='call-1')])
|
||
|
||
|
||
def where_am_i() -> str:
|
||
return 'activity' if activity.in_activity() else 'workflow'
|
||
|
||
|
||
_durability_cap_toolset_agent = Agent(
|
||
FunctionModel(_durability_call_where_am_i),
|
||
name='durability_cap_toolset_agent',
|
||
capabilities=[
|
||
Toolset(FunctionToolset([where_am_i], id='cap_tools')),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityCapabilityToolsetWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
result = await _durability_cap_toolset_agent.run(prompt)
|
||
return result.output
|
||
|
||
|
||
async def test_durability_temporalizes_capability_contributed_toolsets(allow_model_requests: None, client: Client):
|
||
"""Toolsets contributed by other capabilities run as Temporal activities.
|
||
|
||
Durability capabilities are in the `innermost` ordering tier, so `Agent.__init__` binds
|
||
them only after every other capability's contributed toolsets have been extracted into
|
||
`agent.toolsets`. Without that two-phase binding, the `Toolset(...)` capability's tools
|
||
would be invisible to `for_agent` and run unwrapped (non-deterministically) inside the
|
||
workflow instead of in an activity.
|
||
"""
|
||
durability = TemporalDurability.from_agent(_durability_cap_toolset_agent)
|
||
assert durability is not None
|
||
assert 'agent__durability_cap_toolset_agent__toolset__cap_tools__call_tool' in [
|
||
ActivityDefinition.must_from_callable(act).name # pyright: ignore[reportUnknownMemberType]
|
||
for act in durability.temporal_activities
|
||
]
|
||
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityCapabilityToolsetWorkflow],
|
||
plugins=[AgentPlugin(_durability_cap_toolset_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityCapabilityToolsetWorkflow.run,
|
||
args=['Where does the tool run?'],
|
||
id=DurabilityCapabilityToolsetWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == 'activity'
|
||
|
||
|
||
_continuation_model = ScriptedContinuationModel()
|
||
|
||
_continuation_agent = Agent(
|
||
_continuation_model,
|
||
name='durability_continuation_agent',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityContinuationWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
return await _continuation_agent.run(prompt)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityContinuationResumeWorkflow:
|
||
@workflow.run
|
||
async def run(self, messages: list[ModelMessage]) -> AgentRunResult[str]:
|
||
return await _continuation_agent.run(message_history=messages)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityContinuationUsageLimitWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
return await _continuation_agent.run(prompt, usage_limits=UsageLimits(total_tokens_limit=20))
|
||
|
||
|
||
async def test_durability_continuation_chain_in_workflow(client: Client):
|
||
"""A suspended → complete chain resolves across per-segment activities as one merged response.
|
||
|
||
Usage is counted once (a continuation isn't a separate request step), and the workflow
|
||
history shows one scheduled activity for each segment.
|
||
"""
|
||
_continuation_model.reset(
|
||
responses=[
|
||
scripted_response(
|
||
texts=['The answer '],
|
||
state='suspended',
|
||
provider_response_id='cont1',
|
||
input_tokens=5,
|
||
output_tokens=2,
|
||
),
|
||
scripted_response(texts=['is 42.'], provider_response_id='cont2', input_tokens=3, output_tokens=4),
|
||
]
|
||
)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityContinuationWorkflow],
|
||
plugins=[AgentPlugin(_continuation_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityContinuationWorkflow.run,
|
||
args=['go'],
|
||
id='DurabilityContinuationWorkflow_chain',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result = await wf.result()
|
||
history = await wf.fetch_history()
|
||
|
||
assert result.output == 'The answer is 42.'
|
||
response = result.all_messages()[-1]
|
||
assert isinstance(response, ModelResponse)
|
||
assert response.state == 'complete'
|
||
assert [part.content for part in response.parts if isinstance(part, TextPart)] == ['The answer ', 'is 42.']
|
||
usage = result.usage
|
||
assert usage.requests == 1
|
||
assert usage.input_tokens == 8
|
||
assert usage.output_tokens == 6
|
||
# Both segments ran in their own durable boundary.
|
||
assert _continuation_model.request_calls == 2
|
||
assert _scheduled_activity_count(history) == 2
|
||
|
||
|
||
class _DelayedContinuationModel(ScriptedContinuationModel):
|
||
def continuation_delay(self, response: ModelResponse) -> float | None:
|
||
return 0.2
|
||
|
||
|
||
_continuation_delay_model = _DelayedContinuationModel()
|
||
|
||
_continuation_delay_agent = Agent(
|
||
_continuation_delay_model,
|
||
name='durability_continuation_delay_agent',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityContinuationDelayWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
return await _continuation_delay_agent.run(prompt)
|
||
|
||
|
||
async def test_durability_continuation_delay_uses_durable_timer(client: Client):
|
||
"""The wait before re-polling a suspended segment burns a durable Temporal timer.
|
||
|
||
`TemporalDurability` registers `workflow.sleep` as the agent-graph sleep, so a model's
|
||
`continuation_delay` (forwarded through the per-segment wrapper to the real workflow-side
|
||
model) shows up in workflow history as a timer that survives replays, rather than
|
||
consuming activity wall-clock time.
|
||
"""
|
||
_continuation_delay_model.reset(
|
||
responses=[
|
||
scripted_response(
|
||
texts=['The answer '],
|
||
state='suspended',
|
||
provider_response_id='cont1',
|
||
input_tokens=5,
|
||
output_tokens=2,
|
||
),
|
||
scripted_response(texts=['is 42.'], provider_response_id='cont2', input_tokens=3, output_tokens=4),
|
||
]
|
||
)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityContinuationDelayWorkflow],
|
||
plugins=[AgentPlugin(_continuation_delay_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityContinuationDelayWorkflow.run,
|
||
args=['go'],
|
||
id='DurabilityContinuationDelayWorkflow_timer',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result = await wf.result()
|
||
history = await wf.fetch_history()
|
||
|
||
assert result.output == 'The answer is 42.'
|
||
assert _continuation_delay_model.request_calls == 2
|
||
assert _scheduled_activity_count(history) == 2
|
||
assert any(event.HasField('timer_started_event_attributes') for event in history.events)
|
||
|
||
|
||
class _ContinuationFailsToOpen(ScriptedContinuationModel):
|
||
"""Fails to open the stream that would continue a suspended response."""
|
||
|
||
@asynccontextmanager
|
||
async def request_stream(
|
||
self,
|
||
messages: list[ModelMessage],
|
||
model_settings: ModelSettings | None,
|
||
model_request_parameters: ModelRequestParameters,
|
||
run_context: RunContext[Any] | None = None,
|
||
) -> AsyncGenerator[StreamedResponse]:
|
||
self.request_stream_calls += 1
|
||
raise ModelAPIError(model_name='scripted', message='continuation failed')
|
||
yield # pragma: no cover
|
||
|
||
|
||
async def _streamed_answer(messages: list[ModelMessage], info: AgentInfo) -> AsyncIterator[str]:
|
||
yield 'from the backup'
|
||
|
||
|
||
_resume_failing_model = _ContinuationFailsToOpen()
|
||
|
||
_resume_fallback_agent = Agent(
|
||
_resume_failing_model,
|
||
deps_type=type(None),
|
||
name='durability_resume_fallback_agent',
|
||
capabilities=[
|
||
ModelFallback('resume_backup'),
|
||
TemporalDurability(
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
models={'resume_backup': FunctionModel(stream_function=_streamed_answer, model_name='resume_backup')},
|
||
event_stream_handler=_drain_events,
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityResumeFallbackWorkflow:
|
||
@workflow.run
|
||
async def run(self, history: list[ModelMessage]) -> AgentRunResult[str]:
|
||
return await _resume_fallback_agent.run(message_history=history)
|
||
|
||
|
||
async def test_durability_resumed_step_falls_back_when_its_continuation_fails_to_open(client: Client):
|
||
"""A step resumed from a suspended response, whose streamed continuation fails to open, falls back in the workflow.
|
||
|
||
The suspended response's job is cancelled, and the next model generates the turn in an activity of its own.
|
||
"""
|
||
_resume_failing_model.reset()
|
||
history_messages: list[ModelMessage] = [
|
||
ModelRequest(parts=[UserPromptPart(content='go')]),
|
||
scripted_response(
|
||
texts=['The answer '], state='suspended', provider_response_id='job-1', input_tokens=5, output_tokens=2
|
||
),
|
||
]
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityResumeFallbackWorkflow],
|
||
plugins=[AgentPlugin(_resume_fallback_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityResumeFallbackWorkflow.run,
|
||
args=[history_messages],
|
||
id=DurabilityResumeFallbackWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result = await wf.result()
|
||
history = await wf.fetch_history()
|
||
|
||
assert result.output == 'from the backup'
|
||
assert _resume_failing_model.request_stream_calls == 1
|
||
assert [response.provider_response_id for response in _resume_failing_model.cancelled] == ['job-1']
|
||
assert [(attempt.model_name, attempt.outcome) for attempt in result.response.failed_attempts or []] == [
|
||
('scripted', 'error')
|
||
]
|
||
# The failed continuation, the job cancellation, and the backup's request.
|
||
assert _scheduled_activity_count(history) == 3
|
||
|
||
|
||
async def test_durability_continuation_resume_from_history(client: Client):
|
||
"""A `message_history` ending in a suspended response resumes inside the activity.
|
||
|
||
The suspended tail crosses the activity boundary as the last request message and seeds
|
||
the continuation loop there, so the run completes the paused turn instead of starting a
|
||
fresh generation.
|
||
"""
|
||
_continuation_model.reset(
|
||
responses=[scripted_response(texts=['is 42.'], provider_response_id='cont2', input_tokens=3, output_tokens=4)]
|
||
)
|
||
history_messages: list[ModelMessage] = [
|
||
ModelRequest(parts=[UserPromptPart(content='go')]),
|
||
scripted_response(
|
||
texts=['The answer '], state='suspended', provider_response_id='cont1', input_tokens=5, output_tokens=2
|
||
),
|
||
]
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityContinuationResumeWorkflow],
|
||
plugins=[AgentPlugin(_continuation_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityContinuationResumeWorkflow.run,
|
||
args=[history_messages],
|
||
id='DurabilityContinuationWorkflow_resume',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result = await wf.result()
|
||
history = await wf.fetch_history()
|
||
|
||
assert result.output == 'The answer is 42.'
|
||
response = result.all_messages()[-1]
|
||
assert isinstance(response, ModelResponse)
|
||
assert response.state == 'complete'
|
||
assert [part.content for part in response.parts if isinstance(part, TextPart)] == ['The answer ', 'is 42.']
|
||
# The suspended response's 5 + 2 tokens were counted by the run that produced it, so this run counts only
|
||
# the continuation it requested; the completed response in history still reports the whole turn.
|
||
usage = result.usage
|
||
assert usage.requests == 1
|
||
assert (usage.input_tokens, usage.output_tokens) == (3, 4)
|
||
assert (response.usage.input_tokens, response.usage.output_tokens) == (8, 6)
|
||
# The continuation request ran inside the boundary — the seed wasn't re-generated.
|
||
assert _continuation_model.request_calls == 1
|
||
assert _scheduled_activity_count(history) == 1
|
||
|
||
|
||
async def test_durability_continuation_error_cancels_job_inside_activity(client: Client):
|
||
"""A request failure mid-chain cancels the suspended server-side job inside the activity.
|
||
|
||
The cancel-on-error policy runs on the real model inside the durable boundary — the
|
||
workflow side never sees the live suspended response.
|
||
"""
|
||
_continuation_model.reset(
|
||
responses=[
|
||
scripted_response(
|
||
texts=['The answer '],
|
||
state='suspended',
|
||
provider_response_id='cont1',
|
||
input_tokens=5,
|
||
output_tokens=2,
|
||
),
|
||
RuntimeError('provider blew up'),
|
||
]
|
||
)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityContinuationWorkflow],
|
||
plugins=[AgentPlugin(_continuation_agent)],
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
DurabilityContinuationWorkflow.run,
|
||
args=['go'],
|
||
id='DurabilityContinuationWorkflow_cancel_on_error',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
cause = _workflow_failure_cause(exc_info.value)
|
||
assert cause.type == 'RuntimeError'
|
||
assert cause.message == 'provider blew up'
|
||
assert _continuation_model.request_calls == 2
|
||
assert len(_continuation_model.cancelled) == 1
|
||
assert _continuation_model.cancelled[0].provider_response_id == 'cont1'
|
||
|
||
|
||
async def test_durability_continuation_usage_limit_checked_inside_activity(client: Client):
|
||
"""Token limits are enforced mid-chain inside the activity, cancelling the live job.
|
||
|
||
`usage`/`usage_limits` cross the activity boundary on the serialized run context (a
|
||
custom `TemporalRunContext` subclass must keep including them), so a runaway
|
||
continuation fails fast without waiting for the workflow-side commit.
|
||
"""
|
||
_continuation_model.reset(
|
||
responses=[
|
||
scripted_response(
|
||
texts=['The answer '],
|
||
state='suspended',
|
||
provider_response_id='cont1',
|
||
input_tokens=5,
|
||
output_tokens=2,
|
||
),
|
||
scripted_response(
|
||
texts=['keeps going '],
|
||
state='suspended',
|
||
provider_response_id='cont2',
|
||
input_tokens=100,
|
||
output_tokens=50,
|
||
),
|
||
]
|
||
)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityContinuationUsageLimitWorkflow],
|
||
plugins=[AgentPlugin(_continuation_agent)],
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
DurabilityContinuationUsageLimitWorkflow.run,
|
||
args=['go'],
|
||
id='DurabilityContinuationWorkflow_usage_limit',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
cause = _workflow_failure_cause(exc_info.value)
|
||
assert cause.type == UsageLimitExceeded.__name__
|
||
assert 'total_tokens_limit' in cause.message
|
||
assert _continuation_model.request_calls == 2
|
||
# The over-budget merge was still suspended, so the live job was cancelled before raising.
|
||
assert len(_continuation_model.cancelled) == 1
|
||
assert _continuation_model.cancelled[0].provider_response_id == 'cont2'
|
||
|
||
|
||
# --- `BatchModelRequests` rides the continuation loop: one activity per batch check, durable timers between ---
|
||
|
||
_batch_wrapped_model = SlowBatchTestModel()
|
||
|
||
_batch_agent = Agent(
|
||
_batch_wrapped_model,
|
||
name='durability_batch_agent',
|
||
capabilities=[BatchModelRequests(**FAST_BATCH_SETTINGS), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityBatchWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
return await _batch_agent.run(prompt)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityBatchResumeWorkflow:
|
||
@workflow.run
|
||
async def run(self, messages: list[ModelMessage]) -> AgentRunResult[str]:
|
||
return await _batch_agent.run(message_history=messages)
|
||
|
||
|
||
def _timer_count(history: WorkflowHistory) -> int:
|
||
return len([e for e in history.events if e.HasField('timer_started_event_attributes')])
|
||
|
||
|
||
async def test_durability_batch_model_in_workflow(client: Client):
|
||
"""`BatchModelRequests` works under `TemporalDurability` through the continuation loop alone.
|
||
|
||
The submitting request and every later batch check each run in their own model-request
|
||
activity, and the poll delay the batching model's `continuation_delay` asks for is a durable workflow
|
||
timer between them, so a run can wait out a batch across worker restarts. The suspended
|
||
response is replaced by each check and then by the decoded result, so the run ends with one
|
||
complete response counted as one request.
|
||
"""
|
||
_batch_wrapped_model.reset(pending_checks=1)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityBatchWorkflow],
|
||
plugins=[AgentPlugin(_batch_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityBatchWorkflow.run,
|
||
args=['go'],
|
||
id='DurabilityBatchWorkflow_chain',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result = await wf.result()
|
||
history = await wf.fetch_history()
|
||
|
||
assert result.output == 'success (no tool calls)'
|
||
assert [type(message).__name__ for message in result.all_messages()] == ['ModelRequest', 'ModelResponse']
|
||
response = result.all_messages()[-1]
|
||
assert isinstance(response, ModelResponse)
|
||
assert response.state == 'complete'
|
||
assert result.usage.requests == 1
|
||
assert len(_batch_wrapped_model.created) == 1
|
||
# The first check finds the batch in progress, the second finds it ended.
|
||
assert _batch_wrapped_model.status_checks == 2
|
||
# One activity submits the request, then one per check, with a durable timer before each check.
|
||
assert _scheduled_activity_count(history) == 3
|
||
assert _timer_count(history) == 2
|
||
|
||
|
||
async def test_durability_batch_model_resume_from_history(client: Client):
|
||
"""A run resumed from history ending in a pending batch response waits for that same batch.
|
||
|
||
The pending response, created outside the workflow, crosses the activity boundary as the
|
||
last request message, so the activity checks the batch it records instead of submitting
|
||
the request again.
|
||
"""
|
||
_batch_wrapped_model.reset(pending_checks=0)
|
||
request = ModelRequest(parts=[UserPromptPart(content='go')])
|
||
# Batched before the run, for example by another process.
|
||
pending = (
|
||
await BatchPool(**FAST_BATCH_SETTINGS)
|
||
.wrap(_batch_wrapped_model)
|
||
.request([request], None, ModelRequestParameters())
|
||
)
|
||
assert pending.state == 'suspended'
|
||
assert len(_batch_wrapped_model.created) == 1
|
||
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityBatchResumeWorkflow],
|
||
plugins=[AgentPlugin(_batch_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityBatchResumeWorkflow.run,
|
||
args=[[request, pending]],
|
||
id='DurabilityBatchWorkflow_resume',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result = await wf.result()
|
||
history = await wf.fetch_history()
|
||
|
||
assert result.output == 'success (no tool calls)'
|
||
response = result.all_messages()[-1]
|
||
assert isinstance(response, ModelResponse)
|
||
assert response.state == 'complete'
|
||
# No second batch: the one activity checked the batch the history recorded.
|
||
assert len(_batch_wrapped_model.created) == 1
|
||
assert _batch_wrapped_model.status_checks == 1
|
||
assert _scheduled_activity_count(history) == 1
|
||
assert _timer_count(history) == 1
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityBatchPendingWorkflow:
|
||
@workflow.run
|
||
async def run(self, messages: list[ModelMessage] | None) -> AgentRunResult[str | PendingModelResponse]:
|
||
return await _batch_agent.run(
|
||
None if messages else 'go', message_history=messages, output_type=[str, PendingModelResponse]
|
||
)
|
||
|
||
|
||
async def test_durability_batch_model_with_pending_output_ends_and_resumes(client: Client):
|
||
"""With `PendingModelResponse` in the output type, each workflow run makes one batch call and ends.
|
||
|
||
The first run submits the request in one activity and returns the pending response without starting a timer.
|
||
The second run, resumed from that history in a new workflow, checks the batch once, again without a timer, and
|
||
finishes with the result.
|
||
"""
|
||
_batch_wrapped_model.reset(pending_checks=0)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityBatchPendingWorkflow],
|
||
plugins=[AgentPlugin(_batch_agent)],
|
||
):
|
||
submit = await client.start_workflow(
|
||
DurabilityBatchPendingWorkflow.run,
|
||
args=[None],
|
||
id='DurabilityBatchPendingWorkflow_submit',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
submitted = await submit.result()
|
||
submit_history = await submit.fetch_history()
|
||
|
||
assert isinstance(submitted.output, PendingModelResponse)
|
||
assert submitted.output.response.state == 'suspended'
|
||
assert submitted.output.response == submitted.all_messages()[-1]
|
||
assert len(_batch_wrapped_model.created) == 1
|
||
assert _batch_wrapped_model.status_checks == 0
|
||
assert _scheduled_activity_count(submit_history) == 1
|
||
assert _timer_count(submit_history) == 0
|
||
|
||
collect = await client.start_workflow(
|
||
DurabilityBatchPendingWorkflow.run,
|
||
args=[submitted.all_messages()],
|
||
id='DurabilityBatchPendingWorkflow_collect',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
collected = await collect.result()
|
||
collect_history = await collect.fetch_history()
|
||
|
||
assert collected.output == 'success (no tool calls)'
|
||
assert len(_batch_wrapped_model.created) == 1
|
||
assert _batch_wrapped_model.status_checks == 1
|
||
assert _scheduled_activity_count(collect_history) == 1
|
||
assert _timer_count(collect_history) == 0
|
||
|
||
|
||
_shared_batch_wrapped_model = SlowBatchTestModel()
|
||
|
||
_shared_batch_agent = Agent(
|
||
_shared_batch_wrapped_model,
|
||
name='durability_shared_batch_agent',
|
||
capabilities=[
|
||
# Only a full batch is submitted before the long `max_wait`, so the test waits on no timer.
|
||
BatchModelRequests(**FAST_POLLING, max_requests=3, max_wait=timedelta(minutes=1)),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilitySharedBatchWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
return await _shared_batch_agent.run(prompt)
|
||
|
||
|
||
async def test_durability_batch_model_requests_share_a_batch_across_workflows(client: Client):
|
||
"""Requests from concurrent workflow runs are batched together in the worker.
|
||
|
||
The workflow side only wraps the model to answer `continuation_delay`; the model-request activities wrap the
|
||
model they rebuild with the agent's own `BatchModelRequests` instance, so their requests share its pool.
|
||
"""
|
||
_shared_batch_wrapped_model.reset(pending_checks=0)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilitySharedBatchWorkflow],
|
||
plugins=[AgentPlugin(_shared_batch_agent)],
|
||
):
|
||
results = await asyncio.gather(
|
||
*(
|
||
client.execute_workflow(
|
||
DurabilitySharedBatchWorkflow.run,
|
||
args=[f'go {i}'],
|
||
id=f'DurabilitySharedBatchWorkflow_{i}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
for i in range(3)
|
||
)
|
||
)
|
||
|
||
assert [result.output for result in results] == ['success (no tool calls)'] * 3
|
||
assert [batch.request_count for batch in _shared_batch_wrapped_model.created] == [3]
|
||
assert _shared_batch_wrapped_model.status_checks == 1
|
||
|
||
|
||
async def test_durability_batch_model_replay_does_not_submit_again(client: Client):
|
||
"""Replaying a finished workflow reads each model-request activity's recorded result, so nothing is submitted."""
|
||
_batch_wrapped_model.reset(pending_checks=1)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityBatchWorkflow],
|
||
plugins=[AgentPlugin(_batch_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityBatchWorkflow.run,
|
||
args=['go'],
|
||
id='DurabilityBatchWorkflow_replay',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
await wf.result()
|
||
history = await wf.fetch_history()
|
||
assert (len(_batch_wrapped_model.created), _batch_wrapped_model.status_checks) == (1, 2)
|
||
|
||
await Replayer(
|
||
workflows=[DurabilityBatchWorkflow],
|
||
workflow_runner=UnsandboxedWorkflowRunner(),
|
||
plugins=[AgentPlugin(_batch_agent)],
|
||
).replay_workflow(history)
|
||
|
||
assert (len(_batch_wrapped_model.created), _batch_wrapped_model.status_checks) == (1, 2)
|
||
|
||
|
||
class _LostSubmissionModel(SlowBatchTestModel):
|
||
"""Creates the first batch, then fails as if the connection dropped before the response arrived."""
|
||
|
||
async def batch_create(self, requests: Sequence[EncodedBatchRequest]) -> Batch:
|
||
batch = await super().batch_create(requests)
|
||
if len(self.created) == 1:
|
||
raise RuntimeError('The connection dropped after the batch was created.')
|
||
return batch
|
||
|
||
|
||
_lost_submission_model = _LostSubmissionModel()
|
||
|
||
_lost_submission_agent = Agent(
|
||
_lost_submission_model,
|
||
name='durability_lost_submission_agent',
|
||
capabilities=[
|
||
BatchModelRequests(**FAST_BATCH_SETTINGS),
|
||
TemporalDurability(
|
||
activity_config=ActivityConfig(
|
||
start_to_close_timeout=timedelta(seconds=60),
|
||
retry_policy=RetryPolicy(maximum_attempts=2, initial_interval=timedelta(milliseconds=10)),
|
||
)
|
||
),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityLostSubmissionWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
return await _lost_submission_agent.run(prompt)
|
||
|
||
|
||
async def test_durability_batch_model_retried_submission_submits_again(client: Client):
|
||
"""The one window for a second batch: a model-request activity retried after its batch was created.
|
||
|
||
Once the activity that submitted the request completes, its recorded result is reused, but an attempt that
|
||
fails, or times out, after the provider created the batch is retried like any other model request, and the retry
|
||
submits the request again.
|
||
"""
|
||
_lost_submission_model.reset(pending_checks=0)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityLostSubmissionWorkflow],
|
||
plugins=[AgentPlugin(_lost_submission_agent)],
|
||
):
|
||
result = await client.execute_workflow(
|
||
DurabilityLostSubmissionWorkflow.run,
|
||
args=['go'],
|
||
id='DurabilityLostSubmissionWorkflow',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert result.output == 'success (no tool calls)'
|
||
assert len(_lost_submission_model.created) == 2
|
||
|
||
|
||
_continuation_ceiling_model = ScriptedContinuationModel()
|
||
|
||
_continuation_ceiling_agent = Agent(
|
||
_continuation_ceiling_model,
|
||
name='durability_continuation_ceiling_agent',
|
||
capabilities=[
|
||
TemporalDurability(
|
||
activity_config=ActivityConfig(
|
||
start_to_close_timeout=timedelta(seconds=60),
|
||
# More than one attempt allowed, to prove `UnexpectedModelBehavior` is
|
||
# non-retryable rather than merely running out of attempts.
|
||
retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(milliseconds=10)),
|
||
)
|
||
)
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityContinuationCeilingWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
return await _continuation_ceiling_agent.run(prompt)
|
||
|
||
|
||
async def test_durability_continuation_ceiling_surfaces_unexpected_model_behavior(client: Client):
|
||
"""Exceeding the continuation ceiling fails the workflow without activity retries.
|
||
|
||
`UnexpectedModelBehavior` is in the activity retry policy's non-retryable error types:
|
||
re-running the whole chain wouldn't fix a model that never leaves `'suspended'`, it
|
||
would only re-incur its cost. The single-attempt call count proves no retry happened.
|
||
"""
|
||
_continuation_ceiling_model.reset(
|
||
responses=[
|
||
scripted_response(
|
||
texts=[f'segment {i} '],
|
||
state='suspended',
|
||
provider_response_id=f'cont{i}',
|
||
input_tokens=1,
|
||
output_tokens=1,
|
||
)
|
||
for i in range(1, 12)
|
||
]
|
||
)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityContinuationCeilingWorkflow],
|
||
plugins=[AgentPlugin(_continuation_ceiling_agent)],
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
DurabilityContinuationCeilingWorkflow.run,
|
||
args=['go'],
|
||
id=DurabilityContinuationCeilingWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
cause = _workflow_failure_cause(exc_info.value)
|
||
assert cause.type == UnexpectedModelBehavior.__name__
|
||
assert cause.message == snapshot("Model response 'cont11' was suspended more than the maximum of 10 times")
|
||
# 1 initial + 10 continuation requests, from a single activity attempt (no retries).
|
||
assert _continuation_ceiling_model.request_calls == 11
|
||
# Giving up on a still-suspended job cancels it inside the activity so it doesn't leak.
|
||
assert len(_continuation_ceiling_model.cancelled) == 1
|
||
|
||
|
||
# --- `ModelFallback` moves a failed batch on to a batch on the next model ---
|
||
|
||
_fallback_batch_calls: list[tuple[str, str, bool]] = []
|
||
"""Each batch call the models below make: the model, the method, and whether it ran in an activity."""
|
||
|
||
|
||
def _record_fallback_batch_call(model_name: str) -> Callable[[str], None]:
|
||
def record(method: str) -> None:
|
||
_fallback_batch_calls.append((model_name, method, activity.in_activity()))
|
||
|
||
return record
|
||
|
||
|
||
_fallback_batch_primary = FailingBatchTestModel(
|
||
pending_checks=1, on_batch_call=_record_fallback_batch_call('primary'), model_name='primary'
|
||
)
|
||
_fallback_batch_fallback = SlowBatchTestModel(
|
||
pending_checks=1, on_batch_call=_record_fallback_batch_call('fallback'), model_name='fallback'
|
||
)
|
||
|
||
_fallback_batch_agent = Agent(
|
||
_fallback_batch_primary,
|
||
name='durability_fallback_batch_agent',
|
||
capabilities=[
|
||
ModelFallback('batch_fallback'),
|
||
BatchModelRequests(**FAST_BATCH_SETTINGS),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG, models={'batch_fallback': _fallback_batch_fallback}),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityFallbackBatchWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> AgentRunResult[str]:
|
||
return await _fallback_batch_agent.run(prompt)
|
||
|
||
|
||
async def test_durability_fallback_batches_the_next_model_when_a_batch_fails(client: Client):
|
||
"""When the primary model's batch result fails, `ModelFallback` moves the request into a batch on the fallback.
|
||
|
||
The workflow wraps each attempt's model to answer `continuation_delay`, and the model-request activities wrap the
|
||
model they rebuild, the primary's and then the fallback's, so both batches are submitted and checked in activities.
|
||
"""
|
||
_fallback_batch_calls.clear()
|
||
_fallback_batch_primary.reset(pending_checks=1)
|
||
_fallback_batch_fallback.reset(pending_checks=1)
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityFallbackBatchWorkflow],
|
||
plugins=[AgentPlugin(_fallback_batch_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityFallbackBatchWorkflow.run,
|
||
args=['go'],
|
||
id=DurabilityFallbackBatchWorkflow.__name__,
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result = await wf.result()
|
||
history = await wf.fetch_history()
|
||
|
||
assert result.output == 'success (no tool calls)'
|
||
response = result.all_messages()[-1]
|
||
assert isinstance(response, ModelResponse)
|
||
assert response.model_name == 'fallback'
|
||
assert [(attempt.model_name, attempt.outcome) for attempt in response.failed_attempts or []] == [
|
||
('primary', 'error')
|
||
]
|
||
assert _fallback_batch_calls == [
|
||
('primary', 'batch_create', True),
|
||
('primary', 'batch_status', True),
|
||
('primary', 'batch_status', True),
|
||
('fallback', 'batch_create', True),
|
||
('fallback', 'batch_status', True),
|
||
('fallback', 'batch_status', True),
|
||
]
|
||
# Per model: one activity submits the request, then one per check, with a durable timer before each check. The
|
||
# failed check is followed by the cancellation of the primary's suspended response, as any failed continuation is.
|
||
assert [
|
||
e.activity_task_scheduled_event_attributes.activity_type.name.rsplit('__', 1)[-1]
|
||
for e in history.events
|
||
if e.HasField('activity_task_scheduled_event_attributes')
|
||
] == snapshot(
|
||
[
|
||
'model_request',
|
||
'model_request',
|
||
'model_request',
|
||
'model_cancel_suspended_response',
|
||
'model_request',
|
||
'model_request',
|
||
'model_request',
|
||
]
|
||
)
|
||
assert _timer_count(history) == 4
|
||
|
||
|
||
# --- Streaming continuation chains inside the activity ---
|
||
|
||
_continuation_stream_model = ScriptedContinuationModel()
|
||
|
||
_continuation_stream_events: list[AgentStreamEvent] = []
|
||
|
||
|
||
async def _continuation_event_stream_handler(
|
||
ctx: RunContext[object],
|
||
stream: AsyncIterable[AgentStreamEvent],
|
||
) -> None:
|
||
async for event in stream:
|
||
_continuation_stream_events.append(event)
|
||
|
||
|
||
_continuation_stream_agent = Agent(
|
||
_continuation_stream_model,
|
||
name='durability_continuation_stream_agent',
|
||
capabilities=[
|
||
ProcessEventStream(_continuation_event_stream_handler),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityContinuationStreamWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> tuple[AgentRunResult[str], list[tuple[str, int]]]:
|
||
result = await _continuation_stream_agent.run(prompt)
|
||
return result, _text_part_indices(_continuation_stream_events)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityContinuationStreamResumeWorkflow:
|
||
@workflow.run
|
||
async def run(self, messages: list[ModelMessage]) -> tuple[AgentRunResult[str], list[tuple[str, int]]]:
|
||
result = await _continuation_stream_agent.run(message_history=messages)
|
||
return result, _text_part_indices(_continuation_stream_events)
|
||
|
||
|
||
def _text_part_indices(events: list[AgentStreamEvent]) -> list[tuple[str, int]]:
|
||
return [
|
||
(type(event).__name__, event.index) for event in events if isinstance(event, (PartStartEvent, PartDeltaEvent))
|
||
]
|
||
|
||
|
||
async def test_durability_streaming_continuation_chain_in_workflow(client: Client):
|
||
"""A streamed suspended → complete chain is stitched across per-segment activities.
|
||
|
||
`ProcessEventStream` receives each segment's final response in workflow code, one event per
|
||
part, and the final response merges both segments' text with usage summed once.
|
||
"""
|
||
_continuation_stream_model.reset(
|
||
segments=[
|
||
StreamSegment(
|
||
texts=['The answer '],
|
||
state='suspended',
|
||
provider_response_id='cont1',
|
||
input_tokens=5,
|
||
output_tokens=2,
|
||
),
|
||
StreamSegment(
|
||
texts=['is 42.'], state='complete', provider_response_id='cont2', input_tokens=3, output_tokens=4
|
||
),
|
||
]
|
||
)
|
||
_continuation_stream_events.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityContinuationStreamWorkflow],
|
||
plugins=[AgentPlugin(_continuation_stream_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityContinuationStreamWorkflow.run,
|
||
args=['go'],
|
||
id='DurabilityContinuationStreamWorkflow_chain',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result, indices = await wf.result()
|
||
history = await wf.fetch_history()
|
||
|
||
assert result.output == 'The answer is 42.'
|
||
usage = result.usage
|
||
assert usage.requests == 1
|
||
assert usage.input_tokens == 8
|
||
assert usage.output_tokens == 6
|
||
assert indices == snapshot([('PartStartEvent', 0), ('PartStartEvent', 1)])
|
||
assert _continuation_stream_model.request_stream_calls == 2
|
||
assert _scheduled_activity_count(history) == 2
|
||
|
||
|
||
async def test_durability_streaming_continuation_resume_from_history(client: Client):
|
||
"""A streamed resume passes the suspended history tail to the first activity.
|
||
|
||
The suspended tail seeds the workflow-side composite and the final output merges both texts.
|
||
"""
|
||
_continuation_stream_model.reset(
|
||
segments=[
|
||
StreamSegment(
|
||
texts=['is 42.'], state='complete', provider_response_id='cont2', input_tokens=3, output_tokens=4
|
||
),
|
||
]
|
||
)
|
||
_continuation_stream_events.clear()
|
||
history_messages: list[ModelMessage] = [
|
||
ModelRequest(parts=[UserPromptPart(content='go')]),
|
||
scripted_response(
|
||
texts=['The answer '], state='suspended', provider_response_id='cont1', input_tokens=5, output_tokens=2
|
||
),
|
||
]
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityContinuationStreamResumeWorkflow],
|
||
plugins=[AgentPlugin(_continuation_stream_agent)],
|
||
):
|
||
wf = await client.start_workflow(
|
||
DurabilityContinuationStreamResumeWorkflow.run,
|
||
args=[history_messages],
|
||
id='DurabilityContinuationStreamWorkflow_resume',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
result, indices = await wf.result()
|
||
|
||
assert result.output == 'The answer is 42.'
|
||
response = result.all_messages()[-1]
|
||
assert isinstance(response, ModelResponse)
|
||
assert response.state == 'complete'
|
||
assert [part.content for part in response.parts if isinstance(part, TextPart)] == ['The answer ', 'is 42.']
|
||
assert indices == snapshot([('PartStartEvent', 1)])
|
||
assert _continuation_stream_model.request_stream_calls == 1
|
||
|
||
|
||
# --- A static toolset's `prepare` function runs only in workflow code ---
|
||
#
|
||
# The tool-call activity rebuilds the tool from the `ToolDefinition` the workflow prepared (like
|
||
# the MCP path does) instead of listing the toolset's tools again, so `prepare` never runs a
|
||
# second time against the activity's limited `RunContext`, and the definition the model saw is
|
||
# the one the activity enforces. These tests use `UnsandboxedWorkflowRunner` so workflow-side
|
||
# and activity-side calls land on the same module state.
|
||
|
||
_prepare_run_steps: list[int] = []
|
||
|
||
_prepared_descriptions: list[str | None] = []
|
||
|
||
|
||
async def _prepare_sleepy_tool(ctx: RunContext[object], tool_def: ToolDefinition) -> ToolDefinition:
|
||
"""Set a timeout on the first call only, so a second call would change the tool's behavior."""
|
||
_prepare_run_steps.append(ctx.run_step)
|
||
return replace(
|
||
tool_def,
|
||
description=f'prepared {len(_prepare_run_steps)}',
|
||
timeout=0.01 if len(_prepare_run_steps) == 1 else None,
|
||
)
|
||
|
||
|
||
async def _sleepy_tool() -> str:
|
||
await asyncio.sleep(0.5)
|
||
return 'slept' # pragma: no cover
|
||
|
||
|
||
def _prepare_tool_model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
_prepared_descriptions.append(info.function_tools[0].description)
|
||
if len(messages) == 1:
|
||
return ModelResponse(parts=[ToolCallPart('sleepy_tool', {})])
|
||
return ModelResponse(parts=[TextPart('done')])
|
||
|
||
|
||
_prepare_agent = Agent(
|
||
FunctionModel(_prepare_tool_model),
|
||
name='durability_prepare_agent',
|
||
toolsets=[
|
||
FunctionToolset[object](
|
||
tools=[Tool(_sleepy_tool, name='sleepy_tool', prepare=_prepare_sleepy_tool)], id='prepare_ts'
|
||
)
|
||
],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityPrepareWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> list[ModelMessage]:
|
||
return (await _prepare_agent.run(prompt)).all_messages()
|
||
|
||
|
||
@pytest.mark.moves_cache_prefix(reason=TOOLS_CHANGE_MID_RUN)
|
||
async def test_durability_static_tool_prepare_runs_only_in_workflow(client: Client):
|
||
"""`prepare` runs once per model step in workflow code, and the activity honours its `tool_def`.
|
||
|
||
Only the first `prepare` call sets `timeout=0.01`, so re-preparing inside the activity would
|
||
silently drop the timeout that the tool definition the model saw carried.
|
||
"""
|
||
_prepare_run_steps.clear()
|
||
_prepared_descriptions.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityPrepareWorkflow],
|
||
plugins=[AgentPlugin(_prepare_agent)],
|
||
workflow_runner=UnsandboxedWorkflowRunner(),
|
||
):
|
||
messages = await client.execute_workflow(
|
||
DurabilityPrepareWorkflow.run,
|
||
args=['go'],
|
||
id=f'{DurabilityPrepareWorkflow.__name__}-{uuid.uuid4()}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
# One call per model step, both in workflow code; none inside the tool-call activity.
|
||
assert _prepare_run_steps == snapshot([1, 2])
|
||
assert _prepared_descriptions == snapshot(['prepared 1', 'prepared 2'])
|
||
# The `timeout=0.01` from the workflow-side call is what the activity enforced.
|
||
retry_prompts = [
|
||
part.content
|
||
for message in messages
|
||
for part in message.parts
|
||
if isinstance(part, ToolReturnPart) and part.outcome == 'retried'
|
||
]
|
||
assert retry_prompts == snapshot(['Timed out after 0.01 seconds.'])
|
||
|
||
|
||
async def victim_tool() -> str:
|
||
return 'victim' # pragma: no cover
|
||
|
||
|
||
_removal_toolset = FunctionToolset[object]([victim_tool], id='removal_ts')
|
||
|
||
|
||
def _removal_model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
# Runs inside the model activity, after the workflow listed this step's tools: dropping the
|
||
# tool now leaves the workflow calling a tool the activity can no longer resolve.
|
||
_removal_toolset.tools.pop('victim_tool')
|
||
return ModelResponse(parts=[ToolCallPart('victim_tool', {})])
|
||
|
||
|
||
_removal_agent = Agent(
|
||
FunctionModel(_removal_model),
|
||
name='durability_removal_agent',
|
||
toolsets=[_removal_toolset],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityRemovedToolWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await _removal_agent.run(prompt)).output
|
||
|
||
|
||
async def test_durability_removed_tool_still_raises_user_error(client: Client):
|
||
"""A tool that's really gone from the toolset still fails with the tool-removal error."""
|
||
try:
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityRemovedToolWorkflow],
|
||
plugins=[AgentPlugin(_removal_agent)],
|
||
workflow_runner=UnsandboxedWorkflowRunner(),
|
||
):
|
||
with pytest.raises(WorkflowFailureError) as exc_info:
|
||
await client.execute_workflow(
|
||
DurabilityRemovedToolWorkflow.run,
|
||
args=['go'],
|
||
id=f'{DurabilityRemovedToolWorkflow.__name__}-{uuid.uuid4()}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
finally:
|
||
_removal_toolset.add_function(victim_tool)
|
||
|
||
cause = _workflow_failure_cause(exc_info.value)
|
||
assert cause.type == UserError.__name__
|
||
assert cause.message == snapshot(
|
||
"Tool 'victim_tool' not found in toolset 'removal_ts'. "
|
||
'Removing or renaming tools during an agent run is not supported with Temporal.'
|
||
)
|
||
|
||
|
||
async def test_durability_call_tool_activity_without_tool_def_re_prepares_tool():
|
||
"""A tool-call activity scheduled without a `tool_def` still runs, by preparing the tool itself.
|
||
|
||
Unit test: the workflow side always sends the prepared `tool_def` now, so only an activity
|
||
scheduled by a worker predating that field can arrive without one — no workflow run can
|
||
produce this payload, but a rolling upgrade can.
|
||
"""
|
||
prepare_run_steps: list[int] = []
|
||
|
||
async def prepare_legacy_tool(ctx: RunContext[None], tool_def: ToolDefinition) -> ToolDefinition:
|
||
prepare_run_steps.append(ctx.run_step)
|
||
return tool_def
|
||
|
||
async def legacy_tool() -> str:
|
||
return 'legacy'
|
||
|
||
toolset = FunctionToolset[None](
|
||
tools=[Tool(legacy_tool, name='legacy_tool', prepare=prepare_legacy_tool)], id='legacy_ts'
|
||
)
|
||
durable_toolset = temporalize_function_toolset(
|
||
toolset,
|
||
activity_name_prefix='test__legacy_call_tool_params',
|
||
activity_config=BASE_ACTIVITY_CONFIG,
|
||
tool_activity_config={},
|
||
deps_type=type(None),
|
||
)
|
||
(call_tool_activity,) = durable_toolset.durable_registrations
|
||
|
||
ctx = RunContext(deps=None, model=TestModel(), usage=RunUsage(), run_id='run-123', run_step=3)
|
||
result = await call_tool_activity(
|
||
CallToolParams(
|
||
name='legacy_tool',
|
||
tool_args={},
|
||
serialized_run_context=TemporalRunContext.serialize_run_context(ctx),
|
||
tool_def=None,
|
||
),
|
||
None,
|
||
)
|
||
|
||
assert unwrap_tool_call_result(result) == 'legacy'
|
||
assert prepare_run_steps == [3]
|
||
|
||
with pytest.raises(
|
||
UserError,
|
||
match=re.escape(
|
||
"Tool 'missing' not found in toolset 'legacy_ts'. Removing or renaming tools during an agent run"
|
||
),
|
||
):
|
||
await call_tool_activity(
|
||
CallToolParams(
|
||
name='missing',
|
||
tool_args={},
|
||
serialized_run_context=TemporalRunContext.serialize_run_context(ctx),
|
||
tool_def=None,
|
||
),
|
||
None,
|
||
)
|
||
|
||
|
||
async def test_durability_common_call_activity_accepts_legacy_params_without_tool_def():
|
||
"""The common operation activity keeps accepting payloads scheduled before `tool_def` existed."""
|
||
|
||
async def legacy_tool() -> str:
|
||
return 'legacy'
|
||
|
||
toolset = FunctionToolset[None]([legacy_tool], id='common_legacy_ts')
|
||
agent = Agent(
|
||
TestModel(),
|
||
name='common_legacy_params',
|
||
deps_type=type(None),
|
||
toolsets=[toolset],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
durability = TemporalDurability.from_agent(agent)
|
||
assert durability is not None
|
||
registrations_by_name = {
|
||
ActivityDefinition.must_from_callable(registration).name: registration # pyright: ignore[reportUnknownMemberType]
|
||
for registration in durability.temporal_activities
|
||
}
|
||
call_tool_activity = registrations_by_name['agent__common_legacy_params__toolset__common_legacy_ts__call_tool']
|
||
ctx = RunContext(deps=None, model=TestModel(), usage=RunUsage(), run_id='run-123', run_step=3)
|
||
|
||
result = await call_tool_activity(
|
||
CallToolParams(
|
||
name='legacy_tool',
|
||
tool_args={},
|
||
serialized_run_context=TemporalRunContext.serialize_run_context(ctx),
|
||
tool_def=None,
|
||
),
|
||
None,
|
||
)
|
||
assert unwrap_tool_call_result(result) == 'legacy'
|
||
|
||
with pytest.raises(
|
||
UserError,
|
||
match=re.escape(
|
||
"Tool 'missing' not found in toolset 'common_legacy_ts'. Removing or renaming tools during an agent run"
|
||
),
|
||
):
|
||
await call_tool_activity(
|
||
CallToolParams(
|
||
name='missing',
|
||
tool_args={},
|
||
serialized_run_context=TemporalRunContext.serialize_run_context(ctx),
|
||
tool_def=None,
|
||
),
|
||
None,
|
||
)
|
||
|
||
|
||
_renamed_tool_names: list[list[str]] = []
|
||
|
||
|
||
async def registered_tool() -> str:
|
||
return 'the registered function ran'
|
||
|
||
|
||
async def _prepare_renamed_tool(ctx: RunContext[object], tool_def: ToolDefinition) -> ToolDefinition:
|
||
"""Expose the tool to the model under a name the toolset doesn't hold it under."""
|
||
return replace(tool_def, name='exposed_tool')
|
||
|
||
|
||
def _renaming_model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
_renamed_tool_names.append([tool_def.name for tool_def in info.function_tools])
|
||
for message in messages:
|
||
for part in message.parts:
|
||
if isinstance(part, ToolReturnPart):
|
||
return ModelResponse(parts=[TextPart(str(part.content))])
|
||
return ModelResponse(parts=[ToolCallPart('exposed_tool', {})])
|
||
|
||
|
||
_renaming_agent = Agent(
|
||
FunctionModel(_renaming_model),
|
||
name='durability_renaming_agent',
|
||
toolsets=[
|
||
FunctionToolset[object](
|
||
tools=[Tool(registered_tool, name='registered_tool', prepare=_prepare_renamed_tool)], id='renaming_ts'
|
||
)
|
||
],
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityRenamedToolWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str) -> str:
|
||
return (await _renaming_agent.run(prompt)).output
|
||
|
||
|
||
async def test_durability_prepare_renamed_tool_runs_in_activity(client: Client):
|
||
"""A `prepare` function that renames its tool still resolves to that tool inside the activity.
|
||
|
||
The activity looks the tool up by the name the toolset holds it under, which the workflow sends
|
||
alongside the prepared `tool_def`; looking it up by the model-visible name would raise the
|
||
tool-removal error for a tool that is still right there. Runs sandboxed, so the workflow's
|
||
`prepare` result reaches the activity over the wire rather than through shared module state.
|
||
"""
|
||
_renamed_tool_names.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityRenamedToolWorkflow],
|
||
plugins=[AgentPlugin(_renaming_agent)],
|
||
):
|
||
output = await client.execute_workflow(
|
||
DurabilityRenamedToolWorkflow.run,
|
||
args=['go'],
|
||
id=f'{DurabilityRenamedToolWorkflow.__name__}-{uuid.uuid4()}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
assert output == snapshot('the registered function ran')
|
||
# The model only ever saw the renamed tool, in both steps.
|
||
assert _renamed_tool_names == snapshot([['exposed_tool'], ['exposed_tool']])
|
||
|
||
|
||
# --- Retry feedback for output that answered no tool call ---
|
||
|
||
|
||
@dataclass
|
||
class RetryFeedbackAnswer:
|
||
count: int
|
||
|
||
|
||
_retry_feedback_shown: list[list[SystemPromptPart | UserPromptPart]] = []
|
||
"""The retry feedback the model was shown, one entry per model request."""
|
||
|
||
_RETRY_FEEDBACK_TAGS = ('<system>', '<pyai:validation_errors>')
|
||
"""The two tags a translated `RetryFeedbackPart` can arrive under; a `SystemPromptPart` needs none."""
|
||
|
||
|
||
def _retry_feedback_model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
# A raw `RetryFeedbackPart` raises rather than rendering when it reaches a model, so whatever
|
||
# lands here is what `prepare_messages` made of it under the profile of the model being used.
|
||
shown = [
|
||
part
|
||
for message in messages
|
||
if isinstance(message, ModelRequest)
|
||
for part in message.parts
|
||
if isinstance(part, SystemPromptPart)
|
||
or (
|
||
isinstance(part, UserPromptPart)
|
||
and isinstance(part.content, str)
|
||
and any(tag in part.content for tag in _RETRY_FEEDBACK_TAGS)
|
||
)
|
||
]
|
||
_retry_feedback_shown.append(shown)
|
||
return ModelResponse(parts=[TextPart('{"count": 3}' if shown else '{"count": "lots"}')])
|
||
|
||
|
||
_retry_feedback_inline_model = FunctionModel(
|
||
_retry_feedback_model,
|
||
model_name='retry-feedback-inline',
|
||
profile=ModelProfile(supports_inline_system_prompts=True),
|
||
)
|
||
|
||
|
||
def _resolve_retry_feedback_alias(ctx: ModelResolutionContext[None], model_id: str) -> FunctionModel | None:
|
||
"""Resolve the alias for the model that takes a mid-conversation system message.
|
||
|
||
`infer_model` can't build the alias, so the raw string is what crosses the activity boundary and
|
||
the worker-side chain rebuilds the model there.
|
||
"""
|
||
return _retry_feedback_inline_model if model_id == 'retry-feedback-inline' else None
|
||
|
||
|
||
_retry_feedback_agent = Agent(
|
||
FunctionModel(_retry_feedback_model),
|
||
name='durability_retry_feedback_agent',
|
||
deps_type=type(None),
|
||
output_type=PromptedOutput(RetryFeedbackAnswer),
|
||
capabilities=[
|
||
ResolveModelId(_resolve_retry_feedback_alias),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
_workspace_probe_backends: list[FakeWorkspace] = []
|
||
|
||
|
||
@dataclass
|
||
class WorkspaceProbeDeps:
|
||
prefix: str
|
||
|
||
|
||
class WorkspaceProbePolicy(WrapperWorkspace):
|
||
def __init__(self, wrapped: Workspace, deps: WorkspaceProbeDeps):
|
||
super().__init__(wrapped)
|
||
self.deps = deps
|
||
|
||
async def run(
|
||
self,
|
||
command: str | Sequence[str],
|
||
*,
|
||
shell: bool = False,
|
||
env: Mapping[str, str] | None = None,
|
||
timeout: float | None = None,
|
||
cwd: str | None = None,
|
||
) -> CommandResult:
|
||
assert activity.in_activity()
|
||
result = await self.wrapped.run(command, shell=shell, env=env, timeout=timeout, cwd=cwd)
|
||
assert self.ref is not None
|
||
return replace(result, stdout=f'policy:{self.deps.prefix}:{self.ref.id}:{result.stdout}')
|
||
|
||
|
||
class WorkspaceProbeCapability(AbstractCapability[WorkspaceProbeDeps]):
|
||
def get_workspace(self, ctx: RunContext[WorkspaceProbeDeps], *, ref: WorkspaceRef | None) -> WorkspaceBackend:
|
||
assert ref is not None and ref.provider == 'probe'
|
||
return WorkspaceProbePolicy(Workspace(FakeWorkspace(ref.id, ref=ref)), ctx.deps)
|
||
|
||
|
||
class WorkspaceProbeContext(TemporalRunContext[WorkspaceProbeDeps]):
|
||
@classmethod
|
||
def deserialize_run_context(cls, ctx: dict[str, Any], deps: WorkspaceProbeDeps) -> WorkspaceProbeContext:
|
||
data = dict(ctx)
|
||
raw_ref: Any = data.pop('workspace_ref')
|
||
assert isinstance(raw_ref, dict), f'expected JSON object, got {type(raw_ref)}'
|
||
ref = TypeAdapter(WorkspaceRef).validate_python(raw_ref)
|
||
backend = FakeWorkspace(ref.id, ref=ref)
|
||
_workspace_probe_backends.append(backend)
|
||
workspace = WorkspaceProbePolicy(Workspace(backend), deps)
|
||
return cls(**{**data, 'workspace': workspace}, deps=deps)
|
||
|
||
|
||
_workspace_probe_agent = Agent(
|
||
TestModel(call_tools=['probe_workspace']),
|
||
name='workspace_probe_agent',
|
||
deps_type=WorkspaceProbeDeps,
|
||
capabilities=[
|
||
Instrumentation(),
|
||
WorkspaceProbeCapability(),
|
||
TemporalDurability(run_context_type=WorkspaceProbeContext, activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@dataclass
|
||
class RetryFeedbackResult:
|
||
count: int
|
||
messages: list[ModelMessage]
|
||
|
||
|
||
@workflow.defn
|
||
class DurabilityRetryFeedbackWorkflow:
|
||
@workflow.run
|
||
async def run(
|
||
self, prompt: str, model_id: str | None, message_history: list[ModelMessage] | None
|
||
) -> RetryFeedbackResult:
|
||
result = await _retry_feedback_agent.run(prompt, model=model_id, message_history=message_history)
|
||
return RetryFeedbackResult(count=result.output.count, messages=result.all_messages())
|
||
|
||
|
||
async def test_durability_output_retry_feedback_survives_the_activity_and_a_resume(client: Client):
|
||
"""Output that failed validation retries as a durable history fact, in the harness's own voice.
|
||
|
||
The retry answers no tool call, so it is a `RetryFeedbackPart` and not the retried
|
||
`ToolReturnPart` the tool path carries. It has to cross the model activity's payload boundary, come back out through
|
||
the workflow's own result, and go back in as a second execution's argument — the shape a suspend
|
||
and resume leaves behind.
|
||
|
||
The resuming model is reached by an alias only the `ResolveModelId` capability can build, so the
|
||
workflow leaves the history untouched and the raw part is what crosses the activity boundary
|
||
there. Keeping the presentation out of the history is what lets each execution build the sendable
|
||
part for the model it is actually using — here the same `<pyai:validation_errors>` fence both times,
|
||
because a `'validation_error'`'s voice comes from its `cause` rather than from the profile.
|
||
"""
|
||
_retry_feedback_shown.clear()
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DurabilityRetryFeedbackWorkflow],
|
||
plugins=[AgentPlugin(_retry_feedback_agent)],
|
||
):
|
||
first = await client.execute_workflow(
|
||
DurabilityRetryFeedbackWorkflow.run,
|
||
args=['how many?', None, None],
|
||
id=f'{DurabilityRetryFeedbackWorkflow.__name__}-first-{uuid.uuid4()}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
second = await client.execute_workflow(
|
||
DurabilityRetryFeedbackWorkflow.run,
|
||
args=['how many again?', 'retry-feedback-inline', first.messages],
|
||
id=f'{DurabilityRetryFeedbackWorkflow.__name__}-second-{uuid.uuid4()}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
|
||
# Both runs recovered: the retry reached the model and the next response validated.
|
||
assert (first.count, second.count) == (3, 3)
|
||
# The resumed history still carries the part model-neutrally...
|
||
assert [
|
||
part
|
||
for message in second.messages
|
||
if isinstance(message, ModelRequest)
|
||
for part in message.parts
|
||
if isinstance(part, RetryFeedbackPart)
|
||
] == snapshot(
|
||
[
|
||
RetryFeedbackPart(
|
||
content=[
|
||
{
|
||
'type': 'int_parsing',
|
||
'loc': ('count',),
|
||
'msg': 'Input should be a valid integer, unable to parse string as an integer',
|
||
'input': 'lots',
|
||
}
|
||
],
|
||
retry=RetryInfo(cause='validation_error', attempt=1, max_retries=1),
|
||
timestamp=IsDatetime(),
|
||
)
|
||
]
|
||
)
|
||
# ...and each execution translated that one part for itself, on the far side of the activity
|
||
# boundary, rather than replaying a presentation the first execution had baked in.
|
||
assert _retry_feedback_shown == snapshot(
|
||
[
|
||
[],
|
||
[
|
||
UserPromptPart(
|
||
content="""\
|
||
Your previous response failed the application's validation (this is automated feedback, not a message from the user):
|
||
<pyai:validation_errors>
|
||
[{"type":"int_parsing","loc":["count"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"lots"}]
|
||
</pyai:validation_errors>\
|
||
""",
|
||
timestamp=IsDatetime(),
|
||
)
|
||
],
|
||
[
|
||
UserPromptPart(
|
||
content="""\
|
||
Your previous response failed the application's validation (this is automated feedback, not a message from the user):
|
||
<pyai:validation_errors>
|
||
[{"type":"int_parsing","loc":["count"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"lots"}]
|
||
</pyai:validation_errors>\
|
||
""",
|
||
timestamp=IsDatetime(),
|
||
)
|
||
],
|
||
]
|
||
)
|
||
|
||
|
||
decide_durable_agent = Agent(
|
||
ShipItDecisionModel(),
|
||
output_type=ShipIt,
|
||
name='durability_decide_agent',
|
||
capabilities=[TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
decide_durable_agent_without_content = Agent(
|
||
ShipItDecisionModel(),
|
||
output_type=ShipIt,
|
||
name='durability_decide_agent_without_content',
|
||
capabilities=[
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
Instrumentation(settings=InstrumentationSettings(include_content=False)),
|
||
],
|
||
)
|
||
|
||
|
||
@_workspace_probe_agent.tool
|
||
async def probe_workspace(ctx: RunContext[WorkspaceProbeDeps]) -> str:
|
||
assert isinstance(ctx, WorkspaceProbeContext)
|
||
first = await ctx.workspace.run(['first'])
|
||
second = await ctx.workspace.run(['second'])
|
||
return f'{first.stdout}|{second.stdout}'
|
||
|
||
|
||
@workflow.defn
|
||
class WorkspaceProbeWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
result = await _workspace_probe_agent.run(
|
||
'Use the probe_workspace tool.',
|
||
deps=WorkspaceProbeDeps(prefix='worker'),
|
||
workspace=WorkspaceRef(provider='probe', id='existing-123'),
|
||
)
|
||
assert result.workspace.ref == WorkspaceRef(provider='probe', id='existing-123')
|
||
return result.output
|
||
|
||
|
||
async def test_temporal_workspace_restores_ref_and_replays_without_side_effects(client: Client):
|
||
"""A real sandboxed worker restores a typed workspace ref in an activity and replay skips it."""
|
||
_workspace_probe_backends.clear()
|
||
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[WorkspaceProbeWorkflow],
|
||
plugins=[AgentPlugin(_workspace_probe_agent)],
|
||
):
|
||
handle = await client.start_workflow(
|
||
WorkspaceProbeWorkflow.run,
|
||
id=f'{WorkspaceProbeWorkflow.__name__}-{uuid.uuid4()}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await handle.result()
|
||
history = await handle.fetch_history()
|
||
|
||
before_replay = [
|
||
(backend.attach_calls, backend.create_calls, list(backend.commands)) for backend in _workspace_probe_backends
|
||
]
|
||
backend_count = len(_workspace_probe_backends)
|
||
replay = await Replayer(workflows=[WorkspaceProbeWorkflow], plugins=[PydanticAIPlugin()]).replay_workflow(history)
|
||
after_replay = [
|
||
(backend.attach_calls, backend.create_calls, list(backend.commands)) for backend in _workspace_probe_backends
|
||
]
|
||
|
||
assert replay.replay_failure is None
|
||
expected = 'policy:worker:existing-123:connected|policy:worker:existing-123:connected'
|
||
assert TypeAdapter(dict[str, str]).validate_json(output) == {'probe_workspace': expected}
|
||
# The `ensure` activity attaches once at run start, the tool activity once more; nothing creates.
|
||
assert sum(backend.attach_calls for backend in _workspace_probe_backends) == 2
|
||
assert sum(backend.create_calls for backend in _workspace_probe_backends) == 0
|
||
assert len(_workspace_probe_backends) == backend_count
|
||
assert [command for backend in _workspace_probe_backends for command in backend.commands] == [['first'], ['second']]
|
||
assert before_replay == after_replay
|
||
|
||
|
||
@workflow.defn
|
||
class DecideDurableAgentWorkflow:
|
||
@workflow.run
|
||
async def run(self, prompt: str, mode: str) -> ShipIt:
|
||
if mode == 'per_run_without_content':
|
||
# The agent itself records content; this one run asks not to.
|
||
result = await decide_durable_agent.run(
|
||
prompt, capabilities=[Instrumentation(settings=InstrumentationSettings(include_content=False))]
|
||
)
|
||
else:
|
||
agent = decide_durable_agent if mode == 'with_content' else decide_durable_agent_without_content
|
||
result = await agent.run(prompt)
|
||
return result.output
|
||
|
||
|
||
@pytest.mark.parametrize('mode', ['with_content', 'agent_without_content', 'per_run_without_content'])
|
||
async def test_durability_decide_span_in_activity(
|
||
allow_model_requests: None, client_with_logfire: Client, capfire: CaptureLogfire, mode: str
|
||
):
|
||
"""A decision model's `decide` span lands inside the model activity, under the workflow's `chat` span.
|
||
|
||
The context variable the `chat` span sets its policy in does not cross into the activity, so the unit rebuilds
|
||
it from the agent's own instrumentation: the one `Agent.instrument_all()` set up (by `LogfirePlugin`), or an
|
||
`Instrumentation` capability on the agent, which the run lets win and so does the activity. An `Instrumentation`
|
||
passed to one run is out of the activity's sight, so its content policy is carried in with the run context.
|
||
"""
|
||
async with Worker(
|
||
client_with_logfire,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[DecideDurableAgentWorkflow],
|
||
plugins=[AgentPlugin(decide_durable_agent), AgentPlugin(decide_durable_agent_without_content)],
|
||
):
|
||
output = await client_with_logfire.execute_workflow(
|
||
DecideDurableAgentWorkflow.run,
|
||
args=['The migration is reviewed and the tests pass.', mode],
|
||
id=f'{DecideDurableAgentWorkflow.__name__}_{mode}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
assert output == ShipIt(ship=True)
|
||
|
||
lineage, attributes = decide_span_lineage(capfire.exporter.exported_spans_as_dict())
|
||
include_content = mode == 'with_content'
|
||
agent_name = (
|
||
'durability_decide_agent_without_content' if mode == 'agent_without_content' else 'durability_decide_agent'
|
||
)
|
||
assert lineage[:4] == [
|
||
f'RunActivity:agent__{agent_name}__model_request',
|
||
f'StartActivity:agent__{agent_name}__model_request',
|
||
'chat ship-it',
|
||
f'invoke_agent {agent_name}',
|
||
]
|
||
assert ('pydantic_ai.decision.state' in attributes) is include_content
|
||
# Without content an answer keeps its numbers, which a yes/no's answer is all of.
|
||
assert attributes['pydantic_ai.decision.answers'] == '{"ship":{"type":"noul","noul":0.9}}'
|
||
assert ('instructions' in attributes['pydantic_ai.decision.questions']) is include_content
|
||
|
||
|
||
# --- Mid-run tool population changes (https://github.com/pydantic/pydantic-ai/issues/7251) ---
|
||
|
||
|
||
def _population_change_model_fn(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
||
"""Call `unlock`, then `later` once it is advertised, then finish."""
|
||
returned = {part.tool_name for message in messages for part in message.parts if isinstance(part, ToolReturnPart)}
|
||
if 'unlock' not in returned:
|
||
return ModelResponse(parts=[ToolCallPart('unlock', {}, tool_call_id='c1')])
|
||
if 'later' not in returned and any(tool.name == 'later' for tool in info.function_tools):
|
||
return ModelResponse(parts=[ToolCallPart('later', {}, tool_call_id='c2')])
|
||
return ModelResponse(parts=[TextPart('done')])
|
||
|
||
|
||
async def _admit_later_from_step_two(ctx: RunContext[Any], tool_defs: list[ToolDefinition]) -> list[ToolDefinition]:
|
||
# Workflow-side and derived from the run step, so replay resolves the same population.
|
||
return [tool_def for tool_def in tool_defs if tool_def.name != 'later' or ctx.run_step > 1]
|
||
|
||
|
||
def _unlock() -> str:
|
||
return 'unlocked'
|
||
|
||
|
||
def _later() -> str:
|
||
return 'later ran'
|
||
|
||
|
||
population_change_agent = Agent(
|
||
FunctionModel(_population_change_model_fn),
|
||
name='durability_population_change',
|
||
toolsets=[
|
||
FunctionToolset(tools=[Tool(_unlock, name='unlock'), Tool(_later, name='later')], id='population_change')
|
||
],
|
||
capabilities=[
|
||
PrepareTools(_admit_later_from_step_two),
|
||
TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG),
|
||
],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class PopulationChangeWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> list[list[str]]:
|
||
result = await population_change_agent.run('go')
|
||
return [
|
||
part.tools_added
|
||
for message in result.all_messages()
|
||
if isinstance(message, ModelRequest)
|
||
for part in message.parts
|
||
if isinstance(part, ToolAvailabilityDeltaPart)
|
||
]
|
||
|
||
|
||
async def test_population_change_delta_is_recorded_once_and_replays(client: Client):
|
||
"""A mid-run newcomer is recorded once in the workflow, and replaying the workflow history reproduces it exactly.
|
||
|
||
The diff runs in workflow code, so a replay re-derives the same baseline from the same steps and
|
||
writes the same delta: any divergence would surface as a non-determinism `replay_failure`.
|
||
"""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[PopulationChangeWorkflow],
|
||
plugins=[AgentPlugin(population_change_agent)],
|
||
):
|
||
handle = await client.start_workflow(
|
||
PopulationChangeWorkflow.run,
|
||
id=f'{PopulationChangeWorkflow.__name__}-{uuid.uuid4()}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
deltas = await handle.result()
|
||
history = await handle.fetch_history()
|
||
|
||
assert deltas == [['later']]
|
||
replay = await Replayer(workflows=[PopulationChangeWorkflow], plugins=[PydanticAIPlugin()]).replay_workflow(history)
|
||
assert replay.replay_failure is None
|
||
|
||
|
||
def _placement_model_fn(messages: list[ModelMessage], _: AgentInfo) -> ModelResponse:
|
||
returns = [part for message in messages for part in message.parts if isinstance(part, ToolReturnPart)]
|
||
if returns:
|
||
return ModelResponse(parts=[TextPart(' '.join(sorted(str(part.content) for part in returns)))])
|
||
return ModelResponse(
|
||
parts=[
|
||
ToolCallPart('in_workflow', {}, tool_call_id='call-workflow'),
|
||
ToolCallPart('in_activity', {}, tool_call_id='call-activity'),
|
||
]
|
||
)
|
||
|
||
|
||
async def _where_it_ran() -> str:
|
||
return 'workflow' if workflow.in_workflow() else 'activity'
|
||
|
||
|
||
async def _keep_in_workflow(ctx: RunContext[None], tool_defs: list[ToolDefinition]) -> list[ToolDefinition]:
|
||
# Deterministic, as a `prepare` setting `durable` must be: replay sees the same placement.
|
||
return [replace(tool_def, durable=False) if tool_def.name == 'in_workflow' else tool_def for tool_def in tool_defs]
|
||
|
||
|
||
placement_agent = Agent(
|
||
FunctionModel(_placement_model_fn),
|
||
name='durability_prepared_placement',
|
||
deps_type=type(None),
|
||
toolsets=[
|
||
FunctionToolset(
|
||
tools=[Tool(_where_it_ran, name='in_workflow'), Tool(_where_it_ran, name='in_activity')], id='placement'
|
||
)
|
||
],
|
||
capabilities=[PrepareTools(_keep_in_workflow), TemporalDurability(activity_config=BASE_ACTIVITY_CONFIG)],
|
||
)
|
||
|
||
|
||
@workflow.defn
|
||
class PreparedPlacementWorkflow:
|
||
@workflow.run
|
||
async def run(self) -> str:
|
||
return (await placement_agent.run('go')).output
|
||
|
||
|
||
async def test_durable_false_set_by_prepare_tools_runs_the_tool_in_the_workflow(client: Client):
|
||
"""`durable=False` set by `PrepareTools` keeps that tool out of its activity, and the run replays cleanly."""
|
||
async with Worker(
|
||
client,
|
||
task_queue=TASK_QUEUE,
|
||
workflows=[PreparedPlacementWorkflow],
|
||
plugins=[AgentPlugin(placement_agent)],
|
||
):
|
||
handle = await client.start_workflow(
|
||
PreparedPlacementWorkflow.run,
|
||
id=f'{PreparedPlacementWorkflow.__name__}-{uuid.uuid4()}',
|
||
task_queue=TASK_QUEUE,
|
||
)
|
||
output = await handle.result()
|
||
history = await handle.fetch_history()
|
||
|
||
# Each tool reports where it ran: only `in_activity` got a `call_tool` activity.
|
||
assert output == 'activity workflow'
|
||
assert [
|
||
e.activity_task_scheduled_event_attributes.activity_type.name.rsplit('__', 1)[-1]
|
||
for e in history.events
|
||
if e.HasField('activity_task_scheduled_event_attributes')
|
||
and e.activity_task_scheduled_event_attributes.activity_type.name.endswith('__call_tool')
|
||
] == ['call_tool']
|
||
replay = await Replayer(workflows=[PreparedPlacementWorkflow], plugins=[PydanticAIPlugin()]).replay_workflow(
|
||
history
|
||
)
|
||
assert replay.replay_failure is None
|
||
|
||
|
||
class _RealtimeConnection(InferredConnection):
|
||
async def send_input(self, content: RealtimeInput) -> None: ... # pragma: no cover
|
||
|
||
async def codec_events(self) -> AsyncIterator[RealtimeCodecEvent]:
|
||
yield ResponseDone()
|
||
|
||
|
||
class _RealtimeModel(RealtimeModel):
|
||
@property
|
||
def model_name(self) -> str:
|
||
return 'fake-realtime'
|
||
|
||
@property
|
||
def system(self) -> str:
|
||
return 'fake'
|
||
|
||
@property
|
||
def profile(self) -> RealtimeModelProfile:
|
||
return RealtimeModelProfile(supports_session_seeding=True)
|
||
|
||
@asynccontextmanager
|
||
async def connect(
|
||
self,
|
||
*,
|
||
messages: Sequence[ModelMessage],
|
||
model_settings: RealtimeModelSettings | None,
|
||
model_request_parameters: ModelRequestParameters,
|
||
) -> AsyncGenerator[RealtimeConnection]:
|
||
yield _RealtimeConnection()
|
||
|
||
|
||
async def test_realtime_session_with_durability_outside_workflow_does_not_warn() -> None:
|
||
"""Outside a workflow the model-request hooks (including `continue_as_new`'s) pass through, so a session doesn't warn."""
|
||
agent = Agent(
|
||
TestModel(), name='realtime_durability', capabilities=[TemporalDurability(continue_as_new=lambda ctx: None)]
|
||
)
|
||
async with agent.realtime(_RealtimeModel()).session() as session:
|
||
async for _ in session:
|
||
pass
|