You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
LCORE-1675: Documentation for conversation compaction
Document the conversation compaction feature across OpenAPI spec,
configuration guide, architecture overview, and query endpoint docs.
Add context_status field ("full"/"summarized") to QueryResponse and
StreamingQueryResponse documentation. Create comprehensive user guide
at docs/user_doc/conversation_compaction.md with configuration
examples, behavior details, and FAQ.
**Purpose:** Automatically summarize older conversation turns when the conversation history approaches the LLM's context window limit, preventing HTTP 413 failures and enabling arbitrarily long conversations.
376
+
377
+
**Design Philosophy (Option A):** Once compaction triggers, LCore takes ownership of the context sent to the LLM. The `conversation` parameter is dropped from the OGX call (`omit_conversation=True`), and LCore constructs the input explicitly from summaries + recent turns + new query. The full original history remains in OGX for auditing.
-`partition_conversation()` — Splits conversation items into old and recent chunks using a *degrading guard*: starts with the configured `buffer_turns` and shrinks one pair at a time until the recent chunk fits the token budget
385
+
-`summarize_chunk()` — Single LLM call to produce a `ConversationSummary` from older turns
386
+
-`recursively_resummarize()` — Folds multiple accumulated summaries into one when they approach the context limit
387
+
388
+
2.**Runtime Integration Layer** (`utils/conversation_compaction.py`) — Manages side effects:
389
+
- Per-conversation locking (serializes concurrent requests on the same conversation)
390
+
- Compaction state loading (cache-preferred with marker fallback)
391
+
- Marker persistence (`[lightspeed:compaction-summary]` sentinel in conversation items)
392
+
-`CompactionStartedEvent` emission for streaming progress indicators
393
+
-`apply_compaction()` (async generator) — Main entry point used by all endpoints
394
+
-`store_compacted_turn()` — Appends user query + LLM output when in compacted mode
-`buffer_max_ratio` (default: `0.3`) — Max fraction of window for the buffer
443
+
444
+
Models must have context windows registered via `inference.context_windows` (a map of model ID to token count).
445
+
446
+
**Concurrency:** A per-conversation lock dictionary serializes concurrent compaction requests on the same conversation. Lock entries are reference-counted and cleaned up when the last waiter exits.
447
+
448
+
---
449
+
373
450
## 3. Request Processing Pipeline
374
451
375
452
This section illustrates how requests flow through LCore from initial receipt to final response.
@@ -400,11 +477,12 @@ Here's how a real query flows through the system:
400
477
5.**Model Selection** - Use configured default model (e.g., `meta-llama/Llama-3.1-8B-Instruct`)
401
478
6.**Context Building** - Retrieve conversation history, query RAG vector stores for relevant docs, determine available MCP tools
402
479
7.**Shield moderation** - LCore-owned direct-run moderation (and agent capabilities where applicable) using shields configured in LCORE config
403
-
8.**Llama Stack / agent call** - Send request with system prompt, RAG context, and MCP tools
10.**Post-Processing** - Generate conversation summary if new
406
-
11.**Store Results** - Save to Cache DB, User DB, consume quota, update metrics
407
-
12.**Return Response** - Complete LLM response with referenced documents, token usage, and remaining quota
480
+
8.**Conversation compaction** - If enabled and estimated tokens exceed the threshold, summarize older turns and rebuild the context (see [Section 2.11](#211-conversation-compaction-utilscompactionpy-utilsconversation_compactionpy))
481
+
9.**OGX / agent call** - Send request with system prompt, RAG context, and MCP tools
Copy file name to clipboardExpand all lines: docs/devel_doc/openapi.md
+3-2Lines changed: 3 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2738,7 +2738,7 @@ user's query to a selected Llama Stack LLM and returning the generated response.
2738
2738
- mcp_headers: Headers that should be passed to MCP servers.
2739
2739
2740
2740
### Returns:
2741
-
- QueryResponse: Contains the conversation ID and the LLM-generated response.
2741
+
- QueryResponse: Contains the conversation ID, the LLM-generated response, and a `context_status` field indicating whether the conversation context is `"full"` or `"summarized"`.
2742
2742
2743
2743
### Raises:
2744
2744
- HTTPException:
@@ -3021,7 +3021,7 @@ content type text/event-stream.
3021
3021
- mcp_headers: Headers that should be passed to MCP servers.
3022
3022
3023
3023
### Returns:
3024
-
- SSE-formatted events for the query lifecycle.
3024
+
- SSE-formatted events for the query lifecycle. Includes a `context_status` field (`"full"` or `"summarized"`) in the `end` event payload indicating whether conversation compaction was applied. When compaction is triggered, a `compaction` SSE event is emitted before inference begins.
3025
3025
3026
3026
### Raises:
3027
3027
- HTTPException:
@@ -8010,6 +8010,7 @@ Attributes:
8010
8010
| available_quotas | object | Quota available as measured by all configured quota limiters |
8011
8011
| tool_calls | array | List of tool calls made during response generation |
8012
8012
| tool_results | array | List of tool results |
8013
+
| context_status | string | Indicates whether the conversation context sent to the LLM is `"full"` (complete history) or `"summarized"` (older turns were summarized). Only present in QueryResponse and StreamingQueryResponse; omitted from `/v1/responses` (OpenAI-compatible) and `/a2a` responses. |
|`context_status`| string |`"full"`| Whether the conversation context is `"full"` (complete history) or `"summarized"` (older turns were summarized via conversation compaction) |
148
149
149
150
**`referenced_documents` items:**
150
151
@@ -242,7 +243,7 @@ Emitted when the full response is assembled.
242
243
243
244
#### 7. `end`
244
245
245
-
Emitted last on success. Contains metadata.
246
+
Emitted last on success. Contains metadata including `context_status` (`"full"` or `"summarized"`).
246
247
247
248
```json
248
249
{
@@ -251,7 +252,8 @@ Emitted last on success. Contains metadata.
251
252
"referenced_documents": [],
252
253
"truncated": null,
253
254
"input_tokens": 11,
254
-
"output_tokens": 19
255
+
"output_tokens": 19,
256
+
"context_status": "full"
255
257
},
256
258
"available_quotas": {"UserQuotaLimiter": 998911}
257
259
}
@@ -327,9 +329,9 @@ Both endpoints share the same pre-processing pipeline:
327
329
11. Prepare Responses API parameters (model, system prompt, tools, MCP headers)
328
330
12. Extract image attachments separately for multimodal input construction
**`/v1/query` then:** applies conversation compaction (blocking), calls the LLM, generates topic summary, consumes tokens, stores results, returns JSON. When compaction is applied, the response includes `context_status: "summarized"`; otherwise `context_status: "full"`.
331
333
332
-
**`/v1/streaming_query` then:** generates a `request_id`, starts the SSE stream, emits events as the LLM generates tokens, performs post-stream cleanup (topic summary, token consumption, persistence).
334
+
**`/v1/streaming_query` then:** generates a `request_id`, starts the SSE stream, applies compaction if needed (emitting a `compaction` SSE event), emits events as the LLM generates tokens, performs post-stream cleanup (topic summary, token consumption, persistence). The `end` event includes `context_status` indicating whether compaction was applied.
333
335
334
336
---
335
337
@@ -409,7 +411,8 @@ curl -X POST http://localhost:8090/v1/query \
Copy file name to clipboardExpand all lines: docs/user_doc/config.md
+45Lines changed: 45 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -224,6 +224,51 @@ Attributes:
224
224
| buffer_turns | integer | Number of recent turns to keep verbatim. |
225
225
| buffer_max_ratio | number | Maximum fraction of context window the buffer zone can occupy, regardless of buffer_turns. |
226
226
227
+
### How to enable conversation compaction
228
+
229
+
Compaction is disabled by default. To enable it, add a `compaction` section to your `lightspeed-stack.yaml` and set `enabled: true`. You must also register context window sizes for the models you use via the `inference.context_windows` map so the compaction trigger can calculate when older turns should be summarized.
230
+
231
+
**Minimal configuration:**
232
+
233
+
```yaml
234
+
inference:
235
+
default_provider: openai
236
+
default_model: gpt-4o-mini
237
+
context_windows:
238
+
openai/gpt-4o-mini: 128000
239
+
240
+
compaction:
241
+
enabled: true
242
+
```
243
+
244
+
**Full configuration with all options:**
245
+
246
+
```yaml
247
+
inference:
248
+
default_provider: openai
249
+
default_model: gpt-4o-mini
250
+
context_windows:
251
+
openai/gpt-4o-mini: 128000
252
+
openai/gpt-4o: 128000
253
+
254
+
compaction:
255
+
enabled: true
256
+
threshold_ratio: 0.7# trigger at 70% of context window (default)
257
+
token_floor: 4096# minimum tokens before compaction can fire (default)
buffer_max_ratio: 0.3# buffer may use at most 30% of the window (default)
260
+
```
261
+
262
+
**Key considerations:**
263
+
264
+
- `context_windows` is required. Models absent from this map have no registered window and compaction will not trigger for them.
265
+
- `threshold_ratio`controls how aggressively compaction fires. Lower values compact sooner; higher values wait longer (closer to the window limit).
266
+
- `buffer_turns`sets how many recent user/assistant turn pairs are kept in full. A degrading guard automatically reduces this if the buffer itself would exceed `buffer_max_ratio` of the window.
267
+
- `token_floor`prevents compaction from triggering on very short conversations.
268
+
- When compaction is disabled (the default), requests that exceed the context window surface as HTTP 413.
269
+
270
+
For a comprehensive explanation of the feature, see the [Conversation Compaction Guide](conversation_compaction.md).
0 commit comments