@tinyweb_dev/agent-framework-llm 0.1.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.
@@ -0,0 +1,459 @@
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
@@ -0,0 +1,28 @@
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"