coco-framework 0.1.0__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.
Files changed (400) hide show
  1. coco/__init__.py +3 -0
  2. coco/agents/__init__.py +9 -0
  3. coco/agents/_subagent_transformer.py +307 -0
  4. coco/agents/factory.py +2164 -0
  5. coco/agents/middleware/__init__.py +100 -0
  6. coco/agents/middleware/_execution.py +385 -0
  7. coco/agents/middleware/_redaction.py +454 -0
  8. coco/agents/middleware/_retry.py +134 -0
  9. coco/agents/middleware/_trace_policy.py +61 -0
  10. coco/agents/middleware/context_editing.py +306 -0
  11. coco/agents/middleware/file_search.py +433 -0
  12. coco/agents/middleware/human_in_the_loop.py +680 -0
  13. coco/agents/middleware/internal_call_transformer.py +108 -0
  14. coco/agents/middleware/model_call_limit.py +267 -0
  15. coco/agents/middleware/model_fallback.py +417 -0
  16. coco/agents/middleware/model_retry.py +327 -0
  17. coco/agents/middleware/pii.py +878 -0
  18. coco/agents/middleware/provider_tool_search.py +307 -0
  19. coco/agents/middleware/shell_tool.py +949 -0
  20. coco/agents/middleware/summarization.py +910 -0
  21. coco/agents/middleware/todo.py +357 -0
  22. coco/agents/middleware/tool_call_limit.py +495 -0
  23. coco/agents/middleware/tool_emulator.py +251 -0
  24. coco/agents/middleware/tool_error.py +209 -0
  25. coco/agents/middleware/tool_retry.py +421 -0
  26. coco/agents/middleware/tool_selection.py +515 -0
  27. coco/agents/middleware/types.py +2201 -0
  28. coco/agents/structured_output.py +472 -0
  29. coco/chat_models/__init__.py +7 -0
  30. coco/chat_models/base.py +1082 -0
  31. coco/embeddings/__init__.py +18 -0
  32. coco/embeddings/base.py +279 -0
  33. coco/mcp/__init__.py +36 -0
  34. coco/mcp/adapter.py +245 -0
  35. coco/mcp/elicitation.py +394 -0
  36. coco/mcp/tools.py +307 -0
  37. coco/messages/__init__.py +73 -0
  38. coco/py.typed +0 -0
  39. coco/rate_limiters/__init__.py +13 -0
  40. coco/tools/__init__.py +22 -0
  41. coco/tools/tool_node.py +20 -0
  42. coco_anthropic/__init__.py +15 -0
  43. coco_anthropic/_client_utils.py +81 -0
  44. coco_anthropic/_compat.py +228 -0
  45. coco_anthropic/_sdk_compat.py +124 -0
  46. coco_anthropic/_version.py +3 -0
  47. coco_anthropic/chat_models.py +3349 -0
  48. coco_anthropic/data/__init__.py +1 -0
  49. coco_anthropic/data/_profiles.py +491 -0
  50. coco_anthropic/data/profile_augmentations.toml +69 -0
  51. coco_anthropic/experimental.py +140 -0
  52. coco_anthropic/llms.py +428 -0
  53. coco_anthropic/middleware/__init__.py +25 -0
  54. coco_anthropic/middleware/anthropic_tools.py +1197 -0
  55. coco_anthropic/middleware/bash.py +84 -0
  56. coco_anthropic/middleware/file_search.py +360 -0
  57. coco_anthropic/middleware/prompt_caching.py +276 -0
  58. coco_anthropic/output_parsers.py +93 -0
  59. coco_anthropic/py.typed +0 -0
  60. coco_core/__init__.py +20 -0
  61. coco_core/_api/__init__.py +87 -0
  62. coco_core/_api/beta_decorator.py +266 -0
  63. coco_core/_api/deprecation.py +637 -0
  64. coco_core/_api/internal.py +23 -0
  65. coco_core/_api/path.py +50 -0
  66. coco_core/_import_utils.py +41 -0
  67. coco_core/_protocol.py +625 -0
  68. coco_core/_security/__init__.py +36 -0
  69. coco_core/_security/_exceptions.py +9 -0
  70. coco_core/_security/_policy.py +313 -0
  71. coco_core/_security/_ssrf_protection.py +155 -0
  72. coco_core/_security/_transport.py +254 -0
  73. coco_core/agents.py +258 -0
  74. coco_core/caches.py +272 -0
  75. coco_core/callbacks/__init__.py +132 -0
  76. coco_core/callbacks/base.py +1229 -0
  77. coco_core/callbacks/file.py +266 -0
  78. coco_core/callbacks/manager.py +2826 -0
  79. coco_core/callbacks/stdout.py +123 -0
  80. coco_core/callbacks/streaming_stdout.py +154 -0
  81. coco_core/callbacks/usage.py +124 -0
  82. coco_core/chat_history.py +267 -0
  83. coco_core/chat_loaders.py +26 -0
  84. coco_core/chat_sessions.py +19 -0
  85. coco_core/cross_encoders.py +18 -0
  86. coco_core/document_loaders/__init__.py +36 -0
  87. coco_core/document_loaders/base.py +155 -0
  88. coco_core/document_loaders/blob_loaders.py +38 -0
  89. coco_core/documents/__init__.py +55 -0
  90. coco_core/documents/base.py +347 -0
  91. coco_core/documents/compressor.py +74 -0
  92. coco_core/documents/transformers.py +79 -0
  93. coco_core/embeddings/__init__.py +31 -0
  94. coco_core/embeddings/embeddings.py +78 -0
  95. coco_core/embeddings/fake.py +129 -0
  96. coco_core/env.py +22 -0
  97. coco_core/example_selectors/__init__.py +47 -0
  98. coco_core/example_selectors/base.py +60 -0
  99. coco_core/example_selectors/length_based.py +131 -0
  100. coco_core/example_selectors/semantic_similarity.py +366 -0
  101. coco_core/exceptions.py +166 -0
  102. coco_core/globals.py +72 -0
  103. coco_core/indexing/__init__.py +53 -0
  104. coco_core/indexing/api.py +954 -0
  105. coco_core/indexing/base.py +661 -0
  106. coco_core/indexing/in_memory.py +104 -0
  107. coco_core/language_models/__init__.py +116 -0
  108. coco_core/language_models/_compat_bridge.py +844 -0
  109. coco_core/language_models/_utils.py +343 -0
  110. coco_core/language_models/base.py +500 -0
  111. coco_core/language_models/chat_model_stream.py +1525 -0
  112. coco_core/language_models/chat_models.py +2748 -0
  113. coco_core/language_models/fake.py +137 -0
  114. coco_core/language_models/fake_chat_models.py +396 -0
  115. coco_core/language_models/llms.py +1569 -0
  116. coco_core/language_models/model_profile.py +183 -0
  117. coco_core/load/__init__.py +44 -0
  118. coco_core/load/_validation.py +191 -0
  119. coco_core/load/dump.py +120 -0
  120. coco_core/load/load.py +828 -0
  121. coco_core/load/mapping.py +1097 -0
  122. coco_core/load/serializable.py +406 -0
  123. coco_core/messages/__init__.py +198 -0
  124. coco_core/messages/ai.py +854 -0
  125. coco_core/messages/base.py +518 -0
  126. coco_core/messages/block_translators/__init__.py +112 -0
  127. coco_core/messages/block_translators/anthropic.py +534 -0
  128. coco_core/messages/block_translators/bedrock.py +108 -0
  129. coco_core/messages/block_translators/bedrock_converse.py +329 -0
  130. coco_core/messages/block_translators/coco_v0.py +303 -0
  131. coco_core/messages/block_translators/google_genai.py +610 -0
  132. coco_core/messages/block_translators/google_vertexai.py +21 -0
  133. coco_core/messages/block_translators/groq.py +157 -0
  134. coco_core/messages/block_translators/openai.py +1089 -0
  135. coco_core/messages/chat.py +64 -0
  136. coco_core/messages/content.py +1488 -0
  137. coco_core/messages/function.py +62 -0
  138. coco_core/messages/human.py +70 -0
  139. coco_core/messages/modifier.py +33 -0
  140. coco_core/messages/system.py +70 -0
  141. coco_core/messages/tool.py +418 -0
  142. coco_core/messages/utils.py +2442 -0
  143. coco_core/output_parsers/__init__.py +101 -0
  144. coco_core/output_parsers/base.py +361 -0
  145. coco_core/output_parsers/format_instructions.py +16 -0
  146. coco_core/output_parsers/json.py +139 -0
  147. coco_core/output_parsers/list.py +249 -0
  148. coco_core/output_parsers/openai_functions.py +324 -0
  149. coco_core/output_parsers/openai_tools.py +383 -0
  150. coco_core/output_parsers/pydantic.py +141 -0
  151. coco_core/output_parsers/string.py +63 -0
  152. coco_core/output_parsers/transform.py +175 -0
  153. coco_core/output_parsers/xml.py +301 -0
  154. coco_core/outputs/__init__.py +66 -0
  155. coco_core/outputs/chat_generation.py +147 -0
  156. coco_core/outputs/chat_result.py +39 -0
  157. coco_core/outputs/generation.py +80 -0
  158. coco_core/outputs/llm_result.py +112 -0
  159. coco_core/outputs/run_info.py +22 -0
  160. coco_core/prompt_values.py +161 -0
  161. coco_core/prompts/__init__.py +101 -0
  162. coco_core/prompts/base.py +508 -0
  163. coco_core/prompts/chat.py +1495 -0
  164. coco_core/prompts/dict.py +177 -0
  165. coco_core/prompts/few_shot.py +483 -0
  166. coco_core/prompts/few_shot_with_templates.py +239 -0
  167. coco_core/prompts/image.py +177 -0
  168. coco_core/prompts/loading.py +296 -0
  169. coco_core/prompts/message.py +97 -0
  170. coco_core/prompts/prompt.py +312 -0
  171. coco_core/prompts/string.py +399 -0
  172. coco_core/prompts/structured.py +214 -0
  173. coco_core/py.typed +0 -0
  174. coco_core/rate_limiters.py +254 -0
  175. coco_core/retrievers.py +328 -0
  176. coco_core/runnables/__init__.py +136 -0
  177. coco_core/runnables/base.py +6725 -0
  178. coco_core/runnables/branch.py +457 -0
  179. coco_core/runnables/config.py +712 -0
  180. coco_core/runnables/configurable.py +710 -0
  181. coco_core/runnables/fallbacks.py +663 -0
  182. coco_core/runnables/graph.py +741 -0
  183. coco_core/runnables/graph_ascii.py +366 -0
  184. coco_core/runnables/graph_mermaid.py +503 -0
  185. coco_core/runnables/graph_png.py +215 -0
  186. coco_core/runnables/history.py +631 -0
  187. coco_core/runnables/passthrough.py +849 -0
  188. coco_core/runnables/retry.py +379 -0
  189. coco_core/runnables/router.py +239 -0
  190. coco_core/runnables/schema.py +188 -0
  191. coco_core/runnables/utils.py +798 -0
  192. coco_core/stores.py +291 -0
  193. coco_core/structured_query.py +203 -0
  194. coco_core/sys_info.py +154 -0
  195. coco_core/tools/__init__.py +95 -0
  196. coco_core/tools/base.py +1948 -0
  197. coco_core/tools/convert.py +497 -0
  198. coco_core/tools/render.py +67 -0
  199. coco_core/tools/retriever.py +94 -0
  200. coco_core/tools/simple.py +208 -0
  201. coco_core/tools/structured.py +322 -0
  202. coco_core/tracers/__init__.py +47 -0
  203. coco_core/tracers/_compat.py +95 -0
  204. coco_core/tracers/_context.py +337 -0
  205. coco_core/tracers/_streaming.py +53 -0
  206. coco_core/tracers/base.py +955 -0
  207. coco_core/tracers/coco.py +279 -0
  208. coco_core/tracers/context.py +205 -0
  209. coco_core/tracers/core.py +766 -0
  210. coco_core/tracers/event_stream.py +1101 -0
  211. coco_core/tracers/log_stream.py +765 -0
  212. coco_core/tracers/memory_stream.py +200 -0
  213. coco_core/tracers/root_listeners.py +130 -0
  214. coco_core/tracers/run_collector.py +40 -0
  215. coco_core/tracers/schemas.py +14 -0
  216. coco_core/tracers/stdout.py +205 -0
  217. coco_core/utils/__init__.py +111 -0
  218. coco_core/utils/_gateway.py +274 -0
  219. coco_core/utils/_merge.py +218 -0
  220. coco_core/utils/aiter.py +357 -0
  221. coco_core/utils/env.py +86 -0
  222. coco_core/utils/formatting.py +80 -0
  223. coco_core/utils/function_calling.py +869 -0
  224. coco_core/utils/html.py +132 -0
  225. coco_core/utils/image.py +15 -0
  226. coco_core/utils/input.py +82 -0
  227. coco_core/utils/interactive_env.py +12 -0
  228. coco_core/utils/iter.py +229 -0
  229. coco_core/utils/json.py +230 -0
  230. coco_core/utils/json_schema.py +273 -0
  231. coco_core/utils/mustache.py +706 -0
  232. coco_core/utils/pydantic.py +631 -0
  233. coco_core/utils/strings.py +69 -0
  234. coco_core/utils/usage.py +61 -0
  235. coco_core/utils/utils.py +528 -0
  236. coco_core/utils/uuid.py +57 -0
  237. coco_core/vectorstores/__init__.py +53 -0
  238. coco_core/vectorstores/base.py +1111 -0
  239. coco_core/vectorstores/in_memory.py +546 -0
  240. coco_core/vectorstores/utils.py +163 -0
  241. coco_core/version.py +3 -0
  242. coco_framework-0.1.0.dist-info/METADATA +184 -0
  243. coco_framework-0.1.0.dist-info/RECORD +400 -0
  244. coco_framework-0.1.0.dist-info/WHEEL +4 -0
  245. coco_framework-0.1.0.dist-info/licenses/LICENSE +24 -0
  246. coco_framework-0.1.0.dist-info/licenses/NOTICE +15 -0
  247. coco_graph/_internal/__init__.py +4 -0
  248. coco_graph/_internal/_cache.py +31 -0
  249. coco_graph/_internal/_config.py +474 -0
  250. coco_graph/_internal/_constants.py +140 -0
  251. coco_graph/_internal/_fields.py +213 -0
  252. coco_graph/_internal/_future.py +220 -0
  253. coco_graph/_internal/_pydantic.py +275 -0
  254. coco_graph/_internal/_queue.py +124 -0
  255. coco_graph/_internal/_replay.py +90 -0
  256. coco_graph/_internal/_retry.py +29 -0
  257. coco_graph/_internal/_runnable.py +969 -0
  258. coco_graph/_internal/_scratchpad.py +19 -0
  259. coco_graph/_internal/_serde.py +253 -0
  260. coco_graph/_internal/_timeout.py +25 -0
  261. coco_graph/_internal/_typing.py +54 -0
  262. coco_graph/cache/base/__init__.py +48 -0
  263. coco_graph/cache/base/py.typed +0 -0
  264. coco_graph/cache/memory/__init__.py +73 -0
  265. coco_graph/cache/redis/__init__.py +144 -0
  266. coco_graph/cache/sqlite/__init__.py +120 -0
  267. coco_graph/callbacks.py +394 -0
  268. coco_graph/channels/__init__.py +29 -0
  269. coco_graph/channels/any_value.py +72 -0
  270. coco_graph/channels/base.py +121 -0
  271. coco_graph/channels/binop.py +155 -0
  272. coco_graph/channels/delta.py +202 -0
  273. coco_graph/channels/ephemeral_value.py +79 -0
  274. coco_graph/channels/last_value.py +151 -0
  275. coco_graph/channels/named_barrier_value.py +167 -0
  276. coco_graph/channels/topic.py +94 -0
  277. coco_graph/channels/untracked_value.py +73 -0
  278. coco_graph/checkpoint/base/__init__.py +861 -0
  279. coco_graph/checkpoint/base/id.py +109 -0
  280. coco_graph/checkpoint/base/py.typed +0 -0
  281. coco_graph/checkpoint/memory/__init__.py +698 -0
  282. coco_graph/checkpoint/memory/py.typed +0 -0
  283. coco_graph/checkpoint/postgres/__init__.py +602 -0
  284. coco_graph/checkpoint/postgres/_ainternal.py +23 -0
  285. coco_graph/checkpoint/postgres/_internal.py +21 -0
  286. coco_graph/checkpoint/postgres/aio.py +691 -0
  287. coco_graph/checkpoint/postgres/base.py +666 -0
  288. coco_graph/checkpoint/postgres/py.typed +0 -0
  289. coco_graph/checkpoint/postgres/shallow.py +967 -0
  290. coco_graph/checkpoint/serde/__init__.py +0 -0
  291. coco_graph/checkpoint/serde/_msgpack.py +97 -0
  292. coco_graph/checkpoint/serde/base.py +64 -0
  293. coco_graph/checkpoint/serde/encrypted.py +80 -0
  294. coco_graph/checkpoint/serde/event_hooks.py +52 -0
  295. coco_graph/checkpoint/serde/jsonplus.py +883 -0
  296. coco_graph/checkpoint/serde/py.typed +0 -0
  297. coco_graph/checkpoint/serde/types.py +68 -0
  298. coco_graph/checkpoint/sqlite/__init__.py +645 -0
  299. coco_graph/checkpoint/sqlite/_delta.py +172 -0
  300. coco_graph/checkpoint/sqlite/aio.py +738 -0
  301. coco_graph/checkpoint/sqlite/py.typed +0 -0
  302. coco_graph/checkpoint/sqlite/utils.py +116 -0
  303. coco_graph/config.py +196 -0
  304. coco_graph/constants.py +64 -0
  305. coco_graph/errors.py +241 -0
  306. coco_graph/func/__init__.py +620 -0
  307. coco_graph/graph/__init__.py +12 -0
  308. coco_graph/graph/_branch.py +225 -0
  309. coco_graph/graph/_node.py +103 -0
  310. coco_graph/graph/message.py +437 -0
  311. coco_graph/graph/state.py +1978 -0
  312. coco_graph/graph/ui.py +227 -0
  313. coco_graph/managed/__init__.py +3 -0
  314. coco_graph/managed/base.py +31 -0
  315. coco_graph/managed/is_last_step.py +24 -0
  316. coco_graph/prebuilt/__init__.py +23 -0
  317. coco_graph/prebuilt/_tool_call_stream.py +117 -0
  318. coco_graph/prebuilt/_tool_call_transformer.py +165 -0
  319. coco_graph/prebuilt/chat_agent_executor.py +1015 -0
  320. coco_graph/prebuilt/interrupt.py +105 -0
  321. coco_graph/prebuilt/py.typed +0 -0
  322. coco_graph/prebuilt/tool_node.py +2030 -0
  323. coco_graph/prebuilt/tool_validator.py +221 -0
  324. coco_graph/pregel/__init__.py +3 -0
  325. coco_graph/pregel/_algo.py +1460 -0
  326. coco_graph/pregel/_call.py +298 -0
  327. coco_graph/pregel/_checkpoint.py +331 -0
  328. coco_graph/pregel/_config.py +0 -0
  329. coco_graph/pregel/_draw.py +294 -0
  330. coco_graph/pregel/_executor.py +223 -0
  331. coco_graph/pregel/_io.py +174 -0
  332. coco_graph/pregel/_log.py +3 -0
  333. coco_graph/pregel/_loop.py +1988 -0
  334. coco_graph/pregel/_messages.py +461 -0
  335. coco_graph/pregel/_read.py +312 -0
  336. coco_graph/pregel/_retry.py +854 -0
  337. coco_graph/pregel/_runner.py +941 -0
  338. coco_graph/pregel/_tools.py +268 -0
  339. coco_graph/pregel/_utils.py +221 -0
  340. coco_graph/pregel/_validate.py +120 -0
  341. coco_graph/pregel/_write.py +192 -0
  342. coco_graph/pregel/debug.py +302 -0
  343. coco_graph/pregel/main.py +4364 -0
  344. coco_graph/pregel/protocol.py +288 -0
  345. coco_graph/pregel/types.py +38 -0
  346. coco_graph/py.typed +0 -0
  347. coco_graph/runtime.py +350 -0
  348. coco_graph/store/base/__init__.py +1322 -0
  349. coco_graph/store/base/batch.py +371 -0
  350. coco_graph/store/base/embed.py +436 -0
  351. coco_graph/store/base/py.typed +0 -0
  352. coco_graph/store/memory/__init__.py +592 -0
  353. coco_graph/store/memory/py.typed +0 -0
  354. coco_graph/store/postgres/__init__.py +4 -0
  355. coco_graph/store/postgres/aio.py +592 -0
  356. coco_graph/store/postgres/base.py +1480 -0
  357. coco_graph/store/postgres/py.typed +0 -0
  358. coco_graph/store/sqlite/__init__.py +4 -0
  359. coco_graph/store/sqlite/aio.py +632 -0
  360. coco_graph/store/sqlite/base.py +1514 -0
  361. coco_graph/stream/__init__.py +45 -0
  362. coco_graph/stream/_convert.py +32 -0
  363. coco_graph/stream/_mux.py +523 -0
  364. coco_graph/stream/_types.py +330 -0
  365. coco_graph/stream/run_stream.py +735 -0
  366. coco_graph/stream/stream_channel.py +341 -0
  367. coco_graph/stream/transformers.py +1039 -0
  368. coco_graph/types.py +1079 -0
  369. coco_graph/typing.py +48 -0
  370. coco_graph/utils/__init__.py +1 -0
  371. coco_graph/utils/config.py +4 -0
  372. coco_graph/utils/runnable.py +3 -0
  373. coco_graph/version.py +13 -0
  374. coco_graph/warnings.py +69 -0
  375. coco_openai/__init__.py +20 -0
  376. coco_openai/_compat.py +45 -0
  377. coco_openai/_version.py +3 -0
  378. coco_openai/chat_models/__init__.py +6 -0
  379. coco_openai/chat_models/_client_utils.py +684 -0
  380. coco_openai/chat_models/_compat.py +525 -0
  381. coco_openai/chat_models/azure.py +1227 -0
  382. coco_openai/chat_models/base.py +5654 -0
  383. coco_openai/chat_models/codex.py +557 -0
  384. coco_openai/chatgpt_oauth.py +1063 -0
  385. coco_openai/data/__init__.py +1 -0
  386. coco_openai/data/_profiles.py +1655 -0
  387. coco_openai/data/profile_augmentations.toml +127 -0
  388. coco_openai/embeddings/__init__.py +6 -0
  389. coco_openai/embeddings/azure.py +240 -0
  390. coco_openai/embeddings/base.py +820 -0
  391. coco_openai/llms/__init__.py +6 -0
  392. coco_openai/llms/azure.py +249 -0
  393. coco_openai/llms/base.py +919 -0
  394. coco_openai/middleware/__init__.py +11 -0
  395. coco_openai/middleware/openai_moderation.py +484 -0
  396. coco_openai/output_parsers/__init__.py +9 -0
  397. coco_openai/output_parsers/tools.py +9 -0
  398. coco_openai/py.typed +0 -0
  399. coco_openai/tools/__init__.py +5 -0
  400. coco_openai/tools/custom_tool.py +111 -0
@@ -0,0 +1,910 @@
1
+ """Summarization middleware."""
2
+
3
+ import logging
4
+ import uuid
5
+ import warnings
6
+ from collections.abc import Callable, Iterable, Mapping
7
+ from functools import partial
8
+ from typing import Any, Literal, TypedDict, cast
9
+
10
+ from coco_core.messages import (
11
+ AIMessage,
12
+ AnyMessage,
13
+ MessageLikeRepresentation,
14
+ RemoveMessage,
15
+ ToolMessage,
16
+ )
17
+ from coco_core.messages.human import HumanMessage
18
+ from coco_core.messages.utils import (
19
+ count_tokens_approximately,
20
+ get_buffer_string,
21
+ trim_messages,
22
+ )
23
+ from coco_graph.graph.message import (
24
+ REMOVE_ALL_MESSAGES,
25
+ )
26
+ from coco_graph.runtime import Runtime
27
+ from typing_extensions import override
28
+
29
+ from coco.agents.middleware.internal_call_transformer import (
30
+ InternalCallTransformer,
31
+ internal_call_metadata,
32
+ )
33
+ from coco.agents.middleware.types import AgentMiddleware, AgentState, ContextT, ResponseT
34
+ from coco.chat_models import BaseChatModel, init_chat_model
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ TokenCounter = Callable[[Iterable[MessageLikeRepresentation]], int]
39
+
40
+ DEFAULT_SUMMARY_PROMPT = """<role>
41
+ Context Extraction Assistant
42
+ </role>
43
+
44
+ <primary_objective>
45
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
46
+ </primary_objective>
47
+
48
+ <objective_information>
49
+ You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
50
+ This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to continue working toward your overall goal.
51
+ </objective_information>
52
+
53
+ <instructions>
54
+ The conversation history below will be replaced with the context you extract in this step.
55
+ You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
56
+
57
+ You should structure your summary using the following sections. Each section acts as a checklist - you must populate it with relevant information or explicitly state "None" if there is nothing to report for that section:
58
+
59
+ ## SESSION INTENT
60
+
61
+ What is the user's primary goal or request? What overall task are you trying to accomplish? This should be concise but complete enough to understand the purpose of the entire session.
62
+
63
+ ## SUMMARY
64
+
65
+ Extract and record all of the most important context from the conversation history. Include important choices, conclusions, or strategies determined during this conversation. Include the reasoning behind key decisions. Document any rejected options and why they were not pursued.
66
+
67
+ ## ARTIFACTS
68
+
69
+ What artifacts, files, or resources were created, modified, or accessed during this conversation? For file modifications, list specific file paths and briefly describe the changes made to each. This section prevents silent loss of artifact information.
70
+
71
+ ## NEXT STEPS
72
+
73
+ What specific tasks remain to be completed to achieve the session intent? What should you do next?
74
+
75
+ </instructions>
76
+
77
+ The user will message you with the full message history from which you'll extract context to create a replacement. Carefully read through it all and think deeply about what information is most important to your overall goal and should be saved:
78
+
79
+ With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
80
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
81
+
82
+ <messages>
83
+ Messages to summarize:
84
+ {messages}
85
+ </messages>""" # noqa: E501
86
+ """Default prompt used to summarize conversation history.
87
+
88
+ The `<messages>` marker (on its own line) and the `{messages}` placeholder are
89
+ part of this constant's public contract, not just cosmetic formatting.
90
+ Downstream consumers depend on them: for example, deep agents'
91
+ `SummarizationMiddleware` splices an extra instruction block in immediately
92
+ before the `<messages>` marker via `str.replace`. Removing, renaming, or
93
+ reformatting the marker (or the `{messages}` placeholder) is a breaking change
94
+ for those consumers even though it does not alter any function signature, so
95
+ treat edits to it accordingly.
96
+ """
97
+
98
+ _DEFAULT_MESSAGES_TO_KEEP = 20
99
+ _DEFAULT_TRIM_TOKEN_LIMIT = 4000
100
+ _DEFAULT_FALLBACK_MESSAGE_COUNT = 15
101
+
102
+ # Some providers tag emitted messages with a `model_provider` string that differs from
103
+ # their LangSmith `ls_provider`. The reported-token check below compares the two, so we
104
+ # accept known aliases per `ls_provider`.
105
+ _LS_PROVIDER_ALIASES: dict[str, frozenset[str]] = {
106
+ "amazon_bedrock": frozenset({"bedrock", "bedrock_converse"}),
107
+ # ChatOpenAIMantle traces under ls_provider="openai-mantle" but its messages
108
+ # inherit model_provider="openai" from BaseChatOpenAI.
109
+ "openai-mantle": frozenset({"openai"}),
110
+ # ChatAnthropicMantle traces under ls_provider="anthropic-mantle" but its
111
+ # messages inherit model_provider="anthropic" from BaseChatAnthropic.
112
+ "anthropic-mantle": frozenset({"anthropic"}),
113
+ }
114
+
115
+
116
+ def _provider_matches(message_provider: str, model_ls_provider: str | None) -> bool:
117
+ if model_ls_provider is None:
118
+ return False
119
+ if message_provider == model_ls_provider:
120
+ return True
121
+ aliases = _LS_PROVIDER_ALIASES.get(model_ls_provider)
122
+ return aliases is not None and message_provider in aliases
123
+
124
+
125
+ ContextFraction = tuple[Literal["fraction"], float]
126
+ """Fraction of model's maximum input tokens.
127
+
128
+ Example:
129
+ To specify 50% of the model's max input tokens:
130
+
131
+ ```python
132
+ ("fraction", 0.5)
133
+ ```
134
+ """
135
+
136
+ ContextTokens = tuple[Literal["tokens"], int]
137
+ """Absolute number of tokens.
138
+
139
+ Example:
140
+ To specify 3000 tokens:
141
+
142
+ ```python
143
+ ("tokens", 3000)
144
+ ```
145
+ """
146
+
147
+ ContextMessages = tuple[Literal["messages"], int]
148
+ """Absolute number of messages.
149
+
150
+ Example:
151
+ To specify 50 messages:
152
+
153
+ ```python
154
+ ("messages", 50)
155
+ ```
156
+ """
157
+
158
+ ContextSize = ContextFraction | ContextTokens | ContextMessages
159
+ """Union type for context size specifications.
160
+
161
+ Can be either:
162
+
163
+ - [`ContextFraction`][coco.agents.middleware.summarization.ContextFraction]: A
164
+ fraction of the model's maximum input tokens.
165
+ - [`ContextTokens`][coco.agents.middleware.summarization.ContextTokens]: An absolute
166
+ number of tokens.
167
+ - [`ContextMessages`][coco.agents.middleware.summarization.ContextMessages]: An
168
+ absolute number of messages.
169
+
170
+ Depending on use with `trigger` or `keep` parameters, this type indicates either
171
+ when to trigger summarization or how much context to retain.
172
+
173
+ Example:
174
+ ```python
175
+ # ContextFraction
176
+ context_size: ContextSize = ("fraction", 0.5)
177
+
178
+ # ContextTokens
179
+ context_size: ContextSize = ("tokens", 3000)
180
+
181
+ # ContextMessages
182
+ context_size: ContextSize = ("messages", 50)
183
+ ```
184
+ """
185
+
186
+
187
+ class TriggerClause(TypedDict, total=False):
188
+ """Dictionary-based trigger specification for AND conditions.
189
+
190
+ All specified thresholds in a single `TriggerClause` must be met for the clause to
191
+ trigger summarization (AND semantics). When multiple clauses are provided in a list,
192
+ summarization triggers if any clause is met (OR semantics).
193
+
194
+ Example:
195
+ ```python
196
+ # AND: Trigger when tokens >= 4000 AND messages >= 10
197
+ trigger_clause: TriggerClause = {"tokens": 4000, "messages": 10}
198
+
199
+ # Use in a list for OR semantics:
200
+ trigger_list: list[TriggerClause] = [
201
+ {"tokens": 5000, "messages": 3},
202
+ {"tokens": 3000, "messages": 6},
203
+ ]
204
+ ```
205
+ """
206
+
207
+ tokens: int
208
+ """Trigger when the computed (or provider-reported) token count reaches or
209
+ exceeds this value.
210
+ """
211
+
212
+ messages: int
213
+ """Trigger when message count reaches or exceeds this value."""
214
+
215
+ fraction: float
216
+ """Trigger when the computed (or provider-reported) token count reaches or
217
+ exceeds this fraction of the model's maximum input tokens.
218
+ """
219
+
220
+
221
+ def _get_approximate_token_counter(model: BaseChatModel) -> TokenCounter:
222
+ """Tune parameters of approximate token counter based on model type."""
223
+ if model._llm_type.startswith("anthropic-chat"): # noqa: SLF001
224
+ # 3.3 was estimated in an offline experiment, comparing with Claude's token-counting
225
+ # API: https://platform.claude.com/docs/en/build-with-claude/token-counting
226
+ return partial(
227
+ count_tokens_approximately, use_usage_metadata_scaling=True, chars_per_token=3.3
228
+ )
229
+ return partial(count_tokens_approximately, use_usage_metadata_scaling=True)
230
+
231
+
232
+ class SummarizationMiddleware(AgentMiddleware[AgentState[ResponseT], ContextT, ResponseT]):
233
+ """Summarizes conversation history when token limits are approached.
234
+
235
+ This middleware monitors message token counts and automatically summarizes older
236
+ messages when a threshold is reached, preserving recent messages and maintaining
237
+ context continuity by ensuring AI/Tool message pairs remain together.
238
+
239
+ Transient summary-generation errors (rate limits, timeouts) are retried
240
+ in-process, up to 3 attempts total, via `Runnable.with_retry`. If a summary call
241
+ still fails after those attempts, the underlying error propagates rather than
242
+ fabricating a summary.
243
+ """
244
+
245
+ transformers = (InternalCallTransformer,)
246
+ """Keeps the summarization model call's tokens out of `run.messages`.
247
+
248
+ Registered only when this middleware is used — see
249
+ `InternalCallTransformer` for why the call needs tagging and filtering.
250
+ """
251
+
252
+ def __init__(
253
+ self,
254
+ model: str | BaseChatModel,
255
+ *,
256
+ trigger: (ContextSize | TriggerClause | list[ContextSize | TriggerClause] | None) = None,
257
+ keep: ContextSize = ("messages", _DEFAULT_MESSAGES_TO_KEEP),
258
+ token_counter: TokenCounter = count_tokens_approximately,
259
+ summary_prompt: str = DEFAULT_SUMMARY_PROMPT,
260
+ trim_tokens_to_summarize: int | None = _DEFAULT_TRIM_TOKEN_LIMIT,
261
+ **deprecated_kwargs: Any,
262
+ ) -> None:
263
+ """Initialize summarization middleware.
264
+
265
+ Args:
266
+ model: The language model to use for generating summaries.
267
+ trigger: One or more thresholds that trigger summarization.
268
+
269
+ Provide a single
270
+ [`ContextSize`][coco.agents.middleware.summarization.ContextSize]
271
+ tuple, or a single
272
+ [`TriggerClause`][coco.agents.middleware.summarization.TriggerClause]
273
+ dict, or a list mixing either form.
274
+
275
+ A `ContextSize` tuple expresses one threshold. A `TriggerClause` dict
276
+ expresses multiple thresholds that must *all* be met (AND). When a list is
277
+ provided, summarization runs if *any* item is met (OR).
278
+
279
+ !!! example
280
+
281
+ ```python
282
+ # Trigger summarization when 50 messages is reached
283
+ ("messages", 50)
284
+
285
+ # Trigger summarization when 3000 tokens is reached
286
+ ("tokens", 3000)
287
+
288
+ # Trigger summarization either when 80% of model's max input tokens
289
+ # is reached or when 100 messages is reached (whichever comes first)
290
+ [("fraction", 0.8), ("messages", 100)]
291
+
292
+ # Trigger when tokens >= 4000 AND messages >= 10
293
+ {"tokens": 4000, "messages": 10}
294
+
295
+ # Trigger when (tokens >= 5000 AND messages >= 3) OR
296
+ # (tokens >= 3000 AND messages >= 6)
297
+ [{"tokens": 5000, "messages": 3}, {"tokens": 3000, "messages": 6}]
298
+ ```
299
+
300
+ See [`ContextSize`][coco.agents.middleware.summarization.ContextSize]
301
+ for more details.
302
+ keep: Context retention policy applied after summarization.
303
+
304
+ Provide a [`ContextSize`][coco.agents.middleware.summarization.ContextSize]
305
+ tuple to specify how much history to preserve.
306
+
307
+ Defaults to keeping the most recent `20` messages.
308
+
309
+ Does not support multiple values like `trigger`.
310
+
311
+ !!! example
312
+
313
+ ```python
314
+ # Keep the most recent 20 messages
315
+ ("messages", 20)
316
+
317
+ # Keep the most recent 3000 tokens
318
+ ("tokens", 3000)
319
+
320
+ # Keep the most recent 30% of the model's max input tokens
321
+ ("fraction", 0.3)
322
+ ```
323
+ token_counter: Function to count tokens in messages.
324
+ summary_prompt: Prompt template for generating summaries.
325
+ trim_tokens_to_summarize: Maximum tokens to keep when preparing messages for
326
+ the summarization call.
327
+
328
+ Pass `None` to skip trimming entirely.
329
+ """
330
+ # Handle deprecated parameters
331
+ if "max_tokens_before_summary" in deprecated_kwargs:
332
+ value = deprecated_kwargs["max_tokens_before_summary"]
333
+ warnings.warn(
334
+ "max_tokens_before_summary is deprecated. Use trigger=('tokens', value) instead.",
335
+ DeprecationWarning,
336
+ stacklevel=2,
337
+ )
338
+ if trigger is None and value is not None:
339
+ trigger = ("tokens", value)
340
+
341
+ if "messages_to_keep" in deprecated_kwargs:
342
+ value = deprecated_kwargs["messages_to_keep"]
343
+ warnings.warn(
344
+ "messages_to_keep is deprecated. Use keep=('messages', value) instead.",
345
+ DeprecationWarning,
346
+ stacklevel=2,
347
+ )
348
+ if keep == ("messages", _DEFAULT_MESSAGES_TO_KEEP):
349
+ keep = ("messages", value)
350
+
351
+ super().__init__()
352
+
353
+ if isinstance(model, str):
354
+ model = init_chat_model(model)
355
+
356
+ self.model = model
357
+ # Retry transient errors (rate limits, timeouts) in-process, up to 3 attempts
358
+ # total, before giving up. See `Runnable.with_retry`.
359
+ self._summary_model = self.model.with_retry()
360
+
361
+ self.trigger: ContextSize | TriggerClause | list[ContextSize | TriggerClause] | None = (
362
+ self._copy_trigger(trigger)
363
+ )
364
+
365
+ # Canonical trigger representation: AND within a clause, OR across clauses.
366
+ self._trigger_clauses = self._normalize_trigger(self.trigger)
367
+ # Legacy compatibility view for private consumers that inspected the previous
368
+ # tuple-normalized representation. Coco behavior is driven by
369
+ # `_trigger_clauses`, not this attribute. Remove in Coco 2.0.
370
+ self._trigger_conditions = self._legacy_trigger_conditions(self.trigger)
371
+
372
+ self.keep = self._validate_context_size(keep, "keep")
373
+ if token_counter is count_tokens_approximately:
374
+ self.token_counter = _get_approximate_token_counter(self.model)
375
+ self._partial_token_counter: TokenCounter = partial( # type: ignore[call-arg]
376
+ self.token_counter, use_usage_metadata_scaling=False
377
+ )
378
+ else:
379
+ self.token_counter = token_counter
380
+ self._partial_token_counter = token_counter
381
+ self.summary_prompt = summary_prompt
382
+ self.trim_tokens_to_summarize = trim_tokens_to_summarize
383
+
384
+ requires_profile = any("fraction" in clause for clause in self._trigger_clauses)
385
+ if self.keep[0] == "fraction":
386
+ requires_profile = True
387
+ if requires_profile and self._get_profile_limits() is None:
388
+ msg = (
389
+ "Model profile information is required to use fractional token limits, "
390
+ "and is unavailable for the specified model. Please use absolute token "
391
+ "counts instead, or pass "
392
+ '`\n\nChatModel(..., profile={"max_input_tokens": ...})`.\n\n'
393
+ "with a desired integer value of the model's maximum input tokens."
394
+ )
395
+ raise ValueError(msg)
396
+
397
+ @override
398
+ def before_model(
399
+ self, state: AgentState[Any], runtime: Runtime[ContextT]
400
+ ) -> dict[str, Any] | None:
401
+ """Process messages before model invocation, potentially triggering summarization.
402
+
403
+ Args:
404
+ state: The agent state.
405
+ runtime: The runtime environment.
406
+
407
+ Returns:
408
+ An updated state with summarized messages if summarization was performed.
409
+
410
+ Raises:
411
+ Exception: If summary generation still fails once retries are exhausted.
412
+ """
413
+ messages = state["messages"]
414
+ self._ensure_message_ids(messages)
415
+
416
+ total_tokens = self.token_counter(messages)
417
+ if not self._should_summarize(messages, total_tokens):
418
+ return None
419
+
420
+ cutoff_index = self._determine_cutoff_index(messages)
421
+
422
+ if cutoff_index <= 0:
423
+ return None
424
+
425
+ messages_to_summarize, preserved_messages = self._partition_messages(messages, cutoff_index)
426
+
427
+ summary = self._create_summary(messages_to_summarize)
428
+ new_messages = self._build_new_messages(summary)
429
+
430
+ return {
431
+ "messages": [
432
+ RemoveMessage(id=REMOVE_ALL_MESSAGES),
433
+ *new_messages,
434
+ *preserved_messages,
435
+ ]
436
+ }
437
+
438
+ @override
439
+ async def abefore_model(
440
+ self, state: AgentState[Any], runtime: Runtime[ContextT]
441
+ ) -> dict[str, Any] | None:
442
+ """Process messages before model invocation, potentially triggering summarization.
443
+
444
+ Args:
445
+ state: The agent state.
446
+ runtime: The runtime environment.
447
+
448
+ Returns:
449
+ An updated state with summarized messages if summarization was performed.
450
+
451
+ Raises:
452
+ Exception: If summary generation still fails once retries are exhausted.
453
+ """
454
+ messages = state["messages"]
455
+ self._ensure_message_ids(messages)
456
+
457
+ total_tokens = self.token_counter(messages)
458
+ if not self._should_summarize(messages, total_tokens):
459
+ return None
460
+
461
+ cutoff_index = self._determine_cutoff_index(messages)
462
+
463
+ if cutoff_index <= 0:
464
+ return None
465
+
466
+ messages_to_summarize, preserved_messages = self._partition_messages(messages, cutoff_index)
467
+
468
+ summary = await self._acreate_summary(messages_to_summarize)
469
+ new_messages = self._build_new_messages(summary)
470
+
471
+ return {
472
+ "messages": [
473
+ RemoveMessage(id=REMOVE_ALL_MESSAGES),
474
+ *new_messages,
475
+ *preserved_messages,
476
+ ]
477
+ }
478
+
479
+ @staticmethod
480
+ def _copy_trigger(
481
+ trigger: ContextSize | TriggerClause | list[ContextSize | TriggerClause] | None,
482
+ ) -> ContextSize | TriggerClause | list[ContextSize | TriggerClause] | None:
483
+ """Copy mutable trigger containers so caller mutations do not affect this instance."""
484
+ if isinstance(trigger, Mapping):
485
+ return cast("TriggerClause", dict(trigger))
486
+ if isinstance(trigger, list):
487
+ return [
488
+ cast("TriggerClause", dict(item)) if isinstance(item, Mapping) else item
489
+ for item in trigger
490
+ ]
491
+ return trigger
492
+
493
+ def _legacy_trigger_conditions(
494
+ self,
495
+ trigger: ContextSize | TriggerClause | list[ContextSize | TriggerClause] | None,
496
+ ) -> list[ContextSize]:
497
+ """Project tuple-expressible triggers to the legacy private representation."""
498
+ if trigger is None:
499
+ return []
500
+ if isinstance(trigger, tuple):
501
+ return [self._validate_context_size(trigger, "trigger")]
502
+ if isinstance(trigger, Mapping):
503
+ if len(trigger) != 1:
504
+ return []
505
+ kind, value = next(iter(trigger.items()))
506
+ return [self._validate_context_size(cast("ContextSize", (kind, value)), "trigger")]
507
+
508
+ conditions: list[ContextSize] = []
509
+ for item in trigger:
510
+ if isinstance(item, tuple):
511
+ conditions.append(self._validate_context_size(item, "trigger"))
512
+ elif isinstance(item, Mapping) and len(item) == 1:
513
+ kind, value = next(iter(item.items()))
514
+ conditions.append(
515
+ self._validate_context_size(cast("ContextSize", (kind, value)), "trigger")
516
+ )
517
+ return conditions
518
+
519
+ def _normalize_trigger(
520
+ self,
521
+ trigger: (ContextSize | TriggerClause | list[ContextSize | TriggerClause] | None),
522
+ ) -> list[TriggerClause]:
523
+ """Normalize supported trigger inputs into list of Trigger clauses.
524
+
525
+ - tuple ("tokens", 3000) -> [{"tokens": 3000}]
526
+ - dict {"tokens": 4000, "messages": 10} -> [{"tokens": 4000, "messages": 10}]
527
+ - list of either -> OR across items
528
+ """
529
+ if trigger is None:
530
+ return []
531
+
532
+ def _validate_and_convert_tuple(t: ContextSize) -> TriggerClause:
533
+ kind, value = self._validate_context_size(t, "trigger")
534
+ return cast("TriggerClause", {kind: value})
535
+
536
+ def _validate_mapping(m: Mapping[str, Any]) -> TriggerClause:
537
+ """Validate and convert a mapping to a TriggerClause.
538
+
539
+ Type checks reject silent coercion (booleans, numeric strings, and
540
+ fractional floats for integer metrics) so a misconfigured clause fails loudly
541
+ at construction. Range and positivity checks are delegated to
542
+ `_validate_context_size`, keeping a single source of truth for the rules and
543
+ error messages shared with the tuple form.
544
+ """
545
+ if not m:
546
+ msg = "trigger clause must specify at least one of 'tokens', 'messages', 'fraction'"
547
+ raise ValueError(msg)
548
+ out: dict[str, float | int] = {}
549
+ for k, v in m.items():
550
+ if k not in {"tokens", "messages", "fraction"}:
551
+ msg = f"Unsupported trigger metric: {k!r}"
552
+ raise ValueError(msg)
553
+ # `bool` is an `int` subclass; reject it so `{"messages": True}` cannot
554
+ # silently become a threshold of 1. Raise `ValueError` (not `TypeError`)
555
+ # so every trigger-config error stays one catchable type.
556
+ if isinstance(v, bool):
557
+ msg = f"{k} trigger value must be numeric, got {v!r}"
558
+ raise ValueError(msg) # noqa: TRY004
559
+ if k == "fraction":
560
+ if not isinstance(v, (int, float)):
561
+ msg = f"Fraction trigger values must be numeric, got {v!r}"
562
+ raise ValueError(msg)
563
+ elif not isinstance(v, int):
564
+ # Reject floats and numeric strings rather than truncating/coercing.
565
+ msg = f"{k} trigger values must be integers, got {v!r}"
566
+ raise ValueError(msg)
567
+ # Delegate range/positivity validation so dict and tuple forms share
568
+ # identical rules and error messages.
569
+ self._validate_context_size(cast("ContextSize", (k, v)), "trigger")
570
+ out[k] = v
571
+ return cast("TriggerClause", out)
572
+
573
+ clauses: list[TriggerClause] = []
574
+ # `trigger` may originate from untyped callers, so dispatch on the runtime type
575
+ # and raise on anything unsupported.
576
+ subject: Any = trigger
577
+ if isinstance(subject, Mapping):
578
+ clauses.append(_validate_mapping(subject))
579
+ elif isinstance(subject, tuple):
580
+ clauses.append(_validate_and_convert_tuple(cast("ContextSize", subject)))
581
+ elif isinstance(subject, list):
582
+ for item in subject:
583
+ if isinstance(item, Mapping):
584
+ clauses.append(_validate_mapping(item))
585
+ elif isinstance(item, tuple):
586
+ clauses.append(_validate_and_convert_tuple(cast("ContextSize", item)))
587
+ else:
588
+ msg = f"Unsupported trigger item type: {type(item)}"
589
+ raise TypeError(msg)
590
+ else:
591
+ msg = f"Unsupported trigger type: {type(subject)}"
592
+ raise TypeError(msg)
593
+ return clauses
594
+
595
+ def _should_summarize_based_on_reported_tokens(
596
+ self, messages: list[AnyMessage], threshold: float
597
+ ) -> bool:
598
+ """Check if reported token usage from last AIMessage exceeds threshold."""
599
+ last_ai_message = next(
600
+ (msg for msg in reversed(messages) if isinstance(msg, AIMessage)),
601
+ None,
602
+ )
603
+ if ( # noqa: SIM103
604
+ isinstance(last_ai_message, AIMessage)
605
+ and last_ai_message.usage_metadata is not None
606
+ and (reported_tokens := last_ai_message.usage_metadata.get("total_tokens", -1))
607
+ and reported_tokens >= threshold
608
+ and (message_provider := last_ai_message.response_metadata.get("model_provider"))
609
+ and _provider_matches(
610
+ message_provider,
611
+ self.model._get_ls_params().get("ls_provider"), # noqa: SLF001
612
+ )
613
+ ):
614
+ return True
615
+ return False
616
+
617
+ def _should_summarize(self, messages: list[AnyMessage], total_tokens: int) -> bool:
618
+ """Determine whether summarization should run for the current token usage."""
619
+ if not self._trigger_clauses:
620
+ return False
621
+
622
+ for clause in self._trigger_clauses:
623
+ clause_met = True
624
+ for kind, value in clause.items():
625
+ if kind == "messages" and len(messages) < cast("int", value):
626
+ clause_met = False
627
+ break
628
+ if kind == "tokens":
629
+ threshold_tokens = cast("int", value)
630
+ # Trigger if total tokens exceed threshold OR reported tokens do
631
+ if (
632
+ total_tokens < threshold_tokens
633
+ and not self._should_summarize_based_on_reported_tokens(
634
+ messages, float(threshold_tokens)
635
+ )
636
+ ):
637
+ clause_met = False
638
+ break
639
+ if kind == "fraction":
640
+ max_input_tokens = self._get_profile_limits()
641
+ if max_input_tokens is None:
642
+ clause_met = False
643
+ break
644
+ threshold = int(max_input_tokens * cast("float", value))
645
+ if threshold <= 0:
646
+ threshold = 1
647
+ if (
648
+ total_tokens < threshold
649
+ and not self._should_summarize_based_on_reported_tokens(
650
+ messages, float(threshold)
651
+ )
652
+ ):
653
+ clause_met = False
654
+ break
655
+ if clause_met:
656
+ return True
657
+ return False
658
+
659
+ def _determine_cutoff_index(self, messages: list[AnyMessage]) -> int:
660
+ """Choose cutoff index respecting retention configuration."""
661
+ kind, value = self.keep
662
+ if kind in {"tokens", "fraction"}:
663
+ token_based_cutoff = self._find_token_based_cutoff(messages)
664
+ if token_based_cutoff is not None:
665
+ return token_based_cutoff
666
+ # None cutoff -> model profile data not available (caught in __init__ but
667
+ # here for safety), fallback to message count
668
+ return self._find_safe_cutoff(messages, _DEFAULT_MESSAGES_TO_KEEP)
669
+ return self._find_safe_cutoff(messages, cast("int", value))
670
+
671
+ def _find_token_based_cutoff(self, messages: list[AnyMessage]) -> int | None:
672
+ """Find cutoff index based on target token retention."""
673
+ if not messages:
674
+ return 0
675
+
676
+ kind, value = self.keep
677
+ if kind == "fraction":
678
+ max_input_tokens = self._get_profile_limits()
679
+ if max_input_tokens is None:
680
+ return None
681
+ target_token_count = int(max_input_tokens * value)
682
+ elif kind == "tokens":
683
+ target_token_count = int(value)
684
+ else:
685
+ return None
686
+
687
+ if target_token_count <= 0:
688
+ target_token_count = 1
689
+
690
+ if self.token_counter(messages) <= target_token_count:
691
+ return 0
692
+
693
+ # Use binary search to identify the earliest message index that keeps the
694
+ # suffix within the token budget.
695
+ left, right = 0, len(messages)
696
+ cutoff_candidate = len(messages)
697
+ max_iterations = len(messages).bit_length() + 1
698
+ for _ in range(max_iterations):
699
+ if left >= right:
700
+ break
701
+
702
+ mid = (left + right) // 2
703
+ if self._partial_token_counter(messages[mid:]) <= target_token_count:
704
+ cutoff_candidate = mid
705
+ right = mid
706
+ else:
707
+ left = mid + 1
708
+
709
+ if cutoff_candidate == len(messages):
710
+ cutoff_candidate = left
711
+
712
+ if cutoff_candidate >= len(messages):
713
+ if len(messages) == 1:
714
+ return 0
715
+ cutoff_candidate = len(messages) - 1
716
+
717
+ # Advance past any ToolMessages to avoid splitting AI/Tool pairs
718
+ return self._find_safe_cutoff_point(messages, cutoff_candidate)
719
+
720
+ def _get_profile_limits(self) -> int | None:
721
+ """Retrieve max input token limit from the model profile."""
722
+ try:
723
+ profile = self.model.profile
724
+ except AttributeError:
725
+ return None
726
+
727
+ if not isinstance(profile, Mapping):
728
+ return None
729
+
730
+ max_input_tokens = profile.get("max_input_tokens")
731
+
732
+ if not isinstance(max_input_tokens, int):
733
+ return None
734
+
735
+ return max_input_tokens
736
+
737
+ @staticmethod
738
+ def _validate_context_size(context: ContextSize, parameter_name: str) -> ContextSize:
739
+ """Validate context configuration tuples."""
740
+ kind, value = context
741
+ if kind == "fraction":
742
+ if not 0 < value <= 1:
743
+ msg = f"Fractional {parameter_name} values must be between 0 and 1, got {value}."
744
+ raise ValueError(msg)
745
+ elif kind in {"tokens", "messages"}:
746
+ if value <= 0:
747
+ msg = f"{parameter_name} thresholds must be greater than 0, got {value}."
748
+ raise ValueError(msg)
749
+ else:
750
+ msg = f"Unsupported context size type {kind} for {parameter_name}."
751
+ raise ValueError(msg)
752
+ return context
753
+
754
+ @staticmethod
755
+ def _build_new_messages(summary: str) -> list[HumanMessage]:
756
+ return [
757
+ HumanMessage(
758
+ content=f"Here is a summary of the conversation to date:\n\n{summary}",
759
+ additional_kwargs={"lc_source": "summarization"},
760
+ )
761
+ ]
762
+
763
+ @staticmethod
764
+ def _ensure_message_ids(messages: list[AnyMessage]) -> None:
765
+ """Ensure all messages have unique IDs for the add_messages reducer."""
766
+ for msg in messages:
767
+ if msg.id is None:
768
+ msg.id = str(uuid.uuid4())
769
+
770
+ @staticmethod
771
+ def _partition_messages(
772
+ conversation_messages: list[AnyMessage],
773
+ cutoff_index: int,
774
+ ) -> tuple[list[AnyMessage], list[AnyMessage]]:
775
+ """Partition messages into those to summarize and those to preserve."""
776
+ messages_to_summarize = conversation_messages[:cutoff_index]
777
+ preserved_messages = conversation_messages[cutoff_index:]
778
+
779
+ return messages_to_summarize, preserved_messages
780
+
781
+ def _find_safe_cutoff(self, messages: list[AnyMessage], messages_to_keep: int) -> int:
782
+ """Find safe cutoff point that preserves AI/Tool message pairs.
783
+
784
+ Returns the index where messages can be safely cut without separating
785
+ related AI and Tool messages. Returns `0` if no safe cutoff is found.
786
+
787
+ This is aggressive with summarization - if the target cutoff lands in the
788
+ middle of tool messages, we advance past all of them (summarizing more).
789
+ """
790
+ if len(messages) <= messages_to_keep:
791
+ return 0
792
+
793
+ target_cutoff = len(messages) - messages_to_keep
794
+ return self._find_safe_cutoff_point(messages, target_cutoff)
795
+
796
+ @staticmethod
797
+ def _find_safe_cutoff_point(messages: list[AnyMessage], cutoff_index: int) -> int:
798
+ """Find a safe cutoff point that doesn't split AI/Tool message pairs.
799
+
800
+ If the message at `cutoff_index` is a `ToolMessage`, search backward for the
801
+ `AIMessage` containing the corresponding `tool_calls` and adjust the cutoff to
802
+ include it. This ensures tool call requests and responses stay together.
803
+
804
+ Falls back to advancing forward past `ToolMessage` objects only if no matching
805
+ `AIMessage` is found (edge case).
806
+ """
807
+ if cutoff_index >= len(messages) or not isinstance(messages[cutoff_index], ToolMessage):
808
+ return cutoff_index
809
+
810
+ # Collect tool_call_ids from consecutive ToolMessages at/after cutoff
811
+ tool_call_ids: set[str] = set()
812
+ idx = cutoff_index
813
+ while idx < len(messages) and isinstance(messages[idx], ToolMessage):
814
+ tool_msg = cast("ToolMessage", messages[idx])
815
+ if tool_msg.tool_call_id:
816
+ tool_call_ids.add(tool_msg.tool_call_id)
817
+ idx += 1
818
+
819
+ # Search backward for AIMessage with matching tool_calls
820
+ for i in range(cutoff_index - 1, -1, -1):
821
+ msg = messages[i]
822
+ if isinstance(msg, AIMessage) and msg.tool_calls:
823
+ ai_tool_call_ids = {tc.get("id") for tc in msg.tool_calls if tc.get("id")}
824
+ if tool_call_ids & ai_tool_call_ids:
825
+ # Found the AIMessage - move cutoff to include it
826
+ return i
827
+
828
+ # Fallback: no matching AIMessage found, advance past ToolMessages to avoid
829
+ # orphaned tool responses
830
+ return idx
831
+
832
+ def _create_summary(self, messages_to_summarize: list[AnyMessage]) -> str:
833
+ """Generate summary for the given messages.
834
+
835
+ Args:
836
+ messages_to_summarize: Messages to summarize.
837
+
838
+ Returns:
839
+ The generated summary.
840
+
841
+ Raises:
842
+ Exception: If the summary model call still fails once retries (see
843
+ `Runnable.with_retry`) are exhausted.
844
+ """
845
+ if not messages_to_summarize:
846
+ return "No previous conversation history."
847
+
848
+ trimmed_messages = self._trim_messages_for_summary(messages_to_summarize)
849
+ if not trimmed_messages:
850
+ return "Previous conversation was too long to summarize."
851
+
852
+ # Serialize as XML so URL-based multimodal blocks remain visible in the summary
853
+ # prompt while excluding raw message metadata from the token budget.
854
+ formatted_messages = get_buffer_string(trimmed_messages, format="xml")
855
+
856
+ response = self._summary_model.invoke(
857
+ self.summary_prompt.format(messages=formatted_messages).rstrip(),
858
+ config={"metadata": {"lc_source": "summarization", **internal_call_metadata()}},
859
+ )
860
+ return response.text.strip()
861
+
862
+ async def _acreate_summary(self, messages_to_summarize: list[AnyMessage]) -> str:
863
+ """Generate summary for the given messages.
864
+
865
+ Args:
866
+ messages_to_summarize: Messages to summarize.
867
+
868
+ Returns:
869
+ The generated summary.
870
+
871
+ Raises:
872
+ Exception: If the summary model call still fails once retries (see
873
+ `Runnable.with_retry`) are exhausted.
874
+ """
875
+ if not messages_to_summarize:
876
+ return "No previous conversation history."
877
+
878
+ trimmed_messages = self._trim_messages_for_summary(messages_to_summarize)
879
+ if not trimmed_messages:
880
+ return "Previous conversation was too long to summarize."
881
+
882
+ # Serialize as XML so URL-based multimodal blocks remain visible in the summary
883
+ # prompt while excluding raw message metadata from the token budget.
884
+ formatted_messages = get_buffer_string(trimmed_messages, format="xml")
885
+
886
+ response = await self._summary_model.ainvoke(
887
+ self.summary_prompt.format(messages=formatted_messages).rstrip(),
888
+ config={"metadata": {"lc_source": "summarization", **internal_call_metadata()}},
889
+ )
890
+ return response.text.strip()
891
+
892
+ def _trim_messages_for_summary(self, messages: list[AnyMessage]) -> list[AnyMessage]:
893
+ """Trim messages to fit within summary generation limits."""
894
+ try:
895
+ if self.trim_tokens_to_summarize is None:
896
+ return messages
897
+ return cast(
898
+ "list[AnyMessage]",
899
+ trim_messages(
900
+ messages,
901
+ max_tokens=self.trim_tokens_to_summarize,
902
+ token_counter=self.token_counter,
903
+ start_on="human",
904
+ strategy="last",
905
+ allow_partial=True,
906
+ include_system=True,
907
+ ),
908
+ )
909
+ except Exception:
910
+ return messages[-_DEFAULT_FALLBACK_MESSAGE_COUNT:]