@radheim/ai 0.0.0-stage → 2.4.3

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 (560) hide show
  1. package/README.md +1890 -3
  2. package/dist/ai.d.ts +36 -0
  3. package/dist/ai.js +46 -0
  4. package/dist/cache-policy.d.ts +6 -0
  5. package/dist/cache-policy.js +205 -0
  6. package/dist/decision-client.d.ts +10 -0
  7. package/dist/decision-client.js +42 -0
  8. package/dist/decision.d.ts +378 -0
  9. package/dist/decision.js +171 -0
  10. package/dist/effect.d.ts +59 -0
  11. package/dist/effect.js +33 -0
  12. package/dist/effort-updates.d.ts +12 -0
  13. package/dist/effort-updates.js +23 -0
  14. package/dist/embedding-client.d.ts +10 -0
  15. package/dist/embedding-client.js +17 -0
  16. package/dist/embedding.d.ts +113 -0
  17. package/dist/embedding.js +76 -0
  18. package/dist/experimental/cloudflare-run-extraction.d.ts +17 -0
  19. package/dist/experimental/cloudflare-run-extraction.js +85 -0
  20. package/dist/experimental/extraction.d.ts +153 -0
  21. package/dist/experimental/extraction.js +103 -0
  22. package/dist/experimental/realtime.d.ts +80 -0
  23. package/dist/experimental/realtime.js +96 -0
  24. package/dist/experimental.d.ts +10 -0
  25. package/dist/experimental.js +6 -0
  26. package/dist/fetch-middleware.d.ts +7 -0
  27. package/dist/fetch-middleware.js +41 -0
  28. package/dist/generation.d.ts +77 -0
  29. package/dist/generation.js +109 -0
  30. package/dist/image-client.d.ts +14 -0
  31. package/dist/image-client.js +39 -0
  32. package/dist/image.d.ts +323 -0
  33. package/dist/image.js +103 -0
  34. package/dist/index.d.ts +300 -0
  35. package/dist/index.js +179 -0
  36. package/dist/llm.d.ts +109 -0
  37. package/dist/llm.js +177 -0
  38. package/dist/loop.d.ts +38 -0
  39. package/dist/loop.js +139 -0
  40. package/dist/media-client.d.ts +30 -0
  41. package/dist/media-client.js +44 -0
  42. package/dist/media-model.d.ts +49 -0
  43. package/dist/media-model.js +55 -0
  44. package/dist/media.d.ts +237 -0
  45. package/dist/media.js +285 -0
  46. package/dist/promise-media.d.ts +20 -0
  47. package/dist/promise-media.js +16 -0
  48. package/dist/protocols/alibaba-chat.d.ts +315 -0
  49. package/dist/protocols/alibaba-chat.js +78 -0
  50. package/dist/protocols/alibaba-images.d.ts +22 -0
  51. package/dist/protocols/alibaba-images.js +77 -0
  52. package/dist/protocols/alibaba-messages.d.ts +413 -0
  53. package/dist/protocols/alibaba-messages.js +44 -0
  54. package/dist/protocols/alibaba-responses.d.ts +298 -0
  55. package/dist/protocols/alibaba-responses.js +67 -0
  56. package/dist/protocols/anthropic-messages.d.ts +1213 -0
  57. package/dist/protocols/anthropic-messages.js +1412 -0
  58. package/dist/protocols/assemblyai-transcription.d.ts +41 -0
  59. package/dist/protocols/assemblyai-transcription.js +137 -0
  60. package/dist/protocols/bedrock-converse.d.ts +548 -0
  61. package/dist/protocols/bedrock-converse.js +801 -0
  62. package/dist/protocols/bedrock-event-stream.d.ts +14 -0
  63. package/dist/protocols/bedrock-event-stream.js +100 -0
  64. package/dist/protocols/cartesia-speech.d.ts +117 -0
  65. package/dist/protocols/cartesia-speech.js +120 -0
  66. package/dist/protocols/cloudflare-run-decisions.d.ts +9 -0
  67. package/dist/protocols/cloudflare-run-decisions.js +36 -0
  68. package/dist/protocols/cloudflare-workers-ai-images.d.ts +23 -0
  69. package/dist/protocols/cloudflare-workers-ai-images.js +80 -0
  70. package/dist/protocols/cohere-chat.d.ts +184 -0
  71. package/dist/protocols/cohere-chat.js +317 -0
  72. package/dist/protocols/deepgram-speech.d.ts +109 -0
  73. package/dist/protocols/deepgram-speech.js +93 -0
  74. package/dist/protocols/deepgram-transcription.d.ts +26 -0
  75. package/dist/protocols/deepgram-transcription.js +119 -0
  76. package/dist/protocols/elevenlabs-speech.d.ts +112 -0
  77. package/dist/protocols/elevenlabs-speech.js +111 -0
  78. package/dist/protocols/elevenlabs-transcription.d.ts +28 -0
  79. package/dist/protocols/elevenlabs-transcription.js +137 -0
  80. package/dist/protocols/gemini.d.ts +388 -0
  81. package/dist/protocols/gemini.js +741 -0
  82. package/dist/protocols/google-decisions.d.ts +13 -0
  83. package/dist/protocols/google-decisions.js +133 -0
  84. package/dist/protocols/google-embed-content.d.ts +34 -0
  85. package/dist/protocols/google-embed-content.js +110 -0
  86. package/dist/protocols/google-images.d.ts +18 -0
  87. package/dist/protocols/google-images.js +169 -0
  88. package/dist/protocols/google-interactions-video.d.ts +38 -0
  89. package/dist/protocols/google-interactions-video.js +185 -0
  90. package/dist/protocols/google-interactions.d.ts +554 -0
  91. package/dist/protocols/google-interactions.js +756 -0
  92. package/dist/protocols/google-speech.d.ts +120 -0
  93. package/dist/protocols/google-speech.js +94 -0
  94. package/dist/protocols/google-transcription.d.ts +148 -0
  95. package/dist/protocols/google-transcription.js +129 -0
  96. package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
  97. package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
  98. package/dist/protocols/index.d.ts +21 -0
  99. package/dist/protocols/index.js +21 -0
  100. package/dist/protocols/meta-images.d.ts +26 -0
  101. package/dist/protocols/meta-images.js +101 -0
  102. package/dist/protocols/meta-messages.d.ts +423 -0
  103. package/dist/protocols/meta-messages.js +63 -0
  104. package/dist/protocols/meta-responses.d.ts +533 -0
  105. package/dist/protocols/meta-responses.js +189 -0
  106. package/dist/protocols/minimax-images.d.ts +25 -0
  107. package/dist/protocols/minimax-images.js +150 -0
  108. package/dist/protocols/minimax-video.d.ts +45 -0
  109. package/dist/protocols/minimax-video.js +296 -0
  110. package/dist/protocols/mistral-chat.d.ts +565 -0
  111. package/dist/protocols/mistral-chat.js +606 -0
  112. package/dist/protocols/open-responses-channel.d.ts +25 -0
  113. package/dist/protocols/open-responses-channel.js +137 -0
  114. package/dist/protocols/open-responses-continuation.d.ts +18 -0
  115. package/dist/protocols/open-responses-continuation.js +172 -0
  116. package/dist/protocols/open-responses.d.ts +2509 -0
  117. package/dist/protocols/open-responses.js +1335 -0
  118. package/dist/protocols/openai-chat.d.ts +2571 -0
  119. package/dist/protocols/openai-chat.js +1140 -0
  120. package/dist/protocols/openai-compatible-chat.d.ts +184 -0
  121. package/dist/protocols/openai-compatible-chat.js +19 -0
  122. package/dist/protocols/openai-compatible-responses.d.ts +231 -0
  123. package/dist/protocols/openai-compatible-responses.js +18 -0
  124. package/dist/protocols/openai-decisions.d.ts +22 -0
  125. package/dist/protocols/openai-decisions.js +141 -0
  126. package/dist/protocols/openai-embeddings.d.ts +16 -0
  127. package/dist/protocols/openai-embeddings.js +76 -0
  128. package/dist/protocols/openai-freeform.d.ts +78 -0
  129. package/dist/protocols/openai-freeform.js +222 -0
  130. package/dist/protocols/openai-images.d.ts +148 -0
  131. package/dist/protocols/openai-images.js +303 -0
  132. package/dist/protocols/openai-responses.d.ts +1600 -0
  133. package/dist/protocols/openai-responses.js +360 -0
  134. package/dist/protocols/openai-speech.d.ts +110 -0
  135. package/dist/protocols/openai-speech.js +112 -0
  136. package/dist/protocols/openai-transcription.d.ts +185 -0
  137. package/dist/protocols/openai-transcription.js +206 -0
  138. package/dist/protocols/openrouter-video.d.ts +36 -0
  139. package/dist/protocols/openrouter-video.js +139 -0
  140. package/dist/protocols/seedance-video.d.ts +45 -0
  141. package/dist/protocols/seedance-video.js +217 -0
  142. package/dist/protocols/shared.d.ts +249 -0
  143. package/dist/protocols/shared.js +446 -0
  144. package/dist/protocols/system-one.d.ts +145 -0
  145. package/dist/protocols/system-one.js +272 -0
  146. package/dist/protocols/utils/bedrock-auth.d.ts +60 -0
  147. package/dist/protocols/utils/bedrock-auth.js +86 -0
  148. package/dist/protocols/utils/bedrock-cache.d.ts +19 -0
  149. package/dist/protocols/utils/bedrock-cache.js +49 -0
  150. package/dist/protocols/utils/bedrock-media.d.ts +53 -0
  151. package/dist/protocols/utils/bedrock-media.js +98 -0
  152. package/dist/protocols/utils/cache.d.ts +25 -0
  153. package/dist/protocols/utils/cache.js +33 -0
  154. package/dist/protocols/utils/claude-model.d.ts +8 -0
  155. package/dist/protocols/utils/claude-model.js +15 -0
  156. package/dist/protocols/utils/gateway-protocol.d.ts +17 -0
  157. package/dist/protocols/utils/gateway-protocol.js +59 -0
  158. package/dist/protocols/utils/gemini-generate-content.d.ts +75 -0
  159. package/dist/protocols/utils/gemini-generate-content.js +96 -0
  160. package/dist/protocols/utils/gemini-json-schema.d.ts +8 -0
  161. package/dist/protocols/utils/gemini-json-schema.js +76 -0
  162. package/dist/protocols/utils/image-sizing.d.ts +31 -0
  163. package/dist/protocols/utils/image-sizing.js +73 -0
  164. package/dist/protocols/utils/lifecycle.d.ts +24 -0
  165. package/dist/protocols/utils/lifecycle.js +62 -0
  166. package/dist/protocols/utils/media-input.d.ts +32 -0
  167. package/dist/protocols/utils/media-input.js +62 -0
  168. package/dist/protocols/utils/mistral-tool-id.d.ts +5 -0
  169. package/dist/protocols/utils/mistral-tool-id.js +31 -0
  170. package/dist/protocols/utils/open-responses-options.d.ts +54 -0
  171. package/dist/protocols/utils/open-responses-options.js +59 -0
  172. package/dist/protocols/utils/partial-json-options.d.ts +61 -0
  173. package/dist/protocols/utils/partial-json-options.js +51 -0
  174. package/dist/protocols/utils/partial-json.d.ts +8 -0
  175. package/dist/protocols/utils/partial-json.js +280 -0
  176. package/dist/protocols/utils/responses-checkpoint.d.ts +4 -0
  177. package/dist/protocols/utils/responses-checkpoint.js +103 -0
  178. package/dist/protocols/utils/responses-compaction.d.ts +6 -0
  179. package/dist/protocols/utils/responses-compaction.js +162 -0
  180. package/dist/protocols/utils/responses-hosted-tools.d.ts +122 -0
  181. package/dist/protocols/utils/responses-hosted-tools.js +63 -0
  182. package/dist/protocols/utils/speaker-turns.d.ts +3 -0
  183. package/dist/protocols/utils/speaker-turns.js +9 -0
  184. package/dist/protocols/utils/speech-stream.d.ts +49 -0
  185. package/dist/protocols/utils/speech-stream.js +64 -0
  186. package/dist/protocols/utils/tool-schema.d.ts +10 -0
  187. package/dist/protocols/utils/tool-schema.js +109 -0
  188. package/dist/protocols/utils/tool-stream.d.ts +478 -0
  189. package/dist/protocols/utils/tool-stream.js +153 -0
  190. package/dist/protocols/venice-chat.d.ts +340 -0
  191. package/dist/protocols/venice-chat.js +283 -0
  192. package/dist/protocols/xai-images.d.ts +25 -0
  193. package/dist/protocols/xai-images.js +87 -0
  194. package/dist/protocols/xai-responses.d.ts +294 -0
  195. package/dist/protocols/xai-responses.js +86 -0
  196. package/dist/protocols/xai-video.d.ts +35 -0
  197. package/dist/protocols/xai-video.js +159 -0
  198. package/dist/protocols/zai-chat.d.ts +296 -0
  199. package/dist/protocols/zai-chat.js +56 -0
  200. package/dist/protocols/zai-images.d.ts +20 -0
  201. package/dist/protocols/zai-images.js +79 -0
  202. package/dist/protocols/zai-messages.d.ts +409 -0
  203. package/dist/protocols/zai-messages.js +30 -0
  204. package/dist/protocols.d.ts +1 -0
  205. package/dist/protocols.js +1 -0
  206. package/dist/provider-error.d.ts +22 -0
  207. package/dist/provider-error.js +228 -0
  208. package/dist/provider-package.d.ts +17 -0
  209. package/dist/provider-package.js +1 -0
  210. package/dist/providers/alibaba/chat.d.ts +1 -0
  211. package/dist/providers/alibaba/chat.js +1 -0
  212. package/dist/providers/alibaba/embeddings.d.ts +2 -0
  213. package/dist/providers/alibaba/embeddings.js +1 -0
  214. package/dist/providers/alibaba/images.d.ts +2 -0
  215. package/dist/providers/alibaba/images.js +1 -0
  216. package/dist/providers/alibaba/messages.d.ts +3 -0
  217. package/dist/providers/alibaba/messages.js +1 -0
  218. package/dist/providers/alibaba/responses.d.ts +3 -0
  219. package/dist/providers/alibaba/responses.js +1 -0
  220. package/dist/providers/alibaba.d.ts +905 -0
  221. package/dist/providers/alibaba.js +119 -0
  222. package/dist/providers/amazon-bedrock/mantle/chat.d.ts +2 -0
  223. package/dist/providers/amazon-bedrock/mantle/chat.js +1 -0
  224. package/dist/providers/amazon-bedrock/mantle/messages.d.ts +2 -0
  225. package/dist/providers/amazon-bedrock/mantle/messages.js +1 -0
  226. package/dist/providers/amazon-bedrock/mantle/responses.d.ts +2 -0
  227. package/dist/providers/amazon-bedrock/mantle/responses.js +1 -0
  228. package/dist/providers/amazon-bedrock/mantle.d.ts +2 -0
  229. package/dist/providers/amazon-bedrock/mantle.js +1 -0
  230. package/dist/providers/amazon-bedrock-mantle.d.ts +789 -0
  231. package/dist/providers/amazon-bedrock-mantle.js +107 -0
  232. package/dist/providers/amazon-bedrock.d.ts +190 -0
  233. package/dist/providers/amazon-bedrock.js +44 -0
  234. package/dist/providers/anthropic-compatible.d.ts +364 -0
  235. package/dist/providers/anthropic-compatible.js +47 -0
  236. package/dist/providers/anthropic.d.ts +362 -0
  237. package/dist/providers/anthropic.js +36 -0
  238. package/dist/providers/assemblyai.d.ts +19 -0
  239. package/dist/providers/assemblyai.js +19 -0
  240. package/dist/providers/azure/chat.d.ts +2 -0
  241. package/dist/providers/azure/chat.js +1 -0
  242. package/dist/providers/azure/embeddings.d.ts +2 -0
  243. package/dist/providers/azure/embeddings.js +1 -0
  244. package/dist/providers/azure/images.d.ts +2 -0
  245. package/dist/providers/azure/images.js +1 -0
  246. package/dist/providers/azure/messages.d.ts +2 -0
  247. package/dist/providers/azure/messages.js +1 -0
  248. package/dist/providers/azure/responses.d.ts +2 -0
  249. package/dist/providers/azure/responses.js +1 -0
  250. package/dist/providers/azure.d.ts +1074 -0
  251. package/dist/providers/azure.js +150 -0
  252. package/dist/providers/baseten/decisions.d.ts +2 -0
  253. package/dist/providers/baseten/decisions.js +1 -0
  254. package/dist/providers/baseten.d.ts +384 -0
  255. package/dist/providers/baseten.js +56 -0
  256. package/dist/providers/byteplus/videos.d.ts +2 -0
  257. package/dist/providers/byteplus/videos.js +1 -0
  258. package/dist/providers/byteplus.d.ts +24 -0
  259. package/dist/providers/byteplus.js +21 -0
  260. package/dist/providers/cartesia.d.ts +18 -0
  261. package/dist/providers/cartesia.js +17 -0
  262. package/dist/providers/cerebras.d.ts +375 -0
  263. package/dist/providers/cerebras.js +33 -0
  264. package/dist/providers/cloudflare-ai-gateway/decisions.d.ts +2 -0
  265. package/dist/providers/cloudflare-ai-gateway/decisions.js +1 -0
  266. package/dist/providers/cloudflare-ai-gateway.d.ts +1581 -0
  267. package/dist/providers/cloudflare-ai-gateway.js +120 -0
  268. package/dist/providers/cloudflare-shared.d.ts +9 -0
  269. package/dist/providers/cloudflare-shared.js +25 -0
  270. package/dist/providers/cloudflare-workers-ai/decisions.d.ts +2 -0
  271. package/dist/providers/cloudflare-workers-ai/decisions.js +1 -0
  272. package/dist/providers/cloudflare-workers-ai/images.d.ts +2 -0
  273. package/dist/providers/cloudflare-workers-ai/images.js +1 -0
  274. package/dist/providers/cloudflare-workers-ai.d.ts +391 -0
  275. package/dist/providers/cloudflare-workers-ai.js +69 -0
  276. package/dist/providers/cohere/chat.d.ts +4 -0
  277. package/dist/providers/cohere/chat.js +3 -0
  278. package/dist/providers/cohere/embeddings.d.ts +2 -0
  279. package/dist/providers/cohere/embeddings.js +1 -0
  280. package/dist/providers/cohere.d.ts +502 -0
  281. package/dist/providers/cohere.js +55 -0
  282. package/dist/providers/deepgram.d.ts +22 -0
  283. package/dist/providers/deepgram.js +20 -0
  284. package/dist/providers/deepinfra/embeddings.d.ts +2 -0
  285. package/dist/providers/deepinfra/embeddings.js +1 -0
  286. package/dist/providers/deepinfra.d.ts +378 -0
  287. package/dist/providers/deepinfra.js +52 -0
  288. package/dist/providers/deepseek.d.ts +376 -0
  289. package/dist/providers/deepseek.js +30 -0
  290. package/dist/providers/digitalocean/decisions.d.ts +2 -0
  291. package/dist/providers/digitalocean/decisions.js +1 -0
  292. package/dist/providers/digitalocean/embeddings.d.ts +2 -0
  293. package/dist/providers/digitalocean/embeddings.js +1 -0
  294. package/dist/providers/digitalocean/images.d.ts +2 -0
  295. package/dist/providers/digitalocean/images.js +1 -0
  296. package/dist/providers/digitalocean/responses.d.ts +4 -0
  297. package/dist/providers/digitalocean/responses.js +1 -0
  298. package/dist/providers/digitalocean.d.ts +874 -0
  299. package/dist/providers/digitalocean.js +106 -0
  300. package/dist/providers/elevenlabs.d.ts +22 -0
  301. package/dist/providers/elevenlabs.js +22 -0
  302. package/dist/providers/fireworks/embeddings.d.ts +2 -0
  303. package/dist/providers/fireworks/embeddings.js +1 -0
  304. package/dist/providers/fireworks.d.ts +379 -0
  305. package/dist/providers/fireworks.js +40 -0
  306. package/dist/providers/google/decisions.d.ts +2 -0
  307. package/dist/providers/google/decisions.js +1 -0
  308. package/dist/providers/google/embeddings.d.ts +2 -0
  309. package/dist/providers/google/embeddings.js +1 -0
  310. package/dist/providers/google/images.d.ts +2 -0
  311. package/dist/providers/google/images.js +1 -0
  312. package/dist/providers/google/interactions.d.ts +7 -0
  313. package/dist/providers/google/interactions.js +3 -0
  314. package/dist/providers/google/videos.d.ts +2 -0
  315. package/dist/providers/google/videos.js +1 -0
  316. package/dist/providers/google-vertex/chat.d.ts +2 -0
  317. package/dist/providers/google-vertex/chat.js +1 -0
  318. package/dist/providers/google-vertex/embeddings.d.ts +2 -0
  319. package/dist/providers/google-vertex/embeddings.js +1 -0
  320. package/dist/providers/google-vertex/gemini.d.ts +2 -0
  321. package/dist/providers/google-vertex/gemini.js +1 -0
  322. package/dist/providers/google-vertex/images.d.ts +2 -0
  323. package/dist/providers/google-vertex/images.js +1 -0
  324. package/dist/providers/google-vertex/interactions.d.ts +2 -0
  325. package/dist/providers/google-vertex/interactions.js +1 -0
  326. package/dist/providers/google-vertex/messages.d.ts +2 -0
  327. package/dist/providers/google-vertex/messages.js +1 -0
  328. package/dist/providers/google-vertex/mistral.d.ts +2 -0
  329. package/dist/providers/google-vertex/mistral.js +1 -0
  330. package/dist/providers/google-vertex/responses.d.ts +2 -0
  331. package/dist/providers/google-vertex/responses.js +1 -0
  332. package/dist/providers/google-vertex-chat.d.ts +204 -0
  333. package/dist/providers/google-vertex-chat.js +29 -0
  334. package/dist/providers/google-vertex-interactions.d.ts +111 -0
  335. package/dist/providers/google-vertex-interactions.js +62 -0
  336. package/dist/providers/google-vertex-messages.d.ts +362 -0
  337. package/dist/providers/google-vertex-messages.js +51 -0
  338. package/dist/providers/google-vertex-mistral.d.ts +120 -0
  339. package/dist/providers/google-vertex-mistral.js +43 -0
  340. package/dist/providers/google-vertex-responses.d.ts +253 -0
  341. package/dist/providers/google-vertex-responses.js +30 -0
  342. package/dist/providers/google-vertex-shared.d.ts +58 -0
  343. package/dist/providers/google-vertex-shared.js +128 -0
  344. package/dist/providers/google-vertex.d.ts +132 -0
  345. package/dist/providers/google-vertex.js +161 -0
  346. package/dist/providers/google.d.ts +246 -0
  347. package/dist/providers/google.js +80 -0
  348. package/dist/providers/groq.d.ts +470 -0
  349. package/dist/providers/groq.js +63 -0
  350. package/dist/providers/index.d.ts +45 -0
  351. package/dist/providers/index.js +45 -0
  352. package/dist/providers/meta/chat.d.ts +2 -0
  353. package/dist/providers/meta/chat.js +1 -0
  354. package/dist/providers/meta/images.d.ts +2 -0
  355. package/dist/providers/meta/images.js +1 -0
  356. package/dist/providers/meta/messages.d.ts +2 -0
  357. package/dist/providers/meta/messages.js +1 -0
  358. package/dist/providers/meta/responses.d.ts +2 -0
  359. package/dist/providers/meta/responses.js +1 -0
  360. package/dist/providers/meta.d.ts +804 -0
  361. package/dist/providers/meta.js +96 -0
  362. package/dist/providers/minimax/chat.d.ts +4 -0
  363. package/dist/providers/minimax/chat.js +3 -0
  364. package/dist/providers/minimax/images.d.ts +3 -0
  365. package/dist/providers/minimax/images.js +1 -0
  366. package/dist/providers/minimax/messages.d.ts +1 -0
  367. package/dist/providers/minimax/messages.js +1 -0
  368. package/dist/providers/minimax/responses.d.ts +4 -0
  369. package/dist/providers/minimax/responses.js +3 -0
  370. package/dist/providers/minimax/videos.d.ts +3 -0
  371. package/dist/providers/minimax/videos.js +1 -0
  372. package/dist/providers/minimax.d.ts +798 -0
  373. package/dist/providers/minimax.js +99 -0
  374. package/dist/providers/mistral.d.ts +208 -0
  375. package/dist/providers/mistral.js +17 -0
  376. package/dist/providers/moonshot/chat.d.ts +1 -0
  377. package/dist/providers/moonshot/chat.js +1 -0
  378. package/dist/providers/moonshot/messages.d.ts +4 -0
  379. package/dist/providers/moonshot/messages.js +3 -0
  380. package/dist/providers/moonshot/responses.d.ts +4 -0
  381. package/dist/providers/moonshot/responses.js +3 -0
  382. package/dist/providers/moonshot.d.ts +785 -0
  383. package/dist/providers/moonshot.js +78 -0
  384. package/dist/providers/open-responses-options.d.ts +5 -0
  385. package/dist/providers/open-responses-options.js +1 -0
  386. package/dist/providers/openai/chat.d.ts +2 -0
  387. package/dist/providers/openai/chat.js +1 -0
  388. package/dist/providers/openai/embeddings.d.ts +2 -0
  389. package/dist/providers/openai/embeddings.js +1 -0
  390. package/dist/providers/openai/images.d.ts +2 -0
  391. package/dist/providers/openai/images.js +1 -0
  392. package/dist/providers/openai/responses.d.ts +2 -0
  393. package/dist/providers/openai/responses.js +1 -0
  394. package/dist/providers/openai-compatible/decisions.d.ts +2 -0
  395. package/dist/providers/openai-compatible/decisions.js +1 -0
  396. package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
  397. package/dist/providers/openai-compatible/embeddings.js +1 -0
  398. package/dist/providers/openai-compatible/images.d.ts +2 -0
  399. package/dist/providers/openai-compatible/images.js +1 -0
  400. package/dist/providers/openai-compatible/responses.d.ts +1 -0
  401. package/dist/providers/openai-compatible/responses.js +1 -0
  402. package/dist/providers/openai-compatible-responses.d.ts +250 -0
  403. package/dist/providers/openai-compatible-responses.js +26 -0
  404. package/dist/providers/openai-compatible.d.ts +208 -0
  405. package/dist/providers/openai-compatible.js +71 -0
  406. package/dist/providers/openai-options.d.ts +21 -0
  407. package/dist/providers/openai-options.js +37 -0
  408. package/dist/providers/openai.d.ts +522 -0
  409. package/dist/providers/openai.js +118 -0
  410. package/dist/providers/opencode/decisions.d.ts +2 -0
  411. package/dist/providers/opencode/decisions.js +1 -0
  412. package/dist/providers/opencode.d.ts +23 -0
  413. package/dist/providers/opencode.js +25 -0
  414. package/dist/providers/openrouter/decisions.d.ts +2 -0
  415. package/dist/providers/openrouter/decisions.js +1 -0
  416. package/dist/providers/openrouter/embeddings.d.ts +2 -0
  417. package/dist/providers/openrouter/embeddings.js +1 -0
  418. package/dist/providers/openrouter/images.d.ts +2 -0
  419. package/dist/providers/openrouter/images.js +1 -0
  420. package/dist/providers/openrouter/responses.d.ts +3 -0
  421. package/dist/providers/openrouter/responses.js +1 -0
  422. package/dist/providers/openrouter/videos.d.ts +2 -0
  423. package/dist/providers/openrouter/videos.js +1 -0
  424. package/dist/providers/openrouter.d.ts +1204 -0
  425. package/dist/providers/openrouter.js +210 -0
  426. package/dist/providers/settings.d.ts +40 -0
  427. package/dist/providers/settings.js +18 -0
  428. package/dist/providers/togetherai.d.ts +375 -0
  429. package/dist/providers/togetherai.js +30 -0
  430. package/dist/providers/typesafe-ai/decisions.d.ts +2 -0
  431. package/dist/providers/typesafe-ai/decisions.js +1 -0
  432. package/dist/providers/typesafe-ai.d.ts +23 -0
  433. package/dist/providers/typesafe-ai.js +25 -0
  434. package/dist/providers/venice/responses.d.ts +4 -0
  435. package/dist/providers/venice/responses.js +1 -0
  436. package/dist/providers/venice.d.ts +632 -0
  437. package/dist/providers/venice.js +57 -0
  438. package/dist/providers/vercel-ai-gateway/chat.d.ts +2 -0
  439. package/dist/providers/vercel-ai-gateway/chat.js +1 -0
  440. package/dist/providers/vercel-ai-gateway/decisions.d.ts +2 -0
  441. package/dist/providers/vercel-ai-gateway/decisions.js +1 -0
  442. package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
  443. package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
  444. package/dist/providers/vercel-ai-gateway/images.d.ts +2 -0
  445. package/dist/providers/vercel-ai-gateway/images.js +1 -0
  446. package/dist/providers/vercel-ai-gateway/messages.d.ts +2 -0
  447. package/dist/providers/vercel-ai-gateway/messages.js +1 -0
  448. package/dist/providers/vercel-ai-gateway/responses.d.ts +2 -0
  449. package/dist/providers/vercel-ai-gateway/responses.js +1 -0
  450. package/dist/providers/vercel-ai-gateway.d.ts +111 -0
  451. package/dist/providers/vercel-ai-gateway.js +181 -0
  452. package/dist/providers/volcengine/videos.d.ts +2 -0
  453. package/dist/providers/volcengine/videos.js +1 -0
  454. package/dist/providers/volcengine.d.ts +24 -0
  455. package/dist/providers/volcengine.js +21 -0
  456. package/dist/providers/xai/images.d.ts +2 -0
  457. package/dist/providers/xai/images.js +1 -0
  458. package/dist/providers/xai/videos.d.ts +2 -0
  459. package/dist/providers/xai/videos.js +1 -0
  460. package/dist/providers/xai.d.ts +235 -0
  461. package/dist/providers/xai.js +89 -0
  462. package/dist/providers/zai/chat.d.ts +1 -0
  463. package/dist/providers/zai/chat.js +1 -0
  464. package/dist/providers/zai/images.d.ts +2 -0
  465. package/dist/providers/zai/images.js +1 -0
  466. package/dist/providers/zai-coding-plan/chat.d.ts +1 -0
  467. package/dist/providers/zai-coding-plan/chat.js +1 -0
  468. package/dist/providers/zai-coding-plan/messages.d.ts +4 -0
  469. package/dist/providers/zai-coding-plan/messages.js +3 -0
  470. package/dist/providers/zai-coding-plan/responses.d.ts +4 -0
  471. package/dist/providers/zai-coding-plan/responses.js +3 -0
  472. package/dist/providers/zai-coding-plan.d.ts +846 -0
  473. package/dist/providers/zai-coding-plan.js +56 -0
  474. package/dist/providers/zai.d.ts +285 -0
  475. package/dist/providers/zai.js +44 -0
  476. package/dist/providers.d.ts +1 -0
  477. package/dist/providers.js +1 -0
  478. package/dist/public.d.ts +18 -0
  479. package/dist/public.js +7 -0
  480. package/dist/route/auth-options.d.ts +35 -0
  481. package/dist/route/auth-options.js +17 -0
  482. package/dist/route/auth.d.ts +52 -0
  483. package/dist/route/auth.js +92 -0
  484. package/dist/route/client.d.ts +229 -0
  485. package/dist/route/client.js +293 -0
  486. package/dist/route/decision.d.ts +55 -0
  487. package/dist/route/decision.js +73 -0
  488. package/dist/route/embedding.d.ts +58 -0
  489. package/dist/route/embedding.js +85 -0
  490. package/dist/route/endpoint.d.ts +29 -0
  491. package/dist/route/endpoint.js +21 -0
  492. package/dist/route/executor-service.d.ts +54 -0
  493. package/dist/route/executor-service.js +115 -0
  494. package/dist/route/executor.d.ts +37 -0
  495. package/dist/route/executor.js +225 -0
  496. package/dist/route/framing.d.ts +44 -0
  497. package/dist/route/framing.js +63 -0
  498. package/dist/route/index.d.ts +21 -0
  499. package/dist/route/index.js +18 -0
  500. package/dist/route/media-protocol.d.ts +187 -0
  501. package/dist/route/media-protocol.js +117 -0
  502. package/dist/route/media.d.ts +91 -0
  503. package/dist/route/media.js +251 -0
  504. package/dist/route/protocol.d.ts +85 -0
  505. package/dist/route/protocol.js +19 -0
  506. package/dist/route/transport/http.d.ts +34 -0
  507. package/dist/route/transport/http.js +67 -0
  508. package/dist/route/transport/index.d.ts +42 -0
  509. package/dist/route/transport/index.js +4 -0
  510. package/dist/route/transport/websocket-channel.d.ts +56 -0
  511. package/dist/route/transport/websocket-channel.js +1 -0
  512. package/dist/route/transport/websocket.d.ts +32 -0
  513. package/dist/route/transport/websocket.js +315 -0
  514. package/dist/route.d.ts +1 -0
  515. package/dist/route.js +1 -0
  516. package/dist/schema/errors.d.ts +194 -0
  517. package/dist/schema/errors.js +217 -0
  518. package/dist/schema/events.d.ts +11001 -0
  519. package/dist/schema/events.js +542 -0
  520. package/dist/schema/ids.d.ts +17 -0
  521. package/dist/schema/ids.js +10 -0
  522. package/dist/schema/index.d.ts +5 -0
  523. package/dist/schema/index.js +5 -0
  524. package/dist/schema/messages.d.ts +2706 -0
  525. package/dist/schema/messages.js +344 -0
  526. package/dist/schema/options.d.ts +270 -0
  527. package/dist/schema/options.js +198 -0
  528. package/dist/speech.d.ts +266 -0
  529. package/dist/speech.js +114 -0
  530. package/dist/test-ai.d.ts +15 -0
  531. package/dist/test-ai.js +49 -0
  532. package/dist/testing.d.ts +1585 -0
  533. package/dist/testing.js +108 -0
  534. package/dist/tool-history.d.ts +2 -0
  535. package/dist/tool-history.js +91 -0
  536. package/dist/tool-runtime.d.ts +22 -0
  537. package/dist/tool-runtime.js +55 -0
  538. package/dist/tool-updates.d.ts +34 -0
  539. package/dist/tool-updates.js +93 -0
  540. package/dist/tool.d.ts +150 -0
  541. package/dist/tool.js +159 -0
  542. package/dist/transcription.d.ts +254 -0
  543. package/dist/transcription.js +119 -0
  544. package/dist/utils/bytes.d.ts +1 -0
  545. package/dist/utils/bytes.js +10 -0
  546. package/dist/utils/json.d.ts +4 -0
  547. package/dist/utils/json.js +4 -0
  548. package/dist/utils/media-type.d.ts +8 -0
  549. package/dist/utils/media-type.js +93 -0
  550. package/dist/utils/provider-codes.d.ts +3 -0
  551. package/dist/utils/provider-codes.js +41 -0
  552. package/dist/utils/record.d.ts +2 -0
  553. package/dist/utils/record.js +2 -0
  554. package/dist/utils/sanitize.d.ts +5 -0
  555. package/dist/utils/sanitize.js +31 -0
  556. package/dist/video-client.d.ts +12 -0
  557. package/dist/video-client.js +24 -0
  558. package/dist/video.d.ts +178 -0
  559. package/dist/video.js +79 -0
  560. package/package.json +648 -4
package/README.md CHANGED
@@ -1,3 +1,1890 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @radheim/ai
2
+
3
+ Schema-first APIs for text, images, video, decisions, and embeddings, built with Effect. Speech, transcription,
4
+ extraction, and realtime voice are [experimental](#experimental).
5
+
6
+ `@radheim/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file`
7
+ and `ai.write` load `node:fs/promises` on first use, so no Effect `FileSystem` is needed:
8
+
9
+ ```ts
10
+ import { ai, Message } from "@radheim/ai"
11
+ import { OpenAI } from "@radheim/ai/providers"
12
+
13
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
14
+
15
+ const input = { model: openai.responses("gpt-4o-mini"), prompt: "Say hello." }
16
+ console.log(await ai.text(input)) // just the answer's text
17
+ const response = await ai.generate(input) // { message, usage?, finish }
18
+ console.log(Message.text(response.message), response.usage?.totalTokens, response.finish.reason)
19
+ // also Message.reasoning(response.message), Message.toolCalls(response.message)
20
+ const generated = await ai.image.generate({ model: openai.image("gpt-image-2"), prompt: "A lighthouse" })
21
+ await ai.write(generated.images[0], "./lighthouse.png") // also ai.file(path), ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
22
+ for await (const event of ai.stream(ai.request(input))) {
23
+ // StreamEvent
24
+ }
25
+ ```
26
+
27
+ The Effect API lives at `@radheim/ai/effect`. Its `ai` has the same namespaces and methods, returning `Effect` or
28
+ `Stream`:
29
+
30
+ ```ts
31
+ import { Effect } from "effect"
32
+ import { ai, AI, Message } from "@radheim/ai/effect"
33
+ import { OpenAI } from "@radheim/ai/providers"
34
+
35
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
36
+
37
+ const program = Effect.gen(function* () {
38
+ const response = yield* ai.generate({
39
+ model: openai.responses("gpt-4o-mini"), // `.chat(...)` selects the Chat Completions API instead
40
+ system: "You are concise.",
41
+ prompt: "Say hello in one short sentence.",
42
+ maxTokens: 40,
43
+ })
44
+ console.log(Message.text(response.message))
45
+ })
46
+
47
+ // Every client plus the HTTP request executor; `AI.layerWith(executor)` swaps the executor.
48
+ await Effect.runPromise(program.pipe(Effect.provide(AI.fetchLayer)))
49
+ ```
50
+
51
+ Run `ai.stream(...)` instead of `generate` when you want incremental `StreamEvent`s. Both accept input or a prebuilt
52
+ `ai.request(...)`. Input takes either `prompt`, a single user message, or `messages`, the whole conversation, never
53
+ both; `system` goes with either. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
54
+ Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
55
+
56
+ ### Tool loop
57
+
58
+ `stream` runs one model call; `loop` runs the model's tool calls and calls the model again until it stops calling
59
+ tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs (an error result when
60
+ it fails). Only `loop` emits step events: each step starts with `step-start` and ends with `step-finish`, which
61
+ carries that step's reason and usage; one `finish` ends the loop, carrying the final step's reason
62
+ and the usage summed across steps. `until` is checked
63
+ after each step that has tool calls, with every step's response (`{ message, usage?, finish }`); returning `true` ends the loop without running
64
+ them. Tools are an array, sent in the order given so the provider can reuse its cached prompt prefix. Each tool has a
65
+ `name`, and two tools with the same name fail the request. Tool arguments that are not valid JSON go back to the model
66
+ as an error result so it can retry. A step that hits the output token limit ends the loop without running its tool
67
+ calls, which may be cut off. `toolChoice` takes a mode (`"auto"`, `"none"` or `"required"`) or
68
+ `{ type: "tool", name: "weather" }` to force one of the request's tools; a string is always a mode. With `tool(...)`
69
+ values the name is checked at compile time, and a name that none of the request's tools has fails before sending. A
70
+ forced `toolChoice` applies to the first step only; later steps use `auto`. `tool` takes
71
+ a plain `async` execute; a throw or rejection goes back to the model as an error result, and `signal` aborts when the
72
+ loop is interrupted.
73
+ `input` is an Effect Schema or a [Standard Schema](https://standardschema.dev) (Zod, Valibot, ArkType, ...) that
74
+ validates and types the arguments, or a raw JSON Schema object, such as an MCP tool's, whose arguments arrive as
75
+ `unknown`. An optional `output` describes the result: an Effect Schema or Standard Schema next to a typed `input`,
76
+ which also validates it, or a JSON Schema next to a raw one. `tool` from `@radheim/ai/effect` takes the same options
77
+ with an Effect execute:
78
+
79
+ ```ts
80
+ import { readFile } from "node:fs/promises"
81
+ import { Schema } from "effect"
82
+ import { ai, tool } from "@radheim/ai"
83
+
84
+ const read_file = tool({
85
+ name: "read_file",
86
+ description: "Read a UTF-8 file.",
87
+ input: Schema.Struct({ path: Schema.String }),
88
+ execute: ({ path }, { signal }) => readFile(path, { encoding: "utf8", signal }),
89
+ })
90
+
91
+ const events = ai.loop({
92
+ model,
93
+ prompt: "Summarize package.json.",
94
+ tools: [read_file],
95
+ until: ({ steps }) => steps.length >= 8,
96
+ })
97
+ for await (const event of events) {
98
+ if (event.type === "text-delta") process.stdout.write(event.text)
99
+ }
100
+ ```
101
+
102
+ A Standard Schema must also implement [Standard JSON Schema](https://standardschema.dev/json-schema), which the tool
103
+ sends to the model; `tool` throws when it doesn't. Zod 4.2+ and ArkType 2.1.28+ schemas implement it as is; wrap a
104
+ Valibot schema with `toStandardJsonSchema` from `@valibot/to-json-schema`:
105
+
106
+ ```ts
107
+ import { z } from "zod"
108
+
109
+ const weather = tool({
110
+ name: "weather",
111
+ description: "Get current weather.",
112
+ input: z.object({ city: z.string() }),
113
+ output: z.object({ temperature: z.number() }),
114
+ execute: async ({ city }) => ({ temperature: await lookup(city) }),
115
+ })
116
+ ```
117
+
118
+ The terminal `finish` carries the final assistant `message`, `usage`, and why the model stopped: `reason` (`stop`,
119
+ `length`, `tool-calls`, `content-filter`, `error` or `unknown`), an optional human-readable `detail` such as why a
120
+ content filter blocked the response, and the provider's `raw` finish reason. To skip the events, `ai.collect` folds a
121
+ stream from `stream` or `loop` into one result: the final step's `message`, `steps` (one `{ message, usage?, finish }` per call),
122
+ `messages` (each step's assistant message and its tool results, ready to append to the next request), the total
123
+ `usage`, `finish` (`{ reason, detail?, raw? }`), and `object` with `schema`.
124
+
125
+ ```ts
126
+ const result = await ai.collect(ai.loop({ model, prompt: "Summarize package.json.", tools: { read_file } }))
127
+ // Effect: const result = yield* ai.collect(ai.loop({ ... }))
128
+ console.log(Message.text(result.message), result.usage?.totalTokens)
129
+ ```
130
+
131
+ ### Freeform tools
132
+
133
+ A tool with exactly one required string parameter can set `freeform`, so the model writes that parameter as raw text
134
+ instead of JSON arguments: unconstrained `text`, or text matching a `regex` or `lark` grammar.
135
+
136
+ ```ts
137
+ const run_code = tool({
138
+ name: "run_code",
139
+ description: "Run JavaScript",
140
+ input: Schema.Struct({ code: Schema.String }),
141
+ freeform: { type: "lark", grammar: JS_GRAMMAR },
142
+ execute: ({ code }) => runCode(code),
143
+ })
144
+ ```
145
+
146
+ OpenAI Responses and Chat Completions, and every provider that reuses them, send it as a
147
+ [custom tool](https://platform.openai.com/docs/guides/function-calling#custom-tools). Other protocols send the normal
148
+ JSON tool. Only set `freeform` for models that accept custom tools in that format; nothing checks this or falls back
149
+ to JSON, so an unsupported model returns the provider's error. Calls, tool input events, results and history always
150
+ use the `{ code }` object, and past calls replay the way the tool is declared in the current request, so the same
151
+ history works with or without `freeform`.
152
+
153
+ ### Structured output
154
+
155
+ Pass `schema` to `object`, `generate`, `stream` or `loop`. The model must answer through a hidden tool call, decoded
156
+ into `object` (typed from an Effect Schema, or an unvalidated `unknown` for a raw JSON Schema object). In the returned
157
+ `message` the hidden call becomes a text part holding the answer's JSON, as a native JSON mode would have written it,
158
+ so the message can go straight into the history and later turns can refer to the answer:
159
+
160
+ ```ts
161
+ const City = Schema.Struct({ city: Schema.String })
162
+ const city = await ai.object({ model, prompt: "Pick a city.", schema: City }) // just the value
163
+ const res = await ai.generate({ model, prompt: "Pick a city.", schema: City }) // also message, usage and finish
164
+ res.object.city
165
+ ```
166
+
167
+ `stream` puts `object` on its `finish` event; `loop` runs tools first and puts it on the loop's `finish`. A
168
+ decode failure is an `AIError` whose `partial` holds the response.
169
+
170
+ ### Errors
171
+
172
+ Every failure is an `AIError`. `reason._tag` names the kind (`RateLimit`, `InvalidRequest`, `Transport`, ...), and
173
+ getters read the common fields without digging into `reason` or the raw body:
174
+
175
+ ```ts
176
+ try {
177
+ await ai.generate({ model, prompt: "Hi" })
178
+ } catch (error) {
179
+ if (!(error instanceof AIError)) throw error
180
+ error.status // HTTP status, when the failure came from a response
181
+ error.code // provider error code such as "model_not_found", when known
182
+ error.retryAfterMs // delay the provider asked for, when known
183
+ }
184
+ ```
185
+
186
+ `isRetryable` and `isContextOverflow` take any failure and say whether it is an `AIError` worth sending again, or one the
187
+ provider rejected because the request is longer than the model's context window:
188
+
189
+ ```ts
190
+ import { isContextOverflow, isRetryable } from "@radheim/ai"
191
+
192
+ isContextOverflow(error) // compact the conversation, then send it again
193
+ isRetryable(error) // send the same request again, after error.retryAfterMs when set
194
+ ```
195
+
196
+ ### Raw provider events
197
+
198
+ Set `includeRaw: true` on a request to also receive every provider frame as `{ type: "raw", data }`, in order and
199
+ before the events parsed from that frame. `data` is the parsed JSON frame, so frames this package doesn't handle yet
200
+ are visible too. Raw events are off by default, and `generate` ignores them. `RawEvent` is the event's type. Act on a
201
+ frame with a stream map:
202
+
203
+ ```ts
204
+ import { Effect, Stream } from "effect"
205
+ import { ai, AIError, ContentPolicyError } from "@radheim/ai/effect"
206
+
207
+ const flagged = (data: unknown) =>
208
+ typeof data === "object" && data !== null && "type" in data && data.type === "moderation.flagged"
209
+
210
+ const events = ai
211
+ .stream({ model, prompt: "Say hello.", includeRaw: true })
212
+ .pipe(
213
+ Stream.mapEffect((event) =>
214
+ event.type === "raw" && flagged(event.data)
215
+ ? Effect.fail(new AIError({ reason: new ContentPolicyError({ message: "Flagged by moderation" }) }))
216
+ : Effect.succeed(event),
217
+ ),
218
+ )
219
+ ```
220
+
221
+ ### Google Interactions
222
+
223
+ `Google.configure({ apiKey }).interactions(modelID)` selects the Interactions API; `.model(modelID)` still selects
224
+ GenerateContent. The package entrypoint is `@radheim/ai/providers/google/interactions`.
225
+
226
+ For Vertex AI, use `GoogleVertexInteractions.configure({ project, location: "global" }).model(modelID)` or
227
+ `@radheim/ai/providers/google-vertex/interactions`. It uses Application Default Credentials by default, accepts
228
+ an explicit `accessToken` or `auth` override, and supports Express mode with `apiKey`. Vertex metadata and raw usage
229
+ live under `providerMetadata.vertex`. The default is still full-history replay with `store: false`.
230
+
231
+ ```ts
232
+ const model = Google.configure({ apiKey }).interactions("gemini-3.8-flash")
233
+ const response =
234
+ yield *
235
+ ai.generate({
236
+ model,
237
+ prompt: "Say hello.",
238
+ providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
239
+ })
240
+ ```
241
+
242
+ Interactions supports text output, streamed function calls, native tool results, thought signatures, and multimodal
243
+ input. Full-history replay is the default (`store: false`); implicit caching works without retained interactions.
244
+ For server-side continuation, set `store: true` on the predecessor, read `interactionId` from the final event's
245
+ `providerMetadata.google`, and pass `previousInteractionId` on the next request with **only new messages**. Repeat
246
+ the system instructions and tool declarations on each request. Set `store: true` on each response you intend to
247
+ continue from. The package does not automatically select or persist continuation IDs.
248
+
249
+ Raw usage is preserved in `usage.providerMetadata.google`. `inputTokens` follows Google's top-level accounting;
250
+ `contextTokens` uses its full `raw_prompt_token` count when supplied. These can differ substantially with server-side
251
+ continuation. Explicit caches, hosted tools, and generated media are not supported by this initial protocol.
252
+
253
+ The same configured facade names image and video models (and the experimental speech and transcription models).
254
+ `ai.image.generate` resolves the provider's image route from the model and returns `Media.Asset`s with lazily decoded bytes:
255
+
256
+ ```ts
257
+ import { NodeFileSystem } from "@effect/platform-node"
258
+ import { ai, Media } from "@radheim/ai/effect"
259
+
260
+ const image = Effect.gen(function* () {
261
+ const response = yield* ai.image.generate({
262
+ model: openai.image("gpt-image-2"),
263
+ prompt: "A robot tending a rooftop garden",
264
+ aspect: "1:1",
265
+ resolution: "1K",
266
+ providerOptions: { quality: "high" }, // typed per image model
267
+ })
268
+ yield* Media.write(response.images[0], "./garden.png")
269
+ })
270
+
271
+ // `Media.file` / `Media.write` use the Effect `FileSystem` service; provide your platform's layer.
272
+ await Effect.runPromise(image.pipe(Effect.provide(AI.fetchLayer), Effect.provide(NodeFileSystem.layer)))
273
+ ```
274
+
275
+ Advanced: `AI.layer` requires `RequestExecutor.Service`. Compose it with
276
+ `Layer.provideMerge`, not `Layer.provide`: `asset.bytes()`, `Media.write`, and Gemini's `media` output parts need the
277
+ executor too, and hiding it fails type-checking with `RequestExecutorService` left in the requirements.
278
+
279
+ To share a policy such as logging across every client, wrap the executor once with `RequestExecutor.middleware`:
280
+
281
+ ```ts
282
+ import { RequestExecutor } from "@radheim/ai/route"
283
+
284
+ const logged = RequestExecutor.middleware((request, next) =>
285
+ Effect.log(`${request.method} ${request.url}`).pipe(Effect.andThen(next(request))),
286
+ )
287
+
288
+ const everything = AI.layerWith(logged) // or, from `@radheim/ai`, AI.make({ layer: logged })
289
+ ```
290
+
291
+ To hook only some calls, such as adding a per-user header, scope middleware to them. It runs on every provider request
292
+ they make, whatever the modality: submits, polls, results and cancels. Executor-wide middleware wraps it.
293
+
294
+ ```ts
295
+ // Effect: an Effect or a Stream
296
+ const signed: HttpMiddleware = (request, next) => next(HttpClientRequest.setHeader(request, "x-user", "user-1"))
297
+
298
+ const video =
299
+ yield *
300
+ Effect.gen(function* () {
301
+ const job = yield* ai.video.start({ model, prompt: "A red balloon floats up" })
302
+ return yield* ai.video.result(model, job.id)
303
+ }).pipe(RequestExecutor.withMiddleware(signed))
304
+ ```
305
+
306
+ The Promise API takes the same hook with standard fetch types as `middleware` on any call's options; a handle the call
307
+ returns keeps it. Response bodies stream through unread, and `request.signal` aborts when the call does.
308
+
309
+ ```ts
310
+ import { ai, type FetchMiddleware } from "@radheim/ai"
311
+
312
+ const signed: FetchMiddleware = async (request, next) => {
313
+ request.headers.set("x-user", "user-1")
314
+ const response = await next(request)
315
+ console.log(response.status, response.headers.get("x-request-id"))
316
+ return response
317
+ }
318
+
319
+ await ai.video.start({ model, prompt: "A red balloon floats up" }, { middleware: signed })
320
+ ```
321
+
322
+ Downloading a `url` asset never uses the caller's scoped middleware, so hooks that add credentials can't reach another
323
+ host such as a CDN or a presigned storage URL. A result URL on the provider's own origin carries the middleware of the
324
+ call that returned it (`asset.middleware`), so it downloads the same way later. Set `middleware` yourself with
325
+ `Media.url(url, { middleware })`: a `FetchMiddleware` from `@radheim/ai`, an `HttpMiddleware` from `@radheim/ai/effect`.
326
+
327
+ ```ts
328
+ import { ai, Media } from "@radheim/ai"
329
+
330
+ const asset = Media.url("https://files.example.com/report.pdf", {
331
+ middleware: (request, next) => {
332
+ request.headers.set("authorization", `Bearer ${token}`)
333
+ return next(request)
334
+ },
335
+ })
336
+ await ai.write(asset, "./report.pdf") // also ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
337
+ ```
338
+
339
+ ## Venice AI
340
+
341
+ `Venice` provides native Chat Completions with streaming tools and reasoning. `model` and `chat`
342
+ select the same API, and `responses` selects its Responses API; credentials default to `VENICE_API_KEY`.
343
+
344
+ ```ts
345
+ import { ai, Message } from "@radheim/ai/effect"
346
+ import { Venice } from "@radheim/ai/providers"
347
+ import { Effect } from "effect"
348
+
349
+ const program = Effect.gen(function* () {
350
+ const response = yield* ai.generate({
351
+ model: Venice.configure({ apiKey: process.env.VENICE_API_KEY }).chat("qwen3-6-27b"),
352
+ prompt: "Explain this design.",
353
+ providerOptions: {
354
+ reasoningEffort: "high",
355
+ veniceParameters: { includeVeniceSystemPrompt: false },
356
+ },
357
+ })
358
+ console.log(Message.text(response.message))
359
+ })
360
+ ```
361
+
362
+ Effort lowers to `reasoning.effort`; `reasoning.enabled` and `reasoning.summary` are also available.
363
+ Supported effort levels and toggles depend on the selected model. Omitted controls preserve its defaults.
364
+ Venice's added system prompt is disabled by default, matching the previous OpenCode Venice SDK behavior.
365
+
366
+ Replay complete assistant messages to retain signed/encrypted reasoning and Gemini thought
367
+ signatures, including per-tool signatures. Venice's encrypted scalar trailers are excluded from visible
368
+ reasoning but retained in provider metadata for replay. Cache affinity uses `affinity`, and cache-write
369
+ usage reads Venice's `cache_creation_input_tokens` field.
370
+
371
+ The native package entrypoints are `@radheim/ai/providers/venice` and `@radheim/ai/providers/venice/responses`.
372
+ Image generation, embeddings, and client-side E2EE are not implemented by this provider.
373
+
374
+ ## Decisions
375
+
376
+ Decision models answer typed questions about an input: a yes/no `predicate` (a probability), a `choice` from listed
377
+ values, or a `score` on ordered levels, each with the probability of every option.
378
+
379
+ ```ts
380
+ import { Effect } from "effect"
381
+ import { ai, AI, Media } from "@radheim/ai/effect"
382
+ import { OpenAI } from "@radheim/ai/providers"
383
+
384
+ const program = ai.decision.generate({
385
+ model: OpenAI.configure().decision("gpt-6-luna"),
386
+ input: [
387
+ { type: "text", text: "I was charged twice. Please refund the duplicate payment." },
388
+ { type: "media", media: Media.url("https://example.com/receipt.png", { mediaType: "image/png" }) },
389
+ ],
390
+ questions: [
391
+ { name: "refund", type: "predicate", instructions: "Is the customer asking for a refund?" },
392
+ {
393
+ name: "department",
394
+ type: "choice",
395
+ instructions: "Which team should handle this?",
396
+ choices: [{ value: "billing", description: "Payments and refunds" }, { value: "technical" }],
397
+ },
398
+ {
399
+ name: "urgency",
400
+ type: "score",
401
+ instructions: "How urgent is this?",
402
+ levels: [{ label: "Can wait" }, { label: "Needs prompt attention" }, { label: "Blocking revenue" }],
403
+ },
404
+ ],
405
+ })
406
+
407
+ const response = await Effect.runPromise(program.pipe(Effect.provide(AI.fetchLayer)))
408
+ const [refund, department] = response.answers
409
+ ```
410
+
411
+ `input` is a JSON object or an ordered list of `text`, `json` and `media` parts. Answers come back in question order.
412
+ A `predicate` can say what counts as true and as false with `criteria: { true, false }`; hosts without a criteria field
413
+ read them appended to the instructions.
414
+ A question the host declines is `{ name, type: "error", reason, message? }`, with `reason` such as `"refusal"`; the
415
+ other answers still come back.
416
+ `response.usage` has `inputTokens`, `outputTokens`, `totalTokens` and the host's reported `cost` when it sends one;
417
+ the host's raw usage stays in `providerMetadata`.
418
+ Media goes wherever the host reads it, and a kind the host has no place for fails the call. Host-specific fields go in
419
+ `providerOptions`, typed by the selected model (OpenAI `promptCacheKey` and `safetyIdentifier`, OpenRouter
420
+ `provider` routing, Baseten `max_len`).
421
+
422
+ ```ts
423
+ import {
424
+ Baseten,
425
+ CloudflareAIGateway,
426
+ CloudflareWorkersAI,
427
+ DigitalOcean,
428
+ OpenCode,
429
+ OpenRouter,
430
+ TypeSafeAI,
431
+ VercelAIGateway,
432
+ } from "@radheim/ai/providers"
433
+
434
+ TypeSafeAI.configure().decision("jev-latest")
435
+ OpenCode.configure().decision("jev-1.13")
436
+ OpenRouter.configure().decision("typesafe/jev-1.13")
437
+ VercelAIGateway.configure().decision("typesafe-ai/jev")
438
+ Baseten.configure().decision("decision-models/baseten-elephant-9b-latest")
439
+ DigitalOcean.configure().decision("typesafe-jev-1.13.0")
440
+ CloudflareWorkersAI.configure({ accountId }).decision("@cf/cloudflare/clef")
441
+ CloudflareAIGateway.configure({ accountId }).decision("typesafe/jev")
442
+ ```
443
+
444
+ OpenAI and Vercel AI Gateway use OpenAI's `/v1/decisions` API. TypeSafe, OpenCode, OpenRouter, Baseten and
445
+ DigitalOcean use System One (`/systemone`), and Cloudflare sends the System One body through `/ai/run`.
446
+
447
+ ## Embeddings
448
+
449
+ Embedding models turn each value into a vector, returned in value order.
450
+
451
+ ```ts
452
+ import { ai } from "@radheim/ai"
453
+ import { OpenAI } from "@radheim/ai/providers"
454
+
455
+ const response = await ai.embedding.generate({
456
+ model: OpenAI.configure().embedding("text-embedding-3-small"),
457
+ values: ["I was charged twice.", "How do I reset my password?"],
458
+ dimensions: 256,
459
+ inputType: "document",
460
+ })
461
+ const [charge, password] = response.embeddings
462
+ ```
463
+
464
+ A string value is text; media values are an `Asset` (or bytes or a URL) for hosts that embed images or documents.
465
+ `dimensions` asks models that can shorten their vectors for that length. `inputType` says whether the values are
466
+ search queries or stored documents; hosts with no such field (OpenAI's `/embeddings` API) ignore it, and host-specific
467
+ task types go in `providerOptions` (NVIDIA's `input_type: "passage"`). `response.usage.inputTokens` is the host's
468
+ token count, and its raw usage stays in `providerMetadata`. Media values fail the call on hosts that only embed text.
469
+
470
+ ```ts
471
+ import {
472
+ Alibaba,
473
+ Azure,
474
+ Cohere,
475
+ DeepInfra,
476
+ DigitalOcean,
477
+ Fireworks,
478
+ OpenAICompatible,
479
+ OpenRouter,
480
+ VercelAIGateway,
481
+ } from "@radheim/ai/providers"
482
+
483
+ OpenRouter.configure().embedding("openai/text-embedding-3-small")
484
+ VercelAIGateway.configure().embedding("openai/text-embedding-3-small")
485
+ Cohere.configure().embedding("embed-v4.0")
486
+ DeepInfra.configure().embedding("BAAI/bge-m3")
487
+ Fireworks.configure().embedding("nomic-ai/nomic-embed-text-v1.5")
488
+ DigitalOcean.configure().embedding("bge-m3")
489
+ Alibaba.configure({ region: "ap-southeast-1" }).embedding("text-embedding-v4")
490
+ Azure.configure({ resourceName }).embedding("text-embedding-3-small")
491
+ OpenAICompatible.configure({ provider: "nvidia", baseURL: "https://integrate.api.nvidia.com/v1" }).embedding(
492
+ "nvidia/nemotron-3.5-embed-1b",
493
+ )
494
+ ```
495
+
496
+ Every host here uses OpenAI's `/embeddings` API; Cohere through its compatibility API
497
+ (`https://api.cohere.ai/compatibility/v1`). Package entry points are `@radheim/ai/providers/<provider>/embeddings`.
498
+
499
+ Google embeds through `embedContent`, which also takes images, audio, video and PDFs on `gemini-embedding-2`. Each
500
+ value is its own content and gets its own vector (several parts in one content would be averaged into one). `dimensions`
501
+ is `outputDimensionality`, `inputType` becomes `taskType` `RETRIEVAL_QUERY` or `RETRIEVAL_DOCUMENT`, and `taskType` or
502
+ `title` in `providerOptions` replace or add to it. `gemini-embedding-2` ignores task types; Google recommends writing the
503
+ task into the text instead (`task: search result | query: …`, `title: none | text: …`).
504
+
505
+ ```ts
506
+ import { Google, GoogleVertex } from "@radheim/ai/providers"
507
+
508
+ const response = await ai.embedding.generate({
509
+ model: Google.configure().embedding("gemini-embedding-2"),
510
+ values: [await ai.file("./receipt.png"), "A receipt for two coffees."],
511
+ dimensions: 768,
512
+ })
513
+
514
+ GoogleVertex.configure({ project, location: "global" }).embedding("gemini-embedding-2")
515
+ ```
516
+
517
+ `GoogleVertex.configure().embedding(id)` picks the API from the model id: `gemini-embedding-2*` uses `embedContent`,
518
+ and every other model (`gemini-embedding-001`, `text-embedding-005`, `text-multilingual-embedding-002`) uses the
519
+ text-only `:predict` API, which also works with Express Mode keys. On `:predict`, `inputType` and the `taskType` and
520
+ `title` options go on each instance (`task_type`, `title`), and `dimensions`, `autoTruncate` and other options go under
521
+ `parameters`.
522
+
523
+ ```ts
524
+ GoogleVertex.configure({ apiKey }).embedding("text-embedding-005")
525
+ GoogleVertex.configure({ apiKey }).embedding("gemini-embedding-001")
526
+ ```
527
+
528
+ The Gemini API sends up to 100 values per `batchEmbedContents` request, and Vertex `:predict` up to 250 per request
529
+ (one for `gemini-embedding-001`, as Google documents). Vertex `embedContent` takes one value per request, so a call
530
+ sends one request per value, four at a time, and needs project credentials: Vertex Express Mode API keys can't call
531
+ `embedContent`. `gemini-embedding-2` runs in the `global`, `us` and `eu` Vertex locations. When a call
532
+ is split into several requests, the vectors stay in value order, `usage.inputTokens` is their sum, and each request's
533
+ metadata is listed in order under `providerMetadata.<provider>.responses`. The package entry points are
534
+ `@radheim/ai/providers/google/embeddings` and `@radheim/ai/providers/google-vertex/embeddings`.
535
+
536
+ ## Alibaba Cloud Model Studio
537
+
538
+ `Alibaba` provides standard Model Studio inference. Configure a region explicitly, then select
539
+ Chat Completions (`.model` or `.chat`), Anthropic-compatible Messages (`.messages`), or OpenAI-compatible
540
+ Responses (`.responses`). These routes use HTTP/SSE.
541
+
542
+ ```ts
543
+ import { ai } from "@radheim/ai/effect"
544
+ import { Alibaba } from "@radheim/ai/providers"
545
+
546
+ const alibaba = Alibaba.configure({
547
+ region: "ap-southeast-1", // Singapore
548
+ apiKey: process.env.DASHSCOPE_API_KEY,
549
+ // workspaceID: "llm-your-workspace", // use a workspace-dedicated endpoint
550
+ })
551
+
552
+ const request = ai.request({
553
+ model: alibaba.model("qwen3.8-max"),
554
+ prompt: "Explain this design.",
555
+ providerOptions: { reasoningEffort: "medium" },
556
+ })
557
+ ```
558
+
559
+ ### Regions and credentials
560
+
561
+ | Region | `region` | Shared host when `workspaceID` is omitted |
562
+ | ------------------- | ---------------- | ----------------------------------------- |
563
+ | Singapore | `ap-southeast-1` | `dashscope-intl.aliyuncs.com` |
564
+ | China (Beijing) | `cn-beijing` | `dashscope.aliyuncs.com` |
565
+ | China (Hong Kong) | `cn-hongkong` | `cn-hongkong.dashscope.aliyuncs.com` |
566
+ | US (Virginia) | `us-east-1` | `dashscope-us.aliyuncs.com` |
567
+ | Germany (Frankfurt) | `eu-central-1` | Supply `workspaceID` or `baseURL` |
568
+ | Japan (Tokyo) | `ap-northeast-1` | Supply `workspaceID` or `baseURL` |
569
+
570
+ With `workspaceID`, the host is `{workspaceID}.{region}.maas.aliyuncs.com`. A complete `baseURL`
571
+ overrides regional setup, including the API prefix: `/compatible-mode/v1` for Chat/Responses,
572
+ or `/apps/anthropic/v1` for Messages. The selector appends its operation path.
573
+
574
+ Keys and model availability are region-specific. Auth resolves from explicit `auth` or `apiKey`,
575
+ then `DASHSCOPE_API_KEY`, then `ALIBABA_API_KEY`.
576
+
577
+ The access region and inference scope differ: Virginia's `-us` model IDs request US-only inference;
578
+ some regions select scope through their workspace. Model IDs pass through unchanged.
579
+ Alibaba's [regional guide](https://www.alibabacloud.com/help/en/model-studio/regions) and
580
+ [base URL table](https://www.alibabacloud.com/help/en/model-studio/base-url) disagree about Virginia's
581
+ shared host; the entry above follows the base URL table. Dedicated hosts can be copied from the console.
582
+
583
+ ### Native options
584
+
585
+ - **Chat:** `reasoningEffort` → `reasoning_effort`, `enableThinking` → `enable_thinking`,
586
+ `thinkingBudget` → `thinking_budget`, and `preserveThinking` → `preserve_thinking`.
587
+ Replay complete assistant messages to retain `reasoning_content` separately from answer text.
588
+ Qwen 3.8 defaults to preserving thinking; older models have different defaults.
589
+ Additional options include `toolStream`, `parallelToolCalls`, `repetitionPenalty`, `responseFormat`,
590
+ `enableSearch`, and native `searchOptions`. `topK` lowers to `top_k`.
591
+ `clearThinking` is a hosted GLM control, and `thinking.type` is available for hosted MiniMax models.
592
+ - **Messages:** `effort` → `output_config.effort`. `thinking.type` accepts enabled/disabled with an
593
+ optional `budgetTokens` (or native `budget_tokens`). `outputConfig.format` accepts a JSON schema.
594
+ Model Studio's empty thinking signatures are accepted; supplied signatures are replayed unchanged.
595
+ - **Responses:** `reasoningEffort` → `reasoning.effort`, plus `enableThinking`, `store`,
596
+ `previousResponseId`, and `conversation`. Omitted `store` retains the API's default (`true`);
597
+ set it to `false` for client-managed history. `previousResponseId` requires a stored response.
598
+ Hosted tools are `Alibaba.webSearch()`, `Alibaba.webExtractor()`, and `Alibaba.codeInterpreter()`.
599
+ Web extraction is used together with web search. Hosted calls/results carry `providerExecuted: true`.
600
+
601
+ Omitted options preserve provider defaults. Effort values pass through unchanged and accept future
602
+ strings. Qwen 3.8 Chat rejects requests combining a thinking budget with effort.
603
+
604
+ Package entrypoints are `@radheim/ai/providers/alibaba`, `alibaba/chat`, `alibaba/messages`,
605
+ and `alibaba/responses`. Live recordings cover all three APIs in Singapore; regional URL construction
606
+ is unit-tested for all six regions.
607
+
608
+ ### Images
609
+
610
+ `alibaba.image(...)` uses the native multimodal generation API (`/api/v1/services/aigc/multimodal-generation/generation`)
611
+ for Qwen-Image (`qwen-image-2.0`, `qwen-image-2.0-pro`) and Wan (`wan2.7-image`, `wan2.7-image-pro`). `aspect` and
612
+ `resolution` lower to a `W*H` size, `providerOptions.size` sets it exactly, and `images` are sent as URLs or data URLs
613
+ for editing. Native `parameters` include `size`, `seed`, `negativePrompt`, `promptExtend`, `watermark`, `thinkingMode`,
614
+ and `enableSequential`; raw keys such as `bbox_list` pass through. Results are URLs that Model Studio keeps for 24
615
+ hours. A complete `baseURL` for images includes `/api/v1`.
616
+
617
+ ## Z.AI
618
+
619
+ `ZAI` uses the standard API. Chat Completions is the default language-model API;
620
+ the existing `.image(...)` selector provides image generation.
621
+
622
+ ```ts
623
+ import { ai } from "@radheim/ai/effect"
624
+ import { ZAI, ZAICodingPlan } from "@radheim/ai/providers"
625
+
626
+ const zai = ZAI.configure({ apiKey: process.env.ZAI_API_KEY })
627
+ const request = ai.request({
628
+ model: zai.model("glm-5.3"), // also zai.chat("glm-5.3")
629
+ prompt: "Explain this design.",
630
+ providerOptions: {
631
+ reasoningEffort: "high",
632
+ thinking: { type: "enabled", clear_thinking: false },
633
+ },
634
+ })
635
+
636
+ const coding = ZAICodingPlan.configure({ apiKey: process.env.ZAI_API_KEY })
637
+ const messages = ai.request({
638
+ model: coding.messages("glm-5.3"),
639
+ prompt: "Explain this design.",
640
+ providerOptions: { effort: "high" },
641
+ })
642
+ ```
643
+
644
+ The products have distinct provider identities and endpoints:
645
+
646
+ | Provider | Selector | Default base URL |
647
+ | ----------------------------------- | --------------------------- | ------------------------------------- |
648
+ | `ZAI` (`zai`) | `.model`, `.chat`, `.image` | `https://api.z.ai/api/paas/v4` |
649
+ | `ZAICodingPlan` (`zai-coding-plan`) | `.model`, `.chat` | `https://api.z.ai/api/coding/paas/v4` |
650
+ | `ZAICodingPlan` | `.messages` | `https://api.z.ai/api/anthropic/v1` |
651
+ | `ZAICodingPlan` | `.responses` | `https://api.z.ai/api/v1` |
652
+
653
+ Both read `ZAI_API_KEY` when `apiKey` is omitted and support an explicit `auth` override.
654
+ Coding Plan requires an active subscription. `baseURL` overrides the selected API's
655
+ complete base, including its version prefix. Language-model routes use HTTP/SSE.
656
+
657
+ Options retain the selected API's native semantics:
658
+
659
+ - Chat `reasoningEffort` lowers to `reasoning_effort`; Responses lowers it to `reasoning.effort`.
660
+ Messages `effort` lowers to `output_config.effort`. Omission preserves provider defaults.
661
+ - Chat `thinking` passes `type` and `clear_thinking` through unchanged. Set
662
+ `clear_thinking: false` and replay complete assistant messages to preserve reasoning
663
+ across user messages and tool loops. The standard API defaults to clearing historical thinking;
664
+ Coding Plan documents preservation by default.
665
+ - Messages accepts `thinking: { type: "enabled" | "adaptive" | "disabled" }` without requiring
666
+ an Anthropic token budget. Coding Plan documents a disabled toggle as low-effort thinking
667
+ for GLM-5.3, with explicit effort taking precedence.
668
+ - Chat also offers `toolStream`, `doSample`, `responseFormat`, `requestID`, and `userID`.
669
+ Tool-argument streaming is enabled when tools are present on GLM-4.6/4.7/5.x;
670
+ `toolStream: false` explicitly disables it. Older model families omit the opt-in.
671
+ - Effort and thinking values remain forward-compatible strings. Their meaning is model-specific:
672
+ GLM-5.3 accepts `low`, `high`, and `max` effort and rejects disabled thinking with HTTP 400;
673
+ the direct GLM-5.2 recordings returned reasoning even with `none` and `minimal` effort,
674
+ whereas explicit `thinking.type: "disabled"` disabled it on GLM-5.2 and GLM-4.7.
675
+
676
+ Standard API recordings cover GLM-5.3 efforts and a full preserved-reasoning tool loop with
677
+ a subsequent user follow-up, GLM-5.2 efforts, older-model thinking toggles, GLM-4.5 tool calls,
678
+ GLM-5.3-Flash image input, and JSON output. Coding Plan has unit coverage for routing,
679
+ request options, and reasoning replay; successful live recordings are pending.
680
+
681
+ Package entrypoints are `@radheim/ai/providers/zai`, `zai/chat`, `zai-coding-plan`,
682
+ `zai-coding-plan/chat`, `zai-coding-plan/messages`, and `zai-coding-plan/responses`.
683
+
684
+ ## Moonshot
685
+
686
+ Moonshot defaults to Chat Completions, with Messages and Responses selectors for Kimi K3:
687
+
688
+ ```ts
689
+ import { ai } from "@radheim/ai/effect"
690
+ import { Moonshot } from "@radheim/ai/providers"
691
+
692
+ const moonshot = Moonshot.configure({ apiKey: process.env.MOONSHOT_API_KEY })
693
+
694
+ const request = ai.request({
695
+ model: moonshot.model("kimi-k3"), // also moonshot.chat("kimi-k3")
696
+ prompt: "Explain the tradeoffs in this design.",
697
+ providerOptions: { reasoningEffort: "high" },
698
+ })
699
+
700
+ const messages = ai.request({
701
+ model: moonshot.messages("kimi-k3"),
702
+ prompt: "Explain the tradeoffs in this design.",
703
+ providerOptions: { effort: "high" },
704
+ })
705
+
706
+ const responses = ai.request({
707
+ model: moonshot.responses("kimi-k3"),
708
+ prompt: "Explain the tradeoffs in this design.",
709
+ providerOptions: { reasoningEffort: "high" },
710
+ })
711
+ ```
712
+
713
+ When `apiKey` is omitted, authentication reads `MOONSHOT_API_KEY`, then `MOONSHOTAI_API_KEY`.
714
+ Chat and Responses use `https://api.moonshot.ai/v1`; Messages uses
715
+ `https://api.moonshot.ai/anthropic/v1`. `baseURL` overrides the selected API's complete base,
716
+ including the version prefix, for regional endpoints or gateways. Each endpoint requires its own valid credentials.
717
+ All three routes use HTTP/SSE.
718
+
719
+ Reasoning options stay native to the selected API and model:
720
+
721
+ | Model/API | Provider options |
722
+ | --------------------------- | --------------------------------------------------------------------------------------- |
723
+ | K3 Chat / Responses | `reasoningEffort: "low" \| "high" \| "max"`; default is `max` |
724
+ | K3 Messages | `effort: "low" \| "high" \| "max"`; default is `max` |
725
+ | K2.6 Chat | `thinking: { type: "enabled" \| "disabled", keep?: "all" \| null }`; default is enabled |
726
+ | K2.7 Code / high-speed Chat | Omit `thinking` to use always-on, preserved reasoning |
727
+
728
+ Omitting options preserves the model's defaults. K3 uses effort rather than the K2.x `thinking`
729
+ parameter. Known effort values have autocomplete while future strings remain accepted.
730
+ For K2.6, `thinking.keep: "all"` enables preservation of reasoning across user messages.
731
+ K3 and both K2.7 Code variants always preserve reasoning. Continue with the returned
732
+ assistant message and matching tool results so reasoning content and any Messages signatures are retained.
733
+ Leave sampling options such as `temperature` unset to use these models' fixed defaults.
734
+
735
+ The recorded suite covers all three K3 APIs, default and explicit efforts, K2.6 thinking modes,
736
+ both K2.7 Code variants, generated tool loops with a subsequent user follow-up, required/disabled
737
+ tool choice, image-byte input, and native structured output through `http.body` overlays.
738
+ K3 Chat and Messages accept required and disabled tool choice. Responses supports automatic tool
739
+ choice only; explicit `required` and `none` produce a provider `InvalidRequest` error, also covered by recordings.
740
+ The provider targets the Moonshot Open Platform; Kimi Code is a separate product and endpoint.
741
+
742
+ Package entrypoints are `@radheim/ai/providers/moonshot`, `moonshot/chat`, `moonshot/messages`,
743
+ and `moonshot/responses`; each exports `model(modelID, settings)`.
744
+
745
+ ## MiniMax
746
+
747
+ MiniMax defaults to its Messages API and reads `MINIMAX_API_KEY` when `apiKey` is omitted:
748
+
749
+ ```ts
750
+ import { Effect } from "effect"
751
+ import { ai, AI, Message } from "@radheim/ai/effect"
752
+ import { MiniMax } from "@radheim/ai/providers"
753
+
754
+ const minimax = MiniMax.configure({ apiKey: process.env.MINIMAX_API_KEY })
755
+ const request = ai.request({
756
+ model: minimax.model("MiniMax-M3"), // also minimax.messages("MiniMax-M3")
757
+ prompt: "What is 173 multiplied by 219?",
758
+ providerOptions: { thinking: { type: "adaptive" } },
759
+ maxTokens: 1536,
760
+ })
761
+
762
+ const response = await Effect.runPromise(ai.generate(request).pipe(Effect.provide(AI.fetchLayer)))
763
+ console.log(Message.text(response.message))
764
+ ```
765
+
766
+ Select `minimax.chat("MiniMax-M3")` or `minimax.responses("MiniMax-M3")` for MiniMax's native Chat Completions
767
+ and Responses APIs. The matching package entrypoints are `@radheim/ai/providers/minimax/messages`,
768
+ `@radheim/ai/providers/minimax/chat`, and `@radheim/ai/providers/minimax/responses`.
769
+
770
+ - **Messages:** M3 thinking defaults off. Set `thinking: { type: "adaptive" }` to enable it or
771
+ `thinking: { type: "disabled" }` to disable it.
772
+ - **Chat:** M3 thinking defaults on and uses the same `thinking` control. The provider enables `reasoning_split`
773
+ by default so reasoning is separate from answer text; `reasoningSplit: false` selects native `<think>`-tagged text.
774
+ - **Responses:** M3 reasoning defaults off. `reasoningEffort: "none"` disables it; `"minimal"`, `"low"`,
775
+ `"medium"`, and `"high"` enable reasoning without changing its depth.
776
+
777
+ M2.x models always think, even when a disabling option is supplied. For tool continuations, retain the complete
778
+ assistant message in history before adding `Message.tool(...)` results; this preserves reasoning and any signatures.
779
+
780
+ The default API bases are `https://api.minimax.io/anthropic/v1` for Messages and `https://api.minimax.io/v1` for
781
+ Chat, Responses and Images. `configure({ baseURL })` replaces the selected API's base, including its version prefix;
782
+ use `https://api.minimax.cn/v1` for the mainland China platform. `minimax.image("image-01")` (also
783
+ `@radheim/ai/providers/minimax/images`) generates images; see [MiniMax images](#minimax-images).
784
+
785
+ ## Meta
786
+
787
+ Use Meta's direct [Model API](https://dev.meta.ai/docs/overview) with `META_API_KEY`:
788
+
789
+ ```ts
790
+ import { Meta } from "@radheim/ai/providers"
791
+
792
+ const meta = Meta.configure() // or Meta.configure({ apiKey })
793
+ const request = ai.request({
794
+ model: meta.responses("muse-spark-1.3"), // meta.model(...) also selects Responses
795
+ prompt: "What is 173 multiplied by 219? Reply with the integer.",
796
+ providerOptions: { reasoningEffort: "low" },
797
+ maxTokens: 1024,
798
+ })
799
+ ```
800
+
801
+ `meta.chat("muse-spark-1.3")` selects Chat Completions; `meta.messages("muse-spark-1.3")` selects
802
+ the Anthropic-compatible Messages API. All use `https://api.meta.ai/v1`. The package entrypoints
803
+ `@radheim/ai/providers/meta/responses`, `meta/chat`, and `meta/messages` expose `model(modelID, settings)`.
804
+
805
+ [Muse Spark](https://dev.meta.ai/docs/models) supports `minimal`, `low`, `medium`, `high`, and
806
+ `xhigh` reasoning effort; standard-tier 1.3 also supports `max`. Omitting effort uses the model's
807
+ default. Muse Spark always reasons and rejects `none`. The output-token budget includes private reasoning.
808
+
809
+ Responses defaults to `store: false` and `include: ["reasoning.encrypted_content"]`. Preserve
810
+ the assistant message along with matching `Message.tool(...)` results in subsequent requests to replay
811
+ reasoning through tool loops. Optional `reasoningSummary: "auto"` requests a readable summary.
812
+ For server-managed history, override `store: true, include: []` and send the response ID through
813
+ `http: { body: { previous_response_id: responseID } }` with only the new input.
814
+ Chat Completions redacts private reasoning and cannot carry it between calls.
815
+ Responses and Chat support only `toolChoice: "auto"` (the default). Messages also accepts `"none"`;
816
+ its documented forced `"any"` choice currently returns HTTP 400. Messages defaults to adaptive thinking
817
+ with `display: "omitted"`, preserving encrypted `redacted_thinking` in the assistant message. Use
818
+ `providerOptions: { effort: "low" }` for depth or `thinking: { type: "enabled", budgetTokens: 1024 }`
819
+ for budget compatibility (with `maxTokens > 1024`).
820
+
821
+ Add `tools: [Meta.webSearch()]` to a Spark Responses or Messages request for hosted web search.
822
+ Responses exposes hosted results and URL citations in text-part `providerMetadata.meta.annotations`.
823
+ To include search result lists, set `include: ["reasoning.encrypted_content", "web_search_call.results"]`.
824
+ Messages exposes hosted search calls; the recorded Messages API stream does not supply structured
825
+ citations or separate result blocks. Retain the assistant message for either API's continuation.
826
+
827
+ Use `ai.image.generate` for one-off generation or editing:
828
+
829
+ ```ts
830
+ import { ai, Media } from "@radheim/ai/effect"
831
+
832
+ const generation = ai.image.generate({
833
+ model: meta.image("muse-image-1.0"),
834
+ prompt: "A flat black square on a white background.",
835
+ n: 1,
836
+ providerOptions: { reasoningStrength: "low" },
837
+ })
838
+
839
+ const edit = ai.image.generate({
840
+ model: meta.image("muse-image-1.0"),
841
+ prompt: "Make the square purple.",
842
+ images: [Media.bytes(imageBytes, "image/webp")],
843
+ providerOptions: { reasoningStrength: "low", outputFormat: "png" },
844
+ })
845
+ ```
846
+
847
+ The default image format is WEBP; `outputFormat` also accepts PNG/JPEG and `responseFormat: "url"`
848
+ returns a signed URL. `aspect` lowers to Meta's `size`, which is only an aspect-ratio hint: Meta renders about 2.5
849
+ megapixels whatever you ask, so `resolution` is ignored. For conversational images, select
850
+ `meta.responses("muse-image-1.0")` with `tools: [Meta.imageGeneration({ reasoningStrength: "low" })]`.
851
+ Generated images are provider-executed tool results with file content. Retain the assistant message to
852
+ replay the signed image handle on the next request. Muse Image accepts only the `image_generation` tool.
853
+
854
+ Meta Responses is explicitly HTTP/SSE-only and does not use WebSockets, even when a caller supplies
855
+ `StreamOptions.webSocket`. The public `/v1/responses` endpoint rejects WebSocket upgrades with HTTP 405 (`Allow: POST`).
856
+
857
+ ## Image generation
858
+
859
+ Use `ai.image.generate` with an image model for direct asset generation. `ai.image.request` mirrors `ai.request`: the
860
+ model comes from the facade's `.image(...)` selector (mirroring `.responses(...)`), common fields
861
+ (`images`, `n`, `aspect`, `resolution`) lower natively or fail typed, and `providerOptions` is inferred from the
862
+ selected model. `aspect` is a ratio such as `"16:9"`; `resolution` is a size tier (`"1K"` is about 1024×1024 pixels
863
+ at that ratio, `"2K"` about 2048×2048). Exact sizes, seeds, masks, and output formats are provider options:
864
+
865
+ ```ts
866
+ import { ai, Media } from "@radheim/ai/effect"
867
+ import { OpenAI } from "@radheim/ai/providers"
868
+
869
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
870
+
871
+ const program = Effect.gen(function* () {
872
+ const response = yield* ai.image.generate({
873
+ model: openai.image("gpt-image-2"),
874
+ prompt: "A robot tending a rooftop garden",
875
+ n: 2,
876
+ aspect: "16:9",
877
+ resolution: "2K",
878
+ providerOptions: {
879
+ outputFormat: "webp",
880
+ quality: "high", // inferred from the OpenAI image model
881
+ future_option: true, // unknown native options pass through unchanged
882
+ },
883
+ })
884
+
885
+ return response.images // Media.Asset[] with owned bytes or a provider URL
886
+ })
887
+ ```
888
+
889
+ Common fields are portable in shape, not in support. Some routes approximate `aspect` or `resolution` with the nearest
890
+ size they offer; others fail with a typed `AIError` before any network call rather than dropping them, so check this
891
+ table before swapping only the `model`:
892
+
893
+ | Provider | `n` | `aspect` | `resolution` | `images` | Moved to `providerOptions` |
894
+ | --------------------- | --- | ------------------ | ------------------- | -------------------- | ----------------------------------------- |
895
+ | OpenAI | ✓¹ | nearest size | nearest size | ✓ | `size`, `outputFormat`, `mask` |
896
+ | Google (Gemini) | 1 | ✓ | ✓ (`0.5K` as `512`) | ✓ (no public URLs) | `seed` |
897
+ | xAI | ✓ | ✓ | `1k`/`2k` | ✓ | none |
898
+ | Meta | ✓ | ✓ (hint) | ignored | ✓ | `size`, `outputFormat` |
899
+ | Z.ai | ✗ | width × height | width × height | ✗ | `size` |
900
+ | Alibaba | ✓ | width × height | width × height | ✓ | `size`, `seed` |
901
+ | MiniMax | ✓ | preset or w × h⁴ | preset or w × h⁴ | 1 (portrait subject) | `aspect_ratio`, `width`, `height`, `seed` |
902
+ | Vercel AI Gateway | ✓ | as OpenAI³ | as OpenAI³ | per model | as OpenAI |
903
+ | OpenRouter | ✓ | ✓ (`aspect_ratio`) | tier⁵ | per model⁵ | `size`, `outputFormat` (no `mask`) |
904
+ | Cloudflare Workers AI | 1 | width × height² | width × height² | ✗ | `width`, `height`, `seed` |
905
+
906
+ ✓ lowers natively; ✗ fails whenever the field is set (including `n: 1`); `1` means `n > 1` fails. "width × height"
907
+ computes a size the provider accepts and fails when the request falls outside its limits. ¹ `ai.image.stream` on OpenAI
908
+ generates one image. On OpenAI, `gpt-image-2` and later get a computed size; older models get the nearest of their
909
+ fixed sizes. `providerOptions.size` replaces `aspect` and `resolution`, so setting both fails. Vercel AI Gateway
910
+ forwards `outputFormat` but does not apply it, so the returned bytes keep the upstream model's own format. ² Workers AI
911
+ `@cf/black-forest-labs/flux-1-schnell` takes no size, and the provider rejects it. ³ Non-OpenAI gateway models
912
+ (`bfl/flux-2-pro`) get a computed width × height, which the gateway passes through; models with a fixed list, such as
913
+ Recraft, reject sizes outside it. Grok (`spacexai/*`, `xai/*`) ignores `size`, so it gets `providerOptions.xai`
914
+ `aspect_ratio` and `1k`/`2k` instead. ⁴ MiniMax sends its `aspect_ratio` preset for a preset aspect at about `1K` and an
915
+ exact width × height (512–2048 px, steps of 8) otherwise; `image-01-live` takes only the presets, minus `21:9`.
916
+ ⁵ OpenRouter takes `512`, `768`, `1K`, `1.5K`, `2K` or `4K` rather than pixels; other values are left out. It has no
917
+ edits endpoint, so input images go to `/images/generations` as `input_references` (data URLs or http(s) URLs).
918
+
919
+ `Media.Asset` is the one asset type shared by image requests, image responses, LLM messages, and tool results.
920
+ `asset.source` is the serializable `Media.Source` (`bytes`, `base64`, `url`, or `ref`); `asset.bytes()`,
921
+ `asset.base64()`, and `asset.dataUrl()` decode or download lazily and cache; `asset.materialize()` pulls a `url`
922
+ asset into owned bytes before the provider URL expires. Construct assets with `Media.bytes`, `Media.base64`,
923
+ `Media.url`, `Media.ref(provider, id)`, `Media.fromDataUrl`, or `Media.file(path)`.
924
+
925
+ File inputs (message `media` parts, image `images`, decision `media` parts) also take plain data: a `Uint8Array`,
926
+ `ArrayBuffer`, `URL`, or a string holding a data URL, an http(s) URL or base64. Bytes and base64 are sniffed from
927
+ magic bytes; pass `mediaType` when that fails:
928
+
929
+ ```ts
930
+ ai.request({
931
+ model,
932
+ prompt: [
933
+ { type: "text", text: "Summarize this report" },
934
+ { type: "media", media: pdfBase64, mediaType: "application/pdf" },
935
+ ],
936
+ })
937
+ ```
938
+
939
+ Pass ordered image inputs to the same method for editing, composition, or image-conditioned generation:
940
+
941
+ ```ts
942
+ const composed = Effect.gen(function* () {
943
+ const response = yield* ai.image.generate({
944
+ model,
945
+ prompt: "Combine these product photos into one studio scene",
946
+ images: [
947
+ Media.bytes(firstBytes, "image/png"),
948
+ Media.url("https://example.com/second.webp"),
949
+ Media.ref("openai", "file_123"),
950
+ ],
951
+ providerOptions,
952
+ http,
953
+ })
954
+ return response.images
955
+ })
956
+ ```
957
+
958
+ `Media.ref(provider, id)` represents provider file handles such as OpenAI file IDs or Gemini Files URIs; routes
959
+ only forward refs that belong to their own provider (OpenAI, xAI, and Gemini images accept them). No shipped route
960
+ returns a ref yet, and `asset.bytes()` / `materialize()` on a ref fail by design. Empty or omitted `images` uses
961
+ text-to-image generation; a
962
+ non-empty array selects the provider's edit behavior (see the table above for routes that limit the count). OpenAI
963
+ uses multipart for byte/data-URL edits and its JSON reference body for URL or file-ID edits. Inpainting is a
964
+ provider option on the routes that support it (OpenAI):
965
+
966
+ ```ts
967
+ const inpainted = ai.image.generate({
968
+ model: openai.image("gpt-image-2"),
969
+ prompt,
970
+ images: [Media.bytes(sourceBytes, "image/png")],
971
+ providerOptions: { mask: Media.bytes(maskBytes, "image/png") },
972
+ })
973
+ ```
974
+
975
+ On multipart requests, `http.body` can override option fields but not structural `model`, `prompt`, `image[]`,
976
+ or `mask` fields, and the transport owns the multipart `Content-Type` boundary. For JSON requests, `http.body`
977
+ remains the final raw-native overlay. Gemini does not fetch public HTTP URLs, and hosted Z.ai image generation does
978
+ not accept image inputs. These cases fail with a typed `AIError` before network I/O.
979
+
980
+ Provider-native image options belong to each request. Raw `http.body` fields have final precedence over them:
981
+
982
+ ```ts
983
+ const medium = ai.image.generate({
984
+ model: openai.image("gpt-image-2"),
985
+ prompt,
986
+ providerOptions: { quality: "medium" },
987
+ http,
988
+ })
989
+ ```
990
+
991
+ xAI image models use the same request API with xAI-native controls:
992
+
993
+ ```ts
994
+ import { XAI } from "@radheim/ai/providers"
995
+
996
+ const xai = ai.image.generate({
997
+ model: XAI.configure({ apiKey }).image("any-model-id"),
998
+ prompt,
999
+ n: 2,
1000
+ aspect: "16:9",
1001
+ resolution: "1K",
1002
+ providerOptions: {
1003
+ responseFormat: "url", // defaults to "b64_json" (inline bytes)
1004
+ future_option: true,
1005
+ },
1006
+ http,
1007
+ })
1008
+ ```
1009
+
1010
+ Google's current Gemini image models use the same direct API:
1011
+
1012
+ ```ts
1013
+ import { Google } from "@radheim/ai/providers"
1014
+
1015
+ const googleProgram = Effect.gen(function* () {
1016
+ const response = yield* ai.image.generate({
1017
+ model: Google.configure({ apiKey }).image("any-model-id"),
1018
+ prompt: "A robot tending a rooftop garden",
1019
+ aspect: "16:9",
1020
+ resolution: "2K",
1021
+ providerOptions: {
1022
+ seed: 42,
1023
+ thinkingLevel: "HIGH",
1024
+ includeThoughts: true,
1025
+ futureOption: true,
1026
+ },
1027
+ http,
1028
+ })
1029
+
1030
+ return response.images
1031
+ })
1032
+ ```
1033
+
1034
+ Google image options are request-scoped and inferred from the selected model. Known fields autocomplete while
1035
+ future string values and arbitrary native Gemini `generationConfig` fields remain available. Native fields override
1036
+ their mapped aliases, and `http.body` is the final deep overlay. The selected model ID is sent to Gemini
1037
+ `generateContent` without a local allowlist.
1038
+
1039
+ Z.ai image models infer open Z.ai-native options from the selected model:
1040
+
1041
+ ```ts
1042
+ import { ZAI } from "@radheim/ai/providers"
1043
+
1044
+ const zai = ai.image.generate({
1045
+ model: ZAI.configure({ apiKey }).image("any-model-id"),
1046
+ prompt,
1047
+ providerOptions: {
1048
+ quality: "hd",
1049
+ userID: "user-123",
1050
+ future_option: true,
1051
+ },
1052
+ http,
1053
+ })
1054
+ ```
1055
+
1056
+ Z.ai does not include trustworthy MIME metadata for output URLs, so generated images use
1057
+ `application/octet-stream` until materialized. Output URLs expire after 30 days; call `asset.materialize()` and
1058
+ persist the bytes promptly if they must remain available.
1059
+
1060
+ ### MiniMax images
1061
+
1062
+ ```ts
1063
+ import { MiniMax } from "@radheim/ai/providers"
1064
+
1065
+ const minimax = ai.image.generate({
1066
+ model: MiniMax.configure({ apiKey }).image("image-01"),
1067
+ prompt,
1068
+ n: 2,
1069
+ aspect: "16:9",
1070
+ images: [Media.url("https://example.com/portrait.jpg")], // optional subject reference
1071
+ providerOptions: { promptOptimizer: true, seed: 42 },
1072
+ })
1073
+ ```
1074
+
1075
+ The reference image is sent as a `character` subject, so it should be a single front-facing portrait. Images come
1076
+ back inline (`responseFormat: "base64"` by default); `responseFormat: "url"` returns links that expire after 24 hours
1077
+ and carry no MIME type until materialized. MiniMax status codes map to typed errors; code 1026 is a `ContentPolicy`
1078
+ error.
1079
+
1080
+ ### Partial images
1081
+
1082
+ OpenAI's GPT image models stream previews. `ai.image.stream` sends `stream: true` with `partialImages` (0–3, default 2)
1083
+ and emits `image-partial` events before each final `image`; `ai.image.generate` keeps the plain JSON request:
1084
+
1085
+ ```ts
1086
+ import { Stream } from "effect"
1087
+
1088
+ const previews = ai.image
1089
+ .stream({
1090
+ model: openai.image("gpt-image-2"),
1091
+ prompt: "A lighthouse at dusk",
1092
+ providerOptions: { partialImages: 2 },
1093
+ })
1094
+ .pipe(Stream.runForEach((event) => (event.type === "image-partial" ? showPreview(event.image) : Effect.void)))
1095
+ ```
1096
+
1097
+ The provider may send fewer previews than requested when the final image is ready first.
1098
+
1099
+ Imagen is not available: Google shut it down on the Gemini API, and Vertex discontinued the Imagen 4 models on
1100
+ 2026-06-30. `Google.image(...)` uses Gemini-native image models.
1101
+
1102
+ Conversational image generation remains part of the LLM interaction. OpenAI Responses exposes it through its hosted image tool:
1103
+
1104
+ ```ts
1105
+ const program = Effect.gen(function* () {
1106
+ const response = yield* ai.generate(
1107
+ ai.request({
1108
+ model: OpenAI.configure({ apiKey }).responses("gpt-5"),
1109
+ prompt: "Design a solarpunk rooftop garden, then show me.",
1110
+ tools: [OpenAI.imageGeneration({ quality: "high" })],
1111
+ }),
1112
+ )
1113
+
1114
+ return response.message
1115
+ })
1116
+ ```
1117
+
1118
+ The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `StreamEvent` for inline image output (the assistant message then carries a `media` part). Retaining the assistant message preserves the generated image for continuation on both routes.
1119
+
1120
+ ### Image jobs
1121
+
1122
+ `ai.image.generate` and `ai.image.stream` poll a queued image route for you. To manage the job yourself, use the same
1123
+ calls as video: `start` submits it and returns `{ id }` at once, the provider's job ID as a string you can store and
1124
+ read back from another process, and `status`, `result` and `cancel` take the model and that `id`. `status` is one read;
1125
+ `result` fails with an `InvalidRequest` reason while the job is still running; `cancel` fails with an
1126
+ `UnsupportedOperation` reason when the provider has no cancel endpoint. No shipped image route is queued yet, so on
1127
+ every image model today all four fail with an `UnsupportedOperation` reason before sending anything.
1128
+
1129
+ ```ts
1130
+ const program = Effect.gen(function* () {
1131
+ const job = yield* ai.image.start({ model, prompt: "A lighthouse" })
1132
+ const status = yield* ai.image.status(model, job.id) // { status, progress? }
1133
+ if (status.status === "completed") return yield* ai.image.result(model, job.id)
1134
+ })
1135
+ ```
1136
+
1137
+ ## Video generation
1138
+
1139
+ Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`,
1140
+ fetch its `result`, or `cancel` it. Nothing polls for you. Every call after `start` takes the model and the job's
1141
+ `id`, the provider's job ID as a string you can store and read back from another process, so recovering after a restart
1142
+ is the same call as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`,
1143
+ `BytePlus`, `MiniMax` and `Google` facades.
1144
+
1145
+ ```ts
1146
+ import { Effect } from "effect"
1147
+ import { ai, Media } from "@radheim/ai/effect"
1148
+ import { XAI } from "@radheim/ai/providers"
1149
+
1150
+ const model = XAI.configure({ apiKey: process.env.XAI_API_KEY }).video("grok-imagine-video-1.5")
1151
+
1152
+ const program = Effect.gen(function* () {
1153
+ const job = yield* ai.video.start({
1154
+ model,
1155
+ prompt: "Panning wide shot of a calico kitten sleeping in the sunshine",
1156
+ start: "https://example.com/first-frame.png", // exact first frame; `end` pins the last one
1157
+ references: [], // images, videos or audio that guide subject or style
1158
+ duration: "8 seconds",
1159
+ aspect: "16:9", // or "auto" to follow the start image
1160
+ resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value
1161
+ sound: false,
1162
+ })
1163
+ job.id // the provider's job ID: store it with the provider and model ID
1164
+
1165
+ const status = yield* ai.video.status(model, job.id)
1166
+ status.status // "running" | "completed" | "error"
1167
+ status.reason // "failed" | "cancelled" | "expired", only when status is "error"
1168
+ status.progress // 0..1, only when the provider reports it
1169
+
1170
+ const response = yield* ai.video.result(model, job.id)
1171
+ yield* Media.write(response.videos[0], "./kitten.mp4") // streams the download to disk
1172
+ })
1173
+ ```
1174
+
1175
+ The shared fields are `prompt`, `start`, `end`, `references`, `duration`, `aspect`, `resolution` and `sound`;
1176
+ everything else is provider-specific and goes under `providerOptions`, typed from the selected model. A request only
1177
+ fails before sending when its protocol has no way to express it, such as a reference video on xAI. `sound` is the
1178
+ exception: on models whose sound can't be switched (MiniMax H3 and Gemini Omni always have it, Hailuo never does) it
1179
+ isn't sent, and the model's own behavior applies. Values the provider
1180
+ may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed.
1181
+
1182
+ `start` and `end` are images. They take a URL, data URL, base64 string or bytes, or an asset built with
1183
+ `Media.image(...)`, which rejects assets known to be video, audio or documents; URLs and provider file references
1184
+ whose type isn't stated are sent and checked by the provider. `references` take any kind.
1185
+
1186
+ `status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the
1187
+ provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation
1188
+ outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads
1189
+ retry transient failures (rate limits, provider 5xx, network errors) with backoff that honors `retry-after`; `start`
1190
+ and `cancel` never retry. `cancel` fails with an `UnsupportedOperation` reason on providers without a cancel endpoint,
1191
+ such as xAI, where the job keeps running and billing. Finished videos are usually URLs that expire (`expiresAt` when the
1192
+ provider documents it): download them with `Media.write`, `asset.stream()` or `materialize()` before then.
1193
+
1194
+ Provider notes:
1195
+
1196
+ - **xAI** maps `start` to `image`, `end` to `last_frame`, image references to `reference_images`, audio references to
1197
+ `reference_audios`, and `sound` to `generate_audio`, and leaves `aspect: "auto"` out when a start frame sets the
1198
+ shape. It has no reference video input. `providerOptions.mode: "edit" | "extend"` sends a native `video: { url }`
1199
+ source to `/videos/edits` or `/videos/extensions`.
1200
+ - **OpenRouter** (`OpenRouter.configure(...).video("google/veo-3.1")`) maps `start` and `end` to `frame_images`,
1201
+ references to `input_references` by kind (`image_url`, `video_url`, `audio_url`), `sound` to `generate_audio`, and
1202
+ `resolution` to its spelling (`4k` → `4K`), and leaves `aspect: "auto"` out so models that can follow the input image do.
1203
+ Frames and references are both sent; when both are present OpenRouter keeps the frames and drops the references. It
1204
+ rejects reference videos or audio that aren't http(s) URLs (inline images work). Routing and upstream parameters go under `providerOptions.provider` (`only`, `order`,
1205
+ `options: { <slug>: {...} }`), and `providerOptions.previous_job_id` edits or extends a finished job. Results are
1206
+ OpenRouter content URLs that download with the API key, which the asset carries; there is no cancel endpoint.
1207
+ - **Seedance** (`Volcengine.configure(...).video(...)` with `ARK_API_KEY`, `BytePlus.configure(...).video(...)` with
1208
+ `BYTEPLUS_API_KEY`) builds Ark's `content[]`: the prompt as a `text` item, `start` and `end` as `image_url` items
1209
+ with roles `first_frame` and `last_frame`, and references as `reference_image`, `reference_video` or
1210
+ `reference_audio` by kind. Your own `Media.ref(...)` assets go as `asset://<id>`. `duration` goes to `duration`,
1211
+ `aspect` to `ratio` (`auto` becomes `adaptive`), `resolution` to `resolution` and `sound` to `generate_audio`. Ark
1212
+ doesn't allow frames and references in one task; that combination is sent and the provider's error comes back.
1213
+ `providerOptions.draft_task: { id }` adds a `draft_task` item; `frames`, `seed`, `watermark`, `output_format`,
1214
+ `omni_reference_task_type`, `return_last_frame` and the rest go into the body as-is. `cancel` sends `DELETE`, which
1215
+ only cancels a queued task: Ark refuses it for a running one and deletes the record of a finished one. Video URLs
1216
+ expire 24 hours after the task finished.
1217
+ - **MiniMax** (`MiniMax.configure(...).video(id)`, or `@radheim/ai/providers/minimax/videos`) serves two APIs and picks
1218
+ one by model family: Hailuo and `*-01` models use v1, everything else (H3) uses v2. Video builds its `/v1` and `/v2`
1219
+ paths on the API host, so a `baseURL` shared with images or chat (`https://api.minimax.cn/v1`) loses its trailing
1220
+ `/v1`, and a bare host (`https://api.minimax.io`) works as is. On H3, `start`, `end` and `references` become `content[]` items with `first_frame`, `last_frame` and `reference_image` /
1221
+ `reference_video` / `reference_audio` roles, MiniMax file refs become `mm_file://` URLs, `aspect: "auto"` becomes
1222
+ `ratio: "adaptive"`, and `resolution` is uppercased (`480P`, `2K`). H3 requires `resolution` and `duration`, plus a
1223
+ `ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound
1224
+ and has no field for it, so `sound` isn't sent. On Hailuo, `start` and `end` map to `first_frame_image` and
1225
+ `last_frame_image`, image references to `subject_reference`, and the result looks up the file's download URL, which
1226
+ expires after one hour. Hailuo is always silent, so `sound` isn't sent; it has no aspect field, so an explicit
1227
+ `aspect` and video or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields
1228
+ such as `extra.prompt_expansion_mode` (H3), `prompt_optimizer` (Hailuo) and `callback_url` go under `providerOptions`.
1229
+ - **Google** (`Google.video("gemini-omni-1.2-flash")`) starts a background Gemini Omni interaction. Omni has no
1230
+ role field for media, so `start`, `end` and `references` go into `input` in that order (images, plus video
1231
+ references), and `generation_config.video_config.task` is set to `image_to_video` for frames only or
1232
+ `reference_to_video` for references only; with both, the prompt decides. `duration` becomes
1233
+ `response_format.duration` (`"3s"`), and `aspect` and `resolution` go to `response_format` as is (resolution
1234
+ lowercased); `aspect: "auto"` leaves the ratio out. It rejects `end` without `start` (a lone image reads as the
1235
+ first frame). Omni always generates audio and has no field for it, so `sound` isn't sent. Videos come back as inline bytes. `cancel` posts to
1236
+ `/interactions/{id}/cancel`. `providerOptions` takes native Interactions fields, such as `previous_interaction_id`
1237
+ to edit or extend a generated video, `generation_config.video_config.task`, `service_tier` and `webhook_config`.
1238
+
1239
+ The promise client has the same calls, each accepting `{ signal }`:
1240
+
1241
+ ```ts
1242
+ import { ai } from "@radheim/ai"
1243
+
1244
+ const job = await ai.video.start({ model, prompt })
1245
+ const status = await ai.video.status(model, job.id)
1246
+ if (status.status === "completed") await ai.write((await ai.video.result(model, job.id)).videos[0], "./kite.mp4")
1247
+ ```
1248
+
1249
+ ## Public API
1250
+
1251
+ Everything below is exported from `@radheim/ai/effect` unless noted.
1252
+
1253
+ - **`ai.request({...})`** — build a provider-neutral `LLMRequest`, a plain object. Accepts ergonomic inputs (`system: string`, `prompt: string`) and normalizes them into `system`, `messages` and `tools` arrays. Edit it with a spread, or pass the edited object back to `ai.request`.
1254
+ - **`ai.generate` / `ai.stream`** — run direct input or an `LLMRequest` through the `AI` service for one-import use.
1255
+ - **`ai.loop`** — stream model calls, running `tool(...)` tools between them until the model stops calling tools.
1256
+ - **`ai.collect`** — fold a stream from `ai.stream` or `ai.loop` into its final result (`text`, `steps`, `messages`, `usage`).
1257
+ - **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
1258
+ - **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
1259
+ - **`StreamEvent`** — the discriminated union of stream events; narrow with `event.type === "text-delta"` or a `switch` on `type`.
1260
+ - **`ai.image.request` / `generate` / `stream` / `start` / `status` / `result` / `cancel`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. `start`, `status`, `result` and `cancel` address a queued job by the provider's job ID, like video; see [Image jobs](#image-jobs).
1261
+ - **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by the provider's job ID; see [Video generation](#video-generation).
1262
+ - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
1263
+ - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
1264
+ - **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input.
1265
+ - **`ai.embedding.request` / `ai.embedding.generate`** — one vector per text or media value, with optional `dimensions` and `inputType`.
1266
+ - **`AI`** — one Effect service for every operation: text as `stream`, `generate` and `compact`, and media grouped as `image`, `video`, `speech`, `transcription`, `decision` and `embedding`. `AI.stream` and `AI.generate` run a prepared `LLMRequest` through it. `AI.layer` requires `RequestExecutor.Service`; `AI.layerWith(executor)` and `AI.fetchLayer` provide `AI` and the executor in one layer.
1267
+ - **`@radheim/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image`, `decision`, `embedding` and `video` (plus `experimental.speech` and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer? })` builds a client over a custom executor. The same `ai` from `@radheim/ai/effect` returns `Effect` and `Stream`.
1268
+ - **`@radheim/ai/experimental`** — APIs that may change without compatibility guarantees: `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
1269
+
1270
+ ## Experimental
1271
+
1272
+ These APIs may change without compatibility guarantees. The Effect API is exported from `@radheim/ai/experimental`,
1273
+ and the Promise client exposes it under `ai.experimental`.
1274
+
1275
+ - **`Speech`** and **`Transcription`** — speech generation and speech-to-text, run by the `AI` service's `speech` and
1276
+ `transcription` groups. Promise: `ai.experimental.speech` and `.transcription`.
1277
+ - **`Extraction`** — typed values read out of text.
1278
+ - **`Realtime`** — `Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or
1279
+ a short-lived WebSocket URL and token.
1280
+
1281
+ The provider selectors for these modalities (`.speech(...)`, `.transcription(...)`,
1282
+ `.experimental.extraction(...)`) and their protocol entrypoints (such as `@radheim/ai/protocols/openai-speech`) are
1283
+ part of the same experimental surface.
1284
+
1285
+ ### Speech generation
1286
+
1287
+ Speech (text-to-speech) is one request whose response is parsed incrementally, so every route supports both
1288
+ `Speech.generate` (the whole file) and `Speech.stream` (audio chunks as they arrive). Models come from `.speech(...)`
1289
+ selectors on the `OpenAI`, `Google` (Gemini TTS), `ElevenLabs`, `Cartesia`, and `Deepgram` facades. Common fields
1290
+ (`voice`, `format`, `speed`, `language`, `instructions`, `timestamps`) lower natively or fail with a typed `AIError`
1291
+ before any network call; provider-native controls live under `providerOptions`, inferred from the selected model.
1292
+
1293
+ ```ts
1294
+ import { Media } from "@radheim/ai/effect"
1295
+ import { Speech } from "@radheim/ai/experimental"
1296
+ import { ElevenLabs, OpenAI } from "@radheim/ai/providers"
1297
+
1298
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
1299
+
1300
+ // The whole file, written to disk.
1301
+ const program = Effect.gen(function* () {
1302
+ const response = yield* Speech.generate({
1303
+ model: openai.speech("gpt-4o-mini-tts"),
1304
+ text: "Hello from OpenCode.",
1305
+ voice: "coral",
1306
+ format: "mp3",
1307
+ instructions: "Warm and unhurried.",
1308
+ })
1309
+ response.audio // Media.Asset with bytes; headerless PCM carries info.encoding / sampleRate / channels
1310
+ response.usage // undefined: OpenAI reports tokens only on SSE streams (Gemini: tokens; ElevenLabs: credits; Deepgram: characters)
1311
+ yield* Media.write(response.audio, "hello.mp3")
1312
+ })
1313
+
1314
+ // Chunks as they arrive: audio-delta* (interleaved with timestamps) then one finish carrying the assembled asset.
1315
+ const events = Speech.stream({
1316
+ model: ElevenLabs.configure({ apiKey }).speech("eleven_flash_v2_5"),
1317
+ text: "Hello from OpenCode.",
1318
+ voice: "JBFqnCBsd6RMkjVDRZzb",
1319
+ format: "pcm",
1320
+ timestamps: true,
1321
+ }).pipe(
1322
+ Stream.tap((event) => {
1323
+ if (event.type === "audio-delta") return play(event.chunk)
1324
+ if (event.type === "timestamps") return highlight(event.items) // { text, startSeconds, endSeconds }[]
1325
+ return Effect.void
1326
+ }),
1327
+ )
1328
+ ```
1329
+
1330
+ `voice` is the provider's own identifier — a name on OpenAI and Gemini (`"coral"`, `"Kore"`), a voice id on
1331
+ ElevenLabs and Cartesia. `{ id }` selects an OpenAI custom voice (`{ id: "voice_1234" }`) and means the same as the
1332
+ plain string elsewhere. There is no cross-provider voice catalog. `format` is the container-level word (`mp3`, `wav`,
1333
+ `pcm`, `opus`, `aac`, `flac`); sample rates and bitrates live under `providerOptions`, and a value the route cannot
1334
+ produce fails as `UnsupportedOperation`. Streams buffer every chunk so `finish` can carry the whole clip.
1335
+
1336
+ Provider notes:
1337
+
1338
+ - **OpenAI** streams over SSE (`stream_format: "sse"`), which is also the only place it reports token usage; `tts-1`
1339
+ and `tts-1-hd` do not support SSE and stream the raw audio body instead. `pcm` is 24 kHz 16-bit mono. `language`
1340
+ and `timestamps` are not supported.
1341
+ - **Gemini TTS** returns the provider's default output: WAV for Gemini 3.8 TTS `generate`, raw 16-bit PCM
1342
+ (`audio/L16;codec=pcm;rate=24000`) otherwise. `pcm` is the only explicit `format` it accepts, and it fails typed on
1343
+ Gemini 3.8 `generate`; the route never wraps PCM as WAV. Style is directed in the text, so `instructions` and
1344
+ `speed` fail typed. Only `gemini-3.1-flash-tts-preview` and later support streaming. Two-speaker audio goes through
1345
+ `providerOptions.speechConfig.multiSpeakerVoiceConfig`.
1346
+ - **ElevenLabs** requires `voice` (the path voice id) and authenticates with `xi-api-key`. `format` maps to the
1347
+ `output_format` query parameter (`mp3_44100_128`, `pcm_24000`, `wav_24000`, `opus_48000_64`);
1348
+ `providerOptions.outputFormat` sets the exact string. WAV is only available from `generate`. `timestamps: true`
1349
+ selects the `with-timestamps` endpoints and yields character-level alignment. `instructions` is not supported.
1350
+ - **Cartesia** requires `voice` and pins `Cartesia-Version`. `generate` defaults to MP3 from `/tts/bytes`; streams
1351
+ and `timestamps: true` (word-level) use `/tts/sse`, which only serves raw PCM. `providerOptions.sampleRate`,
1352
+ `bitRate`, and `encoding` complete `output_format`. No usage is reported.
1353
+ - **Deepgram** Aura's voice is the model id (`aura-2-thalia-en`), so `voice` and `language` fail typed. `format`
1354
+ and `providerOptions` lower to query parameters (`encoding`, `container`, `sample_rate`, `bit_rate`); `pcm` is
1355
+ `linear16` without a container. Auth is `Authorization: Token <DEEPGRAM_API_KEY>`.
1356
+
1357
+ The promise client mirrors the Effect API; `ai.experimental.speech.stream` is an `AsyncIterable`.
1358
+
1359
+ ```ts
1360
+ import { ai } from "@radheim/ai"
1361
+
1362
+ const response = await ai.experimental.speech.generate({ model, text: "Hello from OpenCode.", voice: "coral" })
1363
+ await ai.write(response.audio, "hello.mp3")
1364
+
1365
+ for await (const event of ai.experimental.speech.stream({ model, text: "Hello from OpenCode.", voice: "coral" })) {
1366
+ if (event.type === "audio-delta") player.write(event.chunk)
1367
+ }
1368
+ ```
1369
+
1370
+ ### Transcription
1371
+
1372
+ Transcription (speech-to-text) is the one modality whose providers use every route kind: OpenAI and Gemini stream,
1373
+ Deepgram and ElevenLabs answer inline, and AssemblyAI is queued. `Transcription.generate` and `Transcription.stream`
1374
+ work on all of them; `Transcription.start` / `resume` return a `Generation` on queued routes and fail with
1375
+ `UnsupportedOperation` elsewhere. Models come from `.transcription(...)` selectors on the `OpenAI`, `Google`,
1376
+ `Deepgram`, `ElevenLabs`, and `AssemblyAI` facades. Common fields (`language`, `prompt`,
1377
+ `timestamps: "none" | "segment" | "word"`, `diarize`, `speakers`) lower natively or fail with a typed `AIError` before
1378
+ any network call; a route may return more than asked.
1379
+
1380
+ ```ts
1381
+ import { Console, Effect, Stream } from "effect"
1382
+ import { Media } from "@radheim/ai/effect"
1383
+ import { Transcription } from "@radheim/ai/experimental"
1384
+ import { AssemblyAI, Deepgram, OpenAI } from "@radheim/ai/providers"
1385
+
1386
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
1387
+
1388
+ const program = Effect.gen(function* () {
1389
+ const audio = yield* Media.file("./call.mp3")
1390
+
1391
+ // Speaker-labelled segments; labels are provider-native strings ("A", "0", "spk:0", "speaker_0").
1392
+ const response = yield* Transcription.generate({
1393
+ model: Deepgram.configure({ apiKey }).transcription("nova-3"),
1394
+ audio,
1395
+ diarize: true,
1396
+ timestamps: "word",
1397
+ })
1398
+ response.text // "Hello from OpenCode."
1399
+ response.segments // [{ text, startSeconds, endSeconds, speaker: "0" }]
1400
+ response.words // [{ text, startSeconds, endSeconds, speaker, confidence }]
1401
+ response.language // the provider's own value, lowercased ("en", "eng", "english", "en_us")
1402
+
1403
+ // Text deltas as the model transcribes, then one finish carrying the whole transcript.
1404
+ yield* Transcription.stream({ model: openai.transcription("gpt-4o-mini-transcribe"), audio }).pipe(
1405
+ Stream.tap((event) => (event.type === "text-delta" ? Console.log(event.delta) : Effect.void)),
1406
+ Stream.runDrain,
1407
+ )
1408
+
1409
+ // Queued: persist the token with the provider and model ID (the token alone cannot pick the model), resume, and await.
1410
+ const model = AssemblyAI.configure({ apiKey }).transcription("universal-3-5-pro")
1411
+ const generation = yield* Transcription.start({ model, audio })
1412
+ const resumed = yield* Transcription.resume(model, JSON.parse(JSON.stringify(generation.token)))
1413
+ const transcript = yield* resumed.await({ poll: { interval: "3 seconds" } })
1414
+ })
1415
+ ```
1416
+
1417
+ Inline routes emit only `finish` from `stream` (no faked deltas); queued routes emit `generation-progress`
1418
+ before it.
1419
+
1420
+ Provider notes:
1421
+
1422
+ - **OpenAI** takes inline audio only; `diarize` needs `gpt-4o-transcribe-diarize`, timestamps need `whisper-1`, and `whisper-1` does not stream.
1423
+ - **Gemini** needs a transcribe model (`gemini-3.5-transcribe`); `prompt` and `speakers` fail typed.
1424
+ - **Deepgram** detects the language unless `language` is set; vocabulary goes in `providerOptions.keyterm`.
1425
+ - **ElevenLabs** (`scribe_v2`) uploads inline audio as the multipart `file` and sends a URL as `source_url`. Words
1426
+ always carry timestamps, and segments are speaker turns, so `diarize`, `timestamps: "segment"`, or `speakers` turns
1427
+ on diarization. `speakers` is an upper bound (`num_speakers`); `prompt` fails typed (vocabulary goes in
1428
+ `providerOptions.keyterms`), as do webhook delivery and per-channel output (`use_multi_channel` without
1429
+ `multichannel_output_style: "combined"`).
1430
+ - **AssemblyAI** uploads inline audio before submitting and treats `speakers` as the exact speaker count.
1431
+
1432
+ The promise client mirrors the Effect API:
1433
+
1434
+ ```ts
1435
+ const audio = await ai.file("./call.mp3")
1436
+ const text = (await ai.experimental.transcription.generate({ model, audio })).text
1437
+ for await (const event of ai.experimental.transcription.stream({ model, audio }))
1438
+ if (event.type === "text-delta") write(event.delta)
1439
+ const generation = await ai.experimental.transcription.start({ model: assemblyai, audio })
1440
+ const transcript = await generation.await({ poll: { interval: 3_000 } })
1441
+ ```
1442
+
1443
+ ### Extraction
1444
+
1445
+ Extraction models read typed values out of text instead of answering questions with probabilities. A field of type
1446
+ `text`, `number`, `date`, `time`, `datetime`, `duration`, `list`, `estimate` or `forecast` gets an answer typed to
1447
+ match; other types are sent and answered as-is. Only Cloudflare's Clairic serves it today.
1448
+
1449
+ ```ts
1450
+ import { ai } from "@radheim/ai"
1451
+ import { Extraction } from "@radheim/ai/experimental"
1452
+ import { CloudflareWorkersAI } from "@radheim/ai/providers"
1453
+
1454
+ const response = await ai.run(
1455
+ Extraction.generate({
1456
+ model: CloudflareWorkersAI.configure({ accountId }).experimental.extraction("@cf/cloudflare/clairic"),
1457
+ input: "Invoice INV-2291, issued 2026-09-02, net 30. Total $1,080.00. Contact: Dana Ruiz, Priya Shah.",
1458
+ fields: {
1459
+ invoiceNumber: { type: "text" },
1460
+ dueDate: { type: "date", instructions: "Issue date plus the net payment days" },
1461
+ total: { type: "number", decimals: 2, unit: "USD" },
1462
+ contacts: { type: "list", items: "text" },
1463
+ },
1464
+ }),
1465
+ )
1466
+ response.answers.total.value // 1080, or null when the input does not say
1467
+ ```
1468
+
1469
+ Value answers carry `guess`, `nullProbability` and `confidence`; text answers carry a `span` into `input`. Estimates and
1470
+ forecasts return `median`, `p10` and `p90`. Field options other than `type`, `instructions` and `nullThreshold` go to
1471
+ Clairic as written. Effect users provide `RequestExecutor.fetchLayer` (or `AI.fetchLayer`). Images are not supported
1472
+ yet.
1473
+
1474
+ ## Testing
1475
+
1476
+ Use the deterministic test client from `@radheim/ai/testing` to script provider-neutral responses and inspect
1477
+ the requests sent by code under test:
1478
+
1479
+ ```ts
1480
+ import { Effect } from "effect"
1481
+ import { TestLLM } from "@radheim/ai/testing"
1482
+
1483
+ const programWithTestClient = Effect.gen(function* () {
1484
+ const test = yield* TestLLM.Test
1485
+ yield* test.push(TestLLM.text("Hello from the test model", "text-1"))
1486
+ const result = yield* program
1487
+ console.log(yield* test.requests())
1488
+ return result
1489
+ }).pipe(Effect.provide(TestLLM.testLayer()))
1490
+ ```
1491
+
1492
+ `testLayer()` provides its text operations under `AI.Service` and the full object under `TestLLM.Test`. Production
1493
+ consumes the normal service; tests use the additional controls. Each layer build has fresh state. The `AI` it provides
1494
+ implements text only; media calls fail as not implemented.
1495
+
1496
+ - `test.push(...)` queues one-shot responses in execution order. Each argument is one response.
1497
+ - `test.always(response)` installs a repeatable fallback. The layer's `fallback` option sets its initial value.
1498
+ - `test.serve(request => response)` installs a request-dependent fallback. `always` and `serve` replace each
1499
+ other without changing queued replies; queued replies take precedence.
1500
+ - `test.requests()` returns an array snapshot. `transformRequest` changes only the recorded observation;
1501
+ `serve` receives the original canonical request.
1502
+ - `test.wait(count)` waits for request arrivals, not output or completion, and supports concurrent waiters.
1503
+ - `test.gate()` returns a scoped gate with countable `started` notifications and a `release` Effect. Release
1504
+ unblocks all requests captured by that gate; closing its scope also releases it. Effect-aware test runners
1505
+ already provide Scope.
1506
+
1507
+ Constructing `stream()` or `generate()` does not record a request, invoke a responder, or consume a script.
1508
+ Each execution does. An exhausted queue without a fallback defects immediately rather than waiting for a
1509
+ future reply.
1510
+
1511
+ Generation responses remain canonical event arrays or arbitrary `Stream<StreamEvent, AIError>` values. The client consumes
1512
+ supplied streams directly, preserving failure identity, finalizers, incomplete output, and post-finish tails;
1513
+ it does not repair or truncate them.
1514
+
1515
+ For explicit compaction, script a `CompactionResponse` through `push`, `always`, or `serve`. Its `replacement` contains the next context window, including retained user messages. The client returns that result and usage directly, with the same lazy request recording and gates. Generation and compaction reject fixtures for the wrong operation instead of converting between response shapes.
1516
+
1517
+ For `compact(request, { mechanism: "trigger" })`, script a `CompactionCheckpointResponse` instead. It carries `checkpoint`, `responseID`, and optional `usage`. Endpoint and trigger calls reject each other's fixtures; both share the same queue, gates, lazy recording, and fallback controls.
1518
+
1519
+ Response helpers build common event arrays: `TestLLM.text(value, id)`, `textWithUsage(value, id, inputTokens)`,
1520
+ `toolCall(id, name, input)`, `stop(...events)`, `toolCalls(...events)`, and
1521
+ `complete({ reason, usage?, providerMetadata? }, ...events)`. `failAfter(error, ...events)` and `hangAfter(...events)`
1522
+ return streams that fail or never finish after the given events.
1523
+
1524
+ `compileRequest`, also from `@radheim/ai/testing`, compiles an `LLMRequest` through its route without sending it, so
1525
+ tests can assert the provider payload.
1526
+
1527
+ To stub individual operations instead, `TestAI.layer` builds a full `AI` service from the parts you pass, text
1528
+ operations or members of any media group. Anything else fails with an "AI.<operation> is not implemented in this test"
1529
+ defect when called:
1530
+
1531
+ ```ts
1532
+ import { Effect, Stream } from "effect"
1533
+ import { TestAI, TestLLM } from "@radheim/ai/testing"
1534
+
1535
+ const layer = TestAI.layer({
1536
+ stream: () => Stream.fromIterable(TestLLM.text("Hello", "text-1")),
1537
+ image: { generate: () => Effect.succeed(fixtureImage) },
1538
+ })
1539
+ ```
1540
+
1541
+ `TestAI.make(implementation)` returns the same service value without a layer.
1542
+
1543
+ Other modalities and the Promise client have no scripted test double. Test them over a custom executor layer, such as
1544
+ `AI.make({ layer })`, that answers the HTTP requests.
1545
+
1546
+ ## Provider compaction
1547
+
1548
+ Compaction is opt-in. The package supports automatic compaction in OpenAI/Azure Responses and Anthropic Messages (including Claude on Vertex), and explicit compaction calls in OpenAI/Azure/xAI Responses. Model and deployment support still depends on the provider.
1549
+
1550
+ This is different from prompt caching, server-side history storage, or truncation. Compaction returns provider-owned context that must be replayed to continue the conversation.
1551
+
1552
+ ### Explicit compaction
1553
+
1554
+ `ai.compact(request)` (equivalently, `{ mechanism: "endpoint" }`) is the caller-controlled operation for OpenAI, Azure, and xAI Responses. It performs exactly one HTTP call to `/responses/compact`, using the selected route's endpoint, credentials, query, and HTTP middleware. It returns a `CompactionResponse` with `replacement: Message[]` and optional `usage`, not a normal generation response. This mechanism does not accept a WebSocket executor.
1555
+
1556
+ Prefer this operation, where supported, when the application owns compaction policy and durable context updates.
1557
+
1558
+ ```ts
1559
+ const compacted = Effect.gen(function* () {
1560
+ const result = yield* ai.compact(request)
1561
+ const next = { ...request, messages: result.replacement }
1562
+ return yield* ai.generate(next)
1563
+ })
1564
+ ```
1565
+
1566
+ From the Promise API, `await ai.compact(request)` takes the same request and options (with `signal`, and `middleware` in place of `http`) and returns the same result.
1567
+
1568
+ `replacement` replaces the complete input window. Do not append it to the original transcript or extract only the encrypted item: the provider may retain additional messages in its output. Retained user and assistant messages remain ordinary messages with typed text, media, or reasoning parts, in their original order. Provider-specific message IDs, status, and phase use `providerMetadata`, not a raw output array hidden in an assistant message. Unsupported returned item types fail explicitly.
1569
+
1570
+ The selected model carries explicit-compaction capability through request construction and updates. Calls using unsupported routes fail type checking. When the model is selected dynamically, narrow the request with `ai.canCompact(request)` before calling `ai.compact`; a model or route switch does not inherit the old capability. Runtime validation still rejects unsupported calls from untyped consumers. Capability describes the route's API, not whether every model or custom deployment supports the operation.
1571
+
1572
+ Generation-only body overlays such as `stream` and `store` are not sent to the compact endpoint. Supported compact controls such as service tier and prompt-cache settings preserve request defaults and HTTP-overlay precedence. Retained image and file detail settings survive serialization and replay.
1573
+
1574
+ The input must still fit the model's context window. Explicit compaction is not an overflow-recovery operation. Anthropic does not expose this operation in this package; its in-band compaction remains available below. Compatible routes do not inherit an explicit compact endpoint simply because they use a Responses protocol.
1575
+
1576
+ ### Streamed checkpoint compaction
1577
+
1578
+ OpenAI Responses also exposes a separate, explicitly selected mechanism:
1579
+
1580
+ ```ts
1581
+ const checkpoint = Effect.gen(function* () {
1582
+ const result = yield* ai.compact(request, {
1583
+ mechanism: "trigger",
1584
+ webSocket, // Optional: without it, the request uses HTTP/SSE.
1585
+ })
1586
+
1587
+ result.checkpoint // Successful encrypted CompactionPart.
1588
+ result.responseID
1589
+ result.usage
1590
+ })
1591
+ ```
1592
+
1593
+ This appends a native `compaction_trigger` control item to the full input and sends a normal Responses request, with tools and instructions retained, `stream: true`, `store: false`, and parallel tool calls enabled. It removes normal-answer text/output-format controls, forced tool choices, output-token/tool-call limits, and automatic `context_management`. Body overlays cannot replace `input` or supply `previous_response_id`/`conversation`; the complete canonical history is required for safe stateless replay. Request metadata, auth, headers, query parameters, service tier, and supported prompt-cache settings are preserved.
1594
+
1595
+ Only a successful `response.completed` with a response ID and exactly one logical encrypted checkpoint succeeds. Repeated item events are correlated by ID/output slot, including ID-less checkpoints. Other output is ignored, not returned as assistant text or dispatched as tools. Failed, incomplete, malformed, and interrupted responses return errors rather than partial checkpoints.
1596
+
1597
+ The result is **not a replacement window**. The caller selects retained history, combines it with `result.checkpoint`, and durably installs it before continuing. The operation does not choose a retention budget, prune messages, or modify the original request.
1598
+
1599
+ The supplied WebSocket executor can reuse a compatible append baseline for the compaction request. On completion the protocol supplies no continuation checkpoint, clearing the old baseline so the next generation sends the newly installed window in full. Validation occurs before transport completion is acknowledged. There is no operation-level retry or fallback to `/responses/compact`; existing safe transport fallback may use SSE, with full history and no connection-local response ID.
1600
+
1601
+ Trigger support is separate from endpoint support. Only the OpenAI Responses route advertises it; Azure, xAI, Chat, and compatible Responses routes do not inherit it. Untyped calls still fail before sending: missing route capabilities return `UnsupportedOperation`, while unknown mechanism names and invalid inputs return `InvalidRequest`. Dynamic callers must narrow for the selected mechanism:
1602
+
1603
+ ```ts
1604
+ const narrowed = Effect.gen(function* () {
1605
+ if (ai.canCompact(request, { mechanism: "trigger" })) {
1606
+ const result = yield* ai.compact(request, { mechanism: "trigger" })
1607
+ }
1608
+ })
1609
+ ```
1610
+
1611
+ This capability describes protocol implementation, **not universal availability on OpenAI API deployments**. The host application owns subscription/deployment eligibility, OAuth, endpoint selection, and deployment-specific headers. Local protocol/socket tests do not establish live provider support.
1612
+
1613
+ ### Advanced: in-band compaction
1614
+
1615
+ `providerOptions.contextManagement` lets the provider decide when to compact during an ordinary `generate` or `stream` call. This is an advanced option for callers that own persistence and recovery: persist the complete assistant message, including its checkpoint, before continuing. Enabling the option does not provide durable checkpoint storage, interruption recovery, or model-switch policy. Keep the prior context until a successful checkpoint has been persisted.
1616
+
1617
+ Enable OpenAI compaction with typed provider options:
1618
+
1619
+ ```ts
1620
+ import { Effect } from "effect"
1621
+ import { ai, AI, Message } from "@radheim/ai/effect"
1622
+ import { OpenAI } from "@radheim/ai/providers"
1623
+
1624
+ const request = ai.request({
1625
+ model: OpenAI.configure({ apiKey }).responses("gpt-5.3-codex"),
1626
+ messages,
1627
+ providerOptions: {
1628
+ contextManagement: [{ type: "compaction", compactThreshold: 200_000 }],
1629
+ },
1630
+ })
1631
+ const continued = Effect.gen(function* () {
1632
+ const response = yield* AI.generate(request)
1633
+ return { ...request, messages: [...request.messages, response.message, Message.user("Continue")] }
1634
+ })
1635
+ ```
1636
+
1637
+ `store: false` remains the default. Keep the entire assistant message, not just its text. Compaction events become ordered `CompactionPart`s alongside text and reasoning. The conversation contains everything needed to continue; there is no separate replay object or hidden provider transcript.
1638
+
1639
+ A compaction part has `provider` and exactly one representation: `encrypted` for Responses, or `text` for Anthropic. Responses also preserves the optional checkpoint `id`. These fields survive message serialization without becoming visible assistant text. Sending a checkpoint to another provider or an incompatible API fails rather than silently losing context.
1640
+
1641
+ ```ts
1642
+ import { CompactionPart, ProviderID } from "@radheim/ai/effect"
1643
+
1644
+ CompactionPart.make({ provider: ProviderID.make("openai"), id: "cmp_123", encrypted: "..." })
1645
+ CompactionPart.make({ provider: ProviderID.make("anthropic"), text: "Summary of the conversation..." })
1646
+ ```
1647
+
1648
+ For Anthropic, use:
1649
+
1650
+ ```ts
1651
+ providerOptions: {
1652
+ contextManagement: {
1653
+ edits: [{
1654
+ type: "compact_20260112",
1655
+ trigger: { type: "input_tokens", value: 150_000 },
1656
+ pauseAfterCompaction: true,
1657
+ instructions: "Summarize the task and decisions. Do not call tools while summarizing.",
1658
+ }],
1659
+ },
1660
+ }
1661
+ ```
1662
+
1663
+ - The trigger is optional (provider default: 150,000 tokens), with a minimum of 50,000.
1664
+ - Custom instructions replace Anthropic's default summarization instructions.
1665
+ - The route adds `compact-2026-01-12` to existing beta headers, including when replaying a checkpoint without enabling new compactions.
1666
+ - A pause is exposed as `response.finish.raw === "compaction"`. It occurs only if the threshold triggers compaction: `pauseAfterCompaction` does not mean "compact now". The caller explicitly issues the next request; the package never automatically resumes.
1667
+ - Anthropic can return a compaction block with `content: null` when summarization fails. This becomes a compaction part with `text: null`, which is **not** a successful replacement for prior history. The package never prunes history automatically.
1668
+ - `Usage` totals include all reported Anthropic `usage.iterations`, including compaction and server-side fallback. `contextTokens` separately reports the final `message` or `fallback_message` iteration's inclusive input size, when available. A compaction-only pause does not report a post-compaction context size. Raw iteration usage remains in `providerMetadata`.
1669
+
1670
+ ### Recording tests
1671
+
1672
+ Tests cover serialized round trips, real local HTTP plus a tool loop, WebSocket recovery, provider errors, malformed blocks, and usage accounting. Live provider tests are gated by `RECORD=true` and the relevant API keys:
1673
+
1674
+ ```sh
1675
+ # Run from packages/ai. Only records the selected new cassette group.
1676
+ RECORD=true RECORDED_PREFIX=openai-compaction bun test test/provider/compaction.recorded.test.ts
1677
+ RECORD=true RECORDED_PREFIX=xai-compaction bun test test/provider/compaction.recorded.test.ts
1678
+ RECORD=true RECORDED_PREFIX=anthropic-compaction bun test test/provider/compaction.recorded.test.ts
1679
+ ```
1680
+
1681
+ Provider references: [OpenAI](https://developers.openai.com/api/docs/guides/compaction), [Azure](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/responses#server-side-compaction), [Anthropic](https://platform.claude.com/docs/en/build-with-claude/compaction), [xAI](https://docs.x.ai/developers/advanced-api-usage/context-compaction).
1682
+
1683
+ ## Caching
1684
+
1685
+ Prompt caching is **on by default**. Every `LLMRequest` resolves to `cache: "auto"` unless the caller opts out with `cache: "none"`. Each protocol translates `CacheHint`s to its wire format (`cache_control` on Anthropic, `cachePoint` on Bedrock; OpenAI and Gemini do implicit caching server-side and don't need inline markers — auto is a no-op there).
1686
+
1687
+ ### Auto placement
1688
+
1689
+ `"auto"` places up to four breakpoints — the last tool definition, the first system part, the last system part when distinct, and the final message boundary. These expose successively larger reusable prefixes for tool definitions, system instructions, and the active conversation. The rolling final-message boundary advances on every request so recent conversation prefixes remain reusable during tool loops.
1690
+
1691
+ Tools precede every system and conversation block in the provider prefix, so tool definitions must remain byte-stable and deterministically ordered for downstream breakpoints to remain reusable.
1692
+
1693
+ Requests below a provider's minimum cacheable size simply do not produce a reusable cache entry.
1694
+
1695
+ ### Opting out
1696
+
1697
+ ```ts
1698
+ ai.request({
1699
+ model,
1700
+ system,
1701
+ prompt: "one-off question",
1702
+ cache: "none",
1703
+ })
1704
+ ```
1705
+
1706
+ ### Granular policy
1707
+
1708
+ ```ts
1709
+ cache: {
1710
+ tools?: boolean,
1711
+ system?: boolean,
1712
+ messages?: "latest-user-message" | "latest-assistant" | { tail: number },
1713
+ ttl?: CacheTTL, // "5m", "30m", "1h", "12h", "24h", ...
1714
+ }
1715
+ ```
1716
+
1717
+ An object with placement fields places exactly those breakpoints. An object with only `ttl` keeps automatic placement.
1718
+
1719
+ ### Cache lifetime
1720
+
1721
+ `ttl` is a duration in models.dev's format (`<number>` followed by `ms`, `s`, `m`, `h` or `d`). It is sent to the provider as given, so use one the provider accepts. Leaving it unset keeps the provider default.
1722
+
1723
+ ```ts
1724
+ ai.request({ model, system, prompt, cache: { ttl: "1h" } })
1725
+ ```
1726
+
1727
+ | Protocol | How `ttl` is sent |
1728
+ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
1729
+ | Anthropic Messages family, Meta Messages | `ttl` on every `cache_control` marker |
1730
+ | Bedrock Converse | `ttl` on every `cachePoint`; older Claude releases that only cache for 5m drop `"1h"` |
1731
+ | OpenRouter, DigitalOcean, Alibaba Chat markers | `ttl` on every `cache_control` marker |
1732
+ | OpenAI Responses (OpenAI, Azure, Cloudflare AI Gateway) | `"24h"` → `prompt_cache_retention: "24h"`; anything else → `prompt_cache_options: { ttl }` |
1733
+ | Chat Completions without markers (OpenAI-compatible, Moonshot, DeepInfra) | same mapping as OpenAI Responses |
1734
+
1735
+ OpenAI's two fields cover different models: `prompt_cache_retention` (`"in_memory"` or `"24h"`) is the only control before GPT-5.6, and GPT-5.6+ reads `prompt_cache_options.ttl` (`"30m"` or `"12h"`). Sending `prompt_cache_options` to an older model returns a 400. `"in_memory"` is not a duration; send it with an HTTP body overlay.
1736
+
1737
+ ### Manual hints
1738
+
1739
+ Inline `CacheHint` (`{ type: "ephemeral", ttl? }`) on any text / system / tool / tool-result part overrides automatic placement. The auto policy preserves manual hints, counts them against Anthropic and Bedrock's four-breakpoint limit, and only fills the remaining slots.
1740
+
1741
+ ```ts
1742
+ ai.request({
1743
+ model,
1744
+ system: [
1745
+ { type: "text", text: "stable system prompt", cache: { type: "ephemeral" } },
1746
+ ],
1747
+ ...
1748
+ })
1749
+ ```
1750
+
1751
+ ### Provider behavior table
1752
+
1753
+ | Protocol | `cache: "auto"` |
1754
+ | ----------------------- | ------------------------------------------------------------------------- |
1755
+ | Anthropic Messages | emits up to 4 `cache_control` markers (4-breakpoint cap enforced) |
1756
+ | Bedrock Converse | emits up to 4 `cachePoint` blocks (4-breakpoint cap enforced) |
1757
+ | OpenRouter | emits up to 4 `cache_control` markers |
1758
+ | OpenAI Chat / Responses | no-op (implicit caching above 1024 tokens) |
1759
+ | Gemini | no-op (implicit caching on 2.5+; explicit `CachedContent` is out-of-band) |
1760
+
1761
+ Normalized cache usage is read back into `response.usage.cacheReadInputTokens` and `cacheWriteInputTokens` across every provider.
1762
+
1763
+ ## Providers
1764
+
1765
+ Provider facades configure endpoint/auth/deployment details first, then expose model selectors that take only a model or deployment id. The selected model carries the executable route value used at runtime.
1766
+
1767
+ ```ts
1768
+ import { OpenAI, CloudflareAIGateway } from "@radheim/ai/providers"
1769
+
1770
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }).responses("gpt-4o-mini")
1771
+ const gateway = CloudflareAIGateway.configure({
1772
+ accountId,
1773
+ gatewayApiKey: process.env.CLOUDFLARE_API_TOKEN,
1774
+ }).model("workers-ai/@cf/meta/llama-3.1-8b-instruct")
1775
+ ```
1776
+
1777
+ For a provider that needs no key, such as a local server, pass `apiKey: false`: the package skips the environment lookup and sends no auth header (Amazon Bedrock and Google Vertex keep their own auth).
1778
+
1779
+ Included LLM providers: OpenAI, Anthropic, Google (Gemini), Google Vertex, Amazon Bedrock (Converse and Mantle), Azure OpenAI, Alibaba, Baseten, Cerebras, Cohere, Cloudflare AI Gateway, Cloudflare Workers AI, DeepInfra, DeepSeek, DigitalOcean, Fireworks, Groq, Meta, MiniMax, Mistral, Moonshot, OpenRouter, TogetherAI, Venice, Vercel AI Gateway, xAI, Z.ai, and Z.ai Coding Plan. TypeSafe AI and OpenCode expose decision models only. Generic Chat Completions, Responses, and Anthropic Messages-compatible entrypoints support custom endpoints.
1780
+
1781
+ Each named provider owns its module, endpoint, authentication, and route setup. Providers with the same wire format compose the shared protocol directly:
1782
+
1783
+ ```ts
1784
+ import { DeepSeek, Fireworks } from "@radheim/ai/providers"
1785
+
1786
+ const deepseek = DeepSeek.configure({ apiKey }).model("deepseek-chat")
1787
+ const fireworks = Fireworks.configure({ apiKey }).model("accounts/fireworks/models/my-model")
1788
+ ```
1789
+
1790
+ The former `OpenAICompatible.baseten`, `.cerebras`, `.deepinfra`, `.deepseek`, `.fireworks`, `.groq`, and `.togetherai` presets are replaced by the top-level `Baseten`, `Cerebras`, `DeepInfra`, `DeepSeek`, `Fireworks`, `Groq`, and `TogetherAI` exports. Use `CloudflareAIGateway` and `CloudflareWorkersAI` directly; each has its own module. `OpenAICompatible` configures generic endpoints with an explicit `baseURL`.
1791
+
1792
+ ### Provider entrypoints
1793
+
1794
+ Provider modules are available through dedicated exports from `@radheim/ai`. Each LLM entrypoint exports `model(modelID, settings)`, where `settings` contains provider configuration plus common `headers` and `body` overlays.
1795
+
1796
+ ```ts
1797
+ import { model } from "@radheim/ai/providers/openai/responses"
1798
+
1799
+ const selected = model("gpt-5", {
1800
+ apiKey: process.env.OPENAI_API_KEY,
1801
+ headers: { "x-application": "example" },
1802
+ })
1803
+ ```
1804
+
1805
+ APIs have separate entrypoints:
1806
+
1807
+ - `@radheim/ai/providers/openai/chat`
1808
+ - `@radheim/ai/providers/openai/responses`
1809
+ - `@radheim/ai/providers/openai-compatible/responses`
1810
+ - `@radheim/ai/providers/anthropic-compatible`
1811
+ - `@radheim/ai/providers/google-vertex/gemini`
1812
+ - `@radheim/ai/providers/google-vertex/interactions`
1813
+ - `@radheim/ai/providers/google-vertex/chat`
1814
+ - `@radheim/ai/providers/google-vertex/responses`
1815
+ - `@radheim/ai/providers/google-vertex/messages`
1816
+
1817
+ OpenAI Responses has one semantic route and uses HTTP by default. Advanced callers may supply a per-call WebSocket channel executor through `StreamOptions`; transport policy does not change provider settings, model identity, or route identity. The provider-neutral Open Responses implementation owns the reusable WebSocket request and event contract, while each provider opts in with its own handshake and connection policy. Azure follows the same Chat/Responses split at `providers/azure/chat` and `providers/azure/responses`. Generic OpenAI-compatible Chat remains at `providers/openai-compatible`; the Responses adapter at `providers/openai-compatible/responses` uses the provider-neutral Open Responses protocol. OpenAI Responses extends that baseline with OpenAI tools, event variants, metadata, and defaults. Generic Anthropic Messages-compatible providers use `providers/anthropic-compatible`, which the named Anthropic provider composes. Google Gemini and Amazon Bedrock expose their single native API through their existing provider paths.
1818
+
1819
+ Vertex Gemini, Vertex Interactions, Vertex Chat, Vertex Responses, and Vertex Messages are separate API entrypoints. All accept `project`, `location`, and an optional `accessToken`; when no explicit token or auth override is supplied they lazily use Google Application Default Credentials. Vertex Gemini and Interactions instead select express mode when `apiKey` or `GOOGLE_VERTEX_API_KEY` is present (explicit `project` or `location` selects ADC over an ambient key). Vertex Chat targets MaaS models through the OpenAI-compatible Chat Completions endpoint, while Vertex Responses targets Grok models and defaults `store` to `false` as required by Vertex. `providers/google-vertex` remains the default alias for `providers/google-vertex/gemini`.
1820
+
1821
+ Tuned Vertex Gemini deployments use model ids shaped like `endpoints/1234567890` and require OAuth or ADC; Vertex express-mode API keys support publisher models only.
1822
+
1823
+ ```ts
1824
+ import { model } from "@radheim/ai/providers/google-vertex/gemini"
1825
+
1826
+ model("gemini-3.5-flash", { project: "my-project", location: "global" })
1827
+ ```
1828
+
1829
+ ```ts
1830
+ import { model } from "@radheim/ai/providers/google-vertex/chat"
1831
+
1832
+ model("deepseek-ai/deepseek-v3.2-maas", { project: "my-project", location: "global" })
1833
+ ```
1834
+
1835
+ ```ts
1836
+ import { model } from "@radheim/ai/providers/google-vertex/responses"
1837
+
1838
+ model("xai/grok-4.20-reasoning", { project: "my-project", location: "global" })
1839
+ ```
1840
+
1841
+ ```ts
1842
+ import { model } from "@radheim/ai/providers/google-vertex/messages"
1843
+
1844
+ model("claude-sonnet-4-6", { project: "my-project", location: "global" })
1845
+ ```
1846
+
1847
+ Additional provider entrypoints include:
1848
+
1849
+ - `@radheim/ai/providers/baseten`
1850
+ - `@radheim/ai/providers/deepseek`
1851
+ - `@radheim/ai/providers/fireworks`
1852
+ - `@radheim/ai/providers/cloudflare-ai-gateway`
1853
+ - `@radheim/ai/providers/cloudflare-workers-ai`
1854
+
1855
+ ## Provider options & HTTP overlays
1856
+
1857
+ Request options in order of stability:
1858
+
1859
+ 1. **Portable knobs** — `maxTokens`, `temperature`, `topP`, `topK`, `frequencyPenalty`, `presencePenalty`, `seed` and `stop`, at the top level of a text request. The `GenerationOptions` schema, exported from `@radheim/ai` and `@radheim/ai/effect`, defines them.
1860
+ 2. **`affinity`** — stable cache affinity, lowered by each protocol to its provider's field (OpenAI `prompt_cache_key`, xAI `x-grok-conv-id`, …).
1861
+ 3. **`providerOptions: { ... }`** — flat options inferred from the selected model (OpenAI `store`, Anthropic `thinking`, Gemini `thinkingConfig`, OpenRouter routing).
1862
+ 4. **`http: { headers, timeout, fetch, query, body, encoding, tls }`** — per-request HTTP settings. `headers` merge over the provider's, `timeout` is milliseconds, `false` or `{ total, headers, chunk }`, and `fetch` (requests only) sends the call through your own `fetch`. `query` and `body` are last-resort serializable overlays merged into the final HTTP request; reach for `body` only when a stable typed path doesn't yet exist. Models and routes take the same `http` under their options, without `fetch`.
1863
+
1864
+ Route/provider defaults are overridden by request-level values for each axis.
1865
+
1866
+ The selected model supplies the provider-specific option type, so per-request overrides stay flat while the canonical runtime request remains provider-neutral:
1867
+
1868
+ ```ts
1869
+ ai.request({
1870
+ model,
1871
+ prompt,
1872
+ providerOptions: {
1873
+ reasoningEffort: "low",
1874
+ },
1875
+ })
1876
+ ```
1877
+
1878
+ ## Routes
1879
+
1880
+ Compose a route with `Route.make({ protocol, endpoint, auth, framing, ... })`. The route owns endpoint/auth/framing and the protocol owns body construction plus stream parsing. Transports receive the route's endpoint and auth when preparing requests. Unsupported request shapes fail during protocol lowering.
1881
+
1882
+ ## Effect
1883
+
1884
+ This package is built on Effect. Public methods in `@radheim/ai/effect` return `Effect` or `Stream`; provide `AI.fetchLayer` (or `AI.layerWith(executor)`) for every modality, then import the provider/protocol modules for the routes you use. The example at `example/tutorial.ts` is a runnable walkthrough.
1885
+
1886
+ ## See also
1887
+
1888
+ - `AGENTS.md` — architecture, route construction, contributor guide
1889
+ - `example/tutorial.ts` — runnable end-to-end walkthrough (`bun example/tutorial.ts <example>`)
1890
+ - `test/provider/*.test.ts` — fixture-first protocol tests; `*.recorded.test.ts` files cover live cassettes