events.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import { Schema } from "effect"
  2. import { ContentBlockID, FinishReason, ProtocolID, ProviderMetadata, ResponseID, RouteID, ToolCallID } from "./ids"
  3. import { ModelRef } from "./options"
  4. import { ToolResultValue } from "./messages"
  5. /**
  6. * Token usage reported by an LLM provider.
  7. *
  8. * **Inclusive totals** (match AI SDK / OpenAI / LangChain convention — a
  9. * reader from any of those ecosystems sees the number they expect):
  10. *
  11. * - `inputTokens` — total prompt tokens, *including* cached reads/writes.
  12. * - `outputTokens` — total output tokens, *including* reasoning.
  13. * - `totalTokens` — provider-supplied total, or `inputTokens + outputTokens`.
  14. *
  15. * **Non-overlapping breakdown** (every field is independently meaningful;
  16. * consumers never have to subtract):
  17. *
  18. * - `nonCachedInputTokens` — the "fresh" portion of the prompt.
  19. * - `cacheReadInputTokens` — input tokens served from cache.
  20. * - `cacheWriteInputTokens` — input tokens written to cache.
  21. * - `reasoningTokens` — subset of `outputTokens` spent on hidden reasoning.
  22. *
  23. * **Invariant**: `nonCachedInputTokens + cacheReadInputTokens +
  24. * cacheWriteInputTokens = inputTokens`, and `reasoningTokens ≤ outputTokens`.
  25. * Each protocol mapper computes whichever side it doesn't get natively,
  26. * with `Math.max(0, …)` clamping for defense against provider bugs. Because
  27. * every breakdown field is stored independently, downstream consumers can
  28. * read whatever they need (cost-by-category, context-pressure, AI-SDK-style
  29. * inclusive total) without ever subtracting — eliminating the underflow
  30. * class of bug where a clamped difference would silently store the wrong
  31. * value.
  32. *
  33. * **Semantics by provider**:
  34. *
  35. * - OpenAI Chat / Responses / Gemini / Bedrock: provider reports inclusive
  36. * `inputTokens` and an inclusive `outputTokens`; mapper subtracts to
  37. * derive the breakdown.
  38. * - Anthropic: provider reports the breakdown natively (`input_tokens` is
  39. * non-cached only); mapper sums to derive the inclusive `inputTokens`.
  40. * Anthropic does *not* break extended-thinking out of `output_tokens`, so
  41. * `reasoningTokens` is `undefined` and `outputTokens` carries the
  42. * combined total — a documented limitation of the Anthropic API.
  43. *
  44. * `providerMetadata` always carries the provider's raw usage payload —
  45. * keyed by provider name (`{ openai: ... }`, `{ anthropic: ... }`, etc.)
  46. * — for fields we don't normalize and for billing-level audit trails.
  47. * Matches the same escape-hatch field on `LLMEvent`.
  48. */
  49. export class Usage extends Schema.Class<Usage>("LLM.Usage")({
  50. inputTokens: Schema.optional(Schema.Number),
  51. outputTokens: Schema.optional(Schema.Number),
  52. nonCachedInputTokens: Schema.optional(Schema.Number),
  53. cacheReadInputTokens: Schema.optional(Schema.Number),
  54. cacheWriteInputTokens: Schema.optional(Schema.Number),
  55. reasoningTokens: Schema.optional(Schema.Number),
  56. totalTokens: Schema.optional(Schema.Number),
  57. providerMetadata: Schema.optional(ProviderMetadata),
  58. }) {
  59. /**
  60. * Visible output tokens — `outputTokens` minus `reasoningTokens`, clamped
  61. * to zero. The one place subtraction happens in this contract; the clamp
  62. * means a provider reporting `reasoningTokens > outputTokens` produces a
  63. * harmless zero rather than a negative that crashes downstream schemas.
  64. */
  65. get visibleOutputTokens() {
  66. return Math.max(0, (this.outputTokens ?? 0) - (this.reasoningTokens ?? 0))
  67. }
  68. }
  69. export const RequestStart = Schema.Struct({
  70. type: Schema.tag("request-start"),
  71. id: ResponseID,
  72. model: ModelRef,
  73. }).annotate({ identifier: "LLM.Event.RequestStart" })
  74. export type RequestStart = Schema.Schema.Type<typeof RequestStart>
  75. export const StepStart = Schema.Struct({
  76. type: Schema.tag("step-start"),
  77. index: Schema.Number,
  78. }).annotate({ identifier: "LLM.Event.StepStart" })
  79. export type StepStart = Schema.Schema.Type<typeof StepStart>
  80. export const TextStart = Schema.Struct({
  81. type: Schema.tag("text-start"),
  82. id: ContentBlockID,
  83. providerMetadata: Schema.optional(ProviderMetadata),
  84. }).annotate({ identifier: "LLM.Event.TextStart" })
  85. export type TextStart = Schema.Schema.Type<typeof TextStart>
  86. export const TextDelta = Schema.Struct({
  87. type: Schema.tag("text-delta"),
  88. id: ContentBlockID,
  89. text: Schema.String,
  90. }).annotate({ identifier: "LLM.Event.TextDelta" })
  91. export type TextDelta = Schema.Schema.Type<typeof TextDelta>
  92. export const TextEnd = Schema.Struct({
  93. type: Schema.tag("text-end"),
  94. id: ContentBlockID,
  95. providerMetadata: Schema.optional(ProviderMetadata),
  96. }).annotate({ identifier: "LLM.Event.TextEnd" })
  97. export type TextEnd = Schema.Schema.Type<typeof TextEnd>
  98. export const ReasoningStart = Schema.Struct({
  99. type: Schema.tag("reasoning-start"),
  100. id: ContentBlockID,
  101. providerMetadata: Schema.optional(ProviderMetadata),
  102. }).annotate({ identifier: "LLM.Event.ReasoningStart" })
  103. export type ReasoningStart = Schema.Schema.Type<typeof ReasoningStart>
  104. export const ReasoningDelta = Schema.Struct({
  105. type: Schema.tag("reasoning-delta"),
  106. id: ContentBlockID,
  107. text: Schema.String,
  108. }).annotate({ identifier: "LLM.Event.ReasoningDelta" })
  109. export type ReasoningDelta = Schema.Schema.Type<typeof ReasoningDelta>
  110. export const ReasoningEnd = Schema.Struct({
  111. type: Schema.tag("reasoning-end"),
  112. id: ContentBlockID,
  113. providerMetadata: Schema.optional(ProviderMetadata),
  114. }).annotate({ identifier: "LLM.Event.ReasoningEnd" })
  115. export type ReasoningEnd = Schema.Schema.Type<typeof ReasoningEnd>
  116. export const ToolInputStart = Schema.Struct({
  117. type: Schema.tag("tool-input-start"),
  118. id: ToolCallID,
  119. name: Schema.String,
  120. providerMetadata: Schema.optional(ProviderMetadata),
  121. }).annotate({ identifier: "LLM.Event.ToolInputStart" })
  122. export type ToolInputStart = Schema.Schema.Type<typeof ToolInputStart>
  123. export const ToolInputDelta = Schema.Struct({
  124. type: Schema.tag("tool-input-delta"),
  125. id: ToolCallID,
  126. name: Schema.String,
  127. text: Schema.String,
  128. }).annotate({ identifier: "LLM.Event.ToolInputDelta" })
  129. export type ToolInputDelta = Schema.Schema.Type<typeof ToolInputDelta>
  130. export const ToolInputEnd = Schema.Struct({
  131. type: Schema.tag("tool-input-end"),
  132. id: ToolCallID,
  133. name: Schema.String,
  134. providerMetadata: Schema.optional(ProviderMetadata),
  135. }).annotate({ identifier: "LLM.Event.ToolInputEnd" })
  136. export type ToolInputEnd = Schema.Schema.Type<typeof ToolInputEnd>
  137. export const ToolCall = Schema.Struct({
  138. type: Schema.tag("tool-call"),
  139. id: ToolCallID,
  140. name: Schema.String,
  141. input: Schema.Unknown,
  142. providerExecuted: Schema.optional(Schema.Boolean),
  143. providerMetadata: Schema.optional(ProviderMetadata),
  144. }).annotate({ identifier: "LLM.Event.ToolCall" })
  145. export type ToolCall = Schema.Schema.Type<typeof ToolCall>
  146. export const ToolResult = Schema.Struct({
  147. type: Schema.tag("tool-result"),
  148. id: ToolCallID,
  149. name: Schema.String,
  150. result: ToolResultValue,
  151. providerExecuted: Schema.optional(Schema.Boolean),
  152. providerMetadata: Schema.optional(ProviderMetadata),
  153. }).annotate({ identifier: "LLM.Event.ToolResult" })
  154. export type ToolResult = Schema.Schema.Type<typeof ToolResult>
  155. export const ToolError = Schema.Struct({
  156. type: Schema.tag("tool-error"),
  157. id: ToolCallID,
  158. name: Schema.String,
  159. message: Schema.String,
  160. providerMetadata: Schema.optional(ProviderMetadata),
  161. }).annotate({ identifier: "LLM.Event.ToolError" })
  162. export type ToolError = Schema.Schema.Type<typeof ToolError>
  163. export const StepFinish = Schema.Struct({
  164. type: Schema.tag("step-finish"),
  165. index: Schema.Number,
  166. reason: FinishReason,
  167. usage: Schema.optional(Usage),
  168. providerMetadata: Schema.optional(ProviderMetadata),
  169. }).annotate({ identifier: "LLM.Event.StepFinish" })
  170. export type StepFinish = Schema.Schema.Type<typeof StepFinish>
  171. export const RequestFinish = Schema.Struct({
  172. type: Schema.tag("request-finish"),
  173. reason: FinishReason,
  174. usage: Schema.optional(Usage),
  175. providerMetadata: Schema.optional(ProviderMetadata),
  176. }).annotate({ identifier: "LLM.Event.RequestFinish" })
  177. export type RequestFinish = Schema.Schema.Type<typeof RequestFinish>
  178. export const ProviderErrorEvent = Schema.Struct({
  179. type: Schema.tag("provider-error"),
  180. message: Schema.String,
  181. retryable: Schema.optional(Schema.Boolean),
  182. providerMetadata: Schema.optional(ProviderMetadata),
  183. }).annotate({ identifier: "LLM.Event.ProviderError" })
  184. export type ProviderErrorEvent = Schema.Schema.Type<typeof ProviderErrorEvent>
  185. const llmEventTagged = Schema.Union([
  186. RequestStart,
  187. StepStart,
  188. TextStart,
  189. TextDelta,
  190. TextEnd,
  191. ReasoningStart,
  192. ReasoningDelta,
  193. ReasoningEnd,
  194. ToolInputStart,
  195. ToolInputDelta,
  196. ToolInputEnd,
  197. ToolCall,
  198. ToolResult,
  199. ToolError,
  200. StepFinish,
  201. RequestFinish,
  202. ProviderErrorEvent,
  203. ]).pipe(Schema.toTaggedUnion("type"))
  204. type WithID<Event extends { readonly id: unknown }, ID> = Omit<Event, "type" | "id"> & { readonly id: ID | string }
  205. const responseID = (value: ResponseID | string) => ResponseID.make(value)
  206. const contentBlockID = (value: ContentBlockID | string) => ContentBlockID.make(value)
  207. const toolCallID = (value: ToolCallID | string) => ToolCallID.make(value)
  208. /**
  209. * camelCase aliases for `LLMEvent.guards` (provided by `Schema.toTaggedUnion`).
  210. * Lets consumers write `events.filter(LLMEvent.is.toolCall)` instead of
  211. * `events.filter(LLMEvent.guards["tool-call"])`.
  212. */
  213. export const LLMEvent = Object.assign(llmEventTagged, {
  214. requestStart: (input: WithID<RequestStart, ResponseID>) => RequestStart.make({ ...input, id: responseID(input.id) }),
  215. stepStart: StepStart.make,
  216. textStart: (input: WithID<TextStart, ContentBlockID>) => TextStart.make({ ...input, id: contentBlockID(input.id) }),
  217. textDelta: (input: WithID<TextDelta, ContentBlockID>) => TextDelta.make({ ...input, id: contentBlockID(input.id) }),
  218. textEnd: (input: WithID<TextEnd, ContentBlockID>) => TextEnd.make({ ...input, id: contentBlockID(input.id) }),
  219. reasoningStart: (input: WithID<ReasoningStart, ContentBlockID>) =>
  220. ReasoningStart.make({ ...input, id: contentBlockID(input.id) }),
  221. reasoningDelta: (input: WithID<ReasoningDelta, ContentBlockID>) =>
  222. ReasoningDelta.make({ ...input, id: contentBlockID(input.id) }),
  223. reasoningEnd: (input: WithID<ReasoningEnd, ContentBlockID>) =>
  224. ReasoningEnd.make({ ...input, id: contentBlockID(input.id) }),
  225. toolInputStart: (input: WithID<ToolInputStart, ToolCallID>) =>
  226. ToolInputStart.make({ ...input, id: toolCallID(input.id) }),
  227. toolInputDelta: (input: WithID<ToolInputDelta, ToolCallID>) =>
  228. ToolInputDelta.make({ ...input, id: toolCallID(input.id) }),
  229. toolInputEnd: (input: WithID<ToolInputEnd, ToolCallID>) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }),
  230. toolCall: (input: WithID<ToolCall, ToolCallID>) => ToolCall.make({ ...input, id: toolCallID(input.id) }),
  231. toolResult: (input: WithID<ToolResult, ToolCallID>) => ToolResult.make({ ...input, id: toolCallID(input.id) }),
  232. toolError: (input: WithID<ToolError, ToolCallID>) => ToolError.make({ ...input, id: toolCallID(input.id) }),
  233. stepFinish: StepFinish.make,
  234. requestFinish: RequestFinish.make,
  235. providerError: ProviderErrorEvent.make,
  236. is: {
  237. requestStart: llmEventTagged.guards["request-start"],
  238. stepStart: llmEventTagged.guards["step-start"],
  239. textStart: llmEventTagged.guards["text-start"],
  240. textDelta: llmEventTagged.guards["text-delta"],
  241. textEnd: llmEventTagged.guards["text-end"],
  242. reasoningStart: llmEventTagged.guards["reasoning-start"],
  243. reasoningDelta: llmEventTagged.guards["reasoning-delta"],
  244. reasoningEnd: llmEventTagged.guards["reasoning-end"],
  245. toolInputStart: llmEventTagged.guards["tool-input-start"],
  246. toolInputDelta: llmEventTagged.guards["tool-input-delta"],
  247. toolInputEnd: llmEventTagged.guards["tool-input-end"],
  248. toolCall: llmEventTagged.guards["tool-call"],
  249. toolResult: llmEventTagged.guards["tool-result"],
  250. toolError: llmEventTagged.guards["tool-error"],
  251. stepFinish: llmEventTagged.guards["step-finish"],
  252. requestFinish: llmEventTagged.guards["request-finish"],
  253. providerError: llmEventTagged.guards["provider-error"],
  254. },
  255. })
  256. export type LLMEvent = Schema.Schema.Type<typeof llmEventTagged>
  257. export class PreparedRequest extends Schema.Class<PreparedRequest>("LLM.PreparedRequest")({
  258. id: Schema.String,
  259. route: RouteID,
  260. protocol: ProtocolID,
  261. model: ModelRef,
  262. body: Schema.Unknown,
  263. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  264. }) {}
  265. /**
  266. * A `PreparedRequest` whose `body` is typed as `Body`. Use with the generic
  267. * on `LLMClient.prepare<Body>(...)` when the caller knows which route their
  268. * request will resolve to and wants its native shape statically exposed
  269. * (debug UIs, request previews, plan rendering).
  270. *
  271. * The runtime body is identical — the route still emits `body: unknown` — so
  272. * this is a type-level assertion the caller makes about what they expect to
  273. * find. The prepare runtime does not validate the assertion.
  274. */
  275. export type PreparedRequestOf<Body> = Omit<PreparedRequest, "body"> & {
  276. readonly body: Body
  277. }
  278. const responseText = (events: ReadonlyArray<LLMEvent>) =>
  279. events
  280. .filter(LLMEvent.is.textDelta)
  281. .map((event) => event.text)
  282. .join("")
  283. const responseReasoning = (events: ReadonlyArray<LLMEvent>) =>
  284. events
  285. .filter(LLMEvent.is.reasoningDelta)
  286. .map((event) => event.text)
  287. .join("")
  288. const responseUsage = (events: ReadonlyArray<LLMEvent>) =>
  289. events.reduce<Usage | undefined>(
  290. (usage, event) => ("usage" in event && event.usage !== undefined ? event.usage : usage),
  291. undefined,
  292. )
  293. export class LLMResponse extends Schema.Class<LLMResponse>("LLM.Response")({
  294. events: Schema.Array(LLMEvent),
  295. usage: Schema.optional(Usage),
  296. }) {
  297. /** Concatenated assistant text assembled from streamed `text-delta` events. */
  298. get text() {
  299. return responseText(this.events)
  300. }
  301. /** Concatenated reasoning text assembled from streamed `reasoning-delta` events. */
  302. get reasoning() {
  303. return responseReasoning(this.events)
  304. }
  305. /** Completed tool calls emitted by the provider. */
  306. get toolCalls() {
  307. return this.events.filter(LLMEvent.is.toolCall)
  308. }
  309. }
  310. export namespace LLMResponse {
  311. export type Output = LLMResponse | { readonly events: ReadonlyArray<LLMEvent>; readonly usage?: Usage }
  312. /** Concatenate assistant text from a response or collected event list. */
  313. export const text = (response: Output) => responseText(response.events)
  314. /** Return response usage, falling back to the latest usage-bearing event. */
  315. export const usage = (response: Output) => response.usage ?? responseUsage(response.events)
  316. /** Return completed tool calls from a response or collected event list. */
  317. export const toolCalls = (response: Output) => response.events.filter(LLMEvent.is.toolCall)
  318. /** Concatenate reasoning text from a response or collected event list. */
  319. export const reasoning = (response: Output) => responseReasoning(response.events)
  320. }