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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 29 additions & 20 deletions examples/demos/procurement_agent/project/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,21 +129,27 @@ async def on_task_event_send(self, params: SendEventParams) -> None:
First event: Triggers the initial agent workflow execution.
Subsequent events: Feed the wait_for_human tool's human_queue.
"""
if self._state is None:
raise ValueError("State is not initialized")

if params.event.content is None:
# Skip events this agent can't handle instead of raising: an exception here fails
# the workflow task, and Temporal replays the signal forever, wedging the task.
# Any content type can be displayed, but an event can arrive with no content.
content = params.event.content
if content is None:
workflow.logger.warning("Received event with no content")
return

# A signal can arrive before on_task_create has initialised state (e.g. with
# signal-with-start): wait for it rather than drop the user's message.
while self._state is None:
await workflow.wait_condition(lambda: self._state is not None)

# Display the user's message in the UI
await adk.messages.create(task_id=params.task.id, content=params.event.content)
await adk.messages.create(task_id=params.task.id, content=content)

# After the first event, all subsequent events are human responses to wait_for_human
if self._workflow_started:
# Extract text content and put it in the human_queue for wait_for_human tool
if isinstance(params.event.content, TextContent):
await self.human_queue.put(params.event.content.content)
if isinstance(content, TextContent):
await self.human_queue.put(content.content)

@workflow.run
@override
Expand Down Expand Up @@ -386,49 +392,52 @@ async def send_event(self, event: str) -> None:
Receives event strings from external systems with validation.
Events should be JSON strings with event_type and required fields.
Example: {"event_type":"Submittal_Approved","item":"Steel Beams"}

Invalid events are logged and dropped, never raised: an exception in a signal
handler fails the workflow task, and Temporal replays the signal forever. The
sender never sees the error either way, since signals do not return results.
"""
# Validate event is not None or empty
if not event:
logger.error("Received empty or None event")
raise ValueError("Event cannot be empty or None")
return

# Validate event is a string
if not isinstance(event, str):
logger.error(f"Event must be string, got {type(event)}")
raise ValueError(f"Event must be a string, received {type(event).__name__}")
return

# Validate event length (prevent DoS)
if len(event) > 50000: # 50KB limit
logger.error(f"Event too large: {len(event)} characters")
raise ValueError(f"Event exceeds maximum size (50KB)")
return

# Validate event is valid JSON
# Validate event is valid JSON. Catch ValueError, not just its subclass JSONDecodeError: an integer
# literal longer than Python's int digit limit raises a plain ValueError, and deeply nested input
# raises RecursionError.
try:
event_data = json.loads(event)
except json.JSONDecodeError as e:
except (ValueError, RecursionError) as e:
logger.error(f"Event is not valid JSON: {e}")
raise ValueError(f"Event must be valid JSON: {e}") from e
return

# Validate event has required structure
if not isinstance(event_data, dict):
logger.error(f"Event JSON must be an object, got {type(event_data)}")
raise ValueError("Event must be a JSON object")
return

# Validate event_type field exists
if "event_type" not in event_data:
logger.error("Event missing 'event_type' field")
raise ValueError("Event must contain 'event_type' field")
return

# Validate event_type is one of the allowed types
event_type_str = event_data["event_type"]
valid_event_types = [e.value for e in EventType]

if event_type_str not in valid_event_types:
logger.error(f"Invalid event_type: {event_type_str}. Valid types: {valid_event_types}")
raise ValueError(
f"Invalid event_type '{event_type_str}'. "
f"Must be one of: {', '.join(valid_event_types)}"
)
return

# Validate event structure based on type using Pydantic models
try:
Expand All @@ -448,7 +457,7 @@ async def send_event(self, event: str) -> None:

except Exception as e:
logger.error(f"Event validation failed for {event_type_str}: {e}")
raise ValueError(f"Invalid event structure for {event_type_str}: {e}") from e
return

logger.info(f"Validated event type: {event_type_str}")
await self.event_queue.put(event)
46 changes: 46 additions & 0 deletions examples/tutorials/10_async/10_temporal/000_hello_acp/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Pytest setup for this tutorial's tests.

``project.workflow`` reads environment variables when it is imported, so the offline tests need them set and
this tutorial's ``project`` package importable. Both are arranged here for this tutorial's tests only. Any
``project`` package already imported (another tutorial's, in a session that collects several) is cleared before
and after them, and so is the SDK's cached ``EnvironmentVariables``, so this tutorial's workflow reads its own
values.
"""

from __future__ import annotations

import os
import sys
from collections.abc import Iterator

import pytest

TUTORIAL_DIR = os.path.dirname(os.path.abspath(__file__))

# Values already set in the environment win.
ENV_DEFAULTS = {
"AGENT_NAME": "at000-hello-acp",
"ACP_URL": "http://localhost:8000",
"WORKFLOW_NAME": "at000-hello-acp",
}


def _forget_project_modules() -> None:
for name in [name for name in sys.modules if name == "project" or name.startswith("project.")]:
del sys.modules[name]


@pytest.fixture(autouse=True, scope="module")
def _tutorial_environment() -> Iterator[None]:
with pytest.MonkeyPatch.context() as patch:
for name, value in ENV_DEFAULTS.items():
if not os.environ.get(name):
patch.setenv(name, value)
patch.syspath_prepend(TUTORIAL_DIR)
# EnvironmentVariables.refresh() keeps the first values it reads for the whole process.
patch.setattr("agentex.lib.environment_variables.refreshed_environment_variables", None)
_forget_project_modules()
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
try:
yield
finally:
_forget_project_modules()
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,18 @@ def __init__(self):
@workflow.signal(name=SignalName.RECEIVE_EVENT)
@override
async def on_task_event_send(self, params: SendEventParams) -> None:
# Skip events this agent can't handle instead of raising: an exception here fails
# the workflow task, and Temporal replays the signal forever, wedging the task.
# Any content type can be echoed back, but an event can arrive with no content.
content = params.event.content
if content is None:
logger.warning("Ignoring event with no content for task %s", params.task.id)
return

logger.info(f"Received task message instruction: {params}")

# 2. Echo back the client's message to show it in the UI. This is not done by default so the agent developer has full control over what is shown to the user.
await adk.messages.create(task_id=params.task.id, content=params.event.content)
await adk.messages.create(task_id=params.task.id, content=content)

# 3. Send a simple response message.
# In future tutorials, this is where we'll add more sophisticated response logic.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
- Non-streaming event sending and polling
- Streaming event sending

It also unit-tests the workflow's signal handler offline (TestOfflineSignalHandler),
which needs no running agent, Temporal or network.

To run these tests:
1. Make sure the agent is running (via docker-compose or `agentex agents run`)
2. Set the AGENTEX_API_BASE_URL environment variable if not using default
Expand All @@ -19,6 +22,8 @@
import uuid
import asyncio
from typing import Any
from datetime import datetime, timezone
from unittest.mock import AsyncMock, patch

import pytest
import pytest_asyncio
Expand All @@ -30,8 +35,17 @@

from agentex import AsyncAgentex
from agentex.types import TaskMessage
from agentex.types.task import Task
from agentex.types.agent import Agent
from agentex.types.event import Event
from agentex.protocol.acp import SendEventParams
from agentex.types.data_content import DataContent
from agentex.types.text_content import TextContent
from agentex.types.agent_rpc_params import ParamsCreateTaskRequest
from agentex.types.reasoning_content import ReasoningContent
from agentex.types.text_content_param import TextContentParam
from agentex.types.tool_request_content import ToolRequestContent
from agentex.types.tool_response_content import ToolResponseContent

# Configuration from environment variables
AGENTEX_API_BASE_URL = os.environ.get("AGENTEX_API_BASE_URL", "http://localhost:5003")
Expand Down Expand Up @@ -185,5 +199,87 @@ async def stream_messages() -> None:
assert user_echo_found, "User message echo not found in stream"
assert agent_response_found, "Agent response not found in stream"


# ---------------------------------------------------------------------------
# Offline signal-handler tests (no running agent, Temporal or network needed)
# ---------------------------------------------------------------------------

TASK_ID = "task-offline-1"


def _send_event_params(content: Any) -> SendEventParams:
"""Real ``SendEventParams``, as the ACP delivers an ``event/send`` to the workflow signal."""
now = datetime.now(timezone.utc)
return SendEventParams(
agent=Agent(id="agent-1", acp_type="async", name=AGENT_NAME, description="", created_at=now, updated_at=now),
task=Task(id=TASK_ID),
event=Event(id="event-1", agent_id="agent-1", task_id=TASK_ID, sequence_id=1, content=content),
)


# Every content type a caller can send. This handler only echoes the content back, so
# all of them are valid input: the one thing it cannot echo is an event with no content.
ECHOED_CONTENTS = [
pytest.param(TextContent(author="user", content="Hello!"), id="text"),
pytest.param(DataContent(author="user", data={}), id="data"),
pytest.param(ReasoningContent(author="user", summary=["thinking"], type="reasoning"), id="reasoning"),
pytest.param(
ToolRequestContent(author="user", name="get_weather", tool_call_id="call-1", arguments={"city": "Paris"}),
id="tool-request",
),
pytest.param(
ToolResponseContent(author="user", name="get_weather", tool_call_id="call-1", content={"k": "v"}),
id="tool-response-dict",
),
pytest.param(
ToolResponseContent(author="user", name="get_weather", tool_call_id="call-1", content=[1, 2]),
id="tool-response-list",
),
]


class TestOfflineSignalHandler:
"""Unit tests for ``on_task_event_send`` that need no running agent, Temporal or network.

The handler is called directly with real ``SendEventParams``; ``adk.messages.create``
is mocked, so nothing leaves the process.
"""

@staticmethod
def _workflow():
from project.workflow import At000HelloAcpWorkflow

# Build the instance without Temporal: skip __init__ and set what it would set.
wf = At000HelloAcpWorkflow.__new__(At000HelloAcpWorkflow)
wf.display_name = AGENT_NAME
wf._complete_task = False
return wf

@pytest.mark.asyncio
async def test_event_without_content_is_ignored(self):
"""No content: return without raising (that would wedge the task) and send nothing."""
with patch("project.workflow.adk.messages.create", new=AsyncMock()) as create:
wf = self._workflow()
await wf.on_task_event_send(_send_event_params(None))

create.assert_not_awaited()
assert wf._complete_task is False

@pytest.mark.asyncio
@pytest.mark.parametrize("content", ECHOED_CONTENTS)
async def test_event_is_echoed_then_answered(self, content):
"""Any content type is echoed back unchanged, then the agent replies."""
with patch("project.workflow.adk.messages.create", new=AsyncMock()) as create:
wf = self._workflow()
await wf.on_task_event_send(_send_event_params(content))

assert create.await_count == 2
echo, reply = create.await_args_list
assert echo.kwargs == {"task_id": TASK_ID, "content": content}
assert reply.kwargs["task_id"] == TASK_ID
assert isinstance(reply.kwargs["content"], TextContent)
assert reply.kwargs["content"].author == "agent"


if __name__ == "__main__":
pytest.main([__file__, "-v"])
46 changes: 46 additions & 0 deletions examples/tutorials/10_async/10_temporal/010_agent_chat/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Pytest setup for this tutorial's tests.

``project.workflow`` reads environment variables when it is imported, so the offline tests need them set and
this tutorial's ``project`` package importable. Both are arranged here for this tutorial's tests only. Any
``project`` package already imported (another tutorial's, in a session that collects several) is cleared before
and after them, and so is the SDK's cached ``EnvironmentVariables``, so this tutorial's workflow reads its own
values.
"""

from __future__ import annotations

import os
import sys
from collections.abc import Iterator

import pytest

TUTORIAL_DIR = os.path.dirname(os.path.abspath(__file__))

# Values already set in the environment win.
ENV_DEFAULTS = {
"AGENT_NAME": "at010-agent-chat",
"ACP_URL": "http://localhost:8000",
"WORKFLOW_NAME": "at010-agent-chat",
}


def _forget_project_modules() -> None:
for name in [name for name in sys.modules if name == "project" or name.startswith("project.")]:
del sys.modules[name]


@pytest.fixture(autouse=True, scope="module")
def _tutorial_environment() -> Iterator[None]:
with pytest.MonkeyPatch.context() as patch:
for name, value in ENV_DEFAULTS.items():
if not os.environ.get(name):
patch.setenv(name, value)
patch.syspath_prepend(TUTORIAL_DIR)
# EnvironmentVariables.refresh() keeps the first values it reads for the whole process.
patch.setattr("agentex.lib.environment_variables.refreshed_environment_variables", None)
_forget_project_modules()
try:
yield
finally:
_forget_project_modules()
Loading
Loading