Skip to content

Commit c5a9420

Browse files
committed
fix: preserve reasoning_details for multi-turn continuity
1 parent bb6bf3c commit c5a9420

2 files changed

Lines changed: 143 additions & 22 deletions

File tree

backend/open_webui/utils/middleware.py

Lines changed: 117 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,35 @@ def split_json_objects(raw: str) -> list[str]:
203203
return expanded
204204

205205

206+
def _merge_reasoning_details(details: list, chunk: object) -> None:
207+
"""Merge reasoning_details delta items into a list in-place.
208+
209+
Items sharing an integer index are merged: text and summary deltas
210+
concatenate when string-valued, other fields overwrite with the latest
211+
delta. Items without a usable index are appended in arrival order.
212+
"""
213+
items = chunk if isinstance(chunk, list) else ([chunk] if isinstance(chunk, dict) else [])
214+
for item in items:
215+
if not isinstance(item, dict):
216+
continue
217+
idx = item.get('index')
218+
existing = None
219+
if isinstance(idx, int) and idx >= 0:
220+
existing = next((e for e in details if e.get('index') == idx), None)
221+
if existing is None:
222+
new_entry = dict(item)
223+
new_entry.setdefault('type', 'reasoning.text')
224+
details.append(new_entry)
225+
continue
226+
for k, v in item.items():
227+
if k in ('text', 'summary'):
228+
if isinstance(v, str):
229+
base = existing.get(k)
230+
existing[k] = (base + v) if isinstance(base, str) else v
231+
else:
232+
existing[k] = v
233+
234+
206235
def get_citation_source_from_tool_result(
207236
tool_name: str, tool_params: dict, tool_result: str, tool_id: str = ''
208237
) -> list[dict]:
@@ -507,6 +536,8 @@ def serialize_output(output: list) -> str:
507536
pass
508537

509538
reasoning_content = ''.join(reasoning_parts).strip()
539+
if not reasoning_content:
540+
continue # no displayable text; item stays in output for round-trip
510541

511542
duration = item.get('duration')
512543
status = item.get('status', 'in_progress')
@@ -3441,15 +3472,43 @@ async def non_streaming_chat_response_handler(response, ctx):
34413472
# otherwise generate from response content
34423473
response_output = response_data.get('output')
34433474
if not response_output:
3444-
response_output = [
3475+
message_obj = choices[0].get('message', {})
3476+
reasoning_text = (
3477+
message_obj.get('reasoning_content')
3478+
or message_obj.get('reasoning')
3479+
)
3480+
reasoning_details = message_obj.get('reasoning_details')
3481+
3482+
response_output = []
3483+
3484+
if reasoning_text or reasoning_details:
3485+
r_item = {
3486+
'type': 'reasoning',
3487+
'id': output_id('r'),
3488+
'status': 'completed',
3489+
'start_tag': '<think>',
3490+
'end_tag': '</think>',
3491+
'attributes': {'type': 'reasoning_content'},
3492+
'content': [{'type': 'output_text', 'text': reasoning_text}] if reasoning_text else [],
3493+
'summary': None,
3494+
}
3495+
if reasoning_details:
3496+
r_item['reasoning_details'] = (
3497+
reasoning_details
3498+
if isinstance(reasoning_details, list)
3499+
else [reasoning_details]
3500+
)
3501+
response_output.append(r_item)
3502+
3503+
response_output.append(
34453504
{
34463505
'type': 'message',
34473506
'id': output_id('msg'),
34483507
'status': 'completed',
34493508
'role': 'assistant',
34503509
'content': [{'type': 'output_text', 'text': content}],
34513510
}
3452-
]
3511+
)
34533512

34543513
await event_emitter(
34553514
{
@@ -3814,6 +3873,7 @@ def set_last_text(out, text):
38143873
]
38153874
else:
38163875
output = []
3876+
_pending_reasoning_details = []
38173877

38183878
usage = None
38193879
prior_output = []
@@ -4162,9 +4222,14 @@ async def flush_pending_delta_data(threshold: int = 0):
41624222
or delta.get('reasoning')
41634223
or delta.get('thinking')
41644224
)
4225+
reasoning_details_chunk = delta.get('reasoning_details')
4226+
4227+
# Only create a reasoning item for visible reasoning text.
4228+
# Details-only deltas (e.g. Gemini encrypted blobs) are
4229+
# buffered to avoid splitting the assistant message mid-stream.
41654230
if reasoning_content:
41664231
if not output or output[-1].get('type') != 'reasoning':
4167-
reasoning_item = {
4232+
output.append({
41684233
'type': 'reasoning',
41694234
'id': output_id('r'),
41704235
'status': 'in_progress',
@@ -4174,23 +4239,37 @@ async def flush_pending_delta_data(threshold: int = 0):
41744239
'content': [],
41754240
'summary': None,
41764241
'started_at': time.time(),
4177-
}
4178-
output.append(reasoning_item)
4179-
else:
4180-
reasoning_item = output[-1]
4242+
})
41814243

4182-
# Append to reasoning content
4244+
if reasoning_content:
4245+
reasoning_item = output[-1]
41834246
parts = reasoning_item.get('content', [])
41844247
if parts and parts[-1].get('type') == 'output_text':
41854248
parts[-1]['text'] += reasoning_content
41864249
else:
4187-
reasoning_item['content'] = [
4188-
{
4189-
'type': 'output_text',
4190-
'text': reasoning_content,
4191-
}
4192-
]
4250+
reasoning_item['content'] = [{'type': 'output_text', 'text': reasoning_content}]
41934251

4252+
# Flush any buffered details-only chunks into this reasoning item.
4253+
if _pending_reasoning_details:
4254+
_merge_reasoning_details(
4255+
reasoning_item.setdefault('reasoning_details', []),
4256+
_pending_reasoning_details,
4257+
)
4258+
_pending_reasoning_details.clear()
4259+
4260+
# Accumulate raw structured reasoning_details for provider round-trip.
4261+
if reasoning_details_chunk:
4262+
if output and output[-1].get('type') == 'reasoning':
4263+
_merge_reasoning_details(
4264+
output[-1].setdefault('reasoning_details', []),
4265+
reasoning_details_chunk,
4266+
)
4267+
else:
4268+
# Buffer until a safe boundary (end-of-stream or real reasoning text).
4269+
items = reasoning_details_chunk if isinstance(reasoning_details_chunk, list) else [reasoning_details_chunk]
4270+
_pending_reasoning_details.extend(items)
4271+
4272+
if reasoning_content or reasoning_details_chunk:
41944273
data = {'content': serialize_output(full_output())}
41954274

41964275
if value:
@@ -4404,6 +4483,30 @@ async def flush_pending_delta_data(threshold: int = 0):
44044483
)
44054484
reasoning_item['status'] = 'completed'
44064485

4486+
# Flush any buffered reasoning_details that never found a reasoning item.
4487+
if _pending_reasoning_details:
4488+
target = next((item for item in output if item.get('type') == 'reasoning'), None)
4489+
if target is None:
4490+
target = {
4491+
'type': 'reasoning',
4492+
'id': output_id('r'),
4493+
'status': 'completed',
4494+
'start_tag': '<think>',
4495+
'end_tag': '</think>',
4496+
'attributes': {'type': 'reasoning_content'},
4497+
'content': [],
4498+
'summary': None,
4499+
'started_at': time.time(),
4500+
'ended_at': time.time(),
4501+
'duration': 0,
4502+
}
4503+
output.insert(0, target)
4504+
_merge_reasoning_details(
4505+
target.setdefault('reasoning_details', []),
4506+
_pending_reasoning_details,
4507+
)
4508+
_pending_reasoning_details.clear()
4509+
44074510
if response_tool_calls:
44084511
tool_calls.append(_split_tool_calls(response_tool_calls))
44094512

backend/open_webui/utils/misc.py

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -218,10 +218,11 @@ def convert_output_to_messages(
218218
pending_tool_calls = []
219219
pending_content = []
220220
pending_reasoning = [] # Only populated when reasoning_format == 'reasoning_content'
221+
pending_reasoning_details = None
221222

222223
def flush_pending():
223-
nonlocal pending_content, pending_tool_calls, pending_reasoning
224-
if not pending_content and not pending_tool_calls and not pending_reasoning:
224+
nonlocal pending_content, pending_tool_calls, pending_reasoning, pending_reasoning_details
225+
if not pending_content and not pending_tool_calls and not pending_reasoning and not pending_reasoning_details:
225226
return
226227

227228
message = {
@@ -233,10 +234,14 @@ def flush_pending():
233234
if pending_reasoning:
234235
message['reasoning_content'] = '\n'.join(pending_reasoning)
235236

237+
if pending_reasoning_details:
238+
message['reasoning_details'] = pending_reasoning_details
239+
236240
messages.append(message)
237241
pending_content = []
238242
pending_tool_calls = []
239243
pending_reasoning = []
244+
pending_reasoning_details = None
240245

241246
for item in output:
242247
item_type = item.get('type', '')
@@ -307,7 +312,7 @@ def flush_pending():
307312
)
308313

309314
elif item_type == 'reasoning':
310-
if not reasoning_format:
315+
if not raw:
311316
continue
312317

313318
reasoning_text = ''
@@ -318,15 +323,28 @@ def flush_pending():
318323
elif 'text' in part:
319324
reasoning_text += part.get('text', '')
320325

326+
raw_details = item.get('reasoning_details')
327+
321328
if reasoning_text:
322-
if reasoning_format == 'think_tags':
323-
# Ollama: embed in content with the item's original tags
329+
if reasoning_format == 'reasoning_content':
330+
# llama.cpp: collect for reasoning_content field
331+
pending_reasoning.append(reasoning_text)
332+
elif not raw_details:
333+
# Wrap reasoning in <think> tags for Ollama and any
334+
# provider that lacks structured reasoning_details.
324335
start_tag = item.get('start_tag', '<think>')
325336
end_tag = item.get('end_tag', '</think>')
326337
pending_content.append(f'{start_tag}{reasoning_text}{end_tag}')
327-
elif reasoning_format == 'reasoning_content':
328-
# llama.cpp: collect for reasoning_content field
329-
pending_reasoning.append(reasoning_text)
338+
339+
# Preserve raw structured reasoning_details for provider round-trip
340+
if raw_details:
341+
if pending_reasoning_details is None:
342+
pending_reasoning_details = list(raw_details) if isinstance(raw_details, list) else [raw_details]
343+
elif isinstance(pending_reasoning_details, list):
344+
if isinstance(raw_details, list):
345+
pending_reasoning_details.extend(raw_details)
346+
else:
347+
pending_reasoning_details.append(raw_details)
330348

331349
elif item_type == 'open_webui:code_interpreter':
332350
# Always include code interpreter content so the LLM knows

0 commit comments

Comments
 (0)