Repository navigation
Fix: support non-stream runtime agent completion - #14596
Conversation
📝 WalkthroughWalkthroughThe agent chat completion flow is refactored to support unified streaming and non-streaming execution paths with a dedicated runtime replica commit step that ensures replicas are committed after execution completion. ChangesAgent Chat Completion Flow Refactoring
Sequence DiagramsequenceDiagram
participant Client
participant Agent API
participant Canvas Runtime
participant Runtime Replica
alt Streaming Path
Client->>Agent API: POST /chat (streaming=true)
Agent API->>Canvas Runtime: Execute run
loop Stream Events
Canvas Runtime->>Agent API: Yield event
Agent API->>Client: Send SSE
end
Agent API->>Runtime Replica: Commit replica
Runtime Replica->>Agent API: Commit complete
Agent API->>Client: Stream end
else Non-Streaming Path
Client->>Agent API: POST /chat (streaming=false)
Agent API->>Canvas Runtime: Execute run
Canvas Runtime->>Agent API: Return final state
Agent API->>Agent API: Aggregate content, references, traces
Agent API->>Runtime Replica: Commit replica
Runtime Replica->>Agent API: Commit complete
Agent API->>Client: Return aggregated result
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)
1037-1081: ⚡ Quick winAdd structured logs for the new non-stream runtime flow.
This branch is the new execution path in the PR, but today it only logs failures. Please add at least start/success logs with
agent_id,tenant_id, andruntime_user_idso this path is observable in production.As per coding guidelines,
**/*.py: Add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/agent_api.py` around lines 1037 - 1081, Add structured start and success logs around the non-stream runtime path: log a start message before entering the try/async-for loop and a success message right before await commit_runtime_replica()/return get_result(...). Include agent_id, tenant_id, and runtime_user_id in both logs (pull these from the available context/req/inputs as appropriate), use the existing logging facility (e.g., logging.info) consistent with logging.exception used on errors, and reference the non-stream flow by mentioning symbols from this block like canvas.run, final_ans, full_content, canvas.cancel_task, and commit_runtime_replica to locate where to insert the messages.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1001-1010: The call to CanvasReplicaService.commit_after_run
inside commit_runtime_replica blocks the Quart event loop because it performs
synchronous Redis I/O; change commit_runtime_replica to invoke
CanvasReplicaService.commit_after_run via the existing thread_pool_exec helper
(await thread_pool_exec(lambda: CanvasReplicaService.commit_after_run(...))) so
the blocking Redis call runs off the event loop, and propagate/log any returned
boolean appropriately; also add structured logging statements (start and
completion with success/failure) around the non-stream runtime flow so the new
flow (the non-stream runtime branch) logs when it begins and when it finishes
(include the runtime identifier like agent_id/canvas_title and success status)
to match the "Add logging for new flows" guideline.
---
Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1037-1081: Add structured start and success logs around the
non-stream runtime path: log a start message before entering the try/async-for
loop and a success message right before await commit_runtime_replica()/return
get_result(...). Include agent_id, tenant_id, and runtime_user_id in both logs
(pull these from the available context/req/inputs as appropriate), use the
existing logging facility (e.g., logging.info) consistent with logging.exception
used on errors, and reference the non-stream flow by mentioning symbols from
this block like canvas.run, final_ans, full_content, canvas.cancel_task, and
commit_runtime_replica to locate where to insert the messages.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e466f06c-a3f4-42c8-a4aa-aef85e568b60
📒 Files selected for processing (1)
api/apps/restful_apis/agent_api.py
| async def commit_runtime_replica(): | ||
| commit_ok = CanvasReplicaService.commit_after_run( | ||
| canvas_id=agent_id, | ||
| tenant_id=str(tenant_id), | ||
| runtime_user_id=user_id, | ||
| dsl=json.loads(str(canvas)), | ||
| canvas_category=canvas_category, | ||
| title=canvas_title, | ||
| ) | ||
| if not commit_ok: |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== commit_after_run implementation =="
sed -n '223,259p' api/apps/services/canvas_replica_service.py
echo
echo "== surrounding async handler =="
sed -n '938,1085p' api/apps/restful_apis/agent_api.py
echo
echo "== existing thread_pool_exec usage in this handler =="
rg -n "thread_pool_exec\\(" api/apps/restful_apis/agent_api.pyRepository: infiniflow/ragflow
Length of output: 7735
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Checking imports at top of agent_api.py ==="
head -50 api/apps/restful_apis/agent_api.py | grep -E "^import|^from"
echo
echo "=== Checking for partial import ==="
rg "from functools import|import functools" api/apps/restful_apis/agent_api.py
echo
echo "=== Finding thread_pool_exec definition ==="
rg -n "def thread_pool_exec" --type py
echo
echo "=== Checking thread_pool_exec usage pattern in agent_api.py ==="
rg -B2 -A4 "await thread_pool_exec" api/apps/restful_apis/agent_api.py | head -60
echo
echo "=== Checking logging in non-stream runtime path (lines 1030-1080) ==="
sed -n '1030,1080p' api/apps/restful_apis/agent_api.pyRepository: infiniflow/ragflow
Length of output: 4701
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== thread_pool_exec signature and implementation ==="
sed -n '128,150p' common/misc_utils.py
echo
echo "=== Check if thread_pool_exec is imported in agent_api.py ==="
rg "thread_pool_exec" api/apps/restful_apis/agent_api.py | head -3
</script>Repository: infiniflow/ragflow
Length of output: 801
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Stream path logging (lines 1015-1035) ==="
sed -n '1015,1035p' api/apps/restful_apis/agent_api.py
echo
echo "=== Non-stream path start (lines 1036-1055) ==="
sed -n '1036,1055p' api/apps/restful_apis/agent_api.py
echo
echo "=== Ruff linting check on the file ==="
rg "ruff" . --type py | head -5
python3 -m pip install ruff 2>/dev/null >/dev/null || true
python3 -m ruff check api/apps/restful_apis/agent_api.py 2>&1 | head -20Repository: infiniflow/ragflow
Length of output: 1985
Offload the replica commit from the async request path.
CanvasReplicaService.commit_after_run() is synchronous Redis I/O, so calling it directly here will block the Quart event loop at the end of every runtime completion. The handler already uses thread_pool_exec() for other blocking operations (lines 938, 945, 983), so this should follow the same pattern.
Additionally, the new non-stream runtime flow (lines 1036–1080) lacks structured logging for the start and completion of the flow, which violates the "Add logging for new flows" guideline.
♻️ Suggested change
async def commit_runtime_replica():
- commit_ok = CanvasReplicaService.commit_after_run(
- canvas_id=agent_id,
- tenant_id=str(tenant_id),
- runtime_user_id=user_id,
- dsl=json.loads(str(canvas)),
- canvas_category=canvas_category,
- title=canvas_title,
- )
+ commit_ok = await thread_pool_exec(
+ partial(
+ CanvasReplicaService.commit_after_run,
+ canvas_id=agent_id,
+ tenant_id=str(tenant_id),
+ runtime_user_id=user_id,
+ dsl=json.loads(str(canvas)),
+ canvas_category=canvas_category,
+ title=canvas_title,
+ )
+ )
if not commit_ok:
logging.error(🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@api/apps/restful_apis/agent_api.py` around lines 1001 - 1010, The call to
CanvasReplicaService.commit_after_run inside commit_runtime_replica blocks the
Quart event loop because it performs synchronous Redis I/O; change
commit_runtime_replica to invoke CanvasReplicaService.commit_after_run via the
existing thread_pool_exec helper (await thread_pool_exec(lambda:
CanvasReplicaService.commit_after_run(...))) so the blocking Redis call runs off
the event loop, and propagate/log any returned boolean appropriately; also add
structured logging statements (start and completion with success/failure) around
the non-stream runtime flow so the new flow (the non-stream runtime branch) logs
when it begins and when it finishes (include the runtime identifier like
agent_id/canvas_title and success status) to match the "Add logging for new
flows" guideline.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14596 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
support non-stream runtime agent completion
Type of change