mirror of
https://github.com/langgenius/dify.git
synced 2026-10-04 13:47:55 +08:00
fix(dify-agent): persist interrupted run history (#40972)
This commit is contained in:
1 parent
356e3a8ab6
commit
930f4e6c26
7 files changed
+235
-140
No files matched your search
@@ -2,8 +2,10 @@
|
||||
|
||||
Dify Agent keeps pydantic-ai conversation history as an optional Agenton layer
|
||||
named ``history``. Current system instructions belong to each run and are never
|
||||
stored; successful runs replace the layer with Pydantic AI's complete, possibly
|
||||
compacted history.
|
||||
stored. Once Pydantic AI binds and builds messages in the run capture, its
|
||||
complete captured history replaces the layer for every terminal outcome,
|
||||
including interrupted runs. A failure or cancellation before the capture
|
||||
contains messages preserves the previously restored history.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -63,11 +65,11 @@ def get_history_layer(run: SupportsHistoryLayerLookup) -> PydanticAIHistoryLayer
|
||||
return None
|
||||
|
||||
|
||||
def replace_successful_run_history(
|
||||
def replace_run_history(
|
||||
history_layer: PydanticAIHistoryLayer | None,
|
||||
messages: Sequence[ModelMessage],
|
||||
) -> None:
|
||||
"""Persist a successful run's complete history without transient instructions."""
|
||||
"""Persist a run's captured history without transient instructions."""
|
||||
if history_layer is None:
|
||||
return
|
||||
persistent_messages = [
|
||||
@@ -79,6 +81,6 @@ def replace_successful_run_history(
|
||||
__all__ = [
|
||||
"SupportsHistoryLayerLookup",
|
||||
"get_history_layer",
|
||||
"replace_successful_run_history",
|
||||
"replace_run_history",
|
||||
"validate_history_layer_composition",
|
||||
]
|
||||
@@ -11,10 +11,12 @@ policy is validated:
|
||||
request-level ``on_exit`` signals, and publish a terminal success or failure event;
|
||||
The Pydantic AI model is resolved from the active Agenton layer named by
|
||||
``DIFY_AGENT_MODEL_LAYER_ID``. An optional history layer contributes stored
|
||||
message history only through session state; successful model runs replace that
|
||||
state with ``result.all_messages()`` after transient instructions are cleared so
|
||||
compaction rewrites persist without saving current system prompts. An optional
|
||||
structured output layer named by
|
||||
message history only through session state. Once pydantic-ai binds and builds
|
||||
messages in the run capture, every terminal outcome replaces that state with the
|
||||
captured messages after transient instructions are cleared; a failure or
|
||||
cancellation before the capture contains messages preserves the restored state.
|
||||
This preserves compaction rewrites and interrupted partial messages without
|
||||
saving current system prompts. An optional structured output layer named by
|
||||
``DIFY_AGENT_OUTPUT_LAYER_ID`` is read after entry and resolved into an output
|
||||
contract whose type both exposes the output schema to the model and performs
|
||||
runtime JSON Schema validation through custom Pydantic hooks. When the ask-human
|
||||
@@ -37,6 +39,7 @@ from typing import Any, Literal, Protocol, cast, runtime_checkable
|
||||
import httpx
|
||||
from graphon.model_runtime.entities.llm_entities import LLMUsage
|
||||
from pydantic import JsonValue, TypeAdapter
|
||||
from pydantic_ai import capture_run_messages
|
||||
from pydantic_ai.exceptions import ModelHTTPError, UsageLimitExceeded
|
||||
from pydantic_ai.messages import AgentStreamEvent, PartDeltaEvent, PartStartEvent, TextPart, TextPartDelta
|
||||
from pydantic_ai.output import OutputSpec
|
||||
@@ -73,7 +76,7 @@ from dify_agent.runtime.event_sink import (
|
||||
)
|
||||
from dify_agent.runtime.history import (
|
||||
get_history_layer,
|
||||
replace_successful_run_history,
|
||||
replace_run_history,
|
||||
validate_history_layer_composition,
|
||||
)
|
||||
from dify_agent.runtime.layer_exit_signals import apply_layer_exit_signals, validate_layer_exit_signals
|
||||
@@ -362,16 +365,21 @@ class AgentRunRunner:
|
||||
)
|
||||
run_timeout = asyncio.timeout(self.run_timeout_seconds)
|
||||
try:
|
||||
async with run_timeout:
|
||||
result = await agent.run(
|
||||
None if deferred_tool_results is not None else normalize_user_input(user_prompts),
|
||||
message_history=message_history,
|
||||
deferred_tool_results=deferred_tool_results,
|
||||
event_stream_handler=handle_events,
|
||||
instructions=run.prompts or None,
|
||||
capabilities=[compaction] if compaction is not None else None,
|
||||
usage_limits=UsageLimits(request_limit=_MAX_AGENT_STEPS_PER_RUN),
|
||||
)
|
||||
with capture_run_messages() as captured_messages:
|
||||
try:
|
||||
async with run_timeout:
|
||||
result = await agent.run(
|
||||
None if deferred_tool_results is not None else normalize_user_input(user_prompts),
|
||||
message_history=message_history,
|
||||
deferred_tool_results=deferred_tool_results,
|
||||
event_stream_handler=handle_events,
|
||||
instructions=run.prompts or None,
|
||||
capabilities=[compaction] if compaction is not None else None,
|
||||
usage_limits=UsageLimits(request_limit=_MAX_AGENT_STEPS_PER_RUN),
|
||||
)
|
||||
finally:
|
||||
if captured_messages:
|
||||
replace_run_history(history_layer, captured_messages)
|
||||
except TimeoutError as exc:
|
||||
if not run_timeout.expired():
|
||||
raise
|
||||
@@ -381,7 +389,6 @@ class AgentRunRunner:
|
||||
complete_usage = model.accumulated_usage if isinstance(model, _HasAccumulatedUsage) else None
|
||||
usage = _serialize_agent_usage(complete_usage if complete_usage is not None else _result_usage(result))
|
||||
self._terminal_usage = usage
|
||||
replace_successful_run_history(history_layer, result.all_messages())
|
||||
if isinstance(result.output, DeferredToolRequests):
|
||||
if ask_human_layer is None:
|
||||
raise AgentRunValidationError(
|
||||
|
||||
Reference in new issue
Block a user