Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(mcp): summarize documents through chat completions (#1037)
Krisztian Gajdar93fe32bc1bfd
diff --git a/packages/sie_mcp/src/sie_mcp/offload.py b/packages/sie_mcp/src/sie_mcp/offload.pyindex f4ca60307..6b6bfeafc 100644--- a/packages/sie_mcp/src/sie_mcp/offload.py+++ b/packages/sie_mcp/src/sie_mcp/offload.py@@ -135,27 +135,15 @@ async def summarize_document(reduction_rounds = 0if len(chunks) == 1:- result = await client.generate(- model,- _SINGLE_PROMPT.format(text=chunks[0]),- max_new_tokens=reduce_tokens,- gpu=gpu,- wait_for_capacity=True,- provision_timeout_s=REQUEST_TIMEOUT_S,+ summary = await _complete(+ client, model, _SINGLE_PROMPT.format(text=chunks[0]), max_tokens=reduce_tokens, gpu=gpu)- summary = _generated_text(result)else:summaries: list[str] = []for chunk in chunks:- result = await client.generate(- model,- _MAP_PROMPT.format(chunk=chunk),- max_new_tokens=map_tokens,- gpu=gpu,- wait_for_capacity=True,- provision_timeout_s=REQUEST_TIMEOUT_S,+ summaries.append(+ await _complete(client, model, _MAP_PROMPT.format(chunk=chunk), max_tokens=map_tokens, gpu=gpu))- summaries.append(_generated_text(result))summary, reduce_calls, reduction_rounds = await _reduce_summaries(client,summaries,@@ -205,16 +193,10 @@ async def _reduce_summaries(next_round.append(batch[0])continueparts = "\n\n".join(f"## Section {i}\n{part}" for i, part in enumerate(batch, start=1))- result = await client.generate(- model,- _REDUCE_PROMPT.format(parts=parts),- max_new_tokens=max_new_tokens,- gpu=gpu,- wait_for_capacity=True,- provision_timeout_s=REQUEST_TIMEOUT_S,+ next_round.append(+ await _complete(client, model, _REDUCE_PROMPT.format(parts=parts), max_tokens=max_new_tokens, gpu=gpu))reduce_calls += 1- next_round.append(_generated_text(result))if len(next_round) >= len(current):raise OffloadError("summary reduction did not make progress")current = next_round@@ -225,11 +207,30 @@ def _batches(items: Sequence[str], batch_size: int) -> list[list[str]]:return [list(items[index : index + batch_size]) for index in range(0, len(items), batch_size)]-def _generated_text(result: Mapping[str, Any]) -> str:- text = result.get("text")- if not isinstance(text, str):+async def _complete(client: Any, model: str, prompt: str, *, max_tokens: int, gpu: str | None) -> str:+ """Run one summary prompt as a chat completion and return the answer text.++ The chat route renders the model's chat template, so the instruction is a+ user turn and the profile's template settings apply (Qwen3.5's+ ``enable_thinking: false``). A native ``/v1/generate`` text prompt skips the+ template: an instruction-tuned model may continue the text instead of+ answering it, or spend tokens on reasoning that is never returned.+ """+ response = await client.chat_completions(+ model,+ [{"role": "user", "content": prompt}],+ max_completion_tokens=max_tokens,+ gpu=gpu,+ wait_for_capacity=True,+ provision_timeout_s=REQUEST_TIMEOUT_S,+ )+ choices = response.get("choices") if isinstance(response, Mapping) else None+ first = choices[0] if isinstance(choices, Sequence) and choices else None+ message = first.get("message") if isinstance(first, Mapping) else None+ content = message.get("content") if isinstance(message, Mapping) else None+ if not isinstance(content, str):raise OffloadError("generation result did not include text")- return text+ return contentdef _extract_windows(content: str, window_words: int, overlap_words: int) -> list[tuple[int, str]]:diff --git a/packages/sie_mcp/tests/test_offload.py b/packages/sie_mcp/tests/test_offload.pyindex ca405d1f1..56389df80 100644--- a/packages/sie_mcp/tests/test_offload.py+++ b/packages/sie_mcp/tests/test_offload.py@@ -18,12 +18,14 @@ _FILLER = "The committee reviewed the figures, then adjourned. " # 9 GLiNER worclass _FakeOffloadClient:def __init__(self) -> None:- self.generate_calls: list[dict[str, Any]] = []+ self.chat_calls: list[dict[str, Any]] = []self.extract_calls: list[dict[str, Any]] = []- async def generate(self, model: str, prompt: str, **kwargs: Any) -> dict[str, str]:- self.generate_calls.append({"model": model, "prompt": prompt, **kwargs})- return {"text": f"summary {len(self.generate_calls)}"}+ async def chat_completions(self, model: str, messages: list[dict[str, str]], **kwargs: Any) -> dict[str, Any]:+ (message,) = messages+ assert message["role"] == "user"+ self.chat_calls.append({"model": model, "prompt": message["content"], **kwargs})+ return {"choices": [{"message": {"role": "assistant", "content": f"summary {len(self.chat_calls)}"}}]}async def extract(self, model: str, items: Any, **kwargs: Any) -> Any:self.extract_calls.append({"model": model, "items": items, **kwargs})@@ -75,8 +77,8 @@ async def test_summarize_document_uses_map_reduce_for_large_content() -> None:assert result["summary"] == "summary 3"assert result["metadata"]["chunks"] == 2assert result["metadata"]["token_savings_estimate"] > 0- assert [call["model"] for call in client.generate_calls] == ["gen", "gen", "gen"]- assert all(call["gpu"] == "l4" for call in client.generate_calls)+ assert [call["model"] for call in client.chat_calls] == ["gen", "gen", "gen"]+ assert all(call["gpu"] == "l4" for call in client.chat_calls)async def test_summarize_document_reduces_many_chunks_hierarchically() -> None:@@ -91,15 +93,45 @@ async def test_summarize_document_reduces_many_chunks_hierarchically() -> None:max_output_tokens=128,)- reduce_prompts = [call["prompt"] for call in client.generate_calls if "SECTION SUMMARIES:" in call["prompt"]]+ reduce_prompts = [call["prompt"] for call in client.chat_calls if "SECTION SUMMARIES:" in call["prompt"]]assert result["metadata"]["chunks"] == chunk_countassert result["metadata"]["reduce_calls"] == 2assert result["metadata"]["reduction_rounds"] == 2assert result["summary"] == f"summary {chunk_count + 2}"- assert len(client.generate_calls) == chunk_count + 2+ assert len(client.chat_calls) == chunk_count + 2assert all(prompt.count("## Section") <= offload.SUMMARY_REDUCE_BATCH_SIZE for prompt in reduce_prompts)+async def test_summarize_document_sends_each_prompt_as_a_capped_chat_completion() -> None:+ client = _FakeOffloadClient()++ result = await offload.summarize_document(client, content="Alice met Bob.", model="gen", max_output_tokens=96)++ (call,) = client.chat_calls+ assert result["summary"] == "summary 1"+ assert "Alice met Bob." in call["prompt"]+ assert call["max_completion_tokens"] == 96+ assert call["wait_for_capacity"] is True+ assert call["provision_timeout_s"] == offload.REQUEST_TIMEOUT_S+++ "response",+ [+ {"choices": []},+ {"choices": [{"message": {"role": "assistant", "content": None}}]},+ {"choices": [{"message": {"role": "assistant", "content": " "}}]},+ ],+)+async def test_summarize_document_refuses_a_completion_without_answer_text(response: dict[str, Any]) -> None:+ class _NoAnswerClient(_FakeOffloadClient):+ async def chat_completions(self, model: str, messages: list[dict[str, str]], **kwargs: Any) -> dict[str, Any]:+ return response++ with pytest.raises(offload.OffloadError):+ await offload.summarize_document(_NoAnswerClient(), content="Alice met Bob.", model="gen")++async def test_extract_entities_returns_entities_and_markdown_table() -> None:client = _FakeOffloadClient()