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,2442 @@
1
+ """Module contains utility functions for working with messages.
2
+
3
+ Some examples of what you can do with these functions include:
4
+
5
+ * Convert messages to strings (serialization)
6
+ * Convert messages from dicts to Message objects (deserialization)
7
+ * Filter messages from a list of messages based on name, type or id etc.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import inspect
14
+ import json
15
+ import logging
16
+ import math
17
+ from collections.abc import Callable, Iterable, Sequence
18
+ from functools import partial, wraps
19
+ from typing import (
20
+ TYPE_CHECKING,
21
+ Annotated,
22
+ Any,
23
+ Concatenate,
24
+ Literal,
25
+ ParamSpec,
26
+ Protocol,
27
+ TypeVar,
28
+ cast,
29
+ overload,
30
+ )
31
+ from xml.sax.saxutils import escape, quoteattr
32
+
33
+ from pydantic import Discriminator, Field, Tag
34
+
35
+ from coco_core.exceptions import ErrorCode, create_message
36
+ from coco_core.messages.ai import AIMessage, AIMessageChunk
37
+ from coco_core.messages.base import BaseMessage, BaseMessageChunk
38
+ from coco_core.messages.block_translators.openai import (
39
+ convert_to_openai_data_block,
40
+ )
41
+ from coco_core.messages.chat import ChatMessage, ChatMessageChunk
42
+ from coco_core.messages.content import (
43
+ is_data_content_block,
44
+ )
45
+ from coco_core.messages.function import FunctionMessage, FunctionMessageChunk
46
+ from coco_core.messages.human import HumanMessage, HumanMessageChunk
47
+ from coco_core.messages.modifier import RemoveMessage
48
+ from coco_core.messages.system import SystemMessage, SystemMessageChunk
49
+ from coco_core.messages.tool import ToolCall, ToolMessage, ToolMessageChunk
50
+ from coco_core.utils.pydantic import model_json_schema as get_model_json_schema
51
+
52
+ if TYPE_CHECKING:
53
+ from coco_core.language_models import BaseLanguageModel
54
+ from coco_core.prompt_values import PromptValue
55
+ from coco_core.runnables.base import Runnable
56
+ from coco_core.tools import BaseTool
57
+
58
+ try:
59
+ from coco_text_splitters import TextSplitter
60
+
61
+ _HAS_COCO_TEXT_SPLITTERS = True
62
+ except ImportError:
63
+ _HAS_COCO_TEXT_SPLITTERS = False
64
+
65
+ logger = logging.getLogger(__name__)
66
+
67
+
68
+ def _get_type(v: Any) -> str:
69
+ """Get the type associated with the object for serialization purposes."""
70
+ if isinstance(v, dict) and "type" in v:
71
+ result = v["type"]
72
+ elif hasattr(v, "type"):
73
+ result = v.type
74
+ else:
75
+ msg = (
76
+ f"Expected either a dictionary with a 'type' key or an object "
77
+ f"with a 'type' attribute. Instead got type {type(v)}."
78
+ )
79
+ raise TypeError(msg)
80
+ if not isinstance(result, str):
81
+ msg = f"Expected 'type' to be a str, got {type(result).__name__}"
82
+ raise TypeError(msg)
83
+ return result
84
+
85
+
86
+ AnyMessage = Annotated[
87
+ Annotated[AIMessage, Tag(tag="ai")]
88
+ | Annotated[HumanMessage, Tag(tag="human")]
89
+ | Annotated[ChatMessage, Tag(tag="chat")]
90
+ | Annotated[SystemMessage, Tag(tag="system")]
91
+ | Annotated[FunctionMessage, Tag(tag="function")]
92
+ | Annotated[ToolMessage, Tag(tag="tool")]
93
+ | Annotated[AIMessageChunk, Tag(tag="AIMessageChunk")]
94
+ | Annotated[HumanMessageChunk, Tag(tag="HumanMessageChunk")]
95
+ | Annotated[ChatMessageChunk, Tag(tag="ChatMessageChunk")]
96
+ | Annotated[SystemMessageChunk, Tag(tag="SystemMessageChunk")]
97
+ | Annotated[FunctionMessageChunk, Tag(tag="FunctionMessageChunk")]
98
+ | Annotated[ToolMessageChunk, Tag(tag="ToolMessageChunk")],
99
+ Field(discriminator=Discriminator(_get_type)),
100
+ ]
101
+ """A type representing any defined `Message` or `MessageChunk` type."""
102
+
103
+
104
+ def _has_base64_data(block: dict[str, Any]) -> bool:
105
+ """Check if a content block contains base64 encoded data.
106
+
107
+ Args:
108
+ block: A content block dictionary.
109
+
110
+ Returns:
111
+ Whether the block contains base64 data.
112
+ """
113
+ # Check for explicit base64 field (standard content blocks)
114
+ if block.get("base64"):
115
+ return True
116
+
117
+ # Check for data: URL in url field
118
+ url = block.get("url", "")
119
+ if isinstance(url, str) and url.startswith("data:"):
120
+ return True
121
+
122
+ # Check for OpenAI-style image_url with data: URL
123
+ image_url = block.get("image_url", {})
124
+ if isinstance(image_url, dict):
125
+ url = image_url.get("url", "")
126
+ if isinstance(url, str) and url.startswith("data:"):
127
+ return True
128
+
129
+ return False
130
+
131
+
132
+ _XML_CONTENT_BLOCK_MAX_LEN = 500
133
+
134
+
135
+ def _truncate(text: str, max_len: int = _XML_CONTENT_BLOCK_MAX_LEN) -> str:
136
+ """Truncate text to `max_len` characters, adding ellipsis if truncated."""
137
+ if len(text) <= max_len:
138
+ return text
139
+ return text[:max_len] + "..."
140
+
141
+
142
+ def _format_content_block_xml(block: dict[str, Any]) -> str | None:
143
+ """Format a content block as XML.
144
+
145
+ Args:
146
+ block: A Coco content block.
147
+
148
+ Returns:
149
+ XML string representation of the block, or `None` if the block should be
150
+ skipped.
151
+
152
+ Note:
153
+ Plain text document content, server tool call arguments, and server tool
154
+ result outputs are truncated to 500 characters.
155
+ """
156
+ block_type = block.get("type", "")
157
+
158
+ # Skip blocks with base64 encoded data
159
+ if _has_base64_data(block):
160
+ return None
161
+
162
+ # Text blocks
163
+ if block_type == "text":
164
+ text = block.get("text", "")
165
+ return escape(text) if text else None
166
+
167
+ # Reasoning blocks
168
+ if block_type == "reasoning":
169
+ reasoning = block.get("reasoning", "")
170
+ if reasoning:
171
+ return f"<reasoning>{escape(reasoning)}</reasoning>"
172
+ return None
173
+
174
+ # Image blocks (URL only, base64 already filtered)
175
+ if block_type == "image":
176
+ url = block.get("url")
177
+ file_id = block.get("file_id")
178
+ if url:
179
+ return f"<image url={quoteattr(url)} />"
180
+ if file_id:
181
+ return f"<image file_id={quoteattr(file_id)} />"
182
+ return None
183
+
184
+ # OpenAI-style image_url blocks
185
+ if block_type == "image_url":
186
+ image_url = block.get("image_url", {})
187
+ if isinstance(image_url, dict):
188
+ url = image_url.get("url", "")
189
+ if url and not url.startswith("data:"):
190
+ return f"<image url={quoteattr(url)} />"
191
+ return None
192
+
193
+ # Audio blocks (URL only)
194
+ if block_type == "audio":
195
+ url = block.get("url")
196
+ file_id = block.get("file_id")
197
+ if url:
198
+ return f"<audio url={quoteattr(url)} />"
199
+ if file_id:
200
+ return f"<audio file_id={quoteattr(file_id)} />"
201
+ return None
202
+
203
+ # Video blocks (URL only)
204
+ if block_type == "video":
205
+ url = block.get("url")
206
+ file_id = block.get("file_id")
207
+ if url:
208
+ return f"<video url={quoteattr(url)} />"
209
+ if file_id:
210
+ return f"<video file_id={quoteattr(file_id)} />"
211
+ return None
212
+
213
+ # Plain text document blocks
214
+ if block_type == "text-plain":
215
+ text = block.get("text", "")
216
+ return escape(_truncate(text)) if text else None
217
+
218
+ # Server tool call blocks (from AI messages)
219
+ if block_type == "server_tool_call":
220
+ tc_id = quoteattr(str(block.get("id") or ""))
221
+ tc_name = quoteattr(str(block.get("name") or ""))
222
+ tc_args_json = json.dumps(block.get("args", {}), ensure_ascii=False)
223
+ tc_args = escape(_truncate(tc_args_json))
224
+ return (
225
+ f"<server_tool_call id={tc_id} name={tc_name}>{tc_args}</server_tool_call>"
226
+ )
227
+
228
+ # Server tool result blocks
229
+ if block_type == "server_tool_result":
230
+ tool_call_id = quoteattr(str(block.get("tool_call_id") or ""))
231
+ status = quoteattr(str(block.get("status") or ""))
232
+ output = block.get("output")
233
+ if output:
234
+ output_json = json.dumps(output, ensure_ascii=False)
235
+ output_str = escape(_truncate(output_json))
236
+ else:
237
+ output_str = ""
238
+ return (
239
+ f"<server_tool_result tool_call_id={tool_call_id} status={status}>"
240
+ f"{output_str}</server_tool_result>"
241
+ )
242
+
243
+ # Unknown block type - skip silently
244
+ return None
245
+
246
+
247
+ def _get_message_type_str(
248
+ m: BaseMessage,
249
+ human_prefix: str,
250
+ ai_prefix: str,
251
+ system_prefix: str,
252
+ function_prefix: str,
253
+ tool_prefix: str,
254
+ ) -> str:
255
+ """Get the type string for XML message element.
256
+
257
+ Args:
258
+ m: The message to get the type string for.
259
+ human_prefix: The prefix to use for `HumanMessage`.
260
+ ai_prefix: The prefix to use for `AIMessage`.
261
+ system_prefix: The prefix to use for `SystemMessage`.
262
+ function_prefix: The prefix to use for `FunctionMessage`.
263
+ tool_prefix: The prefix to use for `ToolMessage`.
264
+
265
+ Returns:
266
+ The type string for the message element.
267
+
268
+ Raises:
269
+ ValueError: If an unsupported message type is encountered.
270
+ """
271
+ if isinstance(m, HumanMessage):
272
+ return human_prefix.lower()
273
+ if isinstance(m, AIMessage):
274
+ return ai_prefix.lower()
275
+ if isinstance(m, SystemMessage):
276
+ return system_prefix.lower()
277
+ if isinstance(m, FunctionMessage):
278
+ return function_prefix.lower()
279
+ if isinstance(m, ToolMessage):
280
+ return tool_prefix.lower()
281
+ if isinstance(m, ChatMessage):
282
+ return m.role
283
+ msg = f"Got unsupported message type: {m}"
284
+ raise ValueError(msg)
285
+
286
+
287
+ _TOOL_CALL_ID_DISPLAY_LIMIT = 64
288
+
289
+
290
+ def _display_tool_call_id(tool_call_id: str) -> str:
291
+ """Abbreviate long tool-call IDs in formatted message strings."""
292
+ if len(tool_call_id) > _TOOL_CALL_ID_DISPLAY_LIMIT:
293
+ return f"{tool_call_id[:_TOOL_CALL_ID_DISPLAY_LIMIT]}..."
294
+ return tool_call_id
295
+
296
+
297
+ def get_buffer_string(
298
+ messages: Sequence[BaseMessage],
299
+ human_prefix: str = "Human",
300
+ ai_prefix: str = "AI",
301
+ *,
302
+ system_prefix: str = "System",
303
+ function_prefix: str = "Function",
304
+ tool_prefix: str = "Tool",
305
+ message_separator: str = "\n",
306
+ format: Literal["prefix", "xml"] = "prefix", # noqa: A002
307
+ ) -> str:
308
+ r"""Convert a sequence of messages to strings and concatenate them into one string.
309
+
310
+ Args:
311
+ messages: Messages to be converted to strings.
312
+ human_prefix: The prefix to prepend to contents of `HumanMessage`s.
313
+ ai_prefix: The prefix to prepend to contents of `AIMessage`.
314
+ system_prefix: The prefix to prepend to contents of `SystemMessage`s.
315
+ function_prefix: The prefix to prepend to contents of `FunctionMessage`s.
316
+ tool_prefix: The prefix to prepend to contents of `ToolMessage`s.
317
+ message_separator: The separator to use between messages.
318
+ format: The output format. `'prefix'` uses `Role: content` format (default).
319
+ For multimodal messages, only string content and `text` blocks are
320
+ included; non-text blocks such as images, audio, and video are omitted.
321
+
322
+ `'xml'` uses XML-style `<message type='role'>` format with proper
323
+ character escaping, which is useful when message content may
324
+ contain role-like prefixes that could cause ambiguity.
325
+
326
+ Use `'xml'` when you need a structured representation of supported
327
+ multimodal content blocks.
328
+
329
+ Returns:
330
+ A single string concatenation of all input messages.
331
+
332
+ Raises:
333
+ ValueError: If an unsupported message type is encountered.
334
+
335
+ !!! warning
336
+
337
+ If a message is an `AIMessage` and contains both tool calls under `tool_calls`
338
+ and a function call under `additional_kwargs["function_call"]`, only the tool
339
+ calls will be appended to the string representation.
340
+ In XML format, tool-call IDs longer than 64 characters are displayed
341
+ as the first 64 characters followed by `...`; the original messages
342
+ are not changed.
343
+
344
+ !!! note "XML format"
345
+
346
+ When using `format='xml'`:
347
+
348
+ - All messages use uniform `<message type="role">content</message>` format.
349
+ - The `type` attribute uses `human_prefix` (lowercased) for `HumanMessage`,
350
+ `ai_prefix` (lowercased) for `AIMessage`, `system_prefix` (lowercased)
351
+ for `SystemMessage`, `function_prefix` (lowercased) for `FunctionMessage`,
352
+ `tool_prefix` (lowercased) for `ToolMessage`, and the original role
353
+ (unchanged) for `ChatMessage`.
354
+ - Message content is escaped using `xml.sax.saxutils.escape()`.
355
+ - Attribute values are escaped using `xml.sax.saxutils.quoteattr()`.
356
+ - AI messages with tool calls use nested structure with `<content>` and
357
+ `<tool_call>` elements.
358
+ - For multi-modal content (list of content blocks), supported block types
359
+ are: `text`, `reasoning`, `image` (URL/file_id only), `image_url`
360
+ (OpenAI-style, URL only), `audio` (URL/file_id only), `video` (URL/file_id
361
+ only), `text-plain`, `server_tool_call`, and `server_tool_result`.
362
+ - Content blocks with base64-encoded data are skipped (including blocks
363
+ with `base64` field or `data:` URLs).
364
+ - Unknown block types are skipped.
365
+ - Plain text document content (`text-plain`), server tool call arguments,
366
+ and server tool result outputs are truncated to 500 characters.
367
+
368
+ Example:
369
+ Default prefix format:
370
+
371
+ ```python
372
+ from coco_core.messages import AIMessage, HumanMessage, get_buffer_string
373
+
374
+ messages = [
375
+ HumanMessage(content="Hi, how are you?"),
376
+ AIMessage(content="Good, how are you?"),
377
+ ]
378
+ get_buffer_string(messages)
379
+ # -> "Human: Hi, how are you?\nAI: Good, how are you?"
380
+ ```
381
+
382
+ XML format (useful when content contains role-like prefixes):
383
+
384
+ ```python
385
+ messages = [
386
+ HumanMessage(content="Example: Human: some text"),
387
+ AIMessage(content="I see the example."),
388
+ ]
389
+ get_buffer_string(messages, format="xml")
390
+ # -> '<message type="human">Example: Human: some text</message>\\n'
391
+ # -> '<message type="ai">I see the example.</message>'
392
+ ```
393
+
394
+ XML format with special characters (automatically escaped):
395
+
396
+ ```python
397
+ messages = [
398
+ HumanMessage(content="Is 5 < 10 & 10 > 5?"),
399
+ ]
400
+ get_buffer_string(messages, format="xml")
401
+ # -> '<message type="human">Is 5 &lt; 10 &amp; 10 &gt; 5?</message>'
402
+ ```
403
+
404
+ XML format with tool calls:
405
+
406
+ ```python
407
+ messages = [
408
+ AIMessage(
409
+ content="I'll search for that.",
410
+ tool_calls=[
411
+ {"id": "call_123", "name": "search", "args": {"query": "weather"}}
412
+ ],
413
+ ),
414
+ ]
415
+ get_buffer_string(messages, format="xml")
416
+ # -> '<message type="ai">\\n'
417
+ # -> ' <content>I\\'ll search for that.</content>\\n'
418
+ # -> ' <tool_call id="call_123" name="search">'
419
+ # -> '{"query": "weather"}</tool_call>\\n'
420
+ # -> '</message>'
421
+ ```
422
+ """
423
+ if format not in {"prefix", "xml"}:
424
+ msg = (
425
+ f"Unrecognized format={format!r}. Supported formats are 'prefix' and 'xml'."
426
+ )
427
+ raise ValueError(msg)
428
+
429
+ string_messages = []
430
+ for m in messages:
431
+ if isinstance(m, HumanMessage):
432
+ role = human_prefix
433
+ elif isinstance(m, AIMessage):
434
+ role = ai_prefix
435
+ elif isinstance(m, SystemMessage):
436
+ role = system_prefix
437
+ elif isinstance(m, FunctionMessage):
438
+ role = function_prefix
439
+ elif isinstance(m, ToolMessage):
440
+ role = tool_prefix
441
+ elif isinstance(m, ChatMessage):
442
+ role = m.role
443
+ else:
444
+ msg = f"Got unsupported message type: {m}"
445
+ raise ValueError(msg) # noqa: TRY004
446
+
447
+ if format == "xml":
448
+ msg_type = _get_message_type_str(
449
+ m, human_prefix, ai_prefix, system_prefix, function_prefix, tool_prefix
450
+ )
451
+
452
+ # Format content blocks
453
+ if isinstance(m.content, str):
454
+ content_parts = [escape(m.content)] if m.content else []
455
+ else:
456
+ # List of content blocks
457
+ content_parts = []
458
+ for block in m.content:
459
+ if isinstance(block, str):
460
+ if block:
461
+ content_parts.append(escape(block))
462
+ else:
463
+ formatted = _format_content_block_xml(block)
464
+ if formatted:
465
+ content_parts.append(formatted)
466
+
467
+ # Check if this is an AIMessage with tool calls
468
+ has_tool_calls = isinstance(m, AIMessage) and m.tool_calls
469
+ has_function_call = (
470
+ isinstance(m, AIMessage)
471
+ and not m.tool_calls
472
+ and "function_call" in m.additional_kwargs
473
+ )
474
+
475
+ if has_tool_calls or has_function_call:
476
+ # Use nested structure for AI messages with tool calls
477
+ # Type narrowing: at this point m is AIMessage (verified above)
478
+ ai_msg = cast("AIMessage", m)
479
+ parts = [f"<message type={quoteattr(msg_type)}>"]
480
+ if content_parts:
481
+ parts.append(f" <content>{' '.join(content_parts)}</content>")
482
+
483
+ if has_tool_calls:
484
+ for tc in ai_msg.tool_calls:
485
+ tc_id = quoteattr(_display_tool_call_id(tc.get("id") or ""))
486
+ tc_name = quoteattr(str(tc.get("name") or ""))
487
+ tc_args = escape(
488
+ json.dumps(tc.get("args", {}), ensure_ascii=False)
489
+ )
490
+ parts.append(
491
+ f" <tool_call id={tc_id} name={tc_name}>"
492
+ f"{tc_args}</tool_call>"
493
+ )
494
+ elif has_function_call:
495
+ fc = ai_msg.additional_kwargs["function_call"]
496
+ fc_name = quoteattr(str(fc.get("name") or ""))
497
+ fc_args = escape(str(fc.get("arguments") or "{}"))
498
+ parts.append(
499
+ f" <function_call name={fc_name}>{fc_args}</function_call>"
500
+ )
501
+
502
+ parts.append("</message>")
503
+ message = "\n".join(parts)
504
+ else:
505
+ # Simple structure for messages without tool calls
506
+ joined_content = " ".join(content_parts)
507
+ message = (
508
+ f"<message type={quoteattr(msg_type)}>{joined_content}</message>"
509
+ )
510
+ else: # format == "prefix"
511
+ content = m.text
512
+ message = f"{role}: {content}"
513
+ tool_info = ""
514
+ if isinstance(m, AIMessage):
515
+ if m.tool_calls:
516
+ tool_info = str(m.tool_calls)
517
+ elif "function_call" in m.additional_kwargs:
518
+ # Legacy behavior assumes only one function call per message
519
+ tool_info = str(m.additional_kwargs["function_call"])
520
+ if tool_info:
521
+ message += tool_info # Preserve original behavior
522
+
523
+ string_messages.append(message)
524
+
525
+ return message_separator.join(string_messages)
526
+
527
+
528
+ def _message_from_dict(message: dict[str, Any]) -> BaseMessage:
529
+ type_ = message["type"]
530
+ if type_ == "human":
531
+ return HumanMessage(**message["data"])
532
+ if type_ == "ai":
533
+ return AIMessage(**message["data"])
534
+ if type_ == "system":
535
+ return SystemMessage(**message["data"])
536
+ if type_ == "chat":
537
+ return ChatMessage(**message["data"])
538
+ if type_ == "function":
539
+ return FunctionMessage(**message["data"])
540
+ if type_ == "tool":
541
+ return ToolMessage(**message["data"])
542
+ if type_ == "remove":
543
+ return RemoveMessage(**message["data"])
544
+ if type_ == "AIMessageChunk":
545
+ return AIMessageChunk(**message["data"])
546
+ if type_ == "HumanMessageChunk":
547
+ return HumanMessageChunk(**message["data"])
548
+ if type_ == "FunctionMessageChunk":
549
+ return FunctionMessageChunk(**message["data"])
550
+ if type_ == "ToolMessageChunk":
551
+ return ToolMessageChunk(**message["data"])
552
+ if type_ == "SystemMessageChunk":
553
+ return SystemMessageChunk(**message["data"])
554
+ if type_ == "ChatMessageChunk":
555
+ return ChatMessageChunk(**message["data"])
556
+ msg = f"Got unexpected message type: {type_}"
557
+ raise ValueError(msg)
558
+
559
+
560
+ def messages_from_dict(messages: Sequence[dict[str, Any]]) -> list[BaseMessage]:
561
+ """Convert a sequence of messages from dicts to `Message` objects.
562
+
563
+ Args:
564
+ messages: Sequence of messages (as dicts) to convert.
565
+
566
+ Returns:
567
+ list of messages (BaseMessages).
568
+
569
+ """
570
+ return [_message_from_dict(m) for m in messages]
571
+
572
+
573
+ def message_chunk_to_message(chunk: BaseMessage) -> BaseMessage:
574
+ """Convert a message chunk to a `Message`.
575
+
576
+ Args:
577
+ chunk: Message chunk to convert.
578
+
579
+ Returns:
580
+ Message.
581
+ """
582
+ if not isinstance(chunk, BaseMessageChunk):
583
+ return chunk
584
+ # chunk classes always have the equivalent non-chunk class as their first parent
585
+ ignore_keys = ["type"]
586
+ if isinstance(chunk, AIMessageChunk):
587
+ ignore_keys.extend(["tool_call_chunks", "chunk_position"])
588
+ return cast(
589
+ "BaseMessage",
590
+ chunk.__class__.__mro__[1](
591
+ **{k: v for k, v in chunk.__dict__.items() if k not in ignore_keys}
592
+ ),
593
+ )
594
+
595
+
596
+ MessageLikeRepresentation = (
597
+ BaseMessage
598
+ | list[str]
599
+ | tuple[str, str | list[str | dict[str, Any]]]
600
+ | str
601
+ | dict[str, Any]
602
+ )
603
+ """A type representing the various ways a message can be represented."""
604
+
605
+
606
+ def _create_message_from_message_type(
607
+ message_type: str,
608
+ content: str | list[str | dict[str, Any]],
609
+ name: str | None = None,
610
+ tool_call_id: str | None = None,
611
+ tool_calls: list[dict[str, Any]] | None = None,
612
+ id: str | None = None,
613
+ **additional_kwargs: Any,
614
+ ) -> BaseMessage:
615
+ """Create a message from a `Message` type and content string.
616
+
617
+ Args:
618
+ message_type: the type of the message (e.g., `'human'`, `'ai'`, etc.).
619
+ content: the content string.
620
+ name: the name of the message.
621
+ tool_call_id: the tool call id.
622
+ tool_calls: the tool calls.
623
+ id: the id of the message.
624
+ additional_kwargs: additional keyword arguments.
625
+
626
+ Returns:
627
+ a message of the appropriate type.
628
+
629
+ Raises:
630
+ ValueError: if the message type is not one of `'human'`, `'user'`, `'ai'`,
631
+ `'assistant'`, `'function'`, `'tool'`, `'system'`, or
632
+ `'developer'`.
633
+ """
634
+ kwargs: dict[str, Any] = {}
635
+ if name is not None:
636
+ kwargs["name"] = name
637
+ if tool_call_id is not None:
638
+ kwargs["tool_call_id"] = tool_call_id
639
+ if additional_kwargs:
640
+ if response_metadata := additional_kwargs.pop("response_metadata", None):
641
+ kwargs["response_metadata"] = response_metadata
642
+ kwargs["additional_kwargs"] = additional_kwargs
643
+ additional_kwargs.update(additional_kwargs.pop("additional_kwargs", {}))
644
+ if id is not None:
645
+ kwargs["id"] = id
646
+ if tool_calls is not None:
647
+ kwargs["tool_calls"] = []
648
+ for tool_call in tool_calls:
649
+ # Convert OpenAI-format tool call to Coco format.
650
+ if "function" in tool_call:
651
+ args = tool_call["function"]["arguments"]
652
+ if isinstance(args, str):
653
+ args = json.loads(args, strict=False)
654
+ kwargs["tool_calls"].append(
655
+ {
656
+ "name": tool_call["function"]["name"],
657
+ "args": args,
658
+ "id": tool_call["id"],
659
+ "type": "tool_call",
660
+ }
661
+ )
662
+ else:
663
+ kwargs["tool_calls"].append(tool_call)
664
+ if message_type in {"human", "user"}:
665
+ if example := kwargs.get("additional_kwargs", {}).pop("example", False):
666
+ kwargs["example"] = example
667
+ message: BaseMessage = HumanMessage(content=content, **kwargs)
668
+ elif message_type in {"ai", "assistant"}:
669
+ if example := kwargs.get("additional_kwargs", {}).pop("example", False):
670
+ kwargs["example"] = example
671
+ message = AIMessage(content=content, **kwargs)
672
+ elif message_type in {"system", "developer"}:
673
+ if message_type == "developer":
674
+ kwargs["additional_kwargs"] = kwargs.get("additional_kwargs") or {}
675
+ kwargs["additional_kwargs"]["__openai_role__"] = "developer"
676
+ message = SystemMessage(content=content, **kwargs)
677
+ elif message_type == "function":
678
+ message = FunctionMessage(content=content, **kwargs)
679
+ elif message_type == "tool":
680
+ artifact = kwargs.get("additional_kwargs", {}).pop("artifact", None)
681
+ status = kwargs.get("additional_kwargs", {}).pop("status", None)
682
+ if status is not None:
683
+ kwargs["status"] = status
684
+ message = ToolMessage(content=content, artifact=artifact, **kwargs)
685
+ elif message_type == "remove":
686
+ message = RemoveMessage(**kwargs)
687
+ else:
688
+ msg = (
689
+ f"Unexpected message type: '{message_type}'. Use one of 'human',"
690
+ f" 'user', 'ai', 'assistant', 'function', 'tool', 'system', or 'developer'."
691
+ )
692
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
693
+ raise ValueError(msg)
694
+ return message
695
+
696
+
697
+ # Map of class names emitted in the `Serializable` constructor-envelope
698
+ # (`{"lc": 1, "type": "constructor", "id": [..., "<ClassName>"],
699
+ # "kwargs": {...}}`) to the message-type strings
700
+ # `_create_message_from_message_type` accepts. Read by
701
+ # `_convert_to_message`'s dict branch when unpacking that wire shape.
702
+ # Kept as a hardcoded allowlist of strings rather than a class registry
703
+ # lookup so dispatch never resolves to a class chosen by the caller.
704
+ _LC_CONSTRUCTOR_NAME_TO_TYPE: dict[str, str] = {
705
+ "HumanMessage": "human",
706
+ "HumanMessageChunk": "human",
707
+ "AIMessage": "ai",
708
+ "AIMessageChunk": "ai",
709
+ "SystemMessage": "system",
710
+ "SystemMessageChunk": "system",
711
+ "FunctionMessage": "function",
712
+ "FunctionMessageChunk": "function",
713
+ "ToolMessage": "tool",
714
+ "ToolMessageChunk": "tool",
715
+ "RemoveMessage": "remove",
716
+ }
717
+
718
+
719
+ def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:
720
+ """Instantiate a `Message` from a variety of message formats.
721
+
722
+ The message format can be one of the following:
723
+
724
+ - `BaseMessagePromptTemplate`
725
+ - `BaseMessage`
726
+ - 2-tuple of (role string, template); e.g., (`'human'`, `'{user_input}'`)
727
+ - dict: a message dict with role and content keys
728
+ - dict: the `Serializable` constructor-envelope wire shape
729
+ `{"lc": 1, "type": "constructor", "id": [..., "<ClassName>"],
730
+ "kwargs": {...}}` — unpacked structurally and routed through the
731
+ standard dict-with-type dispatch.
732
+ - string: shorthand for (`'human'`, template); e.g., `'{user_input}'`
733
+
734
+ Args:
735
+ message: a representation of a message in one of the supported formats.
736
+
737
+ Returns:
738
+ An instance of a message or a message template.
739
+
740
+ Raises:
741
+ NotImplementedError: if the message type is not supported.
742
+ ValueError: if the message dict does not contain the required keys.
743
+
744
+ """
745
+ if isinstance(message, BaseMessage):
746
+ message_ = message
747
+ elif isinstance(message, Sequence):
748
+ if isinstance(message, str):
749
+ message_ = _create_message_from_message_type("human", message)
750
+ else:
751
+ try:
752
+ message_type_str, template = message
753
+ except ValueError as e:
754
+ msg = "Message as a sequence must be (role string, template)"
755
+ raise NotImplementedError(msg) from e
756
+ message_ = _create_message_from_message_type(message_type_str, template)
757
+ elif isinstance(message, dict):
758
+ # `Serializable` constructor-envelope wire shape. Detect structurally, map
759
+ # the class name to a known message-type string via a hardcoded
760
+ # allowlist, and recurse with the canonical
761
+ # `{"type": ..., **kwargs}` shape — no `load()`, no dynamic
762
+ # class instantiation.
763
+ if (
764
+ message.get("lc") == 1
765
+ and message.get("type") == "constructor"
766
+ and isinstance(message.get("id"), list)
767
+ and message["id"]
768
+ and isinstance(message.get("kwargs"), dict)
769
+ ):
770
+ mapped = _LC_CONSTRUCTOR_NAME_TO_TYPE.get(message["id"][-1])
771
+ if mapped is not None:
772
+ return _convert_to_message({"type": mapped, **message["kwargs"]})
773
+
774
+ msg_kwargs = message.copy()
775
+ try:
776
+ try:
777
+ msg_type = msg_kwargs.pop("role")
778
+ except KeyError:
779
+ msg_type = msg_kwargs.pop("type")
780
+ # None msg content is not allowed
781
+ msg_content = msg_kwargs.pop("content") or ""
782
+ except KeyError as e:
783
+ msg = f"Message dict must contain 'role' and 'content' keys, got {message}"
784
+ msg = create_message(
785
+ message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE
786
+ )
787
+ raise ValueError(msg) from e
788
+ message_ = _create_message_from_message_type(
789
+ msg_type, msg_content, **msg_kwargs
790
+ )
791
+ else:
792
+ msg = f"Unsupported message type: {type(message)}" # type: ignore[unreachable]
793
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
794
+ raise NotImplementedError(msg)
795
+
796
+ return message_
797
+
798
+
799
+ def convert_to_messages(
800
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
801
+ ) -> list[BaseMessage]:
802
+ """Convert a sequence of messages to a list of messages.
803
+
804
+ Args:
805
+ messages: Sequence of messages to convert.
806
+
807
+ Returns:
808
+ list of messages (BaseMessages).
809
+
810
+ """
811
+ # Import here to avoid circular imports
812
+ from coco_core.prompt_values import PromptValue # noqa: PLC0415
813
+
814
+ if isinstance(messages, PromptValue):
815
+ return messages.to_messages()
816
+ return [_convert_to_message(m) for m in messages]
817
+
818
+
819
+ _P = ParamSpec("_P")
820
+ _R_co = TypeVar("_R_co", covariant=True)
821
+
822
+
823
+ class _RunnableSupportCallable(Protocol[_P, _R_co]):
824
+ @overload
825
+ def __call__(
826
+ self,
827
+ messages: None = None,
828
+ *args: _P.args,
829
+ **kwargs: _P.kwargs,
830
+ ) -> Runnable[Sequence[MessageLikeRepresentation], _R_co]: ...
831
+
832
+ @overload
833
+ def __call__(
834
+ self,
835
+ messages: Sequence[MessageLikeRepresentation] | PromptValue,
836
+ *args: _P.args,
837
+ **kwargs: _P.kwargs,
838
+ ) -> _R_co: ...
839
+
840
+ def __call__(
841
+ self,
842
+ messages: Sequence[MessageLikeRepresentation] | PromptValue | None = None,
843
+ *args: _P.args,
844
+ **kwargs: _P.kwargs,
845
+ ) -> _R_co | Runnable[Sequence[MessageLikeRepresentation], _R_co]: ...
846
+
847
+
848
+ def _runnable_support(
849
+ func: Callable[
850
+ Concatenate[Sequence[MessageLikeRepresentation] | PromptValue, _P], _R_co
851
+ ],
852
+ ) -> _RunnableSupportCallable[_P, _R_co]:
853
+ @wraps(func)
854
+ def wrapped(
855
+ messages: Sequence[MessageLikeRepresentation] | PromptValue | None = None,
856
+ *args: _P.args,
857
+ **kwargs: _P.kwargs,
858
+ ) -> _R_co | Runnable[Sequence[MessageLikeRepresentation], _R_co]:
859
+ # Import locally to prevent circular import.
860
+ from coco_core.runnables.base import RunnableLambda # noqa: PLC0415
861
+
862
+ if messages is not None:
863
+ return func(messages, *args, **kwargs)
864
+ return RunnableLambda(partial(func, **kwargs), name=func.__name__)
865
+
866
+ return cast("_RunnableSupportCallable[_P, _R_co]", wrapped)
867
+
868
+
869
+ @_runnable_support
870
+ def filter_messages(
871
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
872
+ *,
873
+ include_names: Sequence[str] | None = None,
874
+ exclude_names: Sequence[str] | None = None,
875
+ include_types: Sequence[str | type[BaseMessage]] | None = None,
876
+ exclude_types: Sequence[str | type[BaseMessage]] | None = None,
877
+ include_ids: Sequence[str] | None = None,
878
+ exclude_ids: Sequence[str] | None = None,
879
+ exclude_tool_calls: Sequence[str] | bool | None = None,
880
+ ) -> list[BaseMessage]:
881
+ """Filter messages based on `name`, `type` or `id`.
882
+
883
+ Args:
884
+ messages: Sequence Message-like objects to filter.
885
+ include_names: Message names to include.
886
+ exclude_names: Messages names to exclude.
887
+ include_types: Message types to include. Can be specified as string names
888
+ (e.g. `'system'`, `'human'`, `'ai'`, ...) or as `BaseMessage`
889
+ classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...).
890
+
891
+ exclude_types: Message types to exclude. Can be specified as string names
892
+ (e.g. `'system'`, `'human'`, `'ai'`, ...) or as `BaseMessage`
893
+ classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...).
894
+
895
+ include_ids: Message IDs to include.
896
+ exclude_ids: Message IDs to exclude.
897
+ exclude_tool_calls: Tool call IDs to exclude.
898
+ Can be one of the following:
899
+ - `True`: All `AIMessage` objects with tool calls and all `ToolMessage`
900
+ objects will be excluded.
901
+ - a sequence of tool call IDs to exclude:
902
+ - `ToolMessage` objects with the corresponding tool call ID will be
903
+ excluded.
904
+ - The `tool_calls` in the AIMessage will be updated to exclude
905
+ matching tool calls. If all `tool_calls` are filtered from an
906
+ AIMessage, the whole message is excluded.
907
+
908
+ Returns:
909
+ A list of Messages that meets at least one of the `incl_*` conditions and none
910
+ of the `excl_*` conditions. If not `incl_*` conditions are specified then
911
+ anything that is not explicitly excluded will be included.
912
+
913
+ Raises:
914
+ ValueError: If two incompatible arguments are provided.
915
+
916
+ Example:
917
+ ```python
918
+ from coco_core.messages import (
919
+ filter_messages,
920
+ AIMessage,
921
+ HumanMessage,
922
+ SystemMessage,
923
+ )
924
+
925
+ messages = [
926
+ SystemMessage("you're a good assistant."),
927
+ HumanMessage("what's your name", id="foo", name="example_user"),
928
+ AIMessage("steve-o", id="bar", name="example_assistant"),
929
+ HumanMessage(
930
+ "what's your favorite color",
931
+ id="baz",
932
+ ),
933
+ AIMessage(
934
+ "silicon blue",
935
+ id="blah",
936
+ ),
937
+ ]
938
+
939
+ filter_messages(
940
+ messages,
941
+ include_names=("example_user", "example_assistant"),
942
+ include_types=("system",),
943
+ exclude_ids=("bar",),
944
+ )
945
+ ```
946
+
947
+ ```python
948
+ [
949
+ SystemMessage("you're a good assistant."),
950
+ HumanMessage("what's your name", id="foo", name="example_user"),
951
+ ]
952
+ ```
953
+ """
954
+ messages = convert_to_messages(messages)
955
+ filtered: list[BaseMessage] = []
956
+ for msg in messages:
957
+ if (
958
+ (exclude_names and msg.name in exclude_names)
959
+ or (exclude_types and _is_message_type(msg, exclude_types))
960
+ or (exclude_ids and msg.id in exclude_ids)
961
+ ):
962
+ continue
963
+
964
+ if exclude_tool_calls is True and (
965
+ (isinstance(msg, AIMessage) and msg.tool_calls)
966
+ or isinstance(msg, ToolMessage)
967
+ ):
968
+ continue
969
+
970
+ new_msg = msg
971
+ if isinstance(exclude_tool_calls, (list, tuple, set)):
972
+ if isinstance(msg, AIMessage) and msg.tool_calls:
973
+ tool_calls = [
974
+ tool_call
975
+ for tool_call in msg.tool_calls
976
+ if tool_call["id"] not in exclude_tool_calls
977
+ ]
978
+ if not tool_calls:
979
+ continue
980
+
981
+ content = msg.content
982
+ # handle Anthropic content blocks
983
+ if isinstance(msg.content, list):
984
+ content = [
985
+ content_block
986
+ for content_block in msg.content
987
+ if (
988
+ not isinstance(content_block, dict)
989
+ or content_block.get("type") != "tool_use"
990
+ or content_block.get("id") not in exclude_tool_calls
991
+ )
992
+ ]
993
+
994
+ new_msg = msg.model_copy(
995
+ update={"tool_calls": tool_calls, "content": content}
996
+ )
997
+ elif (
998
+ isinstance(msg, ToolMessage) and msg.tool_call_id in exclude_tool_calls
999
+ ):
1000
+ continue
1001
+
1002
+ # default to inclusion when no inclusion criteria given.
1003
+ if (
1004
+ not (include_types or include_ids or include_names)
1005
+ or (include_names and new_msg.name in include_names)
1006
+ or (include_types and _is_message_type(new_msg, include_types))
1007
+ or (include_ids and new_msg.id in include_ids)
1008
+ ):
1009
+ filtered.append(new_msg)
1010
+
1011
+ return filtered
1012
+
1013
+
1014
+ @_runnable_support
1015
+ def merge_message_runs(
1016
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
1017
+ *,
1018
+ chunk_separator: str = "\n",
1019
+ ) -> list[BaseMessage]:
1020
+ r"""Merge consecutive Messages of the same type.
1021
+
1022
+ !!! note
1023
+ `ToolMessage` objects are not merged, as each has a distinct tool call id that
1024
+ can't be merged.
1025
+
1026
+ Args:
1027
+ messages: Sequence Message-like objects to merge.
1028
+ chunk_separator: Specify the string to be inserted between message chunks.
1029
+
1030
+ Returns:
1031
+ list of BaseMessages with consecutive runs of message types merged into single
1032
+ messages. By default, if two messages being merged both have string contents,
1033
+ the merged content is a concatenation of the two strings with a new-line
1034
+ separator.
1035
+ The separator inserted between message chunks can be controlled by specifying
1036
+ any string with `chunk_separator`. If at least one of the messages has a list
1037
+ of content blocks, the merged content is a list of content blocks.
1038
+
1039
+ Example:
1040
+ ```python
1041
+ from coco_core.messages import (
1042
+ merge_message_runs,
1043
+ AIMessage,
1044
+ HumanMessage,
1045
+ SystemMessage,
1046
+ ToolCall,
1047
+ )
1048
+
1049
+ messages = [
1050
+ SystemMessage("you're a good assistant."),
1051
+ HumanMessage(
1052
+ "what's your favorite color",
1053
+ id="foo",
1054
+ ),
1055
+ HumanMessage(
1056
+ "wait your favorite food",
1057
+ id="bar",
1058
+ ),
1059
+ AIMessage(
1060
+ "my favorite colo",
1061
+ tool_calls=[
1062
+ ToolCall(
1063
+ name="blah_tool", args={"x": 2}, id="123", type="tool_call"
1064
+ )
1065
+ ],
1066
+ id="baz",
1067
+ ),
1068
+ AIMessage(
1069
+ [{"type": "text", "text": "my favorite dish is lasagna"}],
1070
+ tool_calls=[
1071
+ ToolCall(
1072
+ name="blah_tool",
1073
+ args={"x": -10},
1074
+ id="456",
1075
+ type="tool_call",
1076
+ )
1077
+ ],
1078
+ id="blur",
1079
+ ),
1080
+ ]
1081
+
1082
+ merge_message_runs(messages)
1083
+ ```
1084
+
1085
+ ```python
1086
+ [
1087
+ SystemMessage("you're a good assistant."),
1088
+ HumanMessage(
1089
+ "what's your favorite color\\n"
1090
+ "wait your favorite food", id="foo",
1091
+ ),
1092
+ AIMessage(
1093
+ [
1094
+ "my favorite colo",
1095
+ {"type": "text", "text": "my favorite dish is lasagna"}
1096
+ ],
1097
+ tool_calls=[
1098
+ ToolCall({
1099
+ "name": "blah_tool",
1100
+ "args": {"x": 2},
1101
+ "id": "123",
1102
+ "type": "tool_call"
1103
+ }),
1104
+ ToolCall({
1105
+ "name": "blah_tool",
1106
+ "args": {"x": -10},
1107
+ "id": "456",
1108
+ "type": "tool_call"
1109
+ })
1110
+ ]
1111
+ id="baz"
1112
+ ),
1113
+ ]
1114
+
1115
+ ```
1116
+ """
1117
+ if not messages:
1118
+ return []
1119
+ messages = convert_to_messages(messages)
1120
+ merged: list[BaseMessage] = []
1121
+ for msg in messages:
1122
+ last = merged.pop() if merged else None
1123
+ if not last:
1124
+ merged.append(msg)
1125
+ elif isinstance(msg, ToolMessage) or not isinstance(msg, last.__class__):
1126
+ merged.extend([last, msg])
1127
+ else:
1128
+ last_chunk = _msg_to_chunk(last)
1129
+ curr_chunk = _msg_to_chunk(msg)
1130
+ if curr_chunk.response_metadata:
1131
+ curr_chunk.response_metadata.clear()
1132
+ if (
1133
+ isinstance(last_chunk.content, str)
1134
+ and isinstance(curr_chunk.content, str)
1135
+ and last_chunk.content
1136
+ and curr_chunk.content
1137
+ ):
1138
+ last_chunk.content += chunk_separator
1139
+ merged.append(_chunk_to_msg(last_chunk + curr_chunk))
1140
+ return merged
1141
+
1142
+
1143
+ # TODO: Update so validation errors (for token_counter, for example) are raised on
1144
+ # init not at runtime.
1145
+ @_runnable_support
1146
+ def trim_messages(
1147
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
1148
+ *,
1149
+ max_tokens: int,
1150
+ token_counter: Callable[[list[BaseMessage]], int]
1151
+ | Callable[[BaseMessage], int]
1152
+ | BaseLanguageModel[Any]
1153
+ | Literal["approximate"],
1154
+ strategy: Literal["first", "last"] = "last",
1155
+ allow_partial: bool = False,
1156
+ end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
1157
+ start_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
1158
+ include_system: bool = False,
1159
+ text_splitter: Callable[[str], list[str]] | TextSplitter | None = None,
1160
+ ) -> list[BaseMessage]:
1161
+ r"""Trim messages to be below a token count.
1162
+
1163
+ `trim_messages` can be used to reduce the size of a chat history to a specified
1164
+ token or message count.
1165
+
1166
+ In either case, if passing the trimmed chat history back into a chat model
1167
+ directly, the resulting chat history should usually satisfy the following
1168
+ properties:
1169
+
1170
+ 1. The resulting chat history should be valid. Most chat models expect that chat
1171
+ history starts with either (1) a `HumanMessage` or (2) a `SystemMessage`
1172
+ followed by a `HumanMessage`. To achieve this, set `start_on='human'`.
1173
+ In addition, generally a `ToolMessage` can only appear after an `AIMessage`
1174
+ that involved a tool call.
1175
+ 2. It includes recent messages and drops old messages in the chat history.
1176
+ To achieve this set the `strategy='last'`.
1177
+ 3. Usually, the new chat history should include the `SystemMessage` if it
1178
+ was present in the original chat history since the `SystemMessage` includes
1179
+ special instructions to the chat model. The `SystemMessage` is almost always
1180
+ the first message in the history if present. To achieve this set the
1181
+ `include_system=True`.
1182
+
1183
+ !!! note
1184
+ The examples below show how to configure `trim_messages` to achieve a behavior
1185
+ consistent with the above properties.
1186
+
1187
+ Args:
1188
+ messages: Sequence of Message-like objects to trim.
1189
+ max_tokens: Max token count of trimmed messages.
1190
+ token_counter: Function or llm for counting tokens in a `BaseMessage` or a
1191
+ list of `BaseMessage`.
1192
+
1193
+ If a `BaseLanguageModel` is passed in then
1194
+ `BaseLanguageModel.get_num_tokens_from_messages()` will be used. Set to
1195
+ `len` to count the number of **messages** in the chat history.
1196
+
1197
+ You can also use string shortcuts for convenience:
1198
+
1199
+ - `'approximate'`: Uses `count_tokens_approximately` for fast, approximate
1200
+ token counts.
1201
+
1202
+ !!! note
1203
+
1204
+ `count_tokens_approximately` (or the shortcut `'approximate'`) is
1205
+ recommended for using `trim_messages` on the hot path, where exact token
1206
+ counting is not necessary.
1207
+
1208
+ strategy: Strategy for trimming.
1209
+
1210
+ - `'first'`: Keep the first `<= n_count` tokens of the messages.
1211
+ - `'last'`: Keep the last `<= n_count` tokens of the messages.
1212
+ allow_partial: Whether to split a message if only part of the message can be
1213
+ included.
1214
+
1215
+ If `strategy='last'` then the last partial contents of a message are
1216
+ included. If `strategy='first'` then the first partial contents of a
1217
+ message are included.
1218
+ end_on: The message type to end on.
1219
+
1220
+ If specified then every message after the last occurrence of this type is
1221
+ ignored. If `strategy='last'` then this is done before we attempt to get the
1222
+ last `max_tokens`. If `strategy='first'` then this is done after we get the
1223
+ first `max_tokens`. Can be specified as string names (e.g. `'system'`,
1224
+ `'human'`, `'ai'`, ...) or as `BaseMessage` classes (e.g. `SystemMessage`,
1225
+ `HumanMessage`, `AIMessage`, ...). Can be a single type or a list of types.
1226
+
1227
+ start_on: The message type to start on.
1228
+
1229
+ Should only be specified if `strategy='last'`. If specified then every
1230
+ message before the first occurrence of this type is ignored. This is done
1231
+ after we trim the initial messages to the last `max_tokens`. Does not apply
1232
+ to a `SystemMessage` at index 0 if `include_system=True`. Can be specified
1233
+ as string names (e.g. `'system'`, `'human'`, `'ai'`, ...) or as
1234
+ `BaseMessage` classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`,
1235
+ ...). Can be a single type or a list of types.
1236
+
1237
+ include_system: Whether to keep the `SystemMessage` if there is one at index
1238
+ `0`.
1239
+
1240
+ Should only be specified if `strategy="last"`.
1241
+ text_splitter: Function or `coco_text_splitters.TextSplitter` for
1242
+ splitting the string contents of a message.
1243
+
1244
+ Only used if `allow_partial=True`. If `strategy='last'` then the last split
1245
+ tokens from a partial message will be included. if `strategy='first'` then
1246
+ the first split tokens from a partial message will be included. Token
1247
+ splitter assumes that separators are kept, so that split contents can be
1248
+ directly concatenated to recreate the original text. Defaults to splitting
1249
+ on newlines.
1250
+
1251
+ Returns:
1252
+ List of trimmed `BaseMessage`.
1253
+
1254
+ Raises:
1255
+ ValueError: if two incompatible arguments are specified or an unrecognized
1256
+ `strategy` is specified.
1257
+
1258
+ Example:
1259
+ Trim chat history based on token count, keeping the `SystemMessage` if
1260
+ present, and ensuring that the chat history starts with a `HumanMessage` (or a
1261
+ `SystemMessage` followed by a `HumanMessage`).
1262
+
1263
+ ```python
1264
+ from coco_core.messages import (
1265
+ AIMessage,
1266
+ HumanMessage,
1267
+ BaseMessage,
1268
+ SystemMessage,
1269
+ trim_messages,
1270
+ )
1271
+
1272
+ messages = [
1273
+ SystemMessage("you're a good assistant, you always respond with a joke."),
1274
+ HumanMessage("i wonder why it's called coco"),
1275
+ AIMessage(
1276
+ 'Well, I guess they thought "WordRope" and "SentenceString" just '
1277
+ "didn't have the same ring to it!"
1278
+ ),
1279
+ HumanMessage("and who is harrison chasing anyways"),
1280
+ AIMessage(
1281
+ "Hmmm let me think.\n\nWhy, he's probably chasing after the last "
1282
+ "cup of coffee in the office!"
1283
+ ),
1284
+ HumanMessage("what do you call a speechless parrot"),
1285
+ ]
1286
+
1287
+
1288
+ trim_messages(
1289
+ messages,
1290
+ max_tokens=45,
1291
+ strategy="last",
1292
+ token_counter=ChatOpenAI(model="gpt-5.5"),
1293
+ # Most chat models expect that chat history starts with either:
1294
+ # (1) a HumanMessage or
1295
+ # (2) a SystemMessage followed by a HumanMessage
1296
+ start_on="human",
1297
+ # Usually, we want to keep the SystemMessage
1298
+ # if it's present in the original history.
1299
+ # The SystemMessage has special instructions for the model.
1300
+ include_system=True,
1301
+ allow_partial=False,
1302
+ )
1303
+ ```
1304
+
1305
+ ```python
1306
+ [
1307
+ SystemMessage(
1308
+ content="you're a good assistant, you always respond with a joke."
1309
+ ),
1310
+ HumanMessage(content="what do you call a speechless parrot"),
1311
+ ]
1312
+ ```
1313
+
1314
+ Trim chat history using approximate token counting with `'approximate'`:
1315
+
1316
+ ```python
1317
+ trim_messages(
1318
+ messages,
1319
+ max_tokens=45,
1320
+ strategy="last",
1321
+ # Using the "approximate" shortcut for fast token counting
1322
+ token_counter="approximate",
1323
+ start_on="human",
1324
+ include_system=True,
1325
+ )
1326
+
1327
+ # This is equivalent to using `count_tokens_approximately` directly
1328
+ from coco_core.messages.utils import count_tokens_approximately
1329
+
1330
+ trim_messages(
1331
+ messages,
1332
+ max_tokens=45,
1333
+ strategy="last",
1334
+ token_counter=count_tokens_approximately,
1335
+ start_on="human",
1336
+ include_system=True,
1337
+ )
1338
+ ```
1339
+
1340
+ Trim chat history based on the message count, keeping the `SystemMessage` if
1341
+ present, and ensuring that the chat history starts with a HumanMessage (
1342
+ or a `SystemMessage` followed by a `HumanMessage`).
1343
+
1344
+ trim_messages(
1345
+ messages,
1346
+ # When `len` is passed in as the token counter function,
1347
+ # max_tokens will count the number of messages in the chat history.
1348
+ max_tokens=4,
1349
+ strategy="last",
1350
+ # Passing in `len` as a token counter function will
1351
+ # count the number of messages in the chat history.
1352
+ token_counter=len,
1353
+ # Most chat models expect that chat history starts with either:
1354
+ # (1) a HumanMessage or
1355
+ # (2) a SystemMessage followed by a HumanMessage
1356
+ start_on="human",
1357
+ # Usually, we want to keep the SystemMessage
1358
+ # if it's present in the original history.
1359
+ # The SystemMessage has special instructions for the model.
1360
+ include_system=True,
1361
+ allow_partial=False,
1362
+ )
1363
+
1364
+ ```python
1365
+ [
1366
+ SystemMessage(
1367
+ content="you're a good assistant, you always respond with a joke."
1368
+ ),
1369
+ HumanMessage(content="and who is harrison chasing anyways"),
1370
+ AIMessage(
1371
+ content="Hmmm let me think.\n\nWhy, he's probably chasing after "
1372
+ "the last cup of coffee in the office!"
1373
+ ),
1374
+ HumanMessage(content="what do you call a speechless parrot"),
1375
+ ]
1376
+ ```
1377
+ Trim chat history using a custom token counter function that counts the
1378
+ number of tokens in each message.
1379
+
1380
+ ```python
1381
+ messages = [
1382
+ SystemMessage("This is a 4 token text. The full message is 10 tokens."),
1383
+ HumanMessage(
1384
+ "This is a 4 token text. The full message is 10 tokens.", id="first"
1385
+ ),
1386
+ AIMessage(
1387
+ [
1388
+ {"type": "text", "text": "This is the FIRST 4 token block."},
1389
+ {"type": "text", "text": "This is the SECOND 4 token block."},
1390
+ ],
1391
+ id="second",
1392
+ ),
1393
+ HumanMessage(
1394
+ "This is a 4 token text. The full message is 10 tokens.", id="third"
1395
+ ),
1396
+ AIMessage(
1397
+ "This is a 4 token text. The full message is 10 tokens.",
1398
+ id="fourth",
1399
+ ),
1400
+ ]
1401
+
1402
+
1403
+ def dummy_token_counter(messages: list[BaseMessage]) -> int:
1404
+ # treat each message like it adds 3 default tokens at the beginning
1405
+ # of the message and at the end of the message. 3 + 4 + 3 = 10 tokens
1406
+ # per message.
1407
+
1408
+ default_content_len = 4
1409
+ default_msg_prefix_len = 3
1410
+ default_msg_suffix_len = 3
1411
+
1412
+ count = 0
1413
+ for msg in messages:
1414
+ if isinstance(msg.content, str):
1415
+ count += (
1416
+ default_msg_prefix_len
1417
+ + default_content_len
1418
+ + default_msg_suffix_len
1419
+ )
1420
+ if isinstance(msg.content, list):
1421
+ count += (
1422
+ default_msg_prefix_len
1423
+ + len(msg.content) * default_content_len
1424
+ + default_msg_suffix_len
1425
+ )
1426
+ return count
1427
+ ```
1428
+
1429
+ First 30 tokens, allowing partial messages:
1430
+ ```python
1431
+ trim_messages(
1432
+ messages,
1433
+ max_tokens=30,
1434
+ token_counter=dummy_token_counter,
1435
+ strategy="first",
1436
+ allow_partial=True,
1437
+ )
1438
+ ```
1439
+
1440
+ ```python
1441
+ [
1442
+ SystemMessage("This is a 4 token text. The full message is 10 tokens."),
1443
+ HumanMessage(
1444
+ "This is a 4 token text. The full message is 10 tokens.",
1445
+ id="first",
1446
+ ),
1447
+ AIMessage(
1448
+ [{"type": "text", "text": "This is the FIRST 4 token block."}],
1449
+ id="second",
1450
+ ),
1451
+ ]
1452
+ ```
1453
+ """
1454
+ # Validate arguments
1455
+ if start_on and strategy == "first":
1456
+ msg = "start_on parameter is only valid with strategy='last'"
1457
+ raise ValueError(msg)
1458
+ if include_system and strategy == "first":
1459
+ msg = "include_system parameter is only valid with strategy='last'"
1460
+ raise ValueError(msg)
1461
+
1462
+ messages = convert_to_messages(messages)
1463
+
1464
+ # Handle string shortcuts for token counter
1465
+ if isinstance(token_counter, str):
1466
+ if token_counter in _TOKEN_COUNTER_SHORTCUTS:
1467
+ actual_token_counter = _TOKEN_COUNTER_SHORTCUTS[token_counter]
1468
+ else:
1469
+ available_shortcuts = ", ".join(
1470
+ f"'{key}'" for key in _TOKEN_COUNTER_SHORTCUTS
1471
+ )
1472
+ msg = (
1473
+ f"Invalid token_counter shortcut '{token_counter}'. "
1474
+ f"Available shortcuts: {available_shortcuts}."
1475
+ )
1476
+ raise ValueError(msg)
1477
+ else:
1478
+ # Type narrowing: at this point token_counter is not a str
1479
+ actual_token_counter = token_counter # type: ignore[assignment]
1480
+
1481
+ if hasattr(actual_token_counter, "get_num_tokens_from_messages"):
1482
+ list_token_counter = actual_token_counter.get_num_tokens_from_messages
1483
+ elif callable(actual_token_counter):
1484
+ if (
1485
+ next(
1486
+ iter(inspect.signature(actual_token_counter).parameters.values())
1487
+ ).annotation
1488
+ is BaseMessage
1489
+ ):
1490
+
1491
+ def list_token_counter(messages: Sequence[BaseMessage]) -> int:
1492
+ return sum(actual_token_counter(msg) for msg in messages) # type: ignore[arg-type, misc]
1493
+
1494
+ else:
1495
+ list_token_counter = actual_token_counter
1496
+ else:
1497
+ msg = ( # type: ignore[unreachable]
1498
+ f"'token_counter' expected to be a model that implements "
1499
+ f"'get_num_tokens_from_messages()' or a function. Received object of type "
1500
+ f"{type(actual_token_counter)}."
1501
+ )
1502
+ raise ValueError(msg)
1503
+
1504
+ text_splitter_fn: Callable[[str], list[str]]
1505
+ if _HAS_COCO_TEXT_SPLITTERS and isinstance(text_splitter, TextSplitter):
1506
+ text_splitter_fn = text_splitter.split_text
1507
+ elif text_splitter:
1508
+ text_splitter_fn = cast("Callable[[str], list[str]]", text_splitter)
1509
+ else:
1510
+ text_splitter_fn = _default_text_splitter
1511
+
1512
+ if strategy == "first":
1513
+ return _first_max_tokens(
1514
+ messages,
1515
+ max_tokens=max_tokens,
1516
+ token_counter=list_token_counter,
1517
+ text_splitter=text_splitter_fn,
1518
+ partial_strategy="first" if allow_partial else None,
1519
+ end_on=end_on,
1520
+ )
1521
+ if strategy == "last":
1522
+ return _last_max_tokens(
1523
+ messages,
1524
+ max_tokens=max_tokens,
1525
+ token_counter=list_token_counter,
1526
+ allow_partial=allow_partial,
1527
+ include_system=include_system,
1528
+ start_on=start_on,
1529
+ end_on=end_on,
1530
+ text_splitter=text_splitter_fn,
1531
+ )
1532
+ msg = f"Unrecognized {strategy=}. Supported strategies are 'last' and 'first'." # type: ignore[unreachable]
1533
+ raise ValueError(msg)
1534
+
1535
+
1536
+ _SingleMessage = BaseMessage | str | dict[str, Any]
1537
+ _T = TypeVar("_T", bound=_SingleMessage)
1538
+ # A sequence of _SingleMessage that is NOT a bare str
1539
+ _MultipleMessages = Sequence[_T]
1540
+
1541
+
1542
+ @overload
1543
+ def convert_to_openai_messages(
1544
+ messages: _SingleMessage,
1545
+ *,
1546
+ text_format: Literal["string", "block"] = "string",
1547
+ include_id: bool = False,
1548
+ pass_through_unknown_blocks: bool = True,
1549
+ ) -> dict[str, Any]: ...
1550
+
1551
+
1552
+ @overload
1553
+ def convert_to_openai_messages(
1554
+ messages: _MultipleMessages[Any],
1555
+ *,
1556
+ text_format: Literal["string", "block"] = "string",
1557
+ include_id: bool = False,
1558
+ pass_through_unknown_blocks: bool = True,
1559
+ ) -> list[dict[str, Any]]: ...
1560
+
1561
+
1562
+ def convert_to_openai_messages(
1563
+ messages: MessageLikeRepresentation | Sequence[MessageLikeRepresentation],
1564
+ *,
1565
+ text_format: Literal["string", "block"] = "string",
1566
+ include_id: bool = False,
1567
+ pass_through_unknown_blocks: bool = True,
1568
+ ) -> dict[str, Any] | list[dict[str, Any]]:
1569
+ """Convert Coco messages into OpenAI message dicts.
1570
+
1571
+ Args:
1572
+ messages: Message-like object or iterable of objects whose contents are
1573
+ in OpenAI, Anthropic, Bedrock Converse, or VertexAI formats.
1574
+ text_format: How to format string or text block contents:
1575
+ - `'string'`:
1576
+ If a message has a string content, this is left as a string. If
1577
+ a message has content blocks that are all of type `'text'`, these
1578
+ are joined with a newline to make a single string. If a message has
1579
+ content blocks and at least one isn't of type `'text'`, then
1580
+ all blocks are left as dicts.
1581
+ - `'block'`:
1582
+ If a message has a string content, this is turned into a list
1583
+ with a single content block of type `'text'`. If a message has
1584
+ content blocks these are left as is.
1585
+ include_id: Whether to include message IDs in the openai messages, if they
1586
+ are present in the source messages.
1587
+ pass_through_unknown_blocks: Whether to include content blocks with unknown
1588
+ formats in the output. If `False`, an error is raised if an unknown
1589
+ content block is encountered.
1590
+
1591
+ Raises:
1592
+ ValueError: if an unrecognized `text_format` is specified, or if a message
1593
+ content block is missing expected keys.
1594
+
1595
+ Returns:
1596
+ The return type depends on the input type:
1597
+
1598
+ - dict:
1599
+ If a single message-like object is passed in, a single OpenAI message
1600
+ dict is returned.
1601
+ - list[dict]:
1602
+ If a sequence of message-like objects are passed in, a list of OpenAI
1603
+ message dicts is returned.
1604
+
1605
+ Example:
1606
+ ```python
1607
+ from coco_core.messages import (
1608
+ convert_to_openai_messages,
1609
+ AIMessage,
1610
+ SystemMessage,
1611
+ ToolMessage,
1612
+ )
1613
+
1614
+ messages = [
1615
+ SystemMessage([{"type": "text", "text": "foo"}]),
1616
+ {
1617
+ "role": "user",
1618
+ "content": [
1619
+ {"type": "text", "text": "what's in this"},
1620
+ {
1621
+ "type": "image_url",
1622
+ "image_url": {"url": "data:image/png;base64,'/9j/4AAQSk'"},
1623
+ },
1624
+ ],
1625
+ },
1626
+ AIMessage(
1627
+ "",
1628
+ tool_calls=[
1629
+ {
1630
+ "name": "analyze",
1631
+ "args": {"baz": "buz"},
1632
+ "id": "1",
1633
+ "type": "tool_call",
1634
+ }
1635
+ ],
1636
+ ),
1637
+ ToolMessage("foobar", tool_call_id="1", name="bar"),
1638
+ {"role": "assistant", "content": "that's nice"},
1639
+ ]
1640
+ oai_messages = convert_to_openai_messages(messages)
1641
+ # -> [
1642
+ # {'role': 'system', 'content': 'foo'},
1643
+ # {'role': 'user', 'content': [{'type': 'text', 'text': 'what's in this'}, {'type': 'image_url', 'image_url': {'url': "data:image/png;base64,'/9j/4AAQSk'"}}]},
1644
+ # {'role': 'assistant', 'tool_calls': [{'type': 'function', 'id': '1','function': {'name': 'analyze', 'arguments': '{"baz": "buz"}'}}], 'content': ''},
1645
+ # {'role': 'tool', 'name': 'bar', 'content': 'foobar'},
1646
+ # {'role': 'assistant', 'content': 'that's nice'}
1647
+ # ]
1648
+ ```
1649
+
1650
+ !!! version-added "Added in `trustcoco-core` 0.3.11"
1651
+
1652
+ """ # noqa: E501
1653
+ if text_format not in {"string", "block"}:
1654
+ err = f"Unrecognized {text_format=}, expected one of 'string' or 'block'."
1655
+ raise ValueError(err)
1656
+
1657
+ oai_messages: list[dict[str, Any]] = []
1658
+
1659
+ messages_: Sequence[MessageLikeRepresentation]
1660
+ if is_single := isinstance(messages, (BaseMessage, dict, str)):
1661
+ messages_ = [messages]
1662
+ else:
1663
+ messages_ = cast("Sequence[MessageLikeRepresentation]", messages)
1664
+
1665
+ for i, message in enumerate(convert_to_messages(messages_)):
1666
+ oai_msg: dict[str, Any] = {"role": _get_message_openai_role(message)}
1667
+ tool_messages: list[dict[str, Any]] = []
1668
+ content: str | list[dict[str, Any]]
1669
+
1670
+ if message.name:
1671
+ oai_msg["name"] = message.name
1672
+ if isinstance(message, AIMessage) and message.tool_calls:
1673
+ oai_msg["tool_calls"] = _convert_to_openai_tool_calls(message.tool_calls)
1674
+ if message.additional_kwargs.get("refusal"):
1675
+ oai_msg["refusal"] = message.additional_kwargs["refusal"]
1676
+ if isinstance(message, ToolMessage):
1677
+ oai_msg["tool_call_id"] = message.tool_call_id
1678
+ if include_id and message.id:
1679
+ oai_msg["id"] = message.id
1680
+
1681
+ if not message.content:
1682
+ content = "" if text_format == "string" else []
1683
+ elif isinstance(message.content, str):
1684
+ if text_format == "string":
1685
+ content = message.content
1686
+ else:
1687
+ content = [{"type": "text", "text": message.content}]
1688
+ elif text_format == "string" and all(
1689
+ isinstance(block, str) or block.get("type") == "text"
1690
+ for block in message.content
1691
+ ):
1692
+ content = "\n".join(
1693
+ block if isinstance(block, str) else block["text"]
1694
+ for block in message.content
1695
+ )
1696
+ else:
1697
+ content = []
1698
+ for j, block in enumerate(message.content):
1699
+ # OpenAI format
1700
+ if isinstance(block, str):
1701
+ content.append({"type": "text", "text": block})
1702
+ elif block.get("type") == "text":
1703
+ if missing := [k for k in ("text",) if k not in block]:
1704
+ err = (
1705
+ f"Unrecognized content block at "
1706
+ f"messages[{i}].content[{j}] has 'type': 'text' "
1707
+ f"but is missing expected key(s) "
1708
+ f"{missing}. Full content block:\n\n{block}"
1709
+ )
1710
+ raise ValueError(err)
1711
+ content.append({"type": block["type"], "text": block["text"]})
1712
+ elif block.get("type") == "image_url":
1713
+ if missing := [k for k in ("image_url",) if k not in block]:
1714
+ err = (
1715
+ f"Unrecognized content block at "
1716
+ f"messages[{i}].content[{j}] has 'type': 'image_url' "
1717
+ f"but is missing expected key(s) "
1718
+ f"{missing}. Full content block:\n\n{block}"
1719
+ )
1720
+ raise ValueError(err)
1721
+ content.append(
1722
+ {
1723
+ "type": "image_url",
1724
+ "image_url": block["image_url"],
1725
+ }
1726
+ )
1727
+ # Standard multi-modal content block
1728
+ elif is_data_content_block(block):
1729
+ formatted_block = convert_to_openai_data_block(block)
1730
+ if (
1731
+ formatted_block.get("type") == "file"
1732
+ and "file" in formatted_block
1733
+ and "filename" not in formatted_block["file"]
1734
+ ):
1735
+ logger.info("Generating a fallback filename.")
1736
+ formatted_block["file"]["filename"] = "LC_AUTOGENERATED"
1737
+ content.append(formatted_block)
1738
+ # Anthropic and Bedrock converse format
1739
+ elif (block.get("type") == "image") or "image" in block:
1740
+ # Anthropic
1741
+ if source := block.get("source"):
1742
+ if missing := [
1743
+ k for k in ("media_type", "type", "data") if k not in source
1744
+ ]:
1745
+ err = (
1746
+ f"Unrecognized content block at "
1747
+ f"messages[{i}].content[{j}] has 'type': 'image' "
1748
+ f"but 'source' is missing expected key(s) "
1749
+ f"{missing}. Full content block:\n\n{block}"
1750
+ )
1751
+ raise ValueError(err)
1752
+ content.append(
1753
+ {
1754
+ "type": "image_url",
1755
+ "image_url": {
1756
+ "url": (
1757
+ f"data:{source['media_type']};"
1758
+ f"{source['type']},{source['data']}"
1759
+ )
1760
+ },
1761
+ }
1762
+ )
1763
+ # Bedrock converse
1764
+ elif image := block.get("image"):
1765
+ if missing := [
1766
+ k for k in ("source", "format") if k not in image
1767
+ ]:
1768
+ err = (
1769
+ f"Unrecognized content block at "
1770
+ f"messages[{i}].content[{j}] has key 'image', "
1771
+ f"but 'image' is missing expected key(s) "
1772
+ f"{missing}. Full content block:\n\n{block}"
1773
+ )
1774
+ raise ValueError(err)
1775
+ b64_image = _bytes_to_b64_str(image["source"]["bytes"])
1776
+ content.append(
1777
+ {
1778
+ "type": "image_url",
1779
+ "image_url": {
1780
+ "url": (
1781
+ f"data:image/{image['format']};base64,{b64_image}"
1782
+ )
1783
+ },
1784
+ }
1785
+ )
1786
+ else:
1787
+ err = (
1788
+ f"Unrecognized content block at "
1789
+ f"messages[{i}].content[{j}] has 'type': 'image' "
1790
+ f"but does not have a 'source' or 'image' key. Full "
1791
+ f"content block:\n\n{block}"
1792
+ )
1793
+ raise ValueError(err)
1794
+ # OpenAI file format
1795
+ elif (
1796
+ block.get("type") == "file"
1797
+ and isinstance(block.get("file"), dict)
1798
+ and isinstance(block.get("file", {}).get("file_data"), str)
1799
+ ):
1800
+ if block.get("file", {}).get("filename") is None:
1801
+ logger.info("Generating a fallback filename.")
1802
+ formatted_block = {
1803
+ **block,
1804
+ "file": {**block["file"], "filename": "LC_AUTOGENERATED"},
1805
+ }
1806
+ content.append(formatted_block)
1807
+ else:
1808
+ content.append(block)
1809
+ # OpenAI audio format
1810
+ elif (
1811
+ block.get("type") == "input_audio"
1812
+ and isinstance(block.get("input_audio"), dict)
1813
+ and isinstance(block.get("input_audio", {}).get("data"), str)
1814
+ and isinstance(block.get("input_audio", {}).get("format"), str)
1815
+ ):
1816
+ content.append(block)
1817
+ elif block.get("type") == "tool_use":
1818
+ if missing := [
1819
+ k for k in ("id", "name", "input") if k not in block
1820
+ ]:
1821
+ err = (
1822
+ f"Unrecognized content block at "
1823
+ f"messages[{i}].content[{j}] has 'type': "
1824
+ f"'tool_use', but is missing expected key(s) "
1825
+ f"{missing}. Full content block:\n\n{block}"
1826
+ )
1827
+ raise ValueError(err)
1828
+ if not any(
1829
+ tool_call["id"] == block["id"]
1830
+ for tool_call in cast("AIMessage", message).tool_calls
1831
+ ):
1832
+ oai_msg["tool_calls"] = oai_msg.get("tool_calls", [])
1833
+ oai_msg["tool_calls"].append(
1834
+ {
1835
+ "type": "function",
1836
+ "id": block["id"],
1837
+ "function": {
1838
+ "name": block["name"],
1839
+ "arguments": json.dumps(
1840
+ block["input"], ensure_ascii=False
1841
+ ),
1842
+ },
1843
+ }
1844
+ )
1845
+ elif block.get("type") == "function_call": # OpenAI Responses
1846
+ if not any(
1847
+ tool_call["id"] == block.get("call_id")
1848
+ for tool_call in cast("AIMessage", message).tool_calls
1849
+ ):
1850
+ if missing := [
1851
+ k
1852
+ for k in ("call_id", "name", "arguments")
1853
+ if k not in block
1854
+ ]:
1855
+ err = (
1856
+ f"Unrecognized content block at "
1857
+ f"messages[{i}].content[{j}] has 'type': "
1858
+ f"'tool_use', but is missing expected key(s) "
1859
+ f"{missing}. Full content block:\n\n{block}"
1860
+ )
1861
+ raise ValueError(err)
1862
+ oai_msg["tool_calls"] = oai_msg.get("tool_calls", [])
1863
+ oai_msg["tool_calls"].append(
1864
+ {
1865
+ "type": "function",
1866
+ "id": block.get("call_id"),
1867
+ "function": {
1868
+ "name": block.get("name"),
1869
+ "arguments": block.get("arguments"),
1870
+ },
1871
+ }
1872
+ )
1873
+ if pass_through_unknown_blocks:
1874
+ content.append(block)
1875
+ elif block.get("type") == "tool_result":
1876
+ if missing := [
1877
+ k for k in ("content", "tool_use_id") if k not in block
1878
+ ]:
1879
+ msg = (
1880
+ f"Unrecognized content block at "
1881
+ f"messages[{i}].content[{j}] has 'type': "
1882
+ f"'tool_result', but is missing expected key(s) "
1883
+ f"{missing}. Full content block:\n\n{block}"
1884
+ )
1885
+ raise ValueError(msg)
1886
+ tool_message = ToolMessage(
1887
+ block["content"],
1888
+ tool_call_id=block["tool_use_id"],
1889
+ status="error" if block.get("is_error") else "success",
1890
+ )
1891
+ # Recurse to make sure tool message contents are OpenAI format.
1892
+ tool_messages.extend(
1893
+ convert_to_openai_messages(
1894
+ [tool_message], text_format=text_format
1895
+ )
1896
+ )
1897
+ elif (block.get("type") == "json") or "json" in block:
1898
+ if "json" not in block:
1899
+ msg = (
1900
+ f"Unrecognized content block at "
1901
+ f"messages[{i}].content[{j}] has 'type': 'json' "
1902
+ f"but does not have a 'json' key. Full "
1903
+ f"content block:\n\n{block}"
1904
+ )
1905
+ raise ValueError(msg)
1906
+ content.append(
1907
+ {
1908
+ "type": "text",
1909
+ "text": json.dumps(block["json"]),
1910
+ }
1911
+ )
1912
+ elif (block.get("type") == "guard_content") or "guard_content" in block:
1913
+ if (
1914
+ "guard_content" not in block
1915
+ or "text" not in block["guard_content"]
1916
+ ):
1917
+ msg = (
1918
+ f"Unrecognized content block at "
1919
+ f"messages[{i}].content[{j}] has 'type': "
1920
+ f"'guard_content' but does not have a "
1921
+ f"messages[{i}].content[{j}]['guard_content']['text'] "
1922
+ f"key. Full content block:\n\n{block}"
1923
+ )
1924
+ raise ValueError(msg)
1925
+ text = block["guard_content"]["text"]
1926
+ if isinstance(text, dict):
1927
+ text = text["text"]
1928
+ content.append({"type": "text", "text": text})
1929
+ # VertexAI format
1930
+ elif block.get("type") == "media":
1931
+ if missing := [k for k in ("mime_type", "data") if k not in block]:
1932
+ err = (
1933
+ f"Unrecognized content block at "
1934
+ f"messages[{i}].content[{j}] has 'type': "
1935
+ f"'media' but does not have key(s) {missing}. Full "
1936
+ f"content block:\n\n{block}"
1937
+ )
1938
+ raise ValueError(err)
1939
+ if "image" not in block["mime_type"]:
1940
+ err = (
1941
+ f"OpenAI messages can only support text and image data."
1942
+ f" Received content block with media of type:"
1943
+ f" {block['mime_type']}"
1944
+ )
1945
+ raise ValueError(err)
1946
+ b64_image = _bytes_to_b64_str(block["data"])
1947
+ content.append(
1948
+ {
1949
+ "type": "image_url",
1950
+ "image_url": {
1951
+ "url": (f"data:{block['mime_type']};base64,{b64_image}")
1952
+ },
1953
+ }
1954
+ )
1955
+ elif (
1956
+ block.get("type") in {"thinking", "reasoning"}
1957
+ or pass_through_unknown_blocks
1958
+ ):
1959
+ content.append(block)
1960
+ else:
1961
+ err = (
1962
+ f"Unrecognized content block at "
1963
+ f"messages[{i}].content[{j}] does not match OpenAI, "
1964
+ f"Anthropic, Bedrock Converse, or VertexAI format. Full "
1965
+ f"content block:\n\n{block}"
1966
+ )
1967
+ raise ValueError(err)
1968
+ if text_format == "string" and not any(
1969
+ block["type"] != "text" for block in content
1970
+ ):
1971
+ content = "\n".join(block["text"] for block in content)
1972
+ oai_msg["content"] = content
1973
+ if message.content and not oai_msg["content"] and tool_messages:
1974
+ oai_messages.extend(tool_messages)
1975
+ else:
1976
+ oai_messages.extend([oai_msg, *tool_messages])
1977
+
1978
+ if is_single:
1979
+ return oai_messages[0]
1980
+ return oai_messages
1981
+
1982
+
1983
+ def _first_max_tokens(
1984
+ messages: Sequence[BaseMessage],
1985
+ *,
1986
+ max_tokens: int,
1987
+ token_counter: Callable[[list[BaseMessage]], int],
1988
+ text_splitter: Callable[[str], list[str]],
1989
+ partial_strategy: Literal["first", "last"] | None = None,
1990
+ end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
1991
+ ) -> list[BaseMessage]:
1992
+ messages = list(messages)
1993
+ if not messages:
1994
+ return messages
1995
+
1996
+ # Check if all messages already fit within token limit
1997
+ if token_counter(messages) <= max_tokens:
1998
+ # When all messages fit, only apply end_on filtering if needed
1999
+ if end_on:
2000
+ for _ in range(len(messages)):
2001
+ if not _is_message_type(messages[-1], end_on):
2002
+ messages.pop()
2003
+ else:
2004
+ break
2005
+ return messages
2006
+
2007
+ # Use binary search to find the maximum number of messages within token limit
2008
+ left, right = 0, len(messages)
2009
+ max_iterations = len(messages).bit_length()
2010
+ for _ in range(max_iterations):
2011
+ if left >= right:
2012
+ break
2013
+ mid = (left + right + 1) // 2
2014
+ if token_counter(messages[:mid]) <= max_tokens:
2015
+ left = mid
2016
+ idx = mid
2017
+ else:
2018
+ right = mid - 1
2019
+
2020
+ # idx now contains the maximum number of complete messages we can include
2021
+ idx = left
2022
+
2023
+ if partial_strategy and idx < len(messages):
2024
+ included_partial = False
2025
+ copied = False
2026
+ if isinstance(messages[idx].content, list):
2027
+ excluded = messages[idx].model_copy(deep=True)
2028
+ copied = True
2029
+ num_block = len(excluded.content)
2030
+ if partial_strategy == "last":
2031
+ excluded.content = list(reversed(excluded.content))
2032
+ for _ in range(1, num_block):
2033
+ excluded.content = excluded.content[:-1]
2034
+ if token_counter([*messages[:idx], excluded]) <= max_tokens:
2035
+ messages = [*messages[:idx], excluded]
2036
+ idx += 1
2037
+ included_partial = True
2038
+ break
2039
+ if included_partial and partial_strategy == "last":
2040
+ excluded.content = list(reversed(excluded.content))
2041
+ if not included_partial:
2042
+ if not copied:
2043
+ excluded = messages[idx].model_copy(deep=True)
2044
+ copied = True
2045
+
2046
+ # Extract text content efficiently
2047
+ text = None
2048
+ if isinstance(excluded.content, str):
2049
+ text = excluded.content
2050
+ elif isinstance(excluded.content, list) and excluded.content:
2051
+ for block in excluded.content:
2052
+ if isinstance(block, str):
2053
+ text = block
2054
+ break
2055
+ if isinstance(block, dict) and block.get("type") == "text":
2056
+ text = block.get("text")
2057
+ break
2058
+
2059
+ if text:
2060
+ if not copied:
2061
+ excluded = excluded.model_copy(deep=True)
2062
+
2063
+ split_texts = text_splitter(text)
2064
+ base_message_count = token_counter(messages[:idx])
2065
+ if partial_strategy == "last":
2066
+ split_texts = list(reversed(split_texts))
2067
+
2068
+ # Binary search for the maximum number of splits we can include
2069
+ left, right = 0, len(split_texts)
2070
+ max_iterations = len(split_texts).bit_length()
2071
+ for _ in range(max_iterations):
2072
+ if left >= right:
2073
+ break
2074
+ mid = (left + right + 1) // 2
2075
+ excluded.content = "".join(split_texts[:mid])
2076
+ if base_message_count + token_counter([excluded]) <= max_tokens:
2077
+ left = mid
2078
+ else:
2079
+ right = mid - 1
2080
+
2081
+ if left > 0:
2082
+ content_splits = split_texts[:left]
2083
+ if partial_strategy == "last":
2084
+ content_splits = list(reversed(content_splits))
2085
+ excluded.content = "".join(content_splits)
2086
+ messages = [*messages[:idx], excluded]
2087
+ idx += 1
2088
+
2089
+ if end_on:
2090
+ for _ in range(idx):
2091
+ if idx > 0 and not _is_message_type(messages[idx - 1], end_on):
2092
+ idx -= 1
2093
+ else:
2094
+ break
2095
+
2096
+ return messages[:idx]
2097
+
2098
+
2099
+ def _last_max_tokens(
2100
+ messages: Sequence[BaseMessage],
2101
+ *,
2102
+ max_tokens: int,
2103
+ token_counter: Callable[[list[BaseMessage]], int],
2104
+ text_splitter: Callable[[str], list[str]],
2105
+ allow_partial: bool = False,
2106
+ include_system: bool = False,
2107
+ start_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
2108
+ end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
2109
+ ) -> list[BaseMessage]:
2110
+ messages = list(messages)
2111
+ if len(messages) == 0:
2112
+ return []
2113
+
2114
+ # Filter out messages after end_on type
2115
+ if end_on:
2116
+ for _ in range(len(messages)):
2117
+ if not _is_message_type(messages[-1], end_on):
2118
+ messages.pop()
2119
+ else:
2120
+ break
2121
+
2122
+ # Handle system message preservation
2123
+ system_message = None
2124
+ if include_system and len(messages) > 0 and isinstance(messages[0], SystemMessage):
2125
+ system_message = messages[0]
2126
+ messages = messages[1:]
2127
+
2128
+ # Reverse messages to use _first_max_tokens with reversed logic
2129
+ reversed_messages = messages[::-1]
2130
+
2131
+ # Calculate remaining tokens after accounting for system message if present
2132
+ remaining_tokens = max_tokens
2133
+ if system_message:
2134
+ system_tokens = token_counter([system_message])
2135
+ remaining_tokens = max(0, max_tokens - system_tokens)
2136
+
2137
+ reversed_result = _first_max_tokens(
2138
+ reversed_messages,
2139
+ max_tokens=remaining_tokens,
2140
+ token_counter=token_counter,
2141
+ text_splitter=text_splitter,
2142
+ partial_strategy="last" if allow_partial else None,
2143
+ end_on=start_on,
2144
+ )
2145
+
2146
+ # Re-reverse the messages and add back the system message if needed
2147
+ result = reversed_result[::-1]
2148
+ if system_message:
2149
+ result = [system_message, *result]
2150
+
2151
+ return result
2152
+
2153
+
2154
+ _MSG_CHUNK_MAP: dict[type[BaseMessage], type[BaseMessageChunk]] = {
2155
+ HumanMessage: HumanMessageChunk,
2156
+ AIMessage: AIMessageChunk,
2157
+ SystemMessage: SystemMessageChunk,
2158
+ ToolMessage: ToolMessageChunk,
2159
+ FunctionMessage: FunctionMessageChunk,
2160
+ ChatMessage: ChatMessageChunk,
2161
+ }
2162
+ _CHUNK_MSG_MAP = {v: k for k, v in _MSG_CHUNK_MAP.items()}
2163
+
2164
+
2165
+ def _msg_to_chunk(message: BaseMessage) -> BaseMessageChunk:
2166
+ if message.__class__ in _MSG_CHUNK_MAP:
2167
+ return _MSG_CHUNK_MAP[message.__class__](**message.model_dump(exclude={"type"}))
2168
+
2169
+ for msg_cls, chunk_cls in _MSG_CHUNK_MAP.items():
2170
+ if isinstance(message, msg_cls):
2171
+ return chunk_cls(**message.model_dump(exclude={"type"}))
2172
+
2173
+ msg = (
2174
+ f"Unrecognized message class {message.__class__}. Supported classes are "
2175
+ f"{list(_MSG_CHUNK_MAP.keys())}"
2176
+ )
2177
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
2178
+ raise ValueError(msg)
2179
+
2180
+
2181
+ def _chunk_to_msg(chunk: BaseMessageChunk) -> BaseMessage:
2182
+ if chunk.__class__ in _CHUNK_MSG_MAP:
2183
+ return _CHUNK_MSG_MAP[chunk.__class__](
2184
+ **chunk.model_dump(exclude={"type", "tool_call_chunks", "chunk_position"})
2185
+ )
2186
+ for chunk_cls, msg_cls in _CHUNK_MSG_MAP.items():
2187
+ if isinstance(chunk, chunk_cls):
2188
+ return msg_cls(
2189
+ **chunk.model_dump(
2190
+ exclude={"type", "tool_call_chunks", "chunk_position"}
2191
+ )
2192
+ )
2193
+
2194
+ msg = (
2195
+ f"Unrecognized message chunk class {chunk.__class__}. Supported classes are "
2196
+ f"{list(_CHUNK_MSG_MAP.keys())}"
2197
+ )
2198
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
2199
+ raise ValueError(msg)
2200
+
2201
+
2202
+ def _default_text_splitter(text: str) -> list[str]:
2203
+ splits = text.split("\n")
2204
+ return [s + "\n" for s in splits[:-1]] + splits[-1:]
2205
+
2206
+
2207
+ def _is_message_type(
2208
+ message: BaseMessage,
2209
+ type_: str | type[BaseMessage] | Sequence[str | type[BaseMessage]],
2210
+ ) -> bool:
2211
+ types = [type_] if isinstance(type_, (str, type)) else type_
2212
+ types_str = [t for t in types if isinstance(t, str)]
2213
+ types_types = tuple(t for t in types if isinstance(t, type))
2214
+
2215
+ return message.type in types_str or isinstance(message, types_types)
2216
+
2217
+
2218
+ def _bytes_to_b64_str(bytes_: bytes) -> str:
2219
+ return base64.b64encode(bytes_).decode("utf-8")
2220
+
2221
+
2222
+ def _get_message_openai_role(message: BaseMessage) -> str:
2223
+ if isinstance(message, AIMessage):
2224
+ return "assistant"
2225
+ if isinstance(message, HumanMessage):
2226
+ return "user"
2227
+ if isinstance(message, ToolMessage):
2228
+ return "tool"
2229
+ if isinstance(message, SystemMessage):
2230
+ role = message.additional_kwargs.get("__openai_role__", "system")
2231
+ if not isinstance(role, str):
2232
+ msg = f"Expected '__openai_role__' to be a str, got {type(role).__name__}"
2233
+ raise TypeError(msg)
2234
+ return role
2235
+ if isinstance(message, FunctionMessage):
2236
+ return "function"
2237
+ if isinstance(message, ChatMessage):
2238
+ return message.role
2239
+ msg = f"Unknown BaseMessage type {message.__class__}."
2240
+ raise ValueError(msg)
2241
+
2242
+
2243
+ def _convert_to_openai_tool_calls(tool_calls: list[ToolCall]) -> list[dict[str, Any]]:
2244
+ return [
2245
+ {
2246
+ "type": "function",
2247
+ "id": tool_call["id"],
2248
+ "function": {
2249
+ "name": tool_call["name"],
2250
+ "arguments": json.dumps(tool_call["args"], ensure_ascii=False),
2251
+ },
2252
+ }
2253
+ for tool_call in tool_calls
2254
+ ]
2255
+
2256
+
2257
+ def count_tokens_approximately(
2258
+ messages: Iterable[MessageLikeRepresentation],
2259
+ *,
2260
+ chars_per_token: float = 4.0,
2261
+ extra_tokens_per_message: float = 3.0,
2262
+ count_name: bool = True,
2263
+ tokens_per_image: int = 85,
2264
+ use_usage_metadata_scaling: bool = False,
2265
+ tools: list[BaseTool | dict[str, Any]] | None = None,
2266
+ ) -> int:
2267
+ """Approximate the total number of tokens in messages.
2268
+
2269
+ The token count includes stringified message content, role, and (optionally) name.
2270
+
2271
+ - For AI messages, the token count also includes stringified tool calls.
2272
+ - For tool messages, the token count also includes the tool call ID.
2273
+ - For multimodal messages with images, applies a fixed token penalty per image
2274
+ instead of counting base64-encoded characters.
2275
+ - If tools are provided, the token count also includes stringified tool schemas.
2276
+
2277
+ Args:
2278
+ messages: List of messages to count tokens for.
2279
+ chars_per_token: Number of characters per token to use for the approximation.
2280
+ One token corresponds to ~4 chars for common English text.
2281
+ You can also specify `float` values for more fine-grained control.
2282
+ [See more here](https://platform.openai.com/tokenizer).
2283
+ extra_tokens_per_message: Number of extra tokens to add per message, e.g.
2284
+ special tokens, including beginning/end of message.
2285
+ You can also specify `float` values for more fine-grained control.
2286
+ [See more here](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb).
2287
+ count_name: Whether to include message names in the count.
2288
+ tokens_per_image: Fixed token cost per image (default: 85, aligned with
2289
+ OpenAI's low-resolution image token cost).
2290
+ use_usage_metadata_scaling: If True, and all AI messages have consistent
2291
+ `response_metadata['model_provider']`, scale the approximate token count
2292
+ using the **most recent** AI message that has
2293
+ `usage_metadata['total_tokens']`. The scaling factor is:
2294
+ `AI_total_tokens / approx_tokens_up_to_that_AI_message`
2295
+ tools: List of tools to include in the token count. Each tool can be a
2296
+ `BaseTool` instance, a dict representing a tool schema, or a plain
2297
+ callable. `BaseTool` instances and callables are converted to
2298
+ OpenAI tool format before counting.
2299
+
2300
+ Returns:
2301
+ Approximate number of tokens in the messages (and tools, if provided).
2302
+
2303
+ Note:
2304
+ This is a simple approximation that may not match the exact token count used by
2305
+ specific models. For accurate counts, use model-specific tokenizers.
2306
+
2307
+ For multimodal messages containing images, a fixed token penalty is applied
2308
+ per image instead of counting base64-encoded characters, which provides a
2309
+ more realistic approximation.
2310
+
2311
+ !!! version-added "Added in `trustcoco-core` 0.3.46"
2312
+ """
2313
+ converted_messages = convert_to_messages(messages)
2314
+
2315
+ token_count = 0.0
2316
+
2317
+ ai_model_provider: str | None = None
2318
+ invalid_model_provider = False
2319
+ last_ai_total_tokens: int | None = None
2320
+ approx_at_last_ai: float | None = None
2321
+
2322
+ # Count tokens for tools if provided
2323
+ if tools:
2324
+ tools_chars = 0
2325
+ for tool in tools:
2326
+ if isinstance(tool, dict):
2327
+ tool_dict = tool
2328
+ else:
2329
+ # tool_call_schema is memoized per instance
2330
+ schema = tool.tool_call_schema
2331
+ if isinstance(schema, dict):
2332
+ parameters = dict(schema)
2333
+ else:
2334
+ parameters = dict(get_model_json_schema(schema))
2335
+ # Drop the schema's own `title`/`description` to avoid double-counting:
2336
+ # they're duplicated at the top level.
2337
+ parameters.pop("title", None)
2338
+ parameters.pop("description", None)
2339
+ tool_dict = {
2340
+ "name": tool.name,
2341
+ "description": tool.description,
2342
+ "parameters": parameters,
2343
+ }
2344
+ tools_chars += len(json.dumps(tool_dict))
2345
+ token_count += math.ceil(tools_chars / chars_per_token)
2346
+
2347
+ for message in converted_messages:
2348
+ message_chars = 0
2349
+
2350
+ if isinstance(message.content, str):
2351
+ message_chars += len(message.content)
2352
+ # Handle multimodal content (list of content blocks)
2353
+ elif isinstance(message.content, list):
2354
+ for block in message.content:
2355
+ if isinstance(block, str):
2356
+ # String block
2357
+ message_chars += len(block)
2358
+ elif isinstance(block, dict):
2359
+ block_type = block.get("type", "")
2360
+
2361
+ # Apply fixed penalty for image blocks
2362
+ if block_type in {"image", "image_url"}:
2363
+ token_count += tokens_per_image
2364
+ # Count text blocks normally
2365
+ elif block_type == "text":
2366
+ text = block.get("text", "")
2367
+ message_chars += len(text)
2368
+ # Conservative estimate for unknown block types
2369
+ else:
2370
+ message_chars += len(repr(block))
2371
+ else:
2372
+ # Fallback for unexpected block types
2373
+ message_chars += len(repr(block)) # type: ignore[unreachable]
2374
+ else:
2375
+ # Fallback for other content types
2376
+ content = repr(message.content) # type: ignore[unreachable]
2377
+ message_chars += len(content)
2378
+
2379
+ if (
2380
+ isinstance(message, AIMessage)
2381
+ # exclude Anthropic format as tool calls are already included in the content
2382
+ and not isinstance(message.content, list)
2383
+ and message.tool_calls
2384
+ ):
2385
+ tool_calls_content = repr(message.tool_calls)
2386
+ message_chars += len(tool_calls_content)
2387
+
2388
+ if isinstance(message, ToolMessage):
2389
+ message_chars += len(message.tool_call_id)
2390
+
2391
+ role = _get_message_openai_role(message)
2392
+ message_chars += len(role)
2393
+
2394
+ if message.name and count_name:
2395
+ message_chars += len(message.name)
2396
+
2397
+ # NOTE: we're rounding up per message to ensure that
2398
+ # individual message token counts add up to the total count
2399
+ # for a list of messages
2400
+ token_count += math.ceil(message_chars / chars_per_token)
2401
+
2402
+ # add extra tokens per message
2403
+ token_count += extra_tokens_per_message
2404
+
2405
+ if use_usage_metadata_scaling and isinstance(message, AIMessage):
2406
+ model_provider = message.response_metadata.get("model_provider")
2407
+ if ai_model_provider is None:
2408
+ ai_model_provider = model_provider
2409
+ elif model_provider != ai_model_provider:
2410
+ invalid_model_provider = True
2411
+
2412
+ if message.usage_metadata and isinstance(
2413
+ (total_tokens := message.usage_metadata.get("total_tokens")), int
2414
+ ):
2415
+ last_ai_total_tokens = total_tokens
2416
+ approx_at_last_ai = token_count
2417
+
2418
+ if (
2419
+ use_usage_metadata_scaling
2420
+ and len(converted_messages) > 1
2421
+ and not invalid_model_provider
2422
+ and ai_model_provider is not None
2423
+ and last_ai_total_tokens is not None
2424
+ and approx_at_last_ai
2425
+ and approx_at_last_ai > 0
2426
+ ):
2427
+ scale_factor = last_ai_total_tokens / approx_at_last_ai
2428
+ token_count *= min(1.25, max(1.0, scale_factor))
2429
+
2430
+ # round up once more time in case extra_tokens_per_message is a float
2431
+ return math.ceil(token_count)
2432
+
2433
+
2434
+ # Mapping from string shortcuts to token counter functions
2435
+ def _approximate_token_counter(messages: Sequence[BaseMessage]) -> int:
2436
+ """Wrapper for `count_tokens_approximately` that matches expected signature."""
2437
+ return count_tokens_approximately(messages)
2438
+
2439
+
2440
+ _TOKEN_COUNTER_SHORTCUTS = {
2441
+ "approximate": _approximate_token_counter,
2442
+ }