Skip to content

Implement chat completions in go - #16491

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
qinling0210:chat_go
Jul 1, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
qinling0210:chat_go

Conversation

@qinling0210

Copy link
Copy Markdown
Contributor

Summary

POST /api/v1/chat/completions

@qinling0210 qinling0210 self-assigned this Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds /api/v1/chat/completions across the router, handler, service, CLI, and proxy layers, while rewriting think-tag streaming, removing legacy dialog and conversation APIs, and updating dataset metadata filtering for empty maps.

Changes

Chat completions and related routing changes

Layer / File(s) Summary
Think-tag state machine
internal/service/think_tag.go, internal/service/think_tag_test.go
Think-stream state, delta emission, flush handling, visible-answer extraction, and related tests use token-batched buffering and deferred close markers.
AsyncChat integration
internal/service/chat_pipeline.go
Async chat paths use the new think-tag state, answer buffering, visible-answer extraction, and KB content selection, with the fast-path KB check updated.
ChatCompletions service flow
internal/service/chat_session.go, internal/service/chat_session_test.go, internal/service/openai_chat.go, internal/service/dataset.go
Chat session completion handling adds the new stream/non-stream service method, structured response shaping, SSE formatting helpers, chunk normalization, related tests, chunk-field normalization updates, and the dataset metadata-empty-map check.
Legacy chat API removal
internal/service/chat.go, internal/handler/chat.go, internal/handler/chat_session.go, internal/router/router.go
Dialog, conversation, prompt-config, and older completion APIs are removed from the chat service, handler, and router wiring.
CLI chat-completions command
internal/cli/cli.go, internal/cli/cli_http.go, internal/cli/response.go, internal/cli/user_command.go, internal/cli/user_parser.go, internal/development.md
The CLI gains parser, dispatcher, help text, request building, streaming and non-streaming execution, response printing, endpoint text updates, and command documentation.
HTTP and proxy wiring
docker/nginx/ragflow.conf.hybrid, web/vite.config.ts, internal/router/router.go
The new chat-completions route is registered, the provider route path changes, and the Nginx and Vite hybrid proxy rules are updated for the new endpoint.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant CLI
  participant ChatSessionHandler
  participant ChatSessionService
  User->>CLI: chat completions
  CLI->>ChatSessionHandler: POST /api/v1/chat/completions
  ChatSessionHandler->>ChatSessionService: ChatCompletions(...)
  ChatSessionService-->>ChatSessionHandler: stream or structured response
  ChatSessionHandler-->>CLI: SSE or JSON
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • infiniflow/ragflow#15739: Also changes the internal/service/chat_session.go chat-completions path and related backend completion behavior.
  • infiniflow/ragflow#16157: Also modifies the chat management HTTP and service APIs in the same areas affected by the legacy endpoint removals.

Suggested reviewers

  • Haruko386

Poem

🐇 I hopped through routes, both old and new,
With chat-completions sparkling through.
Think-tags danced in token streams,
And CLI pages now dream new dreams.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: implementing chat completions in Go.
Description check ✅ Passed The description matches the required Summary section and states the new endpoint.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qinling0210
qinling0210 marked this pull request as ready for review June 30, 2026 08:23
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 30, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/service/chat_pipeline.go (1)

1048-1049: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Keep thinkState.fullText in sync with streamed answer text.

Line 1186 decorates from thinkState.fullText, but the tool path only appends to fullAnswer, and non-tool answer deltas only go through BufferAnswerDelta. This can make the final streamed answer empty for tool calls or missing the visible answer content for normal streams.

Proposed fix
 						text := *answerDelta
+						thinkState.fullText += text
 						fullAnswer += text
 						if isContentDelta(answer) {
+							thinkState.fullText += *answer
 							fullAnswer += *answer
 							if buffered := BufferAnswerDelta(thinkState, *answer, 16); buffered != "" {

Also applies to: 1135-1137, 1183-1186

🤖 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/chat_pipeline.go` around lines 1048 - 1049,
`thinkState.fullText` is not being updated alongside streamed answer chunks, so
the final decorated output can miss content for tool paths and normal streams.
Update the answer-delta handling in `chat_pipeline.go` around the `fullAnswer`
accumulation, the `BufferAnswerDelta` path, and the final decoration step so
`thinkState.fullText` stays synchronized with every streamed text append,
including tool-call output and regular answer deltas.
🧹 Nitpick comments (1)
internal/service/think_tag_test.go (1)

73-83: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add a split-tag chunk regression case.

The parser now operates incrementally, but this test only splits around complete tags. Add coverage for chunks like "<thi", "nk>reasoning</thi", "nk> answer" so marker detection is protected across arbitrary stream boundaries.

🤖 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/think_tag_test.go` around lines 73 - 83, Add a regression
test in TestNextThinkDelta for split-tag streaming chunks, since NextThinkDelta
and ThinkStreamState should detect markers across arbitrary boundaries. Extend
the existing incremental chunk coverage to include partial tag fragments like
"<thi", "nk>reasoning</thi", and "nk> answer", and assert the parser still
transitions correctly when the think tag is split across calls.
🤖 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/cli/response.go`:
- Around line 982-987: The lookup order in chunkContent currently prefers
content over content_with_weight, so the new weighted field never affects CLI
output when both are present. Update chunkContent to check content_with_weight
before content, keeping the existing trim-and-return behavior, so the weighted
value is used whenever available.

In `@internal/cli/user_command.go`:
- Around line 4233-4248: The generation-params block in user_command.go is
treating zero values as unset, so explicit inputs like temperature 0, top_p 0,
max_tokens 0, and zero penalties are being dropped before the request is built.
Update the handling in the command path around cmd.Params and the request body
assembly so presence is tracked separately from value, or store pointer/sentinel
values instead of plain scalars. Then in the body construction logic, emit each
field whenever the user supplied it, even if the value is zero, using the
existing request type’s pointer fields as the source of truth.
- Around line 4287-4340: The streaming handler in streamChatCompletions is
parsing the wrong SSE shape and using the buffered Request() path, so it never
extracts the server’s actual answer. Update streamChatCompletions to use the
streaming client path for /api/v1/chat/completions and parse the wrapper payload
fields (data.answer, not OpenAI-style choices[0].delta.content) from each SSE
chunk. Make sure the collected content is assigned to
ChatCompletionsResponse.Data so PrintOut() can display it instead of suppressing
an empty streamed response.

In `@internal/development.md`:
- Around line 188-193: The CHAT COMPLETIONS example in the docs is missing the
required chat identifier, which conflicts with what printChatCompletionsHelp()
says the server expects. Update the example shown in the RAGFlow(api/default)>
flow to include chat_id consistently with the help text, and make sure the
documentation references to chat_id match the actual required parameters used by
the chat completions command.

In `@internal/handler/chat_session.go`:
- Around line 107-108: The request parsing in ChatSession is dropping the legacy
pass_all_history alias before it can populate the bound field, so clients
sending pass_all_history still end up with a false value. Update the request
handling in the chat session flow to recognize pass_all_history as an alias for
PassAllHistoryMessages before removing keys from kwargs, and make sure the alias
is applied in the same path that preserves other known request keys. Use the
existing PassAllHistoryMessages and Legacy fields in the chat session request
struct and the related kwargs cleanup logic to keep both names working
consistently.
- Around line 140-143: The typed request decode in ChatSession handling is
silently ignoring malformed known fields, so update the request parsing around
ChatCompletionsRequest to treat the second decode as a real validation step. In
the handler that currently marshals rawBody and unmarshals into req, check and
return a 400 if json.Unmarshal into ChatCompletionsRequest fails, instead of
falling through with partially populated data. Keep the fix localized to the
chat session request binding path so fields like stream, messages, and
max_tokens are validated before continuing.

In `@internal/service/chat_pipeline.go`:
- Around line 1387-1423: The solo final-answer path in chat_pipeline.go is
building the final output from only the streamed visible pieces, so
marker-delimited thinking content can bleed into the answer. Update the logic
around the think-state handling and the final AsyncChatResult assembly to
accumulate every raw answer delta into thinkState.fullText, then derive the solo
final response with ExtractVisibleAnswer instead of relying on fullAnswer alone.
Make sure the same normalization is applied in the related final-result blocks
near the other referenced spots so the emitted final answer excludes any <think>
content consistently.

In `@internal/service/chat_session.go`:
- Around line 645-647: Session persistence errors are being swallowed in the
completion flow, so fix `createSessionForCompletion` to return and propagate DAO
`Create` failures instead of discarding them, and update `updateSessionMessages`
to return its DAO error as well. Then adjust the completion call sites
(including the paths around `createSessionForCompletion`,
`updateSessionMessages`, and the `UpdateByID` usage in `chat_session.go`) to
handle these errors and stop returning a successful session/answer when the DB
write fails.
- Around line 1113-1138: The marshalJSONWithSpaces helper in chat_session.go is
doing blind string replacement, so replaceColonNumber and the comma spacing
logic can mutate JSON string contents such as model text or URLs. Update
marshalJSONWithSpaces (and any related callers in the same area) to add spacing
only when outside quoted strings, or fall back to the compact json.Marshal
output if safe formatting is not needed. Preserve the existing JSON structure
while avoiding changes to literal string values.
- Around line 1154-1182: The sanitizeJSONFloats helper in chat_session.go only
recurses into []interface{}, so typed chunk slices from chunksFormat
([]map[string]interface{}) can still contain NaN/Inf values and fail during
marshaling. Update sanitizeJSONFloats to also handle []map[string]interface{}
(or otherwise sanitize the chunk slice returned by chunksFormat) so every nested
score/value is passed through the same float cleaning before json.Marshal.
- Around line 717-766: The SSE stream produced in chat_session.go is not
matching the CLI’s expected chat-completions shape, so streamed chunks are
ignored by internal/cli/user_command.go. Update the streaming branch in the
session answer flow (including the related final chunk path) so the emitted
payload uses the same structure the CLI reads, specifically the
choices[0].delta.content contract rather than only
{"code":0,"data":{"answer":...}}. Make the change in the chat session streaming
logic around structureAnswer/sseMarshalChunk so both live chunks and the final
streamed response are compatible with the CLI consumer.
- Around line 933-949: The session message payload is being written in one shape
and read in another, which can drop history on the next turn. Update
appendSessionMessage, appendAssistantToSession, and getSessionMessagesAsSlice to
use the same {"messages":[...]} structure everywhere, and ensure any persistence
path always serializes/deserializes that shape instead of a raw array or nil.

In `@internal/service/think_tag.go`:
- Around line 112-124: The chunk parsing in think_tag.go is only scanning the
current newPart, so split markers like "<thi" + "nk>" or "</thi" + "nk>" are
missed and end up as visible text. Update the tag parsing flow in the logic
around state.lastModelFull/state.fullText (including the pending handling in the
later emit path) to either keep a small carry buffer of incomplete tag prefixes
or parse from state.fullText with a cursor, so partial think/thinking tags
spanning arbitrary chunks are recognized and emitted correctly.
- Around line 64-76: The early return in emitText makes section == "think"
bypass batching, so tiny reasoning chunks are emitted immediately instead of
through thinkBuffer. Update emitText in ThinkStreamState to treat think text the
same way as answer text by appending it to the appropriate buffer and only
returning a delta once tokenizer.NumTokensFromString reaches minTokens. Keep the
existing answerBuffer behavior intact and use the same buffering logic for
think-tagged content so the streaming contract stays token-batched.

---

Outside diff comments:
In `@internal/service/chat_pipeline.go`:
- Around line 1048-1049: `thinkState.fullText` is not being updated alongside
streamed answer chunks, so the final decorated output can miss content for tool
paths and normal streams. Update the answer-delta handling in `chat_pipeline.go`
around the `fullAnswer` accumulation, the `BufferAnswerDelta` path, and the
final decoration step so `thinkState.fullText` stays synchronized with every
streamed text append, including tool-call output and regular answer deltas.

---

Nitpick comments:
In `@internal/service/think_tag_test.go`:
- Around line 73-83: Add a regression test in TestNextThinkDelta for split-tag
streaming chunks, since NextThinkDelta and ThinkStreamState should detect
markers across arbitrary boundaries. Extend the existing incremental chunk
coverage to include partial tag fragments like "<thi", "nk>reasoning</thi", and
"nk> answer", and assert the parser still transitions correctly when the think
tag is split across calls.
🪄 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: 9dacd89b-6c11-44b8-b34f-dc9e7a0989ba

📥 Commits

Reviewing files that changed from the base of the PR and between dc8b6d7 and 54a39f8.

📒 Files selected for processing (18)
  • docker/nginx/ragflow.conf.hybrid
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/response.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/development.md
  • internal/handler/chat.go
  • internal/handler/chat_session.go
  • internal/router/router.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/dataset.go
  • internal/service/think_tag.go
  • internal/service/think_tag_test.go
  • web/vite.config.ts
💤 Files with no reviewable changes (2)
  • internal/handler/chat.go
  • internal/service/chat.go

Comment thread internal/cli/response.go Resolved
Comment thread internal/cli/user_command.go Resolved
Comment thread internal/cli/user_command.go Resolved
Comment thread internal/development.md Resolved
Comment thread internal/handler/chat_session.go Resolved
Comment thread internal/service/chat_session.go Resolved
Comment thread internal/service/chat_session.go Resolved
Comment thread internal/service/chat_session.go Resolved
Comment thread internal/service/think_tag.go Resolved
Comment thread internal/service/think_tag.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 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/chat_session.go`:
- Around line 1037-1046: Move the final legacy SSE emission in chat_session.go
so the legacy answer chunk is sent before the done sentinel that wraps
`sseWrapper{Code: 0, Message: "", Data: true}`. Update the logic around the
`legacy` / `finalLegacyAnswer` branch in the streaming path to write the
`finalChunk` first, then emit the sentinel last, preserving the final
answer/reference for clients that stop reading at `data: {"data": true}`.
- Around line 1142-1149: The ownership check in checkDialogOwnership is using
CheckDialogExists with userID, but this path must be tenant-aware instead of
user-specific. Update checkDialogOwnership to reuse the same ownership helper
used by other session operations so access is validated through tenant
membership, and keep the authorization error behavior unchanged when no matching
tenant-scoped access exists.
- Around line 926-953: Initialize the completion config maps before writing into
them in ChatSession generation flow. In the LLM override branch, guard the
mutating writes to genConfig and dialog.LLMSetting by creating empty maps when
either is nil, so the assignments in the llmID path and the default-tenant path
do not panic. Update the logic around s.checkTenantLLMAPIKey, dialog.LLMSetting,
and genConfig so both are safe to merge into before any key assignment.
- Around line 1132-1137: The completion message flow in chat_session.go
generates a fallback messageID when the request message has no id, but that
generated value is only applied to the assistant side, leaving the user message
without a matching id. Update the logic around the message
normalization/completion path so the generated ID is also persisted onto the
user message before the pair is stored, ensuring DeleteSessionMessage can find
both halves by the same id. Use the existing requestMsg handling and messageID
assignment in the completion normalization code to locate and update the user
message payload consistently.
- Around line 1458-1460: The reference payload in chat session response assembly
is using the session-level `reference` array, which causes nested
`reference.chunks` objects instead of returning the latest answer’s chunk
objects directly. Update the response-building logic around `chat_session.go`’s
reference map construction so it pulls the latest answer reference data from the
answer-level structure rather than the per-session `reference` list, and keep
`chunks` flattened to the chunk objects clients expect.
🪄 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: ab8587b9-ff2a-4867-9ac6-93abc0553dd1

📥 Commits

Reviewing files that changed from the base of the PR and between 54a39f8 and 2062421.

📒 Files selected for processing (19)
  • docker/nginx/ragflow.conf.hybrid
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/response.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/development.md
  • internal/handler/chat.go
  • internal/handler/chat_session.go
  • internal/router/router.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/dataset.go
  • internal/service/openai_chat.go
  • internal/service/think_tag.go
  • internal/service/think_tag_test.go
  • web/vite.config.ts
💤 Files with no reviewable changes (1)
  • internal/service/chat.go
✅ Files skipped from review due to trivial changes (2)
  • internal/cli/cli.go
  • internal/development.md
🚧 Files skipped from review as they are similar to previous changes (13)
  • web/vite.config.ts
  • internal/cli/cli_http.go
  • docker/nginx/ragflow.conf.hybrid
  • internal/service/dataset.go
  • internal/cli/response.go
  • internal/service/think_tag_test.go
  • internal/service/chat_session_test.go
  • internal/router/router.go
  • internal/cli/user_command.go
  • internal/service/chat_pipeline.go
  • internal/cli/user_parser.go
  • internal/service/think_tag.go
  • internal/handler/chat_session.go

Comment thread internal/service/chat_session.go Resolved
Comment thread internal/service/chat_session.go Resolved
Comment thread internal/service/chat_session.go Resolved
Comment thread internal/service/chat_session.go Resolved
Comment thread internal/service/chat_session.go Resolved
@qinling0210 qinling0210 added the ci Continue Integration label Jun 30, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 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/handler/chat_session.go`:
- Around line 120-126: The Swagger annotation for chat completions currently
only advertises JSON, but ChatCompletionsRequest defaults to streaming and
ChatSession/handler responses can be SSE. Update the annotations on the chat
completion endpoint to document the streaming/non-streaming variants, including
the text/event-stream response type for the default stream=true path and the
JSON response for non-streaming, so generated clients infer the correct media
type from the handler.
- Around line 212-223: The streaming producer in ChatCompletions can block on
plain sends to streamChan after the client disconnects, which can leave the
goroutine stuck; update the send path to respect reqCtx cancellation or
otherwise stop production when c.Stream ends. Locate the goroutine around
ChatCompletions in chat_session.go and ensure the channel send/loop exits
promptly when the request context is done, so the producer does not hang after
CloseNotify.

In `@internal/service/think_tag.go`:
- Around line 162-183: The deferred-close handling in think_tag.go is stripping
tags too early, causing raw text after a pending </think> marker to be
misclassified. In the closePending branch of the think-state parser, update the
flow so the pending close is emitted first, then continue processing the
remaining raw tail without calling stripThinkTags on it; make sure the logic in
the closePending path and the later emitText/flushThinkBufferInternal sequence
preserves markers like </think>answer<think>more</think> for the parser to
consume in order.
- Around line 354-363: `ExtractVisibleAnswer` in `think_tag.go` is reattaching
the hidden reasoning when `thought != ""`, so it returns more than the visible
answer. Update the logic around `lastClose`, `thought`, and `answer` so the
function always returns only the text after the final `thinkClose` tag,
preserving the existing `stripThinkTags` cleanup but removing the branch that
prepends `thinkOpen`/`thinkClose` back onto the response.
🪄 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: 28a6280e-0f9e-4dfd-9fe0-6d90cfab3030

📥 Commits

Reviewing files that changed from the base of the PR and between 2062421 and be569c4.

📒 Files selected for processing (19)
  • docker/nginx/ragflow.conf.hybrid
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/response.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/development.md
  • internal/handler/chat.go
  • internal/handler/chat_session.go
  • internal/router/router.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/dataset.go
  • internal/service/openai_chat.go
  • internal/service/think_tag.go
  • internal/service/think_tag_test.go
  • web/vite.config.ts
💤 Files with no reviewable changes (2)
  • internal/handler/chat.go
  • internal/service/chat.go
✅ Files skipped from review due to trivial changes (2)
  • internal/cli/cli_http.go
  • docker/nginx/ragflow.conf.hybrid
🚧 Files skipped from review as they are similar to previous changes (12)
  • web/vite.config.ts
  • internal/service/openai_chat.go
  • internal/service/dataset.go
  • internal/cli/cli.go
  • internal/router/router.go
  • internal/cli/response.go
  • internal/service/chat_pipeline.go
  • internal/cli/user_parser.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/think_tag_test.go
  • internal/cli/user_command.go

Comment thread internal/handler/chat_session.go Resolved
Comment thread internal/handler/chat_session.go Resolved
Comment thread internal/service/think_tag.go Resolved
Comment thread internal/service/think_tag.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 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/think_tag.go`:
- Around line 350-361: `BufferAnswerDelta` currently only appends to
`state.answerBuffer`, which bypasses the think-state flow and can cause final
answer text and streamed ordering to be wrong. Update `BufferAnswerDelta` in
`think_tag.go` so answer deltas participate in the same lifecycle as
`NextThinkDelta`, including preserving/flush ordering with `fullText`,
`closePending`, and any pending `</think>` marker. Then adjust the `AsyncChat`
and `AsyncChatSolo` callers to forward the returned buffered text/markers
consistently with how they already handle `NextThinkDelta`, so final visible
output is assembled from the full state instead of only `answerBuffer`.
- Around line 222-249: The close-tag handling in think_tag.go should ignore
stray </think> markers when state.inThink is false instead of emitting a
ThinkDeltaMarker. Update the branch that processes pending text after finding
thinkClose so it only flushes buffers and appends the end marker when a real
think block is open; otherwise strip the unmatched close tag as non-visible
noise and continue. Use the existing state.inThink, flushThinkBufferInternal,
and ThinkDeltaMarker logic to keep matched pairs working while suppressing
unmatched closes.
🪄 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: 9ee4dbcf-3ac1-44c9-86de-743c3107e30f

📥 Commits

Reviewing files that changed from the base of the PR and between be569c4 and 3b67de8.

📒 Files selected for processing (19)
  • docker/nginx/ragflow.conf.hybrid
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/response.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/development.md
  • internal/handler/chat.go
  • internal/handler/chat_session.go
  • internal/router/router.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/dataset.go
  • internal/service/openai_chat.go
  • internal/service/think_tag.go
  • internal/service/think_tag_test.go
  • web/vite.config.ts
💤 Files with no reviewable changes (2)
  • internal/handler/chat.go
  • internal/service/chat.go
✅ Files skipped from review due to trivial changes (1)
  • internal/cli/cli.go
🚧 Files skipped from review as they are similar to previous changes (14)
  • internal/cli/cli_http.go
  • docker/nginx/ragflow.conf.hybrid
  • web/vite.config.ts
  • internal/service/openai_chat.go
  • internal/service/dataset.go
  • internal/router/router.go
  • internal/cli/user_parser.go
  • internal/cli/response.go
  • internal/service/think_tag_test.go
  • internal/service/chat_session_test.go
  • internal/cli/user_command.go
  • internal/service/chat_session.go
  • internal/handler/chat_session.go
  • internal/service/chat_pipeline.go

Comment on lines +222 to +249
// </think> appears first.
before := pending[:closeIdx]
after := pending[closeIdx+len(thinkClose):]
if before != "" {
piece := stripThinkTags(before)
section := "answer"
if state.inThink {
section = "think"
}
if out, kind := emitText(state, section, piece, minTokens); out != "" {
deltas = append(deltas, ThinkDelta{Kind: kind, Value: out})
}
}
if strings.TrimSpace(after) != "" {
if thinkPiece := flushThinkBufferInternal(state); thinkPiece.Value != "" {
deltas = append(deltas, thinkPiece)
}
deltas = append(deltas, ThinkDelta{Kind: ThinkDeltaMarker, Value: thinkClose})
state.postThinkText = newPart[:idx]
newPart = newPart[idx+len(thinkClose):]
state.lastIdx += idx + len(thinkClose)
state.inThink = false
deltas = append(deltas, ThinkDelta{Kind: ThinkDeltaMarker, Value: thinkClose})
pending = after
continue
}
// No visible text after close — defer the marker.
state.closePending = true
if after != "" {
state.pendingAfterClose += after
}
pending = ""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Ignore unmatched close tags instead of emitting EndToThink.

Line 235 can emit a </think> marker even when state.inThink is false. A stray close tag then produces an unmatched end marker instead of being stripped as non-visible tag noise.

Proposed fix
 		if before != "" {
 			piece := stripThinkTags(before)
 			section := "answer"
 			if state.inThink {
 				section = "think"
 			}
 			if out, kind := emitText(state, section, piece, minTokens); out != "" {
 				deltas = append(deltas, ThinkDelta{Kind: kind, Value: out})
 			}
 		}
+		if !state.inThink {
+			pending = after
+			continue
+		}
 		if strings.TrimSpace(after) != "" {
📝 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.

Suggested change
// </think> appears first.
before := pending[:closeIdx]
after := pending[closeIdx+len(thinkClose):]
if before != "" {
piece := stripThinkTags(before)
section := "answer"
if state.inThink {
section = "think"
}
if out, kind := emitText(state, section, piece, minTokens); out != "" {
deltas = append(deltas, ThinkDelta{Kind: kind, Value: out})
}
}
if strings.TrimSpace(after) != "" {
if thinkPiece := flushThinkBufferInternal(state); thinkPiece.Value != "" {
deltas = append(deltas, thinkPiece)
}
deltas = append(deltas, ThinkDelta{Kind: ThinkDeltaMarker, Value: thinkClose})
state.postThinkText = newPart[:idx]
newPart = newPart[idx+len(thinkClose):]
state.lastIdx += idx + len(thinkClose)
state.inThink = false
deltas = append(deltas, ThinkDelta{Kind: ThinkDeltaMarker, Value: thinkClose})
pending = after
continue
}
// No visible text after close — defer the marker.
state.closePending = true
if after != "" {
state.pendingAfterClose += after
}
pending = ""
// </think> appears first.
before := pending[:closeIdx]
after := pending[closeIdx+len(thinkClose):]
if before != "" {
piece := stripThinkTags(before)
section := "answer"
if state.inThink {
section = "think"
}
if out, kind := emitText(state, section, piece, minTokens); out != "" {
deltas = append(deltas, ThinkDelta{Kind: kind, Value: out})
}
}
if !state.inThink {
pending = after
continue
}
if strings.TrimSpace(after) != "" {
if thinkPiece := flushThinkBufferInternal(state); thinkPiece.Value != "" {
deltas = append(deltas, ThinkDelta{Kind: thinkPiece.Kind, Value: thinkPiece.Value})
}
state.inThink = false
deltas = append(deltas, ThinkDelta{Kind: ThinkDeltaMarker, Value: thinkClose})
pending = after
continue
}
// No visible text after close — defer the marker.
state.closePending = true
if after != "" {
state.pendingAfterClose += after
}
pending = ""
🤖 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/think_tag.go` around lines 222 - 249, The close-tag handling
in think_tag.go should ignore stray </think> markers when state.inThink is false
instead of emitting a ThinkDeltaMarker. Update the branch that processes pending
text after finding thinkClose so it only flushes buffers and appends the end
marker when a real think block is open; otherwise strip the unmatched close tag
as non-visible noise and continue. Use the existing state.inThink,
flushThinkBufferInternal, and ThinkDeltaMarker logic to keep matched pairs
working while suppressing unmatched closes.

Comment thread internal/service/think_tag.go Resolved
@codecov

codecov Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (9bf5760) to head (33fe96c).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16491   +/-   ##
=======================================
  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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@qinling0210
qinling0210 force-pushed the chat_go branch 2 times, most recently from c26ec35 to 1a8dc63 Compare July 1, 2026 05:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants