Add tool-call support to LLMAgent.stream_message #67
Labels
No labels
auto/blocked-by-deps
auto/ci-timeout
auto/claimed-implementer
auto/claimed-merge
auto/claimed-reviewer
auto/driver-down
auto/invariant-violation
auto/last-attempt-tier-0
auto/last-attempt-tier-1
auto/last-attempt-tier-2
auto/last-attempt-tier-min
Automation Tracking
auto/needs-conflict-resolution
auto/needs-implementer
auto/postmortem
auto/ready-to-merge
auto/restart-throttled
auto/revert
auto/sentinel
auto/stale-inactivity
auto/unstable
Blocked
Bounty
$100
Bounty
$1000
Bounty
$10000
Bounty
$20
Bounty
$2000
Bounty
$250
Bounty
$50
Bounty
$500
Bounty
$5000
Bounty
$750
MoSCoW
Could have
MoSCoW
Must have
MoSCoW
Should have
Needs Feedback
Points
1
Points
13
Points
2
Points
21
Points
3
Points
34
Points
5
Points
55
Points
8
Points
88
Priority
Backlog
Priority
CI Blocker
Priority
Critical
Priority
High
Priority
Low
Priority
Medium
Signed-off: Owner
Signed-off: Scrum Master
Signed-off: Tech Lead
Spike
State
Completed
State
Duplicate
State
In Progress
State
In Review
State
Paused
State
Unverified
State
Verified
State
Wont Do
Type
Automation
Type
Bug
Type
Discussion
Type
Documentation
Type
Epic
Type
Feature
Type
Legendary
Type
Refactor
Type
Support
Type
Task
Type
Testing
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Depends on
#68 feat(agents): add tool-call support to LLMAgent.stream_message
cleveragents/cleveractors-core
Reference
cleveragents/cleveractors-core#67
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Metadata
feat(agents): add tool-call support to LLMAgent.stream_messagefeature/m2-llm-agent-stream-tool-callsBackground
LLMAgentexposes two execution paths:process_message()(blocking, usesainvoke()) andstream_message()(streaming, usesastream()). These two paths have diverged in capability:process_message()has a fully working multi-turn tool-call loop — it passestoolsto the LLM, detectstool_callson every response, dispatches to ephemeralToolAgentinstances, appendsToolMessages, re-invokes up totool_max_rounds, handles token-budget exhaustion, runs a synthesis prompt when the model is stuck in tool-only mode, and supports tool-output pruning.stream_message()has none of this.The fix is not to duplicate the tool-call logic into
stream_message()— that would split one authoritative implementation into two and create a permanent maintenance burden. Instead, the tool-call loop should be extracted fromprocess_message()into a shared private helper,_execute_tool_loop(), that both paths call.process_message()is refactored to delegate to the helper (no change in observable behaviour).stream_message()calls the same helper for tool-using actors (yielding the complete response as a single content chunk) and retains its existingastream()path unchanged for actors that declare no tools.The single-chunk behaviour for tool-using actors is an accepted trade-off: when tools are involved, the user already waits for tool execution to complete before the final answer begins, so yielding that answer as a single chunk rather than token-by-token has minimal UX impact. The alternative — calling the LLM a second time with
astream()after the helper has already produced the final response withainvoke()— would double the LLM cost of every tool-using request and is not acceptable in a production billing context.The cleveragents-webapp has a temporary router-side workaround in PR #328 (
actor_config_has_tools+ fallback toexecutor.execute()in_execute_via_cleveractors_streamand_generate_actor_sse) that silently degrades to non-streaming for tool-declaring actors. That workaround can be removed from the webapp once this issue is resolved.Current Behaviour
Calling
executor.execute_stream(message)on an actor whose LLM agent declarestoolsyields an empty response or plain-text hallucination.stream_message()callsself.chat_model.astream(lc_messages)without passingtools, so the LLM receives no tool schemas and emits no tool calls. The stream completes immediately with no useful output.Additionally,
process_message()contains the entire multi-turn tool-call loop inline (~200 lines), with no separation between the "tool orchestration" concern and the "final text retrieval" concern, making the method hard to unit-test in isolation and impossible to reuse from other callers.Expected Behaviour
A new private async method
_execute_tool_loop()onLLMAgentencapsulates the complete tool-call orchestration: passingtoolsto the LLM, running the multi-turn loop viaainvoke(), dispatching tool calls through ephemeralToolAgentinstances, accumulating token counts across all rounds, handling token-budget exhaustion and the synthesis prompt, and running the tool-output pruning pass. It returns a result object containing the finalAIMessageresponse and the accumulated(prompt_tokens, completion_tokens).process_message()delegates to_execute_tool_loop()for the tool-call rounds and extractsstr(final_response.content)from the result. Observable behaviour is identical to today.stream_message()branches on whether the actor declares tools:astream()path runs unchanged — real token-by-token streaming is preserved._execute_tool_loop()runs all rounds viaainvoke();stream_message()then yields the final response text as a single content chunk and sets_last_token_usage/last_token_usage_varfrom the accumulated token counts returned by the helper.All billing-integrity guarantees (populating
last_token_usage_varand the_captured_prompt/_captured_completionsentinels on exception paths) are met for both callers of_execute_tool_loop().Acceptance Criteria
executor.execute_stream(message)on a tool-declaring single-LLM actor yields at least one non-empty string token andexecutor.last_resultreports non-zero accumulated token counts covering all tool-call rounds.execute_streamyields the final answer andexecutor.last_result.prompt_tokensequals the sum across all three invocations (two tool rounds + final).tool_max_roundsis exhausted, the generator terminates cleanly andexecutor.last_resultis populated.stream_message()on an actor with no tools configured behaves identically to the current implementation — realastream()token-by-token streaming, same token counts.process_message()behaviour is unchanged for both tool-using and non-tool actors.ConfigurationError, LangChain error),executor.last_resultis populated with accumulated token counts before the exception propagates._execute_tool_loop()has dedicated Behave coverage for each of its internal branches, independently ofprocess_message()andstream_message().nox -s typecheckreports zero errors and zero warnings on all changed files.nox -s coverage_reportreports ≥ 97% coverage.Supporting Information
src/cleveractors/agents/llm.py.process_message()(lines ~831–1303). It is tightly coupled to several local variables (_accumulated_prompt,_captured_prompt,_budget_exhausted,messages,response); the extraction must design a clean return type (a private dataclass or named tuple) that surfaces all state needed by both callers without leaking internal implementation details._captured_prompt/_captured_completion) inprocess_message()andstream_message()must be updated to read accumulated counts from the helper's return value rather than re-reading local variables.actor_config_has_tools+stream_fallback_to_non_streambranch in PR cleveragents/cleveragents-webapp#328 (src/cleverthis/api/routes/v1_chat.pyandsrc/cleverthis/services/chat_stream.py).process_message()refactor ~2d,stream_message()integration ~0.5d, Behave scenarios ~1.5d, Robot test ~0.5d, coverage + PR ~0.5d).Subtasks
_execute_tool_loop(): a private dataclass (e.g._ToolLoopResult) carryingfinal_response,accumulated_prompt,accumulated_completion, and any flags needed by callers (budget_exhausted,synthesis_was_run)._execute_tool_loop()fromprocess_message(): move the multi-turnainvoke()loop, per-toolToolAgentdispatch, token accumulation, budget exhaustion path, synthesis prompt flow, and tool-output pruning pass into the new method._execute_tool_loop()must populate its result correctly on both success and exception paths.process_message()to call_execute_tool_loop()and deriveresponse_textfromresult.final_response.content. All existing tests must continue to pass without modification.stream_message()to call_execute_tool_loop()whenself._lc_tools is not None, yieldstr(result.final_response.content)as a single content chunk, and set_last_token_usage/last_token_usage_varfromresult.accumulated_prompt/result.accumulated_completion. The existing no-toolsastream()branch must remain untouched._captured_prompt/_captured_completionbilling-integrity sentinels in both callers to correctly reflect accumulated counts from the helper on exception paths._execute_tool_loop()internals: basic single tool round; multi-round (two consecutive tool-call rounds);tool_max_roundsexhaustion; token accumulation spanning all rounds; token-budget exhaustion (synthesis path runs); model stuck in tool-only mode (synthesis prompt flow); tool-output pruning (pass runs and token costs included); tool dispatch error (ExecutionErrorcaptured asToolMessage, loop continues); exception path (partial token counts preserved in result).stream_message()integration: tool-using actor yields one non-empty chunk andlast_resulttoken counts equal helper's accumulated totals; no-tools actor behaviour unchanged (real astream tokens).process_message()regression: confirm existing tool-calling scenarios continue to pass after refactor (no new scenarios required if existing coverage is sufficient).execute_stream()on an actor with a tool config (stub provider; no real API key required).nox -s coverage_reportand confirm ≥ 97%.nox(all default sessions) and confirm all pass with zero errors.Definition of Done
This issue is complete when:
master, reviewed, and merged.Implementation Notes — commit
306f114Design decisions
_ToolLoopErrorfor billing integrity across the extraction boundaryThe key challenge in extracting
_execute_tool_loop()was preserving billing integrity: the callers (process_messageandstream_message) need to know the partial accumulated token counts if the helper raises before returning. Since Python has no output parameters, I defined a private_ToolLoopErrorexception that wraps the original exception and carriesaccumulated_prompt,accumulated_completion, andany_invocation_made. Callers catch this, set their_captured_prompt/_captured_completionsentinels, then re-raisecause from None. The outer exception handlers (except ConfigurationError,except LangChainException,except Exception) then process the re-raised original exception normally. This preserves all billing-integrity guarantees from the original implementation.Single-chunk output for
stream_message()with toolsWhen tools are configured,
stream_message()awaits_execute_tool_loop()and yields the complete final response as one chunk. The alternative (callingastream()again afterainvoke()produced the final answer) would double LLM cost for every tool-using request. The accepted trade-off is documented in the issue background and in the commit message. Real token-by-tokenastream()is preserved unchanged for no-tool actors.messageslist modified in-place_execute_tool_loop()takesmessages: list[Any]and appendsAIMessage+ToolMessageobjects as the conversation progresses. This mirrors the original inline behavior. Both callers build the initial[SystemMessage, HumanMessage]list and pass it to the helper, which grows it through tool rounds.tool_max_roundsparsing moved into the helperPreviously
tool_max_roundswas parsed at the top ofprocess_message()before theif _has_toolscheck (so it would raiseConfigurationErrorfor invalid values even for no-tool agents). After extraction, parsing happens inside_execute_tool_loop(), which is only called for tool-configured agents. This is a minor behavior change (no-tool agents with invalidtool_max_roundsno longer raise at call time), but there are no tests for that case and it's not a specified behavior.Key code locations
_ToolLoopResult:src/cleveractors/agents/llm.py, module level, afterChatOpenAIglobals_ToolLoopError: same file, module level, after_ToolLoopResult_execute_tool_loop():LLMAgent._execute_tool_loop, after_run_pruning_passprocess_message()delegation:LLMAgent.process_message, ~15-line block replacing 490+ linesstream_message()tools branch:LLMAgent.stream_message, before the existingastream()loopTests summary
features/llm_agent_tool_loop.feature+features/steps/llm_agent_tool_loop_steps.py: 10 Behave scenarios covering_execute_tool_loop()independentlyfeatures/llm_agent_stream_tool_calls.feature+features/steps/llm_agent_stream_tool_calls_steps.py: 7 Behave scenarios forstream_message()with toolsrobot/llm_tool_calling.robot: 2 new Robot integration tests (stream loop + multi-round token accumulation)llm_agent_tool_calling.featurescenarios pass unmodifiedQuality gates (commit
306f114)Follow-up note (out of scope)
The webapp workaround
actor_config_has_tools+stream_fallback_to_non_streamincleveragents/cleveragents-webapp#328can now be removed. This is webapp work tracked in the issue description under Supporting Information.type: toolgraph node execution by wiringNodeConfig.tooltoToolAgent._execute_tool#75