unique_toolkit 2026.44.0.dev3__py3-none-any.whl → 2026.44.0.dev5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,264 @@
1
+ """Keep agent-loop prompts inside the provider's context window.
2
+
3
+ The local reducer estimates tokens with an OpenAI tokenizer, which can undercount
4
+ other providers by 2x or more. ``ContextOverflowGuard`` verifies near-limit
5
+ payloads with the provider's own counter before the LLM call and recovers when the
6
+ provider still rejects a prompt as too long.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import time
13
+ from collections.abc import Awaitable, Callable
14
+ from logging import Logger
15
+ from typing import Any, TypeVar
16
+
17
+ from unique_toolkit.agentic.history_manager.history_manager import HistoryManager
18
+ from unique_toolkit.agentic.loop_runner.base import _LoopIterationRunnerKwargs
19
+ from unique_toolkit.language_model.infos import LanguageModelInfo
20
+ from unique_toolkit.language_model.settings import ModelFamily
21
+ from unique_toolkit.protocols.support import SupportsTokenCount
22
+
23
+ _T = TypeVar("_T")
24
+
25
+ _CONTEXT_OVERFLOW_SIGNALS = (
26
+ "context_length_exceeded",
27
+ "contextwindowexceedederror",
28
+ "tokenlimitexceeded",
29
+ "maximum context length",
30
+ "prompt is too long",
31
+ "input is too long",
32
+ "too many input tokens",
33
+ "exceeds the maximum number of tokens",
34
+ )
35
+ _CONTEXT_WINDOW_QUALIFIERS = ("exceed", "too long", "maximum")
36
+
37
+ CONTEXT_OVERFLOW_TOKEN_BUDGET_FACTOR = 0.7
38
+ PROVIDER_COUNT_TARGET_RATIO = 0.95
39
+ MAX_PROVIDER_OVERFLOW_REDUCTION_FACTOR = 0.9
40
+ APPROXIMATE_TOKENIZER_TRIGGER_RATIO = 0.7
41
+ NATIVE_TOKENIZER_TRIGGER_RATIO = 0.85
42
+ LOCAL_LIMIT_TRIGGER_RATIO = 0.95
43
+ DEFAULT_OUTPUT_TOKEN_RESERVE = 10_000
44
+ PROVIDER_TOKEN_COUNT_TIMEOUT_SECONDS = 10
45
+
46
+ _NATIVE_TOKENIZER_FAMILIES = {
47
+ ModelFamily.OPENAI,
48
+ ModelFamily.DEEPSEEK,
49
+ ModelFamily.QWEN,
50
+ }
51
+
52
+ WITHHELD_TOOL_RESULT_NOTICE = (
53
+ "The combined output of the tool calls made in this step was too large for "
54
+ "the model's context window, so this result was withheld. Do not repeat "
55
+ "these tool calls in parallel. Call them one at a time instead, and narrow "
56
+ "each call (for example a lower result limit, a shorter date range or a "
57
+ "more specific query) so that each result stays small."
58
+ )
59
+
60
+
61
+ def is_context_window_exceeded_error(exc: BaseException) -> bool:
62
+ """Return True if *exc* indicates the prompt exceeded the model's context window."""
63
+ error_text = f"{type(exc).__name__} {exc}".lower()
64
+ if any(signal in error_text for signal in _CONTEXT_OVERFLOW_SIGNALS):
65
+ return True
66
+ return "context window" in error_text and any(
67
+ qualifier in error_text for qualifier in _CONTEXT_WINDOW_QUALIFIERS
68
+ )
69
+
70
+
71
+ def supports_provider_token_count(model: LanguageModelInfo) -> bool:
72
+ return model.family == ModelFamily.ANTHROPIC
73
+
74
+
75
+ def provider_context_window(model: LanguageModelInfo) -> int:
76
+ return model.provider_context_window
77
+
78
+
79
+ def provider_count_trigger_tokens(
80
+ model: LanguageModelInfo,
81
+ effective_local_limit: int,
82
+ ) -> int:
83
+ """Local count at which an authoritative provider count becomes worthwhile."""
84
+ ratio = (
85
+ NATIVE_TOKENIZER_TRIGGER_RATIO
86
+ if model.family in _NATIVE_TOKENIZER_FAMILIES
87
+ else APPROXIMATE_TOKENIZER_TRIGGER_RATIO
88
+ )
89
+ return min(
90
+ int(provider_context_window(model) * ratio),
91
+ int(effective_local_limit * LOCAL_LIMIT_TRIGGER_RATIO),
92
+ )
93
+
94
+
95
+ def provider_input_target(
96
+ model: LanguageModelInfo,
97
+ other_options: dict[str, Any] | None,
98
+ ) -> int:
99
+ """Maximum provider-counted input while preserving output and safety room."""
100
+ options = other_options or {}
101
+ configured_output = options.get("max_completion_tokens", options.get("max_tokens"))
102
+ output_reserve = (
103
+ configured_output
104
+ if isinstance(configured_output, int) and configured_output >= 0
105
+ else min(
106
+ DEFAULT_OUTPUT_TOKEN_RESERVE,
107
+ model.token_limits.token_limit_output,
108
+ )
109
+ )
110
+ return max(
111
+ 1,
112
+ int(provider_context_window(model) * PROVIDER_COUNT_TARGET_RATIO)
113
+ - output_reserve,
114
+ )
115
+
116
+
117
+ def provider_overflow_reduction_factor(provider_count: int, target: int) -> float:
118
+ """Budget multiplier that brings an oversized provider count under *target*."""
119
+ return min(
120
+ MAX_PROVIDER_OVERFLOW_REDUCTION_FACTOR,
121
+ target / provider_count * PROVIDER_COUNT_TARGET_RATIO,
122
+ )
123
+
124
+
125
+ class ContextOverflowGuard:
126
+ """Preflight provider token-budget verification and overflow retry policy."""
127
+
128
+ def __init__(
129
+ self,
130
+ *,
131
+ logger: Logger,
132
+ history_manager: HistoryManager,
133
+ token_counter: object,
134
+ model: LanguageModelInfo,
135
+ ) -> None:
136
+ self._logger = logger
137
+ self._history_manager = history_manager
138
+ self._token_counter = token_counter
139
+ self._model = model
140
+
141
+ async def preflight_token_budget(
142
+ self,
143
+ kwargs: _LoopIterationRunnerKwargs,
144
+ recompose: Callable[[], Awaitable[None]],
145
+ ) -> None:
146
+ """Verify near-limit payloads using the provider's tokenizer before the LLM call."""
147
+ if not supports_provider_token_count(self._model):
148
+ return
149
+ if not isinstance(self._token_counter, SupportsTokenCount):
150
+ return
151
+
152
+ local_count = self._history_manager.last_token_count
153
+ effective_limit = self._history_manager.effective_token_limit
154
+ trigger = provider_count_trigger_tokens(self._model, effective_limit)
155
+ if local_count < trigger:
156
+ return
157
+
158
+ target = provider_input_target(self._model, kwargs.get("other_options"))
159
+ provider_count = await self._try_provider_token_count(kwargs)
160
+ if provider_count is None or provider_count <= target:
161
+ return
162
+
163
+ self._logger.warning(
164
+ f"Provider token count {provider_count} exceeds the safe input target "
165
+ f"{target}. Reducing tool results before the LLM call."
166
+ )
167
+ reduction_factor = provider_overflow_reduction_factor(provider_count, target)
168
+ self._history_manager.tighten_token_budget(reduction_factor)
169
+ await recompose()
170
+
171
+ reduced_count = await self._try_provider_token_count(kwargs)
172
+ if reduced_count is None or reduced_count <= target:
173
+ return
174
+
175
+ if not self._history_manager.withhold_latest_tool_call_results(
176
+ WITHHELD_TOOL_RESULT_NOTICE
177
+ ):
178
+ self._logger.warning(
179
+ f"Provider token count remains above target ({reduced_count} > "
180
+ f"{target}), but there are no tool results to withhold."
181
+ )
182
+ return
183
+
184
+ self._logger.warning(
185
+ "Provider token count remains above target after reduction. "
186
+ "Withholding the latest tool-call batch."
187
+ )
188
+ await recompose()
189
+
190
+ withheld_count = await self._try_provider_token_count(kwargs)
191
+ if withheld_count is None or withheld_count <= target:
192
+ return
193
+
194
+ self._logger.warning(
195
+ f"Provider token count {withheld_count} still exceeds the safe input "
196
+ f"target {target} after withholding. Reducing history further."
197
+ )
198
+ self._history_manager.tighten_token_budget(
199
+ provider_overflow_reduction_factor(withheld_count, target)
200
+ )
201
+ await recompose()
202
+
203
+ async def retry_after_overflow(
204
+ self,
205
+ exc: Exception,
206
+ *,
207
+ recompose: Callable[[], Awaitable[None]],
208
+ run_iteration: Callable[[], Awaitable[_T]],
209
+ ) -> _T:
210
+ """Retry an oversized LLM call by tightening the budget or withholding the latest tool batch."""
211
+ self._logger.warning(
212
+ "LLM call exceeded the context window. Retrying with a tighter token budget.",
213
+ exc_info=exc,
214
+ )
215
+ self._history_manager.tighten_token_budget(CONTEXT_OVERFLOW_TOKEN_BUDGET_FACTOR)
216
+ await recompose()
217
+ try:
218
+ return await run_iteration()
219
+ except Exception as retry_exc:
220
+ if not is_context_window_exceeded_error(retry_exc):
221
+ raise
222
+ if not self._history_manager.withhold_latest_tool_call_results(
223
+ WITHHELD_TOOL_RESULT_NOTICE
224
+ ):
225
+ raise
226
+ self._logger.warning(
227
+ "LLM call still exceeded the context window. Retrying with the "
228
+ "latest tool call results withheld."
229
+ )
230
+ await recompose()
231
+ return await run_iteration()
232
+
233
+ async def _try_provider_token_count(
234
+ self, kwargs: _LoopIterationRunnerKwargs
235
+ ) -> int | None:
236
+ counter = self._token_counter
237
+ if not isinstance(counter, SupportsTokenCount):
238
+ return None
239
+ started_at = time.perf_counter()
240
+ try:
241
+ count = await asyncio.wait_for(
242
+ counter.count_tokens_async(
243
+ messages=kwargs["messages"],
244
+ model_name=self._model.name,
245
+ temperature=kwargs.get("temperature", 0.0),
246
+ tools=kwargs.get("tools"),
247
+ other_options=kwargs.get("other_options"),
248
+ ),
249
+ timeout=PROVIDER_TOKEN_COUNT_TIMEOUT_SECONDS,
250
+ )
251
+ except Exception:
252
+ elapsed_ms = (time.perf_counter() - started_at) * 1000
253
+ self._logger.warning(
254
+ f"Provider token counting failed after {elapsed_ms:.0f} ms. "
255
+ "Continuing with the local token budget.",
256
+ exc_info=True,
257
+ )
258
+ return None
259
+ elapsed_ms = (time.perf_counter() - started_at) * 1000
260
+ self._logger.info(
261
+ f"Provider token count for {self._model.name}: {count} tokens "
262
+ f"in {elapsed_ms:.0f} ms."
263
+ )
264
+ return count if count > 0 else None
@@ -152,6 +152,7 @@ class HistoryManager:
152
152
  return len(self._loop_history) == 0
153
153
 
154
154
  def add_tool_call_results(self, tool_call_results: list[ToolCallResponse]):
155
+ self._collected_tool_response_image_urls = []
155
156
  for tool_response in tool_call_results:
156
157
  if tool_response.image_data_urls:
157
158
  for url in tool_response.image_data_urls:
@@ -220,6 +221,78 @@ class HistoryManager:
220
221
  def add_assistant_message(self, message: LanguageModelAssistantMessage) -> None:
221
222
  self._loop_history.append(message)
222
223
 
224
+ def tighten_token_budget(self, factor: float) -> None:
225
+ self._token_reducer.tighten_effective_token_limit(factor)
226
+
227
+ @property
228
+ def effective_token_limit(self) -> int:
229
+ return self._token_reducer.effective_token_limit
230
+
231
+ @property
232
+ def last_token_count(self) -> int:
233
+ return self._token_reducer.last_token_count
234
+
235
+ def withhold_latest_tool_call_results(self, notice: str) -> int:
236
+ """Replace every result of the most recent tool-call batch with *notice*.
237
+
238
+ The withheld results' chunks are dropped from the reference manager. They
239
+ are the newest chunks, so source numbers of earlier results stay valid.
240
+ Returns the number of withheld results.
241
+ """
242
+ batch_start: int | None = None
243
+ for index in range(len(self._loop_history) - 1, -1, -1):
244
+ candidate = self._loop_history[index]
245
+ if (
246
+ isinstance(candidate, LanguageModelAssistantMessage)
247
+ and candidate.tool_calls
248
+ ):
249
+ batch_start = index
250
+ break
251
+ if batch_start is None:
252
+ return 0
253
+
254
+ withheld_tool_call_ids: list[str] = []
255
+ for index in range(batch_start + 1, len(self._loop_history)):
256
+ message = self._loop_history[index]
257
+ if not isinstance(message, LanguageModelToolMessage):
258
+ continue
259
+ self._loop_history[index] = LanguageModelToolMessage(
260
+ content=notice,
261
+ tool_call_id=message.tool_call_id,
262
+ name=message.name,
263
+ )
264
+ withheld_tool_call_ids.append(message.tool_call_id)
265
+
266
+ withheld_chunks = {
267
+ id(chunk)
268
+ for tool_call_id in withheld_tool_call_ids
269
+ for chunk in self._reference_manager.get_chunks_of_tool(tool_call_id)
270
+ }
271
+ if withheld_chunks:
272
+ self._reference_manager.replace(
273
+ chunks=[
274
+ chunk
275
+ for chunk in self._reference_manager.get_chunks()
276
+ if id(chunk) not in withheld_chunks
277
+ ]
278
+ )
279
+ for tool_call_id in withheld_tool_call_ids:
280
+ self._reference_manager.replace_chunks_of_tool(tool_call_id, [])
281
+
282
+ if self._collected_tool_response_image_urls:
283
+ withheld_ids = set(withheld_tool_call_ids)
284
+ self._collected_tool_response_image_urls = [
285
+ (url, tool_call_id)
286
+ for url, tool_call_id in self._collected_tool_response_image_urls
287
+ if tool_call_id not in withheld_ids
288
+ ]
289
+
290
+ self._logger.warning(
291
+ f"Withheld {len(withheld_tool_call_ids)} tool call result(s) that "
292
+ "exceeded the context window."
293
+ )
294
+ return len(withheld_tool_call_ids)
295
+
223
296
  async def get_history_for_model_call(
224
297
  self,
225
298
  original_user_message: str,
@@ -238,7 +311,6 @@ class HistoryManager:
238
311
  remove_from_text=remove_from_text,
239
312
  image_data_urls_from_tools=image_data_from_tools,
240
313
  )
241
- self._collected_tool_response_image_urls = []
242
314
 
243
315
  if not self._source_offset_initialized:
244
316
  offset = max(0, self._token_reducer.max_db_source_number + 1)
@@ -38,7 +38,6 @@ MAX_INPUT_TOKENS_SAFETY_PERCENTAGE = env_settings.input_correction_reduction_fac
38
38
  SAFETY_MARGIN_FOR_AGGRESSIVE_REDUCTION = env_settings.input_aggressive_reduction_factor
39
39
 
40
40
  PLAIN_TEXT_TRUNCATION_MARKER = "\n\n[... tool response too long and was truncated]"
41
- # TODO: Make this configurable
42
41
  MIN_PLAIN_TEXT_CHARS_TO_KEEP = 1000
43
42
 
44
43
 
@@ -106,6 +105,7 @@ class LoopTokenReducer:
106
105
  self._language_model.token_limits.token_limit_input
107
106
  * (1 - MAX_INPUT_TOKENS_SAFETY_PERCENTAGE)
108
107
  )
108
+ self._last_token_count = 0
109
109
  self._max_db_source_number: int = -1
110
110
  self._db_source_map: dict[int, ContentChunk] = {}
111
111
  self._enable_tool_call_persistence = enable_tool_call_persistence
@@ -131,6 +131,27 @@ class LoopTokenReducer:
131
131
  def db_source_map(self) -> dict[int, ContentChunk]:
132
132
  return self._db_source_map
133
133
 
134
+ @property
135
+ def effective_token_limit(self) -> int:
136
+ return self._effective_token_limit
137
+
138
+ @property
139
+ def last_token_count(self) -> int:
140
+ return self._last_token_count
141
+
142
+ def tighten_effective_token_limit(self, factor: float) -> None:
143
+ """Shrink the input-token budget for the rest of the run.
144
+
145
+ Used after the provider rejected a payload this reducer counted as within
146
+ budget, i.e. the encoder underestimates the model's real token count.
147
+ """
148
+ previous_limit = self._effective_token_limit
149
+ self._effective_token_limit = int(previous_limit * factor)
150
+ self._logger.warning(
151
+ f"Tightened effective token limit from {previous_limit} to "
152
+ f"{self._effective_token_limit} tokens."
153
+ )
154
+
134
155
  def _get_encoder(self, language_model: LMI) -> Callable[[str], list[int]]:
135
156
  return language_model.get_encoder()
136
157
 
@@ -179,6 +200,7 @@ class LoopTokenReducer:
179
200
  break
180
201
 
181
202
  token_count = self._count_message_tokens(messages)
203
+ self._last_token_count = token_count
182
204
  self._logger.info(
183
205
  f"Final token count after reduction: {token_count} of model_capacity {self._language_model.token_limits.token_limit_input}"
184
206
  )
@@ -191,8 +213,6 @@ class LoopTokenReducer:
191
213
  This is purely a size check. Whether anything can actually be reduced to
192
214
  get back under the limit is a separate concern (:meth:`_can_reduce_history`).
193
215
  """
194
- # TODO: This is not fully correct at the moment as the token_count
195
- # include system_prompt and user question already
196
216
  return token_count > self._effective_token_limit
197
217
 
198
218
  def _can_reduce_history(self, loop_history: list[LanguageModelMessage]) -> bool:
@@ -16,6 +16,9 @@ from .schemas import (
16
16
  from .schemas import (
17
17
  ContentRerankerConfig as ContentRerankerConfig,
18
18
  )
19
+ from .schemas import (
20
+ ContentSearchMergeStrategy as ContentSearchMergeStrategy,
21
+ )
19
22
  from .schemas import (
20
23
  ContentSearchResult as ContentSearchResult,
21
24
  )
@@ -47,6 +50,7 @@ __all__ = [
47
50
  "ContentMetadata",
48
51
  "ContentReference",
49
52
  "ContentRerankerConfig",
53
+ "ContentSearchMergeStrategy",
50
54
  "ContentSearchResult",
51
55
  "ContentSearchType",
52
56
  "ContentService",
@@ -17,6 +17,7 @@ from unique_toolkit.content.schemas import (
17
17
  ContentChunk,
18
18
  ContentInfo,
19
19
  ContentRerankerConfig,
20
+ ContentSearchMergeStrategy,
20
21
  ContentSearchType,
21
22
  DeleteContentResponse,
22
23
  FolderInfo,
@@ -45,6 +46,8 @@ def search_content_chunks(
45
46
  metadata_filter: dict[str, Any] | None = None,
46
47
  content_ids: list[str] | None = None,
47
48
  score_threshold: float | None = None,
49
+ merge_strategy: ContentSearchMergeStrategy | None = None,
50
+ include_scores: bool | None = None,
48
51
  ) -> list[ContentChunk]:
49
52
  """
50
53
  Performs a synchronous search for content chunks in the knowledge base.
@@ -60,6 +63,8 @@ def search_content_chunks(
60
63
  metadata_filter (dict | None): UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.
61
64
  content_ids (list[str] | None): The content IDs to search. Defaults to None.
62
65
  score_threshold (float | None): The minimum score threshold for results. Defaults to 0.
66
+ merge_strategy (ContentSearchMergeStrategy | None): How a COMBINED search merges vector and full-text results. ``ZIP`` interleaves the two lists and keeps each result's original score. ``RRF`` and ``DBSF`` replace those scores with a fused score. Ignored by other search types. Defaults to the backend configuration.
67
+ include_scores (bool | None): When true, each ``ContentChunk.score`` is set. Vector search returns a similarity score, full-text search a BM25 score, and a COMBINED search a fused score for ``RRF`` and ``DBSF``. Scores are only comparable within one search type. Defaults to None.
63
68
  Returns:
64
69
  list[ContentChunk]: The search results.
65
70
  """
@@ -86,6 +91,8 @@ def search_content_chunks(
86
91
  metaDataFilter=metadata_filter,
87
92
  contentIds=content_ids,
88
93
  scoreThreshold=score_threshold,
94
+ mergeStrategy=merge_strategy.value if merge_strategy else None,
95
+ includeScores=include_scores,
89
96
  )
90
97
  return map_to_content_chunks(searches)
91
98
  except Exception as e:
@@ -107,6 +114,8 @@ async def search_content_chunks_async(
107
114
  metadata_filter: dict[str, Any] | None = None,
108
115
  content_ids: list[str] | None = None,
109
116
  score_threshold: float | None = None,
117
+ merge_strategy: ContentSearchMergeStrategy | None = None,
118
+ include_scores: bool | None = None,
110
119
  ):
111
120
  """
112
121
  Performs an asynchronous search for content chunks in the knowledge base.
@@ -136,6 +145,8 @@ async def search_content_chunks_async(
136
145
  metaDataFilter=metadata_filter,
137
146
  contentIds=content_ids,
138
147
  scoreThreshold=score_threshold,
148
+ mergeStrategy=merge_strategy.value if merge_strategy else None,
149
+ includeScores=include_scores,
139
150
  )
140
151
  return map_to_content_chunks(searches)
141
152
  except Exception as e:
@@ -70,6 +70,11 @@ class ContentChunk(BaseModel):
70
70
  description="The end page of the chunk. For document chunks this is the end page of the document.",
71
71
  )
72
72
 
73
+ score: float | None = Field(
74
+ default=None,
75
+ description="The relevance score of the chunk. Only set when the search requested scores. Scores are comparable within a single search type only.",
76
+ )
77
+
73
78
  object: str | None = None
74
79
  metadata: ContentMetadata | None = None
75
80
  internally_stored_at: datetime | None = None
@@ -294,6 +299,18 @@ class ContentSearchType(StrEnum):
294
299
  VECTOR = "VECTOR"
295
300
 
296
301
 
302
+ class ContentSearchMergeStrategy(StrEnum):
303
+ """How a ``COMBINED`` search merges vector and full-text results.
304
+
305
+ Ignored by single-source search types. When omitted, the backend applies its
306
+ configured default.
307
+ """
308
+
309
+ ZIP = "ZIP"
310
+ RRF = "RRF"
311
+ DBSF = "DBSF"
312
+
313
+
297
314
  class ContentSearchResult(BaseModel):
298
315
  """Schema corresponding to unique_sdk.SearchResult"""
299
316
 
@@ -30,6 +30,7 @@ from unique_toolkit.content.schemas import (
30
30
  Content,
31
31
  ContentChunk,
32
32
  ContentRerankerConfig,
33
+ ContentSearchMergeStrategy,
33
34
  ContentSearchType,
34
35
  )
35
36
 
@@ -357,6 +358,8 @@ class ContentService:
357
358
  metadata_filter: dict[str, Any] | None = None,
358
359
  content_ids: list[str] | None = None,
359
360
  score_threshold: float | None = None,
361
+ merge_strategy: ContentSearchMergeStrategy | None = None,
362
+ include_scores: bool | None = None,
360
363
  ) -> list[ContentChunk]:
361
364
  """
362
365
  Performs a synchronous search for content chunks in the knowledge base.
@@ -373,6 +376,8 @@ class ContentService:
373
376
  metadata_filter (dict | None, optional): UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.
374
377
  content_ids (list[str] | None, optional): The content IDs to search within. Defaults to None.
375
378
  score_threshold (float | None, optional): Sets the minimum similarity score for search results to be considered. Defaults to 0.
379
+ merge_strategy (ContentSearchMergeStrategy | None, optional): How a COMBINED search merges vector and full-text results. ``ZIP`` interleaves the two lists and keeps each result's original score. ``RRF`` and ``DBSF`` replace those scores with a fused score. Ignored by other search types. Defaults to the backend configuration.
380
+ include_scores (bool | None, optional): When true, each ``ContentChunk.score`` is set. Vector search returns a similarity score, full-text search a BM25 score, and a COMBINED search a fused score for ``RRF`` and ``DBSF``. Scores are only comparable within one search type. Defaults to None.
376
381
 
377
382
  Returns:
378
383
  list[ContentChunk]: The search results.
@@ -404,6 +409,8 @@ class ContentService:
404
409
  metadata_filter=metadata_filter,
405
410
  content_ids=content_ids,
406
411
  score_threshold=score_threshold,
412
+ merge_strategy=merge_strategy,
413
+ include_scores=include_scores,
407
414
  )
408
415
  return searches
409
416
  except Exception as e:
@@ -424,6 +431,8 @@ class ContentService:
424
431
  metadata_filter: dict[str, Any] | None = None,
425
432
  content_ids: list[str] | None = None,
426
433
  score_threshold: float | None = None,
434
+ merge_strategy: ContentSearchMergeStrategy | None = None,
435
+ include_scores: bool | None = None,
427
436
  ):
428
437
  """
429
438
  Performs an asynchronous search for content chunks in the knowledge base.
@@ -440,6 +449,8 @@ class ContentService:
440
449
  metadata_filter (dict | None, optional): UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.
441
450
  content_ids (list[str] | None, optional): The content IDs to search within. Defaults to None.
442
451
  score_threshold (float | None, optional): Sets the minimum similarity score for search results to be considered. Defaults to 0.
452
+ merge_strategy (ContentSearchMergeStrategy | None, optional): How a COMBINED search merges vector and full-text results. ``ZIP`` interleaves the two lists and keeps each result's original score. ``RRF`` and ``DBSF`` replace those scores with a fused score. Ignored by other search types. Defaults to the backend configuration.
453
+ include_scores (bool | None, optional): When true, each ``ContentChunk.score`` is set. Vector search returns a similarity score, full-text search a BM25 score, and a COMBINED search a fused score for ``RRF`` and ``DBSF``. Scores are only comparable within one search type. Defaults to None.
443
454
 
444
455
  Returns:
445
456
  list[ContentChunk]: The search results.
@@ -470,6 +481,8 @@ class ContentService:
470
481
  metadata_filter=metadata_filter,
471
482
  content_ids=content_ids,
472
483
  score_threshold=score_threshold,
484
+ merge_strategy=merge_strategy,
485
+ include_scores=include_scores,
473
486
  )
474
487
  return searches
475
488
  except Exception as e:
@@ -21,6 +21,9 @@ from unique_toolkit.language_model.infos import (
21
21
  LanguageModelName,
22
22
  ModelCapabilities,
23
23
  )
24
+ from unique_toolkit.language_model.provider_token_count import (
25
+ build_provider_token_count_payload,
26
+ )
24
27
  from unique_toolkit.language_model.reference import (
25
28
  add_references_to_message,
26
29
  )
@@ -748,3 +751,35 @@ async def stream_complete_with_references_openai(
748
751
  except Exception as e:
749
752
  logger.error("Error streaming completion (model=%s): %s", model_name_, e)
750
753
  raise
754
+
755
+
756
+ async def count_tokens_with_provider_async(
757
+ *,
758
+ company_id: str,
759
+ user_id: str,
760
+ messages: LanguageModelMessages | list[ChatCompletionMessageParam],
761
+ model_name: LanguageModelName | str,
762
+ temperature: float = DEFAULT_COMPLETE_TEMPERATURE,
763
+ tools: Sequence[LanguageModelTool | LanguageModelToolDescription] | None = None,
764
+ other_options: dict[str, Any] | None = None,
765
+ ) -> int:
766
+ """Count the completion payload with LiteLLM's provider-backed counter."""
767
+ options, model, messages_dict, _ = _prepare_all_completions_params_util(
768
+ messages=messages,
769
+ model_name=model_name,
770
+ temperature=temperature,
771
+ tools=tools,
772
+ other_options=other_options,
773
+ )
774
+ raw_tools = options.get("tools")
775
+ payload = build_provider_token_count_payload(
776
+ model=model,
777
+ messages=messages_dict,
778
+ tools=raw_tools if isinstance(raw_tools, list) else None,
779
+ )
780
+ response = await unique_sdk.Integrated.count_tokens_async(
781
+ user_id=user_id,
782
+ company_id=company_id,
783
+ **payload,
784
+ )
785
+ return response["input_tokens"]
@@ -335,6 +335,28 @@ def _load_custom_decoder(tokenizer_name: str) -> TypeDecoder:
335
335
  return tokenizer.decode
336
336
 
337
337
 
338
+ _CLAUDE_CONTEXT_WINDOWS = {
339
+ "claude-3-7-sonnet": 200_000,
340
+ "claude-3-7-sonnet-thinking": 200_000,
341
+ "claude-haiku-4-5": 200_000,
342
+ "claude-opus-4": 200_000,
343
+ "claude-opus-4-1": 200_000,
344
+ "claude-opus-4-5": 200_000,
345
+ "claude-opus-4-6": 200_000,
346
+ "claude-sonnet-4": 200_000,
347
+ "claude-sonnet-4-5": 200_000,
348
+ "claude-sonnet-4-6": 200_000,
349
+ "claude-fable-5": 1_000_000,
350
+ "claude-haiku-5-5": 1_000_000,
351
+ "claude-opus-4-7": 1_000_000,
352
+ "claude-opus-4-8": 1_000_000,
353
+ "claude-opus-5": 1_000_000,
354
+ "claude-opus-5-5": 1_000_000,
355
+ "claude-sonnet-5": 1_000_000,
356
+ "claude-sonnet-5-5": 1_000_000,
357
+ }
358
+
359
+
338
360
  class LanguageModelInfo(BaseModel):
339
361
  model_config = get_configuration_dict()
340
362
  name: (
@@ -3731,6 +3753,29 @@ class LanguageModelInfo(BaseModel):
3731
3753
  else:
3732
3754
  return self.name
3733
3755
 
3756
+ @property
3757
+ def provider_context_window(self) -> int:
3758
+ """Return the raw provider input context window before local-tokenizer adjustments."""
3759
+ if self.family == ModelFamily.ANTHROPIC:
3760
+ known_window = _CLAUDE_CONTEXT_WINDOWS.get(self.version)
3761
+ if known_window is None:
3762
+ model_name = str(self.name)
3763
+ known_window = next(
3764
+ (
3765
+ window
3766
+ for version, window in sorted(
3767
+ _CLAUDE_CONTEXT_WINDOWS.items(),
3768
+ key=lambda item: len(item[0]),
3769
+ reverse=True,
3770
+ )
3771
+ if version in model_name
3772
+ ),
3773
+ None,
3774
+ )
3775
+ if known_window is not None:
3776
+ return known_window
3777
+ return self.token_limits.token_limit_input
3778
+
3734
3779
 
3735
3780
  @deprecated(
3736
3781
  """
@@ -0,0 +1,170 @@
1
+ """Build request bodies for LiteLLM's Anthropic-compatible ``count_tokens`` endpoint.
2
+
3
+ Agent-loop messages are in OpenAI chat format. The endpoint expects the Anthropic
4
+ Messages format, so system messages, tool calls, tool results and images are
5
+ converted before counting.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Mapping, Sequence
12
+ from typing import Any
13
+
14
+
15
+ def build_provider_token_count_payload(
16
+ *,
17
+ model: str,
18
+ messages: Sequence[Mapping[str, Any]],
19
+ tools: Sequence[Mapping[str, Any]] | None,
20
+ ) -> dict[str, Any]:
21
+ """Convert an OpenAI chat payload to LiteLLM's Anthropic-compatible counter."""
22
+ system_parts: list[str] = []
23
+ provider_messages: list[dict[str, Any]] = []
24
+
25
+ for message in messages:
26
+ role = message.get("role")
27
+ if role == "system":
28
+ content = message.get("content")
29
+ if isinstance(content, str) and content:
30
+ system_parts.append(content)
31
+ continue
32
+
33
+ if role == "assistant":
34
+ blocks = _assistant_content_blocks(message)
35
+ _append_message(provider_messages, "assistant", blocks)
36
+ elif role == "tool":
37
+ _append_message(
38
+ provider_messages,
39
+ "user",
40
+ [
41
+ {
42
+ "type": "tool_result",
43
+ "tool_use_id": (
44
+ message.get("tool_call_id")
45
+ or message.get("toolCallId")
46
+ or ""
47
+ ),
48
+ "content": _content_as_text(message.get("content")),
49
+ }
50
+ ],
51
+ )
52
+ elif role == "user":
53
+ _append_message(
54
+ provider_messages,
55
+ "user",
56
+ _user_content_blocks(message.get("content")),
57
+ )
58
+
59
+ payload: dict[str, Any] = {
60
+ "model": model.removeprefix("litellm:"),
61
+ "messages": provider_messages,
62
+ }
63
+ if system_parts:
64
+ payload["system"] = "\n\n".join(system_parts)
65
+ if tools:
66
+ payload["tools"] = [_anthropic_tool(tool) for tool in tools]
67
+ return payload
68
+
69
+
70
+ def _assistant_content_blocks(
71
+ message: Mapping[str, Any],
72
+ ) -> list[dict[str, Any]]:
73
+ blocks: list[dict[str, Any]] = []
74
+ content = message.get("content")
75
+ if isinstance(content, str) and content:
76
+ blocks.append({"type": "text", "text": content})
77
+
78
+ tool_calls = message.get("tool_calls") or message.get("toolCalls")
79
+ if isinstance(tool_calls, list):
80
+ for tool_call in tool_calls:
81
+ function = tool_call.get("function", {})
82
+ if not isinstance(function, dict):
83
+ continue
84
+ blocks.append(
85
+ {
86
+ "type": "tool_use",
87
+ "id": tool_call.get("id", ""),
88
+ "name": function.get("name", ""),
89
+ "input": _tool_arguments(function.get("arguments")),
90
+ }
91
+ )
92
+ return blocks
93
+
94
+
95
+ def _user_content_blocks(content: object) -> list[dict[str, Any]]:
96
+ if isinstance(content, str):
97
+ return [{"type": "text", "text": content}]
98
+ if not isinstance(content, list):
99
+ return [{"type": "text", "text": ""}]
100
+
101
+ blocks: list[dict[str, Any]] = []
102
+ for part in content:
103
+ if not isinstance(part, dict):
104
+ continue
105
+ if part.get("type") == "text":
106
+ blocks.append({"type": "text", "text": str(part.get("text", ""))})
107
+ elif part.get("type") == "image_url":
108
+ image_url = part.get("image_url") or part.get("imageUrl")
109
+ if isinstance(image_url, dict):
110
+ image_block = _base64_image_block(image_url.get("url"))
111
+ if image_block is not None:
112
+ blocks.append(image_block)
113
+ return blocks or [{"type": "text", "text": ""}]
114
+
115
+
116
+ def _base64_image_block(url: object) -> dict[str, Any] | None:
117
+ if not isinstance(url, str) or not url.startswith("data:") or ";base64," not in url:
118
+ return None
119
+ metadata, data = url.split(";base64,", 1)
120
+ return {
121
+ "type": "image",
122
+ "source": {
123
+ "type": "base64",
124
+ "media_type": metadata.removeprefix("data:"),
125
+ "data": data,
126
+ },
127
+ }
128
+
129
+
130
+ def _append_message(
131
+ messages: list[dict[str, Any]],
132
+ role: str,
133
+ blocks: list[dict[str, Any]],
134
+ ) -> None:
135
+ if messages and messages[-1]["role"] == role:
136
+ messages[-1]["content"].extend(blocks)
137
+ return
138
+ messages.append({"role": role, "content": blocks})
139
+
140
+
141
+ def _anthropic_tool(tool: Mapping[str, Any]) -> dict[str, Any]:
142
+ function = tool.get("function", tool)
143
+ if not isinstance(function, dict):
144
+ function = {}
145
+ return {
146
+ "name": function.get("name", ""),
147
+ "description": function.get("description", ""),
148
+ "input_schema": function.get(
149
+ "parameters", {"type": "object", "properties": {}}
150
+ ),
151
+ }
152
+
153
+
154
+ def _tool_arguments(arguments: object) -> dict[str, Any]:
155
+ if isinstance(arguments, dict):
156
+ return arguments
157
+ if isinstance(arguments, str):
158
+ try:
159
+ parsed = json.loads(arguments)
160
+ except json.JSONDecodeError:
161
+ return {"raw": arguments}
162
+ if isinstance(parsed, dict):
163
+ return parsed
164
+ return {}
165
+
166
+
167
+ def _content_as_text(content: object) -> str:
168
+ if isinstance(content, str):
169
+ return content
170
+ return json.dumps(content)
@@ -1,4 +1,4 @@
1
- from typing import Any, Protocol, Sequence
1
+ from typing import Any, Protocol, Sequence, runtime_checkable
2
2
 
3
3
  from openai.types.chat import (
4
4
  ChatCompletionMessageParam,
@@ -55,6 +55,19 @@ class SupportsComplete(Protocol):
55
55
  ) -> LanguageModelResponse: ...
56
56
 
57
57
 
58
+ @runtime_checkable
59
+ class SupportsTokenCount(Protocol):
60
+ async def count_tokens_async(
61
+ self,
62
+ *,
63
+ messages: LanguageModelMessages | list[ChatCompletionMessageParam],
64
+ model_name: LanguageModelName | str,
65
+ temperature: float = DEFAULT_COMPLETE_TEMPERATURE,
66
+ tools: Sequence[LanguageModelTool | LanguageModelToolDescription] | None = None,
67
+ other_options: dict[str, Any] | None = None,
68
+ ) -> int: ...
69
+
70
+
58
71
  class SupportCompleteWithReferences(Protocol):
59
72
  def complete_with_references(
60
73
  self,
@@ -97,6 +97,7 @@ from unique_toolkit.content.schemas import (
97
97
  ContentChunk,
98
98
  ContentReference,
99
99
  ContentRerankerConfig,
100
+ ContentSearchMergeStrategy,
100
101
  ContentSearchType,
101
102
  )
102
103
  from unique_toolkit.elicitation.service import ElicitationService
@@ -104,6 +105,9 @@ from unique_toolkit.language_model.constants import (
104
105
  DEFAULT_COMPLETE_TEMPERATURE,
105
106
  DEFAULT_COMPLETE_TIMEOUT,
106
107
  )
108
+ from unique_toolkit.language_model.functions import (
109
+ count_tokens_with_provider_async,
110
+ )
107
111
  from unique_toolkit.language_model.infos import (
108
112
  LanguageModelName,
109
113
  )
@@ -1719,6 +1723,25 @@ class ChatService(ChatServiceDeprecated):
1719
1723
  other_options=other_options,
1720
1724
  )
1721
1725
 
1726
+ async def count_tokens_async(
1727
+ self,
1728
+ *,
1729
+ messages: LanguageModelMessages | list[ChatCompletionMessageParam],
1730
+ model_name: LanguageModelName | str,
1731
+ temperature: float = DEFAULT_COMPLETE_TEMPERATURE,
1732
+ tools: Sequence[LanguageModelTool | LanguageModelToolDescription] | None = None,
1733
+ other_options: dict[str, Any] | None = None,
1734
+ ) -> int:
1735
+ return await count_tokens_with_provider_async(
1736
+ company_id=self._company_id,
1737
+ user_id=self._user_id,
1738
+ messages=messages,
1739
+ model_name=model_name,
1740
+ temperature=temperature,
1741
+ tools=tools,
1742
+ other_options=other_options,
1743
+ )
1744
+
1722
1745
  async def complete_async(
1723
1746
  self,
1724
1747
  messages: LanguageModelMessages | list[ChatCompletionMessageParam],
@@ -2119,8 +2142,15 @@ class ChatService(ChatServiceDeprecated):
2119
2142
  metadata_filter: dict[str, Any] | None = None,
2120
2143
  content_ids: list[str] | None = None,
2121
2144
  score_threshold: float | None = None,
2145
+ merge_strategy: ContentSearchMergeStrategy | None = None,
2146
+ include_scores: bool | None = None,
2122
2147
  ) -> list[ContentChunk]:
2123
- """Search content chunks scoped to this chat session (chat_only=True)."""
2148
+ """Search content chunks scoped to this chat session (chat_only=True).
2149
+
2150
+ Args:
2151
+ merge_strategy: How a COMBINED search merges vector and full-text results. ``ZIP`` interleaves the two lists and keeps each result's original score. ``RRF`` and ``DBSF`` replace those scores with a fused score. Ignored by other search types. Defaults to the backend configuration.
2152
+ include_scores: When true, each ``ContentChunk.score`` is set. Vector search returns a similarity score, full-text search a BM25 score, and a COMBINED search a fused score for ``RRF`` and ``DBSF``. Scores are only comparable within one search type.
2153
+ """
2124
2154
  if scope_ids:
2125
2155
  warnings.warn(
2126
2156
  "Passing scope_ids to ChatService.search_content_chunks_async is "
@@ -2147,6 +2177,8 @@ class ChatService(ChatServiceDeprecated):
2147
2177
  metadata_filter=metadata_filter,
2148
2178
  content_ids=content_ids,
2149
2179
  score_threshold=score_threshold,
2180
+ merge_strategy=merge_strategy,
2181
+ include_scores=include_scores,
2150
2182
  )
2151
2183
 
2152
2184
  async def search_contents_async(
@@ -46,6 +46,7 @@ from unique_toolkit.content.schemas import (
46
46
  ContentChunk,
47
47
  ContentInfo,
48
48
  ContentRerankerConfig,
49
+ ContentSearchMergeStrategy,
49
50
  ContentSearchType,
50
51
  DeleteContentResponse,
51
52
  FolderInfo,
@@ -159,6 +160,8 @@ class KnowledgeBaseService:
159
160
  score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
160
161
  search_language: str = DEFAULT_SEARCH_LANGUAGE,
161
162
  reranker_config: ContentRerankerConfig | None = None,
163
+ merge_strategy: ContentSearchMergeStrategy | None = None,
164
+ include_scores: bool | None = None,
162
165
  ) -> list[ContentChunk]: ...
163
166
 
164
167
  @overload
@@ -173,6 +176,8 @@ class KnowledgeBaseService:
173
176
  score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
174
177
  search_language: str = DEFAULT_SEARCH_LANGUAGE,
175
178
  reranker_config: ContentRerankerConfig | None = None,
179
+ merge_strategy: ContentSearchMergeStrategy | None = None,
180
+ include_scores: bool | None = None,
176
181
  ) -> list[ContentChunk]: ...
177
182
 
178
183
  def search_content_chunks(
@@ -187,6 +192,8 @@ class KnowledgeBaseService:
187
192
  metadata_filter: dict[str, Any] | None = None,
188
193
  content_ids: list[str] | None = None,
189
194
  score_threshold: float | None = None,
195
+ merge_strategy: ContentSearchMergeStrategy | None = None,
196
+ include_scores: bool | None = None,
190
197
  ) -> list[ContentChunk]:
191
198
  """
192
199
  Performs a synchronous search for content chunks in the knowledge base.
@@ -202,6 +209,8 @@ class KnowledgeBaseService:
202
209
  metadata_filter (dict | None, optional): UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.
203
210
  content_ids (list[str] | None, optional): The content IDs to search within. Defaults to None.
204
211
  score_threshold (float | None, optional): Sets the minimum similarity score for search results to be considered. Defaults to 0.
212
+ merge_strategy (ContentSearchMergeStrategy | None, optional): How a COMBINED search merges vector and full-text results. ``ZIP`` interleaves the two lists and keeps each result's original score. ``RRF`` and ``DBSF`` replace those scores with a fused score. Ignored by other search types. Defaults to the backend configuration.
213
+ include_scores (bool | None, optional): When true, each ``ContentChunk.score`` is set. Vector search returns a similarity score, full-text search a BM25 score, and a COMBINED search a fused score for ``RRF`` and ``DBSF``. Scores are only comparable within one search type. Defaults to None.
205
214
 
206
215
  Returns:
207
216
  list[ContentChunk]: The search results.
@@ -240,6 +249,8 @@ class KnowledgeBaseService:
240
249
  metadata_filter=metadata_filter,
241
250
  content_ids=content_ids,
242
251
  score_threshold=score_threshold,
252
+ merge_strategy=merge_strategy,
253
+ include_scores=include_scores,
243
254
  )
244
255
  return searches
245
256
  except Exception as e:
@@ -257,6 +268,8 @@ class KnowledgeBaseService:
257
268
  score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
258
269
  search_language: str = DEFAULT_SEARCH_LANGUAGE,
259
270
  reranker_config: ContentRerankerConfig | None = None,
271
+ merge_strategy: ContentSearchMergeStrategy | None = None,
272
+ include_scores: bool | None = None,
260
273
  ) -> list[ContentChunk]: ...
261
274
 
262
275
  @overload
@@ -271,6 +284,8 @@ class KnowledgeBaseService:
271
284
  score_threshold: float = _DEFAULT_SCORE_THRESHOLD,
272
285
  search_language: str = DEFAULT_SEARCH_LANGUAGE,
273
286
  reranker_config: ContentRerankerConfig | None = None,
287
+ merge_strategy: ContentSearchMergeStrategy | None = None,
288
+ include_scores: bool | None = None,
274
289
  ) -> list[ContentChunk]: ...
275
290
 
276
291
  async def search_content_chunks_async(
@@ -285,6 +300,8 @@ class KnowledgeBaseService:
285
300
  metadata_filter: dict[str, Any] | None = None,
286
301
  content_ids: list[str] | None = None,
287
302
  score_threshold: float | None = None,
303
+ merge_strategy: ContentSearchMergeStrategy | None = None,
304
+ include_scores: bool | None = None,
288
305
  ):
289
306
  """
290
307
  Performs an asynchronous search for content chunks in the knowledge base.
@@ -300,6 +317,8 @@ class KnowledgeBaseService:
300
317
  metadata_filter (dict | None, optional): UniqueQL metadata filter. If unspecified/None, it tries to use the metadata filter from the event. Defaults to None.
301
318
  content_ids (list[str] | None, optional): The content IDs to search within. Defaults to None.
302
319
  score_threshold (float | None, optional): Sets the minimum similarity score for search results to be considered. Defaults to 0.
320
+ merge_strategy (ContentSearchMergeStrategy | None, optional): How a COMBINED search merges vector and full-text results. ``ZIP`` interleaves the two lists and keeps each result's original score. ``RRF`` and ``DBSF`` replace those scores with a fused score. Ignored by other search types. Defaults to the backend configuration.
321
+ include_scores (bool | None, optional): When true, each ``ContentChunk.score`` is set. Vector search returns a similarity score, full-text search a BM25 score, and a COMBINED search a fused score for ``RRF`` and ``DBSF``. Scores are only comparable within one search type. Defaults to None.
303
322
 
304
323
  Returns:
305
324
  list[ContentChunk]: The search results.
@@ -337,6 +356,8 @@ class KnowledgeBaseService:
337
356
  metadata_filter=metadata_filter,
338
357
  content_ids=content_ids,
339
358
  score_threshold=score_threshold,
359
+ merge_strategy=merge_strategy,
360
+ include_scores=include_scores,
340
361
  )
341
362
  return searches
342
363
  except Exception as e:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: unique-toolkit
3
- Version: 2026.44.0.dev3
3
+ Version: 2026.44.0.dev5
4
4
  Summary:
5
5
  Author: Cedric Klinkert, Martin Fadler, Sadique Sheik, Fabian Schläpfer, Pascal Hauri, Ejiroghene Oki-Peter, Rami Azouz, Ricardo Visini, Sanzio Monti
6
6
  Author-email: Cedric Klinkert <cedric.klinkert@unique.ch>, Martin Fadler <martin.fadler@unique.ch>, Sadique Sheik <sadique@unique.ch>, Fabian Schläpfer <fabian@unique.ch>, Pascal Hauri <pascal@unique.ch>, Ejiroghene Oki-Peter <oki-peter.ejiroghene@unique.ai>, Rami Azouz <rami.ext@unique.ch>, Ricardo Visini <ricardo.visini@unique.ch>, Sanzio Monti <sanzio.monti@unique.ai>
@@ -16,7 +16,7 @@ Requires-Dist: sseclient>=0.0.27,<0.0.28
16
16
  Requires-Dist: openai>=1.105.0,<3
17
17
  Requires-Dist: platformdirs>=4.0.0,<5
18
18
  Requires-Dist: pillow>=12.1.1
19
- Requires-Dist: unique-sdk>=2026.44.0.dev1,<2026.44.0rc0
19
+ Requires-Dist: unique-sdk>=2026.44.0.dev8,<2026.44.0rc0
20
20
  Requires-Dist: jambo>=0.1.2,<0.2
21
21
  Requires-Dist: jinja2>=3.1.6,<4
22
22
  Requires-Dist: docxtpl>=0.20.1,<0.21
@@ -113,9 +113,10 @@ unique_toolkit/agentic/evaluation/tests/test_prompt_loaders.py,sha256=zBREdlKf5t
113
113
  unique_toolkit/agentic/evaluation/utils.py,sha256=HmyPaDV8wdW-_gOjjW-wDaMKgdrsP5-SHP7OqTmGI_A,264
114
114
  unique_toolkit/agentic/feature_flags/__init__.py,sha256=fBR9FaLrc9e8sdYDe1LwP9aNJt5aLLtAq3nIphVWkIk,191
115
115
  unique_toolkit/agentic/feature_flags/feature_flags.py,sha256=LlFfcgGV4lRQ_mgOGsbZzjKeTXxjCCOl7agCxvJUhvQ,7133
116
+ unique_toolkit/agentic/history_manager/context_overflow.py,sha256=1GrGcf44rKhyT4dMJI7W2l4JvXyPFqoLUy0zp2n4yYw,9677
116
117
  unique_toolkit/agentic/history_manager/history_construction_with_contents.py,sha256=bJH5RiLM__fg-i_ycact--9xtV5A321xe_cktT__bzA,26284
117
- unique_toolkit/agentic/history_manager/history_manager.py,sha256=PqSa87yzNIDRXqjh1KN7moeIpp_jWxj9qEPig4wv790,16062
118
- unique_toolkit/agentic/history_manager/loop_token_reducer.py,sha256=lgo5zAq6gYLo7FFTNWe5sc6o80vnadKsr-cgEDP6hM8,30754
118
+ unique_toolkit/agentic/history_manager/history_manager.py,sha256=gDrbnOIJlnmh3KvKRtoYKWVAymEgboW61-6GJVWuZ4c,18885
119
+ unique_toolkit/agentic/history_manager/loop_token_reducer.py,sha256=Z9Hr3Lb_2t5qqqRcUEYSoV8tp7UUO-uf4yyro3jCyQE,31458
119
120
  unique_toolkit/agentic/history_manager/settings.py,sha256=Lrx3a8yXeU0MXrWlV6RZSHsgYWF9Zrs8LyR96OpqQ_k,1216
120
121
  unique_toolkit/agentic/history_manager/utils.py,sha256=DiBip8xtah3I9-G-_Ul3OjlYKunrXR-5RJtzREHWV_0,6579
121
122
  unique_toolkit/agentic/loop_runner/__init__.py,sha256=bhwOIloPn2MZyCw60FkHy330twCCRovg3bgye9OjZRE,1496
@@ -270,11 +271,11 @@ unique_toolkit/chat/schemas.py,sha256=tRU8vcT1SQWtktkHQmDO26CNbOgSynFHfFB9FR6D4O
270
271
  unique_toolkit/chat/service.py,sha256=6D00OL4QrGafbOhTaC5zNXaNgg7gS5W_2ePVa4LhqpE,4439
271
272
  unique_toolkit/chat/state.py,sha256=Cjgwv_2vhDFbV69xxsn7SefhaoIAEqLx3ferdVFCnOg,1445
272
273
  unique_toolkit/chat/utils.py,sha256=CsD9IER2gA1IOV0fmUOl-N0LmKvA7JP9dGrOqeOY0Gg,1173
273
- unique_toolkit/content/__init__.py,sha256=nnQDfnNTEvI8-3dgWvIojoFDYU7edwd8Kloi6lMDG0M,1586
274
+ unique_toolkit/content/__init__.py,sha256=yeVVqHjltRii_XwPOX2uId2kHF0_wCcSC4jwalv_5g8,1707
274
275
  unique_toolkit/content/constants.py,sha256=1iy4Y67xobl5VTnJB6SxSyuoBWbdLl9244xfVMUZi5o,60
275
- unique_toolkit/content/functions.py,sha256=GtzgMpcMiz5CIDBpgLhMUC0kNivyZB6EeWWvuZCnJL4,35198
276
- unique_toolkit/content/schemas.py,sha256=AnCgn5AFhSkcVHmrSHL2tbIQTJoQQsBqNyI8tViFtKw,12236
277
- unique_toolkit/content/service.py,sha256=OsUm6lxkHeAAxDweLrSyZT02-ateuOYYENPsoHx9_VA,30051
276
+ unique_toolkit/content/functions.py,sha256=fLEueWbiMOOO43HxnltqdRR_Et9JoQCjnCm5WZA94DY,36284
277
+ unique_toolkit/content/schemas.py,sha256=6cvKqS2WerbrysD2FNmFef0REzaXfRUio7Nb3bLbViA,12734
278
+ unique_toolkit/content/service.py,sha256=3_QUMhJ_zo0OgXiq99nj2J14Hls8z8Vvlioevydp9J4,31775
278
279
  unique_toolkit/content/smart_rules.py,sha256=-bRlF_e66yKA8KsXTPYqfhHZu1jsXXl5akIZnSgu5X8,11621
279
280
  unique_toolkit/content/utils.py,sha256=keDkqu_ZzQY0y_g7g_XLOza3p4XsvfqVVDI9ylM91KY,10115
280
281
  unique_toolkit/data_extraction/README.md,sha256=5KxzqPHC29wxBiWJ-87wBQisSgRBkuSnPTb38pGH1wA,3138
@@ -396,11 +397,12 @@ unique_toolkit/language_model/_responses_api_utils.py,sha256=w2ZyleOQcWLpOWGJNNb
396
397
  unique_toolkit/language_model/builder.py,sha256=KwBzsD6-fvQnB4p2I7M-5Tk6j4tmQ973MYwU1ulXFb4,4526
397
398
  unique_toolkit/language_model/constants.py,sha256=B-topqW0r83dkC_25DeQfnPk3n53qzIHUCBS7YJ0-1U,119
398
399
  unique_toolkit/language_model/default_language_model.py,sha256=mcyuFs_V6tp52C8xJSHiEHO4kFGj6xed1gvozvCRD7k,1181
399
- unique_toolkit/language_model/functions.py,sha256=W6JC4LUh-LZ9waDgph--xVmKeQ7Ls6NRAqDx9DwQdeY,26691
400
- unique_toolkit/language_model/infos.py,sha256=f1xQQ8BvLG9jPsEt2vdSYzxVvaKIkem-Y6T4_n4tT_c,182327
400
+ unique_toolkit/language_model/functions.py,sha256=sjuzKe6xAq6NFwwgIRvgAuU8t6apq1tcdGSkcYCl8EQ,27905
401
+ unique_toolkit/language_model/infos.py,sha256=_fbEwGA9AjBm7TF1FTsihtKzi4SybTwVN7QyHRacMrQ,183899
401
402
  unique_toolkit/language_model/invocation_stats.py,sha256=CQbpUz394IsVd8eNTB1gPSMt5f0UXmkN1amNsqtAW6U,5857
402
403
  unique_toolkit/language_model/model_costs.py,sha256=ShuDAzMew1fUkJ3tzPgU5Zqjp6ivUZaG97BFh93tEn4,6358
403
404
  unique_toolkit/language_model/prompt.py,sha256=JSawaLjQg3VR-E2fK8engFyJnNdk21zaO8pPIodzN4Q,3991
405
+ unique_toolkit/language_model/provider_token_count.py,sha256=nXgyL-figP1Zv88zlHXFLvopZAL3hL8lUvF_lusP98g,5499
404
406
  unique_toolkit/language_model/reference.py,sha256=T3wr2jP_uRg5wKVIbKqLbxJlcgxfbZQGq3XdjbQ2kSo,6984
405
407
  unique_toolkit/language_model/schemas.py,sha256=o8zGkfoYayO1gL85G-ulV3Akp_BwjgEWGGUb89j1OgU,35440
406
408
  unique_toolkit/language_model/service.py,sha256=lgpzWhqxLBOeFacCafQi4e7BqAxJbOlr8GnCYcKeTdM,13274
@@ -413,11 +415,11 @@ unique_toolkit/monitoring/memory.py,sha256=KKnP5NEY63RXR9mmgXOEl5S9fgJSDDr2nE60y
413
415
  unique_toolkit/monitoring/middleware.py,sha256=MNsUuKgt74mSnUwttXTB_AxX546Pz2zKoAP9OewVrwQ,4531
414
416
  unique_toolkit/monitoring/registry.py,sha256=De2Bx5QBBRJQY2MM3xtntiJ2JU2FoKkVT7rNMG7ewgA,5874
415
417
  unique_toolkit/monitoring/tracing.py,sha256=0lmLuQjyyC3iFpNTw8rOyCpEZ6PTvp16nVbzcO9d2sQ,10043
416
- unique_toolkit/protocols/support.py,sha256=x5edzbBmKAUuvm3oLFh52gkgQsqR5LU7M0t8RHK0DZk,5161
418
+ unique_toolkit/protocols/support.py,sha256=vlXZEC9_Gupk2x9wZln5FJQlM6srWv4hIZY6O5WXhbk,5636
417
419
  unique_toolkit/services/__init__.py,sha256=b9Wl7Wvz1JmZDbDexIZzBoXZ0wscXuczGAH8LoL-Qak,572
418
- unique_toolkit/services/chat_service.py,sha256=umPHKDn0FX7vG7y7Tw-88iMultPpw_r0fYlhQlqvLYY,100196
420
+ unique_toolkit/services/chat_service.py,sha256=UasMB15wQnHp8-yMY9kN1zK8UZPhFPCi4vgkxrqBrEM,101802
419
421
  unique_toolkit/services/factory.py,sha256=7gNeanyHkgX23Iz7RMCQTCkE9gI5asCI11nXxM0jjx4,9832
420
- unique_toolkit/services/knowledge_base.py,sha256=6dM4abcXR9y2VYoR6SK79gwjrzb83Wm8jMPPIt5z95o,43461
422
+ unique_toolkit/services/knowledge_base.py,sha256=qvq9JhRUNciyvTn7PaJEuPGFHAyZbM8LzxCXfBo1Mqg,45625
421
423
  unique_toolkit/short_term_memory/__init__.py,sha256=2mI3AUrffgH7Yt-xS57EGqnHf7jnn6xquoKEhJqk3Wg,185
422
424
  unique_toolkit/short_term_memory/constants.py,sha256=698CL6-wjup2MvU19RxSmQk3gX7aqW_OOpZB7sbz_Xg,34
423
425
  unique_toolkit/short_term_memory/functions.py,sha256=mbEeWkJ5Jr0cvg1_m6l9aS1L6nWE5ZhviNzpKlCs-a8,7907
@@ -426,6 +428,6 @@ unique_toolkit/short_term_memory/service.py,sha256=2JMBEBn6GoyK-a0xvdcWpPft-3C74
426
428
  unique_toolkit/smart_rules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
427
429
  unique_toolkit/smart_rules/compile.py,sha256=vRe0aMJWuVIK-VsqomgxQImzke7MDmwgSxxJfYCa7zw,1386
428
430
  unique_toolkit/test_utilities/events.py,sha256=FLrhMh0A_mQutAUjoD0FdMcVQ4Gq31r35OVGzRjvLro,6760
429
- unique_toolkit-2026.44.0.dev3.dist-info/WHEEL,sha256=eh7sammvW2TypMMMGKgsM83HyA_3qQ5Lgg3ynoecH3M,79
430
- unique_toolkit-2026.44.0.dev3.dist-info/METADATA,sha256=WmTxbFMxjCN7yCsDn17P-sDhnxSDxcQL-sSn6LgvBGg,7821
431
- unique_toolkit-2026.44.0.dev3.dist-info/RECORD,,
431
+ unique_toolkit-2026.44.0.dev5.dist-info/WHEEL,sha256=eh7sammvW2TypMMMGKgsM83HyA_3qQ5Lgg3ynoecH3M,79
432
+ unique_toolkit-2026.44.0.dev5.dist-info/METADATA,sha256=eIr1xETlMh66pzXJR__P64AzIJa1TPhYmfn8bL_v8Xw,7821
433
+ unique_toolkit-2026.44.0.dev5.dist-info/RECORD,,