shared.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import { Buffer } from "node:buffer"
  2. import { Effect, Schema, Stream } from "effect"
  3. import * as Sse from "effect/unstable/encoding/Sse"
  4. import { Headers, HttpClientRequest } from "effect/unstable/http"
  5. import {
  6. InvalidProviderOutputReason,
  7. InvalidRequestReason,
  8. LLMError,
  9. type ContentPart,
  10. type LLMRequest,
  11. type MediaPart,
  12. type ToolResultPart,
  13. } from "../schema"
  14. export const Json = Schema.fromJsonString(Schema.Unknown)
  15. export const decodeJson = Schema.decodeUnknownSync(Json)
  16. export const encodeJson = Schema.encodeSync(Json)
  17. export const JsonObject = Schema.Record(Schema.String, Schema.Unknown)
  18. export const optionalArray = <const S extends Schema.Top>(schema: S) => Schema.optional(Schema.Array(schema))
  19. export const optionalNull = <const S extends Schema.Top>(schema: S) => Schema.optional(Schema.NullOr(schema))
  20. /**
  21. * Plain-record narrowing. Excludes arrays so routes checking nested JSON
  22. * Schema fragments don't accidentally treat a tuple as a key/value bag.
  23. */
  24. export const isRecord = (value: unknown): value is Record<string, unknown> =>
  25. typeof value === "object" && value !== null && !Array.isArray(value)
  26. /**
  27. * Streaming tool-call accumulator. Adapters that build a tool call across
  28. * multiple `tool-input-delta` chunks store the partial JSON input string here
  29. * and finalize it with `parseToolInput` once the call completes.
  30. */
  31. export interface ToolAccumulator {
  32. readonly id: string
  33. readonly name: string
  34. readonly input: string
  35. }
  36. /**
  37. * `Usage.totalTokens` policy shared by every route. Honors a provider-
  38. * supplied total; otherwise falls back to `inputTokens + outputTokens` only
  39. * when at least one is defined. Returns `undefined` when neither input nor
  40. * output is known so routes don't publish a misleading `0`.
  41. *
  42. * Under the additive `LLM.Usage` contract, `inputTokens` and `outputTokens`
  43. * are the non-cached input and visible output only. The provider-supplied
  44. * `total` is the source of truth when present; the computed fallback
  45. * under-counts cache and reasoning by design and exists mainly so
  46. * Anthropic-style providers (which don't surface a total) still get a
  47. * sensible aggregate on the input + output axes.
  48. */
  49. export const totalTokens = (
  50. inputTokens: number | undefined,
  51. outputTokens: number | undefined,
  52. total: number | undefined,
  53. ) => {
  54. if (total !== undefined) return total
  55. if (inputTokens === undefined && outputTokens === undefined) return undefined
  56. return (inputTokens ?? 0) + (outputTokens ?? 0)
  57. }
  58. /**
  59. * Subtract `subtrahend` from `total`, clamping to zero if the provider
  60. * reports a non-sensical breakdown (e.g. `cached_tokens > prompt_tokens`).
  61. * Used by protocol mappers when deriving a non-overlapping breakdown field
  62. * from a provider's inclusive total — `nonCachedInputTokens` from
  63. * `inputTokens - cacheReadInputTokens - cacheWriteInputTokens`.
  64. *
  65. * If `total` is `undefined`, returns `undefined` (we don't fabricate
  66. * counts). If `subtrahend` is `undefined`, returns `total` unchanged. The
  67. * provider-native breakdown stays available on `Usage.native` for debugging.
  68. */
  69. export const subtractTokens = (total: number | undefined, subtrahend: number | undefined): number | undefined => {
  70. if (total === undefined) return undefined
  71. if (subtrahend === undefined) return total
  72. return Math.max(0, total - subtrahend)
  73. }
  74. /**
  75. * Sum a list of optional token counts, returning `undefined` only when
  76. * every value is `undefined` (so we don't fabricate a `0`). Used by
  77. * protocol mappers to derive the inclusive `inputTokens` total from a
  78. * provider that natively reports a non-overlapping breakdown
  79. * (e.g. Anthropic, whose `input_tokens` is already non-cached only).
  80. */
  81. export const sumTokens = (...values: ReadonlyArray<number | undefined>): number | undefined => {
  82. if (values.every((value) => value === undefined)) return undefined
  83. return values.reduce<number>((acc, value) => acc + (value ?? 0), 0)
  84. }
  85. export const eventError = (route: string, message: string, raw?: string) =>
  86. new LLMError({
  87. module: "ProviderShared",
  88. method: "stream",
  89. reason: new InvalidProviderOutputReason({ route, message, raw }),
  90. })
  91. export const parseJson = (route: string, input: string, message: string) =>
  92. Effect.try({
  93. try: () => decodeJson(input),
  94. catch: () => eventError(route, message, input),
  95. })
  96. /**
  97. * Join the `text` field of a list of parts with newlines. Used by routes
  98. * that flatten system / message content arrays into a single provider string
  99. * (OpenAI Chat `system` content, OpenAI Responses `system` content, Gemini
  100. * `systemInstruction.parts[].text`).
  101. */
  102. export const joinText = (parts: ReadonlyArray<{ readonly text: string }>) => parts.map((part) => part.text).join("\n")
  103. /**
  104. * Parse the streamed JSON input of a tool call. Treats an empty string as
  105. * `"{}"` — providers occasionally finish a tool call without ever emitting
  106. * input deltas (e.g. zero-arg tools). The error message is uniform across
  107. * routes: `Invalid JSON input for <route> tool call <name>`.
  108. */
  109. export const parseToolInput = (route: string, name: string, raw: string) =>
  110. parseJson(route, raw || "{}", `Invalid JSON input for ${route} tool call ${name}`)
  111. /**
  112. * Encode a `MediaPart`'s raw bytes for inclusion in a JSON request body.
  113. * `data: string` is assumed to already be base64 (matches caller convention
  114. * across Gemini / Bedrock); `data: Uint8Array` is base64-encoded here. Used
  115. * by every route that supports image / document inputs.
  116. */
  117. export const mediaBytes = (part: MediaPart) =>
  118. typeof part.data === "string" ? part.data : Buffer.from(part.data).toString("base64")
  119. export const trimBaseUrl = (value: string) => value.replace(/\/+$/, "")
  120. export const toolResultText = (part: ToolResultPart) => {
  121. if (part.result.type === "text" || part.result.type === "error") return String(part.result.value)
  122. return encodeJson(part.result.value)
  123. }
  124. export const errorText = (error: unknown) => {
  125. if (error instanceof Error) return error.message
  126. if (typeof error === "string") return error
  127. if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint") return String(error)
  128. if (error === null) return "null"
  129. if (error === undefined) return "undefined"
  130. return "Unknown stream error"
  131. }
  132. /**
  133. * `framing` step for Server-Sent Events. Decodes UTF-8, runs the SSE channel
  134. * decoder, and drops empty / `[DONE]` keep-alive events so the downstream
  135. * `decodeChunk` sees one JSON string per element. The SSE channel emits a
  136. * `Retry` control event on its error channel; we drop it here (we don't
  137. * implement client-driven retries) so the public error channel stays
  138. * `LLMError`.
  139. */
  140. export const sseFraming = (bytes: Stream.Stream<Uint8Array, LLMError>): Stream.Stream<string, LLMError> =>
  141. bytes.pipe(
  142. Stream.decodeText(),
  143. Stream.pipeThroughChannel(Sse.decode()),
  144. Stream.catchTag("Retry", () => Stream.empty),
  145. Stream.filter((event) => event.data.length > 0 && event.data !== "[DONE]"),
  146. Stream.map((event) => event.data),
  147. )
  148. /**
  149. * Canonical invalid-request constructor. Lift one-line `const invalid =
  150. * (message) => invalidRequest(message)` aliases out of every
  151. * route so the error constructor lives in one place. If we ever extend
  152. * `InvalidRequestReason` with route context or trace metadata, the change
  153. * lands here.
  154. */
  155. export const invalidRequest = (message: string) =>
  156. new LLMError({
  157. module: "ProviderShared",
  158. method: "request",
  159. reason: new InvalidRequestReason({ message }),
  160. })
  161. export const matchToolChoice = <Auto, None, Required, Tool>(
  162. route: string,
  163. toolChoice: NonNullable<LLMRequest["toolChoice"]>,
  164. cases: {
  165. readonly auto: () => Auto
  166. readonly none: () => None
  167. readonly required: () => Required
  168. readonly tool: (name: string) => Tool
  169. },
  170. ) =>
  171. Effect.gen(function* () {
  172. if (toolChoice.type === "auto") return cases.auto()
  173. if (toolChoice.type === "none") return cases.none()
  174. if (toolChoice.type === "required") return cases.required()
  175. if (!toolChoice.name) return yield* invalidRequest(`${route} tool choice requires a tool name`)
  176. return cases.tool(toolChoice.name)
  177. })
  178. type ContentType = ContentPart["type"]
  179. const formatContentTypes = (types: ReadonlyArray<ContentType>) => {
  180. if (types.length <= 1) return types[0] ?? ""
  181. if (types.length === 2) return `${types[0]} and ${types[1]}`
  182. return `${types.slice(0, -1).join(", ")}, and ${types.at(-1)}`
  183. }
  184. export const supportsContent = <const Type extends ContentType>(
  185. part: ContentPart,
  186. types: ReadonlyArray<Type>,
  187. ): part is Extract<ContentPart, { readonly type: Type }> => (types as ReadonlyArray<ContentType>).includes(part.type)
  188. export const unsupportedContent = (
  189. route: string,
  190. role: LLMRequest["messages"][number]["role"],
  191. types: ReadonlyArray<ContentType>,
  192. ) => invalidRequest(`${route} ${role} messages only support ${formatContentTypes(types)} content for now`)
  193. /**
  194. * Build a `validate` step from a Schema decoder. Replaces the per-route
  195. * lambda body `(payload) => decode(payload).pipe(Effect.mapError((e) =>
  196. * invalid(e.message)))`. Any decode error is translated into
  197. * `LLMError` carrying the original parse-error message.
  198. */
  199. export const validateWith =
  200. <A, I, E extends { readonly message: string }>(decode: (input: I) => Effect.Effect<A, E>) =>
  201. (payload: I) =>
  202. decode(payload).pipe(Effect.mapError((error) => invalidRequest(error.message)))
  203. /**
  204. * Build an HTTP POST with a JSON body. Sets `content-type: application/json`
  205. * automatically after caller-supplied headers so routes cannot accidentally
  206. * send JSON with a stale content type. The body is passed pre-encoded so
  207. * routes can choose between
  208. * `Schema.encodeSync(payload)` and `ProviderShared.encodeJson(payload)`.
  209. */
  210. export const jsonPost = (input: { readonly url: string; readonly body: string; readonly headers?: Headers.Input }) =>
  211. HttpClientRequest.post(input.url).pipe(
  212. HttpClientRequest.setHeaders(Headers.set(Headers.fromInput(input.headers), "content-type", "application/json")),
  213. HttpClientRequest.bodyText(input.body, "application/json"),
  214. )
  215. export * as ProviderShared from "./shared"