@bastani/pi-ai 0.9.14

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 (745) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE.md +16 -0
  4. package/README.md +1672 -0
  5. package/dist/api/anthropic-messages.d.ts +71 -0
  6. package/dist/api/anthropic-messages.d.ts.map +1 -0
  7. package/dist/api/anthropic-messages.js +1060 -0
  8. package/dist/api/anthropic-messages.js.map +1 -0
  9. package/dist/api/anthropic-messages.lazy.d.ts +3 -0
  10. package/dist/api/anthropic-messages.lazy.d.ts.map +1 -0
  11. package/dist/api/anthropic-messages.lazy.js +3 -0
  12. package/dist/api/anthropic-messages.lazy.js.map +1 -0
  13. package/dist/api/azure-openai-responses.d.ts +15 -0
  14. package/dist/api/azure-openai-responses.d.ts.map +1 -0
  15. package/dist/api/azure-openai-responses.js +242 -0
  16. package/dist/api/azure-openai-responses.js.map +1 -0
  17. package/dist/api/azure-openai-responses.lazy.d.ts +3 -0
  18. package/dist/api/azure-openai-responses.lazy.d.ts.map +1 -0
  19. package/dist/api/azure-openai-responses.lazy.js +3 -0
  20. package/dist/api/azure-openai-responses.lazy.js.map +1 -0
  21. package/dist/api/bedrock-converse-stream.d.ts +38 -0
  22. package/dist/api/bedrock-converse-stream.d.ts.map +1 -0
  23. package/dist/api/bedrock-converse-stream.js +967 -0
  24. package/dist/api/bedrock-converse-stream.js.map +1 -0
  25. package/dist/api/bedrock-converse-stream.lazy.d.ts +9 -0
  26. package/dist/api/bedrock-converse-stream.lazy.d.ts.map +1 -0
  27. package/dist/api/bedrock-converse-stream.lazy.js +30 -0
  28. package/dist/api/bedrock-converse-stream.lazy.js.map +1 -0
  29. package/dist/api/cloudflare-gateway-binding.d.ts +69 -0
  30. package/dist/api/cloudflare-gateway-binding.d.ts.map +1 -0
  31. package/dist/api/cloudflare-gateway-binding.js +159 -0
  32. package/dist/api/cloudflare-gateway-binding.js.map +1 -0
  33. package/dist/api/cloudflare.d.ts +9 -0
  34. package/dist/api/cloudflare.d.ts.map +1 -0
  35. package/dist/api/cloudflare.js +9 -0
  36. package/dist/api/cloudflare.js.map +1 -0
  37. package/dist/api/constrained-sampling.d.ts +20 -0
  38. package/dist/api/constrained-sampling.d.ts.map +1 -0
  39. package/dist/api/constrained-sampling.js +222 -0
  40. package/dist/api/constrained-sampling.js.map +1 -0
  41. package/dist/api/github-copilot-headers.d.ts +8 -0
  42. package/dist/api/github-copilot-headers.d.ts.map +1 -0
  43. package/dist/api/github-copilot-headers.js +29 -0
  44. package/dist/api/github-copilot-headers.js.map +1 -0
  45. package/dist/api/google-generative-ai.d.ts +13 -0
  46. package/dist/api/google-generative-ai.d.ts.map +1 -0
  47. package/dist/api/google-generative-ai.js +417 -0
  48. package/dist/api/google-generative-ai.js.map +1 -0
  49. package/dist/api/google-generative-ai.lazy.d.ts +3 -0
  50. package/dist/api/google-generative-ai.lazy.d.ts.map +1 -0
  51. package/dist/api/google-generative-ai.lazy.js +3 -0
  52. package/dist/api/google-generative-ai.lazy.js.map +1 -0
  53. package/dist/api/google-shared.d.ts +81 -0
  54. package/dist/api/google-shared.d.ts.map +1 -0
  55. package/dist/api/google-shared.js +384 -0
  56. package/dist/api/google-shared.js.map +1 -0
  57. package/dist/api/google-vertex.d.ts +15 -0
  58. package/dist/api/google-vertex.d.ts.map +1 -0
  59. package/dist/api/google-vertex.js +466 -0
  60. package/dist/api/google-vertex.js.map +1 -0
  61. package/dist/api/google-vertex.lazy.d.ts +3 -0
  62. package/dist/api/google-vertex.lazy.d.ts.map +1 -0
  63. package/dist/api/google-vertex.lazy.js +3 -0
  64. package/dist/api/google-vertex.lazy.js.map +1 -0
  65. package/dist/api/lazy.d.ts +19 -0
  66. package/dist/api/lazy.d.ts.map +1 -0
  67. package/dist/api/lazy.js +70 -0
  68. package/dist/api/lazy.js.map +1 -0
  69. package/dist/api/mistral-conversations.d.ts +25 -0
  70. package/dist/api/mistral-conversations.d.ts.map +1 -0
  71. package/dist/api/mistral-conversations.js +736 -0
  72. package/dist/api/mistral-conversations.js.map +1 -0
  73. package/dist/api/mistral-conversations.lazy.d.ts +3 -0
  74. package/dist/api/mistral-conversations.lazy.d.ts.map +1 -0
  75. package/dist/api/mistral-conversations.lazy.js +3 -0
  76. package/dist/api/mistral-conversations.lazy.js.map +1 -0
  77. package/dist/api/openai-codex-responses.d.ts +31 -0
  78. package/dist/api/openai-codex-responses.d.ts.map +1 -0
  79. package/dist/api/openai-codex-responses.js +1294 -0
  80. package/dist/api/openai-codex-responses.js.map +1 -0
  81. package/dist/api/openai-codex-responses.lazy.d.ts +3 -0
  82. package/dist/api/openai-codex-responses.lazy.d.ts.map +1 -0
  83. package/dist/api/openai-codex-responses.lazy.js +3 -0
  84. package/dist/api/openai-codex-responses.lazy.js.map +1 -0
  85. package/dist/api/openai-completions.d.ts +22 -0
  86. package/dist/api/openai-completions.d.ts.map +1 -0
  87. package/dist/api/openai-completions.js +1279 -0
  88. package/dist/api/openai-completions.js.map +1 -0
  89. package/dist/api/openai-completions.lazy.d.ts +3 -0
  90. package/dist/api/openai-completions.lazy.d.ts.map +1 -0
  91. package/dist/api/openai-completions.lazy.js +3 -0
  92. package/dist/api/openai-completions.lazy.js.map +1 -0
  93. package/dist/api/openai-prompt-cache.d.ts +3 -0
  94. package/dist/api/openai-prompt-cache.d.ts.map +1 -0
  95. package/dist/api/openai-prompt-cache.js +10 -0
  96. package/dist/api/openai-prompt-cache.js.map +1 -0
  97. package/dist/api/openai-responses-shared.d.ts +26 -0
  98. package/dist/api/openai-responses-shared.d.ts.map +1 -0
  99. package/dist/api/openai-responses-shared.js +686 -0
  100. package/dist/api/openai-responses-shared.js.map +1 -0
  101. package/dist/api/openai-responses.d.ts +14 -0
  102. package/dist/api/openai-responses.d.ts.map +1 -0
  103. package/dist/api/openai-responses.js +283 -0
  104. package/dist/api/openai-responses.js.map +1 -0
  105. package/dist/api/openai-responses.lazy.d.ts +3 -0
  106. package/dist/api/openai-responses.lazy.d.ts.map +1 -0
  107. package/dist/api/openai-responses.lazy.js +3 -0
  108. package/dist/api/openai-responses.lazy.js.map +1 -0
  109. package/dist/api/openrouter-images.d.ts +3 -0
  110. package/dist/api/openrouter-images.d.ts.map +1 -0
  111. package/dist/api/openrouter-images.js +132 -0
  112. package/dist/api/openrouter-images.js.map +1 -0
  113. package/dist/api/openrouter-images.lazy.d.ts +3 -0
  114. package/dist/api/openrouter-images.lazy.d.ts.map +1 -0
  115. package/dist/api/openrouter-images.lazy.js +4 -0
  116. package/dist/api/openrouter-images.lazy.js.map +1 -0
  117. package/dist/api/pi-messages.d.ts +97 -0
  118. package/dist/api/pi-messages.d.ts.map +1 -0
  119. package/dist/api/pi-messages.js +307 -0
  120. package/dist/api/pi-messages.js.map +1 -0
  121. package/dist/api/pi-messages.lazy.d.ts +3 -0
  122. package/dist/api/pi-messages.lazy.d.ts.map +1 -0
  123. package/dist/api/pi-messages.lazy.js +3 -0
  124. package/dist/api/pi-messages.lazy.js.map +1 -0
  125. package/dist/api/simple-options.d.ts +11 -0
  126. package/dist/api/simple-options.d.ts.map +1 -0
  127. package/dist/api/simple-options.js +59 -0
  128. package/dist/api/simple-options.js.map +1 -0
  129. package/dist/api/transform-messages.d.ts +8 -0
  130. package/dist/api/transform-messages.d.ts.map +1 -0
  131. package/dist/api/transform-messages.js +187 -0
  132. package/dist/api/transform-messages.js.map +1 -0
  133. package/dist/auth/context.d.ts +7 -0
  134. package/dist/auth/context.d.ts.map +1 -0
  135. package/dist/auth/context.js +42 -0
  136. package/dist/auth/context.js.map +1 -0
  137. package/dist/auth/credential-store.d.ts +17 -0
  138. package/dist/auth/credential-store.d.ts.map +1 -0
  139. package/dist/auth/credential-store.js +51 -0
  140. package/dist/auth/credential-store.js.map +1 -0
  141. package/dist/auth/helpers.d.ts +22 -0
  142. package/dist/auth/helpers.d.ts.map +1 -0
  143. package/dist/auth/helpers.js +53 -0
  144. package/dist/auth/helpers.js.map +1 -0
  145. package/dist/auth/oauth/anthropic.d.ts +9 -0
  146. package/dist/auth/oauth/anthropic.d.ts.map +1 -0
  147. package/dist/auth/oauth/anthropic.js +308 -0
  148. package/dist/auth/oauth/anthropic.js.map +1 -0
  149. package/dist/auth/oauth/device-code.d.ts +23 -0
  150. package/dist/auth/oauth/device-code.d.ts.map +1 -0
  151. package/dist/auth/oauth/device-code.js +69 -0
  152. package/dist/auth/oauth/device-code.js.map +1 -0
  153. package/dist/auth/oauth/github-copilot.d.ts +6 -0
  154. package/dist/auth/oauth/github-copilot.d.ts.map +1 -0
  155. package/dist/auth/oauth/github-copilot.js +328 -0
  156. package/dist/auth/oauth/github-copilot.js.map +1 -0
  157. package/dist/auth/oauth/kimi-coding.d.ts +10 -0
  158. package/dist/auth/oauth/kimi-coding.d.ts.map +1 -0
  159. package/dist/auth/oauth/kimi-coding.js +261 -0
  160. package/dist/auth/oauth/kimi-coding.js.map +1 -0
  161. package/dist/auth/oauth/load.d.ts +27 -0
  162. package/dist/auth/oauth/load.d.ts.map +1 -0
  163. package/dist/auth/oauth/load.js +59 -0
  164. package/dist/auth/oauth/load.js.map +1 -0
  165. package/dist/auth/oauth/oauth-page.d.ts +3 -0
  166. package/dist/auth/oauth/oauth-page.d.ts.map +1 -0
  167. package/dist/auth/oauth/oauth-page.js +105 -0
  168. package/dist/auth/oauth/oauth-page.js.map +1 -0
  169. package/dist/auth/oauth/openai-codex.d.ts +9 -0
  170. package/dist/auth/oauth/openai-codex.d.ts.map +1 -0
  171. package/dist/auth/oauth/openai-codex.js +450 -0
  172. package/dist/auth/oauth/openai-codex.js.map +1 -0
  173. package/dist/auth/oauth/openrouter.d.ts +15 -0
  174. package/dist/auth/oauth/openrouter.d.ts.map +1 -0
  175. package/dist/auth/oauth/openrouter.js +277 -0
  176. package/dist/auth/oauth/openrouter.js.map +1 -0
  177. package/dist/auth/oauth/pkce.d.ts +13 -0
  178. package/dist/auth/oauth/pkce.d.ts.map +1 -0
  179. package/dist/auth/oauth/pkce.js +31 -0
  180. package/dist/auth/oauth/pkce.js.map +1 -0
  181. package/dist/auth/oauth/radius.d.ts +17 -0
  182. package/dist/auth/oauth/radius.d.ts.map +1 -0
  183. package/dist/auth/oauth/radius.js +321 -0
  184. package/dist/auth/oauth/radius.js.map +1 -0
  185. package/dist/auth/oauth/xai.d.ts +6 -0
  186. package/dist/auth/oauth/xai.d.ts.map +1 -0
  187. package/dist/auth/oauth/xai.js +190 -0
  188. package/dist/auth/oauth/xai.js.map +1 -0
  189. package/dist/auth/resolve.d.ts +27 -0
  190. package/dist/auth/resolve.d.ts.map +1 -0
  191. package/dist/auth/resolve.js +132 -0
  192. package/dist/auth/resolve.js.map +1 -0
  193. package/dist/auth/types.d.ts +231 -0
  194. package/dist/auth/types.d.ts.map +1 -0
  195. package/dist/auth/types.js +2 -0
  196. package/dist/auth/types.js.map +1 -0
  197. package/dist/bedrock-provider.d.ts +5 -0
  198. package/dist/bedrock-provider.d.ts.map +1 -0
  199. package/dist/bedrock-provider.js +6 -0
  200. package/dist/bedrock-provider.js.map +1 -0
  201. package/dist/bun-oauth.d.ts +3 -0
  202. package/dist/bun-oauth.d.ts.map +1 -0
  203. package/dist/bun-oauth.js +21 -0
  204. package/dist/bun-oauth.js.map +1 -0
  205. package/dist/cli.d.ts +3 -0
  206. package/dist/cli.d.ts.map +1 -0
  207. package/dist/cli.js +113 -0
  208. package/dist/cli.js.map +1 -0
  209. package/dist/compat/extension-oauth-types.d.ts +39 -0
  210. package/dist/compat/extension-oauth-types.d.ts.map +1 -0
  211. package/dist/compat/extension-oauth-types.js +2 -0
  212. package/dist/compat/extension-oauth-types.js.map +1 -0
  213. package/dist/compat.d.ts +67 -0
  214. package/dist/compat.d.ts.map +1 -0
  215. package/dist/compat.js +199 -0
  216. package/dist/compat.js.map +1 -0
  217. package/dist/env-api-keys.d.ts +21 -0
  218. package/dist/env-api-keys.d.ts.map +1 -0
  219. package/dist/env-api-keys.js +156 -0
  220. package/dist/env-api-keys.js.map +1 -0
  221. package/dist/image-models.d.ts +10 -0
  222. package/dist/image-models.d.ts.map +1 -0
  223. package/dist/image-models.generated.d.ts +680 -0
  224. package/dist/image-models.generated.d.ts.map +1 -0
  225. package/dist/image-models.generated.js +682 -0
  226. package/dist/image-models.generated.js.map +1 -0
  227. package/dist/image-models.js +23 -0
  228. package/dist/image-models.js.map +1 -0
  229. package/dist/images-api-registry.d.ts +14 -0
  230. package/dist/images-api-registry.d.ts.map +1 -0
  231. package/dist/images-api-registry.js +22 -0
  232. package/dist/images-api-registry.js.map +1 -0
  233. package/dist/images-models.d.ts +95 -0
  234. package/dist/images-models.d.ts.map +1 -0
  235. package/dist/images-models.js +143 -0
  236. package/dist/images-models.js.map +1 -0
  237. package/dist/images.d.ts +4 -0
  238. package/dist/images.d.ts.map +1 -0
  239. package/dist/images.js +14 -0
  240. package/dist/images.js.map +1 -0
  241. package/dist/index.d.ts +35 -0
  242. package/dist/index.d.ts.map +1 -0
  243. package/dist/index.js +22 -0
  244. package/dist/index.js.map +1 -0
  245. package/dist/legacy-api-aliases.d.ts +42 -0
  246. package/dist/legacy-api-aliases.d.ts.map +1 -0
  247. package/dist/legacy-api-aliases.js +49 -0
  248. package/dist/legacy-api-aliases.js.map +1 -0
  249. package/dist/model-catalog.d.ts +17 -0
  250. package/dist/model-catalog.d.ts.map +1 -0
  251. package/dist/model-catalog.js +4 -0
  252. package/dist/model-catalog.js.map +1 -0
  253. package/dist/models-store.d.ts +29 -0
  254. package/dist/models-store.d.ts.map +1 -0
  255. package/dist/models-store.js +17 -0
  256. package/dist/models-store.js.map +1 -0
  257. package/dist/models.d.ts +200 -0
  258. package/dist/models.d.ts.map +1 -0
  259. package/dist/models.generated.d.ts +81 -0
  260. package/dist/models.generated.d.ts.map +1 -0
  261. package/dist/models.generated.js +83 -0
  262. package/dist/models.generated.js.map +1 -0
  263. package/dist/models.js +588 -0
  264. package/dist/models.js.map +1 -0
  265. package/dist/oauth.d.ts +3 -0
  266. package/dist/oauth.d.ts.map +1 -0
  267. package/dist/oauth.js +2 -0
  268. package/dist/oauth.js.map +1 -0
  269. package/dist/providers/all.d.ts +28 -0
  270. package/dist/providers/all.d.ts.map +1 -0
  271. package/dist/providers/all.js +131 -0
  272. package/dist/providers/all.js.map +1 -0
  273. package/dist/providers/amazon-bedrock.d.ts +3 -0
  274. package/dist/providers/amazon-bedrock.d.ts.map +1 -0
  275. package/dist/providers/amazon-bedrock.js +93 -0
  276. package/dist/providers/amazon-bedrock.js.map +1 -0
  277. package/dist/providers/amazon-bedrock.models.d.ts +4 -0
  278. package/dist/providers/amazon-bedrock.models.d.ts.map +1 -0
  279. package/dist/providers/amazon-bedrock.models.js +6 -0
  280. package/dist/providers/amazon-bedrock.models.js.map +1 -0
  281. package/dist/providers/ant-ling.d.ts +3 -0
  282. package/dist/providers/ant-ling.d.ts.map +1 -0
  283. package/dist/providers/ant-ling.js +15 -0
  284. package/dist/providers/ant-ling.js.map +1 -0
  285. package/dist/providers/ant-ling.models.d.ts +4 -0
  286. package/dist/providers/ant-ling.models.d.ts.map +1 -0
  287. package/dist/providers/ant-ling.models.js +6 -0
  288. package/dist/providers/ant-ling.models.js.map +1 -0
  289. package/dist/providers/anthropic.d.ts +3 -0
  290. package/dist/providers/anthropic.d.ts.map +1 -0
  291. package/dist/providers/anthropic.js +56 -0
  292. package/dist/providers/anthropic.js.map +1 -0
  293. package/dist/providers/anthropic.models.d.ts +4 -0
  294. package/dist/providers/anthropic.models.d.ts.map +1 -0
  295. package/dist/providers/anthropic.models.js +6 -0
  296. package/dist/providers/anthropic.models.js.map +1 -0
  297. package/dist/providers/azure-openai-responses.d.ts +3 -0
  298. package/dist/providers/azure-openai-responses.d.ts.map +1 -0
  299. package/dist/providers/azure-openai-responses.js +14 -0
  300. package/dist/providers/azure-openai-responses.js.map +1 -0
  301. package/dist/providers/azure-openai-responses.models.d.ts +4 -0
  302. package/dist/providers/azure-openai-responses.models.d.ts.map +1 -0
  303. package/dist/providers/azure-openai-responses.models.js +6 -0
  304. package/dist/providers/azure-openai-responses.models.js.map +1 -0
  305. package/dist/providers/baseten.d.ts +3 -0
  306. package/dist/providers/baseten.d.ts.map +1 -0
  307. package/dist/providers/baseten.js +15 -0
  308. package/dist/providers/baseten.js.map +1 -0
  309. package/dist/providers/baseten.models.d.ts +4 -0
  310. package/dist/providers/baseten.models.d.ts.map +1 -0
  311. package/dist/providers/baseten.models.js +6 -0
  312. package/dist/providers/baseten.models.js.map +1 -0
  313. package/dist/providers/cerebras.d.ts +3 -0
  314. package/dist/providers/cerebras.d.ts.map +1 -0
  315. package/dist/providers/cerebras.js +15 -0
  316. package/dist/providers/cerebras.js.map +1 -0
  317. package/dist/providers/cerebras.models.d.ts +4 -0
  318. package/dist/providers/cerebras.models.d.ts.map +1 -0
  319. package/dist/providers/cerebras.models.js +6 -0
  320. package/dist/providers/cerebras.models.js.map +1 -0
  321. package/dist/providers/cloudflare-ai-gateway.d.ts +3 -0
  322. package/dist/providers/cloudflare-ai-gateway.d.ts.map +1 -0
  323. package/dist/providers/cloudflare-ai-gateway.js +21 -0
  324. package/dist/providers/cloudflare-ai-gateway.js.map +1 -0
  325. package/dist/providers/cloudflare-ai-gateway.models.d.ts +4 -0
  326. package/dist/providers/cloudflare-ai-gateway.models.d.ts.map +1 -0
  327. package/dist/providers/cloudflare-ai-gateway.models.js +6 -0
  328. package/dist/providers/cloudflare-ai-gateway.models.js.map +1 -0
  329. package/dist/providers/cloudflare-auth.d.ts +4 -0
  330. package/dist/providers/cloudflare-auth.d.ts.map +1 -0
  331. package/dist/providers/cloudflare-auth.js +86 -0
  332. package/dist/providers/cloudflare-auth.js.map +1 -0
  333. package/dist/providers/cloudflare-stream.d.ts +8 -0
  334. package/dist/providers/cloudflare-stream.d.ts.map +1 -0
  335. package/dist/providers/cloudflare-stream.js +21 -0
  336. package/dist/providers/cloudflare-stream.js.map +1 -0
  337. package/dist/providers/cloudflare-workers-ai.d.ts +3 -0
  338. package/dist/providers/cloudflare-workers-ai.d.ts.map +1 -0
  339. package/dist/providers/cloudflare-workers-ai.js +15 -0
  340. package/dist/providers/cloudflare-workers-ai.js.map +1 -0
  341. package/dist/providers/cloudflare-workers-ai.models.d.ts +4 -0
  342. package/dist/providers/cloudflare-workers-ai.models.d.ts.map +1 -0
  343. package/dist/providers/cloudflare-workers-ai.models.js +6 -0
  344. package/dist/providers/cloudflare-workers-ai.models.js.map +1 -0
  345. package/dist/providers/data/.manifest.json +1 -0
  346. package/dist/providers/data/amazon-bedrock.json +1 -0
  347. package/dist/providers/data/ant-ling.json +1 -0
  348. package/dist/providers/data/anthropic.json +1 -0
  349. package/dist/providers/data/azure-openai-responses.json +1 -0
  350. package/dist/providers/data/baseten.json +1 -0
  351. package/dist/providers/data/cerebras.json +1 -0
  352. package/dist/providers/data/cloudflare-ai-gateway.json +1 -0
  353. package/dist/providers/data/cloudflare-workers-ai.json +1 -0
  354. package/dist/providers/data/deepseek.json +1 -0
  355. package/dist/providers/data/fireworks.json +1 -0
  356. package/dist/providers/data/github-copilot.json +1 -0
  357. package/dist/providers/data/google-vertex.json +1 -0
  358. package/dist/providers/data/google.json +1 -0
  359. package/dist/providers/data/groq.json +1 -0
  360. package/dist/providers/data/huggingface.json +1 -0
  361. package/dist/providers/data/kimi-coding.json +1 -0
  362. package/dist/providers/data/minimax-cn.json +1 -0
  363. package/dist/providers/data/minimax.json +1 -0
  364. package/dist/providers/data/mistral.json +1 -0
  365. package/dist/providers/data/moonshotai-cn.json +1 -0
  366. package/dist/providers/data/moonshotai.json +1 -0
  367. package/dist/providers/data/nvidia.json +1 -0
  368. package/dist/providers/data/openai-codex.json +1 -0
  369. package/dist/providers/data/openai.json +1 -0
  370. package/dist/providers/data/opencode-go.json +1 -0
  371. package/dist/providers/data/opencode.json +1 -0
  372. package/dist/providers/data/openrouter.json +1 -0
  373. package/dist/providers/data/qwen-token-plan-cn.json +1 -0
  374. package/dist/providers/data/qwen-token-plan-individual.json +1 -0
  375. package/dist/providers/data/qwen-token-plan.json +1 -0
  376. package/dist/providers/data/together.json +1 -0
  377. package/dist/providers/data/vercel-ai-gateway.json +1 -0
  378. package/dist/providers/data/xai.json +1 -0
  379. package/dist/providers/data/xiaomi-token-plan-ams.json +1 -0
  380. package/dist/providers/data/xiaomi-token-plan-cn.json +1 -0
  381. package/dist/providers/data/xiaomi-token-plan-sgp.json +1 -0
  382. package/dist/providers/data/xiaomi.json +1 -0
  383. package/dist/providers/data/zai-coding-cn.json +1 -0
  384. package/dist/providers/data/zai.json +1 -0
  385. package/dist/providers/deepseek.d.ts +3 -0
  386. package/dist/providers/deepseek.d.ts.map +1 -0
  387. package/dist/providers/deepseek.js +15 -0
  388. package/dist/providers/deepseek.js.map +1 -0
  389. package/dist/providers/deepseek.models.d.ts +4 -0
  390. package/dist/providers/deepseek.models.d.ts.map +1 -0
  391. package/dist/providers/deepseek.models.js +6 -0
  392. package/dist/providers/deepseek.models.js.map +1 -0
  393. package/dist/providers/faux.d.ts +102 -0
  394. package/dist/providers/faux.d.ts.map +1 -0
  395. package/dist/providers/faux.js +488 -0
  396. package/dist/providers/faux.js.map +1 -0
  397. package/dist/providers/fireworks.d.ts +3 -0
  398. package/dist/providers/fireworks.d.ts.map +1 -0
  399. package/dist/providers/fireworks.js +19 -0
  400. package/dist/providers/fireworks.js.map +1 -0
  401. package/dist/providers/fireworks.models.d.ts +4 -0
  402. package/dist/providers/fireworks.models.d.ts.map +1 -0
  403. package/dist/providers/fireworks.models.js +6 -0
  404. package/dist/providers/fireworks.models.js.map +1 -0
  405. package/dist/providers/github-copilot.d.ts +3 -0
  406. package/dist/providers/github-copilot.d.ts.map +1 -0
  407. package/dist/providers/github-copilot.js +35 -0
  408. package/dist/providers/github-copilot.js.map +1 -0
  409. package/dist/providers/github-copilot.models.d.ts +4 -0
  410. package/dist/providers/github-copilot.models.d.ts.map +1 -0
  411. package/dist/providers/github-copilot.models.js +6 -0
  412. package/dist/providers/github-copilot.models.js.map +1 -0
  413. package/dist/providers/google-vertex.d.ts +3 -0
  414. package/dist/providers/google-vertex.d.ts.map +1 -0
  415. package/dist/providers/google-vertex.js +94 -0
  416. package/dist/providers/google-vertex.js.map +1 -0
  417. package/dist/providers/google-vertex.models.d.ts +4 -0
  418. package/dist/providers/google-vertex.models.d.ts.map +1 -0
  419. package/dist/providers/google-vertex.models.js +6 -0
  420. package/dist/providers/google-vertex.models.js.map +1 -0
  421. package/dist/providers/google.d.ts +3 -0
  422. package/dist/providers/google.d.ts.map +1 -0
  423. package/dist/providers/google.js +15 -0
  424. package/dist/providers/google.js.map +1 -0
  425. package/dist/providers/google.models.d.ts +4 -0
  426. package/dist/providers/google.models.d.ts.map +1 -0
  427. package/dist/providers/google.models.js +6 -0
  428. package/dist/providers/google.models.js.map +1 -0
  429. package/dist/providers/groq.d.ts +3 -0
  430. package/dist/providers/groq.d.ts.map +1 -0
  431. package/dist/providers/groq.js +15 -0
  432. package/dist/providers/groq.js.map +1 -0
  433. package/dist/providers/groq.models.d.ts +4 -0
  434. package/dist/providers/groq.models.d.ts.map +1 -0
  435. package/dist/providers/groq.models.js +6 -0
  436. package/dist/providers/groq.models.js.map +1 -0
  437. package/dist/providers/huggingface.d.ts +3 -0
  438. package/dist/providers/huggingface.d.ts.map +1 -0
  439. package/dist/providers/huggingface.js +15 -0
  440. package/dist/providers/huggingface.js.map +1 -0
  441. package/dist/providers/huggingface.models.d.ts +4 -0
  442. package/dist/providers/huggingface.models.d.ts.map +1 -0
  443. package/dist/providers/huggingface.models.js +6 -0
  444. package/dist/providers/huggingface.models.js.map +1 -0
  445. package/dist/providers/images/register-builtins.d.ts +4 -0
  446. package/dist/providers/images/register-builtins.d.ts.map +1 -0
  447. package/dist/providers/images/register-builtins.js +34 -0
  448. package/dist/providers/images/register-builtins.js.map +1 -0
  449. package/dist/providers/kimi-coding.d.ts +3 -0
  450. package/dist/providers/kimi-coding.d.ts.map +1 -0
  451. package/dist/providers/kimi-coding.js +24 -0
  452. package/dist/providers/kimi-coding.js.map +1 -0
  453. package/dist/providers/kimi-coding.models.d.ts +4 -0
  454. package/dist/providers/kimi-coding.models.d.ts.map +1 -0
  455. package/dist/providers/kimi-coding.models.js +6 -0
  456. package/dist/providers/kimi-coding.models.js.map +1 -0
  457. package/dist/providers/minimax-cn.d.ts +3 -0
  458. package/dist/providers/minimax-cn.d.ts.map +1 -0
  459. package/dist/providers/minimax-cn.js +15 -0
  460. package/dist/providers/minimax-cn.js.map +1 -0
  461. package/dist/providers/minimax-cn.models.d.ts +4 -0
  462. package/dist/providers/minimax-cn.models.d.ts.map +1 -0
  463. package/dist/providers/minimax-cn.models.js +6 -0
  464. package/dist/providers/minimax-cn.models.js.map +1 -0
  465. package/dist/providers/minimax.d.ts +3 -0
  466. package/dist/providers/minimax.d.ts.map +1 -0
  467. package/dist/providers/minimax.js +15 -0
  468. package/dist/providers/minimax.js.map +1 -0
  469. package/dist/providers/minimax.models.d.ts +4 -0
  470. package/dist/providers/minimax.models.d.ts.map +1 -0
  471. package/dist/providers/minimax.models.js +6 -0
  472. package/dist/providers/minimax.models.js.map +1 -0
  473. package/dist/providers/mistral.d.ts +3 -0
  474. package/dist/providers/mistral.d.ts.map +1 -0
  475. package/dist/providers/mistral.js +15 -0
  476. package/dist/providers/mistral.js.map +1 -0
  477. package/dist/providers/mistral.models.d.ts +4 -0
  478. package/dist/providers/mistral.models.d.ts.map +1 -0
  479. package/dist/providers/mistral.models.js +6 -0
  480. package/dist/providers/mistral.models.js.map +1 -0
  481. package/dist/providers/moonshotai-cn.d.ts +3 -0
  482. package/dist/providers/moonshotai-cn.d.ts.map +1 -0
  483. package/dist/providers/moonshotai-cn.js +15 -0
  484. package/dist/providers/moonshotai-cn.js.map +1 -0
  485. package/dist/providers/moonshotai-cn.models.d.ts +4 -0
  486. package/dist/providers/moonshotai-cn.models.d.ts.map +1 -0
  487. package/dist/providers/moonshotai-cn.models.js +6 -0
  488. package/dist/providers/moonshotai-cn.models.js.map +1 -0
  489. package/dist/providers/moonshotai.d.ts +3 -0
  490. package/dist/providers/moonshotai.d.ts.map +1 -0
  491. package/dist/providers/moonshotai.js +15 -0
  492. package/dist/providers/moonshotai.js.map +1 -0
  493. package/dist/providers/moonshotai.models.d.ts +4 -0
  494. package/dist/providers/moonshotai.models.d.ts.map +1 -0
  495. package/dist/providers/moonshotai.models.js +6 -0
  496. package/dist/providers/moonshotai.models.js.map +1 -0
  497. package/dist/providers/nvidia.d.ts +3 -0
  498. package/dist/providers/nvidia.d.ts.map +1 -0
  499. package/dist/providers/nvidia.js +15 -0
  500. package/dist/providers/nvidia.js.map +1 -0
  501. package/dist/providers/nvidia.models.d.ts +4 -0
  502. package/dist/providers/nvidia.models.d.ts.map +1 -0
  503. package/dist/providers/nvidia.models.js +6 -0
  504. package/dist/providers/nvidia.models.js.map +1 -0
  505. package/dist/providers/openai-codex.d.ts +3 -0
  506. package/dist/providers/openai-codex.d.ts.map +1 -0
  507. package/dist/providers/openai-codex.js +22 -0
  508. package/dist/providers/openai-codex.js.map +1 -0
  509. package/dist/providers/openai-codex.models.d.ts +4 -0
  510. package/dist/providers/openai-codex.models.d.ts.map +1 -0
  511. package/dist/providers/openai-codex.models.js +6 -0
  512. package/dist/providers/openai-codex.models.js.map +1 -0
  513. package/dist/providers/openai.d.ts +3 -0
  514. package/dist/providers/openai.d.ts.map +1 -0
  515. package/dist/providers/openai.js +15 -0
  516. package/dist/providers/openai.js.map +1 -0
  517. package/dist/providers/openai.models.d.ts +4 -0
  518. package/dist/providers/openai.models.d.ts.map +1 -0
  519. package/dist/providers/openai.models.js +6 -0
  520. package/dist/providers/openai.models.js.map +1 -0
  521. package/dist/providers/opencode-go.d.ts +3 -0
  522. package/dist/providers/opencode-go.d.ts.map +1 -0
  523. package/dist/providers/opencode-go.js +20 -0
  524. package/dist/providers/opencode-go.js.map +1 -0
  525. package/dist/providers/opencode-go.models.d.ts +4 -0
  526. package/dist/providers/opencode-go.models.d.ts.map +1 -0
  527. package/dist/providers/opencode-go.models.js +6 -0
  528. package/dist/providers/opencode-go.models.js.map +1 -0
  529. package/dist/providers/opencode.d.ts +3 -0
  530. package/dist/providers/opencode.d.ts.map +1 -0
  531. package/dist/providers/opencode.js +22 -0
  532. package/dist/providers/opencode.js.map +1 -0
  533. package/dist/providers/opencode.models.d.ts +4 -0
  534. package/dist/providers/opencode.models.d.ts.map +1 -0
  535. package/dist/providers/opencode.models.js +6 -0
  536. package/dist/providers/opencode.models.js.map +1 -0
  537. package/dist/providers/openrouter-images.d.ts +3 -0
  538. package/dist/providers/openrouter-images.d.ts.map +1 -0
  539. package/dist/providers/openrouter-images.js +22 -0
  540. package/dist/providers/openrouter-images.js.map +1 -0
  541. package/dist/providers/openrouter.d.ts +3 -0
  542. package/dist/providers/openrouter.d.ts.map +1 -0
  543. package/dist/providers/openrouter.js +23 -0
  544. package/dist/providers/openrouter.js.map +1 -0
  545. package/dist/providers/openrouter.models.d.ts +4 -0
  546. package/dist/providers/openrouter.models.d.ts.map +1 -0
  547. package/dist/providers/openrouter.models.js +6 -0
  548. package/dist/providers/openrouter.models.js.map +1 -0
  549. package/dist/providers/qwen-token-plan-cn.d.ts +3 -0
  550. package/dist/providers/qwen-token-plan-cn.d.ts.map +1 -0
  551. package/dist/providers/qwen-token-plan-cn.js +15 -0
  552. package/dist/providers/qwen-token-plan-cn.js.map +1 -0
  553. package/dist/providers/qwen-token-plan-cn.models.d.ts +4 -0
  554. package/dist/providers/qwen-token-plan-cn.models.d.ts.map +1 -0
  555. package/dist/providers/qwen-token-plan-cn.models.js +6 -0
  556. package/dist/providers/qwen-token-plan-cn.models.js.map +1 -0
  557. package/dist/providers/qwen-token-plan-individual.d.ts +3 -0
  558. package/dist/providers/qwen-token-plan-individual.d.ts.map +1 -0
  559. package/dist/providers/qwen-token-plan-individual.js +15 -0
  560. package/dist/providers/qwen-token-plan-individual.js.map +1 -0
  561. package/dist/providers/qwen-token-plan-individual.models.d.ts +4 -0
  562. package/dist/providers/qwen-token-plan-individual.models.d.ts.map +1 -0
  563. package/dist/providers/qwen-token-plan-individual.models.js +6 -0
  564. package/dist/providers/qwen-token-plan-individual.models.js.map +1 -0
  565. package/dist/providers/qwen-token-plan.d.ts +3 -0
  566. package/dist/providers/qwen-token-plan.d.ts.map +1 -0
  567. package/dist/providers/qwen-token-plan.js +15 -0
  568. package/dist/providers/qwen-token-plan.js.map +1 -0
  569. package/dist/providers/qwen-token-plan.models.d.ts +4 -0
  570. package/dist/providers/qwen-token-plan.models.d.ts.map +1 -0
  571. package/dist/providers/qwen-token-plan.models.js +6 -0
  572. package/dist/providers/qwen-token-plan.models.js.map +1 -0
  573. package/dist/providers/radius-config.d.ts +26 -0
  574. package/dist/providers/radius-config.d.ts.map +1 -0
  575. package/dist/providers/radius-config.js +63 -0
  576. package/dist/providers/radius-config.js.map +1 -0
  577. package/dist/providers/radius.d.ts +9 -0
  578. package/dist/providers/radius.d.ts.map +1 -0
  579. package/dist/providers/radius.js +64 -0
  580. package/dist/providers/radius.js.map +1 -0
  581. package/dist/providers/together.d.ts +3 -0
  582. package/dist/providers/together.d.ts.map +1 -0
  583. package/dist/providers/together.js +15 -0
  584. package/dist/providers/together.js.map +1 -0
  585. package/dist/providers/together.models.d.ts +4 -0
  586. package/dist/providers/together.models.d.ts.map +1 -0
  587. package/dist/providers/together.models.js +6 -0
  588. package/dist/providers/together.models.js.map +1 -0
  589. package/dist/providers/vercel-ai-gateway.d.ts +3 -0
  590. package/dist/providers/vercel-ai-gateway.d.ts.map +1 -0
  591. package/dist/providers/vercel-ai-gateway.js +15 -0
  592. package/dist/providers/vercel-ai-gateway.js.map +1 -0
  593. package/dist/providers/vercel-ai-gateway.models.d.ts +4 -0
  594. package/dist/providers/vercel-ai-gateway.models.d.ts.map +1 -0
  595. package/dist/providers/vercel-ai-gateway.models.js +6 -0
  596. package/dist/providers/vercel-ai-gateway.models.js.map +1 -0
  597. package/dist/providers/xai.d.ts +3 -0
  598. package/dist/providers/xai.d.ts.map +1 -0
  599. package/dist/providers/xai.js +28 -0
  600. package/dist/providers/xai.js.map +1 -0
  601. package/dist/providers/xai.models.d.ts +4 -0
  602. package/dist/providers/xai.models.d.ts.map +1 -0
  603. package/dist/providers/xai.models.js +6 -0
  604. package/dist/providers/xai.models.js.map +1 -0
  605. package/dist/providers/xiaomi-token-plan-ams.d.ts +3 -0
  606. package/dist/providers/xiaomi-token-plan-ams.d.ts.map +1 -0
  607. package/dist/providers/xiaomi-token-plan-ams.js +15 -0
  608. package/dist/providers/xiaomi-token-plan-ams.js.map +1 -0
  609. package/dist/providers/xiaomi-token-plan-ams.models.d.ts +4 -0
  610. package/dist/providers/xiaomi-token-plan-ams.models.d.ts.map +1 -0
  611. package/dist/providers/xiaomi-token-plan-ams.models.js +6 -0
  612. package/dist/providers/xiaomi-token-plan-ams.models.js.map +1 -0
  613. package/dist/providers/xiaomi-token-plan-cn.d.ts +3 -0
  614. package/dist/providers/xiaomi-token-plan-cn.d.ts.map +1 -0
  615. package/dist/providers/xiaomi-token-plan-cn.js +15 -0
  616. package/dist/providers/xiaomi-token-plan-cn.js.map +1 -0
  617. package/dist/providers/xiaomi-token-plan-cn.models.d.ts +4 -0
  618. package/dist/providers/xiaomi-token-plan-cn.models.d.ts.map +1 -0
  619. package/dist/providers/xiaomi-token-plan-cn.models.js +6 -0
  620. package/dist/providers/xiaomi-token-plan-cn.models.js.map +1 -0
  621. package/dist/providers/xiaomi-token-plan-sgp.d.ts +3 -0
  622. package/dist/providers/xiaomi-token-plan-sgp.d.ts.map +1 -0
  623. package/dist/providers/xiaomi-token-plan-sgp.js +15 -0
  624. package/dist/providers/xiaomi-token-plan-sgp.js.map +1 -0
  625. package/dist/providers/xiaomi-token-plan-sgp.models.d.ts +4 -0
  626. package/dist/providers/xiaomi-token-plan-sgp.models.d.ts.map +1 -0
  627. package/dist/providers/xiaomi-token-plan-sgp.models.js +6 -0
  628. package/dist/providers/xiaomi-token-plan-sgp.models.js.map +1 -0
  629. package/dist/providers/xiaomi.d.ts +3 -0
  630. package/dist/providers/xiaomi.d.ts.map +1 -0
  631. package/dist/providers/xiaomi.js +15 -0
  632. package/dist/providers/xiaomi.js.map +1 -0
  633. package/dist/providers/xiaomi.models.d.ts +4 -0
  634. package/dist/providers/xiaomi.models.d.ts.map +1 -0
  635. package/dist/providers/xiaomi.models.js +6 -0
  636. package/dist/providers/xiaomi.models.js.map +1 -0
  637. package/dist/providers/zai-coding-cn.d.ts +3 -0
  638. package/dist/providers/zai-coding-cn.d.ts.map +1 -0
  639. package/dist/providers/zai-coding-cn.js +15 -0
  640. package/dist/providers/zai-coding-cn.js.map +1 -0
  641. package/dist/providers/zai-coding-cn.models.d.ts +4 -0
  642. package/dist/providers/zai-coding-cn.models.d.ts.map +1 -0
  643. package/dist/providers/zai-coding-cn.models.js +6 -0
  644. package/dist/providers/zai-coding-cn.models.js.map +1 -0
  645. package/dist/providers/zai.d.ts +3 -0
  646. package/dist/providers/zai.d.ts.map +1 -0
  647. package/dist/providers/zai.js +15 -0
  648. package/dist/providers/zai.js.map +1 -0
  649. package/dist/providers/zai.models.d.ts +4 -0
  650. package/dist/providers/zai.models.d.ts.map +1 -0
  651. package/dist/providers/zai.models.js +6 -0
  652. package/dist/providers/zai.models.js.map +1 -0
  653. package/dist/session-resources.d.ts +4 -0
  654. package/dist/session-resources.d.ts.map +1 -0
  655. package/dist/session-resources.js +22 -0
  656. package/dist/session-resources.js.map +1 -0
  657. package/dist/types.d.ts +697 -0
  658. package/dist/types.d.ts.map +1 -0
  659. package/dist/types.js +2 -0
  660. package/dist/types.js.map +1 -0
  661. package/dist/utils/abort-signals.d.ts +6 -0
  662. package/dist/utils/abort-signals.d.ts.map +1 -0
  663. package/dist/utils/abort-signals.js +34 -0
  664. package/dist/utils/abort-signals.js.map +1 -0
  665. package/dist/utils/abort.d.ts +8 -0
  666. package/dist/utils/abort.d.ts.map +1 -0
  667. package/dist/utils/abort.js +49 -0
  668. package/dist/utils/abort.js.map +1 -0
  669. package/dist/utils/deferred-tools.d.ts +9 -0
  670. package/dist/utils/deferred-tools.d.ts.map +1 -0
  671. package/dist/utils/deferred-tools.js +36 -0
  672. package/dist/utils/deferred-tools.js.map +1 -0
  673. package/dist/utils/diagnostics.d.ts +19 -0
  674. package/dist/utils/diagnostics.d.ts.map +1 -0
  675. package/dist/utils/diagnostics.js +25 -0
  676. package/dist/utils/diagnostics.js.map +1 -0
  677. package/dist/utils/error-body.d.ts +25 -0
  678. package/dist/utils/error-body.d.ts.map +1 -0
  679. package/dist/utils/error-body.js +133 -0
  680. package/dist/utils/error-body.js.map +1 -0
  681. package/dist/utils/estimate.d.ts +17 -0
  682. package/dist/utils/estimate.d.ts.map +1 -0
  683. package/dist/utils/estimate.js +116 -0
  684. package/dist/utils/estimate.js.map +1 -0
  685. package/dist/utils/event-stream.d.ts +21 -0
  686. package/dist/utils/event-stream.d.ts.map +1 -0
  687. package/dist/utils/event-stream.js +81 -0
  688. package/dist/utils/event-stream.js.map +1 -0
  689. package/dist/utils/hash.d.ts +3 -0
  690. package/dist/utils/hash.d.ts.map +1 -0
  691. package/dist/utils/hash.js +14 -0
  692. package/dist/utils/hash.js.map +1 -0
  693. package/dist/utils/headers.d.ts +4 -0
  694. package/dist/utils/headers.d.ts.map +1 -0
  695. package/dist/utils/headers.js +18 -0
  696. package/dist/utils/headers.js.map +1 -0
  697. package/dist/utils/json-parse.d.ts +16 -0
  698. package/dist/utils/json-parse.d.ts.map +1 -0
  699. package/dist/utils/json-parse.js +113 -0
  700. package/dist/utils/json-parse.js.map +1 -0
  701. package/dist/utils/node-http-proxy.d.ts +4 -0
  702. package/dist/utils/node-http-proxy.d.ts.map +1 -0
  703. package/dist/utils/node-http-proxy.js +92 -0
  704. package/dist/utils/node-http-proxy.js.map +1 -0
  705. package/dist/utils/overflow.d.ts +68 -0
  706. package/dist/utils/overflow.d.ts.map +1 -0
  707. package/dist/utils/overflow.js +172 -0
  708. package/dist/utils/overflow.js.map +1 -0
  709. package/dist/utils/pi-user-agent.d.ts +2 -0
  710. package/dist/utils/pi-user-agent.d.ts.map +1 -0
  711. package/dist/utils/pi-user-agent.js +12 -0
  712. package/dist/utils/pi-user-agent.js.map +1 -0
  713. package/dist/utils/provider-env.d.ts +7 -0
  714. package/dist/utils/provider-env.d.ts.map +1 -0
  715. package/dist/utils/provider-env.js +44 -0
  716. package/dist/utils/provider-env.js.map +1 -0
  717. package/dist/utils/provider-retry.d.ts +16 -0
  718. package/dist/utils/provider-retry.d.ts.map +1 -0
  719. package/dist/utils/provider-retry.js +94 -0
  720. package/dist/utils/provider-retry.js.map +1 -0
  721. package/dist/utils/retry.d.ts +53 -0
  722. package/dist/utils/retry.d.ts.map +1 -0
  723. package/dist/utils/retry.js +174 -0
  724. package/dist/utils/retry.js.map +1 -0
  725. package/dist/utils/sanitize-unicode.d.ts +22 -0
  726. package/dist/utils/sanitize-unicode.d.ts.map +1 -0
  727. package/dist/utils/sanitize-unicode.js +26 -0
  728. package/dist/utils/sanitize-unicode.js.map +1 -0
  729. package/dist/utils/text.d.ts +6 -0
  730. package/dist/utils/text.d.ts.map +1 -0
  731. package/dist/utils/text.js +10 -0
  732. package/dist/utils/text.js.map +1 -0
  733. package/dist/utils/typebox-helpers.d.ts +17 -0
  734. package/dist/utils/typebox-helpers.d.ts.map +1 -0
  735. package/dist/utils/typebox-helpers.js +21 -0
  736. package/dist/utils/typebox-helpers.js.map +1 -0
  737. package/dist/utils/uuid.d.ts +3 -0
  738. package/dist/utils/uuid.d.ts.map +1 -0
  739. package/dist/utils/uuid.js +46 -0
  740. package/dist/utils/uuid.js.map +1 -0
  741. package/dist/utils/validation.d.ts +18 -0
  742. package/dist/utils/validation.d.ts.map +1 -0
  743. package/dist/utils/validation.js +309 -0
  744. package/dist/utils/validation.js.map +1 -0
  745. package/package.json +122 -0
package/README.md ADDED
@@ -0,0 +1,1672 @@
1
+ # @bastani/pi-ai
2
+
3
+ Bastani-branded fork of [`@earendil-works/pi-ai`](https://www.npmjs.com/package/@earendil-works/pi-ai) from [earendil-works/pi](https://github.com/earendil-works/pi) at **v0.84.2** (`914cf1472e715297caa30db4b9535d534a9eb718`).
4
+
5
+ The public API is a drop-in replacement: install `@bastani/pi-ai` and import from `@bastani/pi-ai` instead of `@earendil-works/pi-ai`. See [NOTICE.md](NOTICE.md). This package lives in the Atomic monorepo and publishes from `.github/workflows/publish.yml`. The first npm version must be published by hand so trusted publishing can be attached.
6
+
7
+ Unified LLM API with provider collections, automatic auth resolution, token and cost tracking, and simple context persistence and hand-off to other models mid-session.
8
+
9
+ **Note**: This library only includes models that support tool calling (function calling), as this is essential for agentic workflows.
10
+
11
+ ## Table of Contents
12
+
13
+ - [Supported Providers](#supported-providers)
14
+ - [Installation](#installation)
15
+ - [Quick Start](#quick-start)
16
+ - [Providers and Models](#providers-and-models)
17
+ - [Provider Factories](#provider-factories)
18
+ - [All Built-in Providers](#all-built-in-providers)
19
+ - [Querying Models](#querying-models)
20
+ - [Static Catalog Reads](#static-catalog-reads)
21
+ - [Dynamic Providers](#dynamic-providers)
22
+ - [Auth](#auth)
23
+ - [How Auth Resolves](#how-auth-resolves)
24
+ - [Transforming Request Headers](#transforming-request-headers)
25
+ - [Credential Store](#credential-store)
26
+ - [Environment Variables](#environment-variables)
27
+ - [Tools](#tools)
28
+ - [Defining Tools](#defining-tools)
29
+ - [Handling Tool Calls](#handling-tool-calls)
30
+ - [Streaming Tool Calls with Partial JSON](#streaming-tool-calls-with-partial-json)
31
+ - [Validating Tool Arguments](#validating-tool-arguments)
32
+ - [Complete Event Reference](#complete-event-reference)
33
+ - [Image Input](#image-input)
34
+ - [Image Generation](#image-generation)
35
+ - [Thinking/Reasoning](#thinkingreasoning)
36
+ - [Unified Interface](#unified-interface-streamsimplecompletesimple)
37
+ - [Provider-Specific Options](#provider-specific-options-streamcomplete)
38
+ - [Streaming Thinking Content](#streaming-thinking-content)
39
+ - [Stop Reasons](#stop-reasons)
40
+ - [Error Handling](#error-handling)
41
+ - [Aborting Requests](#aborting-requests)
42
+ - [Continuing After Abort](#continuing-after-abort)
43
+ - [Debugging Provider Payloads](#debugging-provider-payloads)
44
+ - [Custom Providers](#custom-providers)
45
+ - [createProvider()](#createprovider)
46
+ - [Calling API Implementations Directly](#calling-api-implementations-directly)
47
+ - [OpenAI Compatibility Settings](#openai-compatibility-settings)
48
+ - [Faux Provider for Tests](#faux-provider-for-tests)
49
+ - [Cross-Provider Handoffs](#cross-provider-handoffs)
50
+ - [Context Serialization](#context-serialization)
51
+ - [Browser Usage](#browser-usage)
52
+ - [Bundling and Tree Shaking](#bundling-and-tree-shaking)
53
+ - [OAuth Providers](#oauth-providers)
54
+ - [Vertex AI](#vertex-ai)
55
+ - [CLI Login](#cli-login)
56
+ - [Programmatic OAuth](#programmatic-oauth)
57
+ - [Migrating from the Old Global API](#migrating-from-the-old-global-api)
58
+ - [Development](#development)
59
+ - [License](#license)
60
+
61
+ ## Supported Providers
62
+
63
+ - **OpenAI**
64
+ - **Ant Ling**
65
+ - **Azure OpenAI (Responses)**
66
+ - **OpenAI Codex** (ChatGPT Plus/Pro subscription, requires OAuth, see below)
67
+ - **DeepSeek**
68
+ - **NVIDIA NIM**
69
+ - **Anthropic**
70
+ - **Google**
71
+ - **Vertex AI** (Gemini via Vertex AI)
72
+ - **Mistral**
73
+ - **Groq**
74
+ - **Cerebras**
75
+ - **Cloudflare AI Gateway**
76
+ - **Cloudflare Workers AI**
77
+ - **xAI**
78
+ - **OpenRouter**
79
+ - **Vercel AI Gateway**
80
+ - **ZAI Coding Plan (Global)** (with separate China provider)
81
+ - **MiniMax** (with separate China provider)
82
+ - **Together AI**
83
+ - **Baseten**
84
+ - **Hugging Face**
85
+ - **Moonshot AI** (with separate China provider)
86
+ - **GitHub Copilot** (requires OAuth, see below)
87
+ - **Amazon Bedrock**
88
+ - **OpenCode Zen**
89
+ - **OpenCode Go**
90
+ - **Fireworks** (uses OpenAI- and Anthropic-compatible APIs)
91
+ - **Kimi For Coding** (Moonshot AI subscription endpoint, uses Anthropic-compatible API)
92
+ - **Qwen Token Plan** (separate Individual and existing catalogs, with a separate China provider)
93
+ - **Xiaomi MiMo** (defaults to API billing endpoint, with separate Token Plan providers for `cn`/`ams`/`sgp` regions)
94
+ - **Any OpenAI-compatible API**: Ollama, vLLM, LM Studio, etc.
95
+
96
+ ## Installation
97
+
98
+ ```bash
99
+ npm install @bastani/pi-ai
100
+ ```
101
+
102
+ TypeBox exports are re-exported from `@bastani/pi-ai`: `Type`, `Static`, and `TSchema`.
103
+
104
+ ## Quick Start
105
+
106
+ You build a `Models` collection of providers and stream through it. The quickest start registers every built-in provider; apps that care about bundle size register individual providers instead (see [Provider Factories](#provider-factories) and [Bundling and Tree Shaking](#bundling-and-tree-shaking)).
107
+
108
+ ```typescript
109
+ import { Type, type Context, type Tool } from '@bastani/pi-ai';
110
+ import { builtinModels } from '@bastani/pi-ai/providers/all';
111
+
112
+ // A Models collection with every built-in provider registered
113
+ const models = builtinModels();
114
+
115
+ // Sync lookup against the collection
116
+ const model = models.getModel('openai', 'gpt-4o-mini')!;
117
+
118
+ // Define tools with TypeBox schemas for type safety and validation
119
+ const tools: Tool[] = [{
120
+ name: 'get_time',
121
+ description: 'Get the current time',
122
+ parameters: Type.Object({
123
+ timezone: Type.Optional(Type.String({ description: 'Optional timezone (e.g., America/New_York)' }))
124
+ })
125
+ }];
126
+
127
+ // Build a conversation context (easily serializable and transferable between models)
128
+ const context: Context = {
129
+ systemPrompt: 'You are a helpful assistant.',
130
+ messages: [{ role: 'user', content: 'What time is it?', timestamp: Date.now() }],
131
+ tools
132
+ };
133
+
134
+ // Option 1: Streaming with all event types.
135
+ // Auth resolves through the provider (OPENAI_API_KEY from the environment here).
136
+ const s = models.stream(model, context);
137
+
138
+ for await (const event of s) {
139
+ switch (event.type) {
140
+ case 'start':
141
+ console.log(`Starting with ${event.partial.model}`);
142
+ break;
143
+ case 'text_start':
144
+ console.log('\n[Text started]');
145
+ break;
146
+ case 'text_delta':
147
+ process.stdout.write(event.delta);
148
+ break;
149
+ case 'text_end':
150
+ console.log('\n[Text ended]');
151
+ break;
152
+ case 'thinking_start':
153
+ console.log('[Model is thinking...]');
154
+ break;
155
+ case 'thinking_delta':
156
+ process.stdout.write(event.delta);
157
+ break;
158
+ case 'thinking_end':
159
+ console.log('[Thinking complete]');
160
+ break;
161
+ case 'toolcall_start':
162
+ console.log(`\n[Tool call started: index ${event.contentIndex}]`);
163
+ break;
164
+ case 'toolcall_delta':
165
+ // Partial tool arguments are being streamed
166
+ const partialCall = event.partial.content[event.contentIndex];
167
+ if (partialCall.type === 'toolCall') {
168
+ console.log(`[Streaming args for ${partialCall.name}]`);
169
+ }
170
+ break;
171
+ case 'toolcall_end':
172
+ console.log(`\nTool called: ${event.toolCall.name}`);
173
+ console.log(`Arguments: ${JSON.stringify(event.toolCall.arguments)}`);
174
+ break;
175
+ case 'done':
176
+ console.log(`\nFinished: ${event.reason}`);
177
+ break;
178
+ case 'error':
179
+ console.error(`Error: ${event.error.errorMessage}`);
180
+ break;
181
+ }
182
+ }
183
+
184
+ // Get the final message after streaming, add it to the context
185
+ const finalMessage = await s.result();
186
+ context.messages.push(finalMessage);
187
+
188
+ // Handle tool calls if any
189
+ const toolCalls = finalMessage.content.filter(b => b.type === 'toolCall');
190
+ for (const call of toolCalls) {
191
+ const result = call.name === 'get_time'
192
+ ? new Date().toLocaleString('en-US', {
193
+ timeZone: call.arguments.timezone || 'UTC',
194
+ dateStyle: 'full',
195
+ timeStyle: 'long'
196
+ })
197
+ : 'Unknown tool';
198
+
199
+ // Add tool result to context (supports text and images)
200
+ context.messages.push({
201
+ role: 'toolResult',
202
+ toolCallId: call.id,
203
+ toolName: call.name,
204
+ content: [{ type: 'text', text: result }],
205
+ isError: false,
206
+ timestamp: Date.now()
207
+ });
208
+ }
209
+
210
+ // Continue if there were tool calls
211
+ if (toolCalls.length > 0) {
212
+ const continuation = await models.complete(model, context);
213
+ context.messages.push(continuation);
214
+ console.log('After tool execution:', continuation.content);
215
+ }
216
+
217
+ console.log(`Total tokens: ${finalMessage.usage.input} in, ${finalMessage.usage.output} out`);
218
+ console.log(`Cost: $${finalMessage.usage.cost.total.toFixed(4)}`);
219
+
220
+ // Option 2: Get complete response without streaming
221
+ const response = await models.complete(model, context);
222
+
223
+ for (const block of response.content) {
224
+ if (block.type === 'text') {
225
+ console.log(block.text);
226
+ } else if (block.type === 'toolCall') {
227
+ console.log(`Tool: ${block.name}(${JSON.stringify(block.arguments)})`);
228
+ }
229
+ }
230
+ ```
231
+
232
+ Snippets in the rest of this README assume a `models` collection set up like this (with the relevant providers registered).
233
+
234
+ ## Providers and Models
235
+
236
+ A **provider** is the runtime unit: it owns its model catalog, its auth (API key resolution, OAuth flows), and its stream behavior. A `Models` collection holds providers and routes every request to the provider that owns the model.
237
+
238
+ Providers internally share **API implementations** (the wire protocols): Anthropic models use `anthropic-messages`, OpenAI uses `openai-responses`, while xAI, Groq, Cerebras, OpenRouter, and most others share `openai-completions`. Mixed-API providers (GitHub Copilot, OpenCode Zen) dispatch per model.
239
+
240
+ ### Provider Factories
241
+
242
+ For apps that only need specific providers, there is one factory per built-in provider, each a subpath import that pulls only that provider's catalog:
243
+
244
+ ```typescript
245
+ import { anthropicProvider } from '@bastani/pi-ai/providers/anthropic';
246
+ import { openaiProvider } from '@bastani/pi-ai/providers/openai';
247
+ import { openrouterProvider } from '@bastani/pi-ai/providers/openrouter';
248
+ import { amazonBedrockProvider } from '@bastani/pi-ai/providers/amazon-bedrock';
249
+ // ...one module per provider in the Supported Providers list
250
+
251
+ const models = createModels();
252
+ models.setProvider(anthropicProvider());
253
+ models.setProvider(openrouterProvider());
254
+ ```
255
+
256
+ Provider factories import their model catalog and a lazy API wrapper. They do not import other providers. With bundler code splitting, SDK implementations (`@anthropic-ai/sdk`, `openai`, `@google/genai`, etc.) stay in lazy chunks loaded on the first request to a model of that API.
257
+
258
+ ### All Built-in Providers
259
+
260
+ For apps that want everything (as in Quick Start):
261
+
262
+ ```typescript
263
+ import { builtinModels } from '@bastani/pi-ai/providers/all';
264
+
265
+ const models = builtinModels(); // a Models collection with every built-in provider registered
266
+ ```
267
+
268
+ This imports all catalogs and every built-in provider factory. It is the heavy, explicit entrypoint. `builtinModels()` accepts the same options as `createModels()` (`credentials`, `authContext`); `builtinProviders()` returns the provider array if you want to register them on your own collection.
269
+
270
+ ### Querying Models
271
+
272
+ Reads are synchronous and return the last-known lists:
273
+
274
+ ```typescript
275
+ const providers = models.getProviders(); // registered Provider objects
276
+ const provider = models.getProvider('anthropic'); // one provider
277
+
278
+ const all = models.getModels(); // every model across providers
279
+ const anthropicModels = models.getModels('anthropic');
280
+ const model = models.getModel('anthropic', 'claude-sonnet-4-5');
281
+
282
+ for (const m of anthropicModels) {
283
+ console.log(`${m.id}: ${m.name}`);
284
+ console.log(` API: ${m.api}`);
285
+ console.log(` Context: ${m.contextWindow} tokens`);
286
+ console.log(` Vision: ${m.input.includes('image')}`);
287
+ console.log(` Reasoning: ${m.reasoning}`);
288
+ }
289
+ ```
290
+
291
+ Dynamically listed models are typed `Model<Api>`. Narrow with the `hasApi()` guard when you need API-specific option typing:
292
+
293
+ ```typescript
294
+ import { hasApi } from '@bastani/pi-ai';
295
+
296
+ const m = models.getModel('anthropic', 'claude-sonnet-4-5');
297
+ if (m && hasApi(m, 'anthropic-messages')) {
298
+ // m: Model<'anthropic-messages'> — stream options fully typed
299
+ models.stream(m, context, { thinkingEnabled: true, thinkingBudgetTokens: 2048 });
300
+ }
301
+ ```
302
+
303
+ ### Static Catalog Reads
304
+
305
+ For tooling that wants the generated built-in catalog with full literal typing (provider and model IDs auto-complete), independent of any collection:
306
+
307
+ ```typescript
308
+ import { getBuiltinModel, getBuiltinModels, getBuiltinProviders } from '@bastani/pi-ai/providers/all';
309
+
310
+ const model = getBuiltinModel('openai', 'gpt-4o-mini'); // typed Model<'openai-responses'>
311
+ const providers = getBuiltinProviders();
312
+ const anthropic = getBuiltinModels('anthropic');
313
+ ```
314
+
315
+ ### Dynamic Providers
316
+
317
+ Providers may have dynamic model lists (a llama.cpp server, a live OpenRouter listing). Reads stay sync; fetching is an explicit async verb:
318
+
319
+ ```typescript
320
+ // getModels() returns the last-known list (empty before the first refresh)
321
+ await models.refresh({ providers: ['llamacpp'] }); // refresh one provider
322
+ await models.refresh(); // refresh all providers concurrently, best-effort
323
+ const fresh = models.getModel('llamacpp', 'qwen3-30b');
324
+ ```
325
+
326
+ Static built-in providers are no-ops for `refresh()`. See [createProvider()](#createprovider) for building a dynamic provider.
327
+
328
+ ## Auth
329
+
330
+ Every provider owns its auth: how API keys resolve (stored credentials, environment variables, ambient sources like AWS profiles or gcloud ADC) and, where supported, OAuth login/refresh flows.
331
+
332
+ ### How Auth Resolves
333
+
334
+ When you call `models.stream()`, the collection resolves auth through the owning provider and merges it into the request. Explicit per-request values always win:
335
+
336
+ ```typescript
337
+ // Resolved through the provider (env var, stored credential, OAuth token):
338
+ await models.complete(model, context);
339
+
340
+ // Explicit key wins over anything the provider would resolve:
341
+ await models.complete(model, context, { apiKey: 'sk-explicit' });
342
+ ```
343
+
344
+ You can inspect resolution without making a request. Pass a provider ID for provider-scoped auth, or a model to include its static `model.headers`:
345
+
346
+ ```typescript
347
+ const providerAuth = await models.getAuth(model.provider);
348
+ const modelAuth = await models.getAuth(model);
349
+
350
+ if (modelAuth) {
351
+ console.log(`configured via ${modelAuth.source}`); // e.g. "ANTHROPIC_API_KEY", "OAuth", "stored credential"
352
+ console.log(modelAuth.auth.headers); // Provider auth headers + model.headers
353
+ } else {
354
+ console.log('not configured');
355
+ }
356
+ ```
357
+
358
+ Both overloads resolve credentials, refresh expired OAuth when necessary, and may return an auth-derived `apiKey`, `headers`, or `baseUrl`. `getAuth()` resolves `undefined` for unconfigured providers and rejects with `ModelsError` when something is actually broken (`"oauth"`: token refresh failed, credential preserved for re-login; `"auth"`: key resolution or credential store failure). Request paths surface the same failures as stream errors.
359
+
360
+ `getAuth()`, `checkAuth()`, `getAvailable()`, login, and logout accept optional caller cancellation through their existing options or interaction objects and remain unbounded when no signal is supplied. Provider `login`, `ApiKeyAuth.check`, `ApiKeyAuth.resolve`, and `OAuthAuth.refresh` implementations always receive a concrete signal and must honor it for blocking work.
361
+
362
+ ### Transforming Request Headers
363
+
364
+ `Models.stream()`, `complete()`, `streamSimple()`, and `completeSimple()` accept a Models-only `transformHeaders` option. It runs once after provider auth, `model.headers`, and explicit `options.headers` have been merged, but before provider dispatch:
365
+
366
+ ```typescript
367
+ const response = await models.completeSimple(model, context, {
368
+ headers: { "X-Client": "my-app" },
369
+ transformHeaders: async (headers) => ({
370
+ ...headers,
371
+ "X-Request-ID": crypto.randomUUID(),
372
+ }),
373
+ });
374
+ ```
375
+
376
+ The ordering is:
377
+
378
+ ```text
379
+ provider auth headers -> model.headers -> explicit options.headers -> transformHeaders -> Provider.stream*()
380
+ ```
381
+
382
+ Header names are merged case-insensitively. Explicit headers override auth/model headers, and the transform has final control; returning `null` for a header suppresses lower-level defaults that support deletion.
383
+
384
+ `transformHeaders` belongs to `Models`, not `Provider`. A `Models` implementation must consume it and remove it before calling `Provider.stream*()`. Provider implementations continue receiving ordinary `ApiStreamOptions` or `SimpleStreamOptions` and never handle the transform themselves. Use this option instead of calling `getAuth(model)` before `stream*()`, which would resolve request auth twice.
385
+
386
+ ### Credential Store
387
+
388
+ Stored credentials (API keys entered interactively, OAuth tokens) live in a `CredentialStore` — one type-tagged credential per provider. pi-ai ships an in-memory default; apps inject persistent storage:
389
+
390
+ ```typescript
391
+ import { createModels, type CredentialStore } from '@bastani/pi-ai';
392
+
393
+ const models = createModels({ credentials: myFileBackedStore });
394
+ // builtinModels() takes the same options:
395
+ // const models = builtinModels({ credentials: myFileBackedStore });
396
+ ```
397
+
398
+ The contract is small: `read(providerId)`, `list()` for non-secret `{ providerId, type }` metadata, `modify(providerId, fn)` (the only write path — a serialized read-modify-write), and `delete(providerId)`. Each operation accepts optional cancellation options. Enumeration must not resolve secrets or execute configured key commands. OAuth token refresh runs inside `modify`, so concurrent requests and processes cannot double-refresh a rotated token. A stored credential *owns* its provider: environment variables are only consulted when nothing is stored, and a failed refresh never silently falls back to an env key.
399
+
400
+ API-key credentials use the same discriminator as pi's `auth.json` and can carry provider-scoped env/config values:
401
+
402
+ ```typescript
403
+ const credential = {
404
+ type: 'api_key',
405
+ key: '...',
406
+ env: {
407
+ CLOUDFLARE_ACCOUNT_ID: 'account-id',
408
+ CLOUDFLARE_GATEWAY_ID: 'gateway-id'
409
+ }
410
+ } as const;
411
+ ```
412
+
413
+ ### Environment Variables
414
+
415
+ Built-in providers resolve these env vars (Node.js; in browsers pass `apiKey` explicitly):
416
+
417
+ | Provider | Environment Variable(s) |
418
+ |----------|------------------------|
419
+ | OpenAI | `OPENAI_API_KEY` |
420
+ | Ant Ling | `ANT_LING_API_KEY` |
421
+ | Azure OpenAI | `AZURE_OPENAI_API_KEY` + `AZURE_OPENAI_BASE_URL` (e.g. `https://{resource}.ai.azure.com`) or `AZURE_OPENAI_RESOURCE_NAME`. Supports `*.openai.azure.com`, `*.cognitiveservices.azure.com` and `*.ai.azure.com`; root endpoints auto-normalize to `/openai/v1`. Optional: `AZURE_OPENAI_API_VERSION` (default `v1`), `AZURE_OPENAI_DEPLOYMENT_NAME_MAP`. |
422
+ | Anthropic | `ANTHROPIC_API_KEY` or `ANTHROPIC_OAUTH_TOKEN` |
423
+ | DeepSeek | `DEEPSEEK_API_KEY` |
424
+ | NVIDIA NIM | `NVIDIA_API_KEY` |
425
+ | Google | `GEMINI_API_KEY` |
426
+ | Vertex AI | `GOOGLE_CLOUD_API_KEY` or `GOOGLE_CLOUD_PROJECT` (or `GCLOUD_PROJECT`) + `GOOGLE_CLOUD_LOCATION` + ADC |
427
+ | Mistral | `MISTRAL_API_KEY` |
428
+ | Groq | `GROQ_API_KEY` |
429
+ | Cerebras | `CEREBRAS_API_KEY` |
430
+ | Cloudflare AI Gateway | `CLOUDFLARE_API_KEY` + `CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_GATEWAY_ID` |
431
+ | Cloudflare Workers AI | `CLOUDFLARE_API_KEY` + `CLOUDFLARE_ACCOUNT_ID` |
432
+ | xAI | `XAI_API_KEY` |
433
+ | Fireworks | `FIREWORKS_API_KEY` |
434
+ | Together AI | `TOGETHER_API_KEY` |
435
+ | Baseten | `BASETEN_API_KEY` |
436
+ | OpenRouter | `OPENROUTER_API_KEY` |
437
+ | Vercel AI Gateway | `AI_GATEWAY_API_KEY` |
438
+ | ZAI Coding Plan (Global) | `ZAI_API_KEY` |
439
+ | ZAI Coding Plan (China) | `ZAI_CODING_CN_API_KEY` |
440
+ | MiniMax (Global) | `MINIMAX_API_KEY` |
441
+ | MiniMax (China) | `MINIMAX_CN_API_KEY` |
442
+ | Moonshot AI / Moonshot AI (China) | `MOONSHOT_API_KEY` |
443
+ | Hugging Face | `HF_TOKEN` |
444
+ | OpenCode Zen / OpenCode Go | `OPENCODE_API_KEY` |
445
+ | Kimi For Coding | `KIMI_API_KEY` |
446
+ | Qwen Token Plan (existing catalog) | `QWEN_TOKEN_PLAN_API_KEY` |
447
+ | Qwen Token Plan (Individual) | `QWEN_TOKEN_PLAN_API_KEY` |
448
+ | Qwen Token Plan (China) | `QWEN_TOKEN_PLAN_CN_API_KEY` |
449
+ | Xiaomi MiMo (API billing) | `XIAOMI_API_KEY` |
450
+ | Xiaomi MiMo Token Plan (China) | `XIAOMI_TOKEN_PLAN_CN_API_KEY` |
451
+ | Xiaomi MiMo Token Plan (Amsterdam) | `XIAOMI_TOKEN_PLAN_AMS_API_KEY` |
452
+ | Xiaomi MiMo Token Plan (Singapore) | `XIAOMI_TOKEN_PLAN_SGP_API_KEY` |
453
+ | GitHub Copilot | `COPILOT_GITHUB_TOKEN` |
454
+
455
+ `qwen-token-plan-individual` and `qwen-token-plan` share the international endpoint and
456
+ `QWEN_TOKEN_PLAN_API_KEY`. The Individual provider exposes only the models documented for Individual
457
+ subscriptions, while the existing provider retains its broader catalog for backward compatibility.
458
+ Stored credentials remain provider-scoped, so save the key under the provider ID you register.
459
+
460
+ Amazon Bedrock resolves ambient AWS credentials (`AWS_PROFILE`, access key pairs, `AWS_BEARER_TOKEN_BEDROCK`, ECS task roles, web identity tokens); its provider-owned login flow supports bearer tokens, AWS profiles, and the existing credential chain. Vertex AI resolves either an explicit key or gcloud Application Default Credentials plus project/location, with a provider-owned login flow for API keys, ADC, and service-account files.
461
+
462
+ ## Tools
463
+
464
+ Tools enable LLMs to interact with external systems. This library uses TypeBox schemas for type-safe tool definitions with automatic validation using TypeBox's built-in validator and value conversion utilities. TypeBox schemas can be serialized and deserialized as plain JSON, making them ideal for distributed systems.
465
+
466
+ ### Defining Tools
467
+
468
+ ```typescript
469
+ import { Type, type Tool, StringEnum } from '@bastani/pi-ai';
470
+
471
+ // Define tool parameters with TypeBox
472
+ const weatherTool: Tool = {
473
+ name: 'get_weather',
474
+ description: 'Get current weather for a location',
475
+ parameters: Type.Object({
476
+ location: Type.String({ description: 'City name or coordinates' }),
477
+ units: StringEnum(['celsius', 'fahrenheit'], { default: 'celsius' })
478
+ })
479
+ };
480
+
481
+ // Note: For Google API compatibility, use StringEnum helper instead of Type.Enum
482
+ // Type.Enum generates anyOf/const patterns that Google doesn't support
483
+
484
+ const bookMeetingTool: Tool = {
485
+ name: 'book_meeting',
486
+ description: 'Schedule a meeting',
487
+ parameters: Type.Object({
488
+ title: Type.String({ minLength: 1 }),
489
+ startTime: Type.String({ format: 'date-time' }),
490
+ endTime: Type.String({ format: 'date-time' }),
491
+ attendees: Type.Array(Type.String({ format: 'email' }), { minItems: 1 })
492
+ })
493
+ };
494
+ ```
495
+
496
+ ### Constrained Sampling for Tools
497
+
498
+ Tools can opt in to provider-side constrained sampling. For JSON-schema tools, `strict: 'prefer'` uses provider-side strict schema enforcement when supported and otherwise falls back to normal tool calling. `strict: 'require'` fails the request when the active provider/model cannot honor it. Set `constrainedSampling: false` to explicitly opt out; it behaves the same as omitting the field.
499
+
500
+ ```typescript
501
+ const strictTool: Tool = {
502
+ name: 'edit_file',
503
+ description: 'Edit a file',
504
+ parameters: Type.Object({
505
+ path: Type.String(),
506
+ content: Type.String()
507
+ }, { additionalProperties: false }),
508
+ constrainedSampling: { type: 'json_schema', strict: 'prefer' }
509
+ };
510
+ ```
511
+
512
+ Strict JSON-schema constrained sampling is supported for OpenAI, Anthropic, supported Amazon Bedrock Converse models, Mistral, and Gemini 3 tool calls through the Google Generative AI and Vertex adapters. Google uses `VALIDATED` function-calling mode (or `ANY` when explicitly requested); earlier Gemini versions fall back for `strict: 'prefer'` and reject `strict: 'require'` because they do not enforce required parameters. Bedrock strict-tool capability is generated from model structured-output metadata; custom Bedrock models can override `compat.supportsStrictMode`. OpenAI Responses and Chat Completions can also emit grammar-constrained custom tools with OpenAI Lark or regex grammar variants. If multiple OpenAI variants are supplied, Lark is preferred over regex. Grammar constraints are enforced when the active model supports grammar tools; otherwise the tool falls back to normal function/JSON-schema handling. Grammar tool capability is model metadata: the generated catalog sets `compat.supportsOpenAIGrammarTools` for GPT-5+ models on endpoints that pass OpenAI custom tools through (OpenAI, OpenAI Codex, Azure OpenAI Responses, GitHub Copilot, opencode, and Cloudflare AI Gateway). OpenAI rejects `type: "custom"` tools for pre-GPT-5 models, and gateways that normalize tool schemas (e.g. OpenRouter) mangle them, so the flag stays off elsewhere. Custom model definitions can opt in via `compat`. Grammar-capable models reject grammar configurations without a non-empty supported variant. Native grammar tools must have an object parameter schema with exactly one required string property:
513
+
514
+ ```typescript
515
+ const patchTool: Tool = {
516
+ name: 'apply_patch',
517
+ description: 'Apply a patch',
518
+ parameters: Type.Object({
519
+ input: Type.String()
520
+ }, { additionalProperties: false }),
521
+ constrainedSampling: {
522
+ type: 'grammar',
523
+ variants: {
524
+ openai_lark: 'start: /.+/s'
525
+ }
526
+ }
527
+ };
528
+ ```
529
+
530
+ ### Handling Tool Calls
531
+
532
+ Tool results use content blocks and can include both text and images:
533
+
534
+ ```typescript
535
+ import { readFileSync } from 'fs';
536
+
537
+ const context: Context = {
538
+ messages: [{ role: 'user', content: 'What is the weather in London?', timestamp: Date.now() }],
539
+ tools: [weatherTool]
540
+ };
541
+
542
+ const response = await models.complete(model, context);
543
+
544
+ // Check for tool calls in the response
545
+ for (const block of response.content) {
546
+ if (block.type === 'toolCall') {
547
+ // Execute your tool with the arguments
548
+ // See "Validating Tool Arguments" section for validation
549
+ const result = await executeWeatherApi(block.arguments);
550
+
551
+ // Add tool result with text content
552
+ context.messages.push({
553
+ role: 'toolResult',
554
+ toolCallId: block.id,
555
+ toolName: block.name,
556
+ content: [{ type: 'text', text: JSON.stringify(result) }],
557
+ isError: false,
558
+ timestamp: Date.now()
559
+ });
560
+ }
561
+ }
562
+
563
+ // Tool results can also include images (for vision-capable models)
564
+ const imageBuffer = readFileSync('chart.png');
565
+ context.messages.push({
566
+ role: 'toolResult',
567
+ toolCallId: 'tool_xyz',
568
+ toolName: 'generate_chart',
569
+ content: [
570
+ { type: 'text', text: 'Generated chart showing temperature trends' },
571
+ { type: 'image', data: imageBuffer.toString('base64'), mimeType: 'image/png' }
572
+ ],
573
+ isError: false,
574
+ timestamp: Date.now()
575
+ });
576
+ ```
577
+
578
+ ### Streaming Tool Calls with Partial JSON
579
+
580
+ During streaming, tool call arguments are progressively parsed as they arrive. This enables real-time UI updates before the complete arguments are available:
581
+
582
+ ```typescript
583
+ const s = models.stream(model, context);
584
+
585
+ for await (const event of s) {
586
+ if (event.type === 'toolcall_delta') {
587
+ const toolCall = event.partial.content[event.contentIndex];
588
+
589
+ // toolCall.arguments contains partially parsed JSON during streaming
590
+ // This allows for progressive UI updates
591
+ if (toolCall.type === 'toolCall' && toolCall.arguments) {
592
+ // BE DEFENSIVE: arguments may be incomplete
593
+ // Example: Show file path being written even before content is complete
594
+ if (toolCall.name === 'write_file' && toolCall.arguments.path) {
595
+ console.log(`Writing to: ${toolCall.arguments.path}`);
596
+
597
+ // Content might be partial or missing
598
+ if (toolCall.arguments.content) {
599
+ console.log(`Content preview: ${toolCall.arguments.content.substring(0, 100)}...`);
600
+ }
601
+ }
602
+ }
603
+ }
604
+
605
+ if (event.type === 'toolcall_end') {
606
+ // Here toolCall.arguments is complete (but not yet validated)
607
+ const toolCall = event.toolCall;
608
+ console.log(`Tool completed: ${toolCall.name}`, toolCall.arguments);
609
+ }
610
+ }
611
+ ```
612
+
613
+ **Important notes about partial tool arguments:**
614
+ - During `toolcall_delta` events, `arguments` contains the best-effort parse of partial JSON
615
+ - Fields may be missing or incomplete - always check for existence before use
616
+ - String values may be truncated mid-word
617
+ - Arrays may be incomplete
618
+ - Nested objects may be partially populated
619
+ - At minimum, `arguments` will be an empty object `{}`, never `undefined`
620
+ - The Google provider does not support function call streaming. Instead, you will receive a single `toolcall_delta` event with the full arguments.
621
+
622
+ ### Validating Tool Arguments
623
+
624
+ When implementing your own tool execution loop, use `validateToolCall` to validate arguments before passing them to your tools:
625
+
626
+ ```typescript
627
+ import { validateToolCall, type Tool } from '@bastani/pi-ai';
628
+
629
+ const tools: Tool[] = [weatherTool, calculatorTool];
630
+ const s = models.stream(model, { messages, tools });
631
+
632
+ for await (const event of s) {
633
+ if (event.type === 'toolcall_end') {
634
+ const toolCall = event.toolCall;
635
+
636
+ try {
637
+ // Validate arguments against the tool's schema (throws on invalid args)
638
+ const validatedArgs = validateToolCall(tools, toolCall);
639
+ const result = await executeMyTool(toolCall.name, validatedArgs);
640
+ // ... add tool result to context
641
+ } catch (error) {
642
+ // Validation failed - return error as tool result so model can retry
643
+ context.messages.push({
644
+ role: 'toolResult',
645
+ toolCallId: toolCall.id,
646
+ toolName: toolCall.name,
647
+ content: [{ type: 'text', text: error.message }],
648
+ isError: true,
649
+ timestamp: Date.now()
650
+ });
651
+ }
652
+ }
653
+ }
654
+ ```
655
+
656
+ ### Complete Event Reference
657
+
658
+ All streaming events emitted during assistant message generation:
659
+
660
+ | Event Type | Description | Key Properties |
661
+ |------------|-------------|----------------|
662
+ | `start` | Stream begins | `partial`: Initial assistant message structure |
663
+ | `text_start` | Text block starts | `contentIndex`: Position in content array |
664
+ | `text_delta` | Text chunk received | `delta`: New text, `contentIndex`: Position |
665
+ | `text_end` | Text block complete | `content`: Full text, `contentIndex`: Position |
666
+ | `thinking_start` | Thinking block starts | `contentIndex`: Position in content array |
667
+ | `thinking_delta` | Thinking chunk received | `delta`: New text, `contentIndex`: Position |
668
+ | `thinking_end` | Thinking block complete | `content`: Full thinking, `contentIndex`: Position |
669
+ | `toolcall_start` | Tool call begins | `contentIndex`: Position in content array |
670
+ | `toolcall_delta` | Tool arguments streaming | `delta`: JSON chunk, `partial.content[contentIndex].arguments`: Partial parsed args |
671
+ | `toolcall_end` | Tool call complete | `toolCall`: Complete validated tool call with `id`, `name`, `arguments` |
672
+ | `done` | Stream complete | `reason`: Stop reason ("stop", "length", "toolUse"), `message`: Final assistant message |
673
+ | `error` | Error occurred | `reason`: Error type ("error" or "aborted"), `error`: AssistantMessage with partial content |
674
+
675
+ Streaming events for different content blocks are not guaranteed to be contiguous. Providers may emit deltas for text, thinking, and tool calls in the same upstream chunk, and pi may surface corresponding events interleaved, for example `text_start`, `text_delta`, `toolcall_start`, `text_delta`, `toolcall_delta`. Consumers must use `contentIndex` to associate each delta/end event with its block and must not assume that a block's `*_start`/`*_delta`/`*_end` sequence is uninterrupted by events for other blocks.
676
+
677
+ ## Image Input
678
+
679
+ Models with vision capabilities can process images. You can check if a model supports images via the `input` property. If you pass images to a non-vision model, they are silently ignored.
680
+
681
+ ```typescript
682
+ import { readFileSync } from 'fs';
683
+
684
+ const model = models.getModel('openai', 'gpt-4o-mini')!;
685
+
686
+ // Check if model supports images
687
+ if (model.input.includes('image')) {
688
+ console.log('Model supports vision');
689
+ }
690
+
691
+ const imageBuffer = readFileSync('image.png');
692
+ const base64Image = imageBuffer.toString('base64');
693
+
694
+ const response = await models.complete(model, {
695
+ messages: [{
696
+ role: 'user',
697
+ content: [
698
+ { type: 'text', text: 'What is in this image?' },
699
+ { type: 'image', data: base64Image, mimeType: 'image/png' }
700
+ ],
701
+ timestamp: Date.now()
702
+ }]
703
+ });
704
+
705
+ // Access the response
706
+ for (const block of response.content) {
707
+ if (block.type === 'text') {
708
+ console.log(block.text);
709
+ }
710
+ }
711
+ ```
712
+
713
+ ## Image Generation
714
+
715
+ Image generation uses a separate API surface from text/chat generation, mirroring the chat-side design: an `ImagesModels` collection holds `ImagesProvider`s, reads are sync, and auth resolves through the owning provider. Image generation is a one-shot API: `generateImages()` waits for the provider response and returns the final `AssistantImages` result — do not use the chat/stream APIs for it.
716
+
717
+ ### Basic Image Generation
718
+
719
+ ```typescript
720
+ import { builtinImagesModels } from '@bastani/pi-ai/providers/all';
721
+
722
+ // Every built-in image-generation provider; accepts the same options as createModels()
723
+ const imagesModels = builtinImagesModels();
724
+
725
+ const model = imagesModels.getModel('openrouter', 'google/gemini-2.5-flash-image')!;
726
+
727
+ // Auth resolves through the provider (OPENROUTER_API_KEY here); explicit apiKey wins
728
+ const result = await imagesModels.generateImages(model, {
729
+ input: [{ type: 'text', text: 'Generate a red circle on a plain white background.' }]
730
+ });
731
+
732
+ for (const block of result.output) {
733
+ if (block.type === 'text') {
734
+ console.log(block.text);
735
+ } else if (block.type === 'image') {
736
+ console.log(block.mimeType);
737
+ console.log(block.data.substring(0, 32));
738
+ }
739
+ }
740
+ ```
741
+
742
+ Like the chat side, you can build the collection from parts: `createImagesModels({ credentials?, authContext? })`, the `openrouterImagesProvider()` factory from `@bastani/pi-ai/providers/openrouter-images`, and `createImagesProvider({ id, auth, models, refreshModels?, api })` for custom image providers (with `imagesModels.refresh(provider?)` for dynamic lists). Failures never reject — they return an `AssistantImages` with `stopReason: "error"`. The collection's provider-scoped `getAuth(providerId)` works exactly like the chat-side one.
743
+
744
+ The old global API (`getImageModel()` / `getImageModels()` / `getImageProviders()` / `generateImages()`) remains available on the [compat entrypoint](#migrating-from-the-old-global-api):
745
+
746
+ ```typescript
747
+ import { getImageModel, generateImages } from '@bastani/pi-ai/compat';
748
+
749
+ const model = getImageModel('openrouter', 'google/gemini-2.5-flash-image');
750
+ const result = await generateImages(model, {
751
+ input: [{ type: 'text', text: 'Generate a red circle on a plain white background.' }]
752
+ }, {
753
+ apiKey: process.env.OPENROUTER_API_KEY
754
+ });
755
+ ```
756
+
757
+ Some models also support image input:
758
+
759
+ ```typescript
760
+ import { readFileSync } from 'fs';
761
+
762
+ const imageBuffer = readFileSync('input.png');
763
+ const result = await imagesModels.generateImages(model, {
764
+ input: [
765
+ { type: 'text', text: 'Create a variation of this image with a blue background.' },
766
+ { type: 'image', data: imageBuffer.toString('base64'), mimeType: 'image/png' }
767
+ ]
768
+ });
769
+ ```
770
+
771
+ Check capabilities on the model metadata:
772
+
773
+ ```typescript
774
+ console.log(model.input); // ['text', 'image']
775
+ console.log(model.output); // ['image'] or ['image', 'text']
776
+ ```
777
+
778
+ ### Notes and Limitations
779
+
780
+ - Image models live in `ImagesModels` collections, chat models in `Models` collections; the two are separate surfaces.
781
+ - Use `generateImages()`, not the chat/stream APIs.
782
+ - Image-generation models do not participate in tool calling.
783
+ - Outputs are returned in `AssistantImages.output` and can include both base64-encoded `ImageContent` blocks and `TextContent` blocks.
784
+ - Some models return only images, others return images plus text. Check `model.output`.
785
+ - Some models accept image input, others are text-to-image only. Check `model.input`.
786
+ - Like the streaming APIs, image generation supports options such as `apiKey`, `signal`, `headers`, `onPayload`, and `onResponse`, and results may include `stopReason`, `responseId`, and `usage`.
787
+ - If you want a model to analyze images in a conversation or call tools, use the regular chat APIs with a model that supports image input.
788
+ - At the moment, image generation is available through only one provider, OpenRouter.
789
+
790
+ ## Thinking/Reasoning
791
+
792
+ Many models support thinking/reasoning capabilities where they can show their internal thought process. You can check if a model supports reasoning via the `reasoning` property. If you pass reasoning options to a non-reasoning model, they are silently ignored.
793
+
794
+ ### Unified Interface (streamSimple/completeSimple)
795
+
796
+ ```typescript
797
+ // Many models across providers support thinking/reasoning
798
+ const model = models.getModel('anthropic', 'claude-sonnet-4-5')!;
799
+ // or models.getModel('openai', 'gpt-5-mini');
800
+ // or models.getModel('google', 'gemini-2.5-flash');
801
+ // or models.getModel('xai', 'grok-4.5');
802
+
803
+ // Check if model supports reasoning
804
+ if (model.reasoning) {
805
+ console.log('Model supports reasoning/thinking');
806
+ }
807
+
808
+ // Use the simplified reasoning option
809
+ const response = await models.completeSimple(model, {
810
+ messages: [{ role: 'user', content: 'Solve: 2x + 5 = 13', timestamp: Date.now() }]
811
+ }, {
812
+ reasoning: 'medium' // 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'
813
+ });
814
+
815
+ // Access thinking and text blocks
816
+ for (const block of response.content) {
817
+ if (block.type === 'thinking') {
818
+ console.log('Thinking:', block.thinking);
819
+ } else if (block.type === 'text') {
820
+ console.log('Response:', block.text);
821
+ }
822
+ }
823
+ ```
824
+
825
+ `xhigh` and `max` are model-specific, opt-in levels. Use `getSupportedThinkingLevels(model)` to determine whether a concrete model exposes either level; models such as GPT-5.6 can expose both.
826
+
827
+ ### Provider-Specific Options (stream/complete)
828
+
829
+ `models.stream()`/`complete()` accept the owning API's full option set. Use `hasApi()` to narrow a dynamically looked-up model to its API for full option typing:
830
+
831
+ ```typescript
832
+ import { hasApi } from '@bastani/pi-ai';
833
+
834
+ // OpenAI Reasoning (o1, o3, gpt-5)
835
+ const openaiModel = models.getModel('openai', 'gpt-5-mini')!;
836
+ if (hasApi(openaiModel, 'openai-responses')) {
837
+ await models.complete(openaiModel, context, {
838
+ reasoningEffort: 'medium',
839
+ reasoningSummary: 'detailed' // OpenAI Responses API only
840
+ });
841
+ }
842
+
843
+ // Anthropic Thinking
844
+ const anthropicModel = models.getModel('anthropic', 'claude-sonnet-4-5')!;
845
+ if (hasApi(anthropicModel, 'anthropic-messages')) {
846
+ await models.complete(anthropicModel, context, {
847
+ thinkingEnabled: true,
848
+ thinkingBudgetTokens: 8192 // Optional token limit
849
+ });
850
+ }
851
+
852
+ // Google Gemini Thinking
853
+ const googleModel = models.getModel('google', 'gemini-2.5-flash')!;
854
+ if (hasApi(googleModel, 'google-generative-ai')) {
855
+ await models.complete(googleModel, context, {
856
+ thinking: {
857
+ enabled: true,
858
+ budgetTokens: 8192 // -1 for dynamic, 0 to disable
859
+ }
860
+ });
861
+ }
862
+ ```
863
+
864
+ ### Streaming Thinking Content
865
+
866
+ When streaming, thinking content is delivered through specific events:
867
+
868
+ ```typescript
869
+ const s = models.streamSimple(model, context, { reasoning: 'high' });
870
+
871
+ for await (const event of s) {
872
+ switch (event.type) {
873
+ case 'thinking_start':
874
+ console.log('[Model started thinking]');
875
+ break;
876
+ case 'thinking_delta':
877
+ process.stdout.write(event.delta); // Stream thinking content
878
+ break;
879
+ case 'thinking_end':
880
+ console.log('\n[Thinking complete]');
881
+ break;
882
+ }
883
+ }
884
+ ```
885
+
886
+ ## Stop Reasons
887
+
888
+ Every `AssistantMessage` includes a `stopReason` field that indicates how the generation ended:
889
+
890
+ - `"pending"` - Only present in partial messages when we do not know what the stop reason will be
891
+ - `"stop"` - This is the final message the model will produce this turn
892
+ - `"length"` - Output hit the maximum token limit
893
+ - `"toolUse"` - Model is calling tools and expects tool results
894
+ - `"error"` - An error occurred during generation
895
+ - `"aborted"` - Request was cancelled via abort signal
896
+
897
+ `AssistantMessage` may also include `responseId`, a provider-specific upstream response or message identifier when the underlying API exposes one. Do not assume it is always present across providers.
898
+
899
+ ## Error Handling
900
+
901
+ Request failures never throw out of the stream functions: when a request ends with an error (including aborts and tool call validation errors), the streaming API emits an error event and the final message carries the details:
902
+
903
+ ```typescript
904
+ // In streaming
905
+ for await (const event of s) {
906
+ if (event.type === 'error') {
907
+ // event.reason is either "error" or "aborted"
908
+ // event.error is the AssistantMessage with partial content
909
+ console.error(`Error (${event.reason}):`, event.error.errorMessage);
910
+ console.log('Partial content:', event.error.content);
911
+ }
912
+ }
913
+
914
+ // The final message will have the error details
915
+ const message = await s.result();
916
+ if (message.stopReason === 'error' || message.stopReason === 'aborted') {
917
+ console.error('Request failed:', message.errorMessage);
918
+ // message.content contains any partial content received before the error
919
+ // message.usage contains partial token counts and costs
920
+ }
921
+ ```
922
+
923
+ Auth failures (no key configured, OAuth refresh failed, unknown provider) surface the same way: as a stream error with `stopReason: "error"`.
924
+
925
+ ### Aborting Requests
926
+
927
+ The abort signal allows you to cancel in-progress requests. Aborted requests have `stopReason === 'aborted'`:
928
+
929
+ ```typescript
930
+ const controller = new AbortController();
931
+
932
+ // Abort after 2 seconds
933
+ setTimeout(() => controller.abort(), 2000);
934
+
935
+ const s = models.stream(model, {
936
+ messages: [{ role: 'user', content: 'Write a long story', timestamp: Date.now() }]
937
+ }, {
938
+ signal: controller.signal
939
+ });
940
+
941
+ for await (const event of s) {
942
+ if (event.type === 'text_delta') {
943
+ process.stdout.write(event.delta);
944
+ } else if (event.type === 'error') {
945
+ // event.reason tells you if it was "error" or "aborted"
946
+ console.log(`${event.reason === 'aborted' ? 'Aborted' : 'Error'}:`, event.error.errorMessage);
947
+ }
948
+ }
949
+
950
+ // Get results (may be partial if aborted)
951
+ const response = await s.result();
952
+ if (response.stopReason === 'aborted') {
953
+ console.log('Request was aborted:', response.errorMessage);
954
+ console.log('Partial content received:', response.content);
955
+ console.log('Tokens used:', response.usage);
956
+ }
957
+ ```
958
+
959
+ ### Continuing After Abort
960
+
961
+ Aborted messages can be added to the conversation context and continued in subsequent requests:
962
+
963
+ ```typescript
964
+ const context = {
965
+ messages: [
966
+ { role: 'user', content: 'Explain quantum computing in detail', timestamp: Date.now() }
967
+ ]
968
+ };
969
+
970
+ // First request gets aborted after 2 seconds
971
+ const controller1 = new AbortController();
972
+ setTimeout(() => controller1.abort(), 2000);
973
+
974
+ const partial = await models.complete(model, context, { signal: controller1.signal });
975
+
976
+ // Add the partial response to context
977
+ context.messages.push(partial);
978
+ context.messages.push({ role: 'user', content: 'Please continue', timestamp: Date.now() });
979
+
980
+ // Continue the conversation
981
+ const continuation = await models.complete(model, context);
982
+ ```
983
+
984
+ ### Debugging Provider Payloads
985
+
986
+ Use the `onPayload` callback to inspect the request payload sent to the provider. This is useful for debugging request formatting issues or provider validation errors.
987
+
988
+ ```typescript
989
+ const response = await models.complete(model, context, {
990
+ onPayload: (payload) => {
991
+ console.log('Provider payload:', JSON.stringify(payload, null, 2));
992
+ }
993
+ });
994
+ ```
995
+
996
+ The callback is supported by `stream`, `complete`, `streamSimple`, and `completeSimple`.
997
+
998
+ ## Custom Providers
999
+
1000
+ ### createProvider()
1001
+
1002
+ `createProvider()` builds a provider from parts: identity, auth, a model list, and an API implementation. Use it for local inference servers, proxies, or any OpenAI/Anthropic-compatible endpoint:
1003
+
1004
+ ```typescript
1005
+ import { createModels, createProvider, envApiKeyAuth, type Model } from '@bastani/pi-ai';
1006
+ import { openAICompletionsApi } from '@bastani/pi-ai/api/openai-completions.lazy';
1007
+
1008
+ const ollamaModel: Model<'openai-completions'> = {
1009
+ id: 'llama-3.1-8b',
1010
+ name: 'Llama 3.1 8B (Ollama)',
1011
+ api: 'openai-completions',
1012
+ provider: 'ollama',
1013
+ baseUrl: 'http://localhost:11434/v1',
1014
+ reasoning: false,
1015
+ input: ['text'],
1016
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1017
+ contextWindow: 128000,
1018
+ maxTokens: 32000
1019
+ };
1020
+
1021
+ const ollama = createProvider({
1022
+ id: 'ollama',
1023
+ name: 'Ollama',
1024
+ baseUrl: 'http://localhost:11434/v1',
1025
+ // Every provider declares auth; keyless local servers resolve as configured with no key.
1026
+ auth: { apiKey: { name: 'Ollama', resolve: async () => ({ auth: {} }) } },
1027
+ models: [ollamaModel],
1028
+ api: openAICompletionsApi(),
1029
+ });
1030
+
1031
+ const models = createModels();
1032
+ models.setProvider(ollama);
1033
+
1034
+ await models.complete(models.getModel('ollama', 'llama-3.1-8b')!, context);
1035
+ ```
1036
+
1037
+ For providers with real keys, `envApiKeyAuth(displayName, envVars)` gives the standard behavior (stored credential wins, then the first set env var):
1038
+
1039
+ ```typescript
1040
+ const proxy = createProvider({
1041
+ id: 'my-proxy',
1042
+ auth: { apiKey: envApiKeyAuth('My proxy API key', ['MY_PROXY_API_KEY']) },
1043
+ models: [/* ... */],
1044
+ api: openAICompletionsApi(),
1045
+ });
1046
+ ```
1047
+
1048
+ Mixed-API providers pass a map keyed by `model.api`; each model dispatches to its API's implementation:
1049
+
1050
+ ```typescript
1051
+ import { anthropicMessagesApi } from '@bastani/pi-ai/api/anthropic-messages.lazy';
1052
+ import { openAIResponsesApi } from '@bastani/pi-ai/api/openai-responses.lazy';
1053
+
1054
+ const gateway = createProvider({
1055
+ id: 'my-gateway',
1056
+ auth: { apiKey: envApiKeyAuth('Gateway key', ['GATEWAY_API_KEY']) },
1057
+ models: [/* models with api: 'anthropic-messages' or 'openai-responses' */],
1058
+ api: {
1059
+ 'anthropic-messages': anthropicMessagesApi(),
1060
+ 'openai-responses': openAIResponsesApi(),
1061
+ },
1062
+ });
1063
+ ```
1064
+
1065
+ Provider-wide endpoint or request transformations belong in the provider's API implementation: wrap the `ProviderStreams` you pass as `api` so every request goes through the transformation before dispatch. The Cloudflare providers do this to materialize account/gateway endpoint placeholders from the resolved provider env:
1066
+
1067
+ ```typescript
1068
+ function tenantStreams(streams: ProviderStreams): ProviderStreams {
1069
+ const withTenant = (model: Model<Api>) => ({ ...model, baseUrl: model.baseUrl.replace('{tenant}', tenantId) });
1070
+ return {
1071
+ stream: (model, context, options) => streams.stream(withTenant(model), context, options),
1072
+ streamSimple: (model, context, options) => streams.streamSimple(withTenant(model), context, options),
1073
+ };
1074
+ }
1075
+
1076
+ const tenantGateway = createProvider({
1077
+ id: 'tenant-gateway',
1078
+ auth: { apiKey: envApiKeyAuth('Gateway key', ['GATEWAY_API_KEY']) },
1079
+ models: [/* ... */],
1080
+ api: tenantStreams(openAICompletionsApi()),
1081
+ });
1082
+ ```
1083
+
1084
+ Dynamic model lists use `fetchModels`. `Models.refresh()` refreshes every configured dynamic provider, passing its effective API-key or refreshed OAuth credential. A `ModelsStore` persists dynamic catalogs; both stores default to in-memory implementations. Its `read`, `write`, and `delete` operations accept optional cancellation, and `Models` binds those waits to the provider refresh signal.
1085
+
1086
+ ```typescript
1087
+ const models = createModels({ credentials, modelsStore });
1088
+ const llamacpp = createProvider({
1089
+ id: 'llamacpp',
1090
+ auth: { apiKey: { name: 'llama.cpp', resolve: async () => ({ auth: {} }) } },
1091
+ models: [],
1092
+ fetchModels: async ({ signal }) => fetchModelsFromServer('http://localhost:8080', signal),
1093
+ api: openAICompletionsApi(),
1094
+ });
1095
+
1096
+ models.setProvider(llamacpp);
1097
+ const result = await models.refresh({ signal });
1098
+ if (result.aborted) console.log('refresh cancelled');
1099
+ for (const [provider, error] of result.errors) console.error(provider, error);
1100
+ ```
1101
+
1102
+ `Models.refresh()` is unbounded when its optional signal is omitted. Providers always receive a concrete `RefreshModelsContext.signal` and must honor it for network requests and other blocking work. When a caller supplies a signal, `Models.refresh()` returns promptly with `aborted: true` after cancellation even if a custom provider fails to cooperate; the provider must still honor the signal to stop its underlying work.
1103
+
1104
+ Use `models.refresh({ providers: ['openrouter'] })` to restrict work to selected providers, `models.refresh({ allowNetwork: false })` to restore persisted catalogs without network access, or `models.refresh({ force: true })` to bypass provider freshness checks. Model reads stay synchronous and return the last restored or refreshed list.
1105
+
1106
+ `createProvider()` handles dynamic publication and persistence automatically. Handwritten `Provider.refreshModels()` implementations receive the read-only `context.stored` snapshot and publish through `context.publish({ persist?, update? })`. Omit `persist` to leave storage unchanged, pass a `ModelsStoreEntry` to write it, or pass `persist: null` to delete it. Publication is generation-checked; put synchronous in-memory catalog changes in `update` rather than mutating state before publication.
1107
+
1108
+ Custom models can carry `headers` (e.g. proxies behind bot detection) and `compat` flags. `Models.getAuth(model)` includes those model headers, and stream methods merge them before explicit request headers and `transformHeaders`. See [OpenAI Compatibility Settings](#openai-compatibility-settings).
1109
+
1110
+ Some OpenAI-compatible servers do not understand the `developer` role used for reasoning-capable models. For those providers, set `compat.supportsDeveloperRole` to `false` so the system prompt is sent as a `system` message instead. If the server also does not support `reasoning_effort`, set `compat.supportsReasoningEffort` to `false` too. This commonly applies to Ollama, vLLM, SGLang, and similar OpenAI-compatible servers.
1111
+
1112
+ Use model-level `thinkingLevelMap` to describe model-specific thinking controls. Keys are pi thinking levels (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`). Missing standard levels through `high` use provider defaults; `xhigh` and `max` are opt-in and require a non-null map entry. String values are sent to the provider, `null` marks a level unsupported, and maps may skip levels.
1113
+
1114
+ ```typescript
1115
+ const ollamaReasoningModel: Model<'openai-completions'> = {
1116
+ id: 'gpt-oss:20b',
1117
+ name: 'GPT-OSS 20B (Ollama)',
1118
+ api: 'openai-completions',
1119
+ provider: 'ollama',
1120
+ baseUrl: 'http://localhost:11434/v1',
1121
+ reasoning: true,
1122
+ input: ['text'],
1123
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1124
+ contextWindow: 131072,
1125
+ maxTokens: 32000,
1126
+ thinkingLevelMap: {
1127
+ minimal: null,
1128
+ low: null,
1129
+ medium: null,
1130
+ high: 'high',
1131
+ xhigh: null,
1132
+ },
1133
+ compat: {
1134
+ supportsDeveloperRole: false,
1135
+ supportsReasoningEffort: false,
1136
+ }
1137
+ };
1138
+ ```
1139
+
1140
+ ### Calling API Implementations Directly
1141
+
1142
+ The API implementations are importable on their own. Each module exports exactly `stream` and `streamSimple` with that API's full option typing. Direct calls bypass provider auth — pass `apiKey` explicitly:
1143
+
1144
+ ```typescript
1145
+ import { stream } from '@bastani/pi-ai/api/anthropic-messages';
1146
+
1147
+ const s = stream(claudeModel, context, {
1148
+ apiKey: process.env.ANTHROPIC_API_KEY,
1149
+ thinkingEnabled: true,
1150
+ thinkingBudgetTokens: 2048,
1151
+ });
1152
+ ```
1153
+
1154
+ Built-in API implementations live under `./api/<api-id>`:
1155
+
1156
+ | API id | Options type |
1157
+ |--------|--------------|
1158
+ | `anthropic-messages` | `AnthropicOptions` |
1159
+ | `openai-completions` | `OpenAICompletionsOptions` |
1160
+ | `openai-responses` | `OpenAIResponsesOptions` |
1161
+ | `openai-codex-responses` | `OpenAICodexResponsesOptions` |
1162
+ | `azure-openai-responses` | `AzureOpenAIResponsesOptions` |
1163
+ | `google-generative-ai` | `GoogleOptions` |
1164
+ | `google-vertex` | `GoogleVertexOptions` |
1165
+ | `mistral-conversations` | `MistralOptions` |
1166
+ | `bedrock-converse-stream` | `BedrockOptions` |
1167
+
1168
+ Importing an implementation module loads its SDK. The `./api/<id>.lazy` wrappers (used by the provider factories) defer that load to the first request when the runtime or bundler supports dynamic import chunking. Legacy raw API subpaths from older releases (`./anthropic`, `./google`, `./mistral`, `./openai-completions`, ...) were removed; use `@bastani/pi-ai/api/<api-id>`.
1169
+
1170
+ ### OpenAI Compatibility Settings
1171
+
1172
+ The `openai-completions` API is implemented by many providers with minor differences. By default, the library auto-detects compatibility settings based on `baseUrl` for a small set of known OpenAI-compatible providers (Cerebras, xAI, Chutes, DeepSeek, NVIDIA NIM, Together AI, zAi, OpenCode, Cloudflare Workers AI, etc.). For custom proxies or unknown endpoints, you can override these settings via the `compat` field. For `openai-responses` models, the compat field supports Responses-specific flags.
1173
+
1174
+ ```typescript
1175
+ interface OpenAICompletionsCompat {
1176
+ supportsStore?: boolean; // Whether provider supports the `store` field (default: true)
1177
+ supportsDeveloperRole?: boolean; // Whether provider supports `developer` role vs `system` (default: true)
1178
+ supportsReasoningEffort?: boolean; // Whether provider supports `reasoning_effort` (default: true)
1179
+ supportsUsageInStreaming?: boolean; // Whether provider supports `stream_options: { include_usage: true }` (default: true)
1180
+ supportsStrictMode?: boolean; // Whether provider supports `strict` in tool definitions (default: true)
1181
+ supportsOpenAIGrammarTools?: boolean; // Whether to emit OpenAI custom Lark/regex grammar tools; false falls back to normal function tools (default: false; the generated catalog enables it for capable models)
1182
+ sendSessionAffinityHeaders?: boolean; // Send session-affinity data from `sessionId` (default: false)
1183
+ sessionAffinityFormat?: 'openai' | 'openai-nosession' | 'openrouter'; // Format for session affinity: 'openai' uses `prompt_cache_key`, `session_id`, `x-client-request-id`, and `x-session-affinity`; 'openai-nosession' uses `prompt_cache_key`, `x-client-request-id`, and `x-session-affinity`; 'openrouter' uses `x-session-id` (default: auto-detected)
1184
+ maxTokensField?: 'max_completion_tokens' | 'max_tokens'; // Which field name to use (default: max_completion_tokens)
1185
+ requiresToolResultName?: boolean; // Whether tool results require the `name` field (default: false)
1186
+ requiresAssistantAfterToolResult?: boolean; // Whether tool results must be followed by an assistant message (default: false)
1187
+ requiresThinkingAsText?: boolean; // Whether thinking blocks must be converted to text (default: false)
1188
+ requiresReasoningContentOnAssistantMessages?: boolean; // Whether all replayed assistant messages must include empty reasoning_content when reasoning is enabled (default: auto-detected for DeepSeek)
1189
+ thinkingFormat?: 'openai' | 'openrouter' | 'deepseek' | 'together' | 'baseten' | 'zai' | 'qwen' | 'chat-template' | 'qwen-chat-template' | 'string-thinking' | 'ant-ling'; // Format for reasoning param: 'openai' uses reasoning_effort, 'openrouter' uses reasoning: { effort }, 'deepseek' uses thinking: { type } plus reasoning_effort when supported, 'together' uses reasoning: { enabled } plus reasoning_effort when supported, 'baseten' uses configurable chat_template_args plus reasoning_effort when supported, 'zai' uses thinking: { type }, 'qwen' uses enable_thinking, 'chat-template' uses configurable chat_template_kwargs, 'qwen-chat-template' uses chat_template_kwargs.enable_thinking and preserve_thinking, 'string-thinking' uses top-level thinking, 'ant-ling' uses reasoning: { effort } only for mapped efforts (default: openai)
1190
+ chatTemplateKwargs?: Record<string, string | number | boolean | null | { '$var': 'thinking.enabled' | 'thinking.effort'; omitWhenOff?: boolean }>; // chat_template_kwargs values; use $var for pi-controlled thinking values
1191
+ chatTemplateArgs?: Record<string, string | number | boolean | null | { '$var': 'thinking.enabled' | 'thinking.effort'; omitWhenOff?: boolean }>; // chat_template_args values for thinkingFormat: 'baseten'; use $var for pi-controlled thinking values
1192
+ cacheControlFormat?: 'anthropic'; // Anthropic-style cache_control on system prompt, last tool, and last user/assistant text content
1193
+ openRouterRouting?: OpenRouterRouting; // OpenRouter routing preferences (default: {})
1194
+ vercelGatewayRouting?: VercelGatewayRouting; // Vercel AI Gateway routing preferences (default: {})
1195
+ }
1196
+
1197
+ interface OpenAIResponsesCompat {
1198
+ supportsDeveloperRole?: boolean; // Whether provider supports `developer` role vs `system` (default: true)
1199
+ sessionAffinityFormat?: 'openai' | 'openai-nosession' | 'openrouter'; // Session-affinity header format: 'openai' sends `session_id` and `x-client-request-id`; 'openai-nosession' sends `x-client-request-id`; 'openrouter' sends `x-session-id`. Does not affect the `prompt_cache_key` body param (default: auto-detected)
1200
+ supportsLongCacheRetention?: boolean; // Whether provider supports `prompt_cache_retention: "24h"` (default: true)
1201
+ supportsStrictMode?: boolean; // Whether provider supports strict JSON-schema function tools (default: false; enabled in metadata for built-in OpenAI models)
1202
+ supportsOpenAIGrammarTools?: boolean; // Whether to emit OpenAI custom Lark/regex grammar tools; false falls back to normal function tools (default: false; the generated catalog enables it for capable models)
1203
+ }
1204
+ ```
1205
+
1206
+ If `compat` is not set, the library falls back to URL-based detection. If `compat` is partially set, unspecified fields use the detected defaults. This is useful for:
1207
+
1208
+ - **LiteLLM proxies**: May not support `store` field
1209
+ - **Custom inference servers**: May use non-standard field names
1210
+ - **Self-hosted endpoints**: May have different feature support
1211
+
1212
+ ## Faux Provider for Tests
1213
+
1214
+ `fauxProvider()` builds an in-memory provider with scripted responses for tests and demos:
1215
+
1216
+ ```typescript
1217
+ import {
1218
+ createModels,
1219
+ fauxAssistantMessage,
1220
+ fauxProvider,
1221
+ fauxText,
1222
+ fauxThinking,
1223
+ fauxToolCall,
1224
+ } from '@bastani/pi-ai';
1225
+
1226
+ const faux = fauxProvider({
1227
+ tokensPerSecond: 50 // optional
1228
+ });
1229
+
1230
+ const models = createModels();
1231
+ models.setProvider(faux.provider);
1232
+
1233
+ const model = faux.getModel();
1234
+ const context = {
1235
+ messages: [{ role: 'user', content: 'Summarize package.json and then call echo', timestamp: Date.now() }]
1236
+ };
1237
+
1238
+ faux.setResponses([
1239
+ fauxAssistantMessage([
1240
+ fauxThinking('Need to inspect package metadata first.'),
1241
+ fauxToolCall('echo', { text: 'package.json' })
1242
+ ], { stopReason: 'toolUse' })
1243
+ ]);
1244
+
1245
+ const first = await models.complete(model, context, {
1246
+ sessionId: 'session-1',
1247
+ cacheRetention: 'short'
1248
+ });
1249
+ context.messages.push(first);
1250
+
1251
+ context.messages.push({
1252
+ role: 'toolResult',
1253
+ toolCallId: first.content.find((block) => block.type === 'toolCall')!.id,
1254
+ toolName: 'echo',
1255
+ content: [{ type: 'text', text: 'package.json contents here' }],
1256
+ isError: false,
1257
+ timestamp: Date.now()
1258
+ });
1259
+
1260
+ faux.setResponses([
1261
+ fauxAssistantMessage([
1262
+ fauxThinking('Now I can summarize the tool output.'),
1263
+ fauxText('Here is the summary.')
1264
+ ])
1265
+ ]);
1266
+
1267
+ const s = models.stream(model, context);
1268
+ for await (const event of s) {
1269
+ console.log(event.type);
1270
+ }
1271
+
1272
+ // Optional: multiple faux models for model-switching tests
1273
+ const multiModel = fauxProvider({
1274
+ provider: 'faux-multi',
1275
+ models: [
1276
+ { id: 'faux-fast', reasoning: false },
1277
+ { id: 'faux-thinker', reasoning: true }
1278
+ ]
1279
+ });
1280
+ models.setProvider(multiModel.provider);
1281
+ const thinker = multiModel.getModel('faux-thinker');
1282
+
1283
+ console.log(thinker?.reasoning);
1284
+ console.log(faux.getPendingResponseCount());
1285
+ console.log(faux.state.callCount);
1286
+ ```
1287
+
1288
+ Notes:
1289
+ - Responses are consumed from a queue in request start order.
1290
+ - If the queue is empty, the faux provider returns an assistant error message with `errorMessage: "No more faux responses queued"`.
1291
+ - Use `faux.setResponses([...])` to replace the remaining queue and `faux.appendResponses([...])` to add more responses.
1292
+ - `faux.models` exposes all faux models. `faux.getModel()` returns the first one, and `faux.getModel(id)` returns a specific one.
1293
+ - Use `fauxAssistantMessage(...)` for scripted assistant replies. Use `fauxText(...)`, `fauxThinking(...)`, and `fauxToolCall(...)` to build content blocks without filling in low-level fields manually.
1294
+ - Usage is estimated at roughly 1 token per 4 characters. When `sessionId` is present and `cacheRetention` is not `"none"`, prompt cache reads and writes are simulated automatically.
1295
+ - Tool call arguments stream incrementally via `toolcall_delta` chunks.
1296
+ - By default, each streamed chunk is emitted on its own microtask. Set `tokensPerSecond` to pace chunk delivery in real time.
1297
+ - The intended use is one deterministic scripted flow per handle. If you need independent concurrent flows, create separate faux providers with distinct `provider` ids.
1298
+
1299
+ ## Cross-Provider Handoffs
1300
+
1301
+ The library supports seamless handoffs between different LLM providers within the same conversation. This allows you to switch models mid-conversation while preserving context, including thinking blocks, tool calls, and tool results.
1302
+
1303
+ When messages from one provider are sent to a different provider, the library automatically transforms them for compatibility:
1304
+
1305
+ - **User and tool result messages** are passed through unchanged
1306
+ - **Assistant messages from the same provider/API** are preserved as-is
1307
+ - **Assistant messages from different providers** have their thinking blocks converted to text with `<thinking>` tags
1308
+ - **Tool calls and regular text** are preserved unchanged
1309
+
1310
+ ```typescript
1311
+ import { createModels, type Context } from '@bastani/pi-ai';
1312
+ import { anthropicProvider } from '@bastani/pi-ai/providers/anthropic';
1313
+ import { openaiProvider } from '@bastani/pi-ai/providers/openai';
1314
+ import { googleProvider } from '@bastani/pi-ai/providers/google';
1315
+
1316
+ const models = createModels();
1317
+ models.setProvider(anthropicProvider());
1318
+ models.setProvider(openaiProvider());
1319
+ models.setProvider(googleProvider());
1320
+
1321
+ const context: Context = { messages: [] };
1322
+
1323
+ // Start with Claude
1324
+ const claude = models.getModel('anthropic', 'claude-sonnet-4-5')!;
1325
+ context.messages.push({ role: 'user', content: 'What is 25 * 18?', timestamp: Date.now() });
1326
+ context.messages.push(await models.completeSimple(claude, context, { reasoning: 'medium' }));
1327
+
1328
+ // Switch to GPT-5 - it will see Claude's thinking as <thinking> tagged text
1329
+ const gpt5 = models.getModel('openai', 'gpt-5-mini')!;
1330
+ context.messages.push({ role: 'user', content: 'Is that calculation correct?', timestamp: Date.now() });
1331
+ context.messages.push(await models.complete(gpt5, context));
1332
+
1333
+ // Switch to Gemini
1334
+ const gemini = models.getModel('google', 'gemini-2.5-flash')!;
1335
+ context.messages.push({ role: 'user', content: 'What was the original question?', timestamp: Date.now() });
1336
+ const geminiResponse = await models.complete(gemini, context);
1337
+ ```
1338
+
1339
+ All providers can handle messages from other providers — text, tool calls and results (including images), thinking blocks (transformed to tagged text), and aborted messages with partial content. This enables flexible workflows: start with a fast model, switch to a more capable one for complex reasoning, or maintain continuity across provider outages.
1340
+
1341
+ ## Context Serialization
1342
+
1343
+ The `Context` object can be easily serialized and deserialized using standard JSON methods, making it simple to persist conversations, implement chat history, or transfer contexts between services:
1344
+
1345
+ ```typescript
1346
+ const context: Context = {
1347
+ systemPrompt: 'You are a helpful assistant.',
1348
+ messages: [
1349
+ { role: 'user', content: 'What is TypeScript?', timestamp: Date.now() }
1350
+ ]
1351
+ };
1352
+
1353
+ const model = models.getModel('openai', 'gpt-4o-mini')!;
1354
+ const response = await models.complete(model, context);
1355
+ context.messages.push(response);
1356
+
1357
+ // Serialize the entire context
1358
+ const serialized = JSON.stringify(context);
1359
+
1360
+ // Save to database, localStorage, file, etc.
1361
+ localStorage.setItem('conversation', serialized);
1362
+
1363
+ // Later: deserialize and continue the conversation
1364
+ const restored: Context = JSON.parse(localStorage.getItem('conversation')!);
1365
+ restored.messages.push({ role: 'user', content: 'Tell me more about its type system', timestamp: Date.now() });
1366
+
1367
+ // Continue with any model
1368
+ const newModel = models.getModel('anthropic', 'claude-3-5-haiku-20241022')!;
1369
+ const continuation = await models.complete(newModel, restored);
1370
+ ```
1371
+
1372
+ Models are plain serializable data too — no functions or implementations attached — so persisting "which model was this conversation using" is a `JSON.stringify` away.
1373
+
1374
+ > **Note**: If the context contains images (encoded as base64 as shown in the Image Input section), those will also be serialized.
1375
+
1376
+ ## Browser Usage
1377
+
1378
+ The library supports browser environments. The core entrypoint and provider factories are side-effect free and bundle cleanly. Environment variables are not available in browsers, so pass API keys explicitly — or inject a `CredentialStore` (e.g. localStorage-backed) and let provider auth resolve from stored credentials:
1379
+
1380
+ ```typescript
1381
+ import { createModels } from '@bastani/pi-ai';
1382
+ import { anthropicProvider } from '@bastani/pi-ai/providers/anthropic';
1383
+
1384
+ const models = createModels();
1385
+ models.setProvider(anthropicProvider());
1386
+
1387
+ const model = models.getModel('anthropic', 'claude-3-5-haiku-20241022')!;
1388
+ const response = await models.complete(model, {
1389
+ messages: [{ role: 'user', content: 'Hello!', timestamp: Date.now() }]
1390
+ }, {
1391
+ apiKey: 'your-api-key'
1392
+ });
1393
+ ```
1394
+
1395
+ > **Security Warning**: Exposing API keys in frontend code is dangerous. Anyone can extract and abuse your keys. Only use this approach for internal tools or demos. For production applications, use a backend proxy that keeps your API keys secure.
1396
+
1397
+ Browser compatibility notes:
1398
+
1399
+ - Amazon Bedrock (`bedrock-converse-stream`) is not supported in browser environments. It can still appear in model lists; calls fail at runtime.
1400
+ - OAuth login flows are Node-only. They are lazy-loaded behind bundler-opaque imports, so registering an OAuth-capable provider does not pull Node-only code into a browser bundle — only actually logging in would.
1401
+ - Use a server-side proxy or backend service if you need Bedrock or OAuth-based auth from a web app.
1402
+
1403
+ ## Bundling and Tree Shaking
1404
+
1405
+ For small bundles, import only the providers you need:
1406
+
1407
+ ```typescript
1408
+ import { createModels } from '@bastani/pi-ai';
1409
+ import { openaiProvider } from '@bastani/pi-ai/providers/openai';
1410
+
1411
+ const models = createModels();
1412
+ models.setProvider(openaiProvider());
1413
+ ```
1414
+
1415
+ Rules:
1416
+
1417
+ - `@bastani/pi-ai` is the core entrypoint and does not import built-in catalogs, provider factories, or SDK implementations.
1418
+ - `@bastani/pi-ai/providers/<provider>` imports that provider's catalog and lazy API wrapper only.
1419
+ - `@bastani/pi-ai/providers/all` imports every built-in provider factory and all catalogs. Use it only when you want the full built-in set.
1420
+ - With code splitting, provider SDKs stay in lazy chunks and load on first request.
1421
+ - Without code splitting, bundlers fold reachable lazy API implementations into the single bundle. A single-provider bundle then includes that provider's SDK; `providers/all` includes all statically visible SDKs. Bedrock is the exception: its AWS SDK implementation is loaded through a bundler-opaque Node-only import.
1422
+ - Importing `@bastani/pi-ai/api/<api-id>` directly loads that API implementation and its SDK immediately.
1423
+
1424
+ Avoid `@bastani/pi-ai/compat` in new bundled apps; it preserves the old global API and imports the full built-in catalog surface.
1425
+
1426
+ For single-file Node ESM bundles, some SDK dependencies may still use dynamic CommonJS `require()` internally. If you see errors such as `Dynamic require of "child_process" is not supported`, add a Node `require` shim to the bundle. With esbuild:
1427
+
1428
+ ```bash
1429
+ esbuild app.js --bundle --platform=node --format=esm \
1430
+ --banner:js='import { createRequire } from "module";const require = createRequire(import.meta.url);' \
1431
+ --outfile=app.bundle.js
1432
+ ```
1433
+
1434
+ This is only for Node bundles; it is not a browser or Cloudflare Workers workaround.
1435
+
1436
+ Bedrock is Node-only. Add it like any other provider:
1437
+
1438
+ ```typescript
1439
+ import { createModels } from '@bastani/pi-ai';
1440
+ import { amazonBedrockProvider } from '@bastani/pi-ai/providers/amazon-bedrock';
1441
+
1442
+ const models = createModels();
1443
+ models.setProvider(amazonBedrockProvider());
1444
+ ```
1445
+
1446
+ In normal Node package usage and code-split bundles, Bedrock loads its AWS SDK implementation lazily. For a standalone single-file bundle that must include Bedrock support, register the implementation module explicitly:
1447
+
1448
+ ```typescript
1449
+ import { setBedrockProviderModule } from '@bastani/pi-ai/api/bedrock-converse-stream.lazy';
1450
+ import { bedrockProviderModule } from '@bastani/pi-ai/bedrock-provider';
1451
+
1452
+ setBedrockProviderModule(bedrockProviderModule);
1453
+ ```
1454
+
1455
+ That explicit override bundles the AWS SDK. Without it, Bedrock's opaque runtime import expects the package's Bedrock implementation file to be available at runtime.
1456
+
1457
+ ### Provider-Scoped Environment Overrides
1458
+
1459
+ Pass `env` in stream options to scope provider configuration to a request. Values in `env` are used before process environment variables for provider auth and configuration such as Cloudflare account IDs, Azure OpenAI settings, Vertex project/location, Bedrock settings, `PI_CACHE_RETENTION`, and `HTTP_PROXY`/`HTTPS_PROXY`.
1460
+
1461
+ ```typescript
1462
+ const models = builtinModels();
1463
+ const model = models.getModel('cloudflare-ai-gateway', 'workers-ai/@cf/moonshotai/kimi-k2.6')!;
1464
+
1465
+ const response = await models.complete(model, context, {
1466
+ env: {
1467
+ CLOUDFLARE_API_KEY: '...',
1468
+ CLOUDFLARE_ACCOUNT_ID: 'account-id',
1469
+ CLOUDFLARE_GATEWAY_ID: 'gateway-id'
1470
+ }
1471
+ });
1472
+ ```
1473
+
1474
+ Use this when one process needs different provider settings per request, or when ambient environment variables should not leak into a provider call.
1475
+
1476
+ ## OAuth Providers
1477
+
1478
+ Several providers support OAuth authentication instead of static API keys:
1479
+
1480
+ - **Anthropic** (Claude Pro/Max subscription)
1481
+ - **OpenAI Codex** (ChatGPT Plus/Pro subscription, access to GPT-5.x Codex models)
1482
+ - **GitHub Copilot** (Copilot subscription)
1483
+ - **OpenRouter** (OAuth PKCE that mints a user-controlled API key)
1484
+
1485
+ Each of these providers carries an `OAuthAuth` on `provider.auth.oauth` with three operations: `login(interaction)` uses the provider-neutral `AuthInteraction.prompt()`/`notify()` protocol and returns a credential, `refresh(credential, signal)` refreshes expiring credentials when applicable, and `toAuth(credential)` derives request auth (GitHub Copilot's per-account base URL comes from here). Provider login interactions and refresh calls always carry a concrete abort signal. Refresh is automatic: `models.getAuth(providerId)` and request paths refresh expired tokens under a credential-store lock, so concurrent requests and processes cannot double-refresh. OpenRouter's OAuth flow instead returns a permanent API key, so its refresh operation is a no-op.
1486
+
1487
+ ```typescript
1488
+ import { createModels } from '@bastani/pi-ai';
1489
+ import { anthropicProvider } from '@bastani/pi-ai/providers/anthropic';
1490
+
1491
+ const models = createModels({ credentials: myStore }); // persistent CredentialStore
1492
+ models.setProvider(anthropicProvider());
1493
+
1494
+ // Login: Models drives the flow and persists the credential
1495
+ await models.login('anthropic', 'oauth', {
1496
+ prompt: async (p) => {
1497
+ // p.type: 'text' | 'secret' | 'select' | 'manual_code'
1498
+ // manual_code prompts race a local callback server; p.signal aborts them when the server wins
1499
+ return await askUser(p.message);
1500
+ },
1501
+ notify: (event) => {
1502
+ // event.type: 'info' | 'auth_url' | 'device_code' | 'progress'
1503
+ if (event.type === 'info') {
1504
+ console.log(event.message);
1505
+ for (const link of event.links ?? []) console.log(`${link.label ?? 'More information'}: ${link.url}`);
1506
+ }
1507
+ if (event.type === 'auth_url') console.log(`Open: ${event.url}`);
1508
+ if (event.type === 'device_code') console.log(`Code: ${event.userCode} at ${event.verificationUri}`);
1509
+ if (event.type === 'progress') console.log(event.message);
1510
+ },
1511
+ });
1512
+
1513
+ // From here on, requests resolve and refresh the token automatically
1514
+ const model = models.getModel('anthropic', 'claude-sonnet-4-5')!;
1515
+ await models.complete(model, context);
1516
+
1517
+ // Logout
1518
+ await models.logout('anthropic');
1519
+ ```
1520
+
1521
+ ### Vertex AI
1522
+
1523
+ Vertex AI models support either a Google Cloud API key or Application Default Credentials (ADC). Its provider-owned API-key login flow can configure either method:
1524
+
1525
+ - **API key**: Set `GOOGLE_CLOUD_API_KEY` or pass `apiKey` in the call options.
1526
+ - **Local development (ADC)**: Run `gcloud auth application-default login`
1527
+ - **CI/Production (ADC)**: Set `GOOGLE_APPLICATION_CREDENTIALS` to point to a service account JSON key file
1528
+
1529
+ When using ADC, also set `GOOGLE_CLOUD_PROJECT` (or `GCLOUD_PROJECT`) and `GOOGLE_CLOUD_LOCATION`. You can also pass `project`/`location` in the call options. When using `GOOGLE_CLOUD_API_KEY`, `project` and `location` are not required.
1530
+
1531
+ ```bash
1532
+ # Local (uses your user credentials)
1533
+ gcloud auth application-default login
1534
+ export GOOGLE_CLOUD_PROJECT="my-project"
1535
+ export GOOGLE_CLOUD_LOCATION="us-central1"
1536
+
1537
+ # CI/Production (service account key file)
1538
+ export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
1539
+ ```
1540
+
1541
+ Official docs: [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials)
1542
+
1543
+ ### CLI Login
1544
+
1545
+ The quickest way to authenticate:
1546
+
1547
+ ```bash
1548
+ npx @bastani/pi-ai login # interactive provider selection
1549
+ npx @bastani/pi-ai login anthropic # login to specific provider
1550
+ npx @bastani/pi-ai list # list available providers
1551
+ ```
1552
+
1553
+ Credentials are saved to `auth.json` in the current directory.
1554
+
1555
+ ### Programmatic OAuth
1556
+
1557
+ Built-in login and refresh flows are private provider implementations. Use provider-owned `OAuthAuth`, which composes with `CredentialStore` and gets locked auto-refresh through `Models`. The `@bastani/pi-ai/oauth` entry point retains only type declarations required by coding-agent extension OAuth compatibility.
1558
+
1559
+ Provider notes:
1560
+
1561
+ **OpenAI Codex**: Requires a ChatGPT Plus or Pro subscription. Provides access to GPT-5.x Codex models with extended context windows and reasoning capabilities. The library automatically handles session-based prompt caching when `sessionId` is provided in stream options unless `cacheRetention` is `"none"`. You can set `transport` in stream options to `"sse"`, `"websocket"`, or `"auto"` for Codex Responses transport selection. When using WebSocket with a `sessionId` and cache retention enabled, connections are reused per session and expire after 5 minutes of inactivity.
1562
+
1563
+ **Azure OpenAI (Responses)**: Uses the Responses API only. Set `AZURE_OPENAI_API_KEY` and either `AZURE_OPENAI_BASE_URL` or `AZURE_OPENAI_RESOURCE_NAME`. `AZURE_OPENAI_BASE_URL` supports both `https://<resource>.openai.azure.com` and `https://<resource>.cognitiveservices.azure.com`; root endpoints are normalized to `.../openai/v1` automatically. Use `AZURE_OPENAI_API_VERSION` (defaults to `v1`) to override the API version if needed. Deployment names are treated as model IDs by default, override with `azureDeploymentName` or `AZURE_OPENAI_DEPLOYMENT_NAME_MAP` using comma-separated `model-id=deployment` pairs (for example `gpt-4o-mini=my-deployment,gpt-4o=prod`). Legacy deployment-based URLs are intentionally unsupported.
1564
+
1565
+ **GitHub Copilot**: If you get "The requested model is not supported" error, enable the model manually in VS Code: open Copilot Chat, click the model selector, select the model (warning icon), and click "Enable".
1566
+
1567
+ ## Migrating from the Old Global API
1568
+
1569
+ Older versions exposed a global API: `stream()`/`complete()` dispatching on `model.api` via a global registry, sync `getModel()`/`getModels()`/`getProviders()` catalog reads, `registerApiProvider()`, `getEnvApiKey()`, and per-API lazy stream functions. That surface lives unchanged on the **compat entrypoint**:
1570
+
1571
+ ```typescript
1572
+ // Before
1573
+ import { getModel, complete } from '@bastani/pi-ai';
1574
+
1575
+ // After (verbatim behavior, one import-path change)
1576
+ import { getModel, complete } from '@bastani/pi-ai/compat';
1577
+ ```
1578
+
1579
+ Compat is a strict superset of the root entrypoint, so a file can switch its import path wholesale. It will be removed in a future release; migrate to `createModels()` + provider factories:
1580
+
1581
+ | Old | New |
1582
+ |-----|-----|
1583
+ | `getModel('openai', 'gpt-4o-mini')` | `models.getModel('openai', 'gpt-4o-mini')` or `getBuiltinModel()` from `providers/all` |
1584
+ | `getModels('anthropic')` / `getProviders()` | `models.getModels('anthropic')` / `models.getProviders()` or `getBuiltin*` |
1585
+ | `stream(model, ctx, opts)` (env-key injection) | `models.stream(model, ctx, opts)` (provider auth resolution) |
1586
+ | `registerApiProvider({ api, stream, streamSimple })` | `createProvider({ id, auth, models, api })` + `models.setProvider()` |
1587
+ | `getEnvApiKey('openai')` | `await models.getAuth(model.provider)` |
1588
+ | `streamAnthropic(model, ctx, opts)` | `stream` from `@bastani/pi-ai/api/anthropic-messages`, or a provider in a collection |
1589
+ | `registerFauxProvider()` | `fauxProvider()` + `models.setProvider()` |
1590
+
1591
+ ## Development
1592
+
1593
+ ### Adding a New Provider
1594
+
1595
+ Adding a new LLM provider requires changes across multiple files. The layered layout: API implementations live in `src/api/`, provider factories in `src/providers/`, stable generated catalog wrappers live in `src/providers/<id>.models.ts`, and `src/models.generated.ts` registers them. This checklist covers all necessary steps:
1596
+
1597
+ #### 1. Core Types (`src/types.ts`)
1598
+
1599
+ - Add the API identifier to `KnownApi` (for example `"bedrock-converse-stream"`), if it is a new API
1600
+ - Add the provider name to `KnownProvider` (for example `"amazon-bedrock"`)
1601
+ - Add the options type to `ApiOptionsMap`
1602
+
1603
+ #### 2. API Implementation (`src/api/<api-id>.ts`, only for a new API)
1604
+
1605
+ Create a new API implementation file (for example `bedrock-converse-stream.ts`) that exports exactly `stream` and `streamSimple`, plus:
1606
+
1607
+ - An options interface extending `StreamOptions` (for example `BedrockOptions`)
1608
+ - Message conversion functions to transform `Context` to provider format
1609
+ - Tool conversion if the provider supports tools
1610
+ - Response parsing to emit standardized events (`text`, `tool_call`, `thinking`, `usage`, `stop`)
1611
+
1612
+ Add a lazy wrapper `src/api/<api-id>.lazy.ts` (`<name>Api()` via `lazyApi()`) so providers can reference the implementation without importing its SDK. Add any root-level `export type` re-exports in `src/index.ts` that should remain available from `@bastani/pi-ai`.
1613
+
1614
+ #### 3. Model Generation (`scripts/generate-models.ts`, `scripts/generate-image-models.ts`)
1615
+
1616
+ - Add logic to fetch and parse models from the provider's source (e.g., models.dev API)
1617
+ - Map chat/tool-capable provider model data to the standardized `Model` interface via `scripts/generate-models.ts`; hydration groups the ignored `src/providers/data/<id>.json` values by API, while stable `src/providers/<id>.models.ts` wrappers derive exact model/API types directly from those JSON keys
1618
+ - Map image-generation provider model data to the standardized `ImagesModel` interface via `scripts/generate-image-models.ts`
1619
+ - Handle provider-specific quirks (pricing format, capability flags, model ID transformations)
1620
+
1621
+ #### 4. Provider Factory (`src/providers/<id>.ts`)
1622
+
1623
+ - `createProvider()` wiring catalog + auth + the lazy API wrapper
1624
+ - Auth: `envApiKeyAuth` for standard key providers, a custom `ApiKeyAuth` for ambient auth (AWS profiles, ADC), `lazyOAuth` where an OAuth flow exists
1625
+ - Register the factory in `src/providers/all.ts`
1626
+ - If it is a new API: register it in the builtin list in `src/compat.ts` and add the package subpath export in `package.json`
1627
+
1628
+ #### 5. Tests (`test/`)
1629
+
1630
+ Create or update test files to cover the new provider:
1631
+
1632
+ - `stream.test.ts` - Basic streaming and tool use
1633
+ - `tokens.test.ts` - Token usage reporting
1634
+ - `abort.test.ts` - Request cancellation
1635
+ - `empty.test.ts` - Empty message handling
1636
+ - `context-overflow.test.ts` - Context limit errors
1637
+ - `image-limits.test.ts` - Image support (if applicable)
1638
+ - `unicode-surrogate.test.ts` - Unicode handling
1639
+ - `tool-call-without-result.test.ts` - Orphaned tool calls
1640
+ - `image-tool-result.test.ts` - Images in tool results
1641
+ - `total-tokens.test.ts` - Token counting accuracy
1642
+ - `cross-provider-handoff.test.ts` - Cross-provider context replay
1643
+ - `providers.test.ts` - Provider listing and auth resolution
1644
+
1645
+ For `cross-provider-handoff.test.ts`, add at least one provider/model pair. If the provider exposes multiple model families (for example GPT and Claude), add at least one pair per family.
1646
+
1647
+ For providers with non-standard auth (AWS, Google Vertex), create a utility like `bedrock-utils.ts` with credential detection helpers.
1648
+
1649
+ #### 6. Downstream consumers
1650
+
1651
+ Atomic (`@bastani/atomic`) consumes this package in place of `@earendil-works/pi-ai`. After adding a provider here, switch Atomic onto the published `@bastani/pi-ai` version and update its provider docs if the new provider should appear in the coding-agent catalog.
1652
+
1653
+ #### 7. Documentation
1654
+
1655
+ Update `README.md`:
1656
+
1657
+ - Add to the Supported Providers list
1658
+ - Document any provider-specific options or authentication requirements
1659
+ - Add environment variable to the Environment Variables section
1660
+
1661
+ #### 8. Changelog
1662
+
1663
+ Add an entry to `CHANGELOG.md` under `## [Unreleased]`:
1664
+
1665
+ ```markdown
1666
+ ### Added
1667
+ - Added support for [Provider Name] provider ([#PR](link) by [@author](link))
1668
+ ```
1669
+
1670
+ ## License
1671
+
1672
+ MIT