Repository navigation
Fix Agent session lost <think></think> tag - #16670
Conversation
📝 WalkthroughWalkthroughThis PR adds two unrelated changes: workflow message handlers in agent_api.py now inject ""/"" markers based on start_to_think/end_to_think flags, and agent.go's RunAgent now persists conversation sessions (user input, answer, references) via a new persistAgentRunSession helper at three completion points. ChangesThink Tag Markers in Workflow Streaming
Estimated code review effort: 1 (Trivial) | ~5 minutes Agent Run Session Persistence
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant RunAgent
participant persistAgentRunSession
participant api4ConversationDAO
participant SSEClient
RunAgent->>RunAgent: detect completion path (interrupt, loop, or normal)
RunAgent->>persistAgentRunSession: persist(sessionID, messageID, userInput, answer, reference)
persistAgentRunSession->>api4ConversationDAO: load conversation session
api4ConversationDAO-->>persistAgentRunSession: session data
persistAgentRunSession->>persistAgentRunSession: append user/assistant messages, encode JSON
persistAgentRunSession->>api4ConversationDAO: Update(session)
RunAgent->>SSEClient: emit message/message_end/workflow_finished
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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: 2
🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)
316-321: 🎯 Functional Correctness | 🔵 TrivialPotential double-append if content and think flags coexist.
Content is appended unconditionally on Line 317, then think markers are appended separately based on flags. This differs from the upstream Go contract in
chat_session.go(context snippet 1), which treatsStartToThink/EndToThink/Answeras mutually exclusive via an if/elif/elif chain. If an event ever carries both a non-emptycontentand a think flag, this code would append both, producing malformed output (e.g.,"foo<think>"instead of just"<think>"). Given the current backend always sends these as mutually exclusive, this is currently safe, but the assumption isn't enforced here.Also, this same block is duplicated verbatim in the non-SSE path (Lines 378-381); consider extracting a small helper to keep the two loops in sync.
[medium_effort_and_medium_reward]♻️ Suggested consolidation
+def _apply_think_markers(content: str, data: dict) -> str: + if data.get("start_to_think", False): + return content + "<think>" + elif data.get("end_to_think", False): + return content + "</think>" + return contentThen use
full_content = _apply_think_markers(full_content + ans.get("data", {}).get("content", ""), ans.get("data", {}))in both loops.🤖 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 316 - 321, The message assembly in agent_api.py can double-append content and think markers when a payload includes both content and start/end_think flags, unlike the mutually exclusive handling in chat_session.go. Update the logic in the message-handling block (and the duplicated non-SSE path) so the event data is processed through a single mutually exclusive branch or shared helper that handles Answer/StartToThink/EndToThink consistently, preventing malformed output and keeping both loops in sync.
🤖 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 `@internal/service/agent.go`:
- Around line 1196-1218: The session update flow in the agent run path is doing
a read/append/save on the full Message and Reference blobs, so concurrent
completions can overwrite each other. Update the logic around the session load
and save in the agent service to use a transaction with row-level locking or a
DAO method that atomically appends the new turn and reference data. Keep the fix
centered on the existing GetBySessionID, parseAgentSessionMessages,
parseAgentSessionReferences, and api4ConversationDAO.Update flow so both Message
and Reference are updated safely under concurrency.
- Around line 1201-1202: The session lookup helper in RunAgent currently returns
early when GetBySessionID misses, which causes brand-new runs with a generated
sessionID to be dropped instead of persisted. Update the helper around the
session/sessionID check to create an API4Conversation row when session is nil,
and change the helper signature/call sites to accept userID so the new row can
be owned correctly for later resume checks. Keep the existing session reuse path
intact, but ensure the miss path initializes and persists the conversation
instead of returning immediately.
---
Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 316-321: The message assembly in agent_api.py can double-append
content and think markers when a payload includes both content and
start/end_think flags, unlike the mutually exclusive handling in
chat_session.go. Update the logic in the message-handling block (and the
duplicated non-SSE path) so the event data is processed through a single
mutually exclusive branch or shared helper that handles
Answer/StartToThink/EndToThink consistently, preventing malformed output and
keeping both loops in sync.
🪄 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: dc41a35c-bbf2-4451-af8f-132aaa00c98d
📒 Files selected for processing (2)
api/apps/restful_apis/agent_api.pyinternal/service/agent.go
| session, err := s.api4ConversationDAO.GetBySessionID(sessionID, agentID) | ||
| if err != nil { | ||
| common.Warn("agent run: load session for update failed", zap.String("agent_id", agentID), zap.String("session_id", sessionID), zap.Error(err)) | ||
| return | ||
| } | ||
| if session == nil { | ||
| return | ||
| } | ||
| messages := parseAgentSessionMessages(session.Message) | ||
| now := time.Now().Unix() | ||
| if text := stringifyAgentUserInput(userInput); text != "" { | ||
| messages = append(messages, map[string]interface{}{"role": "user", "content": text, "id": strings.ReplaceAll(uuid.New().String(), "-", ""), "created_at": now}) | ||
| } | ||
| messages = append(messages, map[string]interface{}{"role": "assistant", "content": answer, "id": messageID, "created_at": now}) | ||
| if raw, err := json.Marshal(messages); err == nil { | ||
| session.Message = raw | ||
| } | ||
| references := parseAgentSessionReferences(session.Reference) | ||
| references = append(references, normalizeAgentReferenceEntry(map[string]interface{}{"chunks": reference})) | ||
| if raw, err := json.Marshal(references); err == nil { | ||
| session.Reference = raw | ||
| } | ||
| if err := s.api4ConversationDAO.Update(session); err != nil { |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Avoid lost turns on concurrent session updates.
This load/append/save flow rewrites the full Message and Reference JSON blobs. Two runs finishing for the same session can both read the same row, append independently, and the later Update overwrites the earlier turn. Move this into a transaction with row locking or a DAO-level atomic append/update.
🤖 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 `@internal/service/agent.go` around lines 1196 - 1218, The session update flow
in the agent run path is doing a read/append/save on the full Message and
Reference blobs, so concurrent completions can overwrite each other. Update the
logic around the session load and save in the agent service to use a transaction
with row-level locking or a DAO method that atomically appends the new turn and
reference data. Keep the fix centered on the existing GetBySessionID,
parseAgentSessionMessages, parseAgentSessionReferences, and
api4ConversationDAO.Update flow so both Message and Reference are updated safely
under concurrency.
| if session == nil { | ||
| return |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Create the session row instead of dropping new runs.
When RunAgent generates a new sessionID, GetBySessionID will miss and this helper returns, so the run is never persisted. Create an API4Conversation row on miss and pass userID into this helper so resume checks have a populated owner.
Possible fix shape
-func (s *AgentService) persistAgentRunSession(agentID, sessionID, messageID string, userInput any, answer string, reference []interface{}) {
+func (s *AgentService) persistAgentRunSession(agentID, sessionID, messageID, userID string, userInput any, answer string, reference []interface{}) {
@@
- if session == nil {
- return
+ isNewSession := false
+ if session == nil {
+ isNewSession = true
+ session = &entity.API4Conversation{
+ ID: sessionID,
+ DialogID: agentID,
+ UserID: userID,
+ }
}
@@
- if err := s.api4ConversationDAO.Update(session); err != nil {
+ if isNewSession {
+ err = s.api4ConversationDAO.Create(session)
+ } else {
+ err = s.api4ConversationDAO.Update(session)
+ }
+ if err != nil {
common.Warn("agent run: update session failed", zap.String("agent_id", agentID), zap.String("session_id", sessionID), zap.Error(err))
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if session == nil { | |
| return | |
| isNewSession := false | |
| if session == nil { | |
| isNewSession = true | |
| session = &entity.API4Conversation{ | |
| ID: sessionID, | |
| DialogID: agentID, | |
| UserID: userID, | |
| } | |
| } |
🤖 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 `@internal/service/agent.go` around lines 1201 - 1202, The session lookup
helper in RunAgent currently returns early when GetBySessionID misses, which
causes brand-new runs with a generated sessionID to be dropped instead of
persisted. Update the helper around the session/sessionID check to create an
API4Conversation row when session is nil, and change the helper signature/call
sites to accept userID so the new row can be owned correctly for later resume
checks. Keep the existing session reuse path intact, but ensure the miss path
initializes and persists the conversation instead of returning immediately.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16670 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Session:


Log: