endpoint.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import type { LLMRequest } from "../schema"
  2. import * as ProviderShared from "../protocols/shared"
  3. export interface EndpointInput<Body> {
  4. readonly request: LLMRequest
  5. readonly body: Body
  6. }
  7. export type EndpointPart<Body> = string | ((input: EndpointInput<Body>) => string)
  8. /**
  9. * Declarative URL construction for one route.
  10. *
  11. * `Endpoint` carries only the path. The host always lives on `model.baseURL`,
  12. * supplied by the provider helper that constructs the model. `render(...)`
  13. * just appends the path (and any `model.queryParams`) to that host.
  14. *
  15. * `path` may be a string or a function of `EndpointInput`, for routes whose
  16. * URL embeds the model id, region, or another body field (e.g. Bedrock,
  17. * Gemini).
  18. */
  19. export interface Endpoint<Body> {
  20. readonly path: EndpointPart<Body>
  21. }
  22. /** Construct an `Endpoint` from a path string or path function. */
  23. export const path = <Body>(value: EndpointPart<Body>): Endpoint<Body> => ({ path: value })
  24. const renderPart = <Body>(part: EndpointPart<Body>, input: EndpointInput<Body>) =>
  25. typeof part === "function" ? part(input) : part
  26. export const render = <Body>(endpoint: Endpoint<Body>, input: EndpointInput<Body>) => {
  27. const url = new URL(`${ProviderShared.trimBaseUrl(input.request.model.baseURL)}${renderPart(endpoint.path, input)}`)
  28. const params = input.request.model.queryParams
  29. if (params) for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value)
  30. return url
  31. }
  32. export * as Endpoint from "./endpoint"