Skip to content

API Reference parrot.handlers.web_hitl

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.handlers.web_hitl

View source

Web HITL (Human-in-the-Loop) support for AI-Parrot.

This module provides:

  1. ContextVar helpers — current_web_session stores the active WebSocket channel ID (typically the user's session_id) so that tools invoked by an agent during a web request can resolve the correct recipient without being explicitly passed the value.

  2. WebHumanTool — a :class:~parrot.human.tool.HumanTool subclass that lazily resolves the HumanInteractionManager and the target web session at invocation time, mirroring TelegramHumanTool.

  3. HITLResponseBody / HITLResponseHandler — a Pydantic model and an aiohttp :class:~navigator.views.BaseView that expose the POST /api/v1/agents/hitl/respond endpoint through which the frontend submits human answers back to the waiting agent.

  4. setup_web_hitl — idempotent bootstrap function called from :class:~parrot.manager.manager.BotManager that ensures a process-wide :class:~parrot.human.manager.HumanInteractionManager and :class:~parrot.human.channels.web.WebHumanChannel are initialised at application startup.

Alias ESCALATE_OPTION_KEY

Re-exported from parrot.human.channels.base.ESCALATE_OPTION_KEY.

Class HITLResponseBody

Request body for POST /api/v1/agents/hitl/respond.

Fields:

Field Type Default Description
interaction_id str UUID of the pending interaction to resolve.
value Any The human's response value (type depends on interaction_type).
response_type Optional[str] None Optional override for the response type. Defaults to the interaction's declared type.

Class HITLResponseHandler

HTTP handler for POST /api/v1/agents/hitl/respond.

Accepts a JSON body containing interaction_id and value, looks up the pending interaction in the default :class:~parrot.human.manager.HumanInteractionManager, and calls manager.receive_response(...) to unblock the waiting agent.

Method HITLResponseHandler.post

Handle a human response submission.

post() -> web.Response

Returns: web.Response — 200 — {"ok": true, "interaction_id": "..."} on success. 400 — {"error": "..."} on missing/invalid request body. 404 — {"error": "interaction not found"} for unknown IDs. 503 — {"error": "service unavailable"} when the manager is not configured.

Alias HumanInteractionManager

Re-exported from parrot.human.HumanInteractionManager.

Alias HumanResponse

Re-exported from parrot.human.models.HumanResponse.

Alias HumanTool

Re-exported from parrot.human.HumanTool.

Alias InteractionType

Re-exported from parrot.human.models.InteractionType.

Class SuspendingWebHumanTool

WebHumanTool variant wired for stateless REST suspend/resume (FEAT-204).

Sets wait_strategy=WaitStrategy.SUSPEND, which causes :meth:~parrot.human.tool.HumanTool._execute to call :meth:~parrot.human.manager.HumanInteractionManager.request_human_input_async and raise :class:~parrot.core.exceptions.HumanInteractionInterrupt instead of blocking. The HTTP handler catches the interrupt, serialises the tool-loop state, and returns a paused envelope so the frontend can drive the resume flow via a later hitl_response-tagged request.

Lazy manager resolution and current_web_session-based target resolution are fully inherited from :class:WebHumanTool — no re-implementation.

Both :class:WebHumanTool (WebSocket long-poll, FEAT-146) and this class coexist. Wire an agent with one or the other at construction:

  • Blocking (WebSocket): ask_human = WebHumanTool(source_agent=name)
  • Stateless (REST): ask_human = SuspendingWebHumanTool(source_agent=name)
Parameter Type Default Description
default_targets Optional[List[str]] None Fallback list of target human IDs.
source_agent Optional[str] None Name of the agent that owns this tool.
**kwargs Any {} Forwarded to :class:WebHumanTool.

Alias WaitStrategy

Re-exported from parrot.human.WaitStrategy.

Class WebHumanTool

A :class:~parrot.human.tool.HumanTool that auto-resolves manager and target from the current web request context.

Resolution order for target_humans on each invocation: 1. Explicit target_humans from the LLM call (kwargs). 2. self.default_targets from construction. 3. :func:get_current_web_session — the ContextVar set by :meth:~parrot.handlers.agent.AgentTalk.post at request entry.

Parameter Type Default Description
default_targets Optional[List[str]] None Fallback list of target human IDs.
source_agent Optional[str] None Name of the agent that owns this tool (used to identify the source in the wire payload).
**kwargs Any {} Forwarded to :class:~parrot.human.tool.HumanTool.

Attribute current_web_session

Type: ContextVar[Optional[str]]

Function get_current_web_session

Return the active web session ID for the current request context.

get_current_web_session() -> Optional[str]

Returns: Optional[str] — The WebSocket channel name previously set by func:set_current_web_session, or None if none was set.

Alias get_default_human_manager

Re-exported from parrot.human.get_default_human_manager.

Function is_authenticated

No-op decorator used when navigator_auth is not installed.

is_authenticated()

Attribute logger

Function reset_current_web_session

Reset the web session ContextVar to its previous value.

Should be called in a finally block to ensure the ContextVar is cleaned up even when the request handler raises an exception.

reset_current_web_session(token: Token) -> None

Parameter Type Default Description
token Token The :class:contextvars.Token returned by a prior call to :func:set_current_web_session.

Function set_current_web_session

Set the active web session ID for the current request context.

set_current_web_session(session: Optional[str]) -> Token

Parameter Type Default Description
session Optional[str] WebSocket channel name (typically the user's session_id or ws_channel_id).

Returns: Token — class:contextvars.Token that can be used to restore the previous value via :func:reset_current_web_session.

Alias set_default_human_manager

Re-exported from parrot.human.set_default_human_manager.

Function setup_web_hitl

Bootstrap a process-wide HumanInteractionManager with a WebHumanChannel.

This coroutine is idempotent — it is safe to call multiple times. On each call it:

  1. Checks whether a manager already exists via :func:~parrot.human.get_default_human_manager. If one exists, checks whether it already has a "web" channel registered; if so, skips entirely.
  2. If no manager exists, creates one backed by Redis (parrot.conf.REDIS_URL), registers a :class:~parrot.human.channels.web.WebHumanChannel under the name "web", calls :func:~parrot.human.set_default_human_manager, and awaits manager.startup() directly.
  3. If app['user_socket_manager'] is absent, logs a WARNING but does not raise — the bootstrap completes with a degraded state where the web channel cannot deliver messages.

This function awaits manager.startup() itself rather than appending a new on_startup hook, so it is safe to call from within an existing on_startup callback (where app.on_startup is frozen).

setup_web_hitl(app: web.Application) -> None

Parameter Type Default Description
app web.Application The :class:aiohttp.web.Application instance.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally