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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,19 @@ Both methods return `LLMPollingResult` with one of three states:
- `succeeded`: return the final LLM `result`.
- `failed`: return a terminal `error`.

## Blocking LLM Replay

In SDK 0.11.0 (unreleased), blocking `session.model.llm.invoke` and `session.model.llm_structured_output.invoke` calls preserve the last non-`None` `opaque_body` snapshot.
Empty objects, arrays, strings, zero, and false are valid snapshots; trailing chunks without a snapshot do not erase them.
String chunks are concatenated, while nonempty content arrays retain their blocks and metadata in order, including when mixed with strings.
Providers must assemble complete tool calls before emitting them, once per call, with nonempty IDs unique within the response.
Calls may arrive in separate batches or together; collectors preserve their order and the original argument strings, and reject missing or duplicate IDs.
Each usage update is a cumulative snapshot for the current model response; collectors retain the last non-`None` snapshot, including zero values, and Agents add usage across model responses.
Use `message.get_text_content()` when a consumer needs plain text, and retain the complete message when replaying a tool turn.
`AssistantPromptMessage.is_empty()` treats tool calls and any non-`None` snapshot as content.
`ToolPromptMessage.is_empty()` treats a tool call ID as content, including when the tool result is empty.
The invoking Agent/plugin, provider, daemon, and host must all preserve these fields for replay across tool turns.

## OpenAI-Compatible Streaming

In SDK 0.11.0 (unreleased), `OAICompatLargeLanguageModel` preserves SSE data alongside comments and unknown fields.
Expand Down
7 changes: 6 additions & 1 deletion src/dify_plugin/entities/model/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,12 @@ def empty_usage(cls) -> "LLMUsage":


class LLMResultChunkDelta(BaseModel):
"""Model class for llm result chunk delta."""
"""Stream content with complete tool calls and cumulative usage snapshots.

Providers assemble tool arguments before emitting each call exactly once.
Call IDs must be nonempty and unique within the model response.
The last non-None usage is the total for that response, not an increment.
"""

index: int
message: AssistantPromptMessage
Expand Down
4 changes: 2 additions & 2 deletions src/dify_plugin/entities/model/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def is_empty(self) -> bool:
Returns:
The return value.
"""
return not (not super().is_empty() and not self.tool_calls)
return super().is_empty() and not self.tool_calls and self.opaque_body is None


class SystemPromptMessage(PromptMessage):
Expand Down Expand Up @@ -270,7 +270,7 @@ def is_empty(self) -> bool:
Returns:
The return value.
"""
return not (not super().is_empty() and not self.tool_call_id)
return super().is_empty() and not self.tool_call_id


PROMPT_MESSAGE_TYPES_BY_ROLE: dict[str, type[PromptMessage]] = {
Expand Down
2 changes: 1 addition & 1 deletion src/dify_plugin/interfaces/agent/strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def increase_usage(
usage: LLMUsage,
) -> None:
if not final_llm_usage_dict["usage"]:
final_llm_usage_dict["usage"] = usage
final_llm_usage_dict["usage"] = usage.model_copy()
else:
llm_usage = final_llm_usage_dict["usage"]
llm_usage.prompt_tokens += usage.prompt_tokens
Expand Down
44 changes: 30 additions & 14 deletions src/dify_plugin/invocations/model/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,42 @@
AssistantPromptMessage,
PromptMessage,
PromptMessageTool,
TextPromptMessageContent,
)


def merge_llm_result_chunk(result: LLMResult, chunk: LLMResultChunk) -> None:
"""Append complete tool calls and retain the latest usage and replay snapshots."""
call_ids = {call.id for call in result.message.tool_calls}
for call in chunk.delta.message.tool_calls:
if not call.id:
msg = "Complete tool calls must have a nonempty ID."
raise ValueError(msg)
if call.id in call_ids:
msg = f"Duplicate tool call ID: {call.id}"
raise ValueError(msg)
call_ids.add(call.id)

content = chunk.delta.message.content
# Keep blocking results compatible with callers that expect a string.
if isinstance(content, str):
result.message.content = cast("str", result.message.content) + content
if chunk.delta.message.tool_calls:
result.message.tool_calls = chunk.delta.message.tool_calls
if chunk.delta.usage:
result.usage.prompt_tokens += chunk.delta.usage.prompt_tokens
result.usage.completion_tokens += chunk.delta.usage.completion_tokens
result.usage.total_tokens += chunk.delta.usage.total_tokens

result.usage.completion_price = chunk.delta.usage.completion_price
result.usage.prompt_price = chunk.delta.usage.prompt_price
result.usage.total_price = chunk.delta.usage.total_price
result.usage.currency = chunk.delta.usage.currency
result.usage.latency = chunk.delta.usage.latency
if isinstance(result.message.content, list):
if content:
result.message.content.append(TextPromptMessageContent(data=content))
else:
result.message.content = (result.message.content or "") + content
elif isinstance(content, list) and content:
if not isinstance(result.message.content, list):
result.message.content = (
[TextPromptMessageContent(data=result.message.content)]
if result.message.content
else []
)
result.message.content.extend(content)
result.message.tool_calls.extend(chunk.delta.message.tool_calls)
if chunk.delta.message.opaque_body is not None:
result.message.opaque_body = chunk.delta.message.opaque_body
if chunk.delta.usage is not None:
result.usage = chunk.delta.usage.model_copy()


class LLMInvocation(BackwardsInvocation[LLMResultChunk]):
Expand Down
23 changes: 15 additions & 8 deletions tests/interfaces/agent/test_agent_behavior.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def convert_with_removed_tool(tool: ToolEntity) -> PromptMessageTool:
assert list(agent.invoke({"tools": None})) == []


def test_usage_accumulation_preserves_existing_shared_result_behavior(
def test_usage_accumulation_preserves_each_response_snapshot(
agent: SchemaAgent,
) -> None:
first = LLMUsage.empty_usage().model_copy(
Expand All @@ -179,10 +179,15 @@ def test_usage_accumulation_preserves_existing_shared_result_behavior(
"total_price": Decimal("0.007"),
}
)
original_first = first.model_copy()
original_second = second.model_copy()
total: dict[str, LLMUsage | None] = {"usage": None}
agent.increase_usage(total, first)
agent.increase_usage(total, second)
assert total["usage"] is first
assert total["usage"] is not first
assert first == original_first
assert second == original_second
assert total["usage"] is not None
assert total["usage"].prompt_tokens == 13
assert total["usage"].completion_tokens == 6
assert total["usage"].total_tokens == 19
Expand All @@ -191,12 +196,14 @@ def test_usage_accumulation_preserves_existing_shared_result_behavior(
assert total["usage"].total_price == Decimal("0.025")

agent.increase_usage(total, first)
assert total["usage"].prompt_tokens == 26
assert total["usage"].completion_tokens == 12
assert total["usage"].total_tokens == 38
assert total["usage"].prompt_price == Decimal("0.026")
assert total["usage"].completion_price == Decimal("0.024")
assert total["usage"].total_price == Decimal("0.050")
assert total["usage"].prompt_tokens == 23
assert total["usage"].completion_tokens == 10
assert total["usage"].total_tokens == 33
assert total["usage"].prompt_price == Decimal("0.023")
assert total["usage"].completion_price == Decimal("0.020")
assert total["usage"].total_price == Decimal("0.043")
assert first == original_first
assert second == original_second


@pytest.mark.parametrize("parameter_name", ["max_tokens", "max_completion_tokens"])
Expand Down
Loading
Loading