@opencode/ai 2.2.5 → 2.2.7

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 (306) hide show
  1. package/README.md +228 -72
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/cache-policy.d.ts +1 -1
  5. package/dist/cache-policy.js +16 -4
  6. package/dist/decision-client.d.ts +3 -3
  7. package/dist/decision.d.ts +30 -125
  8. package/dist/decision.js +27 -15
  9. package/dist/effect.d.ts +10 -15
  10. package/dist/effect.js +6 -6
  11. package/dist/effort-updates.d.ts +3 -3
  12. package/dist/effort-updates.js +2 -2
  13. package/dist/embedding-client.d.ts +21 -0
  14. package/dist/embedding-client.js +30 -0
  15. package/dist/embedding.d.ts +111 -0
  16. package/dist/embedding.js +75 -0
  17. package/dist/experimental/cloudflare-run-extraction.d.ts +7 -3
  18. package/dist/experimental/cloudflare-run-extraction.js +4 -1
  19. package/dist/experimental/extraction.d.ts +10 -40
  20. package/dist/experimental/extraction.js +14 -13
  21. package/dist/experimental.d.ts +8 -8
  22. package/dist/experimental.js +4 -4
  23. package/dist/generation.d.ts +0 -2
  24. package/dist/generation.js +2 -2
  25. package/dist/image-client.d.ts +13 -7
  26. package/dist/image-client.js +1 -1
  27. package/dist/image.d.ts +357 -465
  28. package/dist/image.js +17 -18
  29. package/dist/index.d.ts +35 -467
  30. package/dist/index.js +23 -17
  31. package/dist/llm.d.ts +65 -266
  32. package/dist/llm.js +101 -92
  33. package/dist/loop.d.ts +38 -0
  34. package/dist/loop.js +136 -0
  35. package/dist/media-model.d.ts +1 -1
  36. package/dist/media-model.js +8 -6
  37. package/dist/media.d.ts +9 -0
  38. package/dist/media.js +37 -2
  39. package/dist/protocols/alibaba-chat.d.ts +9 -1
  40. package/dist/protocols/alibaba-chat.js +3 -3
  41. package/dist/protocols/alibaba-images.d.ts +2 -2
  42. package/dist/protocols/alibaba-messages.js +3 -3
  43. package/dist/protocols/alibaba-responses.js +8 -20
  44. package/dist/protocols/anthropic-messages.d.ts +1 -1
  45. package/dist/protocols/anthropic-messages.js +57 -176
  46. package/dist/protocols/assemblyai-transcription.d.ts +2 -2
  47. package/dist/protocols/bedrock-converse.js +10 -16
  48. package/dist/protocols/cartesia-speech.d.ts +2 -2
  49. package/dist/protocols/cloudflare-workers-ai-images.d.ts +2 -2
  50. package/dist/protocols/cohere-chat.js +9 -12
  51. package/dist/protocols/deepgram-speech.d.ts +2 -2
  52. package/dist/protocols/deepgram-transcription.d.ts +2 -2
  53. package/dist/protocols/elevenlabs-speech.d.ts +2 -2
  54. package/dist/protocols/elevenlabs-transcription.d.ts +2 -2
  55. package/dist/protocols/gemini.d.ts +3 -0
  56. package/dist/protocols/gemini.js +54 -72
  57. package/dist/protocols/google-embed-content.d.ts +34 -0
  58. package/dist/protocols/google-embed-content.js +110 -0
  59. package/dist/protocols/google-images.d.ts +2 -2
  60. package/dist/protocols/google-interactions.d.ts +3 -4
  61. package/dist/protocols/google-interactions.js +44 -30
  62. package/dist/protocols/google-speech.d.ts +2 -2
  63. package/dist/protocols/google-transcription.d.ts +2 -2
  64. package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
  65. package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
  66. package/dist/protocols/google-video.d.ts +2 -2
  67. package/dist/protocols/index.d.ts +3 -0
  68. package/dist/protocols/index.js +3 -0
  69. package/dist/protocols/meta-images.d.ts +2 -2
  70. package/dist/protocols/meta-responses.js +26 -23
  71. package/dist/protocols/minimax-images.d.ts +2 -2
  72. package/dist/protocols/mistral-chat.js +7 -10
  73. package/dist/protocols/open-responses-channel.js +6 -19
  74. package/dist/protocols/open-responses-continuation.d.ts +1 -5
  75. package/dist/protocols/open-responses-continuation.js +1 -3
  76. package/dist/protocols/open-responses.d.ts +2 -22
  77. package/dist/protocols/open-responses.js +41 -23
  78. package/dist/protocols/openai-chat.d.ts +27 -23
  79. package/dist/protocols/openai-chat.js +62 -57
  80. package/dist/protocols/openai-compatible-chat.d.ts +2 -1
  81. package/dist/protocols/openai-compatible-responses.d.ts +2 -2
  82. package/dist/protocols/openai-compatible-responses.js +1 -1
  83. package/dist/protocols/openai-decisions.js +15 -2
  84. package/dist/protocols/openai-embeddings.d.ts +16 -0
  85. package/dist/protocols/openai-embeddings.js +76 -0
  86. package/dist/protocols/openai-images.d.ts +2 -2
  87. package/dist/protocols/openai-responses.js +10 -29
  88. package/dist/protocols/openai-speech.d.ts +2 -2
  89. package/dist/protocols/openai-transcription.d.ts +2 -2
  90. package/dist/protocols/runway-video.d.ts +2 -2
  91. package/dist/protocols/shared.d.ts +14 -7
  92. package/dist/protocols/shared.js +40 -15
  93. package/dist/protocols/system-one.d.ts +4 -4
  94. package/dist/protocols/system-one.js +8 -1
  95. package/dist/protocols/utils/bedrock-cache.js +2 -5
  96. package/dist/protocols/utils/bedrock-media.d.ts +0 -3
  97. package/dist/protocols/utils/cache.d.ts +3 -0
  98. package/dist/protocols/utils/cache.js +15 -2
  99. package/dist/protocols/utils/image-sizing.d.ts +1 -1
  100. package/dist/protocols/utils/responses-checkpoint.js +1 -1
  101. package/dist/protocols/utils/responses-compaction.d.ts +1 -1
  102. package/dist/protocols/utils/responses-compaction.js +6 -5
  103. package/dist/protocols/utils/responses-hosted-tools.d.ts +97 -1
  104. package/dist/protocols/utils/responses-hosted-tools.js +31 -0
  105. package/dist/protocols/utils/tool-stream.d.ts +5 -271
  106. package/dist/protocols/utils/tool-stream.js +3 -13
  107. package/dist/protocols/venice-chat.d.ts +7 -1
  108. package/dist/protocols/venice-chat.js +4 -4
  109. package/dist/protocols/xai-images.d.ts +2 -2
  110. package/dist/protocols/xai-responses.js +5 -25
  111. package/dist/protocols/xai-video.d.ts +2 -2
  112. package/dist/protocols/zai-chat.d.ts +9 -1
  113. package/dist/protocols/zai-chat.js +1 -1
  114. package/dist/protocols/zai-images.d.ts +2 -2
  115. package/dist/protocols/zai-messages.js +3 -3
  116. package/dist/provider-error.d.ts +0 -1
  117. package/dist/provider-error.js +7 -80
  118. package/dist/providers/alibaba/embeddings.d.ts +2 -0
  119. package/dist/providers/alibaba/embeddings.js +1 -0
  120. package/dist/providers/alibaba.d.ts +70 -4
  121. package/dist/providers/alibaba.js +20 -2
  122. package/dist/providers/amazon-bedrock-mantle.d.ts +7 -3
  123. package/dist/providers/amazon-bedrock-mantle.js +6 -3
  124. package/dist/providers/amazon-bedrock.d.ts +6 -7
  125. package/dist/providers/amazon-bedrock.js +1 -1
  126. package/dist/providers/anthropic-compatible.d.ts +7 -8
  127. package/dist/providers/anthropic-compatible.js +2 -5
  128. package/dist/providers/anthropic.d.ts +8 -9
  129. package/dist/providers/anthropic.js +2 -7
  130. package/dist/providers/assemblyai.d.ts +2 -2
  131. package/dist/providers/assemblyai.js +2 -7
  132. package/dist/providers/azure/embeddings.d.ts +2 -0
  133. package/dist/providers/azure/embeddings.js +1 -0
  134. package/dist/providers/azure/messages.d.ts +2 -0
  135. package/dist/providers/azure/messages.js +1 -0
  136. package/dist/providers/azure.d.ts +325 -7
  137. package/dist/providers/azure.js +40 -9
  138. package/dist/providers/baseten.d.ts +7 -5
  139. package/dist/providers/baseten.js +7 -21
  140. package/dist/providers/cartesia.d.ts +1 -1
  141. package/dist/providers/cerebras.d.ts +7 -5
  142. package/dist/providers/cerebras.js +4 -15
  143. package/dist/providers/cloudflare-ai-gateway.d.ts +23 -13
  144. package/dist/providers/cloudflare-ai-gateway.js +28 -40
  145. package/dist/providers/cloudflare-shared.d.ts +9 -0
  146. package/dist/providers/cloudflare-shared.js +25 -0
  147. package/dist/providers/cloudflare-workers-ai.d.ts +6 -4
  148. package/dist/providers/cloudflare-workers-ai.js +4 -20
  149. package/dist/providers/cohere/chat.js +2 -7
  150. package/dist/providers/cohere/embeddings.d.ts +2 -0
  151. package/dist/providers/cohere/embeddings.js +1 -0
  152. package/dist/providers/cohere.d.ts +14 -5
  153. package/dist/providers/cohere.js +23 -13
  154. package/dist/providers/deepgram.d.ts +2 -2
  155. package/dist/providers/deepgram.js +2 -7
  156. package/dist/providers/deepinfra/embeddings.d.ts +2 -0
  157. package/dist/providers/deepinfra/embeddings.js +1 -0
  158. package/dist/providers/deepinfra.d.ts +10 -5
  159. package/dist/providers/deepinfra.js +20 -14
  160. package/dist/providers/deepseek.d.ts +7 -5
  161. package/dist/providers/deepseek.js +3 -14
  162. package/dist/providers/digitalocean/embeddings.d.ts +2 -0
  163. package/dist/providers/digitalocean/embeddings.js +1 -0
  164. package/dist/providers/digitalocean.d.ts +18 -5
  165. package/dist/providers/digitalocean.js +28 -14
  166. package/dist/providers/elevenlabs.d.ts +2 -2
  167. package/dist/providers/elevenlabs.js +2 -7
  168. package/dist/providers/fireworks/embeddings.d.ts +2 -0
  169. package/dist/providers/fireworks/embeddings.js +1 -0
  170. package/dist/providers/fireworks.d.ts +10 -5
  171. package/dist/providers/fireworks.js +17 -14
  172. package/dist/providers/google/embeddings.d.ts +2 -0
  173. package/dist/providers/google/embeddings.js +1 -0
  174. package/dist/providers/google/interactions.d.ts +1 -1
  175. package/dist/providers/google/interactions.js +2 -7
  176. package/dist/providers/google-vertex/embeddings.d.ts +2 -0
  177. package/dist/providers/google-vertex/embeddings.js +1 -0
  178. package/dist/providers/google-vertex-chat.d.ts +4 -3
  179. package/dist/providers/google-vertex-chat.js +3 -29
  180. package/dist/providers/google-vertex-interactions.d.ts +3 -3
  181. package/dist/providers/google-vertex-messages.d.ts +3 -3
  182. package/dist/providers/google-vertex-messages.js +3 -29
  183. package/dist/providers/google-vertex-mistral.d.ts +3 -3
  184. package/dist/providers/google-vertex-mistral.js +3 -29
  185. package/dist/providers/google-vertex-responses.d.ts +3 -3
  186. package/dist/providers/google-vertex-responses.js +4 -30
  187. package/dist/providers/google-vertex-shared.d.ts +31 -0
  188. package/dist/providers/google-vertex-shared.js +25 -0
  189. package/dist/providers/google-vertex.d.ts +10 -3
  190. package/dist/providers/google-vertex.js +52 -0
  191. package/dist/providers/google.d.ts +21 -13
  192. package/dist/providers/google.js +23 -19
  193. package/dist/providers/groq.d.ts +10 -5
  194. package/dist/providers/groq.js +4 -15
  195. package/dist/providers/meta.d.ts +6 -5
  196. package/dist/providers/meta.js +10 -23
  197. package/dist/providers/minimax/chat.js +2 -7
  198. package/dist/providers/minimax/responses.js +2 -7
  199. package/dist/providers/minimax.d.ts +6 -5
  200. package/dist/providers/minimax.js +7 -22
  201. package/dist/providers/mistral.d.ts +10 -11
  202. package/dist/providers/mistral.js +3 -14
  203. package/dist/providers/moonshot/messages.js +2 -7
  204. package/dist/providers/moonshot/responses.js +2 -7
  205. package/dist/providers/moonshot.d.ts +6 -5
  206. package/dist/providers/moonshot.js +4 -16
  207. package/dist/providers/openai/embeddings.d.ts +2 -0
  208. package/dist/providers/openai/embeddings.js +1 -0
  209. package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
  210. package/dist/providers/openai-compatible/embeddings.js +1 -0
  211. package/dist/providers/openai-compatible-responses.d.ts +6 -7
  212. package/dist/providers/openai-compatible-responses.js +2 -8
  213. package/dist/providers/openai-compatible.d.ts +10 -7
  214. package/dist/providers/openai-compatible.js +17 -10
  215. package/dist/providers/openai.d.ts +11 -4
  216. package/dist/providers/openai.js +17 -3
  217. package/dist/providers/opencode.d.ts +4 -4
  218. package/dist/providers/opencode.js +6 -2
  219. package/dist/providers/openrouter/embeddings.d.ts +2 -0
  220. package/dist/providers/openrouter/embeddings.js +1 -0
  221. package/dist/providers/openrouter.d.ts +24 -5
  222. package/dist/providers/openrouter.js +31 -24
  223. package/dist/providers/runway.d.ts +1 -1
  224. package/dist/providers/settings.d.ts +40 -0
  225. package/dist/providers/settings.js +19 -0
  226. package/dist/providers/togetherai.d.ts +7 -5
  227. package/dist/providers/togetherai.js +5 -15
  228. package/dist/providers/typesafe-ai.d.ts +4 -4
  229. package/dist/providers/typesafe-ai.js +6 -2
  230. package/dist/providers/venice.d.ts +5 -4
  231. package/dist/providers/venice.js +6 -2
  232. package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
  233. package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
  234. package/dist/providers/vercel-ai-gateway.d.ts +9 -5
  235. package/dist/providers/vercel-ai-gateway.js +30 -29
  236. package/dist/providers/xai.d.ts +5 -4
  237. package/dist/providers/xai.js +4 -12
  238. package/dist/providers/zai-coding-plan/messages.js +2 -7
  239. package/dist/providers/zai-coding-plan/responses.js +2 -7
  240. package/dist/providers/zai-coding-plan.d.ts +6 -5
  241. package/dist/providers/zai-coding-plan.js +8 -15
  242. package/dist/providers/zai.d.ts +6 -5
  243. package/dist/providers/zai.js +10 -22
  244. package/dist/public.d.ts +14 -0
  245. package/dist/public.js +6 -0
  246. package/dist/route/auth-options.d.ts +9 -5
  247. package/dist/route/auth-options.js +10 -7
  248. package/dist/route/client.d.ts +50 -37
  249. package/dist/route/client.js +42 -53
  250. package/dist/route/decision.d.ts +8 -8
  251. package/dist/route/decision.js +3 -3
  252. package/dist/route/embedding.d.ts +61 -0
  253. package/dist/route/embedding.js +88 -0
  254. package/dist/route/executor.d.ts +5 -0
  255. package/dist/route/executor.js +10 -0
  256. package/dist/route/index.d.ts +5 -7
  257. package/dist/route/index.js +1 -1
  258. package/dist/route/media.d.ts +7 -11
  259. package/dist/route/media.js +22 -26
  260. package/dist/route/transport/http.js +6 -5
  261. package/dist/route/transport/websocket.js +7 -1
  262. package/dist/schema/errors.d.ts +16 -17
  263. package/dist/schema/errors.js +63 -12
  264. package/dist/schema/events.d.ts +2563 -2954
  265. package/dist/schema/events.js +54 -109
  266. package/dist/schema/messages.d.ts +194 -137
  267. package/dist/schema/messages.js +66 -83
  268. package/dist/schema/options.d.ts +112 -65
  269. package/dist/schema/options.js +52 -101
  270. package/dist/speech-client.d.ts +7 -7
  271. package/dist/speech.d.ts +306 -316
  272. package/dist/speech.js +16 -14
  273. package/dist/testing.d.ts +31 -175
  274. package/dist/testing.js +60 -5
  275. package/dist/tool-history.d.ts +1 -1
  276. package/dist/tool-history.js +3 -10
  277. package/dist/tool-runtime.d.ts +9 -2
  278. package/dist/tool-runtime.js +17 -31
  279. package/dist/tool.d.ts +39 -43
  280. package/dist/tool.js +16 -26
  281. package/dist/transcription-client.d.ts +7 -7
  282. package/dist/transcription.d.ts +314 -265
  283. package/dist/transcription.js +16 -14
  284. package/dist/utils/provider-codes.d.ts +3 -0
  285. package/dist/utils/provider-codes.js +41 -0
  286. package/dist/video-client.d.ts +7 -7
  287. package/dist/video-client.js +1 -1
  288. package/dist/video.d.ts +269 -287
  289. package/dist/video.js +16 -14
  290. package/package.json +309 -257
  291. package/dist/experimental/testing.d.ts +0 -3
  292. package/dist/experimental/testing.js +0 -3
  293. package/dist/testing/decision.d.ts +0 -16
  294. package/dist/testing/decision.js +0 -20
  295. package/dist/testing/image.d.ts +0 -14
  296. package/dist/testing/image.js +0 -12
  297. package/dist/testing/media.d.ts +0 -18
  298. package/dist/testing/media.js +0 -36
  299. package/dist/testing/script.d.ts +0 -28
  300. package/dist/testing/script.js +0 -60
  301. package/dist/testing/speech.d.ts +0 -14
  302. package/dist/testing/speech.js +0 -12
  303. package/dist/testing/transcription.d.ts +0 -14
  304. package/dist/testing/transcription.js +0 -12
  305. package/dist/testing/video.d.ts +0 -14
  306. package/dist/testing/video.js +0 -12
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Effect, Layer, ManagedRuntime, Schema, Stream } from "effect";
2
2
  import { AIClient } from "./ai-client.js";
3
3
  import { Decision } from "./decision.js";
4
+ import { Embedding } from "./embedding.js";
4
5
  import { Image } from "./image.js";
5
6
  import { LLM } from "./llm.js";
6
7
  import { Media } from "./media.js";
@@ -25,15 +26,21 @@ const abortEffect = (signal) => signal === undefined
25
26
  return Effect.sync(() => signal.removeEventListener("abort", onAbort));
26
27
  });
27
28
  export const make = (options = {}) => {
28
- const runtime = ManagedRuntime.make(Layer.merge(AIClient.layerWith(options.layer ?? RequestExecutor.fetchLayer),
29
- // `R` is only inferred from `clients`, so it is `never` whenever `clients` is omitted.
30
- (options.clients ?? Layer.empty)));
29
+ const runtime = ManagedRuntime.make(AIClient.layerWith(options.layer ?? RequestExecutor.fetchLayer));
31
30
  /** Run any package Effect (for example `ai.compact(...)` from `@opencode/ai/effect`) inside this runtime. */
32
31
  const run = (effect, options) => runtime.runPromise(Effect.raceFirst(effect, abortEffect(options?.signal)));
33
32
  const iterate = (stream, options) => Stream.toAsyncIterable(Stream.unwrap(runtime.contextEffect.pipe(Effect.map((context) => stream.pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context))))));
34
- function generateObject(input, options) {
35
- return run("schema" in input ? LLM.generateObject(input) : LLM.generateObject(input), options);
33
+ function generate(input, options) {
34
+ return run(LLM.generate(input, options), options);
36
35
  }
36
+ function stream(input, options) {
37
+ return iterate(LLM.stream(input, options), options);
38
+ }
39
+ function loop(input, options) {
40
+ return iterate(LLM.loop(input, options), options);
41
+ }
42
+ /** Read `events` from `stream` or `loop` to the end and fold them into the final result. */
43
+ const collect = (events, options) => run(LLM.collect(Stream.fromAsyncIterable(events, (error) => error)), options);
37
44
  // The overloads pair each request type with its mechanism; `LLM.compact` checks the route's capability at runtime.
38
45
  function compact(request, options) {
39
46
  return options?.mechanism === "trigger"
@@ -78,12 +85,11 @@ export const make = (options = {}) => {
78
85
  }))), options);
79
86
  },
80
87
  request: LLM.request,
81
- generate: (input, options) => run(LLM.generate(input, options), options),
82
- stream: (input, options) => iterate(LLM.stream(input, options), options),
88
+ generate,
89
+ stream,
83
90
  /** Stream model calls, running their tool calls, until the model stops calling tools or `until` is true. */
84
- loop: (input, options) => iterate(LLM.loop(input, options), options),
85
- /** Decode the model's output against `schema` (or `jsonSchema`, unvalidated). */
86
- generateObject,
91
+ loop,
92
+ collect,
87
93
  /** Compact a Responses request: a replacement window, or a checkpoint with `mechanism: "trigger"`. */
88
94
  compact,
89
95
  canCompact: LLM.canCompact,
@@ -98,6 +104,10 @@ export const make = (options = {}) => {
98
104
  request: Decision.request,
99
105
  generate: (input, options) => run(Decision.generate(input), options),
100
106
  },
107
+ embedding: {
108
+ request: Embedding.request,
109
+ generate: (input, options) => run(Embedding.generate(input), options),
110
+ },
101
111
  /** Experimental: may change without compatibility guarantees. */
102
112
  experimental: {
103
113
  speech: {
@@ -128,16 +138,12 @@ const fileError = (message, cause) => new AIError({ reason: new InvalidRequestEr
128
138
  export const tool = (config) => {
129
139
  const execute = config.execute;
130
140
  return build(config, execute &&
131
- ((params, context) => Effect.tryPromise({
132
- try: async (signal) => execute(params, { ...context, signal }),
141
+ ((input, context) => Effect.tryPromise({
142
+ try: async (signal) => execute(input, { ...context, signal }),
133
143
  catch: (error) => new ToolFailure({ message: error instanceof Error ? error.message : String(error), error }),
134
144
  })));
135
145
  };
136
146
  /** Default client over `RequestExecutor.fetchLayer`; the runtime builds its layer on first use and holds nothing to dispose. */
137
147
  export const ai = make();
138
148
  export * as AI from "./index.js";
139
- export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
140
- export { ProtocolID, RouteID, ModelID, ProviderID, ResponseID, ContentBlockID, ToolCallID, JsonSchema, ProviderOptions, ProviderMetadata, HttpTimeout, RequestEncoding, HttpOptions, GenerationOptions, LanguageModelDefaults, ReasoningEfforts, ReasoningEffort, LanguageModelCompatibility, LanguageModel, LanguageModelSchema, CacheTTL, CacheHint, CachePolicyObject, CachePolicy, MessageRole, SystemPart, TextPart, MediaPart, ToolResultValue, ToolOutput, ToolCallPart, ToolResultPart, ReasoningPart, CompactionPart, EffortPart, ContentPart, Message, Freeform, ToolDefinition, ToolNamespace, ToolEntry, ToolChoice, LLMRequest, FinishReason, Usage, MediaUsage, CompactionResponse, CompactionCheckpointResponse, StepStart, TextStart, TextDelta, TextEnd, ReasoningStart, ReasoningDelta, ReasoningEnd, ToolInputStart, ToolInputDelta, ToolInputEnd, ToolInputError, ToolCall, ToolResult, ToolError, FinishReasonDetails, StepFinish, Finish, MediaEvent, ProviderErrorEvent, LLMEvent, LLMResponse, HttpContext, HttpRateLimitDetails, InvalidRequestError, UnsupportedOperationError, ProviderConfigurationError, NoRouteError, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
141
- export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
142
- export { ChoiceAnswer, ChoiceQuestion, ChoiceValue, DecisionAnswer, DecisionJsonPart, DecisionMediaPart, DecisionModel, DecisionModelCompatibility, DecisionModelSchema, DecisionPart, DecisionQuestion, DecisionRequest, DecisionResponse, DecisionTextPart, DecisionUsage, ErrorAnswer, ErrorReason, PredicateAnswer, PredicateQuestion, ScoreAnswer, ScoreQuestion, } from "./decision.js";
143
- export { Media } from "./media.js";
149
+ export * from "./public.js";
package/dist/llm.d.ts CHANGED
@@ -1,23 +1,58 @@
1
1
  import { Effect, JsonSchema, Schema, Stream } from "effect";
2
- import { Service, type StreamOptions } from "./route/client.js";
3
- import { GenerationOptions, HttpOptions, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, ToolChoice, type ContentPart, type LanguageModelProviderOptions, type ToolEntryInput } from "./schema/index.js";
4
- import { type ExecutableTool, type ToolSchema } from "./tool.js";
5
- /** Input accepted by `LLM.request`, normalized into the canonical `LLMRequest` class. */
6
- export type RequestInput<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<ConstructorParameters<typeof LLMRequest>[0], "model" | "system" | "messages" | "tools" | "toolChoice" | "generation" | "http" | "providerOptions"> & {
7
- readonly model: SelectedLanguageModel;
2
+ import { Service, canCompact, type CheckpointRequest, type CompactionRequest, type EndpointCompactOptions, type StreamOptions, type TriggerCompactOptions } from "./route/client.js";
3
+ import { AIError, LLMEvent, LLMResponse, Message, LanguageModel, SystemPart, type BaseRequest, type CachePolicy, type CompactionCheckpointResponse, type CompactionResponse, type Finish, ToolChoice, type LanguageModelProviderOptions, type GenerationOptionsFields, type LLMRequest, type ToolEntryInput } from "./schema/index.js";
4
+ import { type ExecutableTool, type Tool, type ToolSchema } from "./tool.js";
5
+ /** Input accepted by `ai.request`, `ai.generate`, `ai.stream` and `ai.compact`. An `LLMRequest` is also a valid input. */
6
+ export type LLMRequestInput<Model extends LanguageModel = LanguageModel> = TextRequestFields<Model> & PromptOrMessages;
7
+ /** Exactly one of `prompt`, a single user message, or `messages`, the full conversation. */
8
+ export type PromptOrMessages = {
9
+ readonly prompt: Message.UserContentInput;
10
+ readonly messages?: never;
11
+ } | {
12
+ readonly messages: ReadonlyArray<Message | Message.Input>;
13
+ readonly prompt?: never;
14
+ };
15
+ interface TextRequestFields<Model extends LanguageModel> extends BaseRequest<Model, NoInfer<LanguageModelProviderOptions<Model>>>, GenerationOptionsFields {
16
+ readonly id?: string;
8
17
  readonly system?: string | SystemPart | ReadonlyArray<SystemPart>;
9
- readonly prompt?: string | ContentPart | ReadonlyArray<ContentPart>;
10
- readonly messages?: ReadonlyArray<Message | Message.Input>;
11
- readonly tools?: ReadonlyArray<ToolEntryInput>;
18
+ /** Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. */
19
+ readonly tools?: ReadonlyArray<Tool | ToolEntryInput>;
12
20
  readonly toolChoice?: ToolChoice.Input;
13
- readonly generation?: GenerationOptions.Input;
14
- readonly providerOptions?: NoInfer<LanguageModelProviderOptions<SelectedLanguageModel>>;
15
- readonly http?: HttpOptions.Input;
21
+ readonly cache?: CachePolicy;
22
+ /** Stable cache affinity for protocols that support provider-managed prompt caching. */
23
+ readonly promptCacheKey?: string;
24
+ /** Emit a `raw` event with each provider frame before the events parsed from it. */
25
+ readonly includeRaw?: boolean;
26
+ }
27
+ /** An Effect Schema decodes and types `object`; a raw JSON Schema leaves it `unknown`. */
28
+ export type OutputSchema = ToolSchema<any> | JsonSchema.JsonSchema;
29
+ export type OutputType<S extends OutputSchema> = S extends Schema.Top ? Schema.Schema.Type<S> : unknown;
30
+ export type ObjectResponse<T> = LLMResponse & {
31
+ readonly object: T;
16
32
  };
17
- export declare function generate<const Model extends LanguageModel>(input: RequestInput<Model> | LLMRequest, options?: StreamOptions): Effect.Effect<LLMResponse, AIError, Service>;
18
- export declare function stream<const Model extends LanguageModel>(input: RequestInput<Model> | LLMRequest, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
19
- export type LoopInput<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<RequestInput<SelectedLanguageModel>, "tools"> & {
20
- readonly tools: Record<string, ExecutableTool>;
33
+ /** Stream events for a request with `schema`: the `finish` event carries the decoded `object`. */
34
+ export type ObjectEvent<T> = Exclude<LLMEvent, Finish> | (Finish & {
35
+ readonly object: T;
36
+ });
37
+ /** Loop events for a request with `schema`: the loop's `finish` event carries the decoded `object`. */
38
+ export type LoopObjectEvent<T> = Exclude<LLMEvent, Finish> | (Finish & {
39
+ readonly object?: T;
40
+ });
41
+ /** Run one model call. With `schema`, the model must answer through a forced tool call decoded into `object`. */
42
+ export declare function generate<const Model extends LanguageModel, S extends OutputSchema>(input: LLMRequestInput<Model> & {
43
+ readonly schema: S;
44
+ }, options?: StreamOptions): Effect.Effect<ObjectResponse<OutputType<S>>, AIError, Service>;
45
+ export declare function generate<const Model extends LanguageModel>(input: LLMRequestInput<Model>, options?: StreamOptions): Effect.Effect<LLMResponse, AIError, Service>;
46
+ /**
47
+ * Stream one model call. The `finish` event carries the assistant `message` and `usage`; with `schema`, also the
48
+ * decoded `object`.
49
+ */
50
+ export declare function stream<const Model extends LanguageModel, S extends OutputSchema>(input: LLMRequestInput<Model> & {
51
+ readonly schema: S;
52
+ }, options?: StreamOptions): Stream.Stream<ObjectEvent<OutputType<S>>, AIError, Service>;
53
+ export declare function stream<const Model extends LanguageModel>(input: LLMRequestInput<Model>, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
54
+ export type LLMLoopInput<Model extends LanguageModel = LanguageModel> = Omit<TextRequestFields<Model>, "tools"> & PromptOrMessages & {
55
+ readonly tools: ReadonlyArray<ExecutableTool>;
21
56
  /** Called after each step that has tool calls; returning `true` ends the loop without running them. */
22
57
  readonly until?: (state: {
23
58
  readonly steps: ReadonlyArray<LLMResponse>;
@@ -25,256 +60,20 @@ export type LoopInput<SelectedLanguageModel extends LanguageModel = LanguageMode
25
60
  };
26
61
  /**
27
62
  * Stream model calls, running the model's tool calls between them, until a step has no client-executed tool calls,
28
- * reports a provider error, or `until` returns `true`. Each step's `step-start` and `step-finish` carry its step index.
63
+ * hits the output token limit, or `until` returns `true`. Tool calls whose input is not valid JSON get an error result
64
+ * so the model can retry. A forced `toolChoice` applies to the first step only. Each step's `step-start` and `step-finish` carry its step index and usage; one `finish` ends
65
+ * the loop with the final step's reason and `message` and the usage summed across steps. With `schema`, the model ends
66
+ * by calling the hidden answer tool, decoded into `object` on the `finish`.
29
67
  */
30
- export declare function loop<const Model extends LanguageModel>(input: LoopInput<Model>, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
31
- export declare const request: <const SelectedLanguageModel extends LanguageModel>(input: RequestInput<SelectedLanguageModel>) => LLMRequest<SelectedLanguageModel>;
32
- type GenerateObjectBase<SelectedLanguageModel extends LanguageModel = LanguageModel> = Omit<RequestInput<SelectedLanguageModel>, "tools" | "toolChoice">;
33
- export declare class GenerateObjectResponse<T> {
34
- readonly object: T;
35
- readonly response: LLMResponse;
36
- constructor(object: T, response: LLMResponse);
37
- get events(): readonly ({
38
- readonly type: "step-start";
39
- readonly index: number;
40
- } | {
41
- readonly type: "raw";
42
- readonly data: unknown;
43
- } | {
44
- readonly type: "text-start";
45
- readonly id: string;
46
- readonly providerMetadata?: {
47
- readonly [x: string]: {
48
- readonly [x: string]: unknown;
49
- };
50
- } | undefined;
51
- } | {
52
- readonly type: "text-delta";
53
- readonly id: string;
54
- readonly text: string;
55
- readonly providerMetadata?: {
56
- readonly [x: string]: {
57
- readonly [x: string]: unknown;
58
- };
59
- } | undefined;
60
- } | {
61
- readonly type: "text-end";
62
- readonly id: string;
63
- readonly text?: string | undefined;
64
- readonly providerMetadata?: {
65
- readonly [x: string]: {
66
- readonly [x: string]: unknown;
67
- };
68
- } | undefined;
69
- } | {
70
- readonly type: "reasoning-start";
71
- readonly id: string;
72
- readonly providerMetadata?: {
73
- readonly [x: string]: {
74
- readonly [x: string]: unknown;
75
- };
76
- } | undefined;
77
- } | {
78
- readonly type: "reasoning-delta";
79
- readonly id: string;
80
- readonly text: string;
81
- readonly providerMetadata?: {
82
- readonly [x: string]: {
83
- readonly [x: string]: unknown;
84
- };
85
- } | undefined;
86
- } | {
87
- readonly type: "reasoning-end";
88
- readonly id: string;
89
- readonly text?: string | undefined;
90
- readonly providerMetadata?: {
91
- readonly [x: string]: {
92
- readonly [x: string]: unknown;
93
- };
94
- } | undefined;
95
- } | {
96
- readonly type: "tool-input-start";
97
- readonly id: string;
98
- readonly name: string;
99
- readonly namespace?: string | undefined;
100
- readonly providerExecuted?: boolean | undefined;
101
- readonly providerMetadata?: {
102
- readonly [x: string]: {
103
- readonly [x: string]: unknown;
104
- };
105
- } | undefined;
106
- } | {
107
- readonly type: "tool-input-delta";
108
- readonly id: string;
109
- readonly name: string;
110
- readonly namespace?: string | undefined;
111
- readonly text: string;
112
- readonly input?: unknown;
113
- } | {
114
- readonly type: "tool-input-end";
115
- readonly id: string;
116
- readonly name: string;
117
- readonly namespace?: string | undefined;
118
- readonly providerMetadata?: {
119
- readonly [x: string]: {
120
- readonly [x: string]: unknown;
121
- };
122
- } | undefined;
123
- } | {
124
- readonly type: "tool-input-error";
125
- readonly id: string;
126
- readonly name: string;
127
- readonly namespace?: string | undefined;
128
- readonly raw: string;
129
- } | {
130
- readonly type: "tool-call";
131
- readonly id: string;
132
- readonly name: string;
133
- readonly namespace?: string | undefined;
134
- readonly input: unknown;
135
- readonly providerExecuted?: boolean | undefined;
136
- readonly providerMetadata?: {
137
- readonly [x: string]: {
138
- readonly [x: string]: unknown;
139
- };
140
- } | undefined;
141
- } | {
142
- readonly type: "tool-result";
143
- readonly id: string;
144
- readonly name: string;
145
- readonly namespace?: string | undefined;
146
- readonly result: {
147
- readonly type: "json";
148
- readonly value: unknown;
149
- } | {
150
- readonly type: "text";
151
- readonly value: unknown;
152
- } | {
153
- readonly type: "error";
154
- readonly value: unknown;
155
- } | {
156
- readonly type: "content";
157
- readonly value: readonly ({
158
- readonly type: "text";
159
- readonly text: string;
160
- } | {
161
- readonly type: "file";
162
- readonly uri: string;
163
- readonly mime: string;
164
- readonly name?: string | undefined;
165
- })[];
166
- };
167
- readonly output?: {
168
- readonly structured: unknown;
169
- readonly content: readonly ({
170
- readonly type: "text";
171
- readonly text: string;
172
- } | {
173
- readonly type: "file";
174
- readonly uri: string;
175
- readonly mime: string;
176
- readonly name?: string | undefined;
177
- })[];
178
- } | undefined;
179
- readonly providerExecuted?: boolean | undefined;
180
- readonly providerMetadata?: {
181
- readonly [x: string]: {
182
- readonly [x: string]: unknown;
183
- };
184
- } | undefined;
185
- } | {
186
- readonly type: "tool-error";
187
- readonly id: string;
188
- readonly name: string;
189
- readonly namespace?: string | undefined;
190
- readonly message: string;
191
- readonly error?: unknown;
192
- readonly providerMetadata?: {
193
- readonly [x: string]: {
194
- readonly [x: string]: unknown;
195
- };
196
- } | undefined;
197
- } | {
198
- readonly type: "step-finish";
199
- readonly index: number;
200
- readonly reason: {
201
- readonly normalized: "content-filter" | "error" | "length" | "stop" | "tool-calls" | "unknown";
202
- readonly raw?: string | undefined;
203
- readonly category?: string | undefined;
204
- readonly explanation?: string | undefined;
205
- };
206
- readonly usage?: import("./schema/events.js").Usage | undefined;
207
- readonly providerMetadata?: {
208
- readonly [x: string]: {
209
- readonly [x: string]: unknown;
210
- };
211
- } | undefined;
212
- } | {
213
- readonly type: "finish";
214
- readonly reason: {
215
- readonly normalized: "content-filter" | "error" | "length" | "stop" | "tool-calls" | "unknown";
216
- readonly raw?: string | undefined;
217
- readonly category?: string | undefined;
218
- readonly explanation?: string | undefined;
219
- };
220
- readonly usage?: import("./schema/events.js").Usage | undefined;
221
- readonly providerMetadata?: {
222
- readonly [x: string]: {
223
- readonly [x: string]: unknown;
224
- };
225
- } | undefined;
226
- } | {
227
- readonly type: "media";
228
- readonly media: import("./media.js").Asset;
229
- readonly providerMetadata?: {
230
- readonly [x: string]: {
231
- readonly [x: string]: unknown;
232
- };
233
- } | undefined;
234
- } | {
235
- readonly type: "provider-error";
236
- readonly message: string;
237
- readonly classification?: "context-overflow" | "payload-too-large" | undefined;
238
- readonly providerMetadata?: {
239
- readonly [x: string]: {
240
- readonly [x: string]: unknown;
241
- };
242
- } | undefined;
243
- } | ({
244
- readonly type: "compaction";
245
- readonly provider: string & import("effect/Brand").Brand<"AI.ProviderID">;
246
- readonly id?: string | undefined;
247
- readonly encrypted?: string | undefined;
248
- readonly text?: string | null | undefined;
249
- } & ({
250
- readonly encrypted: string;
251
- readonly text?: never;
252
- } | {
253
- readonly text: string | null;
254
- readonly encrypted?: never;
255
- })))[];
256
- get usage(): import("./schema/events.js").Usage | undefined;
257
- }
258
- export interface GenerateObjectOptions<S extends ToolSchema<any>, SelectedLanguageModel extends LanguageModel = LanguageModel> extends GenerateObjectBase<SelectedLanguageModel> {
68
+ export declare function loop<const Model extends LanguageModel, S extends OutputSchema>(input: LLMLoopInput<Model> & {
259
69
  readonly schema: S;
260
- }
261
- export interface GenerateObjectDynamicOptions<SelectedLanguageModel extends LanguageModel = LanguageModel> extends GenerateObjectBase<SelectedLanguageModel> {
262
- /** Raw JSON Schema object describing the expected output shape. */
263
- readonly jsonSchema: JsonSchema.JsonSchema;
264
- }
265
- /**
266
- * Run a model and decode its output against `schema`. Works on every protocol
267
- * because it forces a synthetic tool call internally — provider-native JSON
268
- * modes are intentionally avoided so behaviour is uniform.
269
- *
270
- * Two input modes:
271
- *
272
- * 1. `schema: EffectSchema<T>` — `.object` is decoded and typed as `T`.
273
- * Decode failures surface as `AIError`.
274
- * 2. `jsonSchema: JsonSchema.JsonSchema` — `.object` is `unknown`. Use when
275
- * the schema is only available at runtime (MCP, plugin manifests). Caller validates.
276
- */
277
- export declare function generateObject<const SelectedLanguageModel extends LanguageModel, S extends ToolSchema<any>>(options: GenerateObjectOptions<S, SelectedLanguageModel>): Effect.Effect<GenerateObjectResponse<Schema.Schema.Type<S>>, AIError, Service>;
278
- export declare function generateObject<const SelectedLanguageModel extends LanguageModel>(options: GenerateObjectDynamicOptions<SelectedLanguageModel>): Effect.Effect<GenerateObjectResponse<unknown>, AIError, Service>;
279
- export { canCompact, compact } from "./route/client.js";
70
+ }, options?: StreamOptions): Stream.Stream<LoopObjectEvent<OutputType<S>>, AIError, Service>;
71
+ export declare function loop<const Model extends LanguageModel>(input: LLMLoopInput<Model>, options?: StreamOptions): Stream.Stream<LLMEvent, AIError, Service>;
72
+ export { collect, type Collected, type CollectResult } from "./loop.js";
73
+ /** Normalize text request input into a plain `LLMRequest`, with `prompt` turned into the one user message. */
74
+ export declare const request: <const Model extends LanguageModel>(input: LLMRequestInput<Model>) => LLMRequest<Model>;
75
+ /** Compact a text request: a replacement window, or a checkpoint with `mechanism: "trigger"`. */
76
+ export declare function compact(input: CheckpointRequest, options: TriggerCompactOptions): Effect.Effect<CompactionCheckpointResponse, AIError, Service>;
77
+ export declare function compact(input: CompactionRequest, options?: EndpointCompactOptions): Effect.Effect<CompactionResponse, AIError, Service>;
78
+ export { canCompact };
280
79
  export * as LLM from "./llm.js";
package/dist/llm.js CHANGED
@@ -1,106 +1,115 @@
1
1
  import { Effect, JsonSchema, Schema, Stream } from "effect";
2
2
  import { tryRequest } from "./media-model.js";
3
- import { LLMClient, Service } from "./route/client.js";
4
- import { GenerationOptions, HttpOptions, InvalidProviderOutputError, AIError, LLMEvent, LLMRequest, LLMResponse, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, withPartial, } from "./schema/index.js";
5
- import { tool, toDefinitions } from "./tool.js";
6
- import { ToolRuntime } from "./tool-runtime.js";
3
+ import { LLMClient, Service, canCompact, compactRequest, } from "./route/client.js";
4
+ import { InvalidProviderOutputError, InvalidRequestError, mergeGeneration, AIError, LLMEvent, LLMResponse, ResponseFold, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, Usage, withPartial, } from "./schema/index.js";
5
+ import { tool } from "./tool.js";
6
+ import { runTools } from "./tool-runtime.js";
7
+ import { addUsage, nextRequest, pendingCalls } from "./loop.js";
7
8
  export function generate(input, options) {
8
- return requestEffect(input).pipe(Effect.flatMap((request) => LLMClient.generate(request, options)));
9
+ return prepare(input).pipe(Effect.flatMap(({ request, output }) => LLMClient.generate(request, options).pipe(Effect.flatMap((response) => output === undefined
10
+ ? Effect.succeed(response)
11
+ : decodeObject(output, response).pipe(Effect.map((object) => Object.assign(response, { object })))))));
9
12
  }
10
13
  export function stream(input, options) {
11
- return Stream.unwrap(requestEffect(input).pipe(Effect.map((request) => LLMClient.stream(request, options))));
14
+ return Stream.unwrap(prepare(input).pipe(Effect.map(({ request, output }) => stepStream(request, undefined, options, (step) => Stream.fromEffect(finishStep(step, step.response.usage, output))))));
12
15
  }
13
16
  export function loop(input, options) {
14
17
  const { tools, until, ...rest } = input;
15
- const step = (request, steps) => Stream.suspend(() => {
16
- let state = LLMResponse.empty();
17
- return LLMClient.stream(request, options).pipe(Stream.map((event) => event.type === "step-start" || event.type === "step-finish" ? { ...event, index: steps.length } : event), Stream.tap((event) => Effect.sync(() => (state = LLMResponse.reduce(state, event)))), Stream.mapError((error) => withPartial(error, LLMResponse.partial(state))), Stream.concat(Stream.unwrap(Effect.gen(function* () {
18
- const response = LLMResponse.complete(state);
19
- const calls = response?.toolCalls.filter((call) => call.providerExecuted !== true) ?? [];
20
- if (!response || calls.length === 0 || state.events.some(LLMEvent.is.providerError))
21
- return Stream.empty;
22
- const done = [...steps, response];
23
- if (until?.({ steps: done }))
24
- return Stream.empty;
25
- const results = yield* Effect.forEach(calls, (call) => ToolRuntime.dispatch(tools, call), {
26
- concurrency: "unbounded",
27
- });
28
- const next = LLMRequest.update(request, {
29
- messages: [
30
- ...request.messages,
31
- response.message,
32
- ...calls.map((call, i) => Message.tool({
33
- id: call.id,
34
- name: call.name,
35
- namespace: call.namespace,
36
- result: results[i].result,
37
- providerMetadata: call.providerMetadata,
38
- })),
39
- ],
18
+ return Stream.unwrap(prepare({ ...rest, tools }).pipe(Effect.map(({ request, output }) => driveLoop({ tools, until, output, options }, request, [], undefined))));
19
+ }
20
+ export { collect } from "./loop.js";
21
+ /**
22
+ * Stream one model call. Its `finish` is held back: `after` gets the completed step and streams what follows it.
23
+ * With `index`, the step's `step-start` and `step-finish` carry it.
24
+ */
25
+ const stepStream = (request, index, options, after) => Stream.suspend(() => {
26
+ let state = ResponseFold.empty();
27
+ let finish;
28
+ return LLMClient.stream(request, options).pipe(Stream.map((event) => index !== undefined && (event.type === "step-start" || event.type === "step-finish")
29
+ ? { ...event, index }
30
+ : event), Stream.tap((event) => Effect.sync(() => {
31
+ state = ResponseFold.reduce(state, event);
32
+ if (event.type === "finish")
33
+ finish = event;
34
+ })), Stream.filter((event) => event.type !== "finish"), Stream.mapError((error) => withPartial(error, ResponseFold.partial(state))), Stream.concat(Stream.suspend(() => {
35
+ const response = ResponseFold.complete(state);
36
+ return response && finish ? after({ response, finish }) : Stream.empty;
37
+ })));
38
+ });
39
+ /** The `finish` that ends a stream or loop: the final step's `message`, the given `usage`, and the decoded `object`. */
40
+ const finishStep = (step, usage, output) => {
41
+ const event = { ...step.finish, usage, message: step.response.message };
42
+ if (output === undefined)
43
+ return Effect.succeed(event);
44
+ return decodeObject(output, step.response).pipe(Effect.map((object) => ({ ...event, object })));
45
+ };
46
+ const driveLoop = (context, request, steps, usage) => stepStream(request, steps.length, context.options, (step) => {
47
+ const total = addUsage(usage, step.response.usage);
48
+ const calls = pendingCalls(step.response, context.output && OBJECT_TOOL);
49
+ const done = [...steps, step.response];
50
+ if (calls.length === 0 || context.until?.({ steps: done }))
51
+ return Stream.fromEffect(finishStep(step, total, calls.length === 0 ? context.output : undefined));
52
+ return Stream.unwrap(runTools(context.tools, calls).pipe(Effect.map((results) => Stream.fromIterable(results.flatMap((result) => result.events)).pipe(Stream.concat(driveLoop(context, nextRequest(request, step.response, calls, results, context.output !== undefined), done, total))))));
53
+ });
54
+ const OBJECT_TOOL = "generate_object";
55
+ // `schema` adds a hidden tool whose input is the answer. With other tools the model only has to call some tool.
56
+ const prepare = (input) => {
57
+ const { schema, ...rest } = input;
58
+ return tryRequest(() => {
59
+ const description = "Return the structured result by calling this tool.";
60
+ const output = schema === undefined ? undefined : tool({ name: OBJECT_TOOL, description, input: schema });
61
+ const tools = rest.tools ?? [];
62
+ const built = request(output === undefined
63
+ ? rest
64
+ : {
65
+ ...rest,
66
+ tools: [...tools, output],
67
+ toolChoice: tools.length === 0 ? ToolChoice.named(OBJECT_TOOL) : new ToolChoice({ type: "required" }),
40
68
  });
41
- return Stream.fromIterable(results.flatMap((result) => result.events)).pipe(Stream.concat(step(next, done)));
42
- }))));
69
+ const duplicate = built.tools.find((entry, index) => built.tools.findIndex((other) => other.name === entry.name) !== index);
70
+ if (duplicate)
71
+ throw new Error(`Duplicate tool name: ${duplicate.name}`);
72
+ return { request: built, output };
43
73
  });
44
- return Stream.unwrap(requestEffect({ ...rest, tools: toDefinitions(tools) }).pipe(Effect.map((request) => step(request, []))));
45
- }
46
- const requestEffect = (input) => input instanceof LLMRequest ? Effect.succeed(input) : tryRequest(() => request(input));
74
+ };
75
+ const decodeObject = (output, response) => {
76
+ const call = response.toolCalls.find((event) => event.name === OBJECT_TOOL);
77
+ const invalid = (message, cause) => new AIError({ reason: new InvalidProviderOutputError({ message, cause }), partial: response });
78
+ // A cut-off call arrives with truncated or empty input, so its decode error would hide the real cause.
79
+ if (response.finishReason.normalized === "length")
80
+ return Effect.fail(invalid("output hit the token limit before the forced tool call completed"));
81
+ if (call)
82
+ return output
83
+ ._decode(call.input)
84
+ .pipe(Effect.mapError((error) => invalid(`schema decode failed: ${error.message}`, error)));
85
+ return Effect.fail(invalid(`model did not call the forced \`${OBJECT_TOOL}\` tool`));
86
+ };
87
+ /** Normalize text request input into a plain `LLMRequest`, with `prompt` turned into the one user message. */
47
88
  export const request = (input) => {
48
- const { system: requestSystem, prompt, messages, tools, toolChoice: requestToolChoice, generation: requestGeneration, providerOptions: requestProviderOptions, http: requestHttp, ...rest } = input;
49
- return new LLMRequest({
50
- ...rest,
51
- system: SystemPart.content(requestSystem),
52
- messages: [...(messages?.map(Message.make) ?? []), ...(prompt === undefined ? [] : [Message.user(prompt)])],
53
- tools: tools?.map(ToolEntry.make) ?? [],
54
- toolChoice: requestToolChoice ? ToolChoice.make(requestToolChoice) : undefined,
55
- generation: requestGeneration === undefined ? undefined : GenerationOptions.make(requestGeneration),
56
- providerOptions: requestProviderOptions,
57
- http: HttpOptions.make(requestHttp),
58
- });
89
+ if ((input.prompt === undefined) === (input.messages === undefined))
90
+ throw new AIError({
91
+ reason: new InvalidRequestError({ message: "Pass exactly one of `prompt` or `messages`, not both or neither" }),
92
+ });
93
+ return {
94
+ id: input.id,
95
+ model: input.model,
96
+ system: SystemPart.content(input.system),
97
+ messages: input.prompt === undefined ? (input.messages ?? []).map(Message.make) : [Message.user(input.prompt)],
98
+ tools: input.tools?.map((item) => ("_definition" in item ? item._definition : ToolEntry.make(item))) ?? [],
99
+ toolChoice: input.toolChoice ? ToolChoice.make(input.toolChoice) : undefined,
100
+ ...mergeGeneration(input),
101
+ providerOptions: input.providerOptions,
102
+ headers: input.headers,
103
+ fetch: input.fetch,
104
+ timeout: input.timeout,
105
+ http: input.http,
106
+ cache: input.cache,
107
+ promptCacheKey: input.promptCacheKey,
108
+ includeRaw: input.includeRaw,
109
+ };
59
110
  };
60
- const GENERATE_OBJECT_TOOL_NAME = "generate_object";
61
- const GENERATE_OBJECT_TOOL_DESCRIPTION = "Return the structured result by calling this tool.";
62
- export class GenerateObjectResponse {
63
- object;
64
- response;
65
- constructor(object, response) {
66
- this.object = object;
67
- this.response = response;
68
- }
69
- get events() {
70
- return this.response.events;
71
- }
72
- get usage() {
73
- return this.response.usage;
74
- }
75
- }
76
- const runGenerateObject = Effect.fn("LLM.generateObject")(function* (options, tool) {
77
- const baseRequest = request(options);
78
- const generateRequest = LLMRequest.update(baseRequest, {
79
- tools: toDefinitions({ [GENERATE_OBJECT_TOOL_NAME]: tool }),
80
- toolChoice: ToolChoice.named(GENERATE_OBJECT_TOOL_NAME),
81
- });
82
- const response = yield* LLMClient.generate(generateRequest);
83
- const call = response.toolCalls.find((event) => event.name === GENERATE_OBJECT_TOOL_NAME);
84
- const invalidOutput = (reason) => new AIError({ reason, partial: response });
85
- if (!call) {
86
- const message = response.finishReason.normalized === "length"
87
- ? "generateObject: output hit the token limit before the forced tool call completed"
88
- : `generateObject: model did not call the forced \`${GENERATE_OBJECT_TOOL_NAME}\` tool`;
89
- return yield* invalidOutput(new InvalidProviderOutputError({ message }));
90
- }
91
- const object = yield* tool._decode(call.input).pipe(Effect.mapError((error) => invalidOutput(new InvalidProviderOutputError({
92
- message: `generateObject: tool input failed schema decode: ${error.message}`,
93
- cause: error,
94
- }))));
95
- return new GenerateObjectResponse(object, response);
96
- });
97
- export function generateObject(options) {
98
- if ("schema" in options) {
99
- const { schema, ...rest } = options;
100
- return runGenerateObject(rest, tool({ description: GENERATE_OBJECT_TOOL_DESCRIPTION, parameters: schema }));
101
- }
102
- const { jsonSchema, ...rest } = options;
103
- return runGenerateObject(rest, tool({ description: GENERATE_OBJECT_TOOL_DESCRIPTION, jsonSchema }));
111
+ export function compact(input, options) {
112
+ return tryRequest(() => request(input)).pipe(Effect.flatMap((normalized) => compactRequest(normalized, options)));
104
113
  }
105
- export { canCompact, compact } from "./route/client.js";
114
+ export { canCompact };
106
115
  export * as LLM from "./llm.js";