Skip to content
Merged
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
3 changes: 2 additions & 1 deletion api/adapters/external_agents/workflow_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from graphon.engine.command.entities import AbortCommand
from graphon.engine.layer import Layer
from graphon.engine_events import GraphRunPausedEvent
from graphon.entities.pause_reason import HitlRequired
from graphon.entities.pause_reason import HitlRequired # pyrefly: ignore[deprecated] - Legacy HITL remains supported.
from graphon.nodes.base.node import Node
from services.external_agents.runtime_contracts import ExecutionIdentity

Expand Down Expand Up @@ -66,6 +66,7 @@ def _abort(self) -> None:
@override
def on_event(self, event) -> None:
if isinstance(event, GraphRunPausedEvent) and self._scope is not None and self._identity is not None:
# pyrefly: ignore[deprecated] - Legacy HITL remains supported.
human_only = bool(event.reasons) and all(isinstance(reason, HitlRequired) for reason in event.reasons)
self._repository.pause_budget(self._scope, self._identity, human_only=human_only, now=datetime.now(UTC))

Expand Down
9 changes: 5 additions & 4 deletions api/adapters/external_agents/workflow_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from core.app.file_access import get_current_file_access_scope, grant_upload_file_access
from core.workflow.system_variables import SystemVariableKey, get_system_text
from graphon.entities.base_node_data import BaseNodeData
from graphon.entities.pause_reason import ExternalWaitReason
from graphon.entities.pause_reason import ExternalWait
from graphon.enums import (
BuiltinNodeTypes,
ErrorStrategy,
Expand All @@ -39,7 +39,7 @@
from models.external_agent import ExternalAgentCommand
from models.external_agent_trace import ExternalAgentDataTombstone
from models.workflow import WorkflowNodeExecutionModel, WorkflowPause, WorkflowRun
from services.external_agents.contracts import ExternalOrigin
from services.external_agents.contracts import EXTERNAL_AGENT_WAIT_TYPE, ExternalOrigin
from services.external_agents.execution_usage import ExternalExecutionUsageQuery
from services.external_agents.file_profile import render_task_value
from services.external_agents.invocation_service import ExternalInvocationService
Expand Down Expand Up @@ -406,11 +406,12 @@ def _run(self) -> Generator[NodeEventPayload]:
self._enqueue()
if result.state in {LocalState.WAITING, LocalState.RETRY_PENDING}:
yield PauseRequestedEvent(
reason=ExternalWaitReason(
reason=ExternalWait(
wait_type=EXTERNAL_AGENT_WAIT_TYPE,
wait_id=result.invocation_id,
node_id=self.id,
node_title=self.node_data.title,
execution_id=self.execution_id,
node_execution_id=identity.execution_id,
frame_id=identity.frame_id,
)
)
Expand Down
11 changes: 10 additions & 1 deletion api/core/agent/cot_agent_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
ToolPromptMessage,
UserPromptMessage,
)
from graphon.model_runtime.model_providers.base.large_language_model import LLMResultAccumulator
from models.model import Message

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -155,7 +156,8 @@ def increase_usage(final_llm_usage_dict: dict[str, LLMUsage | None], usage: LLMU
)

usage_dict: dict[str, LLMUsage | None] = {}
react_chunks = CotAgentOutputParser.handle_react_stream_output(chunks, usage_dict)
result = LLMResultAccumulator()
react_chunks = CotAgentOutputParser.handle_react_stream_output(chunks, usage_dict, result=result)
scratchpad = AgentScratchpadUnit(
agent_response="",
thought="",
Expand Down Expand Up @@ -249,6 +251,12 @@ def increase_usage(final_llm_usage_dict: dict[str, LLMUsage | None], usage: LLMU
message_file_ids=message_file_ids,
trace_scope=trace_scope,
)
self._current_thoughts.extend(
(
result.to_result(model=model_instance.model_name, prompt_messages=prompt_messages).message,
UserPromptMessage(content=f"Observation: {tool_invoke_response}\n\ncontinue"),
)
)
scratchpad.observation = tool_invoke_response
scratchpad.agent_response = tool_invoke_response

Expand Down Expand Up @@ -388,6 +396,7 @@ def _init_react_state(self, query):
"""
self._query = query
self._agent_scratchpad = []
self._current_thoughts = []
self._historic_prompt_messages = self._organize_historic_prompt_messages()

@abstractmethod
Expand Down
12 changes: 12 additions & 0 deletions api/core/agent/cot_chat_agent_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ def _organize_prompt_messages(self) -> list[PromptMessage]:
# organize system prompt
system_message = self._organize_system_prompt()

# A formatted scratchpad cannot carry a signed assistant turn or ordered content blocks.
if any(
isinstance(turn, AssistantPromptMessage)
and (turn.opaque_body is not None or isinstance(turn.content, list))
for turn in self._current_thoughts
):
query_messages = self._organize_user_query(self._query, [])
history = self._organize_historic_prompt_messages(
[system_message, *query_messages, *self._current_thoughts]
)
return [system_message, *history, *query_messages, *self._current_thoughts]

# organize current assistant messages
agent_scratchpad = self._agent_scratchpad
if not agent_scratchpad:
Expand Down
141 changes: 26 additions & 115 deletions api/core/agent/fc_agent_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
UserPromptMessage,
)
from graphon.model_runtime.entities.message_entities import ImagePromptMessageContent, PromptMessageContentUnionTypes
from graphon.model_runtime.model_providers.base.large_language_model import LLMResultAccumulator
from models import UploadFile
from models.model import Message

Expand Down Expand Up @@ -114,8 +115,12 @@ def _build_dataset_tool_image_contents(
return prompt_message_contents

def run(self, session: Session, message: Message, query: str, **kwargs: Any) -> Generator[LLMResultChunk]:
"""
Run FunctionCall agent application
"""Run configured tool rounds, yielding model chunks and saving thoughts.

Requires an initialized agent configuration and a persisted message.
Replay uses empty strings for empty content arrays while preserving
tool calls, content blocks, and provider state.
Exhausting the configured tool rounds raises AgentMaxIterationError.
"""
self.query = query
app_generate_entity = self.application_generate_entity
Expand Down Expand Up @@ -195,107 +200,48 @@ def increase_usage(final_llm_usage_dict: dict[str, LLMUsage | None], usage: LLMU
request_metadata=request_metadata,
)

tool_calls: list[tuple[str, str, dict[str, Any]]] = []

# save full response
response = ""

# save tool call names and inputs
tool_call_names = ""
tool_call_inputs = ""

current_llm_usage = None

if isinstance(chunks, Generator):
accumulator = LLMResultAccumulator()
is_first_chunk = True
for chunk in chunks:
if is_first_chunk:
self.queue_manager.publish(
QueueAgentThoughtEvent(agent_thought_id=agent_thought_id), PublishFrom.APPLICATION_MANAGER
)
is_first_chunk = False
# check if there is any tool call
if self.check_tool_calls(chunk):
function_call_state = True
tool_calls.extend(self.extract_tool_calls(chunk) or [])
tool_call_names = ";".join([tool_call[1] for tool_call in tool_calls])
try:
tool_call_inputs = json.dumps(
{tool_call[1]: tool_call[2] for tool_call in tool_calls}, ensure_ascii=False
)
except TypeError:
# fallback: force ASCII to handle non-serializable objects
tool_call_inputs = json.dumps({tool_call[1]: tool_call[2] for tool_call in tool_calls})

if chunk.delta.message and chunk.delta.message.content:
if isinstance(chunk.delta.message.content, list):
for content in chunk.delta.message.content:
response += content.data
else:
response += str(chunk.delta.message.content)

accumulator.consume(chunk)
if chunk.delta.usage:
increase_usage(llm_usage, chunk.delta.usage)
current_llm_usage = chunk.delta.usage

increase_usage(llm_usage, current_llm_usage)
yield chunk
result = accumulator.to_result(model=model_instance.model_name, prompt_messages=prompt_messages)
else:
result = chunks
# check if there is any tool call
if self.check_blocking_tool_calls(result):
function_call_state = True
tool_calls.extend(self.extract_blocking_tool_calls(result) or [])
tool_call_names = ";".join([tool_call[1] for tool_call in tool_calls])
try:
tool_call_inputs = json.dumps(
{tool_call[1]: tool_call[2] for tool_call in tool_calls}, ensure_ascii=False
)
except TypeError:
# fallback: force ASCII to handle non-serializable objects
tool_call_inputs = json.dumps({tool_call[1]: tool_call[2] for tool_call in tool_calls})

if result.usage:
increase_usage(llm_usage, result.usage)
current_llm_usage = result.usage

if result.message and result.message.content:
if isinstance(result.message.content, list):
for content in result.message.content:
response += content.data
else:
response += result.message.content

if not result.message.content:
result.message.content = ""

current_llm_usage = result.usage
increase_usage(llm_usage, current_llm_usage)
if result.message.content is None:
result = result.model_copy(update={"message": result.message.model_copy(update={"content": ""})})
self.queue_manager.publish(
QueueAgentThoughtEvent(agent_thought_id=agent_thought_id), PublishFrom.APPLICATION_MANAGER
)

yield LLMResultChunk(
model=model_instance.model_name,
prompt_messages=result.prompt_messages,
system_fingerprint=result.system_fingerprint,
delta=LLMResultChunkDelta(
index=0,
message=result.message,
usage=result.usage,
),
delta=LLMResultChunkDelta(index=0, message=result.message, usage=result.usage),
)

assistant_message = AssistantPromptMessage(content=response, tool_calls=[])
if tool_calls:
assistant_message.tool_calls = [
AssistantPromptMessage.ToolCall(
id=tool_call[0],
type="function",
function=AssistantPromptMessage.ToolCall.ToolCallFunction(
name=tool_call[1], arguments=json.dumps(tool_call[2], ensure_ascii=False)
),
)
for tool_call in tool_calls
]

assistant_message = result.message
if assistant_message.content == []:
assistant_message = assistant_message.model_copy(update={"content": ""})
response = assistant_message.get_text_content()
tool_calls = self.extract_blocking_tool_calls(result) or []
function_call_state = bool(tool_calls)
tool_call_names = ";".join(tool_call[1] for tool_call in tool_calls)
tool_call_inputs = (
json.dumps({call[1]: call[2] for call in tool_calls}, ensure_ascii=False) if tool_calls else ""
)
self._current_thoughts.append(assistant_message)

# save thought
Expand Down Expand Up @@ -435,41 +381,6 @@ def increase_usage(final_llm_usage_dict: dict[str, LLMUsage | None], usage: LLMU
PublishFrom.APPLICATION_MANAGER,
)

def check_tool_calls(self, llm_result_chunk: LLMResultChunk) -> bool:
"""
Check if there is any tool call in llm result chunk
"""
return bool(llm_result_chunk.delta.message.tool_calls)

def check_blocking_tool_calls(self, llm_result: LLMResult) -> bool:
"""
Check if there is any blocking tool call in llm result
"""
return bool(llm_result.message.tool_calls)

def extract_tool_calls(self, llm_result_chunk: LLMResultChunk) -> list[tuple[str, str, dict[str, Any]]]:
"""
Extract tool calls from llm result chunk

Returns:
List[Tuple[str, str, Dict[str, Any]]]: [(tool_call_id, tool_call_name, tool_call_args)]
"""
tool_calls = []
for prompt_message in llm_result_chunk.delta.message.tool_calls:
args = {}
if prompt_message.function.arguments != "":
args = json.loads(prompt_message.function.arguments)

tool_calls.append(
(
prompt_message.id,
prompt_message.function.name,
args,
)
)

return tool_calls

def extract_blocking_tool_calls(self, llm_result: LLMResult) -> list[tuple[str, str, dict[str, Any]]]:
"""
Extract blocking tool calls from llm result
Expand Down
13 changes: 9 additions & 4 deletions api/core/agent/output_parser/cot_output_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from core.agent.entities import AgentScratchpadUnit
from graphon.model_runtime.entities.llm_entities import LLMResultChunk
from graphon.model_runtime.model_providers.base.large_language_model import LLMResultAccumulator

# Keys that name the action even when the model adds other fields to the JSON blob,
# highest priority first, so the selected tool does not depend on JSON key order.
Expand All @@ -14,7 +15,11 @@
class CotAgentOutputParser:
@classmethod
def handle_react_stream_output(
cls, llm_response: Generator[LLMResultChunk], usage_dict: dict[str, Any]
cls,
llm_response: Generator[LLMResultChunk],
usage_dict: dict[str, Any],
*,
result: LLMResultAccumulator | None = None,
) -> Generator[str | AgentScratchpadUnit.Action]:
def parse_action(action) -> str | AgentScratchpadUnit.Action:
"""Convert model-generated JSON into an action, or fall back to text.
Expand Down Expand Up @@ -97,11 +102,11 @@ def extra_json_from_code_block(code_block) -> list[list | dict]:
last_character = ""

for response in llm_response:
if result is not None:
result.consume(response)
if response.delta.usage:
usage_dict["usage"] = response.delta.usage
response_content = response.delta.message.content
if not isinstance(response_content, str):
continue
response_content = response.delta.message.get_text_content()

# stream
index = 0
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import contextlib
import json
import re
from typing import Any

from core.app.app_config.entities import RagPipelineVariableEntity
from domain.rag_pipeline.datasource_parameters import get_input_variable_name
from graphon.variables.input_entities import VariableEntity
from models.workflow import Workflow

Expand Down Expand Up @@ -50,9 +50,10 @@ def _normalize_json_schema(variable: dict[str, Any]) -> None:
@classmethod
def convert_rag_pipeline_variable(cls, workflow: Workflow, start_node_id: str) -> list[RagPipelineVariableEntity]:
"""
Convert workflow start variables to variables
Validate the node's second-step inputs after excluding datasource bindings.

:param workflow: workflow instance
Accept a stored workflow and start node ID. Return validated input entities
without changing the configuration; propagate invalid-entity errors.
"""
variables = []

Expand All @@ -72,17 +73,10 @@ def convert_rag_pipeline_variable(cls, workflow: Workflow, start_node_id: str) -
if datasource_node_data:
datasource_parameters = datasource_node_data.get("datasource_parameters", {})

for _, value in datasource_parameters.items():
if value.get("value") and isinstance(value.get("value"), str):
pattern = r"\{\{#([a-zA-Z0-9_]{1,50}(?:\.[a-zA-Z0-9_][a-zA-Z0-9_]{0,29}){1,10})#\}\}"
match = re.match(pattern, value["value"])
if match:
full_path = match.group(1)
last_part = full_path.split(".")[-1]
variables_map.pop(last_part, None)
if value.get("value") and isinstance(value.get("value"), list):
last_part = value.get("value")[-1]
variables_map.pop(last_part, None)
for value in datasource_parameters.values():
input_name = get_input_variable_name(value.get("value"))
if input_name is not None:
variables_map.pop(input_name, None)

all_second_step_variables = list(variables_map.values())

Expand Down
4 changes: 2 additions & 2 deletions api/core/app/apps/common/workflow_response_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
enrich_human_input_pause_reasons,
resolve_variable_select_input_options,
)
from core.workflow.nodes.human_input.pause_reason import HumanInputRequired
from core.workflow.nodes.human_input.pause_reason import HumanInputRequired, serialize_workflow_pause_reason
from core.workflow.nodes.human_input_v2.presentation import build_human_input_v2_pause_reason
from core.workflow.nodes.human_input_v2.runtime import PreparedForm
from core.workflow.system_variables import SystemVariableKey, system_variables_to_mapping
Expand Down Expand Up @@ -402,7 +402,7 @@ def workflow_pause_to_stream_response(
# order, including scheduling reasons interleaved with approval forms.
for reason in event.reasons:
if not isinstance(reason, HumanInputRequired):
pause_reasons.append(reason.model_dump(mode="json"))
pause_reasons.append(serialize_workflow_pause_reason(reason))
continue
match reason.form_version:
case "1":
Expand Down
Loading