@tinyweb_dev/agent-framework-llm 0.2.0 → 0.4.0

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 (177) hide show
  1. package/dist/cache-policy.d.ts +3 -0
  2. package/dist/cache-policy.d.ts.map +1 -0
  3. package/dist/index.cjs +2968 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.ts +23 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +2843 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/llm.cjs +1718 -0
  10. package/dist/llm.cjs.map +1 -0
  11. package/dist/llm.d.ts +284 -0
  12. package/dist/llm.d.ts.map +1 -0
  13. package/dist/llm.js +1692 -0
  14. package/dist/llm.js.map +1 -0
  15. package/dist/protocols/openai-chat.cjs +2455 -0
  16. package/dist/protocols/openai-chat.cjs.map +1 -0
  17. package/dist/protocols/openai-chat.d.ts +359 -0
  18. package/dist/protocols/openai-chat.d.ts.map +1 -0
  19. package/dist/protocols/openai-chat.js +2426 -0
  20. package/dist/protocols/openai-chat.js.map +1 -0
  21. package/dist/protocols/openai-compatible-chat.cjs +2455 -0
  22. package/dist/protocols/openai-compatible-chat.cjs.map +1 -0
  23. package/dist/protocols/openai-compatible-chat.d.ts +77 -0
  24. package/dist/protocols/openai-compatible-chat.d.ts.map +1 -0
  25. package/dist/protocols/openai-compatible-chat.js +2431 -0
  26. package/dist/protocols/openai-compatible-chat.js.map +1 -0
  27. package/dist/protocols/shared.cjs +904 -0
  28. package/dist/protocols/shared.cjs.map +1 -0
  29. package/dist/protocols/shared.d.ts +51 -0
  30. package/dist/protocols/shared.d.ts.map +1 -0
  31. package/dist/protocols/shared.js +857 -0
  32. package/dist/protocols/shared.js.map +1 -0
  33. package/dist/protocols/utils/openai-options.d.ts +15 -0
  34. package/dist/protocols/utils/openai-options.d.ts.map +1 -0
  35. package/dist/protocols/utils/tool-stream.d.ts +78 -0
  36. package/dist/protocols/utils/tool-stream.d.ts.map +1 -0
  37. package/dist/provider.cjs +20 -0
  38. package/dist/provider.cjs.map +1 -0
  39. package/dist/provider.d.ts +19 -0
  40. package/dist/provider.d.ts.map +1 -0
  41. package/dist/provider.js +17 -0
  42. package/dist/provider.js.map +1 -0
  43. package/{src/providers/openai-compatible-profile.ts → dist/providers/openai-compatible-profile.cjs} +12 -12
  44. package/dist/providers/openai-compatible-profile.cjs.map +1 -0
  45. package/dist/providers/openai-compatible-profile.d.ts +52 -0
  46. package/dist/providers/openai-compatible-profile.d.ts.map +1 -0
  47. package/dist/providers/openai-compatible-profile.js +21 -0
  48. package/dist/providers/openai-compatible-profile.js.map +1 -0
  49. package/dist/providers/openai-compatible.cjs +2545 -0
  50. package/dist/providers/openai-compatible.cjs.map +1 -0
  51. package/dist/providers/openai-compatible.d.ts +128 -0
  52. package/dist/providers/openai-compatible.d.ts.map +1 -0
  53. package/dist/providers/openai-compatible.js +2507 -0
  54. package/dist/providers/openai-compatible.js.map +1 -0
  55. package/dist/providers/openai-options.cjs +797 -0
  56. package/dist/providers/openai-options.cjs.map +1 -0
  57. package/dist/providers/openai-options.d.ts +29 -0
  58. package/dist/providers/openai-options.d.ts.map +1 -0
  59. package/dist/providers/openai-options.js +792 -0
  60. package/dist/providers/openai-options.js.map +1 -0
  61. package/dist/providers/openai.cjs +2529 -0
  62. package/dist/providers/openai.cjs.map +1 -0
  63. package/dist/providers/openai.d.ts +87 -0
  64. package/dist/providers/openai.d.ts.map +1 -0
  65. package/dist/providers/openai.js +2501 -0
  66. package/dist/providers/openai.js.map +1 -0
  67. package/dist/route/auth-options.cjs +855 -0
  68. package/dist/route/auth-options.cjs.map +1 -0
  69. package/dist/route/auth-options.d.ts +25 -0
  70. package/dist/route/auth-options.d.ts.map +1 -0
  71. package/dist/route/auth-options.js +852 -0
  72. package/dist/route/auth-options.js.map +1 -0
  73. package/dist/route/auth.cjs +855 -0
  74. package/dist/route/auth.cjs.map +1 -0
  75. package/dist/route/auth.d.ts +51 -0
  76. package/dist/route/auth.d.ts.map +1 -0
  77. package/dist/route/auth.js +836 -0
  78. package/dist/route/auth.js.map +1 -0
  79. package/dist/route/client.cjs +1844 -0
  80. package/dist/route/client.cjs.map +1 -0
  81. package/dist/route/client.d.ts +268 -0
  82. package/dist/route/client.d.ts.map +1 -0
  83. package/dist/route/client.js +1830 -0
  84. package/dist/route/client.js.map +1 -0
  85. package/dist/route/endpoint.cjs +756 -0
  86. package/dist/route/endpoint.cjs.map +1 -0
  87. package/dist/route/endpoint.d.ts +13 -0
  88. package/dist/route/endpoint.d.ts.map +1 -0
  89. package/dist/route/endpoint.js +752 -0
  90. package/dist/route/endpoint.js.map +1 -0
  91. package/dist/route/executor.cjs +1077 -0
  92. package/dist/route/executor.cjs.map +1 -0
  93. package/dist/route/executor.d.ts +13 -0
  94. package/dist/route/executor.d.ts.map +1 -0
  95. package/dist/route/executor.js +1072 -0
  96. package/dist/route/executor.js.map +1 -0
  97. package/dist/route/framing.cjs +773 -0
  98. package/dist/route/framing.cjs.map +1 -0
  99. package/dist/route/framing.d.ts +9 -0
  100. package/dist/route/framing.d.ts.map +1 -0
  101. package/dist/route/framing.js +750 -0
  102. package/dist/route/framing.js.map +1 -0
  103. package/dist/route/overflow-detect.d.ts +18 -0
  104. package/dist/route/overflow-detect.d.ts.map +1 -0
  105. package/dist/route/protocol.cjs +25 -0
  106. package/dist/route/protocol.cjs.map +1 -0
  107. package/dist/route/protocol.d.ts +40 -0
  108. package/dist/route/protocol.d.ts.map +1 -0
  109. package/dist/route/protocol.js +21 -0
  110. package/dist/route/protocol.js.map +1 -0
  111. package/dist/route/transport/http.d.ts +48 -0
  112. package/dist/route/transport/http.d.ts.map +1 -0
  113. package/dist/route/transport/index.cjs +969 -0
  114. package/dist/route/transport/index.cjs.map +1 -0
  115. package/dist/route/transport/index.d.ts +13 -0
  116. package/dist/route/transport/index.d.ts.map +1 -0
  117. package/dist/route/transport/index.js +967 -0
  118. package/dist/route/transport/index.js.map +1 -0
  119. package/dist/schema/errors.d.ts +181 -0
  120. package/dist/schema/errors.d.ts.map +1 -0
  121. package/dist/schema/events.d.ts +3224 -0
  122. package/dist/schema/events.d.ts.map +1 -0
  123. package/dist/schema/ids.d.ts +31 -0
  124. package/dist/schema/ids.d.ts.map +1 -0
  125. package/dist/schema/index.cjs +847 -0
  126. package/dist/schema/index.cjs.map +1 -0
  127. package/dist/schema/index.d.ts +6 -0
  128. package/dist/schema/index.d.ts.map +1 -0
  129. package/dist/schema/index.js +777 -0
  130. package/dist/schema/index.js.map +1 -0
  131. package/dist/schema/messages.d.ts +292 -0
  132. package/dist/schema/messages.d.ts.map +1 -0
  133. package/dist/schema/options.d.ts +123 -0
  134. package/dist/schema/options.d.ts.map +1 -0
  135. package/dist/tool-runtime.cjs +907 -0
  136. package/dist/tool-runtime.cjs.map +1 -0
  137. package/dist/tool-runtime.d.ts +50 -0
  138. package/dist/tool-runtime.d.ts.map +1 -0
  139. package/dist/tool-runtime.js +901 -0
  140. package/dist/tool-runtime.js.map +1 -0
  141. package/dist/tool.cjs +802 -0
  142. package/dist/tool.cjs.map +1 -0
  143. package/dist/tool.d.ts +111 -0
  144. package/dist/tool.d.ts.map +1 -0
  145. package/dist/tool.js +796 -0
  146. package/dist/tool.js.map +1 -0
  147. package/package.json +112 -29
  148. package/src/cache-policy.ts +0 -92
  149. package/src/index.ts +0 -62
  150. package/src/llm.ts +0 -210
  151. package/src/protocols/openai-chat.ts +0 -464
  152. package/src/protocols/openai-compatible-chat.ts +0 -29
  153. package/src/protocols/shared.ts +0 -204
  154. package/src/protocols/utils/openai-options.ts +0 -56
  155. package/src/protocols/utils/tool-stream.ts +0 -135
  156. package/src/provider.ts +0 -32
  157. package/src/providers/openai-compatible.ts +0 -69
  158. package/src/providers/openai-options.ts +0 -71
  159. package/src/providers/openai.ts +0 -39
  160. package/src/route/auth-options.ts +0 -48
  161. package/src/route/auth.ts +0 -198
  162. package/src/route/client.ts +0 -459
  163. package/src/route/endpoint.ts +0 -28
  164. package/src/route/executor.ts +0 -396
  165. package/src/route/framing.ts +0 -13
  166. package/src/route/overflow-detect.ts +0 -74
  167. package/src/route/protocol.ts +0 -48
  168. package/src/route/transport/http.ts +0 -123
  169. package/src/route/transport/index.ts +0 -21
  170. package/src/schema/errors.ts +0 -225
  171. package/src/schema/events.ts +0 -335
  172. package/src/schema/ids.ts +0 -44
  173. package/src/schema/index.ts +0 -6
  174. package/src/schema/messages.ts +0 -250
  175. package/src/schema/options.ts +0 -231
  176. package/src/tool-runtime.ts +0 -301
  177. package/src/tool.ts +0 -212
package/src/route/auth.ts DELETED
@@ -1,198 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/route/auth.ts
2
- import { Config, Effect, Redacted } from "effect"
3
- import { Headers } from "effect/unstable/http"
4
- import { AuthenticationReason, InvalidRequestReason, LLMError, type LLMRequest } from "../schema"
5
-
6
- export class MissingCredentialError extends Error {
7
- readonly _tag = "MissingCredentialError"
8
-
9
- constructor(readonly source: string) {
10
- super(`Missing auth credential: ${source}`)
11
- }
12
- }
13
-
14
- export type CredentialError = MissingCredentialError | Config.ConfigError
15
- export type AuthError = CredentialError | LLMError
16
-
17
- export interface AuthInput {
18
- readonly request: LLMRequest
19
- readonly method: "POST" | "GET"
20
- readonly url: string
21
- readonly body: string
22
- readonly headers: Headers.Headers
23
- }
24
-
25
- export interface Credential {
26
- readonly load: Effect.Effect<Redacted.Redacted<string>, CredentialError>
27
- readonly orElse: (that: Credential) => Credential
28
- readonly bearer: () => Auth
29
- readonly header: (name: string) => Auth
30
- readonly pipe: <A>(f: (self: Credential) => A) => A
31
- }
32
-
33
- export interface Auth {
34
- readonly apply: (input: AuthInput) => Effect.Effect<Headers.Headers, AuthError>
35
- readonly andThen: (that: Auth) => Auth
36
- readonly orElse: (that: Auth) => Auth
37
- readonly pipe: <A>(f: (self: Auth) => A) => A
38
- }
39
-
40
- export const isAuth = (input: unknown): input is Auth =>
41
- typeof input === "object" && input !== null && "apply" in input && typeof input.apply === "function"
42
-
43
- const credential = (load: Effect.Effect<Redacted.Redacted<string>, CredentialError>): Credential => {
44
- const self: Credential = {
45
- load,
46
- orElse: (that) => credential(load.pipe(Effect.catch(() => that.load))),
47
- bearer: () => fromCredential(self, (secret) => ({ authorization: `Bearer ${secret}` })),
48
- header: (name) => fromCredential(self, (secret) => ({ [name]: secret })),
49
- pipe: (f) => f(self),
50
- }
51
- return self
52
- }
53
-
54
- const auth = (apply: Auth["apply"]): Auth => {
55
- const self: Auth = {
56
- apply,
57
- andThen: (that) =>
58
- auth((input) => apply(input).pipe(Effect.flatMap((headers) => that.apply({ ...input, headers })))),
59
- orElse: (that) => auth((input) => apply(input).pipe(Effect.catch(() => that.apply(input)))),
60
- pipe: (f) => f(self),
61
- }
62
- return self
63
- }
64
-
65
- const fromCredential = (source: Credential, render: (secret: string) => Headers.Input) =>
66
- auth((input) =>
67
- source.load.pipe(Effect.map((secret) => Headers.setAll(input.headers, render(Redacted.value(secret))))),
68
- )
69
-
70
- const secretEffect = (secret: string | Redacted.Redacted<string>, source: string) => {
71
- const redacted = typeof secret === "string" ? Redacted.make(secret) : secret
72
- if (Redacted.value(redacted) === "") return Effect.fail(new MissingCredentialError(source))
73
- return Effect.succeed(redacted)
74
- }
75
-
76
- const credentialFromSecret = (
77
- secret: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>>,
78
- source: string,
79
- ) => {
80
- if (typeof secret === "string" || Redacted.isRedacted(secret)) return credential(secretEffect(secret, source))
81
- return credential(
82
- Effect.gen(function* () {
83
- return yield* secretEffect(yield* secret, source)
84
- }),
85
- )
86
- }
87
-
88
- export const value = (secret: string, source = "value") => credentialFromSecret(secret, source)
89
-
90
- export const optional = (
91
- secret: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | undefined,
92
- source = "optional value",
93
- ) =>
94
- secret === undefined
95
- ? credential(Effect.fail(new MissingCredentialError(source)))
96
- : credentialFromSecret(secret, source)
97
-
98
- export const config = (name: string) => credentialFromSecret(Config.redacted(name), name)
99
-
100
- export const effect = (load: Effect.Effect<Redacted.Redacted<string>, CredentialError>) => credential(load)
101
-
102
- export const none = auth((input) => Effect.succeed(input.headers))
103
-
104
- export const headers = (input: Headers.Input) =>
105
- auth((inputAuth) => Effect.succeed(Headers.setAll(inputAuth.headers, input)))
106
-
107
- export const remove = (name: string) => auth((input) => Effect.succeed(Headers.remove(input.headers, name)))
108
-
109
- export const custom = (apply: (input: AuthInput) => Effect.Effect<Headers.Headers, LLMError>) => auth(apply)
110
-
111
- export const passthrough = none
112
-
113
- const fromModelApiKey = (from: (apiKey: string) => Headers.Input) =>
114
- auth(({ request, headers }) => {
115
- const key = request.model.apiKey
116
- if (!key) return Effect.succeed(headers)
117
- return Effect.succeed(Headers.setAll(headers, from(key)))
118
- })
119
-
120
- const credentialInput = (
121
- source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
122
- ) =>
123
- typeof source === "string" || Redacted.isRedacted(source) || Config.isConfig(source)
124
- ? credentialFromSecret(source, "value")
125
- : source
126
-
127
- export function bearer(): Auth
128
- export function bearer(
129
- source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
130
- ): Auth
131
- export function bearer(
132
- source?: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
133
- ) {
134
- if (source === undefined) return fromModelApiKey((key) => ({ authorization: `Bearer ${key}` }))
135
- return credentialInput(source).bearer()
136
- }
137
-
138
- export const apiKey = bearer
139
-
140
- export const apiKeyHeader = (name: string) => fromModelApiKey((key) => ({ [name]: key }))
141
-
142
- export function header(
143
- name: string,
144
- ): (source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential) => Auth
145
- export function header(
146
- name: string,
147
- source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
148
- ): Auth
149
- export function header(
150
- name: string,
151
- source?: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
152
- ) {
153
- if (source === undefined) {
154
- return (
155
- next: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
156
- ) => credentialInput(next).header(name)
157
- }
158
- return credentialInput(source).header(name)
159
- }
160
-
161
- export function bearerHeader(
162
- name: string,
163
- ): (source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential) => Auth
164
- export function bearerHeader(
165
- name: string,
166
- source: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
167
- ): Auth
168
- export function bearerHeader(
169
- name: string,
170
- source?: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
171
- ) {
172
- const render = (
173
- input: string | Redacted.Redacted<string> | Config.Config<string | Redacted.Redacted<string>> | Credential,
174
- ) => fromCredential(credentialInput(input), (secret) => ({ [name]: `Bearer ${secret}` }))
175
- if (source === undefined) return render
176
- return render(source)
177
- }
178
-
179
- const toLLMError = (error: AuthError): LLMError => {
180
- if (error instanceof MissingCredentialError || error instanceof Config.ConfigError) {
181
- return new LLMError({
182
- module: "Auth",
183
- method: "apply",
184
- reason:
185
- error instanceof MissingCredentialError
186
- ? new AuthenticationReason({ message: error.message, kind: "missing" })
187
- : new InvalidRequestReason({ message: `Failed to resolve auth config: ${error.message}` }),
188
- })
189
- }
190
- return error
191
- }
192
-
193
- export const toEffect =
194
- (input: Auth) =>
195
- (authInput: AuthInput): Effect.Effect<Headers.Headers, LLMError> =>
196
- input.apply(authInput).pipe(Effect.mapError(toLLMError))
197
-
198
- export * as Auth from "./auth"
@@ -1,459 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/route/client.ts
2
- // WebSocket transport layer (`layerWithWebSocket`) intentionally omitted at v1.
3
- import { Cause, Context, Effect, Layer, Schema, Stream } from "effect"
4
- import type { Auth as AuthDef } from "./auth"
5
- import type { Endpoint } from "./endpoint"
6
- import { RequestExecutor } from "./executor"
7
- import type { Framing } from "./framing"
8
- import { HttpTransport } from "./transport"
9
- import type { Transport, TransportRuntime } from "./transport"
10
- import type { Protocol } from "./protocol"
11
- import { applyCachePolicy } from "../cache-policy"
12
- import * as ProviderShared from "../protocols/shared"
13
- import * as ToolRuntime from "../tool-runtime"
14
- import type { Tools } from "../tool"
15
- import type { LLMError, LLMEvent, PreparedRequestOf, ProtocolID } from "../schema"
16
- import {
17
- GenerationOptions,
18
- HttpOptions,
19
- LLMRequest,
20
- LLMResponse,
21
- ModelID,
22
- ModelLimits,
23
- ModelRef,
24
- LLMError as LLMErrorClass,
25
- NoRouteReason,
26
- PreparedRequest,
27
- ProviderID,
28
- RouteID,
29
- mergeGenerationOptions,
30
- mergeHttpOptions,
31
- mergeProviderOptions,
32
- } from "../schema"
33
-
34
- export interface RouteBody<Body> {
35
- readonly schema: Schema.Codec<Body, unknown>
36
- readonly from: (request: LLMRequest) => Effect.Effect<Body, LLMError>
37
- }
38
-
39
- export interface Route<Body, Prepared = unknown> {
40
- readonly id: string
41
- readonly provider?: ProviderID
42
- readonly protocol: ProtocolID
43
- readonly transport: Transport<Body, Prepared, unknown>
44
- readonly defaults: RouteDefaults
45
- readonly body: RouteBody<Body>
46
- readonly with: (patch: RoutePatch<Body, Prepared>) => Route<Body, Prepared>
47
- readonly model: <Input extends RouteModelInput = RouteModelInput>(input: Input) => ModelRef
48
- readonly prepareTransport: (body: Body, request: LLMRequest) => Effect.Effect<Prepared, LLMError>
49
- readonly streamPrepared: (
50
- prepared: Prepared,
51
- request: LLMRequest,
52
- runtime: TransportRuntime,
53
- ) => Stream.Stream<LLMEvent, LLMError>
54
- }
55
-
56
- // oxlint-disable-next-line typescript-eslint/no-explicit-any
57
- export type AnyRoute = Route<any, any>
58
-
59
- const routeRegistry = new Map<string, AnyRoute>()
60
-
61
- const register = <R extends AnyRoute>(route: R): R => {
62
- const existing = routeRegistry.get(route.id)
63
- if (existing && existing !== route) throw new Error(`Duplicate LLM route id "${route.id}"`)
64
- routeRegistry.set(route.id, route)
65
- return route
66
- }
67
-
68
- const registeredRoute = (id: string) => routeRegistry.get(id)
69
-
70
- export type HttpOptionsInput = HttpOptions.Input
71
-
72
- export type ModelRefInput = Omit<
73
- ConstructorParameters<typeof ModelRef>[0],
74
- "id" | "provider" | "route" | "limits" | "generation" | "http" | "auth"
75
- > & {
76
- readonly id: string | ModelID
77
- readonly provider: string | ProviderID
78
- readonly route: string | RouteID
79
- readonly auth?: AuthDef
80
- readonly limits?: ModelLimits.Input
81
- readonly generation?: GenerationOptions.Input
82
- readonly http?: HttpOptionsInput
83
- }
84
-
85
- export type RouteModelInput = Omit<ModelRefInput, "provider" | "route" | "baseURL"> & {
86
- readonly baseURL?: string
87
- }
88
-
89
- export type RouteModelDefaults = Omit<ModelRefInput, "id" | "route" | "baseURL"> & {
90
- readonly baseURL?: string
91
- }
92
-
93
- export type RouteRoutedModelInput = Omit<ModelRefInput, "route" | "baseURL"> & {
94
- readonly baseURL?: string
95
- }
96
-
97
- export type RouteRoutedModelDefaults = Partial<Omit<ModelRefInput, "id" | "provider" | "route">>
98
-
99
- export type RouteDefaults = Partial<Omit<ModelRefInput, "id" | "provider" | "route">>
100
-
101
- export interface RoutePatch<Body, Prepared> extends RouteDefaults {
102
- readonly id: string
103
- readonly provider?: string | ProviderID
104
- readonly transport?: Transport<Body, Prepared, unknown>
105
- }
106
-
107
- type RouteMappedModelInput = RouteModelInput | RouteRoutedModelInput
108
-
109
- export interface RouteModelOptions<
110
- Input extends RouteMappedModelInput,
111
- Output extends RouteMappedModelInput = RouteMappedModelInput,
112
- > {
113
- readonly mapInput?: (input: Input) => Output
114
- }
115
-
116
- export interface RouteMappedModelOptions<Input, Output extends RouteMappedModelInput = RouteMappedModelInput> {
117
- readonly mapInput: (input: Input) => Output
118
- }
119
-
120
- const modelWithDefaults =
121
- <Input>(
122
- route: AnyRoute,
123
- defaults: Partial<Omit<ModelRefInput, "id" | "route">>,
124
- options: { readonly mapInput?: (input: Input) => RouteMappedModelInput },
125
- ) =>
126
- (input: Input) => {
127
- const mapped = options.mapInput === undefined ? (input as RouteMappedModelInput) : options.mapInput(input)
128
- const provider = defaults.provider ?? route.provider ?? ("provider" in mapped ? mapped.provider : undefined)
129
- if (!provider) throw new Error(`Route.model(${route.id}) requires a provider`)
130
- const baseURL = mapped.baseURL ?? defaults.baseURL ?? route.defaults.baseURL
131
- if (!baseURL)
132
- throw new Error(`Route.model(${route.id}) requires a baseURL — supply it via input, defaults, or route defaults`)
133
- const generation = mergeGenerationOptions(route.defaults.generation, defaults.generation)
134
- const providerOptions = mergeProviderOptions(route.defaults.providerOptions, defaults.providerOptions)
135
- const http = mergeHttpOptions(httpOptions(route.defaults.http), httpOptions(defaults.http))
136
- return modelRef({
137
- ...route.defaults,
138
- ...defaults,
139
- ...mapped,
140
- baseURL,
141
- provider,
142
- route: route.id,
143
- limits: mapped.limits ?? defaults.limits ?? route.defaults.limits,
144
- generation: mergeGenerationOptions(generation, mapped.generation),
145
- providerOptions: mergeProviderOptions(providerOptions, mapped.providerOptions),
146
- http: mergeHttpOptions(http, httpOptions(mapped.http)),
147
- })
148
- }
149
-
150
- const mergeRouteDefaults = (base: RouteDefaults | undefined, patch: RouteDefaults): RouteDefaults => ({
151
- ...base,
152
- ...patch,
153
- limits: patch.limits ?? base?.limits,
154
- generation: mergeGenerationOptions(generationOptions(base?.generation), generationOptions(patch.generation)),
155
- providerOptions: mergeProviderOptions(base?.providerOptions, patch.providerOptions),
156
- http: mergeHttpOptions(httpOptions(base?.http), httpOptions(patch.http)),
157
- })
158
-
159
- export const modelLimits = ModelLimits.make
160
-
161
- export const generationOptions = (input: GenerationOptions.Input | undefined) =>
162
- input === undefined ? undefined : GenerationOptions.make(input)
163
-
164
- export const httpOptions = (input: HttpOptionsInput | undefined) => {
165
- if (input === undefined) return input
166
- return HttpOptions.make(input)
167
- }
168
-
169
- export const modelRef = (input: ModelRefInput) =>
170
- new ModelRef({
171
- ...input,
172
- id: ModelID.make(input.id),
173
- provider: ProviderID.make(input.provider),
174
- route: RouteID.make(input.route),
175
- limits: modelLimits(input.limits),
176
- generation: generationOptions(input.generation),
177
- http: httpOptions(input.http),
178
- })
179
-
180
- function model<Input extends RouteModelInput = RouteModelInput>(
181
- route: AnyRoute,
182
- defaults: RouteModelDefaults,
183
- options?: RouteModelOptions<Input, RouteModelInput>,
184
- ): (input: Input) => ModelRef
185
- function model<Input extends RouteRoutedModelInput = RouteRoutedModelInput>(
186
- route: AnyRoute,
187
- defaults?: RouteRoutedModelDefaults,
188
- options?: RouteModelOptions<Input, RouteRoutedModelInput>,
189
- ): (input: Input) => ModelRef
190
- function model<Input, Output extends RouteMappedModelInput = RouteMappedModelInput>(
191
- route: AnyRoute,
192
- defaults: Partial<Omit<ModelRefInput, "id" | "route">>,
193
- options: RouteMappedModelOptions<Input, Output>,
194
- ): (input: Input) => ModelRef
195
- function model<Input>(
196
- route: AnyRoute,
197
- defaults: Partial<Omit<ModelRefInput, "id" | "route">> = {},
198
- options: { readonly mapInput?: (input: Input) => RouteMappedModelInput } = {},
199
- ) {
200
- return modelWithDefaults(route, defaults, options)
201
- }
202
-
203
- export interface Interface {
204
- readonly prepare: <Body = unknown>(request: LLMRequest) => Effect.Effect<PreparedRequestOf<Body>, LLMError>
205
- readonly stream: StreamMethod
206
- readonly generate: GenerateMethod
207
- }
208
-
209
- export interface StreamMethod {
210
- (request: LLMRequest): Stream.Stream<LLMEvent, LLMError>
211
- <T extends Tools>(options: ToolRuntime.RunOptions<T>): Stream.Stream<LLMEvent, LLMError>
212
- }
213
-
214
- export interface GenerateMethod {
215
- (request: LLMRequest): Effect.Effect<LLMResponse, LLMError>
216
- <T extends Tools>(options: ToolRuntime.RunOptions<T>): Effect.Effect<LLMResponse, LLMError>
217
- }
218
-
219
- export class Service extends Context.Service<Service, Interface>()("@tinyweb-agent/LLMClient") {}
220
-
221
- const noRoute = (model: ModelRef) =>
222
- new LLMErrorClass({
223
- module: "LLMClient",
224
- method: "resolveRoute",
225
- reason: new NoRouteReason({ route: model.route, provider: model.provider, model: model.id }),
226
- })
227
-
228
- const resolveRequestOptions = (request: LLMRequest) =>
229
- LLMRequest.update(request, {
230
- generation: mergeGenerationOptions(request.model.generation, request.generation) ?? new GenerationOptions({}),
231
- providerOptions: mergeProviderOptions(request.model.providerOptions, request.providerOptions),
232
- http: mergeHttpOptions(request.model.http, request.http),
233
- })
234
-
235
- export interface MakeInput<Body, Frame, Event, State> {
236
- readonly id: string
237
- readonly provider?: string | ProviderID
238
- readonly protocol: Protocol<Body, Frame, Event, State>
239
- readonly endpoint: Endpoint<Body>
240
- readonly auth?: AuthDef
241
- readonly framing: Framing<Frame>
242
- readonly headers?: (input: { readonly request: LLMRequest }) => Record<string, string>
243
- readonly defaults?: RouteDefaults
244
- }
245
-
246
- export interface MakeTransportInput<Body, Prepared, Frame, Event, State> {
247
- readonly id: string
248
- readonly provider?: string | ProviderID
249
- readonly protocol: Protocol<Body, Frame, Event, State>
250
- readonly transport: Transport<Body, Prepared, Frame>
251
- readonly defaults?: RouteDefaults
252
- }
253
-
254
- const streamError = (route: string, message: string, cause: Cause.Cause<unknown>) => {
255
- const failed = cause.reasons.find(Cause.isFailReason)?.error
256
- if (failed instanceof LLMErrorClass) return failed
257
- return ProviderShared.eventError(route, message, Cause.pretty(cause))
258
- }
259
-
260
- function makeFromTransport<Body, Prepared, Frame, Event, State>(
261
- input: MakeTransportInput<Body, Prepared, Frame, Event, State>,
262
- ): Route<Body, Prepared> {
263
- const protocol = input.protocol
264
- const decodeEventEffect = Schema.decodeUnknownEffect(protocol.stream.event)
265
- const decodeEvent = (route: string) => (frame: Frame) =>
266
- decodeEventEffect(frame).pipe(
267
- Effect.mapError(() =>
268
- ProviderShared.eventError(
269
- input.id,
270
- `Invalid ${route} stream event`,
271
- typeof frame === "string" ? frame : ProviderShared.encodeJson(frame),
272
- ),
273
- ),
274
- )
275
-
276
- const build = (routeInput: MakeTransportInput<Body, Prepared, Frame, Event, State>): Route<Body, Prepared> => {
277
- const route: Route<Body, Prepared> = {
278
- id: routeInput.id,
279
- provider: routeInput.provider === undefined ? undefined : ProviderID.make(routeInput.provider),
280
- protocol: protocol.id,
281
- transport: routeInput.transport,
282
- defaults: routeInput.defaults ?? {},
283
- body: protocol.body,
284
- with: (patch: RoutePatch<Body, Prepared>) => {
285
- const { id, provider, transport, ...defaults } = patch
286
- if (!id || id === routeInput.id) throw new Error(`Route.with(${routeInput.id}) requires a new route id`)
287
- return build({
288
- ...routeInput,
289
- id,
290
- provider: provider ?? routeInput.provider,
291
- transport: (transport as Transport<Body, Prepared, Frame> | undefined) ?? routeInput.transport,
292
- defaults: mergeRouteDefaults(routeInput.defaults, defaults),
293
- })
294
- },
295
- model: (input: RouteModelInput): ModelRef => modelWithDefaults<RouteModelInput>(route, {}, {})(input),
296
- prepareTransport: routeInput.transport.prepare,
297
- streamPrepared: (prepared: Prepared, request: LLMRequest, runtime: TransportRuntime) => {
298
- const route = `${request.model.provider}/${request.model.route}`
299
- const events = routeInput.transport
300
- .frames(prepared, request, runtime)
301
- .pipe(
302
- Stream.mapEffect(decodeEvent(route)),
303
- protocol.stream.terminal ? Stream.takeUntil(protocol.stream.terminal) : (stream) => stream,
304
- )
305
- return events.pipe(
306
- Stream.mapAccumEffect(
307
- protocol.stream.initial,
308
- protocol.stream.step,
309
- protocol.stream.onHalt ? { onHalt: protocol.stream.onHalt } : undefined,
310
- ),
311
- Stream.catchCause((cause) => Stream.fail(streamError(route, `Failed to read ${route} stream`, cause))),
312
- )
313
- },
314
- } satisfies Route<Body, Prepared>
315
- return register(route)
316
- }
317
-
318
- return build(input)
319
- }
320
-
321
- export function make<Body, Prepared, Frame, Event, State>(
322
- input: MakeTransportInput<Body, Prepared, Frame, Event, State>,
323
- ): Route<Body, Prepared>
324
- export function make<Body, Frame, Event, State>(
325
- input: MakeInput<Body, Frame, Event, State>,
326
- ): Route<Body, HttpTransport.HttpPrepared<Frame>>
327
- export function make<Body, Prepared, Frame, Event, State>(
328
- input: MakeInput<Body, Frame, Event, State> | MakeTransportInput<Body, Prepared, Frame, Event, State>,
329
- ): Route<Body, Prepared> | Route<Body, HttpTransport.HttpPrepared<Frame>> {
330
- if ("transport" in input) return makeFromTransport(input)
331
- const protocol = input.protocol
332
- const encodeBody = Schema.encodeSync(Schema.fromJsonString(protocol.body.schema))
333
- return makeFromTransport({
334
- id: input.id,
335
- provider: input.provider,
336
- protocol,
337
- transport: HttpTransport.httpJson({
338
- endpoint: input.endpoint,
339
- auth: input.auth,
340
- framing: input.framing,
341
- encodeBody,
342
- headers: input.headers,
343
- }),
344
- defaults: input.defaults,
345
- })
346
- }
347
-
348
- const compile = Effect.fn("LLM.compile")(function* (request: LLMRequest) {
349
- const resolved = applyCachePolicy(resolveRequestOptions(request))
350
- const route = registeredRoute(resolved.model.route)
351
- if (!route) return yield* noRoute(resolved.model)
352
-
353
- const body = yield* route.body
354
- .from(resolved)
355
- .pipe(Effect.flatMap(ProviderShared.validateWith(Schema.decodeUnknownEffect(route.body.schema))))
356
- const prepared = yield* route.prepareTransport(body, resolved)
357
-
358
- return {
359
- request: resolved,
360
- route,
361
- body,
362
- prepared,
363
- }
364
- })
365
-
366
- const prepareWith = Effect.fn("LLMClient.prepare")(function* (request: LLMRequest) {
367
- const compiled = yield* compile(request)
368
-
369
- return new PreparedRequest({
370
- id: compiled.request.id ?? "request",
371
- route: compiled.route.id,
372
- protocol: compiled.route.protocol,
373
- model: compiled.request.model,
374
- body: compiled.body,
375
- metadata: { transport: compiled.route.transport.id },
376
- })
377
- })
378
-
379
- const streamRequestWith = (runtime: TransportRuntime) => (request: LLMRequest) =>
380
- Stream.unwrap(
381
- Effect.gen(function* () {
382
- const compiled = yield* compile(request)
383
- return compiled.route.streamPrepared(compiled.prepared, compiled.request, runtime)
384
- }),
385
- )
386
-
387
- const isToolRunOptions = (input: LLMRequest | ToolRuntime.RunOptions<Tools>): input is ToolRuntime.RunOptions<Tools> =>
388
- "request" in input && "tools" in input
389
-
390
- const streamWith = (streamRequest: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMError>): StreamMethod =>
391
- ((input: LLMRequest | ToolRuntime.RunOptions<Tools>) => {
392
- if (isToolRunOptions(input)) return ToolRuntime.stream({ ...input, stream: streamRequest })
393
- return streamRequest(input)
394
- }) as StreamMethod
395
-
396
- const generateWith = (stream: Interface["stream"]) =>
397
- Effect.fn("LLM.generate")(function* (input: LLMRequest | ToolRuntime.RunOptions<Tools>) {
398
- return new LLMResponse(
399
- yield* stream(input as never).pipe(
400
- Stream.runFold(
401
- () => ({ events: [] as LLMEvent[], usage: undefined as LLMResponse["usage"] }),
402
- (acc, event) => {
403
- acc.events.push(event)
404
- if ("usage" in event && event.usage !== undefined) acc.usage = event.usage
405
- return acc
406
- },
407
- ),
408
- ),
409
- )
410
- })
411
-
412
- export const prepare = <Body = unknown>(request: LLMRequest) =>
413
- prepareWith(request) as Effect.Effect<PreparedRequestOf<Body>, LLMError>
414
-
415
- export function stream(request: LLMRequest): Stream.Stream<LLMEvent, LLMError>
416
- export function stream<T extends Tools>(options: ToolRuntime.RunOptions<T>): Stream.Stream<LLMEvent, LLMError>
417
- export function stream(input: LLMRequest | ToolRuntime.RunOptions<Tools>) {
418
- return Stream.unwrap(
419
- Effect.gen(function* () {
420
- return (yield* Service).stream(input as never)
421
- }),
422
- )
423
- }
424
-
425
- export function generate(request: LLMRequest): Effect.Effect<LLMResponse, LLMError>
426
- export function generate<T extends Tools>(options: ToolRuntime.RunOptions<T>): Effect.Effect<LLMResponse, LLMError>
427
- export function generate(input: LLMRequest | ToolRuntime.RunOptions<Tools>) {
428
- return Effect.gen(function* () {
429
- return yield* (yield* Service).generate(input as never)
430
- })
431
- }
432
-
433
- export const streamRequest = (request: LLMRequest) =>
434
- Stream.unwrap(
435
- Effect.gen(function* () {
436
- return (yield* Service).stream(request)
437
- }),
438
- )
439
-
440
- export const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer.effect(
441
- Service,
442
- Effect.gen(function* () {
443
- const stream = streamWith(streamRequestWith({ http: yield* RequestExecutor.Service }))
444
- return Service.of({ prepare: prepareWith as Interface["prepare"], stream, generate: generateWith(stream) })
445
- }),
446
- )
447
-
448
- export const Route = { make, model } as const
449
-
450
- export const LLMClient = {
451
- Service,
452
- layer,
453
- prepare,
454
- stream,
455
- generate,
456
- stepCountIs: ToolRuntime.stepCountIs,
457
- hasToolCall: ToolRuntime.hasToolCall,
458
- stopWhenAny: ToolRuntime.stopWhenAny,
459
- } as const
@@ -1,28 +0,0 @@
1
- // Adapted from opencode@v1.14.48 packages/llm/src/route/endpoint.ts
2
- import type { LLMRequest } from "../schema"
3
- import * as ProviderShared from "../protocols/shared"
4
-
5
- export interface EndpointInput<Body> {
6
- readonly request: LLMRequest
7
- readonly body: Body
8
- }
9
-
10
- export type EndpointPart<Body> = string | ((input: EndpointInput<Body>) => string)
11
-
12
- export interface Endpoint<Body> {
13
- readonly path: EndpointPart<Body>
14
- }
15
-
16
- export const path = <Body>(value: EndpointPart<Body>): Endpoint<Body> => ({ path: value })
17
-
18
- const renderPart = <Body>(part: EndpointPart<Body>, input: EndpointInput<Body>) =>
19
- typeof part === "function" ? part(input) : part
20
-
21
- export const render = <Body>(endpoint: Endpoint<Body>, input: EndpointInput<Body>) => {
22
- const url = new URL(`${ProviderShared.trimBaseUrl(input.request.model.baseURL)}${renderPart(endpoint.path, input)}`)
23
- const params = input.request.model.queryParams
24
- if (params) for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value)
25
- return url
26
- }
27
-
28
- export * as Endpoint from "./endpoint"