Repository navigation
Implement chat completions in go - #16491
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds ChangesChat completions and related routing changes
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
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested reviewers
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: 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 winKeep
thinkState.fullTextin sync with streamed answer text.Line 1186 decorates from
thinkState.fullText, but the tool path only appends tofullAnswer, and non-tool answer deltas only go throughBufferAnswerDelta. 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 += textif 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 winAdd 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
📒 Files selected for processing (18)
docker/nginx/ragflow.conf.hybridinternal/cli/cli.gointernal/cli/cli_http.gointernal/cli/response.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/development.mdinternal/handler/chat.gointernal/handler/chat_session.gointernal/router/router.gointernal/service/chat.gointernal/service/chat_pipeline.gointernal/service/chat_session.gointernal/service/chat_session_test.gointernal/service/dataset.gointernal/service/think_tag.gointernal/service/think_tag_test.goweb/vite.config.ts
💤 Files with no reviewable changes (2)
- internal/handler/chat.go
- internal/service/chat.go
There was a problem hiding this comment.
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
📒 Files selected for processing (19)
docker/nginx/ragflow.conf.hybridinternal/cli/cli.gointernal/cli/cli_http.gointernal/cli/response.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/development.mdinternal/handler/chat.gointernal/handler/chat_session.gointernal/router/router.gointernal/service/chat.gointernal/service/chat_pipeline.gointernal/service/chat_session.gointernal/service/chat_session_test.gointernal/service/dataset.gointernal/service/openai_chat.gointernal/service/think_tag.gointernal/service/think_tag_test.goweb/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
There was a problem hiding this comment.
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
📒 Files selected for processing (19)
docker/nginx/ragflow.conf.hybridinternal/cli/cli.gointernal/cli/cli_http.gointernal/cli/response.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/development.mdinternal/handler/chat.gointernal/handler/chat_session.gointernal/router/router.gointernal/service/chat.gointernal/service/chat_pipeline.gointernal/service/chat_session.gointernal/service/chat_session_test.gointernal/service/dataset.gointernal/service/openai_chat.gointernal/service/think_tag.gointernal/service/think_tag_test.goweb/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
There was a problem hiding this comment.
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
📒 Files selected for processing (19)
docker/nginx/ragflow.conf.hybridinternal/cli/cli.gointernal/cli/cli_http.gointernal/cli/response.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/development.mdinternal/handler/chat.gointernal/handler/chat_session.gointernal/router/router.gointernal/service/chat.gointernal/service/chat_pipeline.gointernal/service/chat_session.gointernal/service/chat_session_test.gointernal/service/dataset.gointernal/service/openai_chat.gointernal/service/think_tag.gointernal/service/think_tag_test.goweb/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
| // </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 = "" |
There was a problem hiding this comment.
🎯 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.
| // </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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
c26ec35 to
1a8dc63
Compare
Summary
POST /api/v1/chat/completions